...
Run Format

Source file src/crypto/x509/x509_test.go

Documentation: crypto/x509

     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  	"net/url"
    26  	"os/exec"
    27  	"reflect"
    28  	"runtime"
    29  	"strings"
    30  	"testing"
    31  	"time"
    32  )
    33  
    34  func TestParsePKCS1PrivateKey(t *testing.T) {
    35  	block, _ := pem.Decode([]byte(pemPrivateKey))
    36  	priv, err := ParsePKCS1PrivateKey(block.Bytes)
    37  	if err != nil {
    38  		t.Errorf("Failed to parse private key: %s", err)
    39  		return
    40  	}
    41  	if priv.PublicKey.N.Cmp(rsaPrivateKey.PublicKey.N) != 0 ||
    42  		priv.PublicKey.E != rsaPrivateKey.PublicKey.E ||
    43  		priv.D.Cmp(rsaPrivateKey.D) != 0 ||
    44  		priv.Primes[0].Cmp(rsaPrivateKey.Primes[0]) != 0 ||
    45  		priv.Primes[1].Cmp(rsaPrivateKey.Primes[1]) != 0 {
    46  		t.Errorf("got:%+v want:%+v", priv, rsaPrivateKey)
    47  	}
    48  
    49  	// This private key includes an invalid prime that
    50  	// rsa.PrivateKey.Validate should reject.
    51  	data := []byte("0\x16\x02\x00\x02\x02\u007f\x00\x02\x0200\x02\x0200\x02\x02\x00\x01\x02\x02\u007f\x00")
    52  	if _, err := ParsePKCS1PrivateKey(data); err == nil {
    53  		t.Errorf("parsing invalid private key did not result in an error")
    54  	}
    55  }
    56  
    57  func TestParsePKIXPublicKey(t *testing.T) {
    58  	block, _ := pem.Decode([]byte(pemPublicKey))
    59  	pub, err := ParsePKIXPublicKey(block.Bytes)
    60  	if err != nil {
    61  		t.Errorf("Failed to parse RSA public key: %s", err)
    62  		return
    63  	}
    64  	rsaPub, ok := pub.(*rsa.PublicKey)
    65  	if !ok {
    66  		t.Errorf("Value returned from ParsePKIXPublicKey was not an RSA public key")
    67  		return
    68  	}
    69  
    70  	pubBytes2, err := MarshalPKIXPublicKey(rsaPub)
    71  	if err != nil {
    72  		t.Errorf("Failed to marshal RSA public key for the second time: %s", err)
    73  		return
    74  	}
    75  	if !bytes.Equal(pubBytes2, block.Bytes) {
    76  		t.Errorf("Reserialization of public key didn't match. got %x, want %x", pubBytes2, block.Bytes)
    77  	}
    78  }
    79  
    80  var pemPublicKey = `-----BEGIN PUBLIC KEY-----
    81  MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3VoPN9PKUjKFLMwOge6+
    82  wnDi8sbETGIx2FKXGgqtAKpzmem53kRGEQg8WeqRmp12wgp74TGpkEXsGae7RS1k
    83  enJCnma4fii+noGH7R0qKgHvPrI2Bwa9hzsH8tHxpyM3qrXslOmD45EH9SxIDUBJ
    84  FehNdaPbLP1gFyahKMsdfxFJLUvbUycuZSJ2ZnIgeVxwm4qbSvZInL9Iu4FzuPtg
    85  fINKcbbovy1qq4KvPIrXzhbY3PWDc6btxCf3SE0JdE1MCPThntB62/bLMSQ7xdDR
    86  FF53oIpvxe/SCOymfWq/LW849Ytv3Xwod0+wzAP8STXG4HSELS4UedPYeHJJJYcZ
    87  +QIDAQAB
    88  -----END PUBLIC KEY-----
    89  `
    90  
    91  var pemPrivateKey = `
    92  -----BEGIN RSA PRIVATE KEY-----
    93  MIICXAIBAAKBgQCxoeCUW5KJxNPxMp+KmCxKLc1Zv9Ny+4CFqcUXVUYH69L3mQ7v
    94  IWrJ9GBfcaA7BPQqUlWxWM+OCEQZH1EZNIuqRMNQVuIGCbz5UQ8w6tS0gcgdeGX7
    95  J7jgCQ4RK3F/PuCM38QBLaHx988qG8NMc6VKErBjctCXFHQt14lerd5KpQIDAQAB
    96  AoGAYrf6Hbk+mT5AI33k2Jt1kcweodBP7UkExkPxeuQzRVe0KVJw0EkcFhywKpr1
    97  V5eLMrILWcJnpyHE5slWwtFHBG6a5fLaNtsBBtcAIfqTQ0Vfj5c6SzVaJv0Z5rOd
    98  7gQF6isy3t3w9IF3We9wXQKzT6q5ypPGdm6fciKQ8RnzREkCQQDZwppKATqQ41/R
    99  vhSj90fFifrGE6aVKC1hgSpxGQa4oIdsYYHwMzyhBmWW9Xv/R+fPyr8ZwPxp2c12
   100  33QwOLPLAkEA0NNUb+z4ebVVHyvSwF5jhfJxigim+s49KuzJ1+A2RaSApGyBZiwS
   101  rWvWkB471POAKUYt5ykIWVZ83zcceQiNTwJBAMJUFQZX5GDqWFc/zwGoKkeR49Yi
   102  MTXIvf7Wmv6E++eFcnT461FlGAUHRV+bQQXGsItR/opIG7mGogIkVXa3E1MCQARX
   103  AAA7eoZ9AEHflUeuLn9QJI/r0hyQQLEtrpwv6rDT1GCWaLII5HJ6NUFVf4TTcqxo
   104  6vdM4QGKTJoO+SaCyP0CQFdpcxSAuzpFcKv0IlJ8XzS/cy+mweCMwyJ1PFEc4FX6
   105  wg/HcAJWY60xZTJDFN+Qfx8ZQvBEin6c2/h+zZi5IVY=
   106  -----END RSA PRIVATE KEY-----
   107  `
   108  
   109  var testPrivateKey *rsa.PrivateKey
   110  
   111  func init() {
   112  	block, _ := pem.Decode([]byte(pemPrivateKey))
   113  
   114  	var err error
   115  	if testPrivateKey, err = ParsePKCS1PrivateKey(block.Bytes); err != nil {
   116  		panic("Failed to parse private key: " + err.Error())
   117  	}
   118  }
   119  
   120  func bigFromString(s string) *big.Int {
   121  	ret := new(big.Int)
   122  	ret.SetString(s, 10)
   123  	return ret
   124  }
   125  
   126  func fromBase10(base10 string) *big.Int {
   127  	i := new(big.Int)
   128  	i.SetString(base10, 10)
   129  	return i
   130  }
   131  
   132  func bigFromHexString(s string) *big.Int {
   133  	ret := new(big.Int)
   134  	ret.SetString(s, 16)
   135  	return ret
   136  }
   137  
   138  var rsaPrivateKey = &rsa.PrivateKey{
   139  	PublicKey: rsa.PublicKey{
   140  		N: bigFromString("124737666279038955318614287965056875799409043964547386061640914307192830334599556034328900586693254156136128122194531292927142396093148164407300419162827624945636708870992355233833321488652786796134504707628792159725681555822420087112284637501705261187690946267527866880072856272532711620639179596808018872997"),
   141  		E: 65537,
   142  	},
   143  	D: bigFromString("69322600686866301945688231018559005300304807960033948687567105312977055197015197977971637657636780793670599180105424702854759606794705928621125408040473426339714144598640466128488132656829419518221592374964225347786430566310906679585739468938549035854760501049443920822523780156843263434219450229353270690889"),
   144  	Primes: []*big.Int{
   145  		bigFromString("11405025354575369741595561190164746858706645478381139288033759331174478411254205003127028642766986913445391069745480057674348716675323735886284176682955723"),
   146  		bigFromString("10937079261204603443118731009201819560867324167189758120988909645641782263430128449826989846631183550578761324239709121189827307416350485191350050332642639"),
   147  	},
   148  }
   149  
   150  func TestMarshalRSAPrivateKey(t *testing.T) {
   151  	priv := &rsa.PrivateKey{
   152  		PublicKey: rsa.PublicKey{
   153  			N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
   154  			E: 3,
   155  		},
   156  		D: fromBase10("10897585948254795600358846499957366070880176878341177571733155050184921896034527397712889205732614568234385175145686545381899460748279607074689061600935843283397424506622998458510302603922766336783617368686090042765718290914099334449154829375179958369993407724946186243249568928237086215759259909861748642124071874879861299389874230489928271621259294894142840428407196932444474088857746123104978617098858619445675532587787023228852383149557470077802718705420275739737958953794088728369933811184572620857678792001136676902250566845618813972833750098806496641114644760255910789397593428910198080271317419213080834885003"),
   157  		Primes: []*big.Int{
   158  			fromBase10("1025363189502892836833747188838978207017355117492483312747347695538428729137306368764177201532277413433182799108299960196606011786562992097313508180436744488171474690412562218914213688661311117337381958560443"),
   159  			fromBase10("3467903426626310123395340254094941045497208049900750380025518552334536945536837294961497712862519984786362199788654739924501424784631315081391467293694361474867825728031147665777546570788493758372218019373"),
   160  			fromBase10("4597024781409332673052708605078359346966325141767460991205742124888960305710298765592730135879076084498363772408626791576005136245060321874472727132746643162385746062759369754202494417496879741537284589047"),
   161  		},
   162  	}
   163  
   164  	derBytes := MarshalPKCS1PrivateKey(priv)
   165  
   166  	priv2, err := ParsePKCS1PrivateKey(derBytes)
   167  	if err != nil {
   168  		t.Errorf("error parsing serialized key: %s", err)
   169  		return
   170  	}
   171  	if priv.PublicKey.N.Cmp(priv2.PublicKey.N) != 0 ||
   172  		priv.PublicKey.E != priv2.PublicKey.E ||
   173  		priv.D.Cmp(priv2.D) != 0 ||
   174  		len(priv2.Primes) != 3 ||
   175  		priv.Primes[0].Cmp(priv2.Primes[0]) != 0 ||
   176  		priv.Primes[1].Cmp(priv2.Primes[1]) != 0 ||
   177  		priv.Primes[2].Cmp(priv2.Primes[2]) != 0 {
   178  		t.Errorf("got:%+v want:%+v", priv, priv2)
   179  	}
   180  }
   181  
   182  func TestMarshalRSAPublicKey(t *testing.T) {
   183  	pub := &rsa.PublicKey{
   184  		N: fromBase10("16346378922382193400538269749936049106320265317511766357599732575277382844051791096569333808598921852351577762718529818072849191122419410612033592401403764925096136759934497687765453905884149505175426053037420486697072448609022753683683718057795566811401938833367954642951433473337066311978821180526439641496973296037000052546108507805269279414789035461158073156772151892452251106173507240488993608650881929629163465099476849643165682709047462010581308719577053905787496296934240246311806555924593059995202856826239801816771116902778517096212527979497399966526283516447337775509777558018145573127308919204297111496233"),
   185  		E: 3,
   186  	}
   187  	derBytes := MarshalPKCS1PublicKey(pub)
   188  	pub2, err := ParsePKCS1PublicKey(derBytes)
   189  	if err != nil {
   190  		t.Errorf("ParsePKCS1PublicKey: %s", err)
   191  	}
   192  	if pub.N.Cmp(pub2.N) != 0 || pub.E != pub2.E {
   193  		t.Errorf("ParsePKCS1PublicKey = %+v, want %+v", pub, pub2)
   194  	}
   195  
   196  	// It's never been documented that asn1.Marshal/Unmarshal on rsa.PublicKey works,
   197  	// but it does, and we know of code that depends on it.
   198  	// Lock that in, even though we'd prefer that people use MarshalPKCS1PublicKey and ParsePKCS1PublicKey.
   199  	derBytes2, err := asn1.Marshal(*pub)
   200  	if err != nil {
   201  		t.Errorf("Marshal(rsa.PublicKey): %v", err)
   202  	} else if !bytes.Equal(derBytes, derBytes2) {
   203  		t.Errorf("Marshal(rsa.PublicKey) = %x, want %x", derBytes2, derBytes)
   204  	}
   205  	pub3 := new(rsa.PublicKey)
   206  	rest, err := asn1.Unmarshal(derBytes, pub3)
   207  	if err != nil {
   208  		t.Errorf("Unmarshal(rsa.PublicKey): %v", err)
   209  	}
   210  	if len(rest) != 0 || pub.N.Cmp(pub3.N) != 0 || pub.E != pub3.E {
   211  		t.Errorf("Unmarshal(rsa.PublicKey) = %+v, %q want %+v, %q", pub, rest, pub2, []byte(nil))
   212  	}
   213  
   214  	publicKeys := []struct {
   215  		derBytes          []byte
   216  		expectedErrSubstr string
   217  	}{
   218  		{
   219  			derBytes: []byte{
   220  				0x30, 6, // SEQUENCE, 6 bytes
   221  				0x02, 1, // INTEGER, 1 byte
   222  				17,
   223  				0x02, 1, // INTEGER, 1 byte
   224  				3, // 3
   225  			},
   226  		}, {
   227  			derBytes: []byte{
   228  				0x30, 6, // SEQUENCE
   229  				0x02, 1, // INTEGER, 1 byte
   230  				0xff,    // -1
   231  				0x02, 1, // INTEGER, 1 byte
   232  				3,
   233  			},
   234  			expectedErrSubstr: "zero or negative",
   235  		}, {
   236  			derBytes: []byte{
   237  				0x30, 6, // SEQUENCE
   238  				0x02, 1, // INTEGER, 1 byte
   239  				17,
   240  				0x02, 1, // INTEGER, 1 byte
   241  				0xff, // -1
   242  			},
   243  			expectedErrSubstr: "zero or negative",
   244  		}, {
   245  			derBytes: []byte{
   246  				0x30, 6, // SEQUENCE
   247  				0x02, 1, // INTEGER, 1 byte
   248  				17,
   249  				0x02, 1, // INTEGER, 1 byte
   250  				3,
   251  				1,
   252  			},
   253  			expectedErrSubstr: "trailing data",
   254  		}, {
   255  			derBytes: []byte{
   256  				0x30, 9, // SEQUENCE
   257  				0x02, 1, // INTEGER, 1 byte
   258  				17,
   259  				0x02, 4, // INTEGER, 4 bytes
   260  				0x7f, 0xff, 0xff, 0xff,
   261  			},
   262  		}, {
   263  			derBytes: []byte{
   264  				0x30, 10, // SEQUENCE
   265  				0x02, 1, // INTEGER, 1 byte
   266  				17,
   267  				0x02, 5, // INTEGER, 5 bytes
   268  				0x00, 0x80, 0x00, 0x00, 0x00,
   269  			},
   270  			// On 64-bit systems, encoding/asn1 will accept the
   271  			// public exponent, but ParsePKCS1PublicKey will return
   272  			// an error. On 32-bit systems, encoding/asn1 will
   273  			// return the error. The common substring of both error
   274  			// is the word “large”.
   275  			expectedErrSubstr: "large",
   276  		},
   277  	}
   278  
   279  	for i, test := range publicKeys {
   280  		shouldFail := len(test.expectedErrSubstr) > 0
   281  		pub, err := ParsePKCS1PublicKey(test.derBytes)
   282  		if shouldFail {
   283  			if err == nil {
   284  				t.Errorf("#%d: unexpected success, got %#v", i, pub)
   285  			} else if !strings.Contains(err.Error(), test.expectedErrSubstr) {
   286  				t.Errorf("#%d: expected error containing %q, got %s", i, test.expectedErrSubstr, err)
   287  			}
   288  		} else {
   289  			if err != nil {
   290  				t.Errorf("#%d: unexpected failure: %s", i, err)
   291  				continue
   292  			}
   293  			reserialized := MarshalPKCS1PublicKey(pub)
   294  			if !bytes.Equal(reserialized, test.derBytes) {
   295  				t.Errorf("#%d: failed to reserialize: got %x, expected %x", i, reserialized, test.derBytes)
   296  			}
   297  		}
   298  	}
   299  }
   300  
   301  type matchHostnamesTest struct {
   302  	pattern, host string
   303  	ok            bool
   304  }
   305  
   306  var matchHostnamesTests = []matchHostnamesTest{
   307  	{"a.b.c", "a.b.c", true},
   308  	{"a.b.c", "b.b.c", false},
   309  	{"", "b.b.c", false},
   310  	{"a.b.c", "", false},
   311  	{"example.com", "example.com", true},
   312  	{"example.com", "www.example.com", false},
   313  	{"*.example.com", "example.com", false},
   314  	{"*.example.com", "www.example.com", true},
   315  	{"*.example.com", "www.example.com.", true},
   316  	{"*.example.com", "xyz.www.example.com", false},
   317  	{"*.*.example.com", "xyz.www.example.com", false},
   318  	{"*.www.*.com", "xyz.www.example.com", false},
   319  	{"*bar.example.com", "foobar.example.com", false},
   320  	{"f*.example.com", "foobar.example.com", false},
   321  	{"", ".", false},
   322  	{".", "", false},
   323  	{".", ".", false},
   324  	{"example.com", "example.com.", true},
   325  	{"example.com.", "example.com", true},
   326  	{"example.com.", "example.com.", true},
   327  	{"*.com.", "example.com.", true},
   328  	{"*.com.", "example.com", true},
   329  	{"*.com", "example.com", true},
   330  	{"*.com", "example.com.", true},
   331  }
   332  
   333  func TestMatchHostnames(t *testing.T) {
   334  	for i, test := range matchHostnamesTests {
   335  		r := matchHostnames(test.pattern, test.host)
   336  		if r != test.ok {
   337  			t.Errorf("#%d mismatch got: %t want: %t when matching '%s' against '%s'", i, r, test.ok, test.host, test.pattern)
   338  		}
   339  	}
   340  }
   341  
   342  func TestMatchIP(t *testing.T) {
   343  	// Check that pattern matching is working.
   344  	c := &Certificate{
   345  		DNSNames: []string{"*.foo.bar.baz"},
   346  		Subject: pkix.Name{
   347  			CommonName: "*.foo.bar.baz",
   348  		},
   349  	}
   350  	err := c.VerifyHostname("quux.foo.bar.baz")
   351  	if err != nil {
   352  		t.Fatalf("VerifyHostname(quux.foo.bar.baz): %v", err)
   353  	}
   354  
   355  	// But check that if we change it to be matching against an IP address,
   356  	// it is rejected.
   357  	c = &Certificate{
   358  		DNSNames: []string{"*.2.3.4"},
   359  		Subject: pkix.Name{
   360  			CommonName: "*.2.3.4",
   361  		},
   362  	}
   363  	err = c.VerifyHostname("1.2.3.4")
   364  	if err == nil {
   365  		t.Fatalf("VerifyHostname(1.2.3.4) should have failed, did not")
   366  	}
   367  
   368  	c = &Certificate{
   369  		IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
   370  	}
   371  	err = c.VerifyHostname("127.0.0.1")
   372  	if err != nil {
   373  		t.Fatalf("VerifyHostname(127.0.0.1): %v", err)
   374  	}
   375  	err = c.VerifyHostname("::1")
   376  	if err != nil {
   377  		t.Fatalf("VerifyHostname(::1): %v", err)
   378  	}
   379  	err = c.VerifyHostname("[::1]")
   380  	if err != nil {
   381  		t.Fatalf("VerifyHostname([::1]): %v", err)
   382  	}
   383  }
   384  
   385  func TestCertificateParse(t *testing.T) {
   386  	s, _ := hex.DecodeString(certBytes)
   387  	certs, err := ParseCertificates(s)
   388  	if err != nil {
   389  		t.Error(err)
   390  	}
   391  	if len(certs) != 2 {
   392  		t.Errorf("Wrong number of certs: got %d want 2", len(certs))
   393  		return
   394  	}
   395  
   396  	err = certs[0].CheckSignatureFrom(certs[1])
   397  	if err != nil {
   398  		t.Error(err)
   399  	}
   400  
   401  	if err := certs[0].VerifyHostname("mail.google.com"); err != nil {
   402  		t.Error(err)
   403  	}
   404  
   405  	const expectedExtensions = 4
   406  	if n := len(certs[0].Extensions); n != expectedExtensions {
   407  		t.Errorf("want %d extensions, got %d", expectedExtensions, n)
   408  	}
   409  }
   410  
   411  func TestMismatchedSignatureAlgorithm(t *testing.T) {
   412  	der, _ := pem.Decode([]byte(rsaPSSSelfSignedPEM))
   413  	if der == nil {
   414  		t.Fatal("Failed to find PEM block")
   415  	}
   416  
   417  	cert, err := ParseCertificate(der.Bytes)
   418  	if err != nil {
   419  		t.Fatal(err)
   420  	}
   421  
   422  	if err = cert.CheckSignature(ECDSAWithSHA256, nil, nil); err == nil {
   423  		t.Fatal("CheckSignature unexpectedly return no error")
   424  	}
   425  
   426  	const expectedSubstring = " but have public key of type "
   427  	if !strings.Contains(err.Error(), expectedSubstring) {
   428  		t.Errorf("Expected error containing %q, but got %q", expectedSubstring, err)
   429  	}
   430  }
   431  
   432  var certBytes = "308203223082028ba00302010202106edf0d9499fd4533dd1297fc42a93be1300d06092a864886" +
   433  	"f70d0101050500304c310b3009060355040613025a4131253023060355040a131c546861777465" +
   434  	"20436f6e73756c74696e67202850747929204c74642e311630140603550403130d546861777465" +
   435  	"20534743204341301e170d3039303332353136343932395a170d3130303332353136343932395a" +
   436  	"3069310b3009060355040613025553311330110603550408130a43616c69666f726e6961311630" +
   437  	"140603550407130d4d6f756e7461696e205669657731133011060355040a130a476f6f676c6520" +
   438  	"496e63311830160603550403130f6d61696c2e676f6f676c652e636f6d30819f300d06092a8648" +
   439  	"86f70d010101050003818d0030818902818100c5d6f892fccaf5614b064149e80a2c9581a218ef" +
   440  	"41ec35bd7a58125ae76f9ea54ddc893abbeb029f6b73616bf0ffd868791fba7af9c4aebf3706ba" +
   441  	"3eeaeed27435b4ddcfb157c05f351d66aa87fee0de072d66d773affbd36ab78bef090e0cc861a9" +
   442  	"03ac90dd98b51c9c41566c017f0beec3bff391051ffba0f5cc6850ad2a590203010001a381e730" +
   443  	"81e430280603551d250421301f06082b0601050507030106082b06010505070302060960864801" +
   444  	"86f842040130360603551d1f042f302d302ba029a0278625687474703a2f2f63726c2e74686177" +
   445  	"74652e636f6d2f54686177746553474343412e63726c307206082b060105050701010466306430" +
   446  	"2206082b060105050730018616687474703a2f2f6f6373702e7468617774652e636f6d303e0608" +
   447  	"2b060105050730028632687474703a2f2f7777772e7468617774652e636f6d2f7265706f736974" +
   448  	"6f72792f5468617774655f5347435f43412e637274300c0603551d130101ff04023000300d0609" +
   449  	"2a864886f70d01010505000381810062f1f3050ebc105e497c7aedf87e24d2f4a986bb3b837bd1" +
   450  	"9b91ebcad98b065992f6bd2b49b7d6d3cb2e427a99d606c7b1d46352527fac39e6a8b6726de5bf" +
   451  	"70212a52cba07634a5e332011bd1868e78eb5e3c93cf03072276786f207494feaa0ed9d53b2110" +
   452  	"a76571f90209cdae884385c882587030ee15f33d761e2e45a6bc308203233082028ca003020102" +
   453  	"020430000002300d06092a864886f70d0101050500305f310b3009060355040613025553311730" +
   454  	"15060355040a130e566572695369676e2c20496e632e31373035060355040b132e436c61737320" +
   455  	"33205075626c6963205072696d6172792043657274696669636174696f6e20417574686f726974" +
   456  	"79301e170d3034303531333030303030305a170d3134303531323233353935395a304c310b3009" +
   457  	"060355040613025a4131253023060355040a131c54686177746520436f6e73756c74696e672028" +
   458  	"50747929204c74642e311630140603550403130d5468617774652053474320434130819f300d06" +
   459  	"092a864886f70d010101050003818d0030818902818100d4d367d08d157faecd31fe7d1d91a13f" +
   460  	"0b713cacccc864fb63fc324b0794bd6f80ba2fe10493c033fc093323e90b742b71c403c6d2cde2" +
   461  	"2ff50963cdff48a500bfe0e7f388b72d32de9836e60aad007bc4644a3b847503f270927d0e62f5" +
   462  	"21ab693684317590f8bfc76c881b06957cc9e5a8de75a12c7a68dfd5ca1c875860190203010001" +
   463  	"a381fe3081fb30120603551d130101ff040830060101ff020100300b0603551d0f040403020106" +
   464  	"301106096086480186f842010104040302010630280603551d110421301fa41d301b3119301706" +
   465  	"035504031310507269766174654c6162656c332d313530310603551d1f042a30283026a024a022" +
   466  	"8620687474703a2f2f63726c2e766572697369676e2e636f6d2f706361332e63726c303206082b" +
   467  	"0601050507010104263024302206082b060105050730018616687474703a2f2f6f6373702e7468" +
   468  	"617774652e636f6d30340603551d25042d302b06082b0601050507030106082b06010505070302" +
   469  	"06096086480186f8420401060a6086480186f845010801300d06092a864886f70d010105050003" +
   470  	"81810055ac63eadea1ddd2905f9f0bce76be13518f93d9052bc81b774bad6950a1eededcfddb07" +
   471  	"e9e83994dcab72792f06bfab8170c4a8edea5334edef1e53d906c7562bd15cf4d18a8eb42bb137" +
   472  	"9048084225c53e8acb7feb6f04d16dc574a2f7a27c7b603c77cd0ece48027f012fb69b37e02a2a" +
   473  	"36dcd585d6ace53f546f961e05af"
   474  
   475  func parseCIDR(s string) *net.IPNet {
   476  	_, net, err := net.ParseCIDR(s)
   477  	if err != nil {
   478  		panic(err)
   479  	}
   480  	return net
   481  }
   482  
   483  func parseURI(s string) *url.URL {
   484  	uri, err := url.Parse(s)
   485  	if err != nil {
   486  		panic(err)
   487  	}
   488  	return uri
   489  }
   490  
   491  func TestCreateSelfSignedCertificate(t *testing.T) {
   492  	random := rand.Reader
   493  
   494  	ecdsaPriv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
   495  	if err != nil {
   496  		t.Fatalf("Failed to generate ECDSA key: %s", err)
   497  	}
   498  
   499  	tests := []struct {
   500  		name      string
   501  		pub, priv interface{}
   502  		checkSig  bool
   503  		sigAlgo   SignatureAlgorithm
   504  	}{
   505  		{"RSA/RSA", &testPrivateKey.PublicKey, testPrivateKey, true, SHA1WithRSA},
   506  		{"RSA/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   507  		{"ECDSA/RSA", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSA},
   508  		{"ECDSA/ECDSA", &ecdsaPriv.PublicKey, ecdsaPriv, true, ECDSAWithSHA1},
   509  		{"RSAPSS/RSAPSS", &testPrivateKey.PublicKey, testPrivateKey, true, SHA256WithRSAPSS},
   510  		{"ECDSA/RSAPSS", &ecdsaPriv.PublicKey, testPrivateKey, false, SHA256WithRSAPSS},
   511  		{"RSAPSS/ECDSA", &testPrivateKey.PublicKey, ecdsaPriv, false, ECDSAWithSHA384},
   512  	}
   513  
   514  	testExtKeyUsage := []ExtKeyUsage{ExtKeyUsageClientAuth, ExtKeyUsageServerAuth}
   515  	testUnknownExtKeyUsage := []asn1.ObjectIdentifier{[]int{1, 2, 3}, []int{2, 59, 1}}
   516  	extraExtensionData := []byte("extra extension")
   517  
   518  	for _, test := range tests {
   519  		commonName := "test.example.com"
   520  		template := Certificate{
   521  			// SerialNumber is negative to ensure that negative
   522  			// values are parsed. This is due to the prevalence of
   523  			// buggy code that produces certificates with negative
   524  			// serial numbers.
   525  			SerialNumber: big.NewInt(-1),
   526  			Subject: pkix.Name{
   527  				CommonName:   commonName,
   528  				Organization: []string{"Σ Acme Co"},
   529  				Country:      []string{"US"},
   530  				ExtraNames: []pkix.AttributeTypeAndValue{
   531  					{
   532  						Type:  []int{2, 5, 4, 42},
   533  						Value: "Gopher",
   534  					},
   535  					// This should override the Country, above.
   536  					{
   537  						Type:  []int{2, 5, 4, 6},
   538  						Value: "NL",
   539  					},
   540  				},
   541  			},
   542  			NotBefore: time.Unix(1000, 0),
   543  			NotAfter:  time.Unix(100000, 0),
   544  
   545  			SignatureAlgorithm: test.sigAlgo,
   546  
   547  			SubjectKeyId: []byte{1, 2, 3, 4},
   548  			KeyUsage:     KeyUsageCertSign,
   549  
   550  			ExtKeyUsage:        testExtKeyUsage,
   551  			UnknownExtKeyUsage: testUnknownExtKeyUsage,
   552  
   553  			BasicConstraintsValid: true,
   554  			IsCA:                  true,
   555  
   556  			OCSPServer:            []string{"http://ocsp.example.com"},
   557  			IssuingCertificateURL: []string{"http://crt.example.com/ca1.crt"},
   558  
   559  			DNSNames:       []string{"test.example.com"},
   560  			EmailAddresses: []string{"gopher@golang.org"},
   561  			IPAddresses:    []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
   562  			URIs:           []*url.URL{parseURI("https://foo.com/wibble#foo")},
   563  
   564  			PolicyIdentifiers:       []asn1.ObjectIdentifier{[]int{1, 2, 3}},
   565  			PermittedDNSDomains:     []string{".example.com", "example.com"},
   566  			ExcludedDNSDomains:      []string{"bar.example.com"},
   567  			PermittedIPRanges:       []*net.IPNet{parseCIDR("192.168.1.1/16"), parseCIDR("1.2.3.4/8")},
   568  			ExcludedIPRanges:        []*net.IPNet{parseCIDR("2001:db8::/48")},
   569  			PermittedEmailAddresses: []string{"foo@example.com"},
   570  			ExcludedEmailAddresses:  []string{".example.com", "example.com"},
   571  			PermittedURIDomains:     []string{".bar.com", "bar.com"},
   572  			ExcludedURIDomains:      []string{".bar2.com", "bar2.com"},
   573  
   574  			CRLDistributionPoints: []string{"http://crl1.example.com/ca1.crl", "http://crl2.example.com/ca1.crl"},
   575  
   576  			ExtraExtensions: []pkix.Extension{
   577  				{
   578  					Id:    []int{1, 2, 3, 4},
   579  					Value: extraExtensionData,
   580  				},
   581  				// This extension should override the SubjectKeyId, above.
   582  				{
   583  					Id:       oidExtensionSubjectKeyId,
   584  					Critical: false,
   585  					Value:    []byte{0x04, 0x04, 4, 3, 2, 1},
   586  				},
   587  			},
   588  		}
   589  
   590  		derBytes, err := CreateCertificate(random, &template, &template, test.pub, test.priv)
   591  		if err != nil {
   592  			t.Errorf("%s: failed to create certificate: %s", test.name, err)
   593  			continue
   594  		}
   595  
   596  		cert, err := ParseCertificate(derBytes)
   597  		if err != nil {
   598  			t.Errorf("%s: failed to parse certificate: %s", test.name, err)
   599  			continue
   600  		}
   601  
   602  		if len(cert.PolicyIdentifiers) != 1 || !cert.PolicyIdentifiers[0].Equal(template.PolicyIdentifiers[0]) {
   603  			t.Errorf("%s: failed to parse policy identifiers: got:%#v want:%#v", test.name, cert.PolicyIdentifiers, template.PolicyIdentifiers)
   604  		}
   605  
   606  		if len(cert.PermittedDNSDomains) != 2 || cert.PermittedDNSDomains[0] != ".example.com" || cert.PermittedDNSDomains[1] != "example.com" {
   607  			t.Errorf("%s: failed to parse name constraints: %#v", test.name, cert.PermittedDNSDomains)
   608  		}
   609  
   610  		if len(cert.ExcludedDNSDomains) != 1 || cert.ExcludedDNSDomains[0] != "bar.example.com" {
   611  			t.Errorf("%s: failed to parse name constraint exclusions: %#v", test.name, cert.ExcludedDNSDomains)
   612  		}
   613  
   614  		if len(cert.PermittedIPRanges) != 2 || cert.PermittedIPRanges[0].String() != "192.168.0.0/16" || cert.PermittedIPRanges[1].String() != "1.0.0.0/8" {
   615  			t.Errorf("%s: failed to parse IP constraints: %#v", test.name, cert.PermittedIPRanges)
   616  		}
   617  
   618  		if len(cert.ExcludedIPRanges) != 1 || cert.ExcludedIPRanges[0].String() != "2001:db8::/48" {
   619  			t.Errorf("%s: failed to parse IP constraint exclusions: %#v", test.name, cert.ExcludedIPRanges)
   620  		}
   621  
   622  		if len(cert.PermittedEmailAddresses) != 1 || cert.PermittedEmailAddresses[0] != "foo@example.com" {
   623  			t.Errorf("%s: failed to parse permitted email addreses: %#v", test.name, cert.PermittedEmailAddresses)
   624  		}
   625  
   626  		if len(cert.ExcludedEmailAddresses) != 2 || cert.ExcludedEmailAddresses[0] != ".example.com" || cert.ExcludedEmailAddresses[1] != "example.com" {
   627  			t.Errorf("%s: failed to parse excluded email addreses: %#v", test.name, cert.ExcludedEmailAddresses)
   628  		}
   629  
   630  		if len(cert.PermittedURIDomains) != 2 || cert.PermittedURIDomains[0] != ".bar.com" || cert.PermittedURIDomains[1] != "bar.com" {
   631  			t.Errorf("%s: failed to parse permitted URIs: %#v", test.name, cert.PermittedURIDomains)
   632  		}
   633  
   634  		if len(cert.ExcludedURIDomains) != 2 || cert.ExcludedURIDomains[0] != ".bar2.com" || cert.ExcludedURIDomains[1] != "bar2.com" {
   635  			t.Errorf("%s: failed to parse excluded URIs: %#v", test.name, cert.ExcludedURIDomains)
   636  		}
   637  
   638  		if cert.Subject.CommonName != commonName {
   639  			t.Errorf("%s: subject wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Subject.CommonName, commonName)
   640  		}
   641  
   642  		if len(cert.Subject.Country) != 1 || cert.Subject.Country[0] != "NL" {
   643  			t.Errorf("%s: ExtraNames didn't override Country", test.name)
   644  		}
   645  
   646  		for _, ext := range cert.Extensions {
   647  			if ext.Id.Equal(oidExtensionSubjectAltName) {
   648  				if ext.Critical {
   649  					t.Fatal("SAN extension is marked critical")
   650  				}
   651  			}
   652  		}
   653  
   654  		found := false
   655  		for _, atv := range cert.Subject.Names {
   656  			if atv.Type.Equal([]int{2, 5, 4, 42}) {
   657  				found = true
   658  				break
   659  			}
   660  		}
   661  		if !found {
   662  			t.Errorf("%s: Names didn't contain oid 2.5.4.42 from ExtraNames", test.name)
   663  		}
   664  
   665  		if cert.Issuer.CommonName != commonName {
   666  			t.Errorf("%s: issuer wasn't correctly copied from the template. Got %s, want %s", test.name, cert.Issuer.CommonName, commonName)
   667  		}
   668  
   669  		if cert.SignatureAlgorithm != test.sigAlgo {
   670  			t.Errorf("%s: SignatureAlgorithm wasn't copied from template. Got %v, want %v", test.name, cert.SignatureAlgorithm, test.sigAlgo)
   671  		}
   672  
   673  		if !reflect.DeepEqual(cert.ExtKeyUsage, testExtKeyUsage) {
   674  			t.Errorf("%s: extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.ExtKeyUsage, testExtKeyUsage)
   675  		}
   676  
   677  		if !reflect.DeepEqual(cert.UnknownExtKeyUsage, testUnknownExtKeyUsage) {
   678  			t.Errorf("%s: unknown extkeyusage wasn't correctly copied from the template. Got %v, want %v", test.name, cert.UnknownExtKeyUsage, testUnknownExtKeyUsage)
   679  		}
   680  
   681  		if !reflect.DeepEqual(cert.OCSPServer, template.OCSPServer) {
   682  			t.Errorf("%s: OCSP servers differ from template. Got %v, want %v", test.name, cert.OCSPServer, template.OCSPServer)
   683  		}
   684  
   685  		if !reflect.DeepEqual(cert.IssuingCertificateURL, template.IssuingCertificateURL) {
   686  			t.Errorf("%s: Issuing certificate URLs differ from template. Got %v, want %v", test.name, cert.IssuingCertificateURL, template.IssuingCertificateURL)
   687  		}
   688  
   689  		if !reflect.DeepEqual(cert.DNSNames, template.DNSNames) {
   690  			t.Errorf("%s: SAN DNS names differ from template. Got %v, want %v", test.name, cert.DNSNames, template.DNSNames)
   691  		}
   692  
   693  		if !reflect.DeepEqual(cert.EmailAddresses, template.EmailAddresses) {
   694  			t.Errorf("%s: SAN emails differ from template. Got %v, want %v", test.name, cert.EmailAddresses, template.EmailAddresses)
   695  		}
   696  
   697  		if len(cert.URIs) != 1 || cert.URIs[0].String() != "https://foo.com/wibble#foo" {
   698  			t.Errorf("%s: URIs differ from template. Got %v, want %v", test.name, cert.URIs, template.URIs)
   699  		}
   700  
   701  		if !reflect.DeepEqual(cert.IPAddresses, template.IPAddresses) {
   702  			t.Errorf("%s: SAN IPs differ from template. Got %v, want %v", test.name, cert.IPAddresses, template.IPAddresses)
   703  		}
   704  
   705  		if !reflect.DeepEqual(cert.CRLDistributionPoints, template.CRLDistributionPoints) {
   706  			t.Errorf("%s: CRL distribution points differ from template. Got %v, want %v", test.name, cert.CRLDistributionPoints, template.CRLDistributionPoints)
   707  		}
   708  
   709  		if !bytes.Equal(cert.SubjectKeyId, []byte{4, 3, 2, 1}) {
   710  			t.Errorf("%s: ExtraExtensions didn't override SubjectKeyId", test.name)
   711  		}
   712  
   713  		if !bytes.Contains(derBytes, extraExtensionData) {
   714  			t.Errorf("%s: didn't find extra extension in DER output", test.name)
   715  		}
   716  
   717  		if test.checkSig {
   718  			err = cert.CheckSignatureFrom(cert)
   719  			if err != nil {
   720  				t.Errorf("%s: signature verification failed: %s", test.name, err)
   721  			}
   722  		}
   723  	}
   724  }
   725  
   726  // Self-signed certificate using ECDSA with SHA1 & secp256r1
   727  var ecdsaSHA1CertPem = `
   728  -----BEGIN CERTIFICATE-----
   729  MIICDjCCAbUCCQDF6SfN0nsnrjAJBgcqhkjOPQQBMIGPMQswCQYDVQQGEwJVUzET
   730  MBEGA1UECAwKQ2FsaWZvcm5pYTEWMBQGA1UEBwwNTW91bnRhaW4gVmlldzEVMBMG
   731  A1UECgwMR29vZ2xlLCBJbmMuMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   732  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIwMjAyMDUw
   733  WhcNMjIwNTE4MjAyMDUwWjCBjzELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   734  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTATBgNVBAoMDEdvb2dsZSwg
   735  SW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAhBgkqhkiG9w0BCQEWFGdv
   736  bGFuZy1kZXZAZ21haWwuY29tMFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAE/Wgn
   737  WQDo5+bz71T0327ERgd5SDDXFbXLpzIZDXTkjpe8QTEbsF+ezsQfrekrpDPC4Cd3
   738  P9LY0tG+aI8IyVKdUjAJBgcqhkjOPQQBA0gAMEUCIGlsqMcRqWVIWTD6wXwe6Jk2
   739  DKxL46r/FLgJYnzBEH99AiEA3fBouObsvV1R3oVkb4BQYnD4/4LeId6lAT43YvyV
   740  a/A=
   741  -----END CERTIFICATE-----
   742  `
   743  
   744  // Self-signed certificate using ECDSA with SHA256 & secp256r1
   745  var ecdsaSHA256p256CertPem = `
   746  -----BEGIN CERTIFICATE-----
   747  MIICDzCCAbYCCQDlsuMWvgQzhTAKBggqhkjOPQQDAjCBjzELMAkGA1UEBhMCVVMx
   748  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFTAT
   749  BgNVBAoMDEdvb2dsZSwgSW5jLjEXMBUGA1UEAwwOd3d3Lmdvb2dsZS5jb20xIzAh
   750  BgkqhkiG9w0BCQEWFGdvbGFuZy1kZXZAZ21haWwuY29tMB4XDTEyMDUyMTAwMTkx
   751  NloXDTIyMDUxOTAwMTkxNlowgY8xCzAJBgNVBAYTAlVTMRMwEQYDVQQIDApDYWxp
   752  Zm9ybmlhMRYwFAYDVQQHDA1Nb3VudGFpbiBWaWV3MRUwEwYDVQQKDAxHb29nbGUs
   753  IEluYy4xFzAVBgNVBAMMDnd3dy5nb29nbGUuY29tMSMwIQYJKoZIhvcNAQkBFhRn
   754  b2xhbmctZGV2QGdtYWlsLmNvbTBZMBMGByqGSM49AgEGCCqGSM49AwEHA0IABPMt
   755  2ErhxAty5EJRu9yM+MTy+hUXm3pdW1ensAv382KoGExSXAFWP7pjJnNtHO+XSwVm
   756  YNtqjcAGFKpweoN//kQwCgYIKoZIzj0EAwIDRwAwRAIgIYSaUA/IB81gjbIw/hUV
   757  70twxJr5EcgOo0hLp3Jm+EYCIFDO3NNcgmURbJ1kfoS3N/0O+irUtoPw38YoNkqJ
   758  h5wi
   759  -----END CERTIFICATE-----
   760  `
   761  
   762  // Self-signed certificate using ECDSA with SHA256 & secp384r1
   763  var ecdsaSHA256p384CertPem = `
   764  -----BEGIN CERTIFICATE-----
   765  MIICSjCCAdECCQDje/no7mXkVzAKBggqhkjOPQQDAjCBjjELMAkGA1UEBhMCVVMx
   766  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   767  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   768  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMDYxMDM0
   769  WhcNMjIwNTE5MDYxMDM0WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   770  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   771  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   772  YW5nLWRldkBnbWFpbC5jb20wdjAQBgcqhkjOPQIBBgUrgQQAIgNiAARRuzRNIKRK
   773  jIktEmXanNmrTR/q/FaHXLhWRZ6nHWe26Fw7Rsrbk+VjGy4vfWtNn7xSFKrOu5ze
   774  qxKnmE0h5E480MNgrUiRkaGO2GMJJVmxx20aqkXOk59U8yGA4CghE6MwCgYIKoZI
   775  zj0EAwIDZwAwZAIwBZEN8gvmRmfeP/9C1PRLzODIY4JqWub2PLRT4mv9GU+yw3Gr
   776  PU9A3CHMdEcdw/MEAjBBO1lId8KOCh9UZunsSMfqXiVurpzmhWd6VYZ/32G+M+Mh
   777  3yILeYQzllt/g0rKVRk=
   778  -----END CERTIFICATE-----
   779  `
   780  
   781  // Self-signed certificate using ECDSA with SHA384 & secp521r1
   782  var ecdsaSHA384p521CertPem = `
   783  -----BEGIN CERTIFICATE-----
   784  MIICljCCAfcCCQDhp1AFD/ahKjAKBggqhkjOPQQDAzCBjjELMAkGA1UEBhMCVVMx
   785  EzARBgNVBAgMCkNhbGlmb3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDAS
   786  BgNVBAoMC0dvb2dsZSwgSW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEG
   787  CSqGSIb3DQEJARYUZ29sYW5nLWRldkBnbWFpbC5jb20wHhcNMTIwNTIxMTUwNDI5
   788  WhcNMjIwNTE5MTUwNDI5WjCBjjELMAkGA1UEBhMCVVMxEzARBgNVBAgMCkNhbGlm
   789  b3JuaWExFjAUBgNVBAcMDU1vdW50YWluIFZpZXcxFDASBgNVBAoMC0dvb2dsZSwg
   790  SW5jMRcwFQYDVQQDDA53d3cuZ29vZ2xlLmNvbTEjMCEGCSqGSIb3DQEJARYUZ29s
   791  YW5nLWRldkBnbWFpbC5jb20wgZswEAYHKoZIzj0CAQYFK4EEACMDgYYABACqx9Rv
   792  IssRs1LWYcNN+WffwlHw4Tv3y8/LIAA9MF1ZScIonU9nRMxt4a2uGJVCPDw6JHpz
   793  PaYc0E9puLoE9AfKpwFr59Jkot7dBg55SKPEFkddoip/rvmN7NPAWjMBirOwjOkm
   794  8FPthvPhGPqsu9AvgVuHu3PosWiHGNrhh379pva8MzAKBggqhkjOPQQDAwOBjAAw
   795  gYgCQgEHNmswkUdPpHqrVxp9PvLVl+xxPuHBkT+75z9JizyxtqykHQo9Uh6SWCYH
   796  BF9KLolo01wMt8DjoYP5Fb3j5MH7xwJCAbWZzTOp4l4DPkIvAh4LeC4VWbwPPyqh
   797  kBg71w/iEcSY3wUKgHGcJJrObZw7wys91I5kENljqw/Samdr3ka+jBJa
   798  -----END CERTIFICATE-----
   799  `
   800  
   801  var ecdsaTests = []struct {
   802  	sigAlgo SignatureAlgorithm
   803  	pemCert string
   804  }{
   805  	{ECDSAWithSHA1, ecdsaSHA1CertPem},
   806  	{ECDSAWithSHA256, ecdsaSHA256p256CertPem},
   807  	{ECDSAWithSHA256, ecdsaSHA256p384CertPem},
   808  	{ECDSAWithSHA384, ecdsaSHA384p521CertPem},
   809  }
   810  
   811  func TestECDSA(t *testing.T) {
   812  	for i, test := range ecdsaTests {
   813  		pemBlock, _ := pem.Decode([]byte(test.pemCert))
   814  		cert, err := ParseCertificate(pemBlock.Bytes)
   815  		if err != nil {
   816  			t.Errorf("%d: failed to parse certificate: %s", i, err)
   817  			continue
   818  		}
   819  		if sa := cert.SignatureAlgorithm; sa != test.sigAlgo {
   820  			t.Errorf("%d: signature algorithm is %v, want %v", i, sa, test.sigAlgo)
   821  		}
   822  		if parsedKey, ok := cert.PublicKey.(*ecdsa.PublicKey); !ok {
   823  			t.Errorf("%d: wanted an ECDSA public key but found: %#v", i, parsedKey)
   824  		}
   825  		if pka := cert.PublicKeyAlgorithm; pka != ECDSA {
   826  			t.Errorf("%d: public key algorithm is %v, want ECDSA", i, pka)
   827  		}
   828  		if err = cert.CheckSignatureFrom(cert); err != nil {
   829  			t.Errorf("%d: certificate verification failed: %s", i, err)
   830  		}
   831  	}
   832  }
   833  
   834  // Self-signed certificate using DSA with SHA1
   835  var dsaCertPem = `-----BEGIN CERTIFICATE-----
   836  MIIEDTCCA82gAwIBAgIJALHPghaoxeDhMAkGByqGSM44BAMweTELMAkGA1UEBhMC
   837  VVMxCzAJBgNVBAgTAk5DMQ8wDQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2ds
   838  ZSwgSW5jMRIwEAYDVQQDEwlKb24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFs
   839  bGllQGdvb2dsZS5jb20wHhcNMTEwNTE0MDMwMTQ1WhcNMTEwNjEzMDMwMTQ1WjB5
   840  MQswCQYDVQQGEwJVUzELMAkGA1UECBMCTkMxDzANBgNVBAcTBk5ld3RvbjEUMBIG
   841  A1UEChMLR29vZ2xlLCBJbmMxEjAQBgNVBAMTCUpvbiBBbGxpZTEiMCAGCSqGSIb3
   842  DQEJARYTam9uYWxsaWVAZ29vZ2xlLmNvbTCCAbcwggEsBgcqhkjOOAQBMIIBHwKB
   843  gQC8hLUnQ7FpFYu4WXTj6DKvXvz8QrJkNJCVMTpKAT7uBpobk32S5RrPKXocd4gN
   844  8lyGB9ggS03EVlEwXvSmO0DH2MQtke2jl9j1HLydClMf4sbx5V6TV9IFw505U1iW
   845  jL7awRMgxge+FsudtJK254FjMFo03ZnOQ8ZJJ9E6AEDrlwIVAJpnBn9moyP11Ox5
   846  Asc/5dnjb6dPAoGBAJFHd4KVv1iTVCvEG6gGiYop5DJh28hUQcN9kul+2A0yPUSC
   847  X93oN00P8Vh3eYgSaCWZsha7zDG53MrVJ0Zf6v/X/CoZNhLldeNOepivTRAzn+Rz
   848  kKUYy5l1sxYLHQKF0UGNCXfFKZT0PCmgU+PWhYNBBMn6/cIh44vp85ideo5CA4GE
   849  AAKBgFmifCafzeRaohYKXJgMGSEaggCVCRq5xdyDCat+wbOkjC4mfG01/um3G8u5
   850  LxasjlWRKTR/tcAL7t0QuokVyQaYdVypZXNaMtx1db7YBuHjj3aP+8JOQRI9xz8c
   851  bp5NDJ5pISiFOv4p3GZfqZPcqckDt78AtkQrmnal2txhhjF6o4HeMIHbMB0GA1Ud
   852  DgQWBBQVyyr7hO11ZFFpWX50298Sa3V+rzCBqwYDVR0jBIGjMIGggBQVyyr7hO11
   853  ZFFpWX50298Sa3V+r6F9pHsweTELMAkGA1UEBhMCVVMxCzAJBgNVBAgTAk5DMQ8w
   854  DQYDVQQHEwZOZXd0b24xFDASBgNVBAoTC0dvb2dsZSwgSW5jMRIwEAYDVQQDEwlK
   855  b24gQWxsaWUxIjAgBgkqhkiG9w0BCQEWE2pvbmFsbGllQGdvb2dsZS5jb22CCQCx
   856  z4IWqMXg4TAMBgNVHRMEBTADAQH/MAkGByqGSM44BAMDLwAwLAIUPtn/5j8Q1jJI
   857  7ggOIsgrhgUdjGQCFCsmDq1H11q9+9Wp9IMeGrTSKHIM
   858  -----END CERTIFICATE-----
   859  `
   860  
   861  func TestParseCertificateWithDsaPublicKey(t *testing.T) {
   862  	expectedKey := &dsa.PublicKey{
   863  		Parameters: dsa.Parameters{
   864  			P: bigFromHexString("00BC84B52743B169158BB85974E3E832AF5EFCFC42B264349095313A4A013EEE069A1B937D92E51ACF297A1C77880DF25C8607D8204B4DC45651305EF4A63B40C7D8C42D91EDA397D8F51CBC9D0A531FE2C6F1E55E9357D205C39D395358968CBEDAC11320C607BE16CB9DB492B6E78163305A34DD99CE43C64927D13A0040EB97"),
   865  			Q: bigFromHexString("009A67067F66A323F5D4EC7902C73FE5D9E36FA74F"),
   866  			G: bigFromHexString("009147778295BF5893542BC41BA806898A29E43261DBC85441C37D92E97ED80D323D44825FDDE8374D0FF15877798812682599B216BBCC31B9DCCAD527465FEAFFD7FC2A193612E575E34E7A98AF4D10339FE47390A518CB9975B3160B1D0285D1418D0977C52994F43C29A053E3D685834104C9FAFDC221E38BE9F3989D7A8E42"),
   867  		},
   868  		Y: bigFromHexString("59A27C269FCDE45AA2160A5C980C19211A820095091AB9C5DC8309AB7EC1B3A48C2E267C6D35FEE9B71BCBB92F16AC8E559129347FB5C00BEEDD10BA8915C90698755CA965735A32DC7575BED806E1E38F768FFBC24E41123DC73F1C6E9E4D0C9E692128853AFE29DC665FA993DCA9C903B7BF00B6442B9A76A5DADC6186317A"),
   869  	}
   870  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   871  	cert, err := ParseCertificate(pemBlock.Bytes)
   872  	if err != nil {
   873  		t.Fatalf("Failed to parse certificate: %s", err)
   874  	}
   875  	if cert.PublicKeyAlgorithm != DSA {
   876  		t.Errorf("Parsed key algorithm was not DSA")
   877  	}
   878  	parsedKey, ok := cert.PublicKey.(*dsa.PublicKey)
   879  	if !ok {
   880  		t.Fatalf("Parsed key was not a DSA key: %s", err)
   881  	}
   882  	if expectedKey.Y.Cmp(parsedKey.Y) != 0 ||
   883  		expectedKey.P.Cmp(parsedKey.P) != 0 ||
   884  		expectedKey.Q.Cmp(parsedKey.Q) != 0 ||
   885  		expectedKey.G.Cmp(parsedKey.G) != 0 {
   886  		t.Fatal("Parsed key differs from expected key")
   887  	}
   888  }
   889  
   890  func TestParseCertificateWithDSASignatureAlgorithm(t *testing.T) {
   891  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   892  	cert, err := ParseCertificate(pemBlock.Bytes)
   893  	if err != nil {
   894  		t.Fatalf("Failed to parse certificate: %s", err)
   895  	}
   896  	if cert.SignatureAlgorithm != DSAWithSHA1 {
   897  		t.Errorf("Parsed signature algorithm was not DSAWithSHA1")
   898  	}
   899  }
   900  
   901  func TestVerifyCertificateWithDSASignature(t *testing.T) {
   902  	pemBlock, _ := pem.Decode([]byte(dsaCertPem))
   903  	cert, err := ParseCertificate(pemBlock.Bytes)
   904  	if err != nil {
   905  		t.Fatalf("Failed to parse certificate: %s", err)
   906  	}
   907  	// test cert is self-signed
   908  	if err = cert.CheckSignatureFrom(cert); err != nil {
   909  		t.Fatalf("DSA Certificate verification failed: %s", err)
   910  	}
   911  }
   912  
   913  var rsaPSSSelfSignedPEM = `-----BEGIN CERTIFICATE-----
   914  MIIGHjCCA9KgAwIBAgIBdjBBBgkqhkiG9w0BAQowNKAPMA0GCWCGSAFlAwQCAQUA
   915  oRwwGgYJKoZIhvcNAQEIMA0GCWCGSAFlAwQCAQUAogMCASAwbjELMAkGA1UEBhMC
   916  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   917  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   918  U0NBMB4XDTEzMDUxNDA1MDczMFoXDTI5MDUxNDA1MDczMFowbjELMAkGA1UEBhMC
   919  SlAxHDAaBgNVBAoME0phcGFuZXNlIEdvdmVybm1lbnQxKDAmBgNVBAsMH1RoZSBN
   920  aW5pc3RyeSBvZiBGb3JlaWduIEFmZmFpcnMxFzAVBgNVBAMMDmUtcGFzc3BvcnRD
   921  U0NBMIICIjANBgkqhkiG9w0BAQEFAAOCAg8AMIICCgKCAgEAx/E3WRVxcCDXhoST
   922  8nVSLjW6hwM4Ni99AegWzcGtfGFo0zjFA1Cl5URqxauvYu3gQgQHBGA1CovWeGrl
   923  yVSRzOL1imcYsSgLOcnhVYB3Xcrof4ebv9+W+TwNdc9YzAwcj8rNd5nP6PKXIQ+W
   924  PCkEOXdyb80YEnxuT+NPjkVfFSPBS7QYZpvT2fwy4fZ0eh48253+7VleSmTO0mqj
   925  7TlzaG56q150SLZbhpOd8jD8bM/wACnLCPR88wj4hCcDLEwoLyY85HJCTIQQMnoT
   926  UpqyzEeupPREIm6yi4d8C9YqIWFn2YTnRcWcmMaJLzq+kYwKoudfnoC6RW2vzZXn
   927  defQs68IZuK+uALu9G3JWGPgu0CQGj0JNDT8zkiDV++4eNrZczWKjr1YnAL+VbLK
   928  bApwL2u19l2WDpfUklimhWfraqHNIUKU6CjZOG31RzXcplIj0mtqs0E1r7r357Es
   929  yFoB28iNo4cz1lCulh0E4WJzWzLZcT4ZspHHRCFyvYnXoibXEV1nULq8ByKKG0FS
   930  7nn4SseoV+8PvjHLPhmHGMvi4mxkbcXdV3wthHT1/HXdqY84A4xHWt1+sB/TpTek
   931  tDhFlEfcUygvTu58UtOnysomOVVeERmi7WSujfzKsGJAJYeetiA5R+zX7BxeyFVE
   932  qW0zh1Tkwh0S8LRe5diJh4+6FG0CAwEAAaNfMF0wHQYDVR0OBBYEFD+oahaikBTV
   933  Urk81Uz7kRS2sx0aMA4GA1UdDwEB/wQEAwIBBjAYBgNVHSAEETAPMA0GCyqDCIaP
   934  fgYFAQEBMBIGA1UdEwEB/wQIMAYBAf8CAQAwQQYJKoZIhvcNAQEKMDSgDzANBglg
   935  hkgBZQMEAgEFAKEcMBoGCSqGSIb3DQEBCDANBglghkgBZQMEAgEFAKIDAgEgA4IC
   936  AQAaxWBQn5CZuNBfyzL57mn31ukHUFd61OMROSX3PT7oCv1Dy+C2AdRlxOcbN3/n
   937  li0yfXUUqiY3COlLAHKRlkr97mLtxEFoJ0R8nVN2IQdChNQM/XSCzSGyY8NVa1OR
   938  TTpEWLnexJ9kvIdbFXwUqdTnAkOI0m7Rg8j+E+lRRHg1xDAA1qKttrtUj3HRQWf3
   939  kNTu628SiMvap6aIdncburaK56MP7gkR1Wr/ichOfjIA3Jgw2PapI31i0GqeMd66
   940  U1+lC9FeyMAJpuSVp/SoiYzYo+79SFcVoM2yw3yAnIKg7q9GLYYqzncdykT6C06c
   941  15gWFI6igmReAsD9ITSvYh0jLrLHfEYcPTOD3ZXJ4EwwHtWSoO3gq1EAtOYKu/Lv
   942  C8zfBsZcFdsHvsSiYeBU8Oioe42mguky3Ax9O7D805Ek6R68ra07MW/G4YxvV7IN
   943  2BfSaYy8MX9IG0ZMIOcoc0FeF5xkFmJ7kdrlTaJzC0IE9PNxNaH5QnOAFB8vxHcO
   944  FioUxb6UKdHcPLR1VZtAdTdTMjSJxUqD/35Cdfqs7oDJXz8f6TXO2Tdy6G++YUs9
   945  qsGZWxzFvvkXUkQSl0dQQ5jO/FtUJcAVXVVp20LxPemfatAHpW31WdJYeWSQWky2
   946  +f9b5TXKXVyjlUL7uHxowWrT2AtTchDH22wTEtqLEF9Z3Q==
   947  -----END CERTIFICATE-----`
   948  
   949  // openssl req -newkey rsa:2048 -keyout test.key -sha256 -sigopt \
   950  // rsa_padding_mode:pss -sigopt rsa_pss_saltlen:32 -sigopt rsa_mgf1_md:sha256 \
   951  // -x509 -days 3650 -nodes -subj '/C=US/ST=CA/L=SF/O=Test/CN=Test' -out \
   952  // test.pem
   953  var rsaPSSSelfSignedOpenSSL110PEM = `-----BEGIN CERTIFICATE-----
   954  MIIDwDCCAnigAwIBAgIJAM9LAMHTE5xpMD0GCSqGSIb3DQEBCjAwoA0wCwYJYIZI
   955  AWUDBAIBoRowGAYJKoZIhvcNAQEIMAsGCWCGSAFlAwQCAaIDAgEgMEUxCzAJBgNV
   956  BAYTAlVTMQswCQYDVQQIDAJDQTELMAkGA1UEBwwCU0YxDTALBgNVBAoMBFRlc3Qx
   957  DTALBgNVBAMMBFRlc3QwHhcNMTgwMjIyMjIxMzE4WhcNMjgwMjIwMjIxMzE4WjBF
   958  MQswCQYDVQQGEwJVUzELMAkGA1UECAwCQ0ExCzAJBgNVBAcMAlNGMQ0wCwYDVQQK
   959  DARUZXN0MQ0wCwYDVQQDDARUZXN0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB
   960  CgKCAQEA4Zrsydod+GoTAJLLutWNF87qhhVPBsK1zB1Gj+NAAe4+VbrZ1E41H1wp
   961  qITx7DA8DRtJEf+NqrTAnAdZWBG/tAOA5LfXVax0ZSQtLnYLSeylLoMtDyY3eFAj
   962  TmuTOoyVy6raktowCnHCh01NsstqqTfrx6SbmzOmDmKTkq/I+7K0MCVsn41xRDVM
   963  +ShD0WGFGioEGoiWnFSWupxJDA3Q6jIDEygVwNKHwnhv/2NgG2kqZzrZSQA67en0
   964  iKAXtoDNPpmyD5oS9YbEJ+2Nbm7oLeON30i6kZvXKIzJXx+UWViazHZqnsi5rQ8G
   965  RHF+iVFXsqd0MzDKmkKOT5FDhrsbKQIDAQABo1MwUTAdBgNVHQ4EFgQU9uFY/nlg
   966  gLH00NBnr/o7QvpN9ugwHwYDVR0jBBgwFoAU9uFY/nlggLH00NBnr/o7QvpN9ugw
   967  DwYDVR0TAQH/BAUwAwEB/zA9BgkqhkiG9w0BAQowMKANMAsGCWCGSAFlAwQCAaEa
   968  MBgGCSqGSIb3DQEBCDALBglghkgBZQMEAgGiAwIBIAOCAQEAhJzpwxBNGKvzKWDe
   969  WLqv6RMrl/q4GcH3b7M9wjxe0yOm4F+Tb2zJ7re4h+D39YkJf8cX1NV9UQVu6z4s
   970  Fvo2kmlR0qZOXAg5augmCQ1xS0WHFoF6B52anNzHkZQbAIYJ3kGoFsUHzs7Sz7F/
   971  656FsRpHA9UzJQ3avPPMrA4Y4aoJ7ANJ6XIwTrdWrhULOVuvYRLCl4CdTVztVFX6
   972  wxX8nS1ISYd8jXPUMgsBKVbWufvLoIymMJW8CZbpprVZel5zFn0bmPrON8IHS30w
   973  Gs+ITJjKEnZgXmAQ25SLKVzkZkBcGANs2GsdHNJ370Puisy0FIPD2NXR5uASAf7J
   974  +w9fjQ==
   975  -----END CERTIFICATE-----`
   976  
   977  func TestRSAPSSSelfSigned(t *testing.T) {
   978  	for i, pemBlock := range []string{rsaPSSSelfSignedPEM, rsaPSSSelfSignedOpenSSL110PEM} {
   979  		der, _ := pem.Decode([]byte(pemBlock))
   980  		if der == nil {
   981  			t.Errorf("#%d: failed to find PEM block", i)
   982  			continue
   983  		}
   984  
   985  		cert, err := ParseCertificate(der.Bytes)
   986  		if err != nil {
   987  			t.Errorf("#%d: failed to parse: %s", i, err)
   988  			continue
   989  		}
   990  
   991  		if err = cert.CheckSignatureFrom(cert); err != nil {
   992  			t.Errorf("#%d: signature check failed: %s", i, err)
   993  			continue
   994  		}
   995  	}
   996  }
   997  
   998  const pemCertificate = `-----BEGIN CERTIFICATE-----
   999  MIIDATCCAemgAwIBAgIRAKQkkrFx1T/dgB/Go/xBM5swDQYJKoZIhvcNAQELBQAw
  1000  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xNjA4MTcyMDM2MDdaFw0xNzA4MTcyMDM2
  1001  MDdaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1002  ggEKAoIBAQDAoJtjG7M6InsWwIo+l3qq9u+g2rKFXNu9/mZ24XQ8XhV6PUR+5HQ4
  1003  jUFWC58ExYhottqK5zQtKGkw5NuhjowFUgWB/VlNGAUBHtJcWR/062wYrHBYRxJH
  1004  qVXOpYKbIWwFKoXu3hcpg/CkdOlDWGKoZKBCwQwUBhWE7MDhpVdQ+ZljUJWL+FlK
  1005  yQK5iRsJd5TGJ6VUzLzdT4fmN2DzeK6GLeyMpVpU3sWV90JJbxWQ4YrzkKzYhMmB
  1006  EcpXTG2wm+ujiHU/k2p8zlf8Sm7VBM/scmnMFt0ynNXop4FWvJzEm1G0xD2t+e2I
  1007  5Utr04dOZPCgkm++QJgYhtZvgW7ZZiGTAgMBAAGjUjBQMA4GA1UdDwEB/wQEAwIF
  1008  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMBsGA1UdEQQUMBKC
  1009  EHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBADpqKQxrthH5InC7
  1010  X96UP0OJCu/lLEMkrjoEWYIQaFl7uLPxKH5AmQPH4lYwF7u7gksR7owVG9QU9fs6
  1011  1fK7II9CVgCd/4tZ0zm98FmU4D0lHGtPARrrzoZaqVZcAvRnFTlPX5pFkPhVjjai
  1012  /mkxX9LpD8oK1445DFHxK5UjLMmPIIWd8EOi+v5a+hgGwnJpoW7hntSl8kHMtTmy
  1013  fnnktsblSUV4lRCit0ymC7Ojhe+gzCCwkgs5kDzVVag+tnl/0e2DloIjASwOhpbH
  1014  KVcg7fBd484ht/sS+l0dsB4KDOSpd8JzVDMF8OZqlaydizoJO0yWr9GbCN1+OKq5
  1015  EhLrEqU=
  1016  -----END CERTIFICATE-----`
  1017  
  1018  func TestCRLCreation(t *testing.T) {
  1019  	block, _ := pem.Decode([]byte(pemPrivateKey))
  1020  	priv, _ := ParsePKCS1PrivateKey(block.Bytes)
  1021  	block, _ = pem.Decode([]byte(pemCertificate))
  1022  	cert, _ := ParseCertificate(block.Bytes)
  1023  
  1024  	loc := time.FixedZone("Oz/Atlantis", int((2 * time.Hour).Seconds()))
  1025  
  1026  	now := time.Unix(1000, 0).In(loc)
  1027  	nowUTC := now.UTC()
  1028  	expiry := time.Unix(10000, 0)
  1029  
  1030  	revokedCerts := []pkix.RevokedCertificate{
  1031  		{
  1032  			SerialNumber:   big.NewInt(1),
  1033  			RevocationTime: nowUTC,
  1034  		},
  1035  		{
  1036  			SerialNumber: big.NewInt(42),
  1037  			// RevocationTime should be converted to UTC before marshaling.
  1038  			RevocationTime: now,
  1039  		},
  1040  	}
  1041  	expectedCerts := []pkix.RevokedCertificate{
  1042  		{
  1043  			SerialNumber:   big.NewInt(1),
  1044  			RevocationTime: nowUTC,
  1045  		},
  1046  		{
  1047  			SerialNumber:   big.NewInt(42),
  1048  			RevocationTime: nowUTC,
  1049  		},
  1050  	}
  1051  
  1052  	crlBytes, err := cert.CreateCRL(rand.Reader, priv, revokedCerts, now, expiry)
  1053  	if err != nil {
  1054  		t.Errorf("error creating CRL: %s", err)
  1055  	}
  1056  
  1057  	parsedCRL, err := ParseDERCRL(crlBytes)
  1058  	if err != nil {
  1059  		t.Errorf("error reparsing CRL: %s", err)
  1060  	}
  1061  	if !reflect.DeepEqual(parsedCRL.TBSCertList.RevokedCertificates, expectedCerts) {
  1062  		t.Errorf("RevokedCertificates mismatch: got %v; want %v.",
  1063  			parsedCRL.TBSCertList.RevokedCertificates, expectedCerts)
  1064  	}
  1065  }
  1066  
  1067  func fromBase64(in string) []byte {
  1068  	out := make([]byte, base64.StdEncoding.DecodedLen(len(in)))
  1069  	n, err := base64.StdEncoding.Decode(out, []byte(in))
  1070  	if err != nil {
  1071  		panic("failed to base64 decode")
  1072  	}
  1073  	return out[:n]
  1074  }
  1075  
  1076  func TestParseDERCRL(t *testing.T) {
  1077  	derBytes := fromBase64(derCRLBase64)
  1078  	certList, err := ParseDERCRL(derBytes)
  1079  	if err != nil {
  1080  		t.Errorf("error parsing: %s", err)
  1081  		return
  1082  	}
  1083  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1084  	expected := 88
  1085  	if numCerts != expected {
  1086  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1087  	}
  1088  
  1089  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1090  		t.Errorf("CRL has expired (but shouldn't have)")
  1091  	}
  1092  
  1093  	// Can't check the signature here without a package cycle.
  1094  }
  1095  
  1096  func TestCRLWithoutExpiry(t *testing.T) {
  1097  	derBytes := fromBase64("MIHYMIGZMAkGByqGSM44BAMwEjEQMA4GA1UEAxMHQ2FybERTUxcNOTkwODI3MDcwMDAwWjBpMBMCAgDIFw05OTA4MjIwNzAwMDBaMBMCAgDJFw05OTA4MjIwNzAwMDBaMBMCAgDTFw05OTA4MjIwNzAwMDBaMBMCAgDSFw05OTA4MjIwNzAwMDBaMBMCAgDUFw05OTA4MjQwNzAwMDBaMAkGByqGSM44BAMDLwAwLAIUfmVSdjP+NHMX0feW+aDU2G1cfT0CFAJ6W7fVWxjBz4fvftok8yqDnDWh")
  1098  	certList, err := ParseDERCRL(derBytes)
  1099  	if err != nil {
  1100  		t.Fatal(err)
  1101  	}
  1102  	if !certList.TBSCertList.NextUpdate.IsZero() {
  1103  		t.Errorf("NextUpdate is not the zero value")
  1104  	}
  1105  }
  1106  
  1107  func TestParsePEMCRL(t *testing.T) {
  1108  	pemBytes := fromBase64(pemCRLBase64)
  1109  	certList, err := ParseCRL(pemBytes)
  1110  	if err != nil {
  1111  		t.Errorf("error parsing: %s", err)
  1112  		return
  1113  	}
  1114  	numCerts := len(certList.TBSCertList.RevokedCertificates)
  1115  	expected := 2
  1116  	if numCerts != expected {
  1117  		t.Errorf("bad number of revoked certificates. got: %d want: %d", numCerts, expected)
  1118  	}
  1119  
  1120  	if certList.HasExpired(time.Unix(1302517272, 0)) {
  1121  		t.Errorf("CRL has expired (but shouldn't have)")
  1122  	}
  1123  
  1124  	// Can't check the signature here without a package cycle.
  1125  }
  1126  
  1127  func TestImports(t *testing.T) {
  1128  	testenv.MustHaveGoRun(t)
  1129  
  1130  	if err := exec.Command(testenv.GoToolPath(t), "run", "x509_test_import.go").Run(); err != nil {
  1131  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VXdNVFJhb0RBd0xqQWZCZ05WSFNNRUdEQVdnQlQxVERGNlVRTS9MTmVMDQpsNWx2cUhHUXEzZzltekFMQmdOVkhSUUVCQUlDQUlRd0RRWUpLb1pJaHZjTkFRRUZCUUFEZ1lFQUZVNUFzNk16DQpxNVBSc2lmYW9iUVBHaDFhSkx5QytNczVBZ2MwYld5QTNHQWR4dXI1U3BQWmVSV0NCamlQL01FSEJXSkNsQkhQDQpHUmNxNXlJZDNFakRrYUV5eFJhK2k2N0x6dmhJNmMyOUVlNks5cFNZd2ppLzdSVWhtbW5Qclh0VHhsTDBsckxyDQptUVFKNnhoRFJhNUczUUE0Q21VZHNITnZicnpnbUNZcHZWRT0NCi0tLS0tRU5EIFg1MDkgQ1JMLS0tLS0NCg0K"
  1138  
  1139  func TestCreateCertificateRequest(t *testing.T) {
  1140  	random := rand.Reader
  1141  
  1142  	ecdsa256Priv, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
  1143  	if err != nil {
  1144  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1145  	}
  1146  
  1147  	ecdsa384Priv, err := ecdsa.GenerateKey(elliptic.P384(), rand.Reader)
  1148  	if err != nil {
  1149  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1150  	}
  1151  
  1152  	ecdsa521Priv, err := ecdsa.GenerateKey(elliptic.P521(), rand.Reader)
  1153  	if err != nil {
  1154  		t.Fatalf("Failed to generate ECDSA key: %s", err)
  1155  	}
  1156  
  1157  	tests := []struct {
  1158  		name    string
  1159  		priv    interface{}
  1160  		sigAlgo SignatureAlgorithm
  1161  	}{
  1162  		{"RSA", testPrivateKey, SHA1WithRSA},
  1163  		{"ECDSA-256", ecdsa256Priv, ECDSAWithSHA1},
  1164  		{"ECDSA-384", ecdsa384Priv, ECDSAWithSHA1},
  1165  		{"ECDSA-521", ecdsa521Priv, ECDSAWithSHA1},
  1166  	}
  1167  
  1168  	for _, test := range tests {
  1169  		template := CertificateRequest{
  1170  			Subject: pkix.Name{
  1171  				CommonName:   "test.example.com",
  1172  				Organization: []string{"Σ Acme Co"},
  1173  			},
  1174  			SignatureAlgorithm: test.sigAlgo,
  1175  			DNSNames:           []string{"test.example.com"},
  1176  			EmailAddresses:     []string{"gopher@golang.org"},
  1177  			IPAddresses:        []net.IP{net.IPv4(127, 0, 0, 1).To4(), net.ParseIP("2001:4860:0:2001::68")},
  1178  		}
  1179  
  1180  		derBytes, err := CreateCertificateRequest(random, &template, test.priv)
  1181  		if err != nil {
  1182  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
  1183  			continue
  1184  		}
  1185  
  1186  		out, err := ParseCertificateRequest(derBytes)
  1187  		if err != nil {
  1188  			t.Errorf("%s: failed to create certificate request: %s", test.name, err)
  1189  			continue
  1190  		}
  1191  
  1192  		err = out.CheckSignature()
  1193  		if err != nil {
  1194  			t.Errorf("%s: failed to check certificate request signature: %s", test.name, err)
  1195  			continue
  1196  		}
  1197  
  1198  		if out.Subject.CommonName != template.Subject.CommonName {
  1199  			t.Errorf("%s: output subject common name and template subject common name don't match", test.name)
  1200  		} else if len(out.Subject.Organization) != len(template.Subject.Organization) {
  1201  			t.Errorf("%s: output subject organisation and template subject organisation don't match", test.name)
  1202  		} else if len(out.DNSNames) != len(template.DNSNames) {
  1203  			t.Errorf("%s: output DNS names and template DNS names don't match", test.name)
  1204  		} else if len(out.EmailAddresses) != len(template.EmailAddresses) {
  1205  			t.Errorf("%s: output email addresses and template email addresses don't match", test.name)
  1206  		} else if len(out.IPAddresses) != len(template.IPAddresses) {
  1207  			t.Errorf("%s: output IP addresses and template IP addresses names don't match", test.name)
  1208  		}
  1209  	}
  1210  }
  1211  
  1212  func marshalAndParseCSR(t *testing.T, template *CertificateRequest) *CertificateRequest {
  1213  	derBytes, err := CreateCertificateRequest(rand.Reader, template, testPrivateKey)
  1214  	if err != nil {
  1215  		t.Fatal(err)
  1216  	}
  1217  
  1218  	csr, err := ParseCertificateRequest(derBytes)
  1219  	if err != nil {
  1220  		t.Fatal(err)
  1221  	}
  1222  
  1223  	return csr
  1224  }
  1225  
  1226  func TestCertificateRequestOverrides(t *testing.T) {
  1227  	sanContents, err := marshalSANs([]string{"foo.example.com"}, nil, nil, nil)
  1228  	if err != nil {
  1229  		t.Fatal(err)
  1230  	}
  1231  
  1232  	template := CertificateRequest{
  1233  		Subject: pkix.Name{
  1234  			CommonName:   "test.example.com",
  1235  			Organization: []string{"Σ Acme Co"},
  1236  		},
  1237  		DNSNames: []string{"test.example.com"},
  1238  
  1239  		// An explicit extension should override the DNSNames from the
  1240  		// template.
  1241  		ExtraExtensions: []pkix.Extension{
  1242  			{
  1243  				Id:       oidExtensionSubjectAltName,
  1244  				Value:    sanContents,
  1245  				Critical: true,
  1246  			},
  1247  		},
  1248  	}
  1249  
  1250  	csr := marshalAndParseCSR(t, &template)
  1251  
  1252  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo.example.com" {
  1253  		t.Errorf("Extension did not override template. Got %v\n", csr.DNSNames)
  1254  	}
  1255  
  1256  	if len(csr.Extensions) != 1 || !csr.Extensions[0].Id.Equal(oidExtensionSubjectAltName) || !csr.Extensions[0].Critical {
  1257  		t.Errorf("SAN extension was not faithfully copied, got %#v", csr.Extensions)
  1258  	}
  1259  
  1260  	// If there is already an attribute with X.509 extensions then the
  1261  	// extra extensions should be added to it rather than creating a CSR
  1262  	// with two extension attributes.
  1263  
  1264  	template.Attributes = []pkix.AttributeTypeAndValueSET{
  1265  		{
  1266  			Type: oidExtensionRequest,
  1267  			Value: [][]pkix.AttributeTypeAndValue{
  1268  				{
  1269  					{
  1270  						Type:  oidExtensionAuthorityInfoAccess,
  1271  						Value: []byte("foo"),
  1272  					},
  1273  				},
  1274  			},
  1275  		},
  1276  	}
  1277  
  1278  	csr = marshalAndParseCSR(t, &template)
  1279  	if l := len(csr.Attributes); l != 1 {
  1280  		t.Errorf("incorrect number of attributes: %d\n", l)
  1281  	}
  1282  
  1283  	if !csr.Attributes[0].Type.Equal(oidExtensionRequest) ||
  1284  		len(csr.Attributes[0].Value) != 1 ||
  1285  		len(csr.Attributes[0].Value[0]) != 2 {
  1286  		t.Errorf("bad attributes: %#v\n", csr.Attributes)
  1287  	}
  1288  
  1289  	sanContents2, err := marshalSANs([]string{"foo2.example.com"}, nil, nil, nil)
  1290  	if err != nil {
  1291  		t.Fatal(err)
  1292  	}
  1293  
  1294  	// Extensions in Attributes should override those in ExtraExtensions.
  1295  	template.Attributes[0].Value[0] = append(template.Attributes[0].Value[0], pkix.AttributeTypeAndValue{
  1296  		Type:  oidExtensionSubjectAltName,
  1297  		Value: sanContents2,
  1298  	})
  1299  
  1300  	csr = marshalAndParseCSR(t, &template)
  1301  
  1302  	if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "foo2.example.com" {
  1303  		t.Errorf("Attributes did not override ExtraExtensions. Got %v\n", csr.DNSNames)
  1304  	}
  1305  }
  1306  
  1307  func TestParseCertificateRequest(t *testing.T) {
  1308  	for _, csrBase64 := range csrBase64Array {
  1309  		csrBytes := fromBase64(csrBase64)
  1310  		csr, err := ParseCertificateRequest(csrBytes)
  1311  		if err != nil {
  1312  			t.Fatalf("failed to parse CSR: %s", err)
  1313  		}
  1314  
  1315  		if len(csr.EmailAddresses) != 1 || csr.EmailAddresses[0] != "gopher@golang.org" {
  1316  			t.Errorf("incorrect email addresses found: %v", csr.EmailAddresses)
  1317  		}
  1318  
  1319  		if len(csr.DNSNames) != 1 || csr.DNSNames[0] != "test.example.com" {
  1320  			t.Errorf("incorrect DNS names found: %v", csr.DNSNames)
  1321  		}
  1322  
  1323  		if len(csr.Subject.Country) != 1 || csr.Subject.Country[0] != "AU" {
  1324  			t.Errorf("incorrect Subject name: %v", csr.Subject)
  1325  		}
  1326  
  1327  		found := false
  1328  		for _, e := range csr.Extensions {
  1329  			if e.Id.Equal(oidExtensionBasicConstraints) {
  1330  				found = true
  1331  				break
  1332  			}
  1333  		}
  1334  		if !found {
  1335  			t.Errorf("basic constraints extension not found in CSR")
  1336  		}
  1337  	}
  1338  }
  1339  
  1340  func TestCriticalFlagInCSRRequestedExtensions(t *testing.T) {
  1341  	// This CSR contains an extension request where the extensions have a
  1342  	// critical flag in them. In the past we failed to handle this.
  1343  	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="
  1344  
  1345  	csrBytes := fromBase64(csrBase64)
  1346  	csr, err := ParseCertificateRequest(csrBytes)
  1347  	if err != nil {
  1348  		t.Fatalf("failed to parse CSR: %s", err)
  1349  	}
  1350  
  1351  	expected := []struct {
  1352  		Id    asn1.ObjectIdentifier
  1353  		Value []byte
  1354  	}{
  1355  		{oidExtensionBasicConstraints, fromBase64("MAYBAf8CAQA=")},
  1356  		{oidExtensionKeyUsage, fromBase64("AwIChA==")},
  1357  	}
  1358  
  1359  	if n := len(csr.Extensions); n != len(expected) {
  1360  		t.Fatalf("expected to find %d extensions but found %d", len(expected), n)
  1361  	}
  1362  
  1363  	for i, extension := range csr.Extensions {
  1364  		if !extension.Id.Equal(expected[i].Id) {
  1365  			t.Fatalf("extension #%d has unexpected type %v (expected %v)", i, extension.Id, expected[i].Id)
  1366  		}
  1367  
  1368  		if !bytes.Equal(extension.Value, expected[i].Value) {
  1369  			t.Fatalf("extension #%d has unexpected contents %x (expected %x)", i, extension.Value, expected[i].Value)
  1370  		}
  1371  	}
  1372  }
  1373  
  1374  // serialiseAndParse generates a self-signed certificate from template and
  1375  // returns a parsed version of it.
  1376  func serialiseAndParse(t *testing.T, template *Certificate) *Certificate {
  1377  	derBytes, err := CreateCertificate(rand.Reader, template, template, &testPrivateKey.PublicKey, testPrivateKey)
  1378  	if err != nil {
  1379  		t.Fatalf("failed to create certificate: %s", err)
  1380  		return nil
  1381  	}
  1382  
  1383  	cert, err := ParseCertificate(derBytes)
  1384  	if err != nil {
  1385  		t.Fatalf("failed to parse certificate: %s", err)
  1386  		return nil
  1387  	}
  1388  
  1389  	return cert
  1390  }
  1391  
  1392  func TestMaxPathLen(t *testing.T) {
  1393  	template := &Certificate{
  1394  		SerialNumber: big.NewInt(1),
  1395  		Subject: pkix.Name{
  1396  			CommonName: "Σ Acme Co",
  1397  		},
  1398  		NotBefore: time.Unix(1000, 0),
  1399  		NotAfter:  time.Unix(100000, 0),
  1400  
  1401  		BasicConstraintsValid: true,
  1402  		IsCA:                  true,
  1403  	}
  1404  
  1405  	cert1 := serialiseAndParse(t, template)
  1406  	if m := cert1.MaxPathLen; m != -1 {
  1407  		t.Errorf("Omitting MaxPathLen didn't turn into -1, got %d", m)
  1408  	}
  1409  	if cert1.MaxPathLenZero {
  1410  		t.Errorf("Omitting MaxPathLen resulted in MaxPathLenZero")
  1411  	}
  1412  
  1413  	template.MaxPathLen = 1
  1414  	cert2 := serialiseAndParse(t, template)
  1415  	if m := cert2.MaxPathLen; m != 1 {
  1416  		t.Errorf("Setting MaxPathLen didn't work. Got %d but set 1", m)
  1417  	}
  1418  	if cert2.MaxPathLenZero {
  1419  		t.Errorf("Setting MaxPathLen resulted in MaxPathLenZero")
  1420  	}
  1421  
  1422  	template.MaxPathLen = 0
  1423  	template.MaxPathLenZero = true
  1424  	cert3 := serialiseAndParse(t, template)
  1425  	if m := cert3.MaxPathLen; m != 0 {
  1426  		t.Errorf("Setting MaxPathLenZero didn't work, got %d", m)
  1427  	}
  1428  	if !cert3.MaxPathLenZero {
  1429  		t.Errorf("Setting MaxPathLen to zero didn't result in MaxPathLenZero")
  1430  	}
  1431  }
  1432  
  1433  func TestNoAuthorityKeyIdInSelfSignedCert(t *testing.T) {
  1434  	template := &Certificate{
  1435  		SerialNumber: big.NewInt(1),
  1436  		Subject: pkix.Name{
  1437  			CommonName: "Σ Acme Co",
  1438  		},
  1439  		NotBefore: time.Unix(1000, 0),
  1440  		NotAfter:  time.Unix(100000, 0),
  1441  
  1442  		BasicConstraintsValid: true,
  1443  		IsCA:                  true,
  1444  		SubjectKeyId:          []byte{1, 2, 3, 4},
  1445  	}
  1446  
  1447  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) != 0 {
  1448  		t.Fatalf("self-signed certificate contained default authority key id")
  1449  	}
  1450  
  1451  	template.AuthorityKeyId = []byte{1, 2, 3, 4}
  1452  	if cert := serialiseAndParse(t, template); len(cert.AuthorityKeyId) == 0 {
  1453  		t.Fatalf("self-signed certificate erased explicit authority key id")
  1454  	}
  1455  }
  1456  
  1457  func TestASN1BitLength(t *testing.T) {
  1458  	tests := []struct {
  1459  		bytes  []byte
  1460  		bitLen int
  1461  	}{
  1462  		{nil, 0},
  1463  		{[]byte{0x00}, 0},
  1464  		{[]byte{0x00, 0x00}, 0},
  1465  		{[]byte{0xf0}, 4},
  1466  		{[]byte{0x88}, 5},
  1467  		{[]byte{0xff}, 8},
  1468  		{[]byte{0xff, 0x80}, 9},
  1469  		{[]byte{0xff, 0x81}, 16},
  1470  	}
  1471  
  1472  	for i, test := range tests {
  1473  		if got := asn1BitLength(test.bytes); got != test.bitLen {
  1474  			t.Errorf("#%d: calculated bit-length of %d for %x, wanted %d", i, got, test.bytes, test.bitLen)
  1475  		}
  1476  	}
  1477  }
  1478  
  1479  func TestVerifyEmptyCertificate(t *testing.T) {
  1480  	if _, err := new(Certificate).Verify(VerifyOptions{}); err != errNotParsed {
  1481  		t.Errorf("Verifying empty certificate resulted in unexpected error: %q (wanted %q)", err, errNotParsed)
  1482  	}
  1483  }
  1484  
  1485  func TestInsecureAlgorithmErrorString(t *testing.T) {
  1486  	tests := []struct {
  1487  		sa   SignatureAlgorithm
  1488  		want string
  1489  	}{
  1490  		{MD2WithRSA, "x509: cannot verify signature: insecure algorithm MD2-RSA"},
  1491  		{-1, "x509: cannot verify signature: insecure algorithm -1"},
  1492  		{0, "x509: cannot verify signature: insecure algorithm 0"},
  1493  		{9999, "x509: cannot verify signature: insecure algorithm 9999"},
  1494  	}
  1495  	for i, tt := range tests {
  1496  		if got := fmt.Sprint(InsecureAlgorithmError(tt.sa)); got != tt.want {
  1497  			t.Errorf("%d. mismatch.\n got: %s\nwant: %s\n", i, got, tt.want)
  1498  		}
  1499  	}
  1500  }
  1501  
  1502  // These CSR was generated with OpenSSL:
  1503  //  openssl req -out CSR.csr -new -sha256 -nodes -keyout privateKey.key -config openssl.cnf
  1504  //
  1505  // With openssl.cnf containing the following sections:
  1506  //   [ v3_req ]
  1507  //   basicConstraints = CA:FALSE
  1508  //   keyUsage = nonRepudiation, digitalSignature, keyEncipherment
  1509  //   subjectAltName = email:gopher@golang.org,DNS:test.example.com
  1510  //   [ req_attributes ]
  1511  //   challengePassword = ignored challenge
  1512  //   unstructuredName  = ignored unstructured name
  1513  var csrBase64Array = [...]string{
  1514  	// Just [ v3_req ]
  1515  	"MIIDHDCCAgQCAQAwfjELMAkGA1UEBhMCQVUxEzARBgNVBAgMClNvbWUtU3RhdGUxITAfBgNVBAoMGEludGVybmV0IFdpZGdpdHMgUHR5IEx0ZDEUMBIGA1UEAwwLQ29tbW9uIE5hbWUxITAfBgkqhkiG9w0BCQEWEnRlc3RAZW1haWwuYWRkcmVzczCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAK1GY4YFx2ujlZEOJxQVYmsjUnLsd5nFVnNpLE4cV+77sgv9NPNlB8uhn3MXt5leD34rm/2BisCHOifPucYlSrszo2beuKhvwn4+2FxDmWtBEMu/QA16L5IvoOfYZm/gJTsPwKDqvaR0tTU67a9OtxwNTBMI56YKtmwd/o8d3hYv9cg+9ZGAZ/gKONcg/OWYx/XRh6bd0g8DMbCikpWgXKDsvvK1Nk+VtkDO1JxuBaj4Lz/p/MifTfnHoqHxWOWl4EaTs4Ychxsv34/rSj1KD1tJqorIv5Xv2aqv4sjxfbrYzX4kvS5SC1goIovLnhj5UjmQ3Qy8u65eow/LLWw+YFcCAwEAAaBZMFcGCSqGSIb3DQEJDjFKMEgwCQYDVR0TBAIwADALBgNVHQ8EBAMCBeAwLgYDVR0RBCcwJYERZ29waGVyQGdvbGFuZy5vcmeCEHRlc3QuZXhhbXBsZS5jb20wDQYJKoZIhvcNAQELBQADggEBAB6VPMRrchvNW61Tokyq3ZvO6/NoGIbuwUn54q6l5VZW0Ep5Nq8juhegSSnaJ0jrovmUgKDN9vEo2KxuAtwG6udS6Ami3zP+hRd4k9Q8djJPb78nrjzWiindLK5Fps9U5mMoi1ER8ViveyAOTfnZt/jsKUaRsscY2FzE9t9/o5moE6LTcHUS4Ap1eheR+J72WOnQYn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SccOhzUCcZ/G4qcrfhhx6gTZTeA01nP7TdTJURvWAH5iFqj9sQ0qnLq6nEcVHij3sG6M5+BxAIVClQBk6lTCzgphc835Fjj6qSLuJ20XHdL5UfUbiJxx299CHgyBRL+hBUIPfz8p+ZgamyAuDLfnj54zzcRVyLlrmMLNPZNll1Q70RxoU6uWvLH8wB8vQe3Q/guSGubLyLRTUQVPh+dw1L4t8MKFWfX/48jwRM4gIRHFHPeAAE9D9YAoqdIvj/iFm/eQ++7DP8MDwOZWsXeB6jjwHuLmkQ==",
  1518  }
  1519  
  1520  var md5cert = `
  1521  -----BEGIN CERTIFICATE-----
  1522  MIIB4TCCAUoCCQCfmw3vMgPS5TANBgkqhkiG9w0BAQQFADA1MQswCQYDVQQGEwJB
  1523  VTETMBEGA1UECBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wHhcNMTUx
  1524  MjAzMTkyOTMyWhcNMjkwODEyMTkyOTMyWjA1MQswCQYDVQQGEwJBVTETMBEGA1UE
  1525  CBMKU29tZS1TdGF0ZTERMA8GA1UEChMITUQ1IEluYy4wgZ8wDQYJKoZIhvcNAQEB
  1526  BQADgY0AMIGJAoGBANrq2nhLQj5mlXbpVX3QUPhfEm/vdEqPkoWtR/jRZIWm4WGf
  1527  Wpq/LKHJx2Pqwn+t117syN8l4U5unyAi1BJSXjBwPZNd7dXjcuJ+bRLV7FZ/iuvs
  1528  cfYyQQFTxan4TaJMd0x1HoNDbNbjHa02IyjjYE/r3mb/PIg+J2t5AZEh80lPAgMB
  1529  AAEwDQYJKoZIhvcNAQEEBQADgYEAjGzp3K3ey/YfKHohf33yHHWd695HQxDAP+wY
  1530  cs9/TAyLR+gJzJP7d18EcDDLJWVi7bhfa4EAD86di05azOh9kWSn4b3o9QYRGCSw
  1531  GNnI3Zk0cwNKA49hZntKKiy22DhRk7JAHF01d6Bu3KkHkmENrtJ+zj/+159WAnUa
  1532  qViorq4=
  1533  -----END CERTIFICATE-----
  1534  `
  1535  
  1536  func TestMD5(t *testing.T) {
  1537  	pemBlock, _ := pem.Decode([]byte(md5cert))
  1538  	cert, err := ParseCertificate(pemBlock.Bytes)
  1539  	if err != nil {
  1540  		t.Fatalf("failed to parse certificate: %s", err)
  1541  	}
  1542  	if sa := cert.SignatureAlgorithm; sa != MD5WithRSA {
  1543  		t.Errorf("signature algorithm is %v, want %v", sa, MD5WithRSA)
  1544  	}
  1545  	if err = cert.CheckSignatureFrom(cert); err == nil {
  1546  		t.Fatalf("certificate verification succeeded incorrectly")
  1547  	}
  1548  	if _, ok := err.(InsecureAlgorithmError); !ok {
  1549  		t.Fatalf("certificate verification returned %v (%T), wanted InsecureAlgorithmError", err, err)
  1550  	}
  1551  }
  1552  
  1553  // certMissingRSANULL contains an RSA public key where the AlgorithmIdentifer
  1554  // parameters are omitted rather than being an ASN.1 NULL.
  1555  const certMissingRSANULL = `
  1556  -----BEGIN CERTIFICATE-----
  1557  MIIB7TCCAVigAwIBAgIBADALBgkqhkiG9w0BAQUwJjEQMA4GA1UEChMHQWNtZSBD
  1558  bzESMBAGA1UEAxMJMTI3LjAuMC4xMB4XDTExMTIwODA3NTUxMloXDTEyMTIwNzA4
  1559  MDAxMlowJjEQMA4GA1UEChMHQWNtZSBDbzESMBAGA1UEAxMJMTI3LjAuMC4xMIGc
  1560  MAsGCSqGSIb3DQEBAQOBjAAwgYgCgYBO0Hsx44Jk2VnAwoekXh6LczPHY1PfZpIG
  1561  hPZk1Y/kNqcdK+izIDZFI7Xjla7t4PUgnI2V339aEu+H5Fto5OkOdOwEin/ekyfE
  1562  ARl6vfLcPRSr0FTKIQzQTW6HLlzF0rtNS0/Otiz3fojsfNcCkXSmHgwa2uNKWi7e
  1563  E5xMQIhZkwIDAQABozIwMDAOBgNVHQ8BAf8EBAMCAKAwDQYDVR0OBAYEBAECAwQw
  1564  DwYDVR0jBAgwBoAEAQIDBDALBgkqhkiG9w0BAQUDgYEANh+zegx1yW43RmEr1b3A
  1565  p0vMRpqBWHyFeSnIyMZn3TJWRSt1tukkqVCavh9a+hoV2cxVlXIWg7nCto/9iIw4
  1566  hB2rXZIxE0/9gzvGnfERYraL7KtnvshksBFQRlgXa5kc0x38BvEO5ZaoDPl4ILdE
  1567  GFGNEH5PlGffo05wc46QkYU=
  1568  -----END CERTIFICATE-----`
  1569  
  1570  func TestRSAMissingNULLParameters(t *testing.T) {
  1571  	block, _ := pem.Decode([]byte(certMissingRSANULL))
  1572  	if _, err := ParseCertificate(block.Bytes); err == nil {
  1573  		t.Error("unexpected success when parsing certificate with missing RSA NULL parameter")
  1574  	} else if !strings.Contains(err.Error(), "missing NULL") {
  1575  		t.Errorf("unrecognised error when parsing certificate with missing RSA NULL parameter: %s", err)
  1576  	}
  1577  }
  1578  
  1579  const certISOOID = `
  1580  -----BEGIN CERTIFICATE-----
  1581  MIIB5TCCAVKgAwIBAgIQtwyL3RPWV7dJQp34HwZG9DAJBgUrDgMCHQUAMBExDzAN
  1582  BgNVBAMTBm15dGVzdDAeFw0xNjA4MDkyMjExMDVaFw0zOTEyMzEyMzU5NTlaMBEx
  1583  DzANBgNVBAMTBm15dGVzdDCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEArzIH
  1584  GsyDB3ohIGkkvijF2PTRUX1bvOtY1eUUpjwHyu0twpAKSuaQv2Ha+/63+aHe8O86
  1585  BT+98wjXFX6RFSagtAujo80rIF2dSm33BGt18pDN8v6zp93dnAm0jRaSQrHJ75xw
  1586  5O+S1oEYR1LtUoFJy6qB104j6aINBAgOiLIKiMkCAwEAAaNGMEQwQgYDVR0BBDsw
  1587  OYAQVuYVQ/WDjdGSkZRlTtJDNKETMBExDzANBgNVBAMTBm15dGVzdIIQtwyL3RPW
  1588  V7dJQp34HwZG9DAJBgUrDgMCHQUAA4GBABngrSkH7vG5lY4sa4AZF59lAAXqBVJE
  1589  J4TBiKC62hCdZv18rBleP6ETfhbPg7pTs8p4ebQbpmtNxRS9Lw3MzQ8Ya5Ybwzj2
  1590  NwBSyCtCQl7mrEg4nJqJl4A2EUhnET/oVxU0oTV/SZ3ziGXcY1oG1s6vidV7TZTu
  1591  MCRtdSdaM7g3
  1592  -----END CERTIFICATE-----`
  1593  
  1594  func TestISOOIDInCertificate(t *testing.T) {
  1595  	block, _ := pem.Decode([]byte(certISOOID))
  1596  	if cert, err := ParseCertificate(block.Bytes); err != nil {
  1597  		t.Errorf("certificate with ISO OID failed to parse: %s", err)
  1598  	} else if cert.SignatureAlgorithm == UnknownSignatureAlgorithm {
  1599  		t.Errorf("ISO OID not recognised in certificate")
  1600  	}
  1601  }
  1602  
  1603  // certMultipleRDN contains a RelativeDistinguishedName with two elements (the
  1604  // common name and serial number). This particular certificate was the first
  1605  // such certificate in the “Pilot” Certificate Transparency log.
  1606  const certMultipleRDN = `
  1607  -----BEGIN CERTIFICATE-----
  1608  MIIFRzCCBC+gAwIBAgIEOl59NTANBgkqhkiG9w0BAQUFADA9MQswCQYDVQQGEwJz
  1609  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMREwDwYDVQQLEwhzaWdvdi1j
  1610  YTAeFw0xMjExMTYxMDUyNTdaFw0xNzExMTYxMjQ5MDVaMIGLMQswCQYDVQQGEwJz
  1611  aTEbMBkGA1UEChMSc3RhdGUtaW5zdGl0dXRpb25zMRkwFwYDVQQLExB3ZWItY2Vy
  1612  dGlmaWNhdGVzMRAwDgYDVQQLEwdTZXJ2ZXJzMTIwFAYDVQQFEw0xMjM2NDg0MDEw
  1613  MDEwMBoGA1UEAxMTZXBvcnRhbC5tc3MuZWR1cy5zaTCCASIwDQYJKoZIhvcNAQEB
  1614  BQADggEPADCCAQoCggEBAMrNkZH9MPuBTjMGNk3sJX8V+CkFx/4ru7RTlLS6dlYM
  1615  098dtSfJ3s2w0p/1NB9UmR8j0yS0Kg6yoZ3ShsSO4DWBtcQD8820a6BYwqxxQTNf
  1616  HSRZOc+N/4TQrvmK6t4k9Aw+YEYTMrWOU4UTeyhDeCcUsBdh7HjfWsVaqNky+2s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va/CzGgZh+CES0aWCPy+4Gb8lwOTt+854/laaJvd6kgKTER7z7U9
  1633  9C86Ch2y4sXNwwwPJ1A9dmrZJZOcJjS/WYZgwaafY2Hdxub5jqPE5nehwYUPVu9R
  1634  uH6/skk4OEKcfOtN0hCnISOVuKYyS4ANARWRG5VGHIH06z3lGUVARFRJ61gtAprd
  1635  La+fgSS+LVZ+kU2TkeoWAKvGq8MAgDq4D4Xqwekg7WKFeuyusi/NI5rm40XgjBMF
  1636  DF72IUofoVt7wo0=
  1637  -----END CERTIFICATE-----`
  1638  
  1639  func TestMultipleRDN(t *testing.T) {
  1640  	block, _ := pem.Decode([]byte(certMultipleRDN))
  1641  	cert, err := ParseCertificate(block.Bytes)
  1642  	if err != nil {
  1643  		t.Fatalf("certificate with two elements in an RDN failed to parse: %v", err)
  1644  	}
  1645  
  1646  	if want := "eportal.mss.edus.si"; cert.Subject.CommonName != want {
  1647  		t.Errorf("got common name of %q, but want %q", cert.Subject.CommonName, want)
  1648  	}
  1649  
  1650  	if want := "1236484010010"; cert.Subject.SerialNumber != want {
  1651  		t.Errorf("got serial number of %q, but want %q", cert.Subject.SerialNumber, want)
  1652  	}
  1653  }
  1654  
  1655  func TestSystemCertPool(t *testing.T) {
  1656  	if runtime.GOOS == "windows" {
  1657  		t.Skip("not implemented on Windows; Issue 16736, 18609")
  1658  	}
  1659  	a, err := SystemCertPool()
  1660  	if err != nil {
  1661  		t.Fatal(err)
  1662  	}
  1663  	b, err := SystemCertPool()
  1664  	if err != nil {
  1665  		t.Fatal(err)
  1666  	}
  1667  	if !reflect.DeepEqual(a, b) {
  1668  		t.Fatal("two calls to SystemCertPool had different results")
  1669  	}
  1670  	if ok := b.AppendCertsFromPEM([]byte(`
  1671  -----BEGIN CERTIFICATE-----
  1672  MIIDBjCCAe6gAwIBAgIRANXM5I3gjuqDfTp/PYrs+u8wDQYJKoZIhvcNAQELBQAw
  1673  EjEQMA4GA1UEChMHQWNtZSBDbzAeFw0xODAzMjcxOTU2MjFaFw0xOTAzMjcxOTU2
  1674  MjFaMBIxEDAOBgNVBAoTB0FjbWUgQ28wggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1675  ggEKAoIBAQDK+9m3rjsO2Djes6bIYQZ3eV29JF09ZrjOrEHLtaKrD6/acsoSoTsf
  1676  cQr+rzzztdB5ijWXCS64zo/0OiqBeZUNZ67jVdToa9qW5UYe2H0Y+ZNdfA5GYMFD
  1677  yk/l3/uBu3suTZPfXiW2TjEi27Q8ruNUIZ54DpTcs6y2rBRFzadPWwn/VQMlvRXM
  1678  jrzl8Y08dgnYmaAHprxVzwMXcQ/Brol+v9GvjaH1DooHqkn8O178wsPQNhdtvN01
  1679  IXL46cYdcUwWrE/GX5u+9DaSi+0KWxAPQ+NVD5qUI0CKl4714yGGh7feXMjJdHgl
  1680  VG4QJZlJvC4FsURgCHJT6uHGIelnSwhbAgMBAAGjVzBVMA4GA1UdDwEB/wQEAwIF
  1681  oDATBgNVHSUEDDAKBggrBgEFBQcDATAMBgNVHRMBAf8EAjAAMCAGA1UdEQQZMBeC
  1682  FVRlc3RTeXN0ZW1DZXJ0UG9vbC5nbzANBgkqhkiG9w0BAQsFAAOCAQEAwuSRx/VR
  1683  BKh2ICxZjL6jBwk/7UlU1XKbhQD96RqkidDNGEc6eLZ90Z5XXTurEsXqdm5jQYPs
  1684  1cdcSW+fOSMl7MfW9e5tM66FaIPZl9rKZ1r7GkOfgn93xdLAWe8XHd19xRfDreub
  1685  YC8DVqgLASOEYFupVSl76ktPfxkU5KCvmUf3P2PrRybk1qLGFytGxfyice2gHSNI
  1686  gify3K/+H/7wCkyFW4xYvzl7WW4mXxoqPRPjQt1J423DhnnQ4G1P8V/vhUpXNXOq
  1687  N9IEPnWuihC09cyx/WMQIUlWnaQLHdfpPS04Iez3yy2PdfXJzwfPrja7rNE+skK6
  1688  pa/O1nF0AfWOpw==
  1689  -----END CERTIFICATE-----
  1690  	`)); !ok {
  1691  		t.Fatal("AppendCertsFromPEM failed")
  1692  	}
  1693  	if reflect.DeepEqual(a, b) {
  1694  		t.Fatal("changing one pool modified the other")
  1695  	}
  1696  }
  1697  
  1698  const emptyNameConstraintsPEM = `
  1699  -----BEGIN CERTIFICATE-----
  1700  MIIC1jCCAb6gAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  1701  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  1702  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  1703  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  1704  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  1705  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  1706  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  1707  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  1708  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  1709  AQABoxEwDzANBgNVHR4EBjAEoAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMH
  1710  QhP8uNCtgSHyim/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb
  1711  6L+iJa4ElREJOi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6H
  1712  v5SsvpYW+1XleYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6M
  1713  LYPmRhTioROA/drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOga
  1714  nCOSyFYfGhqOANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8
  1715  o+WoY6IsCKXV/g==
  1716  -----END CERTIFICATE-----`
  1717  
  1718  func TestEmptyNameConstraints(t *testing.T) {
  1719  	block, _ := pem.Decode([]byte(emptyNameConstraintsPEM))
  1720  	_, err := ParseCertificate(block.Bytes)
  1721  	if err == nil {
  1722  		t.Fatal("unexpected success")
  1723  	}
  1724  
  1725  	const expected = "empty name constraints"
  1726  	if str := err.Error(); !strings.Contains(str, expected) {
  1727  		t.Errorf("expected %q in error but got %q", expected, str)
  1728  	}
  1729  }
  1730  
  1731  func TestPKIXNameString(t *testing.T) {
  1732  	pem, err := hex.DecodeString(certBytes)
  1733  	if err != nil {
  1734  		t.Fatal(err)
  1735  	}
  1736  	certs, err := ParseCertificates(pem)
  1737  	if err != nil {
  1738  		t.Fatal(err)
  1739  	}
  1740  
  1741  	tests := []struct {
  1742  		dn   pkix.Name
  1743  		want string
  1744  	}{
  1745  		{pkix.Name{
  1746  			CommonName:         "Steve Kille",
  1747  			Organization:       []string{"Isode Limited"},
  1748  			OrganizationalUnit: []string{"RFCs"},
  1749  			Locality:           []string{"Richmond"},
  1750  			Province:           []string{"Surrey"},
  1751  			StreetAddress:      []string{"The Square"},
  1752  			PostalCode:         []string{"TW9 1DT"},
  1753  			SerialNumber:       "RFC 2253",
  1754  			Country:            []string{"GB"},
  1755  		}, "SERIALNUMBER=RFC 2253,CN=Steve Kille,OU=RFCs,O=Isode Limited,POSTALCODE=TW9 1DT,STREET=The Square,L=Richmond,ST=Surrey,C=GB"},
  1756  		{certs[0].Subject,
  1757  			"CN=mail.google.com,O=Google Inc,L=Mountain View,ST=California,C=US"},
  1758  		{pkix.Name{
  1759  			Organization: []string{"#Google, Inc. \n-> 'Alphabet\" "},
  1760  			Country:      []string{"US"},
  1761  		}, "O=\\#Google\\, Inc. \n-\\> 'Alphabet\\\"\\ ,C=US"},
  1762  		{pkix.Name{
  1763  			CommonName:   "foo.com",
  1764  			Organization: []string{"Gopher Industries"},
  1765  			ExtraNames: []pkix.AttributeTypeAndValue{
  1766  				{Type: asn1.ObjectIdentifier([]int{2, 5, 4, 3}), Value: "bar.com"}},
  1767  		}, "CN=bar.com,O=Gopher Industries"},
  1768  		{pkix.Name{
  1769  			Locality: []string{"Gophertown"},
  1770  			ExtraNames: []pkix.AttributeTypeAndValue{
  1771  				{Type: asn1.ObjectIdentifier([]int{1, 2, 3, 4, 5}), Value: "golang.org"}},
  1772  		}, "1.2.3.4.5=#130a676f6c616e672e6f7267,L=Gophertown"},
  1773  	}
  1774  
  1775  	for i, test := range tests {
  1776  		if got := test.dn.String(); got != test.want {
  1777  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  1778  		}
  1779  	}
  1780  }
  1781  
  1782  func TestRDNSequenceString(t *testing.T) {
  1783  	// Test some extra cases that get lost in pkix.Name conversions such as
  1784  	// multi-valued attributes.
  1785  
  1786  	var (
  1787  		oidCountry            = []int{2, 5, 4, 6}
  1788  		oidOrganization       = []int{2, 5, 4, 10}
  1789  		oidOrganizationalUnit = []int{2, 5, 4, 11}
  1790  		oidCommonName         = []int{2, 5, 4, 3}
  1791  	)
  1792  
  1793  	tests := []struct {
  1794  		seq  pkix.RDNSequence
  1795  		want string
  1796  	}{
  1797  		{
  1798  			seq: pkix.RDNSequence{
  1799  				pkix.RelativeDistinguishedNameSET{
  1800  					pkix.AttributeTypeAndValue{Type: oidCountry, Value: "US"},
  1801  				},
  1802  				pkix.RelativeDistinguishedNameSET{
  1803  					pkix.AttributeTypeAndValue{Type: oidOrganization, Value: "Widget Inc."},
  1804  				},
  1805  				pkix.RelativeDistinguishedNameSET{
  1806  					pkix.AttributeTypeAndValue{Type: oidOrganizationalUnit, Value: "Sales"},
  1807  					pkix.AttributeTypeAndValue{Type: oidCommonName, Value: "J. Smith"},
  1808  				},
  1809  			},
  1810  			want: "OU=Sales+CN=J. Smith,O=Widget Inc.,C=US",
  1811  		},
  1812  	}
  1813  
  1814  	for i, test := range tests {
  1815  		if got := test.seq.String(); got != test.want {
  1816  			t.Errorf("#%d: String() = \n%s\n, want \n%s", i, got, test.want)
  1817  		}
  1818  	}
  1819  }
  1820  
  1821  const criticalNameConstraintWithUnknownTypePEM = `
  1822  -----BEGIN CERTIFICATE-----
  1823  MIIC/TCCAeWgAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwKDEmMCQGA1UEAxMdRW1w
  1824  dHkgbmFtZSBjb25zdHJhaW50cyBpc3N1ZXIwHhcNMTMwMjAxMDAwMDAwWhcNMjAw
  1825  NTMwMTA0ODM4WjAhMR8wHQYDVQQDExZFbXB0eSBuYW1lIGNvbnN0cmFpbnRzMIIB
  1826  IjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwriElUIt3LCqmJObs+yDoWPD
  1827  F5IqgWk6moIobYjPfextZiYU6I3EfvAwoNxPDkN2WowcocUZMJbEeEq5ebBksFnx
  1828  f12gBxlIViIYwZAzu7aFvhDMyPKQI3C8CG0ZSC9ABZ1E3umdA3CEueNOmP/TChNq
  1829  Cl23+BG1Qb/PJkpAO+GfpWSVhTcV53Mf/cKvFHcjGNrxzdSoq9fyW7a6gfcGEQY0
  1830  LVkmwFWUfJ0wT8kaeLr0E0tozkIfo01KNWNzv6NcYP80QOBRDlApWu9ODmEVJHPD
  1831  blx4jzTQ3JLa+4DvBNOjVUOp+mgRmjiW0rLdrxwOxIqIOwNjweMCp/hgxX/hTQID
  1832  AQABozgwNjA0BgNVHR4BAf8EKjAooCQwIokgIACrzQAAAAAAAAAAAAAAAP////8A
  1833  AAAAAAAAAAAAAAChADANBgkqhkiG9w0BAQsFAAOCAQEAWG+/zUMHQhP8uNCtgSHy
  1834  im/vh7wminwAvWgMKxlkLBFns6nZeQqsOV1lABY7U0Zuoqa1Z5nb6L+iJa4ElREJ
  1835  Oi/erLc9uLwBdDCAR0hUTKD7a6i4ooS39DTle87cUnj0MW1CUa6Hv5SsvpYW+1Xl
  1836  eYJk/axQOOTcy4Es53dvnZsjXH0EA/QHnn7UV+JmlE3rtVxcYp6MLYPmRhTioROA
  1837  /drghicRkiu9hxdPyxkYS16M5g3Zj30jdm+k/6C6PeNtN9YmOOganCOSyFYfGhqO
  1838  ANYzpmuV+oIedAsPpIbfIzN8njYUs1zio+1IoI4o8ddM9sCbtPU8o+WoY6IsCKXV
  1839  /g==
  1840  -----END CERTIFICATE-----`
  1841  
  1842  func TestCriticalNameConstraintWithUnknownType(t *testing.T) {
  1843  	block, _ := pem.Decode([]byte(criticalNameConstraintWithUnknownTypePEM))
  1844  	cert, err := ParseCertificate(block.Bytes)
  1845  	if err != nil {
  1846  		t.Fatalf("unexpected parsing failure: %s", err)
  1847  	}
  1848  
  1849  	if l := len(cert.UnhandledCriticalExtensions); l != 1 {
  1850  		t.Fatalf("expected one unhandled critical extension, but found %d", l)
  1851  	}
  1852  }
  1853  
  1854  const badIPMaskPEM = `
  1855  -----BEGIN CERTIFICATE-----
  1856  MIICzzCCAbegAwIBAgICEjQwDQYJKoZIhvcNAQELBQAwHTEbMBkGA1UEAxMSQmFk
  1857  IElQIG1hc2sgaXNzdWVyMB4XDTEzMDIwMTAwMDAwMFoXDTIwMDUzMDEwNDgzOFow
  1858  FjEUMBIGA1UEAxMLQmFkIElQIG1hc2swggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw
  1859  ggEKAoIBAQDCuISVQi3csKqYk5uz7IOhY8MXkiqBaTqagihtiM997G1mJhTojcR+
  1860  8DCg3E8OQ3ZajByhxRkwlsR4Srl5sGSwWfF/XaAHGUhWIhjBkDO7toW+EMzI8pAj
  1861  cLwIbRlIL0AFnUTe6Z0DcIS5406Y/9MKE2oKXbf4EbVBv88mSkA74Z+lZJWFNxXn
  1862  cx/9wq8UdyMY2vHN1Kir1/JbtrqB9wYRBjQtWSbAVZR8nTBPyRp4uvQTS2jOQh+j
  1863  TUo1Y3O/o1xg/zRA4FEOUCla704OYRUkc8NuXHiPNNDcktr7gO8E06NVQ6n6aBGa
  1864  OJbSst2vHA7Eiog7A2PB4wKn+GDFf+FNAgMBAAGjIDAeMBwGA1UdHgEB/wQSMBCg
  1865  DDAKhwgBAgME//8BAKEAMA0GCSqGSIb3DQEBCwUAA4IBAQBYb7/NQwdCE/y40K2B
  1866  IfKKb++HvCaKfAC9aAwrGWQsEWezqdl5Cqw5XWUAFjtTRm6iprVnmdvov6IlrgSV
  1867  EQk6L96stz24vAF0MIBHSFRMoPtrqLiihLf0NOV7ztxSePQxbUJRroe/lKy+lhb7
  1868  VeV5gmT9rFA45NzLgSznd2+dmyNcfQQD9AeeftRX4maUTeu1XFxinowtg+ZGFOKh
  1869  E4D92uCGJxGSK72HF0/LGRhLXozmDdmPfSN2b6T/oLo942031iY46BqcI5LIVh8a
  1870  Go4A1jOma5X6gh50Cw+kht8jM3yeNhSzXOKj7Uigjijx10z2wJu09Tyj5ahjoiwI
  1871  pdX+
  1872  -----END CERTIFICATE-----`
  1873  
  1874  func TestBadIPMask(t *testing.T) {
  1875  	block, _ := pem.Decode([]byte(badIPMaskPEM))
  1876  	_, err := ParseCertificate(block.Bytes)
  1877  	if err == nil {
  1878  		t.Fatalf("unexpected success")
  1879  	}
  1880  
  1881  	const expected = "contained invalid mask"
  1882  	if !strings.Contains(err.Error(), expected) {
  1883  		t.Fatalf("expected %q in error but got: %s", expected, err)
  1884  	}
  1885  }
  1886  
  1887  const additionalGeneralSubtreePEM = `
  1888  -----BEGIN CERTIFICATE-----
  1889  MIIG4TCCBMmgAwIBAgIRALss+4rLw2Ia7tFFhxE8g5cwDQYJKoZIhvcNAQELBQAw
  1890  bjELMAkGA1UEBhMCTkwxIDAeBgNVBAoMF01pbmlzdGVyaWUgdmFuIERlZmVuc2ll
  1891  MT0wOwYDVQQDDDRNaW5pc3RlcmllIHZhbiBEZWZlbnNpZSBDZXJ0aWZpY2F0aWUg
  1892  QXV0b3JpdGVpdCAtIEcyMB4XDTEzMDMwNjEyMDM0OVoXDTEzMTEzMDEyMDM1MFow
  1893  bDELMAkGA1UEBhMCVVMxFjAUBgNVBAoTDUNlcnRpUGF0aCBMTEMxIjAgBgNVBAsT
  1894  GUNlcnRpZmljYXRpb24gQXV0aG9yaXRpZXMxITAfBgNVBAMTGENlcnRpUGF0aCBC
  1895  cmlkZ2UgQ0EgLSBHMjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBANLW
  1896  4kXiRqvwBhJfN9uz12FA+P2D34MPxOt7TGXljm2plJ2CLzvaH8/ymsMdSWdJBS1M
  1897  8FmwvNL1w3A6ZuzksJjPikAu8kY3dcp3mrkk9eCPORDAwGtfsXwZysLiuEaDWpbD
  1898  dHOaHnI6qWU0N6OI+hNX58EjDpIGC1WQdho1tHOTPc5Hf5/hOpM/29v/wr7kySjs
  1899  Z+7nsvkm5rNhuJNzPsLsgzVaJ5/BVyOplZy24FKM8Y43MjR4osZm+a2e0zniqw6/
  1900  rvcjcGYabYaznZfQG1GXoyf2Vea+CCgpgUhlVafgkwEs8izl8rIpvBzXiFAgFQuG
  1901  Ituoy92PJbDs430fA/cCAwEAAaOCAnowggJ2MEUGCCsGAQUFBwEBBDkwNzA1Bggr
  1902  BgEFBQcwAoYpaHR0cDovL2NlcnRzLmNhLm1pbmRlZi5ubC9taW5kZWYtY2EtMi5w
  1903  N2MwHwYDVR0jBBgwFoAUzln9WSPz2M64Rl2HYf2/KD8StmQwDwYDVR0TAQH/BAUw
  1904  AwEB/zCB6QYDVR0gBIHhMIHeMEgGCmCEEAGHawECBQEwOjA4BggrBgEFBQcCARYs
  1905  aHR0cDovL2Nwcy5kcC5jYS5taW5kZWYubmwvbWluZGVmLWNhLWRwLWNwcy8wSAYK
  1906  YIQQAYdrAQIFAjA6MDgGCCsGAQUFBwIBFixodHRwOi8vY3BzLmRwLmNhLm1pbmRl
  1907  Zi5ubC9taW5kZWYtY2EtZHAtY3BzLzBIBgpghBABh2sBAgUDMDowOAYIKwYBBQUH
  1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Zr6Z6Ib8CECgTehU4QvepkgDXNoNrKRZBG0JhLjkwxh2whZq
  1924  nvWBfALC2VuNOM6C0rDY+HmhMlVt0XeqnybD9MuQALMit7Z00Cw2CIjNsBI9xBqD
  1925  xKK9CjUb7gzRUWSpB9jGHsvpEMHOzIFhufvH2Bz1XJw+Cl7khw==
  1926  -----END CERTIFICATE-----`
  1927  
  1928  func TestAdditionFieldsInGeneralSubtree(t *testing.T) {
  1929  	// Very rarely, certificates can include additional fields in the
  1930  	// GeneralSubtree structure. This tests that such certificates can be
  1931  	// parsed.
  1932  	block, _ := pem.Decode([]byte(additionalGeneralSubtreePEM))
  1933  	if _, err := ParseCertificate(block.Bytes); err != nil {
  1934  		t.Fatalf("failed to parse certificate: %s", err)
  1935  	}
  1936  }
  1937  
  1938  func TestEmptySubject(t *testing.T) {
  1939  	template := Certificate{
  1940  		SerialNumber: big.NewInt(1),
  1941  		DNSNames:     []string{"example.com"},
  1942  	}
  1943  
  1944  	derBytes, err := CreateCertificate(rand.Reader, &template, &template, &testPrivateKey.PublicKey, testPrivateKey)
  1945  	if err != nil {
  1946  		t.Fatalf("failed to create certificate: %s", err)
  1947  	}
  1948  
  1949  	cert, err := ParseCertificate(derBytes)
  1950  	if err != nil {
  1951  		t.Fatalf("failed to parse certificate: %s", err)
  1952  	}
  1953  
  1954  	for _, ext := range cert.Extensions {
  1955  		if ext.Id.Equal(oidExtensionSubjectAltName) {
  1956  			if !ext.Critical {
  1957  				t.Fatal("SAN extension is not critical")
  1958  			}
  1959  			return
  1960  		}
  1961  	}
  1962  
  1963  	t.Fatal("SAN extension is missing")
  1964  }
  1965  
  1966  // multipleURLsInCRLDPPEM contains two URLs in a single CRL DistributionPoint
  1967  // structure. It is taken from https://crt.sh/?id=12721534.
  1968  const multipleURLsInCRLDPPEM = `
  1969  -----BEGIN CERTIFICATE-----
  1970  MIIF4TCCBMmgAwIBAgIQc+6uFePfrahUGpXs8lhiTzANBgkqhkiG9w0BAQsFADCB
  1971  8zELM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DwEB/wQEAwIBBjAdBgNVHQ4EFgQUC2hZPofI
  1987  oxUa4ECCIl+fHbLFNxUwHwYDVR0jBBgwFoAUoMOLRKo3pUW/l4Ba0fF4opvpXY0w
  1988  gdYGA1UdIASBzjCByzCByAYEVR0gADCBvzAxBggrBgEFBQcCARYlaHR0cHM6Ly93
  1989  d3cuYW9jLmNhdC9DQVRDZXJ0L1JlZ3VsYWNpbzCBiQYIKwYBBQUHAgIwfQx7QXF1
  1990  ZXN0IGNlcnRpZmljYXQgw6lzIGVtw6hzIMO6bmljYSBpIGV4Y2x1c2l2YW1lbnQg
  1991  YSBFbnRpdGF0cyBkZSBDZXJ0aWZpY2FjacOzLiBWZWdldSBodHRwczovL3d3dy5h
  1992  b2MuY2F0L0NBVENlcnQvUmVndWxhY2lvMDMGCCsGAQUFBwEBBCcwJTAjBggrBgEF
  1993  BQcwAYYXaHR0cDovL29jc3AuY2F0Y2VydC5jYXQwYgYDVR0fBFswWTBXoFWgU4Yn
  1994  aHR0cDovL2Vwc2NkLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JshihodHRwOi8v
  1995  ZXBzY2QyLmNhdGNlcnQubmV0L2NybC9lYy1hY2MuY3JsMA0GCSqGSIb3DQEBCwUA
  1996  A4IBAQChqFTjlAH5PyIhLjLgEs68CyNNC1+vDuZXRhy22TI83JcvGmQrZosPvVIL
  1997  PsUXx+C06Pfqmh48Q9S89X9K8w1SdJxP/rZeGEoRiKpwvQzM4ArD9QxyC8jirxex
  1998  3Umg9Ai/sXQ+1lBf6xw4HfUUr1WIp7pNHj0ZWLo106urqktcdeAFWme+/klis5fu
  1999  labCSVPuT/QpwakPrtqOhRms8vgpKiXa/eLtL9ZiA28X/Mker0zlAeTA7Z7uAnp6
  2000  oPJTlZu1Gg1ZDJueTWWsLlO+P+Wzm3MRRIbcgdRzm4mdO7ubu26SzX/aQXDhuih+
  2001  eVxXDTCfs7GUlxnjOp5j559X/N0A
  2002  -----END CERTIFICATE-----
  2003  `
  2004  
  2005  func TestMultipleURLsInCRLDP(t *testing.T) {
  2006  	block, _ := pem.Decode([]byte(multipleURLsInCRLDPPEM))
  2007  	cert, err := ParseCertificate(block.Bytes)
  2008  	if err != nil {
  2009  		t.Fatalf("failed to parse certificate: %s", err)
  2010  	}
  2011  
  2012  	want := []string{
  2013  		"http://epscd.catcert.net/crl/ec-acc.crl",
  2014  		"http://epscd2.catcert.net/crl/ec-acc.crl",
  2015  	}
  2016  	if got := cert.CRLDistributionPoints; !reflect.DeepEqual(got, want) {
  2017  		t.Errorf("CRL distribution points = %#v, want #%v", got, want)
  2018  	}
  2019  }
  2020  

View as plain text