github.com/d4l3k/go@v0.0.0-20151015000803-65fc379daeda/src/crypto/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 "crypto/ecdsa" 11 "crypto/elliptic" 12 "crypto/rand" 13 "crypto/rsa" 14 _ "crypto/sha256" 15 _ "crypto/sha512" 16 "crypto/x509/pkix" 17 "encoding/asn1" 18 "encoding/base64" 19 "encoding/hex" 20 "encoding/pem" 21 "internal/testenv" 22 "math/big" 23 "net" 24 "os/exec" 25 "reflect" 26 "testing" 27 "time" 28 ) 29 30 func TestParsePKCS1PrivateKey(t *testing.T) { 31 block, _ := pem.Decode([]byte(pemPrivateKey)) 32 priv, err := ParsePKCS1PrivateKey(block.Bytes) 33 if err != nil { 34 t.Errorf("Failed to parse private key: %s", err) 35 return 36 } 37 if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 || 38 priv.PublicKey.E != rsaPrivateKey.PublicKey.E || 39 priv.D.Cmp(rsaPrivateKey.D) != 0 || 40 priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 || 41 priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 { 42 t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey) 43 } 44 45 // This private key includes an invalid prime that 46 // rsa.PrivateKey.Validate should reject. 47 data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00") 48 if _, err := ParsePKCS1PrivateKey(data); err == nil { 49 t.Errorf("parsing invalid private key did not result in an error") 50 } 51 } 52 53 func TestParsePKIXPublicKey(t *testing.T) { 54 block, _ := pem.Decode([]byte(pemPublicKey)) 55 pub, err := ParsePKIXPublicKey(block.Bytes) 56 if err != nil { 57 t.Errorf("Failed to parse RSA public key: %s", err) 58 return 59 } 60 rsaPub, ok := pub.(*rsa.PublicKey) 61 if !ok { 62 t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key") 63 return 64 } 65 66 pubBytes2, err := MarshalPKIXPublicKey(rsaPub) 67 if err != nil { 68 t.Errorf("Failed to marshal RSA public key for the second time: %s", err) 69 return 70 } 71 if !bytes.Equal(pubBytes2, block.Bytes) { 72 t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes) 73 } 74 } 75 76 var pemPublicKey = `-----BEGIN PUBLIC KEY----- 77 MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+ 78 wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k 79 enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ 80 FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg 81 fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR 82 FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ 83 +QIDAQAB 84 -----END PUBLIC KEY----- 85 ` 86 87 var pemPrivateKey = `-----BEGIN RSA PRIVATE KEY----- 88 MIIBOgIBAAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0 89 fd7Ai2KW5ToIwzFofvJcS/STa6HA5gQenRUCAwEAAQJBAIq9amn00aS0h/CrjXqu 90 /ThglAXJmZhOMPVn4eiu7/ROixi9sex436MaVeMqSNf7Ex9a8fRNfWss7Sqd9eWu 91 RTUCIQDasvGASLqmjeffBNLTXV2A5g4t+kLVCpsEIZAycV5GswIhANEPLmax0ME/ 92 EO+ZJ79TJKN5yiGBRsv5yvx5UiHxajEXAiAhAol5N4EUyq6I9w1rYdhPMGpLfk7A 93 IU2snfRJ6Nq2CQIgFrPsWRCkV+gOYcajD17rEqmuLrdIRexpg8N1DOSXoJ8CIGlS 94 tAboUGBxTDq3ZroNism3DaMIbKPyYrAqhKov1h5V 95 -----END RSA PRIVATE KEY----- 96 ` 97 98 func bigFromString(s string) *big.Int { 99 ret := new(big.Int) 100 ret.SetString(s, 10) 101 return ret 102 } 103 104 func fromBase10(base10 string) *big.Int { 105 i := new(big.Int) 106 i.SetString(base10, 10) 107 return i 108 } 109 110 func bigFromHexString(s string) *big.Int { 111 ret := new(big.Int) 112 ret.SetString(s, 16) 113 return ret 114 } 115 116 var rsaPrivateKey = &rsa.PrivateKey{ 117 PublicKey: rsa.PublicKey{ 118 N: bigFromString("9353930466774385905609975137998169297361893554149986716853295022578535724979677252958524466350471210367835187480748268864277464700638583474144061408845077"), 119 E: 65537, 120 }, 121 D: bigFromString("7266398431328116344057699379749222532279343923819063639497049039389899328538543087657733766554155839834519529439851673014800261285757759040931985506583861"), 122 Primes: []*big.Int{ 123 bigFromString("98920366548084643601728869055592650835572950932266967461790948584315647051443"), 124 bigFromString("94560208308847015747498523884063394671606671904944666360068158221458669711639"), 125 }, 126 } 127 128 func TestMarshalRSAPrivateKey(t *testing.T) { 129 priv := &rsa.PrivateKey{ 130 PublicKey: rsa.PublicKey{ 131 N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"), 132 E: 3, 133 }, 134 D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"), 135 Primes: []*big.Int{ 136 fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"), 137 fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"), 138 fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"), 139 }, 140 } 141 142 derBytes := MarshalPKCS1PrivateKey(priv) 143 144 priv2, err := ParsePKCS1PrivateKey(derBytes) 145 if err != nil { 146 t.Errorf("error parsing serialized key: %s", err) 147 return 148 } 149 if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 || 150 priv.PublicKey.E != priv2.PublicKey.E || 151 priv.D.Cmp(priv2.D) != 0 || 152 len(priv2.Primes) != 3 || 153 priv.Primes[0].Cmp(priv2.Primes[0]) != 0 || 154 priv.Primes[1].Cmp(priv2.Primes[1]) != 0 || 155 priv.Primes[2].Cmp(priv2.Primes[2]) != 0 { 156 t.Errorf("got:%+v want:%+v", priv, priv2) 157 } 158 } 159 160 type matchHostnamesTest struct { 161 pattern, host string 162 ok bool 163 } 164 165 var matchHostnamesTests = []matchHostnamesTest{ 166 {"a.b.c", "a.b.c", true}, 167 {"a.b.c", "b.b.c", false}, 168 {"", "b.b.c", false}, 169 {"a.b.c", "", false}, 170 {"example.com", "example.com", true}, 171 {"example.com", "www.example.com", false}, 172 {"*.example.com", "example.com", false}, 173 {"*.example.com", "www.example.com", true}, 174 {"*.example.com", "www.example.com.", true}, 175 {"*.example.com", "xyz.www.example.com", false}, 176 {"*.*.example.com", "xyz.www.example.com", false}, 177 {"*.www.*.com", "xyz.www.example.com", false}, 178 {"*bar.example.com", "foobar.example.com", false}, 179 {"f*.example.com", "foobar.example.com", false}, 180 {"", ".", false}, 181 {".", "", false}, 182 {".", ".", false}, 183 {"example.com", "example.com.", true}, 184 {"example.com.", "example.com", true}, 185 {"example.com.", "example.com.", true}, 186 {"*.com.", "example.com.", true}, 187 {"*.com.", "example.com", true}, 188 {"*.com", "example.com", true}, 189 {"*.com", "example.com.", true}, 190 } 191 192 func TestMatchHostnames(t *testing.T) { 193 for i, test := range matchHostnamesTests { 194 r := matchHostnames(test.pattern, test.host) 195 if r != test.ok { 196 t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern) 197 } 198 } 199 } 200 201 func TestMatchIP(t *testing.T) { 202 // Check that pattern matching is working. 203 c := &Certificate{ 204 DNSNames: []string{"*.foo.bar.baz"}, 205 Subject: pkix.Name{ 206 CommonName: "*.foo.bar.baz", 207 }, 208 } 209 err := c.VerifyHostname("quux.foo.bar.baz") 210 if err != nil { 211 t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err) 212 } 213 214 // But check that if we change it to be matching against an IP address, 215 // it is rejected. 216 c = &Certificate{ 217 DNSNames: []string{"*.2.3.4"}, 218 Subject: pkix.Name{ 219 CommonName: "*.2.3.4", 220 }, 221 } 222 err = c.VerifyHostname("1.2.3.4") 223 if err == nil { 224 t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not") 225 } 226 227 c = &Certificate{ 228 IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")}, 229 } 230 err = c.VerifyHostname("127.0.0.1") 231 if err != nil { 232 t.Fatalf("VerifyHostname(127.0.0.1): %v", err) 233 } 234 err = c.VerifyHostname("::1") 235 if err != nil { 236 t.Fatalf("VerifyHostname(::1): %v", err) 237 } 238 err = c.VerifyHostname("[::1]") 239 if err != nil { 240 t.Fatalf("VerifyHostname([::1]): %v", err) 241 } 242 } 243 244 func TestCertificateParse(t *testing.T) { 245 s, _ := hex.DecodeString(certBytes) 246 certs, err := ParseCertificates(s) 247 if err != nil { 248 t.Error(err) 249 } 250 if len(certs) != 2 { 251 t.Errorf("Wrong number of certs: got %d want 2", len(certs)) 252 return 253 } 254 255 err = certs[0].CheckSignatureFrom(certs[1]) 256 if err != nil { 257 t.Error(err) 258 } 259 260 if err := certs[0].VerifyHostname("mail.google.com"); err != nil { 261 t.Error(err) 262 } 263 264 const expectedExtensions = 4 265 if n := len(certs[0].Extensions); n != expectedExtensions { 266 t.Errorf("want %d extensions, got %d", expectedExtensions, n) 267 } 268 } 269 270 var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" + 271 "f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" + 272 "20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" + 273 "20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" + 274 "3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" + 275 "140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" + 276 "496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" + 277 "86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" + 278 "41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" + 279 "3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" + 280 "03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" + 281 "81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" + 282 "86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" + 283 "74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" + 284 "2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" + 285 "2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" + 286 "6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" + 287 "2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" + 288 "9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" + 289 "70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" + 290 "a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" + 291 "020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" + 292 "15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" + 293 "33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" + 294 "79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" + 295 "060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" + 296 "50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" + 297 "092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" + 298 "0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" + 299 "2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" + 300 "21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" + 301 "a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" + 302 "301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" + 303 "035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" + 304 "8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" + 305 "0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" + 306 "617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" + 307 "06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" + 308 "81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" + 309 "e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" + 310 "9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" + 311 "36dcd585d6ace53f546f961e05af" 312 313 func TestCreateSelfSignedCertificate(t *testing.T) { 314 random := rand.Reader 315 316 block, _ := pem.Decode([]byte(pemPrivateKey)) 317 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 318 if err != nil { 319 t.Fatalf("Failed to parse private key: %s", err) 320 } 321 322 ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 323 if err != nil { 324 t.Fatalf("Failed to generate ECDSA key: %s", err) 325 } 326 327 tests := []struct { 328 name string 329 pub, priv interface{} 330 checkSig bool 331 sigAlgo SignatureAlgorithm 332 }{ 333 {"RSA/RSA", &rsaPriv.PublicKey, rsaPriv, true, SHA1WithRSA}, 334 {"RSA/ECDSA", &rsaPriv.PublicKey, ecdsaPriv, false, ECDSAWithSHA384}, 335 {"ECDSA/RSA", &ecdsaPriv.PublicKey, rsaPriv, false, SHA256WithRSA}, 336 {"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1}, 337 } 338 339 testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth} 340 testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} 341 extraExtensionData := []byte("extra extension") 342 343 for _, test := range tests { 344 commonName := "test.example.com" 345 template := Certificate{ 346 SerialNumber: big.NewInt(1), 347 Subject: pkix.Name{ 348 CommonName: commonName, 349 Organization: []string{"Σ Acme Co"}, 350 Country: []string{"US"}, 351 ExtraNames: []pkix.AttributeTypeAndValue{ 352 { 353 Type: []int{2, 5, 4, 42}, 354 Value: "Gopher", 355 }, 356 // This should override the Country, above. 357 { 358 Type: []int{2, 5, 4, 6}, 359 Value: "NL", 360 }, 361 }, 362 }, 363 NotBefore: time.Unix(1000, 0), 364 NotAfter: time.Unix(100000, 0), 365 366 SignatureAlgorithm: test.sigAlgo, 367 368 SubjectKeyId: []byte{1, 2, 3, 4}, 369 KeyUsage: KeyUsageCertSign, 370 371 ExtKeyUsage: testExtKeyUsage, 372 UnknownExtKeyUsage: testUnknownExtKeyUsage, 373 374 BasicConstraintsValid: true, 375 IsCA: true, 376 377 OCSPServer: []string{"http://ocsp.example.com"}, 378 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, 379 380 DNSNames: []string{"test.example.com"}, 381 EmailAddresses: []string{"gopher@golang.org"}, 382 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 383 384 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}}, 385 PermittedDNSDomains: []string{".example.com", "example.com"}, 386 387 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, 388 389 ExtraExtensions: []pkix.Extension{ 390 { 391 Id: []int{1, 2, 3, 4}, 392 Value: extraExtensionData, 393 }, 394 // This extension should override the SubjectKeyId, above. 395 { 396 Id: oidExtensionSubjectKeyId, 397 Critical: false, 398 Value: []byte{0x04, 0x04, 4, 3, 2, 1}, 399 }, 400 }, 401 } 402 403 derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv) 404 if err != nil { 405 t.Errorf("%s: failed to create certificate: %s", test.name, err) 406 continue 407 } 408 409 cert, err := ParseCertificate(derBytes) 410 if err != nil { 411 t.Errorf("%s: failed to parse certificate: %s", test.name, err) 412 continue 413 } 414 415 if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) { 416 t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers) 417 } 418 419 if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" { 420 t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains) 421 } 422 423 if cert.Subject.CommonName != commonName { 424 t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName) 425 } 426 427 if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" { 428 t.Errorf("%s: ExtraNames didn't override Country", test.name) 429 } 430 431 found := false 432 for _, atv := range cert.Subject.Names { 433 if atv.Type.Equal([]int{2, 5, 4, 42}) { 434 found = true 435 break 436 } 437 } 438 if !found { 439 t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name) 440 } 441 442 if cert.Issuer.CommonName != commonName { 443 t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName) 444 } 445 446 if cert.SignatureAlgorithm != test.sigAlgo { 447 t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo) 448 } 449 450 if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) { 451 t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage) 452 } 453 454 if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) { 455 t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) 456 } 457 458 if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) { 459 t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer) 460 } 461 462 if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) { 463 t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL) 464 } 465 466 if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) { 467 t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames) 468 } 469 470 if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) { 471 t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses) 472 } 473 474 if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) { 475 t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses) 476 } 477 478 if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) { 479 t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints) 480 } 481 482 if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) { 483 t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name) 484 } 485 486 if bytes.Index(derBytes, extraExtensionData) == -1 { 487 t.Errorf("%s: didn't find extra extension in DER output", test.name) 488 } 489 490 if test.checkSig { 491 err = cert.CheckSignatureFrom(cert) 492 if err != nil { 493 t.Errorf("%s: signature verification failed: %s", test.name, err) 494 } 495 } 496 } 497 } 498 499 func TestUnknownCriticalExtension(t *testing.T) { 500 priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 501 if err != nil { 502 t.Fatalf("Failed to generate ECDSA key: %s", err) 503 } 504 505 oids := []asn1.ObjectIdentifier{ 506 // This OID is in the PKIX arc, but unknown. 507 {2, 5, 29, 999999}, 508 // This is a nonsense, unassigned OID. 509 {1, 2, 3, 4}, 510 } 511 512 for _, oid := range oids { 513 template := Certificate{ 514 SerialNumber: big.NewInt(1), 515 Subject: pkix.Name{ 516 CommonName: "foo", 517 }, 518 NotBefore: time.Unix(1000, 0), 519 NotAfter: time.Now().AddDate(1, 0, 0), 520 521 BasicConstraintsValid: true, 522 IsCA: true, 523 524 KeyUsage: KeyUsageCertSign, 525 ExtKeyUsage: []ExtKeyUsage{ExtKeyUsageServerAuth}, 526 527 ExtraExtensions: []pkix.Extension{ 528 { 529 Id: oid, 530 Critical: true, 531 Value: nil, 532 }, 533 }, 534 } 535 536 derBytes, err := CreateCertificate(rand.Reader, &template, &template, &priv.PublicKey, priv) 537 if err != nil { 538 t.Fatalf("failed to create certificate: %s", err) 539 } 540 541 cert, err := ParseCertificate(derBytes) 542 if err != nil { 543 t.Fatalf("Certificate with unknown critical extension was not parsed: %s", err) 544 } 545 546 roots := NewCertPool() 547 roots.AddCert(cert) 548 549 // Setting Roots ensures that Verify won't delegate to the OS 550 // library and thus the correct error should always be 551 // returned. 552 _, err = cert.Verify(VerifyOptions{Roots: roots}) 553 if err == nil { 554 t.Fatal("Certificate with unknown critical extension was verified without error") 555 } 556 if _, ok := err.(UnhandledCriticalExtension); !ok { 557 t.Fatalf("Error was %#v, but wanted one of type UnhandledCriticalExtension", err) 558 } 559 560 cert.UnhandledCriticalExtensions = nil 561 if _, err = cert.Verify(VerifyOptions{Roots: roots}); err != nil { 562 t.Errorf("Certificate failed to verify after unhandled critical extensions were cleared: %s", err) 563 } 564 } 565 } 566 567 // Self-signed certificate using ECDSA with SHA1 & secp256r1 568 var ecdsaSHA1CertPem = ` 569 -----BEGIN CERTIFICATE----- 570 MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET 571 MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG 572 A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 573 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw 574 WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 575 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg 576 SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv 577 bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn 578 WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3 579 P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2 580 DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV 581 a/A= 582 -----END CERTIFICATE----- 583 ` 584 585 // Self-signed certificate using ECDSA with SHA256 & secp256r1 586 var ecdsaSHA256p256CertPem = ` 587 -----BEGIN CERTIFICATE----- 588 MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx 589 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT 590 BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh 591 BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx 592 NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp 593 Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs 594 IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn 595 b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt 596 2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm 597 YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV 598 70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ 599 h5wi 600 -----END CERTIFICATE----- 601 ` 602 603 // Self-signed certificate using ECDSA with SHA256 & secp384r1 604 var ecdsaSHA256p384CertPem = ` 605 -----BEGIN CERTIFICATE----- 606 MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx 607 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 608 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 609 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0 610 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 611 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 612 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 613 YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK 614 jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze 615 qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI 616 zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr 617 PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh 618 3yILeYQzllt/g0rKVRk= 619 -----END CERTIFICATE----- 620 ` 621 622 // Self-signed certificate using ECDSA with SHA384 & secp521r1 623 var ecdsaSHA384p521CertPem = ` 624 -----BEGIN CERTIFICATE----- 625 MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx 626 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 627 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 628 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5 629 WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 630 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 631 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 632 YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv 633 IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz 634 PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm 635 8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw 636 gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH 637 BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh 638 kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa 639 -----END CERTIFICATE----- 640 ` 641 642 var ecdsaTests = []struct { 643 sigAlgo SignatureAlgorithm 644 pemCert string 645 }{ 646 {ECDSAWithSHA1, ecdsaSHA1CertPem}, 647 {ECDSAWithSHA256, ecdsaSHA256p256CertPem}, 648 {ECDSAWithSHA256, ecdsaSHA256p384CertPem}, 649 {ECDSAWithSHA384, ecdsaSHA384p521CertPem}, 650 } 651 652 func TestECDSA(t *testing.T) { 653 for i, test := range ecdsaTests { 654 pemBlock, _ := pem.Decode([]byte(test.pemCert)) 655 cert, err := ParseCertificate(pemBlock.Bytes) 656 if err != nil { 657 t.Errorf("%d: failed to parse certificate: %s", i, err) 658 continue 659 } 660 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { 661 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) 662 } 663 if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok { 664 t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey) 665 } 666 if pka := cert.PublicKeyAlgorithm; pka != ECDSA { 667 t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka) 668 } 669 if err = cert.CheckSignatureFrom(cert); err != nil { 670 t.Errorf("%d: certificate verification failed: %s", i, err) 671 } 672 } 673 } 674 675 // Self-signed certificate using DSA with SHA1 676 var dsaCertPem = `-----BEGIN CERTIFICATE----- 677 MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC 678 VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds 679 ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs 680 bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5 681 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG 682 A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbi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M 699 -----END CERTIFICATE----- 700 ` 701 702 func TestParseCertificateWithDsaPublicKey(t *testing.T) { 703 expectedKey := &dsa.PublicKey{ 704 Parameters: dsa.Parameters{ 705 P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"), 706 Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"), 707 G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"), 708 }, 709 Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"), 710 } 711 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 712 cert, err := ParseCertificate(pemBlock.Bytes) 713 if err != nil { 714 t.Fatalf("Failed to parse certificate: %s", err) 715 } 716 if cert.PublicKeyAlgorithm != DSA { 717 t.Errorf("Parsed key algorithm was not DSA") 718 } 719 parsedKey, ok := cert.PublicKey.(*dsa.PublicKey) 720 if !ok { 721 t.Fatalf("Parsed key was not a DSA key: %s", err) 722 } 723 if expectedKey.Y.Cmp(parsedKey.Y) != 0 || 724 expectedKey.P.Cmp(parsedKey.P) != 0 || 725 expectedKey.Q.Cmp(parsedKey.Q) != 0 || 726 expectedKey.G.Cmp(parsedKey.G) != 0 { 727 t.Fatal("Parsed key differs from expected key") 728 } 729 } 730 731 func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) { 732 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 733 cert, err := ParseCertificate(pemBlock.Bytes) 734 if err != nil { 735 t.Fatalf("Failed to parse certificate: %s", err) 736 } 737 if cert.SignatureAlgorithm != DSAWithSHA1 { 738 t.Errorf("Parsed signature algorithm was not DSAWithSHA1") 739 } 740 } 741 742 func TestVerifyCertificateWithDSASignature(t *testing.T) { 743 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 744 cert, err := ParseCertificate(pemBlock.Bytes) 745 if err != nil { 746 t.Fatalf("Failed to parse certificate: %s", err) 747 } 748 // test cert is self-signed 749 if err = cert.CheckSignatureFrom(cert); err != nil { 750 t.Fatalf("DSA Certificate verification failed: %s", err) 751 } 752 } 753 754 const pemCertificate = `-----BEGIN CERTIFICATE----- 755 MIIB5DCCAZCgAwIBAgIBATALBgkqhkiG9w0BAQUwLTEQMA4GA1UEChMHQWNtZSBDbzEZMBcGA1UE 756 AxMQdGVzdC5leGFtcGxlLmNvbTAeFw03MDAxMDEwMDE2NDBaFw03MDAxMDIwMzQ2NDBaMC0xEDAO 757 BgNVBAoTB0FjbWUgQ28xGTAXBgNVBAMTEHRlc3QuZXhhbXBsZS5jb20wWjALBgkqhkiG9w0BAQED 758 SwAwSAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0fd7Ai2KW5ToIwzFo 759 fvJcS/STa6HA5gQenRUCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAAQwDwYDVR0TAQH/BAUwAwEB 760 /zANBgNVHQ4EBgQEAQIDBDAPBgNVHSMECDAGgAQBAgMEMBsGA1UdEQQUMBKCEHRlc3QuZXhhbXBs 761 ZS5jb20wDwYDVR0gBAgwBjAEBgIqAzAqBgNVHR4EIzAhoB8wDoIMLmV4YW1wbGUuY29tMA2CC2V4 762 YW1wbGUuY29tMAsGCSqGSIb3DQEBBQNBAHKZKoS1wEQOGhgklx4+/yFYQlnqwKXvar/ZecQvJwui 763 0seMQnwBhwdBkHfVIU2Fu5VUMRyxlf0ZNaDXcpU581k= 764 -----END CERTIFICATE-----` 765 766 func TestCRLCreation(t *testing.T) { 767 block, _ := pem.Decode([]byte(pemPrivateKey)) 768 priv, _ := ParsePKCS1PrivateKey(block.Bytes) 769 block, _ = pem.Decode([]byte(pemCertificate)) 770 cert, _ := ParseCertificate(block.Bytes) 771 772 now := time.Unix(1000, 0) 773 expiry := time.Unix(10000, 0) 774 775 revokedCerts := []pkix.RevokedCertificate{ 776 { 777 SerialNumber: big.NewInt(1), 778 RevocationTime: now, 779 }, 780 { 781 SerialNumber: big.NewInt(42), 782 RevocationTime: now, 783 }, 784 } 785 786 crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry) 787 if err != nil { 788 t.Errorf("error creating CRL: %s", err) 789 } 790 791 _, err = ParseDERCRL(crlBytes) 792 if err != nil { 793 t.Errorf("error reparsing CRL: %s", err) 794 } 795 } 796 797 func fromBase64(in string) []byte { 798 out := make([]byte, base64.StdEncoding.DecodedLen(len(in))) 799 n, err := base64.StdEncoding.Decode(out, []byte(in)) 800 if err != nil { 801 panic("failed to base64 decode") 802 } 803 return out[:n] 804 } 805 806 func TestParseDERCRL(t *testing.T) { 807 derBytes := fromBase64(derCRLBase64) 808 certList, err := ParseDERCRL(derBytes) 809 if err != nil { 810 t.Errorf("error parsing: %s", err) 811 return 812 } 813 numCerts := len(certList.TBSCertList.RevokedCertificates) 814 expected := 88 815 if numCerts != expected { 816 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 817 } 818 819 if certList.HasExpired(time.Unix(1302517272, 0)) { 820 t.Errorf("CRL has expired (but shouldn't have)") 821 } 822 823 // Can't check the signature here without a package cycle. 824 } 825 826 func TestCRLWithoutExpiry(t *testing.T) { 827 derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh") 828 certList, err := ParseDERCRL(derBytes) 829 if err != nil { 830 t.Fatal(err) 831 } 832 if !certList.TBSCertList.NextUpdate.IsZero() { 833 t.Errorf("NextUpdate is not the zero value") 834 } 835 } 836 837 func TestParsePEMCRL(t *testing.T) { 838 pemBytes := fromBase64(pemCRLBase64) 839 certList, err := ParseCRL(pemBytes) 840 if err != nil { 841 t.Errorf("error parsing: %s", err) 842 return 843 } 844 numCerts := len(certList.TBSCertList.RevokedCertificates) 845 expected := 2 846 if numCerts != expected { 847 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 848 } 849 850 if certList.HasExpired(time.Unix(1302517272, 0)) { 851 t.Errorf("CRL has expired (but shouldn't have)") 852 } 853 854 // Can't check the signature here without a package cycle. 855 } 856 857 func TestImports(t *testing.T) { 858 testenv.MustHaveGoRun(t) 859 860 if err := exec.Command("go", "run", "x509_test_import.go").Run(); err != nil { 861 t.Errorf("failed to run x509_test_import.go: %s", err) 862 } 863 } 864 865 const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0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h0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K" 868 869 func TestCreateCertificateRequest(t *testing.T) { 870 random := rand.Reader 871 872 block, _ := pem.Decode([]byte(pemPrivateKey)) 873 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 874 if err != nil { 875 t.Fatalf("Failed to parse private key: %s", err) 876 } 877 878 ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 879 if err != nil { 880 t.Fatalf("Failed to generate ECDSA key: %s", err) 881 } 882 883 ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 884 if err != nil { 885 t.Fatalf("Failed to generate ECDSA key: %s", err) 886 } 887 888 ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) 889 if err != nil { 890 t.Fatalf("Failed to generate ECDSA key: %s", err) 891 } 892 893 tests := []struct { 894 name string 895 priv interface{} 896 sigAlgo SignatureAlgorithm 897 }{ 898 {"RSA", rsaPriv, SHA1WithRSA}, 899 {"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1}, 900 {"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1}, 901 {"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1}, 902 } 903 904 for _, test := range tests { 905 template := CertificateRequest{ 906 Subject: pkix.Name{ 907 CommonName: "test.example.com", 908 Organization: []string{"Σ Acme Co"}, 909 }, 910 SignatureAlgorithm: test.sigAlgo, 911 DNSNames: []string{"test.example.com"}, 912 EmailAddresses: []string{"gopher@golang.org"}, 913 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 914 } 915 916 derBytes, err := CreateCertificateRequest(random, &template, test.priv) 917 if err != nil { 918 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 919 continue 920 } 921 922 out, err := ParseCertificateRequest(derBytes) 923 if err != nil { 924 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 925 continue 926 } 927 928 err = out.CheckSignature() 929 if err != nil { 930 t.Errorf("%s: failed to check certificate request signature: %s", test.name, err) 931 continue 932 } 933 934 if out.Subject.CommonName != template.Subject.CommonName { 935 t.Errorf("%s: output subject common name and template subject common name don't match", test.name) 936 } else if len(out.Subject.Organization) != len(template.Subject.Organization) { 937 t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name) 938 } else if len(out.DNSNames) != len(template.DNSNames) { 939 t.Errorf("%s: output DNS names and template DNS names don't match", test.name) 940 } else if len(out.EmailAddresses) != len(template.EmailAddresses) { 941 t.Errorf("%s: output email addresses and template email addresses don't match", test.name) 942 } else if len(out.IPAddresses) != len(template.IPAddresses) { 943 t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name) 944 } 945 } 946 } 947 948 func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest { 949 block, _ := pem.Decode([]byte(pemPrivateKey)) 950 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 951 if err != nil { 952 t.Fatal(err) 953 } 954 955 derBytes, err := CreateCertificateRequest(rand.Reader, template, rsaPriv) 956 if err != nil { 957 t.Fatal(err) 958 } 959 960 csr, err := ParseCertificateRequest(derBytes) 961 if err != nil { 962 t.Fatal(err) 963 } 964 965 return csr 966 } 967 968 func TestCertificateRequestOverrides(t *testing.T) { 969 sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil) 970 if err != nil { 971 t.Fatal(err) 972 } 973 974 template := CertificateRequest{ 975 Subject: pkix.Name{ 976 CommonName: "test.example.com", 977 Organization: []string{"Σ Acme Co"}, 978 }, 979 DNSNames: []string{"test.example.com"}, 980 981 // An explicit extension should override the DNSNames from the 982 // template. 983 ExtraExtensions: []pkix.Extension{ 984 { 985 Id: oidExtensionSubjectAltName, 986 Value: sanContents, 987 }, 988 }, 989 } 990 991 csr := marshalAndParseCSR(t, &template) 992 993 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" { 994 t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames) 995 } 996 997 // If there is already an attribute with X.509 extensions then the 998 // extra extensions should be added to it rather than creating a CSR 999 // with two extension attributes. 1000 1001 template.Attributes = []pkix.AttributeTypeAndValueSET{ 1002 { 1003 Type: oidExtensionRequest, 1004 Value: [][]pkix.AttributeTypeAndValue{ 1005 { 1006 { 1007 Type: oidExtensionAuthorityInfoAccess, 1008 Value: []byte("foo"), 1009 }, 1010 }, 1011 }, 1012 }, 1013 } 1014 1015 csr = marshalAndParseCSR(t, &template) 1016 if l := len(csr.Attributes); l != 1 { 1017 t.Errorf("incorrect number of attributes: %d\n", l) 1018 } 1019 1020 if !csr.Attributes[0].Type.Equal(oidExtensionRequest) || 1021 len(csr.Attributes[0].Value) != 1 || 1022 len(csr.Attributes[0].Value[0]) != 2 { 1023 t.Errorf("bad attributes: %#v\n", csr.Attributes) 1024 } 1025 1026 sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil) 1027 if err != nil { 1028 t.Fatal(err) 1029 } 1030 1031 // Extensions in Attributes should override those in ExtraExtensions. 1032 template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{ 1033 Type: oidExtensionSubjectAltName, 1034 Value: sanContents2, 1035 }) 1036 1037 csr = marshalAndParseCSR(t, &template) 1038 1039 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" { 1040 t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames) 1041 } 1042 } 1043 1044 func TestParseCertificateRequest(t *testing.T) { 1045 for _, csrBase64 := range csrBase64Array { 1046 csrBytes := fromBase64(csrBase64) 1047 csr, err := ParseCertificateRequest(csrBytes) 1048 if err != nil { 1049 t.Fatalf("failed to parse CSR: %s", err) 1050 } 1051 1052 if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" { 1053 t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses) 1054 } 1055 1056 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" { 1057 t.Errorf("incorrect DNS names found: %v", csr.DNSNames) 1058 } 1059 1060 if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" { 1061 t.Errorf("incorrect Subject name: %v", csr.Subject) 1062 } 1063 1064 found := false 1065 for _, e := range csr.Extensions { 1066 if e.Id.Equal(oidExtensionBasicConstraints) { 1067 found = true 1068 break 1069 } 1070 } 1071 if !found { 1072 t.Errorf("basic constraints extension not found in CSR") 1073 } 1074 } 1075 } 1076 1077 func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) { 1078 // This CSR contains an extension request where the extensions have a 1079 // critical flag in them. In the past we failed to handle this. 1080 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=" 1081 1082 csrBytes := fromBase64(csrBase64) 1083 csr, err := ParseCertificateRequest(csrBytes) 1084 if err != nil { 1085 t.Fatalf("failed to parse CSR: %s", err) 1086 } 1087 1088 expected := []struct{ 1089 Id asn1.ObjectIdentifier 1090 Value []byte 1091 }{ 1092 {oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")}, 1093 {oidExtensionKeyUsage, fromBase64("AwIChA==")}, 1094 } 1095 1096 if n := len(csr.Extensions); n != len(expected) { 1097 t.Fatalf("expected to find %d extensions but found %d", len(expected), n) 1098 } 1099 1100 for i, extension := range csr.Extensions { 1101 if !extension.Id.Equal(expected[i].Id) { 1102 t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id) 1103 } 1104 1105 if !bytes.Equal(extension.Value, expected[i].Value) { 1106 t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value) 1107 } 1108 } 1109 } 1110 1111 func TestMaxPathLen(t *testing.T) { 1112 block, _ := pem.Decode([]byte(pemPrivateKey)) 1113 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 1114 if err != nil { 1115 t.Fatalf("Failed to parse private key: %s", err) 1116 } 1117 1118 template := &Certificate{ 1119 SerialNumber: big.NewInt(1), 1120 Subject: pkix.Name{ 1121 CommonName: "Σ Acme Co", 1122 }, 1123 NotBefore: time.Unix(1000, 0), 1124 NotAfter: time.Unix(100000, 0), 1125 1126 BasicConstraintsValid: true, 1127 IsCA: true, 1128 } 1129 1130 serialiseAndParse := func(template *Certificate) *Certificate { 1131 derBytes, err := CreateCertificate(rand.Reader, template, template, &rsaPriv.PublicKey, rsaPriv) 1132 if err != nil { 1133 t.Fatalf("failed to create certificate: %s", err) 1134 return nil 1135 } 1136 1137 cert, err := ParseCertificate(derBytes) 1138 if err != nil { 1139 t.Fatalf("failed to parse certificate: %s", err) 1140 return nil 1141 } 1142 1143 return cert 1144 } 1145 1146 cert1 := serialiseAndParse(template) 1147 if m := cert1.MaxPathLen; m != -1 { 1148 t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m) 1149 } 1150 if cert1.MaxPathLenZero { 1151 t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero") 1152 } 1153 1154 template.MaxPathLen = 1 1155 cert2 := serialiseAndParse(template) 1156 if m := cert2.MaxPathLen; m != 1 { 1157 t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m) 1158 } 1159 if cert2.MaxPathLenZero { 1160 t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero") 1161 } 1162 1163 template.MaxPathLen = 0 1164 template.MaxPathLenZero = true 1165 cert3 := serialiseAndParse(template) 1166 if m := cert3.MaxPathLen; m != 0 { 1167 t.Errorf("Setting MaxPathLenZero didn't work, got %d", m) 1168 } 1169 if !cert3.MaxPathLenZero { 1170 t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero") 1171 } 1172 } 1173 1174 func TestASN1BitLength(t *testing.T) { 1175 tests := []struct { 1176 bytes []byte 1177 bitLen int 1178 }{ 1179 {nil, 0}, 1180 {[]byte{0x00}, 0}, 1181 {[]byte{0x00, 0x00}, 0}, 1182 {[]byte{0xf0}, 4}, 1183 {[]byte{0x88}, 5}, 1184 {[]byte{0xff}, 8}, 1185 {[]byte{0xff, 0x80}, 9}, 1186 {[]byte{0xff, 0x81}, 16}, 1187 } 1188 1189 for i, test := range tests { 1190 if got := asn1BitLength(test.bytes); got != test.bitLen { 1191 t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen) 1192 } 1193 } 1194 } 1195 1196 func TestVerifyEmptyCertificate(t *testing.T) { 1197 if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed { 1198 t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed) 1199 } 1200 } 1201 1202 // These CSR was generated with OpenSSL: 1203 // openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf 1204 // 1205 // With openssl.cnf containing the following sections: 1206 // [ v3_req ] 1207 // basicConstraints = CA:FALSE 1208 // keyUsage = nonRepudiation, digitalSignature, keyEncipherment 1209 // subjectAltName = email:gopher@golang.org,DNS:test.example.com 1210 // [ req_attributes ] 1211 // challengePassword = ignored challenge 1212 // unstructuredName = ignored unstructured name 1213 var csrBase64Array = [...]string{ 1214 // Just [ v3_req ] 1215 "MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKM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