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