github.com/FISCO-BCOS/crypto@v0.0.0-20200202032121-bd8ab0b5d4f1/x509/x509_test.go (about) 1 // Copyright 2009 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package x509 6 7 import ( 8 "bytes" 9 "crypto/dsa" 10 "github.com/FISCO-BCOS/crypto/ecdsa" 11 "crypto/ed25519" 12 "github.com/FISCO-BCOS/crypto/elliptic" 13 "crypto/rand" 14 "crypto/rsa" 15 _ "crypto/sha256" 16 _ "crypto/sha512" 17 "crypto/x509/pkix" 18 "encoding/asn1" 19 "encoding/base64" 20 "encoding/hex" 21 "encoding/pem" 22 "fmt" 23 "github.com/FISCO-BCOS/crypto/internal/testenv" 24 "math/big" 25 "net" 26 "net/url" 27 "os/exec" 28 "reflect" 29 "runtime" 30 "strings" 31 "testing" 32 "time" 33 ) 34 35 func TestParsePKCS1PrivateKey(t *testing.T) { 36 block, _ := pem.Decode([]byte(pemPrivateKey)) 37 priv, err := ParsePKCS1PrivateKey(block.Bytes) 38 if err != nil { 39 t.Errorf("Failed to parse private key: %s", err) 40 return 41 } 42 if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 || 43 priv.PublicKey.E != rsaPrivateKey.PublicKey.E || 44 priv.D.Cmp(rsaPrivateKey.D) != 0 || 45 priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 || 46 priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 { 47 t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey) 48 } 49 50 // This private key includes an invalid prime that 51 // rsa.PrivateKey.Validate should reject. 52 data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00") 53 if _, err := ParsePKCS1PrivateKey(data); err == nil { 54 t.Errorf("parsing invalid private key did not result in an error") 55 } 56 } 57 58 func TestPKCS1MismatchPublicKeyFormat(t *testing.T) { 59 60 const pkixPublicKey = "30820122300d06092a864886f70d01010105000382010f003082010a0282010100dd5a0f37d3ca5232852ccc0e81eebec270e2f2c6c44c6231d852971a0aad00aa7399e9b9de444611083c59ea919a9d76c20a7be131a99045ec19a7bb452d647a72429e66b87e28be9e8187ed1d2a2a01ef3eb2360706bd873b07f2d1f1a72337aab5ec94e983e39107f52c480d404915e84d75a3db2cfd601726a128cb1d7f11492d4bdb53272e652276667220795c709b8a9b4af6489cbf48bb8173b8fb607c834a71b6e8bf2d6aab82af3c8ad7ce16d8dcf58373a6edc427f7484d09744d4c08f4e19ed07adbf6cb31243bc5d0d1145e77a08a6fc5efd208eca67d6abf2d6f38f58b6fdd7c28774fb0cc03fc4935c6e074842d2e1479d3d8787249258719f90203010001" 61 const errorContains = "use ParsePKIXPublicKey instead" 62 derBytes, _ := hex.DecodeString(pkixPublicKey) 63 _, err := ParsePKCS1PublicKey(derBytes) 64 if !strings.Contains(err.Error(), errorContains) { 65 t.Errorf("expected error containing %q, got %s", errorContains, err) 66 } 67 } 68 69 func testParsePKIXPublicKey(t *testing.T, pemBytes string) (pub interface{}) { 70 block, _ := pem.Decode([]byte(pemBytes)) 71 pub, err := ParsePKIXPublicKey(block.Bytes) 72 if err != nil { 73 t.Fatalf("Failed to parse public key: %s", err) 74 } 75 76 pubBytes2, err := MarshalPKIXPublicKey(pub) 77 if err != nil { 78 t.Errorf("Failed to marshal public key for the second time: %s", err) 79 return 80 } 81 if !bytes.Equal(pubBytes2, block.Bytes) { 82 t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes) 83 } 84 return 85 } 86 87 func TestParsePKIXPublicKey(t *testing.T) { 88 t.Run("RSA", func(t *testing.T) { 89 pub := testParsePKIXPublicKey(t, pemPublicKey) 90 _, ok := pub.(*rsa.PublicKey) 91 if !ok { 92 t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key") 93 } 94 }) 95 t.Run("Ed25519", func(t *testing.T) { 96 pub := testParsePKIXPublicKey(t, pemEd25519Key) 97 _, ok := pub.(ed25519.PublicKey) 98 if !ok { 99 t.Errorf("Value returned from ParsePKIXPublicKey was not an Ed25519 public key") 100 } 101 }) 102 } 103 104 var pemPublicKey = `-----BEGIN PUBLIC KEY----- 105 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+ 106 wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k 107 enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ 108 FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg 109 fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR 110 FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ 111 +QIDAQAB 112 -----END PUBLIC KEY----- 113 ` 114 115 var pemPrivateKey = testingKey(` 116 -----BEGIN RSA TESTING KEY----- 117 MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v 118 IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7 119 J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB 120 AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1 121 V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd 122 7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R 123 vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12 124 33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS 125 rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi 126 MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX 127 AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo 128 6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6 129 wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY= 130 -----END RSA TESTING KEY----- 131 `) 132 133 // pemEd25519Key is the example from RFC 8410, Secrion 4. 134 var pemEd25519Key = ` 135 -----BEGIN PUBLIC KEY----- 136 MCowBQYDK2VwAyEAGb9ECWmEzf6FQbrBZ9w7lshQhqowtrbLDFw4rXAxZuE= 137 -----END PUBLIC KEY----- 138 ` 139 140 func TestPKIXMismatchPublicKeyFormat(t *testing.T) { 141 142 const pkcs1PublicKey = "308201080282010100817cfed98bcaa2e2a57087451c7674e0c675686dc33ff1268b0c2a6ee0202dec710858ee1c31bdf5e7783582e8ca800be45f3275c6576adc35d98e26e95bb88ca5beb186f853b8745d88bc9102c5f38753bcda519fb05948d5c77ac429255ff8aaf27d9f45d1586e95e2e9ba8a7cb771b8a09dd8c8fed3f933fd9b439bc9f30c475953418ef25f71a2b6496f53d94d39ce850aa0cc75d445b5f5b4f4ee4db78ab197a9a8d8a852f44529a007ac0ac23d895928d60ba538b16b0b087a7f903ed29770e215019b77eaecc360f35f7ab11b6d735978795b2c4a74e5bdea4dc6594cd67ed752a108e666729a753ab36d6c4f606f8760f507e1765be8cd744007e629020103" 143 const errorContains = "use ParsePKCS1PublicKey instead" 144 derBytes, _ := hex.DecodeString(pkcs1PublicKey) 145 _, err := ParsePKIXPublicKey(derBytes) 146 if !strings.Contains(err.Error(), errorContains) { 147 t.Errorf("expected error containing %q, got %s", errorContains, err) 148 } 149 } 150 151 var testPrivateKey *rsa.PrivateKey 152 153 func init() { 154 block, _ := pem.Decode([]byte(pemPrivateKey)) 155 156 var err error 157 if testPrivateKey, err = ParsePKCS1PrivateKey(block.Bytes); err != nil { 158 panic("Failed to parse private key: " + err.Error()) 159 } 160 } 161 162 func bigFromString(s string) *big.Int { 163 ret := new(big.Int) 164 ret.SetString(s, 10) 165 return ret 166 } 167 168 func fromBase10(base10 string) *big.Int { 169 i := new(big.Int) 170 i.SetString(base10, 10) 171 return i 172 } 173 174 func bigFromHexString(s string) *big.Int { 175 ret := new(big.Int) 176 ret.SetString(s, 16) 177 return ret 178 } 179 180 var rsaPrivateKey = &rsa.PrivateKey{ 181 PublicKey: rsa.PublicKey{ 182 N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"), 183 E: 65537, 184 }, 185 D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"), 186 Primes: []*big.Int{ 187 bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"), 188 bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"), 189 }, 190 } 191 192 func TestMarshalRSAPrivateKey(t *testing.T) { 193 priv := &rsa.PrivateKey{ 194 PublicKey: rsa.PublicKey{ 195 N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"), 196 E: 3, 197 }, 198 D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"), 199 Primes: []*big.Int{ 200 fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"), 201 fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"), 202 fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"), 203 }, 204 } 205 206 derBytes := MarshalPKCS1PrivateKey(priv) 207 208 priv2, err := ParsePKCS1PrivateKey(derBytes) 209 if err != nil { 210 t.Errorf("error parsing serialized key: %s", err) 211 return 212 } 213 if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 || 214 priv.PublicKey.E != priv2.PublicKey.E || 215 priv.D.Cmp(priv2.D) != 0 || 216 len(priv2.Primes) != 3 || 217 priv.Primes[0].Cmp(priv2.Primes[0]) != 0 || 218 priv.Primes[1].Cmp(priv2.Primes[1]) != 0 || 219 priv.Primes[2].Cmp(priv2.Primes[2]) != 0 { 220 t.Errorf("got:%+v want:%+v", priv, priv2) 221 } 222 } 223 224 func TestMarshalRSAPublicKey(t *testing.T) { 225 pub := &rsa.PublicKey{ 226 N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"), 227 E: 3, 228 } 229 derBytes := MarshalPKCS1PublicKey(pub) 230 pub2, err := ParsePKCS1PublicKey(derBytes) 231 if err != nil { 232 t.Errorf("ParsePKCS1PublicKey: %s", err) 233 } 234 if pub.N.Cmp(pub2.N) != 0 || pub.E != pub2.E { 235 t.Errorf("ParsePKCS1PublicKey = %+v, want %+v", pub, pub2) 236 } 237 238 // It's never been documented that asn1.Marshal/Unmarshal on rsa.PublicKey works, 239 // but it does, and we know of code that depends on it. 240 // Lock that in, even though we'd prefer that people use MarshalPKCS1PublicKey and ParsePKCS1PublicKey. 241 derBytes2, err := asn1.Marshal(*pub) 242 if err != nil { 243 t.Errorf("Marshal(rsa.PublicKey): %v", err) 244 } else if !bytes.Equal(derBytes, derBytes2) { 245 t.Errorf("Marshal(rsa.PublicKey) = %x, want %x", derBytes2, derBytes) 246 } 247 pub3 := new(rsa.PublicKey) 248 rest, err := asn1.Unmarshal(derBytes, pub3) 249 if err != nil { 250 t.Errorf("Unmarshal(rsa.PublicKey): %v", err) 251 } 252 if len(rest) != 0 || pub.N.Cmp(pub3.N) != 0 || pub.E != pub3.E { 253 t.Errorf("Unmarshal(rsa.PublicKey) = %+v, %q want %+v, %q", pub, rest, pub2, []byte(nil)) 254 } 255 256 publicKeys := []struct { 257 derBytes []byte 258 expectedErrSubstr string 259 }{ 260 { 261 derBytes: []byte{ 262 0x30, 6, // SEQUENCE, 6 bytes 263 0x02, 1, // INTEGER, 1 byte 264 17, 265 0x02, 1, // INTEGER, 1 byte 266 3, // 3 267 }, 268 }, { 269 derBytes: []byte{ 270 0x30, 6, // SEQUENCE 271 0x02, 1, // INTEGER, 1 byte 272 0xff, // -1 273 0x02, 1, // INTEGER, 1 byte 274 3, 275 }, 276 expectedErrSubstr: "zero or negative", 277 }, { 278 derBytes: []byte{ 279 0x30, 6, // SEQUENCE 280 0x02, 1, // INTEGER, 1 byte 281 17, 282 0x02, 1, // INTEGER, 1 byte 283 0xff, // -1 284 }, 285 expectedErrSubstr: "zero or negative", 286 }, { 287 derBytes: []byte{ 288 0x30, 6, // SEQUENCE 289 0x02, 1, // INTEGER, 1 byte 290 17, 291 0x02, 1, // INTEGER, 1 byte 292 3, 293 1, 294 }, 295 expectedErrSubstr: "trailing data", 296 }, { 297 derBytes: []byte{ 298 0x30, 9, // SEQUENCE 299 0x02, 1, // INTEGER, 1 byte 300 17, 301 0x02, 4, // INTEGER, 4 bytes 302 0x7f, 0xff, 0xff, 0xff, 303 }, 304 }, { 305 derBytes: []byte{ 306 0x30, 10, // SEQUENCE 307 0x02, 1, // INTEGER, 1 byte 308 17, 309 0x02, 5, // INTEGER, 5 bytes 310 0x00, 0x80, 0x00, 0x00, 0x00, 311 }, 312 // On 64-bit systems, encoding/asn1 will accept the 313 // public exponent, but ParsePKCS1PublicKey will return 314 // an error. On 32-bit systems, encoding/asn1 will 315 // return the error. The common substring of both error 316 // is the word “large”. 317 expectedErrSubstr: "large", 318 }, 319 } 320 321 for i, test := range publicKeys { 322 shouldFail := len(test.expectedErrSubstr) > 0 323 pub, err := ParsePKCS1PublicKey(test.derBytes) 324 if shouldFail { 325 if err == nil { 326 t.Errorf("#%d: unexpected success, got %#v", i, pub) 327 } else if !strings.Contains(err.Error(), test.expectedErrSubstr) { 328 t.Errorf("#%d: expected error containing %q, got %s", i, test.expectedErrSubstr, err) 329 } 330 } else { 331 if err != nil { 332 t.Errorf("#%d: unexpected failure: %s", i, err) 333 continue 334 } 335 reserialized := MarshalPKCS1PublicKey(pub) 336 if !bytes.Equal(reserialized, test.derBytes) { 337 t.Errorf("#%d: failed to reserialize: got %x, expected %x", i, reserialized, test.derBytes) 338 } 339 } 340 } 341 } 342 343 type matchHostnamesTest struct { 344 pattern, host string 345 ok bool 346 } 347 348 var matchHostnamesTests = []matchHostnamesTest{ 349 {"a.b.c", "a.b.c", true}, 350 {"a.b.c", "b.b.c", false}, 351 {"", "b.b.c", false}, 352 {"a.b.c", "", false}, 353 {"example.com", "example.com", true}, 354 {"example.com", "www.example.com", false}, 355 {"*.example.com", "example.com", false}, 356 {"*.example.com", "www.example.com", true}, 357 {"*.example.com", "www.example.com.", true}, 358 {"*.example.com", "xyz.www.example.com", false}, 359 {"*.*.example.com", "xyz.www.example.com", false}, 360 {"*.www.*.com", "xyz.www.example.com", false}, 361 {"*bar.example.com", "foobar.example.com", false}, 362 {"f*.example.com", "foobar.example.com", false}, 363 {"", ".", false}, 364 {".", "", false}, 365 {".", ".", false}, 366 {"example.com", "example.com.", true}, 367 {"example.com.", "example.com", true}, 368 {"example.com.", "example.com.", true}, 369 {"*.com.", "example.com.", true}, 370 {"*.com.", "example.com", true}, 371 {"*.com", "example.com", true}, 372 {"*.com", "example.com.", true}, 373 } 374 375 func TestMatchHostnames(t *testing.T) { 376 for i, test := range matchHostnamesTests { 377 r := matchHostnames(test.pattern, test.host) 378 if r != test.ok { 379 t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern) 380 } 381 } 382 } 383 384 func TestMatchIP(t *testing.T) { 385 // Check that pattern matching is working. 386 c := &Certificate{ 387 DNSNames: []string{"*.foo.bar.baz"}, 388 Subject: pkix.Name{ 389 CommonName: "*.foo.bar.baz", 390 }, 391 } 392 err := c.VerifyHostname("quux.foo.bar.baz") 393 if err != nil { 394 t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err) 395 } 396 397 // But check that if we change it to be matching against an IP address, 398 // it is rejected. 399 c = &Certificate{ 400 DNSNames: []string{"*.2.3.4"}, 401 Subject: pkix.Name{ 402 CommonName: "*.2.3.4", 403 }, 404 } 405 err = c.VerifyHostname("1.2.3.4") 406 if err == nil { 407 t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not") 408 } 409 410 c = &Certificate{ 411 IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, 412 } 413 err = c.VerifyHostname("127.0.0.1") 414 if err != nil { 415 t.Fatalf("VerifyHostname(127.0.0.1): %v", err) 416 } 417 err = c.VerifyHostname("::1") 418 if err != nil { 419 t.Fatalf("VerifyHostname(::1): %v", err) 420 } 421 err = c.VerifyHostname("[::1]") 422 if err != nil { 423 t.Fatalf("VerifyHostname([::1]): %v", err) 424 } 425 } 426 427 func TestCertificateParse(t *testing.T) { 428 s, _ := hex.DecodeString(certBytes) 429 certs, err := ParseCertificates(s) 430 if err != nil { 431 t.Error(err) 432 } 433 if len(certs) != 2 { 434 t.Errorf("Wrong number of certs: got %d want 2", len(certs)) 435 return 436 } 437 438 err = certs[0].CheckSignatureFrom(certs[1]) 439 if err != nil { 440 t.Error(err) 441 } 442 443 if err := certs[0].VerifyHostname("mail.google.com"); err != nil { 444 t.Error(err) 445 } 446 447 const expectedExtensions = 4 448 if n := len(certs[0].Extensions); n != expectedExtensions { 449 t.Errorf("want %d extensions, got %d", expectedExtensions, n) 450 } 451 } 452 453 func TestMismatchedSignatureAlgorithm(t *testing.T) { 454 der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM)) 455 if der == nil { 456 t.Fatal("Failed to find PEM block") 457 } 458 459 cert, err := ParseCertificate(der.Bytes) 460 if err != nil { 461 t.Fatal(err) 462 } 463 464 if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil { 465 t.Fatal("CheckSignature unexpectedly return no error") 466 } 467 468 const expectedSubstring = " but have public key of type " 469 if !strings.Contains(err.Error(), expectedSubstring) { 470 t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err) 471 } 472 } 473 474 var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" + 475 "f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" + 476 "20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" + 477 "20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" + 478 "3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" + 479 "140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" + 480 "496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" + 481 "86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" + 482 "41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" + 483 "3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" + 484 "03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" + 485 "81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" + 486 "86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" + 487 "74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" + 488 "2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" + 489 "2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" + 490 "6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" + 491 "2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" + 492 "9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" + 493 "70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" + 494 "a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" + 495 "020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" + 496 "15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" + 497 "33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" + 498 "79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" + 499 "060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" + 500 "50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" + 501 "092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" + 502 "0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" + 503 "2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" + 504 "21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" + 505 "a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" + 506 "301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" + 507 "035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" + 508 "8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" + 509 "0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" + 510 "617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" + 511 "06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" + 512 "81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" + 513 "e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" + 514 "9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" + 515 "36dcd585d6ace53f546f961e05af" 516 517 func parseCIDR(s string) *net.IPNet { 518 _, net, err := net.ParseCIDR(s) 519 if err != nil { 520 panic(err) 521 } 522 return net 523 } 524 525 func parseURI(s string) *url.URL { 526 uri, err := url.Parse(s) 527 if err != nil { 528 panic(err) 529 } 530 return uri 531 } 532 533 func TestCreateSelfSignedCertificate(t *testing.T) { 534 random := rand.Reader 535 536 ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 537 if err != nil { 538 t.Fatalf("Failed to generate ECDSA key: %s", err) 539 } 540 541 ed25519Pub, ed25519Priv, err := ed25519.GenerateKey(random) 542 if err != nil { 543 t.Fatalf("Failed to generate Ed25519 key: %s", err) 544 } 545 546 tests := []struct { 547 name string 548 pub, priv interface{} 549 checkSig bool 550 sigAlgo SignatureAlgorithm 551 }{ 552 {"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA1WithRSA}, 553 {"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384}, 554 {"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA}, 555 {"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1}, 556 {"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS}, 557 {"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS}, 558 {"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384}, 559 {"Ed25519", ed25519Pub, ed25519Priv, true, PureEd25519}, 560 } 561 562 testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth} 563 testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} 564 extraExtensionData := []byte("extra extension") 565 566 for _, test := range tests { 567 commonName := "test.example.com" 568 template := Certificate{ 569 // SerialNumber is negative to ensure that negative 570 // values are parsed. This is due to the prevalence of 571 // buggy code that produces certificates with negative 572 // serial numbers. 573 SerialNumber: big.NewInt(-1), 574 Subject: pkix.Name{ 575 CommonName: commonName, 576 Organization: []string{"Σ Acme Co"}, 577 Country: []string{"US"}, 578 ExtraNames: []pkix.AttributeTypeAndValue{ 579 { 580 Type: []int{2, 5, 4, 42}, 581 Value: "Gopher", 582 }, 583 // This should override the Country, above. 584 { 585 Type: []int{2, 5, 4, 6}, 586 Value: "NL", 587 }, 588 }, 589 }, 590 NotBefore: time.Unix(1000, 0), 591 NotAfter: time.Unix(100000, 0), 592 593 SignatureAlgorithm: test.sigAlgo, 594 595 SubjectKeyId: []byte{1, 2, 3, 4}, 596 KeyUsage: KeyUsageCertSign, 597 598 ExtKeyUsage: testExtKeyUsage, 599 UnknownExtKeyUsage: testUnknownExtKeyUsage, 600 601 BasicConstraintsValid: true, 602 IsCA: true, 603 604 OCSPServer: []string{"http://ocsp.example.com"}, 605 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, 606 607 DNSNames: []string{"test.example.com"}, 608 EmailAddresses: []string{"gopher@golang.org"}, 609 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 610 URIs: []*url.URL{parseURI("https://foo.com/wibble#foo")}, 611 612 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}}, 613 PermittedDNSDomains: []string{".example.com", "example.com"}, 614 ExcludedDNSDomains: []string{"bar.example.com"}, 615 PermittedIPRanges: []*net.IPNet{parseCIDR("192.168.1.1/16"), parseCIDR("1.2.3.4/8")}, 616 ExcludedIPRanges: []*net.IPNet{parseCIDR("2001:db8::/48")}, 617 PermittedEmailAddresses: []string{"foo@example.com"}, 618 ExcludedEmailAddresses: []string{".example.com", "example.com"}, 619 PermittedURIDomains: []string{".bar.com", "bar.com"}, 620 ExcludedURIDomains: []string{".bar2.com", "bar2.com"}, 621 622 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, 623 624 ExtraExtensions: []pkix.Extension{ 625 { 626 Id: []int{1, 2, 3, 4}, 627 Value: extraExtensionData, 628 }, 629 // This extension should override the SubjectKeyId, above. 630 { 631 Id: oidExtensionSubjectKeyId, 632 Critical: false, 633 Value: []byte{0x04, 0x04, 4, 3, 2, 1}, 634 }, 635 }, 636 } 637 638 derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv) 639 if err != nil { 640 t.Errorf("%s: failed to create certificate: %s", test.name, err) 641 continue 642 } 643 644 cert, err := ParseCertificate(derBytes) 645 if err != nil { 646 t.Errorf("%s: failed to parse certificate: %s", test.name, err) 647 continue 648 } 649 650 if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) { 651 t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers) 652 } 653 654 if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" { 655 t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains) 656 } 657 658 if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" { 659 t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains) 660 } 661 662 if len(cert.PermittedIPRanges) != 2 || cert.PermittedIPRanges[0].String() != "192.168.0.0/16" || cert.PermittedIPRanges[1].String() != "1.0.0.0/8" { 663 t.Errorf("%s: failed to parse IP constraints: %#v", test.name, cert.PermittedIPRanges) 664 } 665 666 if len(cert.ExcludedIPRanges) != 1 || cert.ExcludedIPRanges[0].String() != "2001:db8::/48" { 667 t.Errorf("%s: failed to parse IP constraint exclusions: %#v", test.name, cert.ExcludedIPRanges) 668 } 669 670 if len(cert.PermittedEmailAddresses) != 1 || cert.PermittedEmailAddresses[0] != "foo@example.com" { 671 t.Errorf("%s: failed to parse permitted email addreses: %#v", test.name, cert.PermittedEmailAddresses) 672 } 673 674 if len(cert.ExcludedEmailAddresses) != 2 || cert.ExcludedEmailAddresses[0] != ".example.com" || cert.ExcludedEmailAddresses[1] != "example.com" { 675 t.Errorf("%s: failed to parse excluded email addreses: %#v", test.name, cert.ExcludedEmailAddresses) 676 } 677 678 if len(cert.PermittedURIDomains) != 2 || cert.PermittedURIDomains[0] != ".bar.com" || cert.PermittedURIDomains[1] != "bar.com" { 679 t.Errorf("%s: failed to parse permitted URIs: %#v", test.name, cert.PermittedURIDomains) 680 } 681 682 if len(cert.ExcludedURIDomains) != 2 || cert.ExcludedURIDomains[0] != ".bar2.com" || cert.ExcludedURIDomains[1] != "bar2.com" { 683 t.Errorf("%s: failed to parse excluded URIs: %#v", test.name, cert.ExcludedURIDomains) 684 } 685 686 if cert.Subject.CommonName != commonName { 687 t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName) 688 } 689 690 if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" { 691 t.Errorf("%s: ExtraNames didn't override Country", test.name) 692 } 693 694 for _, ext := range cert.Extensions { 695 if ext.Id.Equal(oidExtensionSubjectAltName) { 696 if ext.Critical { 697 t.Fatal("SAN extension is marked critical") 698 } 699 } 700 } 701 702 found := false 703 for _, atv := range cert.Subject.Names { 704 if atv.Type.Equal([]int{2, 5, 4, 42}) { 705 found = true 706 break 707 } 708 } 709 if !found { 710 t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name) 711 } 712 713 if cert.Issuer.CommonName != commonName { 714 t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName) 715 } 716 717 if cert.SignatureAlgorithm != test.sigAlgo { 718 t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo) 719 } 720 721 if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) { 722 t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage) 723 } 724 725 if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) { 726 t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) 727 } 728 729 if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) { 730 t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer) 731 } 732 733 if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) { 734 t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL) 735 } 736 737 if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) { 738 t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames) 739 } 740 741 if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) { 742 t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses) 743 } 744 745 if len(cert.URIs) != 1 || cert.URIs[0].String() != "https://foo.com/wibble#foo" { 746 t.Errorf("%s: URIs differ from template. Got %v, want %v", test.name, cert.URIs, template.URIs) 747 } 748 749 if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) { 750 t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses) 751 } 752 753 if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) { 754 t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints) 755 } 756 757 if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) { 758 t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name) 759 } 760 761 if !bytes.Contains(derBytes, extraExtensionData) { 762 t.Errorf("%s: didn't find extra extension in DER output", test.name) 763 } 764 765 if test.checkSig { 766 err = cert.CheckSignatureFrom(cert) 767 if err != nil { 768 t.Errorf("%s: signature verification failed: %s", test.name, err) 769 } 770 } 771 } 772 } 773 774 // Self-signed certificate using ECDSA with SHA1 & secp256r1 775 var ecdsaSHA1CertPem = ` 776 -----BEGIN CERTIFICATE----- 777 MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET 778 MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG 779 A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 780 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw 781 WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 782 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg 783 SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv 784 bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn 785 WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3 786 P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2 787 DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV 788 a/A= 789 -----END CERTIFICATE----- 790 ` 791 792 // Self-signed certificate using ECDSA with SHA256 & secp256r1 793 var ecdsaSHA256p256CertPem = ` 794 -----BEGIN CERTIFICATE----- 795 MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx 796 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT 797 BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh 798 BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx 799 NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp 800 Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs 801 IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn 802 b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt 803 2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm 804 YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV 805 70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ 806 h5wi 807 -----END CERTIFICATE----- 808 ` 809 810 // Self-signed certificate using ECDSA with SHA256 & secp384r1 811 var ecdsaSHA256p384CertPem = ` 812 -----BEGIN CERTIFICATE----- 813 MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx 814 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 815 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 816 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0 817 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 818 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 819 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 820 YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK 821 jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze 822 qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI 823 zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr 824 PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh 825 3yILeYQzllt/g0rKVRk= 826 -----END CERTIFICATE----- 827 ` 828 829 // Self-signed certificate using ECDSA with SHA384 & secp521r1 830 var ecdsaSHA384p521CertPem = ` 831 -----BEGIN CERTIFICATE----- 832 MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx 833 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 834 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 835 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5 836 WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 837 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 838 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 839 YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv 840 IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz 841 PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm 842 8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw 843 gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH 844 BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh 845 kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa 846 -----END CERTIFICATE----- 847 ` 848 849 var ecdsaTests = []struct { 850 sigAlgo SignatureAlgorithm 851 pemCert string 852 }{ 853 {ECDSAWithSHA1, ecdsaSHA1CertPem}, 854 {ECDSAWithSHA256, ecdsaSHA256p256CertPem}, 855 {ECDSAWithSHA256, ecdsaSHA256p384CertPem}, 856 {ECDSAWithSHA384, ecdsaSHA384p521CertPem}, 857 } 858 859 func TestECDSA(t *testing.T) { 860 for i, test := range ecdsaTests { 861 pemBlock, _ := pem.Decode([]byte(test.pemCert)) 862 cert, err := ParseCertificate(pemBlock.Bytes) 863 if err != nil { 864 t.Errorf("%d: failed to parse certificate: %s", i, err) 865 continue 866 } 867 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { 868 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) 869 } 870 if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok { 871 t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey) 872 } 873 if pka := cert.PublicKeyAlgorithm; pka != ECDSA { 874 t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka) 875 } 876 if err = cert.CheckSignatureFrom(cert); err != nil { 877 t.Errorf("%d: certificate verification failed: %s", i, err) 878 } 879 } 880 } 881 882 // Self-signed certificate using DSA with SHA1 883 var dsaCertPem = `-----BEGIN CERTIFICATE----- 884 MIIEDTCC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yr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11 901 ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w 902 DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK 903 b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx 904 z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI 905 7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM 906 -----END CERTIFICATE----- 907 ` 908 909 func TestParseCertificateWithDsaPublicKey(t *testing.T) { 910 expectedKey := &dsa.PublicKey{ 911 Parameters: dsa.Parameters{ 912 P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"), 913 Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"), 914 G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"), 915 }, 916 Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"), 917 } 918 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 919 cert, err := ParseCertificate(pemBlock.Bytes) 920 if err != nil { 921 t.Fatalf("Failed to parse certificate: %s", err) 922 } 923 if cert.PublicKeyAlgorithm != DSA { 924 t.Errorf("Parsed key algorithm was not DSA") 925 } 926 parsedKey, ok := cert.PublicKey.(*dsa.PublicKey) 927 if !ok { 928 t.Fatalf("Parsed key was not a DSA key: %s", err) 929 } 930 if expectedKey.Y.Cmp(parsedKey.Y) != 0 || 931 expectedKey.P.Cmp(parsedKey.P) != 0 || 932 expectedKey.Q.Cmp(parsedKey.Q) != 0 || 933 expectedKey.G.Cmp(parsedKey.G) != 0 { 934 t.Fatal("Parsed key differs from expected key") 935 } 936 } 937 938 func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) { 939 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 940 cert, err := ParseCertificate(pemBlock.Bytes) 941 if err != nil { 942 t.Fatalf("Failed to parse certificate: %s", err) 943 } 944 if cert.SignatureAlgorithm != DSAWithSHA1 { 945 t.Errorf("Parsed signature algorithm was not DSAWithSHA1") 946 } 947 } 948 949 func TestVerifyCertificateWithDSASignature(t *testing.T) { 950 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 951 cert, err := ParseCertificate(pemBlock.Bytes) 952 if err != nil { 953 t.Fatalf("Failed to parse certificate: %s", err) 954 } 955 // test cert is self-signed 956 if err = cert.CheckSignatureFrom(cert); err != nil { 957 t.Fatalf("DSA Certificate verification failed: %s", err) 958 } 959 } 960 961 var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE----- 962 MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA 963 oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC 964 SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1l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EFD+oahaikBTV 981 Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP 982 fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg 983 hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC 984 AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n 985 li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR 986 TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3 987 kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66 988 U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c 989 15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv 990 C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN 991 2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO 992 FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9 993 qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2 994 +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q== 995 -----END CERTIFICATE-----` 996 997 // openssl req -newkey rsa:2048 -keyout test.key -sha256 -sigopt \ 998 // rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sigopt rsa_mgf1_md:sha256 \ 999 // -x509 -days 3650 -nodes -subj '/C=US/ST=CA/L=SF/O=Test/CN=Test' -out \ 1000 // test.pem 1001 var rsaPSSSelfSignedOpenSSL110PEM = `-----BEGIN CERTIFICATE----- 1002 MIIDwDCCAnigAwIBAgIJAM9LAMHTE5xpMD0GCSqGSIb3DQEBCjAwoA0wCwYJYIZI 1003 AWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQCAaIDAgEgMEUxCzAJBgNV 1004 BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDTALBgNVBAoMBFRlc3Qx 1005 DTALBgNVBAMMBFRlc3QwHhcNMTgwMjIyMjIxMzE4WhcNMjgwMjIwMjIxMzE4WjBF 1006 MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMQ0wCwYDVQQK 1007 DARUZXN0MQ0wCwYDVQQDDARUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 1008 CgKCAQEA4Zrsydod+GoTAJLLutWNF87qhhVPBsK1zB1Gj+NAAe4+VbrZ1E41H1wp 1009 qITx7DA8DRtJEf+NqrTAnAdZWBG/tAOA5LfXVax0ZSQtLnYLSeylLoMtDyY3eFAj 1010 TmuTOoyVy6raktowCnHCh01NsstqqTfrx6SbmzOmDmKTkq/I+7K0MCVsn41xRDVM 1011 +ShD0WGFGioEGoiWnFSWupxJDA3Q6jIDEygVwNKHwnhv/2NgG2kqZzrZSQA67en0 1012 iKAXtoDNPpmyD5oS9YbEJ+2Nbm7oLeON30i6kZvXKIzJXx+UWViazHZqnsi5rQ8G 1013 RHF+iVFXsqd0MzDKmkKOT5FDhrsbKQIDAQABo1MwUTAdBgNVHQ4EFgQU9uFY/nlg 1014 gLH00NBnr/o7QvpN9ugwHwYDVR0jBBgwFoAU9uFY/nlggLH00NBnr/o7QvpN9ugw 1015 DwYDVR0TAQH/BAUwAwEB/zA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa 1016 MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQEAhJzpwxBNGKvzKWDe 1017 WLqv6RMrl/q4GcH3b7M9wjxe0yOm4F+Tb2zJ7re4h+D39YkJf8cX1NV9UQVu6z4s 1018 Fvo2kmlR0qZOXAg5augmCQ1xS0WHFoF6B52anNzHkZQbAIYJ3kGoFsUHzs7Sz7F/ 1019 656FsRpHA9UzJQ3avPPMrA4Y4aoJ7ANJ6XIwTrdWrhULOVuvYRLCl4CdTVztVFX6 1020 wxX8nS1ISYd8jXPUMgsBKVbWufvLoIymMJW8CZbpprVZel5zFn0bmPrON8IHS30w 1021 Gs+ITJjKEnZgXmAQ25SLKVzkZkBcGANs2GsdHNJ370Puisy0FIPD2NXR5uASAf7J 1022 +w9fjQ== 1023 -----END CERTIFICATE-----` 1024 1025 func TestRSAPSSSelfSigned(t *testing.T) { 1026 for i, pemBlock := range []string{rsaPSSSelfSignedPEM, rsaPSSSelfSignedOpenSSL110PEM} { 1027 der, _ := pem.Decode([]byte(pemBlock)) 1028 if der == nil { 1029 t.Errorf("#%d: failed to find PEM block", i) 1030 continue 1031 } 1032 1033 cert, err := ParseCertificate(der.Bytes) 1034 if err != nil { 1035 t.Errorf("#%d: failed to parse: %s", i, err) 1036 continue 1037 } 1038 1039 if err = cert.CheckSignatureFrom(cert); err != nil { 1040 t.Errorf("#%d: signature check failed: %s", i, err) 1041 continue 1042 } 1043 } 1044 } 1045 1046 const ed25519Certificate = ` 1047 Certificate: 1048 Data: 1049 Version: 3 (0x2) 1050 Serial Number: 1051 0c:83:d8:21:2b:82:cb:23:98:23:63:e2:f7:97:8a:43:5b:f3:bd:92 1052 Signature Algorithm: ED25519 1053 Issuer: CN = Ed25519 test certificate 1054 Validity 1055 Not Before: May 6 17:27:16 2019 GMT 1056 Not After : Jun 5 17:27:16 2019 GMT 1057 Subject: CN = Ed25519 test certificate 1058 Subject Public Key Info: 1059 Public Key Algorithm: ED25519 1060 ED25519 Public-Key: 1061 pub: 1062 36:29:c5:6c:0d:4f:14:6c:81:d0:ff:75:d3:6a:70: 1063 5f:69:cd:0f:4d:66:d5:da:98:7e:82:49:89:a3:8a: 1064 3c:fa 1065 X509v3 extensions: 1066 X509v3 Subject Key Identifier: 1067 09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE 1068 X509v3 Authority Key Identifier: 1069 keyid:09:3B:3A:9D:4A:29:D8:95:FF:68:BE:7B:43:54:72:E0:AD:A2:E3:AE 1070 1071 X509v3 Basic Constraints: critical 1072 CA:TRUE 1073 Signature Algorithm: ED25519 1074 53:a5:58:1c:2c:3b:2a:9e:ac:9d:4e:a5:1d:5f:5d:6d:a6:b5: 1075 08:de:12:82:f3:97:20:ae:fa:d8:98:f4:1a:83:32:6b:91:f5: 1076 24:1d:c4:20:7f:2c:e2:4d:da:13:3b:6d:54:1a:d2:a8:28:dc: 1077 60:b9:d4:f4:78:4b:3c:1c:91:00 1078 -----BEGIN CERTIFICATE----- 1079 MIIBWzCCAQ2gAwIBAgIUDIPYISuCyyOYI2Pi95eKQ1vzvZIwBQYDK2VwMCMxITAf 1080 BgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZpY2F0ZTAeFw0xOTA1MDYxNzI3MTZa 1081 Fw0xOTA2MDUxNzI3MTZaMCMxITAfBgNVBAMMGEVkMjU1MTkgdGVzdCBjZXJ0aWZp 1082 Y2F0ZTAqMAUGAytlcAMhADYpxWwNTxRsgdD/ddNqcF9pzQ9NZtXamH6CSYmjijz6 1083 o1MwUTAdBgNVHQ4EFgQUCTs6nUop2JX/aL57Q1Ry4K2i464wHwYDVR0jBBgwFoAU 1084 CTs6nUop2JX/aL57Q1Ry4K2i464wDwYDVR0TAQH/BAUwAwEB/zAFBgMrZXADQQBT 1085 pVgcLDsqnqydTqUdX11tprUI3hKC85cgrvrYmPQagzJrkfUkHcQgfyziTdoTO21U 1086 GtKoKNxgudT0eEs8HJEA 1087 -----END CERTIFICATE-----` 1088 1089 func TestEd25519SelfSigned(t *testing.T) { 1090 der, _ := pem.Decode([]byte(ed25519Certificate)) 1091 if der == nil { 1092 t.Fatalf("Failed to find PEM block") 1093 } 1094 1095 cert, err := ParseCertificate(der.Bytes) 1096 if err != nil { 1097 t.Fatalf("Failed to parse: %s", err) 1098 } 1099 1100 if cert.PublicKeyAlgorithm != Ed25519 { 1101 t.Fatalf("Parsed key algorithm was not Ed25519") 1102 } 1103 parsedKey, ok := cert.PublicKey.(ed25519.PublicKey) 1104 if !ok { 1105 t.Fatalf("Parsed key was not an Ed25519 key: %s", err) 1106 } 1107 if len(parsedKey) != ed25519.PublicKeySize { 1108 t.Fatalf("Invalid Ed25519 key") 1109 } 1110 1111 if err = cert.CheckSignatureFrom(cert); err != nil { 1112 t.Fatalf("Signature check failed: %s", err) 1113 } 1114 } 1115 1116 const pemCertificate = `-----BEGIN CERTIFICATE----- 1117 MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw 1118 EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2 1119 MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw 1120 ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4 1121 jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH 1122 qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK 1123 yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB 1124 EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I 1125 5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF 1126 oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC 1127 EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7 1128 X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6 1129 1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai 1130 /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy 1131 fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH 1132 KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5 1133 EhLrEqU= 1134 -----END CERTIFICATE-----` 1135 1136 func TestCRLCreation(t *testing.T) { 1137 block, _ := pem.Decode([]byte(pemPrivateKey)) 1138 priv, _ := ParsePKCS1PrivateKey(block.Bytes) 1139 block, _ = pem.Decode([]byte(pemCertificate)) 1140 cert, _ := ParseCertificate(block.Bytes) 1141 1142 loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds())) 1143 1144 now := time.Unix(1000, 0).In(loc) 1145 nowUTC := now.UTC() 1146 expiry := time.Unix(10000, 0) 1147 1148 revokedCerts := []pkix.RevokedCertificate{ 1149 { 1150 SerialNumber: big.NewInt(1), 1151 RevocationTime: nowUTC, 1152 }, 1153 { 1154 SerialNumber: big.NewInt(42), 1155 // RevocationTime should be converted to UTC before marshaling. 1156 RevocationTime: now, 1157 }, 1158 } 1159 expectedCerts := []pkix.RevokedCertificate{ 1160 { 1161 SerialNumber: big.NewInt(1), 1162 RevocationTime: nowUTC, 1163 }, 1164 { 1165 SerialNumber: big.NewInt(42), 1166 RevocationTime: nowUTC, 1167 }, 1168 } 1169 1170 crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry) 1171 if err != nil { 1172 t.Errorf("error creating CRL: %s", err) 1173 } 1174 1175 parsedCRL, err := ParseDERCRL(crlBytes) 1176 if err != nil { 1177 t.Errorf("error reparsing CRL: %s", err) 1178 } 1179 if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) { 1180 t.Errorf("RevokedCertificates mismatch: got %v; want %v.", 1181 parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) 1182 } 1183 } 1184 1185 func fromBase64(in string) []byte { 1186 out := make([]byte, base64.StdEncoding.DecodedLen(len(in))) 1187 n, err := base64.StdEncoding.Decode(out, []byte(in)) 1188 if err != nil { 1189 panic("failed to base64 decode") 1190 } 1191 return out[:n] 1192 } 1193 1194 func TestParseDERCRL(t *testing.T) { 1195 derBytes := fromBase64(derCRLBase64) 1196 certList, err := ParseDERCRL(derBytes) 1197 if err != nil { 1198 t.Errorf("error parsing: %s", err) 1199 return 1200 } 1201 numCerts := len(certList.TBSCertList.RevokedCertificates) 1202 expected := 88 1203 if numCerts != expected { 1204 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 1205 } 1206 1207 if certList.HasExpired(time.Unix(1302517272, 0)) { 1208 t.Errorf("CRL has expired (but shouldn't have)") 1209 } 1210 1211 // Can't check the signature here without a package cycle. 1212 } 1213 1214 func TestCRLWithoutExpiry(t *testing.T) { 1215 derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh") 1216 certList, err := ParseDERCRL(derBytes) 1217 if err != nil { 1218 t.Fatal(err) 1219 } 1220 if !certList.TBSCertList.NextUpdate.IsZero() { 1221 t.Errorf("NextUpdate is not the zero value") 1222 } 1223 } 1224 1225 func TestParsePEMCRL(t *testing.T) { 1226 pemBytes := fromBase64(pemCRLBase64) 1227 certList, err := ParseCRL(pemBytes) 1228 if err != nil { 1229 t.Errorf("error parsing: %s", err) 1230 return 1231 } 1232 numCerts := len(certList.TBSCertList.RevokedCertificates) 1233 expected := 2 1234 if numCerts != expected { 1235 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 1236 } 1237 1238 if certList.HasExpired(time.Unix(1302517272, 0)) { 1239 t.Errorf("CRL has expired (but shouldn't have)") 1240 } 1241 1242 // Can't check the signature here without a package cycle. 1243 } 1244 1245 func TestImports(t *testing.T) { 1246 if testing.Short() { 1247 t.Skip("skipping in -short mode") 1248 } 1249 testenv.MustHaveGoRun(t) 1250 1251 if out, err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").CombinedOutput(); err != nil { 1252 t.Errorf("failed to run x509_test_import.go: %s\n%s", err, out) 1253 } 1254 } 1255 1256 const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1Ci/UHJ0DPFw0wOTA3MTYwODQzMTNaMAAwIQIOESB9tVAmX3cY7QcnQNAXDTA5MDcxNjA4NDUyMlowADAhAg4S1tGAQ3mHt8uVBydA1RcNMDkwODA0MT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:= rand.Reader 1262 1263 ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 1264 if err != nil { 1265 t.Fatalf("Failed to generate ECDSA key: %s", err) 1266 } 1267 1268 ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 1269 if err != nil { 1270 t.Fatalf("Failed to generate ECDSA key: %s", err) 1271 } 1272 1273 ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) 1274 if err != nil { 1275 t.Fatalf("Failed to generate ECDSA key: %s", err) 1276 } 1277 1278 _, ed25519Priv, err := ed25519.GenerateKey(random) 1279 if err != nil { 1280 t.Fatalf("Failed to generate Ed25519 key: %s", err) 1281 } 1282 1283 tests := []struct { 1284 name string 1285 priv interface{} 1286 sigAlgo SignatureAlgorithm 1287 }{ 1288 {"RSA", testPrivateKey, SHA1WithRSA}, 1289 {"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1}, 1290 {"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1}, 1291 {"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1}, 1292 {"Ed25519", ed25519Priv, PureEd25519}, 1293 } 1294 1295 for _, test := range tests { 1296 template := CertificateRequest{ 1297 Subject: pkix.Name{ 1298 CommonName: "test.example.com", 1299 Organization: []string{"Σ Acme Co"}, 1300 }, 1301 SignatureAlgorithm: test.sigAlgo, 1302 DNSNames: []string{"test.example.com"}, 1303 EmailAddresses: []string{"gopher@golang.org"}, 1304 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 1305 } 1306 1307 derBytes, err := CreateCertificateRequest(random, &template, test.priv) 1308 if err != nil { 1309 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 1310 continue 1311 } 1312 1313 out, err := ParseCertificateRequest(derBytes) 1314 if err != nil { 1315 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 1316 continue 1317 } 1318 1319 err = out.CheckSignature() 1320 if err != nil { 1321 t.Errorf("%s: failed to check certificate request signature: %s", test.name, err) 1322 continue 1323 } 1324 1325 if out.Subject.CommonName != template.Subject.CommonName { 1326 t.Errorf("%s: output subject common name and template subject common name don't match", test.name) 1327 } else if len(out.Subject.Organization) != len(template.Subject.Organization) { 1328 t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name) 1329 } else if len(out.DNSNames) != len(template.DNSNames) { 1330 t.Errorf("%s: output DNS names and template DNS names don't match", test.name) 1331 } else if len(out.EmailAddresses) != len(template.EmailAddresses) { 1332 t.Errorf("%s: output email addresses and template email addresses don't match", test.name) 1333 } else if len(out.IPAddresses) != len(template.IPAddresses) { 1334 t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name) 1335 } 1336 } 1337 } 1338 1339 func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest { 1340 derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey) 1341 if err != nil { 1342 t.Fatal(err) 1343 } 1344 1345 csr, err := ParseCertificateRequest(derBytes) 1346 if err != nil { 1347 t.Fatal(err) 1348 } 1349 1350 return csr 1351 } 1352 1353 func TestCertificateRequestOverrides(t *testing.T) { 1354 sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil, nil) 1355 if err != nil { 1356 t.Fatal(err) 1357 } 1358 1359 template := CertificateRequest{ 1360 Subject: pkix.Name{ 1361 CommonName: "test.example.com", 1362 Organization: []string{"Σ Acme Co"}, 1363 }, 1364 DNSNames: []string{"test.example.com"}, 1365 1366 // An explicit extension should override the DNSNames from the 1367 // template. 1368 ExtraExtensions: []pkix.Extension{ 1369 { 1370 Id: oidExtensionSubjectAltName, 1371 Value: sanContents, 1372 Critical: true, 1373 }, 1374 }, 1375 } 1376 1377 csr := marshalAndParseCSR(t, &template) 1378 1379 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" { 1380 t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames) 1381 } 1382 1383 if len(csr.Extensions) != 1 || !csr.Extensions[0].Id.Equal(oidExtensionSubjectAltName) || !csr.Extensions[0].Critical { 1384 t.Errorf("SAN extension was not faithfully copied, got %#v", csr.Extensions) 1385 } 1386 1387 // If there is already an attribute with X.509 extensions then the 1388 // extra extensions should be added to it rather than creating a CSR 1389 // with two extension attributes. 1390 1391 template.Attributes = []pkix.AttributeTypeAndValueSET{ 1392 { 1393 Type: oidExtensionRequest, 1394 Value: [][]pkix.AttributeTypeAndValue{ 1395 { 1396 { 1397 Type: oidExtensionAuthorityInfoAccess, 1398 Value: []byte("foo"), 1399 }, 1400 }, 1401 }, 1402 }, 1403 } 1404 1405 csr = marshalAndParseCSR(t, &template) 1406 if l := len(csr.Attributes); l != 1 { 1407 t.Errorf("incorrect number of attributes: %d\n", l) 1408 } 1409 1410 if !csr.Attributes[0].Type.Equal(oidExtensionRequest) || 1411 len(csr.Attributes[0].Value) != 1 || 1412 len(csr.Attributes[0].Value[0]) != 2 { 1413 t.Errorf("bad attributes: %#v\n", csr.Attributes) 1414 } 1415 1416 sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil, nil) 1417 if err != nil { 1418 t.Fatal(err) 1419 } 1420 1421 // Extensions in Attributes should override those in ExtraExtensions. 1422 template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{ 1423 Type: oidExtensionSubjectAltName, 1424 Value: sanContents2, 1425 }) 1426 1427 csr = marshalAndParseCSR(t, &template) 1428 1429 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" { 1430 t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames) 1431 } 1432 } 1433 1434 func TestParseCertificateRequest(t *testing.T) { 1435 for _, csrBase64 := range csrBase64Array { 1436 csrBytes := fromBase64(csrBase64) 1437 csr, err := ParseCertificateRequest(csrBytes) 1438 if err != nil { 1439 t.Fatalf("failed to parse CSR: %s", err) 1440 } 1441 1442 if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" { 1443 t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses) 1444 } 1445 1446 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" { 1447 t.Errorf("incorrect DNS names found: %v", csr.DNSNames) 1448 } 1449 1450 if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" { 1451 t.Errorf("incorrect Subject name: %v", csr.Subject) 1452 } 1453 1454 found := false 1455 for _, e := range csr.Extensions { 1456 if e.Id.Equal(oidExtensionBasicConstraints) { 1457 found = true 1458 break 1459 } 1460 } 1461 if !found { 1462 t.Errorf("basic constraints extension not found in CSR") 1463 } 1464 } 1465 } 1466 1467 func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) { 1468 // This CSR contains an extension request where the extensions have a 1469 // critical flag in them. In the past we failed to handle this. 1470 const csrBase64 = "MIICrTCCAZUCAQIwMzEgMB4GA1UEAwwXU0NFUCBDQSBmb3IgRGV2ZWxlciBTcmwxDzANBgNVBAsMBjQzNTk3MTCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALFMAJ7Zy9YyfgbNlbUWAW0LalNRMPs7aXmLANsCpjhnw3lLlfDPaLeWyKh1nK5I5ojaJOW6KIOSAcJkDUe3rrE0wR0RVt3UxArqs0R/ND3u5Q+bDQY2X1HAFUHzUzcdm5JRAIA355v90teMckaWAIlkRQjDE22Lzc6NAl64KOd1rqOUNj8+PfX6fSo20jm94Pp1+a6mfk3G/RUWVuSm7owO5DZI/Fsi2ijdmb4NUar6K/bDKYTrDFkzcqAyMfP3TitUtBp19Mp3B1yAlHjlbp/r5fSSXfOGHZdgIvp0WkLuK2u5eQrX5l7HMB/5epgUs3HQxKY6ljhh5wAjDwz//LsCAwEAAaA1MDMGCSqGSIb3DQEJDjEmMCQwEgYDVR0TAQH/BAgwBgEB/wIBADAOBgNVHQ8BAf8EBAMCAoQwDQYJKoZIhvcNAQEFBQADggEBAAMq3bxJSPQEgzLYR/yaVvgjCDrc3zUbIwdOis6Go06Q4RnjH5yRaSZAqZQTDsPurQcnz2I39VMGEiSkFJFavf4QHIZ7QFLkyXadMtALc87tm17Ej719SbHcBSSZayR9VYJUNXRLayI6HvyUrmqcMKh+iX3WY3ICr59/wlM0tYa8DYN4yzmOa2Onb29gy3YlaF5A2AKAMmk003cRT9gY26mjpv7d21czOSSeNyVIoZ04IR9ee71vWTMdv0hu/af5kSjQ+ZG5/Qgc0+mnECLz/1gtxt1srLYbtYQ/qAY8oX1DCSGFS61tN/vl+4cxGMD/VGcGzADRLRHSlVqy2Qgss6Q=" 1471 1472 csrBytes := fromBase64(csrBase64) 1473 csr, err := ParseCertificateRequest(csrBytes) 1474 if err != nil { 1475 t.Fatalf("failed to parse CSR: %s", err) 1476 } 1477 1478 expected := []struct { 1479 Id asn1.ObjectIdentifier 1480 Value []byte 1481 }{ 1482 {oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")}, 1483 {oidExtensionKeyUsage, fromBase64("AwIChA==")}, 1484 } 1485 1486 if n := len(csr.Extensions); n != len(expected) { 1487 t.Fatalf("expected to find %d extensions but found %d", len(expected), n) 1488 } 1489 1490 for i, extension := range csr.Extensions { 1491 if !extension.Id.Equal(expected[i].Id) { 1492 t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id) 1493 } 1494 1495 if !bytes.Equal(extension.Value, expected[i].Value) { 1496 t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value) 1497 } 1498 } 1499 } 1500 1501 // serialiseAndParse generates a self-signed certificate from template and 1502 // returns a parsed version of it. 1503 func serialiseAndParse(t *testing.T, template *Certificate) *Certificate { 1504 derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey) 1505 if err != nil { 1506 t.Fatalf("failed to create certificate: %s", err) 1507 return nil 1508 } 1509 1510 cert, err := ParseCertificate(derBytes) 1511 if err != nil { 1512 t.Fatalf("failed to parse certificate: %s", err) 1513 return nil 1514 } 1515 1516 return cert 1517 } 1518 1519 func TestMaxPathLen(t *testing.T) { 1520 template := &Certificate{ 1521 SerialNumber: big.NewInt(1), 1522 Subject: pkix.Name{ 1523 CommonName: "Σ Acme Co", 1524 }, 1525 NotBefore: time.Unix(1000, 0), 1526 NotAfter: time.Unix(100000, 0), 1527 1528 BasicConstraintsValid: true, 1529 IsCA: true, 1530 } 1531 1532 cert1 := serialiseAndParse(t, template) 1533 if m := cert1.MaxPathLen; m != -1 { 1534 t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m) 1535 } 1536 if cert1.MaxPathLenZero { 1537 t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero") 1538 } 1539 1540 template.MaxPathLen = 1 1541 cert2 := serialiseAndParse(t, template) 1542 if m := cert2.MaxPathLen; m != 1 { 1543 t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m) 1544 } 1545 if cert2.MaxPathLenZero { 1546 t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero") 1547 } 1548 1549 template.MaxPathLen = 0 1550 template.MaxPathLenZero = true 1551 cert3 := serialiseAndParse(t, template) 1552 if m := cert3.MaxPathLen; m != 0 { 1553 t.Errorf("Setting MaxPathLenZero didn't work, got %d", m) 1554 } 1555 if !cert3.MaxPathLenZero { 1556 t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero") 1557 } 1558 } 1559 1560 func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) { 1561 template := &Certificate{ 1562 SerialNumber: big.NewInt(1), 1563 Subject: pkix.Name{ 1564 CommonName: "Σ Acme Co", 1565 }, 1566 NotBefore: time.Unix(1000, 0), 1567 NotAfter: time.Unix(100000, 0), 1568 1569 BasicConstraintsValid: true, 1570 IsCA: true, 1571 SubjectKeyId: []byte{1, 2, 3, 4}, 1572 } 1573 1574 if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 { 1575 t.Fatalf("self-signed certificate contained default authority key id") 1576 } 1577 1578 template.AuthorityKeyId = []byte{1, 2, 3, 4} 1579 if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 { 1580 t.Fatalf("self-signed certificate erased explicit authority key id") 1581 } 1582 } 1583 1584 func TestASN1BitLength(t *testing.T) { 1585 tests := []struct { 1586 bytes []byte 1587 bitLen int 1588 }{ 1589 {nil, 0}, 1590 {[]byte{0x00}, 0}, 1591 {[]byte{0x00, 0x00}, 0}, 1592 {[]byte{0xf0}, 4}, 1593 {[]byte{0x88}, 5}, 1594 {[]byte{0xff}, 8}, 1595 {[]byte{0xff, 0x80}, 9}, 1596 {[]byte{0xff, 0x81}, 16}, 1597 } 1598 1599 for i, test := range tests { 1600 if got := asn1BitLength(test.bytes); got != test.bitLen { 1601 t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen) 1602 } 1603 } 1604 } 1605 1606 func TestVerifyEmptyCertificate(t *testing.T) { 1607 if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed { 1608 t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed) 1609 } 1610 } 1611 1612 func TestInsecureAlgorithmErrorString(t *testing.T) { 1613 tests := []struct { 1614 sa SignatureAlgorithm 1615 want string 1616 }{ 1617 {MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"}, 1618 {-1, "x509: cannot verify signature: insecure algorithm -1"}, 1619 {0, "x509: cannot verify signature: insecure algorithm 0"}, 1620 {9999, "x509: cannot verify signature: insecure algorithm 9999"}, 1621 } 1622 for i, tt := range tests { 1623 if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want { 1624 t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want) 1625 } 1626 } 1627 } 1628 1629 // These CSR was generated with OpenSSL: 1630 // openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf 1631 // 1632 // With openssl.cnf containing the following sections: 1633 // [ v3_req ] 1634 // basicConstraints = CA:FALSE 1635 // keyUsage = nonRepudiation, digitalSignature, keyEncipherment 1636 // subjectAltName = email:gopher@golang.org,DNS:test.example.com 1637 // [ req_attributes ] 1638 // challengePassword = ignored challenge 1639 // unstructuredName = ignored unstructured name 1640 var csrBase64Array = [...]string{ 1641 // Just [ v3_req ] 1642 "MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBAB6VPMRrchvNW61Tokyq3ZvO6/NoGIbuwUn54q6l5VZW0Ep5Nq8juhegSSnaJ0jrovmUgKDN9vEo2KxuAtwG6udS6Ami3zP+hRd4k9Q8djJPb78nrjzWiindLK5Fps9U5mMoi1ER8ViveyAOTfnZt/jsKUaRsscY2FzE9t9/o5moE6LTcHUS4Ap1eheR+J72WOn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ccOhzUCcZ/G4qcrfhhx6gTZTeA01nP7TdTJURvWAH5iFqj9sQ0qnLq6nEcVHij3sG6M5+BxAIVClQBk6lTCzgphc835Fjj6qSLuJ20XHdL5UfUbiJxx299CHgyBRL+hBUIPfz8p+ZgamyAuDLfnj54zzcRVyLlrmMLNPZNll1Q70RxoU6uWvLH8wB8vQe3Q/guSGubLyLRTUQVPh+dw1L4t8MKFWfX/48jwRM4gIRHFHPeAAE9D9YAoqdIvj/iFm/eQ++7DP8MDwOZWsXeB6jjwHuLmkQ==", 1645 } 1646 1647 var md5cert = ` 1648 -----BEGIN CERTIFICATE----- 1649 MIIB4TCCAUoCCQCfmw3vMgPS5TANBgkqhkiG9w0BAQQFADA1MQswCQYDVQQGEwJB 1650 VTETMBEGA1UECBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wHhcNMTUx 1651 MjAzMTkyOTMyWhcNMjkwODEyMTkyOTMyWjA1MQswCQYDVQQGEwJBVTETMBEGA1UE 1652 CBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wgZ8wDQYJKoZIhvcNAQEB 1653 BQADgY0AMIGJAoGBANrq2nhLQj5mlXbpVX3QUPhfEm/vdEqPkoWtR/jRZIWm4WGf 1654 Wpq/LKHJx2Pqwn+t117syN8l4U5unyAi1BJSXjBwPZNd7dXjcuJ+bRLV7FZ/iuvs 1655 cfYyQQFTxan4TaJMd0x1HoNDbNbjHa02IyjjYE/r3mb/PIg+J2t5AZEh80lPAgMB 1656 AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY 1657 cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw 1658 GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa 1659 qViorq4= 1660 -----END CERTIFICATE----- 1661 ` 1662 1663 func TestMD5(t *testing.T) { 1664 pemBlock, _ := pem.Decode([]byte(md5cert)) 1665 cert, err := ParseCertificate(pemBlock.Bytes) 1666 if err != nil { 1667 t.Fatalf("failed to parse certificate: %s", err) 1668 } 1669 if sa := cert.SignatureAlgorithm; sa != MD5WithRSA { 1670 t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA) 1671 } 1672 if err = cert.CheckSignatureFrom(cert); err == nil { 1673 t.Fatalf("certificate verification succeeded incorrectly") 1674 } 1675 if _, ok := err.(InsecureAlgorithmError); !ok { 1676 t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err) 1677 } 1678 } 1679 1680 // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifer 1681 // parameters are omitted rather than being an ASN.1 NULL. 1682 const certMissingRSANULL = ` 1683 -----BEGIN CERTIFICATE----- 1684 MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD 1685 bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4 1686 MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc 1687 MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG 1688 hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE 1689 ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e 1690 E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw 1691 DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A 1692 p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4 1693 hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE 1694 GFGNEH5PlGffo05wc46QkYU= 1695 -----END CERTIFICATE-----` 1696 1697 func TestRSAMissingNULLParameters(t *testing.T) { 1698 block, _ := pem.Decode([]byte(certMissingRSANULL)) 1699 if _, err := ParseCertificate(block.Bytes); err == nil { 1700 t.Error("unexpected success when parsing certificate with missing RSA NULL parameter") 1701 } else if !strings.Contains(err.Error(), "missing NULL") { 1702 t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err) 1703 } 1704 } 1705 1706 const certISOOID = ` 1707 -----BEGIN CERTIFICATE----- 1708 MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN 1709 BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx 1710 DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH 1711 GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86 1712 BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw 1713 5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw 1714 OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW 1715 V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE 1716 J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2 1717 NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu 1718 MCRtdSdaM7g3 1719 -----END CERTIFICATE-----` 1720 1721 func TestISOOIDInCertificate(t *testing.T) { 1722 block, _ := pem.Decode([]byte(certISOOID)) 1723 if cert, err := ParseCertificate(block.Bytes); err != nil { 1724 t.Errorf("certificate with ISO OID failed to parse: %s", err) 1725 } else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm { 1726 t.Errorf("ISO OID not recognised in certificate") 1727 } 1728 } 1729 1730 // certMultipleRDN contains a RelativeDistinguishedName with two elements (the 1731 // common name and serial number). This particular certificate was the first 1732 // such certificate in the “Pilot” Certificate Transparency log. 1733 const certMultipleRDN = ` 1734 -----BEGIN CERTIFICATE----- 1735 MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz 1736 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j 1737 YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz 1738 aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwFwYDVQQLExB3ZWItY2Vy 1739 dGlmaWNhdGVzMRAwDgYDVQQLEwdTZXJ2ZXJzMTIwFAYDVQQFEw0xMjM2NDg0MDEw 1740 MDEwMBoGA1UEAxMTZXBvcnRhbC5tc3MuZWR1cy5zaTCCASIwDQYJKoZIhvcNAQEB 1741 BQADggEPADCCAQoCggEBAMrNkZH9MPuBTjMGNk3sJX8V+CkFx/4ru7RTlLS6dlYM 1742 098dtSfJ3s2w0p/1NB9UmR8j0yS0Kg6yoZ3ShsSO4DWBtcQD8820a6BYwqxxQTNf 1743 HSRZOc+N/4TQrvmK6t4k9Aw+YEYTMrWOU4UTeyhDeCcUsBdh7HjfWsVaqNky+2sv 1744 oic3zP5gF+2QfPkvOoHT3FLR8olNhViIE6Kk3eFIEs4dkq/ZzlYdLb8pHQoj/sGI 1745 zFmA5AFvm1HURqOmJriFjBwaCtn8AVEYOtQrnUCzJYu1ex8azyS2ZgY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uKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd 1762 La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF 1763 DF72IUofoVt7wo0= 1764 -----END CERTIFICATE-----` 1765 1766 func TestMultipleRDN(t *testing.T) { 1767 block, _ := pem.Decode([]byte(certMultipleRDN)) 1768 cert, err := ParseCertificate(block.Bytes) 1769 if err != nil { 1770 t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err) 1771 } 1772 1773 if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want { 1774 t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want) 1775 } 1776 1777 if want := "1236484010010"; cert.Subject.SerialNumber != want { 1778 t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want) 1779 } 1780 } 1781 1782 func TestSystemCertPool(t *testing.T) { 1783 if runtime.GOOS == "windows" { 1784 t.Skip("not implemented on Windows; Issue 16736, 18609") 1785 } 1786 a, err := SystemCertPool() 1787 if err != nil { 1788 t.Fatal(err) 1789 } 1790 b, err := SystemCertPool() 1791 if err != nil { 1792 t.Fatal(err) 1793 } 1794 if !reflect.DeepEqual(a, b) { 1795 t.Fatal("two calls to SystemCertPool had different results") 1796 } 1797 if ok := b.AppendCertsFromPEM([]byte(` 1798 -----BEGIN CERTIFICATE----- 1799 MIIDBjCCAe6gAwIBAgIRANXM5I3gjuqDfTp/PYrs+u8wDQYJKoZIhvcNAQELBQAw 1800 EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xODAzMjcxOTU2MjFaFw0xOTAzMjcxOTU2 1801 MjFaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw 1802 ggEKAoIBAQDK+9m3rjsO2Djes6bIYQZ3eV29JF09ZrjOrEHLtaKrD6/acsoSoTsf 1803 cQr+rzzztdB5ijWXCS64zo/0OiqBeZUNZ67jVdToa9qW5UYe2H0Y+ZNdfA5GYMFD 1804 yk/l3/uBu3suTZPfXiW2TjEi27Q8ruNUIZ54DpTcs6y2rBRFzadPWwn/VQMlvRXM 1805 jrzl8Y08dgnYmaAHprxVzwMXcQ/Brol+v9GvjaH1DooHqkn8O178wsPQNhdtvN01 1806 IXL46cYdcUwWrE/GX5u+9DaSi+0KWxAPQ+NVD5qUI0CKl4714yGGh7feXMjJdHgl 1807 VG4QJZlJvC4FsURgCHJT6uHGIelnSwhbAgMBAAGjVzBVMA4GA1UdDwEB/wQEAwIF 1808 oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMCAGA1UdEQQZMBeC 1809 FVRlc3RTeXN0ZW1DZXJ0UG9vbC5nbzANBgkqhkiG9w0BAQsFAAOCAQEAwuSRx/VR 1810 BKh2ICxZjL6jBwk/7UlU1XKbhQD96RqkidDNGEc6eLZ90Z5XXTurEsXqdm5jQYPs 1811 1cdcSW+fOSMl7MfW9e5tM66FaIPZl9rKZ1r7GkOfgn93xdLAWe8XHd19xRfDreub 1812 YC8DVqgLASOEYFupVSl76ktPfxkU5KCvmUf3P2PrRybk1qLGFytGxfyice2gHSNI 1813 gify3K/+H/7wCkyFW4xYvzl7WW4mXxoqPRPjQt1J423DhnnQ4G1P8V/vhUpXNXOq 1814 N9IEPnWuihC09cyx/WMQIUlWnaQLHdfpPS04Iez3yy2PdfXJzwfPrja7rNE+skK6 1815 pa/O1nF0AfWOpw== 1816 -----END CERTIFICATE----- 1817 `)); !ok { 1818 t.Fatal("AppendCertsFromPEM failed") 1819 } 1820 if reflect.DeepEqual(a, b) { 1821 t.Fatal("changing one pool modified the other") 1822 } 1823 } 1824 1825 const emptyNameConstraintsPEM = ` 1826 -----BEGIN CERTIFICATE----- 1827 MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w 1828 dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw 1829 NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB 1830 IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD 1831 F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx 1832 f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq 1833 Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0 1834 LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD 1835 blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID 1836 AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH 1837 QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb 1838 6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H 1839 v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M 1840 LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga 1841 nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8 1842 o+WoY6IsCKXV/g== 1843 -----END CERTIFICATE-----` 1844 1845 func TestEmptyNameConstraints(t *testing.T) { 1846 block, _ := pem.Decode([]byte(emptyNameConstraintsPEM)) 1847 _, err := ParseCertificate(block.Bytes) 1848 if err == nil { 1849 t.Fatal("unexpected success") 1850 } 1851 1852 const expected = "empty name constraints" 1853 if str := err.Error(); !strings.Contains(str, expected) { 1854 t.Errorf("expected %q in error but got %q", expected, str) 1855 } 1856 } 1857 1858 func TestPKIXNameString(t *testing.T) { 1859 pem, err := hex.DecodeString(certBytes) 1860 if err != nil { 1861 t.Fatal(err) 1862 } 1863 certs, err := ParseCertificates(pem) 1864 if err != nil { 1865 t.Fatal(err) 1866 } 1867 1868 tests := []struct { 1869 dn pkix.Name 1870 want string 1871 }{ 1872 {pkix.Name{ 1873 CommonName: "Steve Kille", 1874 Organization: []string{"Isode Limited"}, 1875 OrganizationalUnit: []string{"RFCs"}, 1876 Locality: []string{"Richmond"}, 1877 Province: []string{"Surrey"}, 1878 StreetAddress: []string{"The Square"}, 1879 PostalCode: []string{"TW9 1DT"}, 1880 SerialNumber: "RFC 2253", 1881 Country: []string{"GB"}, 1882 }, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"}, 1883 {certs[0].Subject, 1884 "CN=mail.google.com,O=Google Inc,L=Mountain View,ST=California,C=US"}, 1885 {pkix.Name{ 1886 Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "}, 1887 Country: []string{"US"}, 1888 }, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"}, 1889 {pkix.Name{ 1890 CommonName: "foo.com", 1891 Organization: []string{"Gopher Industries"}, 1892 ExtraNames: []pkix.AttributeTypeAndValue{ 1893 {Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}}, 1894 }, "CN=bar.com,O=Gopher Industries"}, 1895 {pkix.Name{ 1896 Locality: []string{"Gophertown"}, 1897 ExtraNames: []pkix.AttributeTypeAndValue{ 1898 {Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}}, 1899 }, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"}, 1900 } 1901 1902 for i, test := range tests { 1903 if got := test.dn.String(); got != test.want { 1904 t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want) 1905 } 1906 } 1907 } 1908 1909 func TestRDNSequenceString(t *testing.T) { 1910 // Test some extra cases that get lost in pkix.Name conversions such as 1911 // multi-valued attributes. 1912 1913 var ( 1914 oidCountry = []int{2, 5, 4, 6} 1915 oidOrganization = []int{2, 5, 4, 10} 1916 oidOrganizationalUnit = []int{2, 5, 4, 11} 1917 oidCommonName = []int{2, 5, 4, 3} 1918 ) 1919 1920 tests := []struct { 1921 seq pkix.RDNSequence 1922 want string 1923 }{ 1924 { 1925 seq: pkix.RDNSequence{ 1926 pkix.RelativeDistinguishedNameSET{ 1927 pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"}, 1928 }, 1929 pkix.RelativeDistinguishedNameSET{ 1930 pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."}, 1931 }, 1932 pkix.RelativeDistinguishedNameSET{ 1933 pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"}, 1934 pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"}, 1935 }, 1936 }, 1937 want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US", 1938 }, 1939 } 1940 1941 for i, test := range tests { 1942 if got := test.seq.String(); got != test.want { 1943 t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want) 1944 } 1945 } 1946 } 1947 1948 const criticalNameConstraintWithUnknownTypePEM = ` 1949 -----BEGIN CERTIFICATE----- 1950 MIIC/TCCAeWgAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w 1951 dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw 1952 NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB 1953 IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD 1954 F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx 1955 f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq 1956 Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0 1957 LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD 1958 blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID 1959 AQABozgwNjA0BgNVHR4BAf8EKjAooCQwIokgIACrzQAAAAAAAAAAAAAAAP////8A 1960 AAAAAAAAAAAAAAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMHQhP8uNCtgSHy 1961 im/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb6L+iJa4ElREJ 1962 Oi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6Hv5SsvpYW+1Xl 1963 eYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6MLYPmRhTioROA 1964 /drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOganCOSyFYfGhqO 1965 ANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8o+WoY6IsCKXV 1966 /g== 1967 -----END CERTIFICATE-----` 1968 1969 func TestCriticalNameConstraintWithUnknownType(t *testing.T) { 1970 block, _ := pem.Decode([]byte(criticalNameConstraintWithUnknownTypePEM)) 1971 cert, err := ParseCertificate(block.Bytes) 1972 if err != nil { 1973 t.Fatalf("unexpected parsing failure: %s", err) 1974 } 1975 1976 if l := len(cert.UnhandledCriticalExtensions); l != 1 { 1977 t.Fatalf("expected one unhandled critical extension, but found %d", l) 1978 } 1979 } 1980 1981 const badIPMaskPEM = ` 1982 -----BEGIN CERTIFICATE----- 1983 MIICzzCCAbegAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAxMSQmFk 1984 IElQIG1hc2sgaXNzdWVyMB4XDTEzMDIwMTAwMDAwMFoXDTIwMDUzMDEwNDgzOFow 1985 FjEUMBIGA1UEAxMLQmFkIElQIG1hc2swggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw 1986 ggEKAoIBAQDCuISVQi3csKqYk5uz7IOhY8MXkiqBaTqagihtiM997G1mJhTojcR+ 1987 8DCg3E8OQ3ZajByhxRkwlsR4Srl5sGSwWfF/XaAHGUhWIhjBkDO7toW+EMzI8pAj 1988 cLwIbRlIL0AFnUTe6Z0DcIS5406Y/9MKE2oKXbf4EbVBv88mSkA74Z+lZJWFNxXn 1989 cx/9wq8UdyMY2vHN1Kir1/JbtrqB9wYRBjQtWSbAVZR8nTBPyRp4uvQTS2jOQh+j 1990 TUo1Y3O/o1xg/zRA4FEOUCla704OYRUkc8NuXHiPNNDcktr7gO8E06NVQ6n6aBGa 1991 OJbSst2vHA7Eiog7A2PB4wKn+GDFf+FNAgMBAAGjIDAeMBwGA1UdHgEB/wQSMBCg 1992 DDAKhwgBAgME//8BAKEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYb7/NQwdCE/y40K2B 1993 IfKKb++HvCaKfAC9aAwrGWQsEWezqdl5Cqw5XWUAFjtTRm6iprVnmdvov6IlrgSV 1994 EQk6L96stz24vAF0MIBHSFRMoPtrqLiihLf0NOV7ztxSePQxbUJRroe/lKy+lhb7 1995 VeV5gmT9rFA45NzLgSznd2+dmyNcfQQD9AeeftRX4maUTeu1XFxinowtg+ZGFOKh 1996 E4D92uCGJxGSK72HF0/LGRhLXozmDdmPfSN2b6T/oLo942031iY46BqcI5LIVh8a 1997 Go4A1jOma5X6gh50Cw+kht8jM3yeNhSzXOKj7Uigjijx10z2wJu09Tyj5ahjoiwI 1998 pdX+ 1999 -----END CERTIFICATE-----` 2000 2001 func TestBadIPMask(t *testing.T) { 2002 block, _ := pem.Decode([]byte(badIPMaskPEM)) 2003 _, err := ParseCertificate(block.Bytes) 2004 if err == nil { 2005 t.Fatalf("unexpected success") 2006 } 2007 2008 const expected = "contained invalid mask" 2009 if !strings.Contains(err.Error(), expected) { 2010 t.Fatalf("expected %q in error but got: %s", expected, err) 2011 } 2012 } 2013 2014 const additionalGeneralSubtreePEM = ` 2015 -----BEGIN CERTIFICATE----- 2016 MIIG4TCCBMmgAwIBAgIRALss+4rLw2Ia7tFFhxE8g5cwDQYJKoZIhvcNAQELBQAw 2017 bjELMAkGA1UEBhMCTkwxIDAeBgNVBAoMF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll 2018 MT0wOwYDVQQDDDRNaW5pc3RlcmllIHZhbiBEZWZlbnNpZSBDZXJ0aWZpY2F0aWUg 2019 QXV0b3JpdGVpdCAtIEcyMB4XDTEzMDMwNjEyMDM0OVoXDTEzMTEzMDEyMDM1MFow 2020 bDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUNlcnRpUGF0aCBMTEMxIjAgBgNVBAsT 2021 GUNlcnRpZmljYXRpb24gQXV0aG9yaXRpZXMxITAfBgNVBAMTGENlcnRpUGF0aCBC 2022 cmlkZ2UgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANLW 2023 4kXiRqvwBhJfN9uz12FA+P2D34MPxOt7TGXljm2plJ2CLzvaH8/ymsMdSWdJBS1M 2024 8FmwvNL1w3A6ZuzksJjPikAu8kY3dcp3mrkk9eCPORDAwGtfsXwZysLiuEaDWpbD 2025 dHOaHnI6qWU0N6OI+hNX58EjDpIGC1WQdho1tHOTPc5Hf5/hOpM/29v/wr7kySjs 2026 Z+7nsvkm5rNhuJNzPsLsgzVaJ5/BVyOplZy24FKM8Y43MjR4osZm+a2e0zniqw6/ 2027 rvcjcGYabYaznZfQG1GXoyf2Vea+CCgpg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mjnXiTsziT3my0r9Mxvz/btKK/lnVOMW4c2q/8sIsIPnnW5ZaRGrsANB 2044 dNDZkzMYmeG2Pfgvd0AQSOrpE/TVgWfu/+MMRWwX9y6VbooBR7BLv7zMuVH0WqLn 2045 6OMFth7fqsThlfMSzkE/RDSaU6n3wXAWT1SIqBITtccRjSUQUFm/q3xrb2cwcZA6 2046 8vdS4hzNd+ttS905ay31Ks4/1Wrm1bH5RhEfRSH0VSXnc0b+z+RyBbmiwtVZqzxE 2047 u3UQg/rAmtLDclLFEzjp8YDTIRYSLwstDbEXO/0ArdGrQm79HQ8i/3ZbP2357myW 2048 i15qd6gMJIgGHS4b8Hc7R1K8LQ9Gm1aLKBEWVNGZlPK/cpXThpVmoEyslN2DHCrc 2049 fbMbjNZpXlTMa+/b9z7Fa4X8dY8u/ELzZuJXJv5Rmqtg29eopFFYDCl0Nkh1XAjo 2050 QejEoHHUvYV8TThHZr6Z6Ib8CECgTehU4QvepkgDXNoNrKRZBG0JhLjkwxh2whZq 2051 nvWBfALC2VuNOM6C0rDY+HmhMlVt0XeqnybD9MuQALMit7Z00Cw2CIjNsBI9xBqD 2052 xKK9CjUb7gzRUWSpB9jGHsvpEMHOzIFhufvH2Bz1XJw+Cl7khw== 2053 -----END CERTIFICATE-----` 2054 2055 func TestAdditionFieldsInGeneralSubtree(t *testing.T) { 2056 // Very rarely, certificates can include additional fields in the 2057 // GeneralSubtree structure. This tests that such certificates can be 2058 // parsed. 2059 block, _ := pem.Decode([]byte(additionalGeneralSubtreePEM)) 2060 if _, err := ParseCertificate(block.Bytes); err != nil { 2061 t.Fatalf("failed to parse certificate: %s", err) 2062 } 2063 } 2064 2065 func TestEmptySubject(t *testing.T) { 2066 template := Certificate{ 2067 SerialNumber: big.NewInt(1), 2068 DNSNames: []string{"example.com"}, 2069 } 2070 2071 derBytes, err := CreateCertificate(rand.Reader, &template, &template, &testPrivateKey.PublicKey, testPrivateKey) 2072 if err != nil { 2073 t.Fatalf("failed to create certificate: %s", err) 2074 } 2075 2076 cert, err := ParseCertificate(derBytes) 2077 if err != nil { 2078 t.Fatalf("failed to parse certificate: %s", err) 2079 } 2080 2081 for _, ext := range cert.Extensions { 2082 if ext.Id.Equal(oidExtensionSubjectAltName) { 2083 if !ext.Critical { 2084 t.Fatal("SAN extension is not critical") 2085 } 2086 return 2087 } 2088 } 2089 2090 t.Fatal("SAN extension is missing") 2091 } 2092 2093 // multipleURLsInCRLDPPEM contains two URLs in a single CRL DistributionPoint 2094 // structure. It is taken from https://crt.sh/?id=12721534. 2095 const multipleURLsInCRLDPPEM = ` 2096 -----BEGIN CERTIFICATE----- 2097 MIIF4TCCBMmgAwIBAgIQc+6uFePfrahUGpXs8lhiTzANBgkqhkiG9w0BAQsFADCB 2098 8zELMAkGA1UEBhMCRVMxOzA5BgNVBAoTMkFnZW5jaWEgQ2F0YWxhbmEgZGUgQ2Vy 2099 dGlmaWNhY2lvIChOSUYgUS0wODAxMTc2LUkpMSgwJgYDVQQLEx9TZXJ2ZWlzIFB1 2100 YmxpY3MgZGUgQ2VydGlmaWNhY2lvMTUwMwYDVQQLEyxWZWdldSBodHRwczovL3d3 2101 dy5jYXRjZXJ0Lm5ldC92ZXJhcnJlbCAoYykwMzE1MDMGA1UECxMsSmVyYXJxdWlh 2102 IEVudGl0YXRzIGRlIENlcnRpZmljYWNpbyBDYXRhbGFuZXMxDzANBgNVBAMTBkVD 2103 LUFDQzAeFw0xNDA5MTgwODIxMDBaFw0zMDA5MTgwODIxMDBaMIGGMQswCQYDVQQG 2104 EwJFUzEzMDEGA1UECgwqQ09OU09SQ0kgQURNSU5JU1RSQUNJTyBPQkVSVEEgREUg 2105 Q0FUQUxVTllBMSowKAYDVQQLDCFTZXJ2ZWlzIFDDumJsaWNzIGRlIENlcnRpZmlj 2106 YWNpw7MxFjAUBgNVBAMMDUVDLUNpdXRhZGFuaWEwggEiMA0GCSqGSIb3DQEBAQUA 2107 A4IBDwAwggEKAoIBAQDFkHPRZPZlXTWZ5psJhbS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5PyIhLjLgEs68CyNNC1+vDuZXRhy22TI83JcvGmQrZosPvVIL 2124 PsUXx+C06Pfqmh48Q9S89X9K8w1SdJxP/rZeGEoRiKpwvQzM4ArD9QxyC8jirxex 2125 3Umg9Ai/sXQ+1lBf6xw4HfUUr1WIp7pNHj0ZWLo106urqktcdeAFWme+/klis5fu 2126 labCSVPuT/QpwakPrtqOhRms8vgpKiXa/eLtL9ZiA28X/Mker0zlAeTA7Z7uAnp6 2127 oPJTlZu1Gg1ZDJueTWWsLlO+P+Wzm3MRRIbcgdRzm4mdO7ubu26SzX/aQXDhuih+ 2128 eVxXDTCfs7GUlxnjOp5j559X/N0A 2129 -----END CERTIFICATE----- 2130 ` 2131 2132 func TestMultipleURLsInCRLDP(t *testing.T) { 2133 block, _ := pem.Decode([]byte(multipleURLsInCRLDPPEM)) 2134 cert, err := ParseCertificate(block.Bytes) 2135 if err != nil { 2136 t.Fatalf("failed to parse certificate: %s", err) 2137 } 2138 2139 want := []string{ 2140 "http://epscd.catcert.net/crl/ec-acc.crl", 2141 "http://epscd2.catcert.net/crl/ec-acc.crl", 2142 } 2143 if got := cert.CRLDistributionPoints; !reflect.DeepEqual(got, want) { 2144 t.Errorf("CRL distribution points = %#v, want #%v", got, want) 2145 } 2146 } 2147 2148 const hexPKCS1TestPKCS8Key = "30820278020100300d06092a864886f70d0101010500048202623082025e02010002818100cfb1b5bf9685ffa97b4f99df4ff122b70e59ac9b992f3bc2b3dde17d53c1a34928719b02e8fd17839499bfbd515bd6ef99c7a1c47a239718fe36bfd824c0d96060084b5f67f0273443007a24dfaf5634f7772c9346e10eb294c2306671a5a5e719ae24b4de467291bc571014b0e02dec04534d66a9bb171d644b66b091780e8d020301000102818100b595778383c4afdbab95d2bfed12b3f93bb0a73a7ad952f44d7185fd9ec6c34de8f03a48770f2009c8580bcd275e9632714e9a5e3f32f29dc55474b2329ff0ebc08b3ffcb35bc96e6516b483df80a4a59cceb71918cbabf91564e64a39d7e35dce21cb3031824fdbc845dba6458852ec16af5dddf51a8397a8797ae0337b1439024100ea0eb1b914158c70db39031dd8904d6f18f408c85fbbc592d7d20dee7986969efbda081fdf8bc40e1b1336d6b638110c836bfdc3f314560d2e49cd4fbde1e20b024100e32a4e793b574c9c4a94c8803db5152141e72d03de64e54ef2c8ed104988ca780cd11397bc359630d01b97ebd87067c5451ba777cf045ca23f5912f1031308c702406dfcdbbd5a57c9f85abc4edf9e9e29153507b07ce0a7ef6f52e60dcfebe1b8341babd8b789a837485da6c8d55b29bbb142ace3c24a1f5b54b454d01b51e2ad03024100bd6a2b60dee01e1b3bfcef6a2f09ed027c273cdbbaf6ba55a80f6dcc64e4509ee560f84b4f3e076bd03b11e42fe71a3fdd2dffe7e0902c8584f8cad877cdc945024100aa512fa4ada69881f1d8bb8ad6614f192b83200aef5edf4811313d5ef30a86cbd0a90f7b025c71ea06ec6b34db6306c86b1040670fd8654ad7291d066d06d031" 2149 const hexPKCS1TestECKey = "3081a40201010430bdb9839c08ee793d1157886a7a758a3c8b2a17a4df48f17ace57c72c56b4723cf21dcda21d4e1ad57ff034f19fcfd98ea00706052b81040022a16403620004feea808b5ee2429cfcce13c32160e1c960990bd050bb0fdf7222f3decd0a55008e32a6aa3c9062051c4cba92a7a3b178b24567412d43cdd2f882fa5addddd726fe3e208d2c26d733a773a597abb749714df7256ead5105fa6e7b3650de236b50" 2150 2151 var pkcs1MismatchKeyTests = []struct { 2152 hexKey string 2153 errorContains string 2154 }{ 2155 {hexKey: hexPKCS1TestPKCS8Key, errorContains: "use ParsePKCS8PrivateKey instead"}, 2156 {hexKey: hexPKCS1TestECKey, errorContains: "use ParseECPrivateKey instead"}, 2157 } 2158 2159 func TestPKCS1MismatchKeyFormat(t *testing.T) { 2160 for i, test := range pkcs1MismatchKeyTests { 2161 derBytes, _ := hex.DecodeString(test.hexKey) 2162 _, err := ParsePKCS1PrivateKey(derBytes) 2163 if !strings.Contains(err.Error(), test.errorContains) { 2164 t.Errorf("#%d: expected error containing %q, got %s", i, test.errorContains, err) 2165 } 2166 } 2167 }