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