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