github.com/zmap/zcrypto@v0.0.0-20240512203510-0fef58d9a9db/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/ecdsa" 10 "crypto/elliptic" 11 "crypto/rand" 12 "crypto/rsa" 13 _ "crypto/sha256" 14 _ "crypto/sha512" 15 "encoding/base64" 16 "encoding/hex" 17 "encoding/pem" 18 "io" 19 "io/ioutil" 20 "math/big" 21 "net" 22 "os/exec" 23 "reflect" 24 "runtime" 25 "testing" 26 "time" 27 28 "github.com/stretchr/testify/assert" 29 "github.com/stretchr/testify/require" 30 "github.com/zmap/zcrypto/dsa" 31 "github.com/zmap/zcrypto/encoding/asn1" 32 "github.com/zmap/zcrypto/x509/pkix" 33 "golang.org/x/crypto/curve25519" 34 "golang.org/x/crypto/ed25519" 35 ) 36 37 func TestParsePKCS1PrivateKey(t *testing.T) { 38 block, _ := pem.Decode([]byte(pemPrivateKey)) 39 priv, err := ParsePKCS1PrivateKey(block.Bytes) 40 if err != nil { 41 t.Errorf("Failed to parse private key: %s", err) 42 return 43 } 44 if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 || 45 priv.PublicKey.E != rsaPrivateKey.PublicKey.E || 46 priv.D.Cmp(rsaPrivateKey.D) != 0 || 47 priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 || 48 priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 { 49 t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey) 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", "www.example.com", true}, 173 {"*.example.com", "xyz.www.example.com", false}, 174 {"*.*.example.com", "xyz.www.example.com", true}, 175 {"*.www.*.com", "xyz.www.example.com", true}, 176 } 177 178 func TestCertificateParse(t *testing.T) { 179 s, _ := hex.DecodeString(certBytes) 180 certs, err := ParseCertificates(s) 181 if err != nil { 182 t.Error(err) 183 } 184 if len(certs) != 2 { 185 t.Errorf("Wrong number of certs: got %d want 2", len(certs)) 186 return 187 } 188 189 err = certs[0].CheckSignatureFrom(certs[1]) 190 if err != nil { 191 t.Error(err) 192 } 193 194 const expectedExtensions = 4 195 if n := len(certs[0].Extensions); n != expectedExtensions { 196 t.Errorf("want %d extensions, got %d", expectedExtensions, n) 197 } 198 199 if extMap := certs[0].ExtensionsMap; extMap == nil { 200 t.Fatal("expected non-nil ExtensionsMap, got nil") 201 } else if len(extMap) != expectedExtensions { 202 t.Errorf("wanted %d extensions in ExtensionsMap, got %d", 203 expectedExtensions, len(extMap)) 204 } 205 206 expectedOIDs := []string{ 207 "2.5.29.31", 208 "1.3.6.1.5.5.7.1.1", 209 "2.5.29.19", 210 "2.5.29.37", 211 } 212 for _, expectedOID := range expectedOIDs { 213 if ext, present := certs[0].ExtensionsMap[expectedOID]; !present { 214 t.Errorf("expected oid %q missing in ExtensionsMap", expectedOID) 215 } else if ext.Id.String() != expectedOID { 216 t.Errorf("expected oid %q in ExtensionsMap to key "+ 217 "pkix.Extension with same oid, got %q", 218 expectedOID, ext.Id.String()) 219 } 220 } 221 } 222 223 var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" + 224 "f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" + 225 "20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" + 226 "20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" + 227 "3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" + 228 "140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" + 229 "496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" + 230 "86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" + 231 "41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" + 232 "3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" + 233 "03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" + 234 "81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" + 235 "86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" + 236 "74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" + 237 "2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" + 238 "2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" + 239 "6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" + 240 "2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" + 241 "9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" + 242 "70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" + 243 "a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" + 244 "020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" + 245 "15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" + 246 "33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" + 247 "79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" + 248 "060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" + 249 "50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" + 250 "092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" + 251 "0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" + 252 "2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" + 253 "21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" + 254 "a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" + 255 "301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" + 256 "035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" + 257 "8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" + 258 "0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" + 259 "617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" + 260 "06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" + 261 "81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" + 262 "e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" + 263 "9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" + 264 "36dcd585d6ace53f546f961e05af" 265 266 func TestCreateSelfSignedCertificate(t *testing.T) { 267 random := rand.Reader 268 269 block, _ := pem.Decode([]byte(pemPrivateKey)) 270 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 271 if err != nil { 272 t.Fatalf("Failed to parse private key: %s", err) 273 } 274 275 ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 276 if err != nil { 277 t.Fatalf("Failed to generate ECDSA key: %s", err) 278 } 279 280 byt := make([]byte, 0) 281 null := asn1.BitString{Bytes: byt, BitLength: 0} 282 283 ed25519Pub, ed25519Priv, err := ed25519.GenerateKey(nil) 284 if err != nil { 285 t.Fatalf("Failed to generate Ed25519 key: %s", err) 286 } 287 var pubkey, privkey [32]byte 288 if _, err := io.ReadFull(rand.Reader, privkey[:]); err != nil { 289 panic(err) 290 } 291 curve25519.ScalarBaseMult(&pubkey, &privkey) 292 x25519Pub := X25519PublicKey(pubkey[:]) 293 294 tests := []struct { 295 name string 296 pub, priv interface{} 297 checkSig bool 298 sigAlgo SignatureAlgorithm 299 selfSigned bool 300 }{ 301 {"RSA/RSA", &rsaPriv.PublicKey, rsaPriv, true, SHA1WithRSA, true}, 302 {"RSA/ECDSA", &rsaPriv.PublicKey, ecdsaPriv, false, ECDSAWithSHA384, false}, 303 {"ECDSA/RSA", &AugmentedECDSA{Pub: &ecdsaPriv.PublicKey, Raw: null}, rsaPriv, false, SHA256WithRSA, false}, 304 {"ECDSA/ECDSA", &AugmentedECDSA{Pub: &ecdsaPriv.PublicKey, Raw: null}, ecdsaPriv, true, ECDSAWithSHA1, true}, 305 {"Ed25519/Ed25519", ed25519Pub, ed25519Priv, true, Ed25519Sig, true}, 306 {"X25519/Ed25519", x25519Pub, ed25519Priv, false, Ed25519Sig, false}, 307 } 308 309 testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth} 310 testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}} 311 extraExtensionData := []byte("extra extension") 312 313 for _, test := range tests { 314 commonName := "test.example.com" 315 template := Certificate{ 316 SerialNumber: big.NewInt(1), 317 Subject: pkix.Name{ 318 CommonName: commonName, 319 Organization: []string{"Σ Acme Co"}, 320 }, 321 NotBefore: time.Unix(1000, 0), 322 NotAfter: time.Unix(100000, 0), 323 324 SignatureAlgorithm: test.sigAlgo, 325 326 SubjectKeyId: []byte{1, 2, 3, 4}, 327 KeyUsage: KeyUsageCertSign, 328 329 ExtKeyUsage: testExtKeyUsage, 330 UnknownExtKeyUsage: testUnknownExtKeyUsage, 331 332 BasicConstraintsValid: true, 333 IsCA: true, 334 335 OCSPServer: []string{"http://ocsp.example.com"}, 336 IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"}, 337 338 DNSNames: []string{"test.example.com"}, 339 EmailAddresses: []string{"gopher@golang.org"}, 340 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 341 342 PolicyIdentifiers: []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 23, 140, 1, 1}}, 343 PermittedDNSNames: []GeneralSubtreeString{{Data: ".example.com"}, {Data: "example.com"}}, 344 345 CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"}, 346 347 ExtraExtensions: []pkix.Extension{ 348 { 349 Id: []int{1, 2, 3, 4}, 350 Value: extraExtensionData, 351 }, 352 // This extension should override the SubjectKeyId, above. 353 { 354 Id: oidExtensionSubjectKeyId, 355 Critical: false, 356 Value: []byte{0x04, 0x04, 4, 3, 2, 1}, 357 }, 358 }, 359 } 360 361 derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv) 362 if err != nil { 363 t.Errorf("%s: failed to create certificate: %s", test.name, err) 364 continue 365 } 366 367 cert, err := ParseCertificate(derBytes) 368 if err != nil { 369 t.Errorf("%s: failed to parse certificate: %s", test.name, err) 370 continue 371 } 372 373 if len(cert.PolicyIdentifiers) != 2 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) { 374 t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers) 375 } 376 377 if len(cert.PermittedDNSNames) != 2 || cert.PermittedDNSNames[0].Data != ".example.com" || cert.PermittedDNSNames[1].Data != "example.com" { 378 t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSNames) 379 } 380 381 if cert.Subject.CommonName != commonName { 382 t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName) 383 } 384 385 if cert.Issuer.CommonName != commonName { 386 t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName) 387 } 388 389 if cert.SignatureAlgorithm != test.sigAlgo { 390 t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo) 391 } 392 393 if cert.SelfSigned != test.selfSigned { 394 t.Errorf("%s: SelfSigned was not set properly. Got %v, want %v", test.name, cert.SelfSigned, test.selfSigned) 395 } 396 397 if !cert.SelfSigned { 398 if cert.ValidationLevel != EV { 399 t.Errorf("%s: ValidationLevel was not set properly. Got %s, want %s", test.name, cert.ValidationLevel.String(), EV.String()) 400 } 401 } 402 403 if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) { 404 t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage) 405 } 406 407 if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) { 408 t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) 409 } 410 411 if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) { 412 t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer) 413 } 414 415 if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) { 416 t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL) 417 } 418 419 if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) { 420 t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames) 421 } 422 423 if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) { 424 t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses) 425 } 426 427 if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) { 428 t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses) 429 } 430 431 if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) { 432 t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints) 433 } 434 435 if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) { 436 t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name) 437 } 438 439 if bytes.Index(derBytes, extraExtensionData) == -1 { 440 t.Errorf("%s: didn't find extra extension in DER output", test.name) 441 } 442 443 if test.checkSig { 444 err = cert.CheckSignatureFrom(cert) 445 if err != nil { 446 t.Errorf("%s: signature verification failed: %s", test.name, err) 447 } 448 } 449 } 450 } 451 452 // Self-signed certificate using ECDSA with SHA1 & secp256r1 453 var ecdsaSHA1CertPem = ` 454 -----BEGIN CERTIFICATE----- 455 MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET 456 MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG 457 A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 458 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw 459 WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 460 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg 461 SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv 462 bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn 463 WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3 464 P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2 465 DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV 466 a/A= 467 -----END CERTIFICATE----- 468 ` 469 470 // Self-signed certificate using ECDSA with SHA256 & secp256r1 471 var ecdsaSHA256p256CertPem = ` 472 -----BEGIN CERTIFICATE----- 473 MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx 474 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT 475 BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh 476 BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx 477 NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp 478 Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs 479 IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn 480 b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt 481 2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm 482 YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV 483 70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ 484 h5wi 485 -----END CERTIFICATE----- 486 ` 487 488 // Self-signed certificate using ECDSA with SHA256 & secp384r1 489 var ecdsaSHA256p384CertPem = ` 490 -----BEGIN CERTIFICATE----- 491 MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx 492 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 493 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 494 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0 495 WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 496 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 497 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 498 YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK 499 jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze 500 qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI 501 zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr 502 PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh 503 3yILeYQzllt/g0rKVRk= 504 -----END CERTIFICATE----- 505 ` 506 507 // Self-signed certificate using ECDSA with SHA384 & secp521r1 508 var ecdsaSHA384p521CertPem = ` 509 -----BEGIN CERTIFICATE----- 510 MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx 511 EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS 512 BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG 513 CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5 514 WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm 515 b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg 516 SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s 517 YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv 518 IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz 519 PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm 520 8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw 521 gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH 522 BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh 523 kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa 524 -----END CERTIFICATE----- 525 ` 526 527 var ecdsaTests = []struct { 528 sigAlgo SignatureAlgorithm 529 pemCert string 530 }{ 531 {ECDSAWithSHA1, ecdsaSHA1CertPem}, 532 {ECDSAWithSHA256, ecdsaSHA256p256CertPem}, 533 {ECDSAWithSHA256, ecdsaSHA256p384CertPem}, 534 {ECDSAWithSHA384, ecdsaSHA384p521CertPem}, 535 } 536 537 func TestECDSA(t *testing.T) { 538 for i, test := range ecdsaTests { 539 pemBlock, _ := pem.Decode([]byte(test.pemCert)) 540 cert, err := ParseCertificate(pemBlock.Bytes) 541 if err != nil { 542 t.Errorf("%d: failed to parse certificate: %s", i, err) 543 continue 544 } 545 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { 546 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) 547 } 548 if parsedKey, ok := cert.PublicKey.(*AugmentedECDSA); !ok { 549 t.Errorf("%d: wanted an AugmentedECDSA public key but found: %#v", i, parsedKey) 550 } 551 // if parsedKey, ok := cert.PublicKey.Pub(*ecdsa.PublicKey); !ok { 552 // t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey) 553 // } 554 // if parsedKey, ok := cert.PublicKey.Raw(*asn.BitString); !ok { 555 // t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey) 556 // } 557 if pka := cert.PublicKeyAlgorithm; pka != ECDSA { 558 t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka) 559 } 560 if err = cert.CheckSignatureFrom(cert); err != nil { 561 t.Errorf("%d: certificate verification failed: %s", i, err) 562 } 563 } 564 } 565 566 var ed25519CertPem = `-----BEGIN CERTIFICATE----- 567 MIIBFTCByKADAgECAghNZYIhB/z9UjAFBgMrZXAwDzENMAsGA1UEAxMEcm9vdDAe 568 Fw0xNzAyMTIxOTQ5NDVaFw0xNzAyMTMxOTQ5NDVaMA8xDTALBgNVBAMTBHJvb3Qw 569 KjAFBgMrZXADIQB1mSjGpYU8nliw5Ah7Uq6pElOk/QofMn476Lr4CII0zKNCMEAw 570 DgYDVR0PAQH/BAQDAgKEMA8GA1UdEwEB/wQFMAMBAf8wHQYDVR0OBBYEFKeTKKir 571 Wabr+CP52M0stAf7KInwMAUGAytlcANBAFRwyNSg/F3Zfeqiptn99pbeQsoIApvb 572 zKfb2zXCmF6OdhUSWrtHFY0y5rsCo1ha7cQQttRjOGiuKSKkjkmzHAg= 573 -----END CERTIFICATE-----` 574 var x25519CertPem = `-----BEGIN CERTIFICATE----- 575 MIIBTDCB/6ADAgECAgh4YpoPXz8WTzAFBgMrZXAwDzENMAsGA1UEAxMEcm9vdDAe 576 Fw0xNzAyMTIxOTQ5NDVaFw0xNzAyMTMxOTQ5NDVaMBMxETAPBgNVBAMTCHRlc3Qu 577 Y29tMCowBQYDK2VuAyEAFKwi3LTY6apEQDNMrx2WagCHpGVFL7tIB/uTwzoyUiCj 578 dTBzMA4GA1UdDwEB/wQEAwIHgDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMB 579 Af8EAjAAMB0GA1UdDgQWBBQG9I1UYG2pAHSs6nYKQFo/YTAkpTAfBgNVHSMEGDAW 580 gBSnkyioq1mm6/gj+djNLLQH+yiJ8DAFBgMrZXADQQBbuoByEYlgzxTskoUtCwBo 581 dVaJPEZmR+AHGHAFcBTEISEK5sl6h9Z923i6xMwHTjWbYw3JYwqeuJUfm3qCncQL 582 -----END CERTIFICATE-----` 583 var ed25519Tests = []struct { 584 sigAlgo SignatureAlgorithm 585 pemCert string 586 signerCert string 587 }{ 588 {Ed25519Sig, ed25519CertPem, ed25519CertPem}, 589 } 590 591 func Test25519(t *testing.T) { 592 for i, test := range ed25519Tests { 593 pemBlock, _ := pem.Decode([]byte(test.pemCert)) 594 cert, err := ParseCertificate(pemBlock.Bytes) 595 if err != nil { 596 t.Errorf("%d: failed to parse certificate: %s", i, err) 597 continue 598 } 599 pemBlock, _ = pem.Decode([]byte(test.signerCert)) 600 signerCert, err := ParseCertificate(pemBlock.Bytes) 601 if err != nil { 602 t.Errorf("%d: failed to parse certificate: %s", i, err) 603 continue 604 } 605 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { 606 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) 607 } 608 if parsedKey, ok := cert.PublicKey.(ed25519.PublicKey); !ok { 609 t.Errorf("%d: wanted an Ed25519 public key but found: %#v", i, parsedKey) 610 } 611 if pka := cert.PublicKeyAlgorithm; pka != Ed25519 { 612 t.Errorf("%d: public key algorithm is %v, want Ed25519", i, pka) 613 } 614 if err = cert.CheckSignatureFrom(signerCert); err != nil { 615 t.Errorf("%d: certificate verification failed: %s", i, err) 616 } 617 } 618 } 619 620 var x25519Tests = []struct { 621 sigAlgo SignatureAlgorithm 622 pemCert string 623 signerCert string 624 }{ 625 {Ed25519Sig, x25519CertPem, ed25519CertPem}, 626 } 627 628 func TestX25519(t *testing.T) { 629 for i, test := range x25519Tests { 630 pemBlock, _ := pem.Decode([]byte(test.pemCert)) 631 cert, err := ParseCertificate(pemBlock.Bytes) 632 if err != nil { 633 t.Errorf("%d: failed to parse certificate: %s", i, err) 634 continue 635 } 636 pemBlock, _ = pem.Decode([]byte(test.signerCert)) 637 signerCert, err := ParseCertificate(pemBlock.Bytes) 638 if err != nil { 639 t.Errorf("%d: failed to parse certificate: %s", i, err) 640 continue 641 } 642 if sa := cert.SignatureAlgorithm; sa != test.sigAlgo { 643 t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo) 644 } 645 if parsedKey, ok := cert.PublicKey.(X25519PublicKey); !ok { 646 t.Errorf("%d: wanted an Ed25519 public key but found: %#v", i, parsedKey) 647 } 648 if pka := cert.PublicKeyAlgorithm; pka != X25519 { 649 t.Errorf("%d: public key algorithm is %v, want Ed25519", i, pka) 650 } 651 if err = cert.CheckSignatureFrom(signerCert); err != nil { 652 t.Errorf("%d: certificate verification failed: %s", i, err) 653 } 654 } 655 } 656 657 // Self-signed certificate using DSA with SHA1 658 var dsaCertPem = `-----BEGIN CERTIFICATE----- 659 MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC 660 VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds 661 ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs 662 bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5 663 MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG 664 A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3 665 DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB 666 gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN 667 8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW 668 jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5 669 Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC 670 X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz 671 kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE 672 AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5 673 LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c 674 bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud 675 DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11 676 ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w 677 DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK 678 b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx 679 z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI 680 7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM 681 -----END CERTIFICATE----- 682 ` 683 684 func TestParseCertificateWithDsaPublicKey(t *testing.T) { 685 expectedKey := &dsa.PublicKey{ 686 Parameters: dsa.Parameters{ 687 P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"), 688 Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"), 689 G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"), 690 }, 691 Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"), 692 } 693 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 694 cert, err := ParseCertificate(pemBlock.Bytes) 695 if err != nil { 696 t.Fatalf("Failed to parse certificate: %s", err) 697 } 698 if cert.PublicKeyAlgorithm != DSA { 699 t.Errorf("Parsed key algorithm was not DSA") 700 } 701 parsedKey, ok := cert.PublicKey.(*dsa.PublicKey) 702 if !ok { 703 t.Fatalf("Parsed key was not a DSA key: %s", err) 704 } 705 if expectedKey.Y.Cmp(parsedKey.Y) != 0 || 706 expectedKey.P.Cmp(parsedKey.P) != 0 || 707 expectedKey.Q.Cmp(parsedKey.Q) != 0 || 708 expectedKey.G.Cmp(parsedKey.G) != 0 { 709 t.Fatal("Parsed key differs from expected key") 710 } 711 } 712 713 func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) { 714 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 715 cert, err := ParseCertificate(pemBlock.Bytes) 716 if err != nil { 717 t.Fatalf("Failed to parse certificate: %s", err) 718 } 719 if cert.SignatureAlgorithm != DSAWithSHA1 { 720 t.Errorf("Parsed signature algorithm was not DSAWithSHA1") 721 } 722 } 723 724 func TestVerifyCertificateWithDSASignature(t *testing.T) { 725 pemBlock, _ := pem.Decode([]byte(dsaCertPem)) 726 cert, err := ParseCertificate(pemBlock.Bytes) 727 if err != nil { 728 t.Fatalf("Failed to parse certificate: %s", err) 729 } 730 // test cert is self-signed 731 if err = cert.CheckSignatureFrom(cert); err != nil { 732 t.Fatalf("DSA Certificate verification failed: %s", err) 733 } 734 } 735 736 const pemCertificate = `-----BEGIN CERTIFICATE----- 737 MIIB5DCCAZCgAwIBAgIBATALBgkqhkiG9w0BAQUwLTEQMA4GA1UEChMHQWNtZSBDbzEZMBcGA1UE 738 AxMQdGVzdC5leGFtcGxlLmNvbTAeFw03MDAxMDEwMDE2NDBaFw03MDAxMDIwMzQ2NDBaMC0xEDAO 739 BgNVBAoTB0FjbWUgQ28xGTAXBgNVBAMTEHRlc3QuZXhhbXBsZS5jb20wWjALBgkqhkiG9w0BAQED 740 SwAwSAJBALKZD0nEffqM1ACuak0bijtqE2QrI/KLADv7l3kK3ppMyCuLKoF0fd7Ai2KW5ToIwzFo 741 fvJcS/STa6HA5gQenRUCAwEAAaOBnjCBmzAOBgNVHQ8BAf8EBAMCAAQwDwYDVR0TAQH/BAUwAwEB 742 /zANBgNVHQ4EBgQEAQIDBDAPBgNVHSMECDAGgAQBAgMEMBsGA1UdEQQUMBKCEHRlc3QuZXhhbXBs 743 ZS5jb20wDwYDVR0gBAgwBjAEBgIqAzAqBgNVHR4EIzAhoB8wDoIMLmV4YW1wbGUuY29tMA2CC2V4 744 YW1wbGUuY29tMAsGCSqGSIb3DQEBBQNBAHKZKoS1wEQOGhgklx4+/yFYQlnqwKXvar/ZecQvJwui 745 0seMQnwBhwdBkHfVIU2Fu5VUMRyxlf0ZNaDXcpU581k= 746 -----END CERTIFICATE-----` 747 748 func TestCRLCreation(t *testing.T) { 749 block, _ := pem.Decode([]byte(pemPrivateKey)) 750 priv, _ := ParsePKCS1PrivateKey(block.Bytes) 751 block, _ = pem.Decode([]byte(pemCertificate)) 752 cert, _ := ParseCertificate(block.Bytes) 753 754 now := time.Unix(1000, 0) 755 expiry := time.Unix(10000, 0) 756 757 revokedCerts := []pkix.RevokedCertificate{ 758 { 759 SerialNumber: big.NewInt(1), 760 RevocationTime: now, 761 }, 762 { 763 SerialNumber: big.NewInt(42), 764 RevocationTime: now, 765 }, 766 } 767 768 crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry) 769 if err != nil { 770 t.Errorf("error creating CRL: %s", err) 771 } 772 773 _, err = ParseDERCRL(crlBytes) 774 if err != nil { 775 t.Errorf("error reparsing CRL: %s", err) 776 } 777 } 778 779 func fromBase64(in string) []byte { 780 out := make([]byte, base64.StdEncoding.DecodedLen(len(in))) 781 n, err := base64.StdEncoding.Decode(out, []byte(in)) 782 if err != nil { 783 panic("failed to base64 decode") 784 } 785 return out[:n] 786 } 787 788 func TestParseDERCRL(t *testing.T) { 789 derBytes := fromBase64(derCRLBase64) 790 certList, err := ParseDERCRL(derBytes) 791 if err != nil { 792 t.Errorf("error parsing: %s", err) 793 return 794 } 795 numCerts := len(certList.TBSCertList.RevokedCertificates) 796 expected := 88 797 if numCerts != expected { 798 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 799 } 800 801 if certList.HasExpired(time.Unix(1302517272, 0)) { 802 t.Errorf("CRL has expired (but shouldn't have)") 803 } 804 805 // Can't check the signature here without a package cycle. 806 } 807 808 func TestCRLWithoutExpiry(t *testing.T) { 809 derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh") 810 certList, err := ParseDERCRL(derBytes) 811 if err != nil { 812 t.Fatal(err) 813 } 814 if !certList.TBSCertList.NextUpdate.IsZero() { 815 t.Errorf("NextUpdate is not the zero value") 816 } 817 } 818 819 func TestParsePEMCRL(t *testing.T) { 820 pemBytes := fromBase64(pemCRLBase64) 821 certList, err := ParseCRL(pemBytes) 822 if err != nil { 823 t.Errorf("error parsing: %s", err) 824 return 825 } 826 numCerts := len(certList.TBSCertList.RevokedCertificates) 827 expected := 2 828 if numCerts != expected { 829 t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected) 830 } 831 832 if certList.HasExpired(time.Unix(1302517272, 0)) { 833 t.Errorf("CRL has expired (but shouldn't have)") 834 } 835 836 // Can't check the signature here without a package cycle. 837 } 838 839 func TestImports(t *testing.T) { 840 switch runtime.GOOS { 841 case "android", "nacl": 842 t.Skipf("skipping on %s", runtime.GOOS) 843 } 844 845 if err := exec.Command("go", "run", "x509_test_import.go").Run(); err != nil { 846 t.Errorf("failed to run x509_test_import.go: %s", err) 847 } 848 } 849 850 const derCRLBase64 = "MIINqzCCDJMCAQEwDQYJKoZIhvcNAQEFBQAwVjEZMBcGA1UEAxMQUEtJIEZJTk1FQ0NBTklDQTEVMBMGA1UEChMMRklOTUVDQ0FOSUNBMRUwEwYDVQQLEwxGSU5NRUNDQU5JQ0ExCzAJBgNVBAYTAklUFw0xMTA1MDQxNjU3NDJaFw0xMTA1MDQyMDU3NDJaMIIMBzAhAg4Ze1od49Lt1qIXBydAzhcNMDkwNzE2MDg0MzIyWjAAMCECDl0HSL9bcZ1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oRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K" 853 854 func TestCreateCertificateRequest(t *testing.T) { 855 random := rand.Reader 856 857 block, _ := pem.Decode([]byte(pemPrivateKey)) 858 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 859 if err != nil { 860 t.Fatalf("Failed to parse private key: %s", err) 861 } 862 863 ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) 864 if err != nil { 865 t.Fatalf("Failed to generate ECDSA key: %s", err) 866 } 867 868 ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader) 869 if err != nil { 870 t.Fatalf("Failed to generate ECDSA key: %s", err) 871 } 872 873 ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader) 874 if err != nil { 875 t.Fatalf("Failed to generate ECDSA key: %s", err) 876 } 877 878 tests := []struct { 879 name string 880 priv interface{} 881 sigAlgo SignatureAlgorithm 882 }{ 883 {"RSA", rsaPriv, SHA1WithRSA}, 884 {"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1}, 885 {"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1}, 886 {"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1}, 887 } 888 889 for _, test := range tests { 890 template := CertificateRequest{ 891 Subject: pkix.Name{ 892 CommonName: "test.example.com", 893 Organization: []string{"Σ Acme Co"}, 894 }, 895 SignatureAlgorithm: test.sigAlgo, 896 DNSNames: []string{"test.example.com"}, 897 EmailAddresses: []string{"gopher@golang.org"}, 898 IPAddresses: []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")}, 899 } 900 901 derBytes, err := CreateCertificateRequest(random, &template, test.priv) 902 if err != nil { 903 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 904 continue 905 } 906 907 out, err := ParseCertificateRequest(derBytes) 908 if err != nil { 909 t.Errorf("%s: failed to create certificate request: %s", test.name, err) 910 continue 911 } 912 913 if out.Subject.CommonName != template.Subject.CommonName { 914 t.Errorf("%s: output subject common name and template subject common name don't match", test.name) 915 } else if len(out.Subject.Organization) != len(template.Subject.Organization) { 916 t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name) 917 } else if len(out.DNSNames) != len(template.DNSNames) { 918 t.Errorf("%s: output DNS names and template DNS names don't match", test.name) 919 } else if len(out.EmailAddresses) != len(template.EmailAddresses) { 920 t.Errorf("%s: output email addresses and template email addresses don't match", test.name) 921 } else if len(out.IPAddresses) != len(template.IPAddresses) { 922 t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name) 923 } 924 } 925 } 926 927 func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest { 928 block, _ := pem.Decode([]byte(pemPrivateKey)) 929 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 930 if err != nil { 931 t.Fatal(err) 932 } 933 934 derBytes, err := CreateCertificateRequest(rand.Reader, template, rsaPriv) 935 if err != nil { 936 t.Fatal(err) 937 } 938 939 csr, err := ParseCertificateRequest(derBytes) 940 if err != nil { 941 t.Fatal(err) 942 } 943 944 return csr 945 } 946 947 func TestCertificateRequestOverrides(t *testing.T) { 948 sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil) 949 if err != nil { 950 t.Fatal(err) 951 } 952 953 template := CertificateRequest{ 954 Subject: pkix.Name{ 955 CommonName: "test.example.com", 956 Organization: []string{"Σ Acme Co"}, 957 }, 958 DNSNames: []string{"test.example.com"}, 959 960 // An explicit extension should override the DNSNames from the 961 // template. 962 ExtraExtensions: []pkix.Extension{ 963 { 964 Id: oidExtensionSubjectAltName, 965 Value: sanContents, 966 }, 967 }, 968 } 969 970 csr := marshalAndParseCSR(t, &template) 971 972 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" { 973 t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames) 974 } 975 976 // If there is already an attribute with X.509 extensions then the 977 // extra extensions should be added to it rather than creating a CSR 978 // with two extension attributes. 979 980 template.Attributes = []pkix.AttributeTypeAndValueSET{ 981 { 982 Type: oidExtensionRequest, 983 Value: [][]pkix.AttributeTypeAndValue{ 984 { 985 { 986 Type: oidExtensionAuthorityInfoAccess, 987 Value: []byte("foo"), 988 }, 989 }, 990 }, 991 }, 992 } 993 994 csr = marshalAndParseCSR(t, &template) 995 if l := len(csr.Attributes); l != 1 { 996 t.Errorf("incorrect number of attributes: %d\n", l) 997 } 998 999 if !csr.Attributes[0].Type.Equal(oidExtensionRequest) || 1000 len(csr.Attributes[0].Value) != 1 || 1001 len(csr.Attributes[0].Value[0]) != 2 { 1002 t.Errorf("bad attributes: %#v\n", csr.Attributes) 1003 } 1004 1005 sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil) 1006 if err != nil { 1007 t.Fatal(err) 1008 } 1009 1010 // Extensions in Attributes should override those in ExtraExtensions. 1011 template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{ 1012 Type: oidExtensionSubjectAltName, 1013 Value: sanContents2, 1014 }) 1015 1016 csr = marshalAndParseCSR(t, &template) 1017 1018 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" { 1019 t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames) 1020 } 1021 } 1022 1023 func TestParseCertificateRequest(t *testing.T) { 1024 csrBytes := fromBase64(csrBase64) 1025 csr, err := ParseCertificateRequest(csrBytes) 1026 if err != nil { 1027 t.Fatalf("failed to parse CSR: %s", err) 1028 } 1029 1030 if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" { 1031 t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses) 1032 } 1033 1034 if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" { 1035 t.Errorf("incorrect DNS names found: %v", csr.DNSNames) 1036 } 1037 1038 if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" { 1039 t.Errorf("incorrect Subject name: %v", csr.Subject) 1040 } 1041 1042 found := false 1043 for _, e := range csr.Extensions { 1044 if e.Id.Equal(oidExtensionBasicConstraints) { 1045 found = true 1046 break 1047 } 1048 } 1049 if !found { 1050 t.Errorf("basic constraints extension not found in CSR") 1051 } 1052 } 1053 1054 func TestMaxPathLen(t *testing.T) { 1055 block, _ := pem.Decode([]byte(pemPrivateKey)) 1056 rsaPriv, err := ParsePKCS1PrivateKey(block.Bytes) 1057 if err != nil { 1058 t.Fatalf("Failed to parse private key: %s", err) 1059 } 1060 1061 template := &Certificate{ 1062 SerialNumber: big.NewInt(1), 1063 Subject: pkix.Name{ 1064 CommonName: "Σ Acme Co", 1065 }, 1066 NotBefore: time.Unix(1000, 0), 1067 NotAfter: time.Unix(100000, 0), 1068 1069 BasicConstraintsValid: true, 1070 IsCA: true, 1071 } 1072 1073 serialiseAndParse := func(template *Certificate) *Certificate { 1074 derBytes, err := CreateCertificate(rand.Reader, template, template, &rsaPriv.PublicKey, rsaPriv) 1075 if err != nil { 1076 t.Fatalf("failed to create certificate: %s", err) 1077 return nil 1078 } 1079 1080 cert, err := ParseCertificate(derBytes) 1081 if err != nil { 1082 t.Fatalf("failed to parse certificate: %s", err) 1083 return nil 1084 } 1085 1086 return cert 1087 } 1088 1089 cert1 := serialiseAndParse(template) 1090 if m := cert1.MaxPathLen; m != -1 { 1091 t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m) 1092 } 1093 if cert1.MaxPathLenZero { 1094 t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero") 1095 } 1096 1097 template.MaxPathLen = 1 1098 cert2 := serialiseAndParse(template) 1099 if m := cert2.MaxPathLen; m != 1 { 1100 t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m) 1101 } 1102 if cert2.MaxPathLenZero { 1103 t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero") 1104 } 1105 1106 template.MaxPathLen = 0 1107 template.MaxPathLenZero = true 1108 cert3 := serialiseAndParse(template) 1109 if m := cert3.MaxPathLen; m != 0 { 1110 t.Errorf("Setting MaxPathLenZero didn't work, got %d", m) 1111 } 1112 if !cert3.MaxPathLenZero { 1113 t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero") 1114 } 1115 } 1116 1117 // This CSR was generated with OpenSSL: 1118 // 1119 // openssl req -out CSR.csr -new -newkey rsa:2048 -nodes -keyout privateKey.key -config openssl.cnf 1120 // 1121 // The openssl.cnf needs to include this section: 1122 // 1123 // [ v3_req ] 1124 // basicConstraints = CA:FALSE 1125 // keyUsage = nonRepudiation, digitalSignature, keyEncipherment 1126 // subjectAltName = email:gopher@golang.org,DNS:test.example.com 1127 const csrBase64 = "MIIC4zCCAcsCAQAwRTELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAOY+MVedRg2JEnyeLcSzcsMv2VcsTfkB5+Etd6hihAh6MrGezNyASMMKuQN6YhCX1icQDiQtGsDLTtheNnSXK06tAhHjAP/hGlszRJp+5+rP2M58fDBAkUBEhskbCUWwpY14jFtVuGNJ8vF8h8IeczdolvQhX9lVai9G0EUXJMliMKdjA899H0mRs9PzHyidyrXFNiZlQXfD8Kg7gETn2Ny965iyI6ujAIYSCvam6TnxRHYH2MBKyVGvsYGbPYUQJCsgdgyajEg6ekihvQY3SzO1HSAlZAd7d1QYO4VeWJ2mY6Wu3Jpmh+AmG19S9CcHqGjd0bhuAX9cpPOKgnEmqn0CAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQEFBQADggEBAC9+QpKfdabxwCWwf4IEe1cKjdXLS1ScSuw27a3kZzQiPV78WJMa6dB8dqhdH5BRwGZ/qsgLrO6ZHlNeIv2Ib41Ccq71ecHW/nXc94A1BzJ/bVdI9LZcmTUvR1/m1jCpN7UqQ0ml1u9VihK7Pe762hEYxuWDQzYEU0l15S/bXmqeq3eF1A59XT/2jwe5+NV0Wwf4UQlkTXsAQMsJ+KzrQafd8Qv2A49o048uRvmjeJDrXLawGVianZ7D5A6Fpd1rZh6XcjqBpmgLw41DRQWENOdzhy+HyphKRv1MlY8OLkNqpGMhu8DdgJVGoT16DGiickoEa7Z3UCPVNgdTkT9jq7U=" 1128 1129 const sanManyOtherName = "MEmgEAYIKwYBBAHZWy6gBAICAc2CCHRlc3QuZ292oA8GCCsGAQQB2VsuoAMCASqCB2dvdi5nb3agEQYIKwYBBAHZWy6gBQIDAXUA" 1130 1131 func TestParseGeneralNamesOtherName(t *testing.T) { 1132 sanMultipleOther := fromBase64(sanManyOtherName) 1133 otherNames, dnsNames, emailAddresses, URIs, directoryNames, ediPartyNames, ipAddresses, registeredIDs, _, err := parseGeneralNames(sanMultipleOther) 1134 1135 if err != nil { 1136 t.Errorf("parseGeneralNames returned error %v", err) 1137 } 1138 if emailAddresses != nil || directoryNames != nil || URIs != nil || ediPartyNames != nil || ipAddresses != nil || registeredIDs != nil { 1139 t.Errorf("parseGeneralNames returned unexpected name type from sanManyOtherName") 1140 } 1141 if len(dnsNames) != 2 || dnsNames[0] != "test.gov" || dnsNames[1] != "gov.gov" { 1142 t.Errorf("parseGeneralNames returned unexpected dnsNames from sanManyOtherName: %v", dnsNames) 1143 } 1144 if len(otherNames) != 3 { 1145 t.Errorf("parseGeneralNames returned unexpected # of otherName in sanManyOtherName: %v (expected 3)", len(otherNames)) 1146 } 1147 var otherInts [3]int 1148 var expectedInts [3]int = [3]int{461, 42, 95488} 1149 for x := 0; x < 3; x++ { 1150 rest, err := asn1.Unmarshal(otherNames[x].Value.Bytes, &(otherInts[x])) 1151 if err != nil { 1152 t.Errorf("unexpected error in unmarshaling otherName %v", err) 1153 } 1154 if len(rest) != 0 { 1155 t.Errorf("unexpected extra bytes in otherName") 1156 } 1157 } 1158 for i := range otherInts { 1159 if otherInts[i] != expectedInts[i] { 1160 t.Errorf("otherName contained unexpected value %v, expected %v", otherInts[i], expectedInts[i]) 1161 } 1162 } 1163 1164 } 1165 1166 const sanManyDirectoryName = "MIHtpBwwGjEYMBYGA1UEChMPRXh0cmVtZSBEaXNjb3JkgggqLmdvdi51c6SBnDCBmTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAkZMMRQwEgYDVQQHEwtUYWxsYWhhc3NlZTEcMBoGA1UECRMTMzIxMCBIb2xseSBNaWxsIFJ1bjEOMAwGA1UEERMFMzAwNjIxGDAWBgNVBAoTD0V4dHJlbWUgRGlzY29yZDEOMAwGA1UECxMFQ2hhb3MxDzANBgNVBAMTBmdvdi51c4IGZ292LnVzpBwwGjEYMBYGA1UEChMPRXh0cmVtZSBEaXNjb3Jk" 1167 1168 func TestParseGeneralNamesDirectoryName(t *testing.T) { 1169 // TODO: This needs to test that we can parse a GeneralName that contains a 1170 // DirectoryName, not that we can parse DirectoryNames correctly, which is 1171 // what it was previously doing. DirectoryName parsing falls under pkix.Name, 1172 // and should be tested in the pkix package. 1173 } 1174 1175 const sanManyURI = "MF6GGGh0dHA6Ly9nb3YudXMvaW5kZXguaHRtbIIIKi5nb3YudXOGE2h0dHA6Ly9nb3YudXMvaG9tZS+CBmdvdi51c4YbaHR0cDovL2dvdi51cy9ob21lL2NhcGl0b2wv" 1176 1177 func TestParseGeneralNamesUniformResourceIdentifier(t *testing.T) { 1178 sanMultipleURI := fromBase64(sanManyURI) 1179 otherNames, dnsNames, emailAddresses, URIs, directoryNames, ediPartyNames, ipAddresses, registeredIDs, _, err := parseGeneralNames(sanMultipleURI) 1180 1181 if err != nil { 1182 t.Errorf("parseGeneralNames returned error %v", err) 1183 } 1184 if emailAddresses != nil || otherNames != nil || directoryNames != nil || ediPartyNames != nil || ipAddresses != nil || registeredIDs != nil { 1185 t.Errorf("parseGeneralNames returned unexpected name type from sanManyURI") 1186 } 1187 if len(dnsNames) != 2 || dnsNames[0] != "*.gov.us" || dnsNames[1] != "gov.us" { 1188 t.Errorf("parseGeneralNames returned unexpected dnsNames from sanManyURI: %v", dnsNames) 1189 } 1190 if len(URIs) != 3 { 1191 t.Errorf("parseGeneralNames returned unexpected # of uniformResourceIdentifier in sanManyURI: %v (expected 3)", len(URIs)) 1192 } 1193 1194 var expectedNames [3]string = [3]string{"http://gov.us/index.html", "http://gov.us/home/", "http://gov.us/home/capitol/"} 1195 for i := range URIs { 1196 if URIs[i] != expectedNames[i] { 1197 t.Errorf("uniformResourceIdentifier contained unexpected value %v, expected %v", URIs[i], expectedNames[i]) 1198 } 1199 } 1200 } 1201 1202 const sanManyRegisteredID = "MDGICCsGAQUFBw0Bggh0ZXN0LmdvdogIKwYBBAHZWyqCB2dvdi5nb3aICCsGAQUFBw0D" 1203 1204 func TestParseGeneralNamesRegisteredID(t *testing.T) { 1205 sanMultipleRID := fromBase64(sanManyRegisteredID) 1206 otherNames, dnsNames, emailAddresses, URIs, directoryNames, ediPartyNames, ipAddresses, registeredIDs, _, err := parseGeneralNames(sanMultipleRID) 1207 1208 if err != nil { 1209 t.Errorf("parseGeneralNames returned error %v", err) 1210 } 1211 if emailAddresses != nil || otherNames != nil || directoryNames != nil || ediPartyNames != nil || ipAddresses != nil || URIs != nil { 1212 t.Errorf("parseGeneralNames returned unexpected name type from sanManyRegisteredID") 1213 } 1214 if len(dnsNames) != 2 || dnsNames[0] != "test.gov" || dnsNames[1] != "gov.gov" { 1215 t.Errorf("parseGeneralNames returned unexpected dnsNames from sanManyRegisteredID: %v", dnsNames) 1216 } 1217 if len(registeredIDs) != 3 { 1218 t.Errorf("parseGeneralNames returned unexpected # of registeredIDs in sanManyRegisteredID: %v (expected 3)", len(registeredIDs)) 1219 } 1220 1221 var expectedNames [3]asn1.ObjectIdentifier = [3]asn1.ObjectIdentifier{{1, 3, 6, 1, 5, 5, 7, 13, 1}, {1, 3, 6, 1, 4, 1, 11483, 42}, {1, 3, 6, 1, 5, 5, 7, 13, 3}} 1222 for i := range registeredIDs { 1223 if !registeredIDs[i].Equal(expectedNames[i]) { 1224 t.Errorf("registeredID contained unexpected value %v, expected %v", registeredIDs[i], expectedNames[i]) 1225 } 1226 } 1227 } 1228 1229 const sanManyEDI = "MIGjpRigBwwFRWFydGihDQwLVW5kZXJncm91bmSCCHRlc3QuZ292pQ6hDBMKZ292ZXJubWVudKUNoQsMCXNvdmVyZWlnboIHZ292LmdvdqUjoAoTCHVuaXZlcnNloRUME1N1cHJlbWUgTGVnaXNsYXR1cmWBDWFkbWluQGdvdi5nb3alIaAKEwh1bml2ZXJzZaETExFTdXByZW1lIEV4ZWN1dGl2ZQ==" 1230 1231 func TestParseGeneralNamesEDIPartyName(t *testing.T) { 1232 sanMultipleEDI := fromBase64(sanManyEDI) 1233 otherNames, dnsNames, emailAddresses, URIs, directoryNames, ediPartyNames, ipAddresses, registeredIDs, _, err := parseGeneralNames(sanMultipleEDI) 1234 1235 if err != nil { 1236 t.Errorf("parseGeneralNames returned error %v", err) 1237 } 1238 if registeredIDs != nil || otherNames != nil || directoryNames != nil || ipAddresses != nil || URIs != nil { 1239 t.Errorf("parseGeneralNames returned unexpected name type from sanManyEDI") 1240 } 1241 if len(dnsNames) != 2 || dnsNames[0] != "test.gov" || dnsNames[1] != "gov.gov" { 1242 t.Errorf("parseGeneralNames returned unexpected dnsNames from sanManyEDI: %v (expected 2)", dnsNames) 1243 } 1244 if len(emailAddresses) != 1 || emailAddresses[0] != "admin@gov.gov" { 1245 t.Errorf("parseGeneralNames returned unexpected rfc822Names from sanManyEDI: %v", emailAddresses) 1246 } 1247 if len(ediPartyNames) != 5 { 1248 t.Errorf("parseGeneralNames returned unexpected # of ediPartyNames in sanManyEDI: %v (expected 5)", len(ediPartyNames)) 1249 } 1250 1251 var expectedNames [5]pkix.EDIPartyName 1252 expectedNames[0] = pkix.EDIPartyName{NameAssigner: "Earth", PartyName: "Underground"} 1253 expectedNames[1] = pkix.EDIPartyName{PartyName: "government"} 1254 expectedNames[2] = pkix.EDIPartyName{PartyName: "sovereign"} 1255 expectedNames[3] = pkix.EDIPartyName{NameAssigner: "universe", PartyName: "Supreme Legislature"} 1256 expectedNames[4] = pkix.EDIPartyName{NameAssigner: "universe", PartyName: "Supreme Executive"} 1257 1258 for i := range ediPartyNames { 1259 if !reflect.DeepEqual(ediPartyNames[i], expectedNames[i]) { 1260 t.Errorf("ediPartyName contained unexpected value %v, expected %v", ediPartyNames[i], expectedNames[i]) 1261 } 1262 } 1263 } 1264 1265 const sanAllSuported = "MIGXiAkrBgEEAdlbgzqkHDAaMRgwFgYDVQQKEw9FeHRyZW1lIERpc2NvcmSgEQYIKwYBBAHZWy6gBQIDCCoJpR6gDxMNTW90aGVyIE5hdHVyZaELEwlwYXJ0eU5hbWWCCCouZ292LnVzggZnb3YudXOBDGFkbWluQGdvdi51c4YTaHR0cHM6Ly9nb3YudXMvaG9tZYcEwMAAAQ==" 1266 1267 func TestParseGeneralNamesAll(t *testing.T) { 1268 // TODO: This should test we can parse a GeneralName that contains all 1269 // possible types of GeneralName, not that we can parse a DN correctly. We 1270 // should not rely on implementation details of pkix.Name to handle parsing a 1271 // GeneralName. More broadly, we should consider refactoring how GeneralName 1272 // is handled, and maybe move it to the pkix package. 1273 } 1274 1275 func TestTimeInValidityPeriod(t *testing.T) { 1276 fileBytes, _ := ioutil.ReadFile("testdata/davidadrian.org.cert") 1277 p, _ := pem.Decode(fileBytes) 1278 c, err := ParseCertificate(p.Bytes) 1279 if err != nil { 1280 t.Fatalf("unable to parse PEM: %s", err) 1281 } 1282 tests := []struct { 1283 unixTime int64 1284 expected bool 1285 }{ 1286 { 1287 unixTime: 946684800, // 2000-01-01 00:00:00 1288 expected: false, 1289 }, 1290 { 1291 unixTime: 0, 1292 expected: false, 1293 }, 1294 { 1295 unixTime: 2208988800, // 2040-01-01 00:00:00 1296 expected: false, 1297 }, 1298 { 1299 unixTime: 1420070400, // 2015-01-01 00:00:00 1300 expected: true, 1301 }, 1302 } 1303 for idx, test := range tests { 1304 timestamp := time.Unix(test.unixTime, 0) 1305 if actual := c.TimeInValidityPeriod(timestamp); actual != test.expected { 1306 t.Errorf("#%d: for time %d got %t, expected %v", idx, test.unixTime, actual, test.expected) 1307 } 1308 } 1309 } 1310 1311 func TestParseSignedCertificateTimestampListErrors(t *testing.T) { 1312 incompleteList, _ := asn1.Marshal([]byte{0x00}) 1313 nodataList, _ := asn1.Marshal([]byte{0x00, 0x00}) 1314 trailingDataList, _ := asn1.Marshal([]byte{0x00, 0x00, 0x00}) 1315 incompleteSCTList, _ := asn1.Marshal([]byte{0x00, 0x00, 0x00, 0x99}) 1316 badSCTList, _ := asn1.Marshal([]byte{0x00, 0x00, 0x00, 0x00, 0x00}) 1317 1318 testCases := []struct { 1319 name string 1320 ext pkix.Extension 1321 expectedErrMsg string 1322 }{ 1323 { 1324 name: "incomplete len", 1325 ext: pkix.Extension{Value: incompleteList}, 1326 expectedErrMsg: "malformed SCT extension: incomplete length field", 1327 }, 1328 { 1329 name: "trailing data", 1330 ext: pkix.Extension{Value: trailingDataList}, 1331 expectedErrMsg: "malformed SCT extension: trailing data", 1332 }, 1333 { 1334 name: "incomplete SCT in list", 1335 ext: pkix.Extension{Value: incompleteSCTList}, 1336 expectedErrMsg: "malformed SCT extension: incomplete SCT", 1337 }, 1338 { 1339 name: "bad SCT in list", 1340 ext: pkix.Extension{Value: badSCTList}, 1341 expectedErrMsg: "malformed SCT extension: SCT parse err: EOF", 1342 }, 1343 { 1344 name: "no data", 1345 ext: pkix.Extension{Value: nodataList}, 1346 }, 1347 } 1348 1349 for _, tc := range testCases { 1350 t.Run(tc.name, func(t *testing.T) { 1351 out := &Certificate{} 1352 err := parseSignedCertificateTimestampList(out, tc.ext) 1353 1354 if err != nil && err.Error() != tc.expectedErrMsg { 1355 t.Errorf("expected err %q got %q", tc.expectedErrMsg, err.Error()) 1356 } else if err == nil && tc.expectedErrMsg != "" { 1357 t.Errorf("expected err %q got nil", tc.expectedErrMsg) 1358 } 1359 }) 1360 } 1361 } 1362 1363 func TestParseCert(t *testing.T) { 1364 tcases := []string{ 1365 "testdata/parsecert1.pem", 1366 "testdata/parsecert2.pem", 1367 "testdata/parsecert3.pem", 1368 "testdata/parsecert4-time.pem", 1369 "testdata/parsecert5-printable.pem", 1370 "testdata/parsecert6-explicittag.pem", 1371 "testdata/parsecert7-tagmatch.pem", 1372 "testdata/parsecert8-rsapositive.pem", 1373 "testdata/parsecert9-intminlen.pem", 1374 "testdata/parsecert10-tag.pem", 1375 "testdata/parsecert11-ia5.pem", 1376 "testdata/parsecert12-minlen.pem", 1377 } 1378 1379 for _, tc := range tcases { 1380 t.Run(tc, func(t *testing.T) { 1381 b, err := ioutil.ReadFile(tc) 1382 require.NoError(t, err) 1383 1384 block, _ := pem.Decode(b) 1385 require.NotNil(t, block) 1386 1387 _, err = ParseCertificate(block.Bytes) 1388 assert.Error(t, err) 1389 }) 1390 } 1391 1392 asn1.AllowPermissiveParsing = true 1393 1394 for _, tc := range tcases { 1395 t.Run(tc, func(t *testing.T) { 1396 b, err := ioutil.ReadFile(tc) 1397 require.NoError(t, err) 1398 1399 block, _ := pem.Decode(b) 1400 require.NotNil(t, block) 1401 1402 _, err = ParseCertificate(block.Bytes) 1403 assert.NoError(t, err) 1404 }) 1405 } 1406 }