github.com/xushiwei/go@v0.0.0-20130601165731-2b9d83f45bc9/src/pkg/crypto/x509/x509.go (about)

     1  // Copyright 2009 The Go Authors. All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  // Package x509 parses X.509-encoded keys and certificates.
     6  package x509
     7  
     8  import (
     9  	"bytes"
    10  	"crypto"
    11  	"crypto/dsa"
    12  	"crypto/ecdsa"
    13  	"crypto/elliptic"
    14  	"crypto/rsa"
    15  	"crypto/sha1"
    16  	"crypto/x509/pkix"
    17  	"encoding/asn1"
    18  	"encoding/pem"
    19  	"errors"
    20  	"io"
    21  	"math/big"
    22  	"net"
    23  	"strconv"
    24  	"time"
    25  )
    26  
    27  // pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    28  // in RFC 3280.
    29  type pkixPublicKey struct {
    30  	Algo      pkix.AlgorithmIdentifier
    31  	BitString asn1.BitString
    32  }
    33  
    34  // ParsePKIXPublicKey parses a DER encoded public key. These values are
    35  // typically found in PEM blocks with "BEGIN PUBLIC KEY".
    36  func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
    37  	var pki publicKeyInfo
    38  	if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
    39  		return
    40  	}
    41  	algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
    42  	if algo == UnknownPublicKeyAlgorithm {
    43  		return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
    44  	}
    45  	return parsePublicKey(algo, &pki)
    46  }
    47  
    48  // MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
    49  func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
    50  	var pubBytes []byte
    51  
    52  	switch pub := pub.(type) {
    53  	case *rsa.PublicKey:
    54  		pubBytes, _ = asn1.Marshal(rsaPublicKey{
    55  			N: pub.N,
    56  			E: pub.E,
    57  		})
    58  	default:
    59  		return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
    60  	}
    61  
    62  	pkix := pkixPublicKey{
    63  		Algo: pkix.AlgorithmIdentifier{
    64  			Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
    65  			// This is a NULL parameters value which is technically
    66  			// superfluous, but most other code includes it and, by
    67  			// doing this, we match their public key hashes.
    68  			Parameters: asn1.RawValue{
    69  				Tag: 5,
    70  			},
    71  		},
    72  		BitString: asn1.BitString{
    73  			Bytes:     pubBytes,
    74  			BitLength: 8 * len(pubBytes),
    75  		},
    76  	}
    77  
    78  	ret, _ := asn1.Marshal(pkix)
    79  	return ret, nil
    80  }
    81  
    82  // These structures reflect the ASN.1 structure of X.509 certificates.:
    83  
    84  type certificate struct {
    85  	Raw                asn1.RawContent
    86  	TBSCertificate     tbsCertificate
    87  	SignatureAlgorithm pkix.AlgorithmIdentifier
    88  	SignatureValue     asn1.BitString
    89  }
    90  
    91  type tbsCertificate struct {
    92  	Raw                asn1.RawContent
    93  	Version            int `asn1:"optional,explicit,default:1,tag:0"`
    94  	SerialNumber       *big.Int
    95  	SignatureAlgorithm pkix.AlgorithmIdentifier
    96  	Issuer             asn1.RawValue
    97  	Validity           validity
    98  	Subject            asn1.RawValue
    99  	PublicKey          publicKeyInfo
   100  	UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
   101  	SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
   102  	Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
   103  }
   104  
   105  type dsaAlgorithmParameters struct {
   106  	P, Q, G *big.Int
   107  }
   108  
   109  type dsaSignature struct {
   110  	R, S *big.Int
   111  }
   112  
   113  type ecdsaSignature dsaSignature
   114  
   115  type validity struct {
   116  	NotBefore, NotAfter time.Time
   117  }
   118  
   119  type publicKeyInfo struct {
   120  	Raw       asn1.RawContent
   121  	Algorithm pkix.AlgorithmIdentifier
   122  	PublicKey asn1.BitString
   123  }
   124  
   125  // RFC 5280,  4.2.1.1
   126  type authKeyId struct {
   127  	Id []byte `asn1:"optional,tag:0"`
   128  }
   129  
   130  type SignatureAlgorithm int
   131  
   132  const (
   133  	UnknownSignatureAlgorithm SignatureAlgorithm = iota
   134  	MD2WithRSA
   135  	MD5WithRSA
   136  	SHA1WithRSA
   137  	SHA256WithRSA
   138  	SHA384WithRSA
   139  	SHA512WithRSA
   140  	DSAWithSHA1
   141  	DSAWithSHA256
   142  	ECDSAWithSHA1
   143  	ECDSAWithSHA256
   144  	ECDSAWithSHA384
   145  	ECDSAWithSHA512
   146  )
   147  
   148  type PublicKeyAlgorithm int
   149  
   150  const (
   151  	UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   152  	RSA
   153  	DSA
   154  	ECDSA
   155  )
   156  
   157  // OIDs for signature algorithms
   158  //
   159  // pkcs-1 OBJECT IDENTIFIER ::= {
   160  //    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   161  //
   162  //
   163  // RFC 3279 2.2.1 RSA Signature Algorithms
   164  //
   165  // md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   166  //
   167  // md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   168  //
   169  // sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   170  //
   171  // dsaWithSha1 OBJECT IDENTIFIER ::= {
   172  //    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 }
   173  //
   174  // RFC 3279 2.2.3 ECDSA Signature Algorithm
   175  //
   176  // ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
   177  // 	  iso(1) member-body(2) us(840) ansi-x962(10045)
   178  //    signatures(4) ecdsa-with-SHA1(1)}
   179  //
   180  //
   181  // RFC 4055 5 PKCS #1 Version 1.5
   182  //
   183  // sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   184  //
   185  // sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   186  //
   187  // sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   188  //
   189  //
   190  // RFC 5758 3.1 DSA Signature Algorithms
   191  //
   192  // dsaWithSha256 OBJECT IDENTIFIER ::= {
   193  //    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   194  //    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   195  //
   196  // RFC 5758 3.2 ECDSA Signature Algorithm
   197  //
   198  // ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   199  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 2 }
   200  //
   201  // ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   202  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 3 }
   203  //
   204  // ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2)
   205  //    us(840) ansi-X9-62(10045) signatures(4) ecdsa-with-SHA2(3) 4 }
   206  
   207  var (
   208  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   209  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   210  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   211  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   212  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   213  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   214  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   215  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
   216  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   217  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   218  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   219  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   220  )
   221  
   222  func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
   223  	switch {
   224  	case oid.Equal(oidSignatureMD2WithRSA):
   225  		return MD2WithRSA
   226  	case oid.Equal(oidSignatureMD5WithRSA):
   227  		return MD5WithRSA
   228  	case oid.Equal(oidSignatureSHA1WithRSA):
   229  		return SHA1WithRSA
   230  	case oid.Equal(oidSignatureSHA256WithRSA):
   231  		return SHA256WithRSA
   232  	case oid.Equal(oidSignatureSHA384WithRSA):
   233  		return SHA384WithRSA
   234  	case oid.Equal(oidSignatureSHA512WithRSA):
   235  		return SHA512WithRSA
   236  	case oid.Equal(oidSignatureDSAWithSHA1):
   237  		return DSAWithSHA1
   238  	case oid.Equal(oidSignatureDSAWithSHA256):
   239  		return DSAWithSHA256
   240  	case oid.Equal(oidSignatureECDSAWithSHA1):
   241  		return ECDSAWithSHA1
   242  	case oid.Equal(oidSignatureECDSAWithSHA256):
   243  		return ECDSAWithSHA256
   244  	case oid.Equal(oidSignatureECDSAWithSHA384):
   245  		return ECDSAWithSHA384
   246  	case oid.Equal(oidSignatureECDSAWithSHA512):
   247  		return ECDSAWithSHA512
   248  	}
   249  	return UnknownSignatureAlgorithm
   250  }
   251  
   252  // RFC 3279, 2.3 Public Key Algorithms
   253  //
   254  // pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   255  //    rsadsi(113549) pkcs(1) 1 }
   256  //
   257  // rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   258  //
   259  // id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   260  //    x9-57(10040) x9cm(4) 1 }
   261  //
   262  // RFC 5480, 2.1.1 Unrestricted Algorithm Identifier and Parameters
   263  //
   264  // id-ecPublicKey OBJECT IDENTIFIER ::= {
   265  //       iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
   266  var (
   267  	oidPublicKeyRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   268  	oidPublicKeyDSA   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   269  	oidPublicKeyECDSA = asn1.ObjectIdentifier{1, 2, 840, 10045, 2, 1}
   270  )
   271  
   272  func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   273  	switch {
   274  	case oid.Equal(oidPublicKeyRSA):
   275  		return RSA
   276  	case oid.Equal(oidPublicKeyDSA):
   277  		return DSA
   278  	case oid.Equal(oidPublicKeyECDSA):
   279  		return ECDSA
   280  	}
   281  	return UnknownPublicKeyAlgorithm
   282  }
   283  
   284  // RFC 5480, 2.1.1.1. Named Curve
   285  //
   286  // secp224r1 OBJECT IDENTIFIER ::= {
   287  //   iso(1) identified-organization(3) certicom(132) curve(0) 33 }
   288  //
   289  // secp256r1 OBJECT IDENTIFIER ::= {
   290  //   iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3)
   291  //   prime(1) 7 }
   292  //
   293  // secp384r1 OBJECT IDENTIFIER ::= {
   294  //   iso(1) identified-organization(3) certicom(132) curve(0) 34 }
   295  //
   296  // secp521r1 OBJECT IDENTIFIER ::= {
   297  //   iso(1) identified-organization(3) certicom(132) curve(0) 35 }
   298  //
   299  // NB: secp256r1 is equivalent to prime256v1
   300  var (
   301  	oidNamedCurveP224 = asn1.ObjectIdentifier{1, 3, 132, 0, 33}
   302  	oidNamedCurveP256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 3, 1, 7}
   303  	oidNamedCurveP384 = asn1.ObjectIdentifier{1, 3, 132, 0, 34}
   304  	oidNamedCurveP521 = asn1.ObjectIdentifier{1, 3, 132, 0, 35}
   305  )
   306  
   307  func namedCurveFromOID(oid asn1.ObjectIdentifier) elliptic.Curve {
   308  	switch {
   309  	case oid.Equal(oidNamedCurveP224):
   310  		return elliptic.P224()
   311  	case oid.Equal(oidNamedCurveP256):
   312  		return elliptic.P256()
   313  	case oid.Equal(oidNamedCurveP384):
   314  		return elliptic.P384()
   315  	case oid.Equal(oidNamedCurveP521):
   316  		return elliptic.P521()
   317  	}
   318  	return nil
   319  }
   320  
   321  func oidFromNamedCurve(curve elliptic.Curve) (asn1.ObjectIdentifier, bool) {
   322  	switch curve {
   323  	case elliptic.P224():
   324  		return oidNamedCurveP224, true
   325  	case elliptic.P256():
   326  		return oidNamedCurveP256, true
   327  	case elliptic.P384():
   328  		return oidNamedCurveP384, true
   329  	case elliptic.P521():
   330  		return oidNamedCurveP521, true
   331  	}
   332  
   333  	return nil, false
   334  }
   335  
   336  // KeyUsage represents the set of actions that are valid for a given key. It's
   337  // a bitmap of the KeyUsage* constants.
   338  type KeyUsage int
   339  
   340  const (
   341  	KeyUsageDigitalSignature KeyUsage = 1 << iota
   342  	KeyUsageContentCommitment
   343  	KeyUsageKeyEncipherment
   344  	KeyUsageDataEncipherment
   345  	KeyUsageKeyAgreement
   346  	KeyUsageCertSign
   347  	KeyUsageCRLSign
   348  	KeyUsageEncipherOnly
   349  	KeyUsageDecipherOnly
   350  )
   351  
   352  // RFC 5280, 4.2.1.12  Extended Key Usage
   353  //
   354  // anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   355  //
   356  // id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   357  //
   358  // id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   359  // id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   360  // id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   361  // id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   362  // id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   363  // id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   364  var (
   365  	oidExtKeyUsageAny                        = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   366  	oidExtKeyUsageServerAuth                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   367  	oidExtKeyUsageClientAuth                 = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   368  	oidExtKeyUsageCodeSigning                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   369  	oidExtKeyUsageEmailProtection            = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   370  	oidExtKeyUsageIPSECEndSystem             = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 5}
   371  	oidExtKeyUsageIPSECTunnel                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 6}
   372  	oidExtKeyUsageIPSECUser                  = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 7}
   373  	oidExtKeyUsageTimeStamping               = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   374  	oidExtKeyUsageOCSPSigning                = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   375  	oidExtKeyUsageMicrosoftServerGatedCrypto = asn1.ObjectIdentifier{1, 3, 6, 1, 4, 1, 311, 10, 3, 3}
   376  	oidExtKeyUsageNetscapeServerGatedCrypto  = asn1.ObjectIdentifier{2, 16, 840, 1, 113730, 4, 1}
   377  )
   378  
   379  // ExtKeyUsage represents an extended set of actions that are valid for a given key.
   380  // Each of the ExtKeyUsage* constants define a unique action.
   381  type ExtKeyUsage int
   382  
   383  const (
   384  	ExtKeyUsageAny ExtKeyUsage = iota
   385  	ExtKeyUsageServerAuth
   386  	ExtKeyUsageClientAuth
   387  	ExtKeyUsageCodeSigning
   388  	ExtKeyUsageEmailProtection
   389  	ExtKeyUsageIPSECEndSystem
   390  	ExtKeyUsageIPSECTunnel
   391  	ExtKeyUsageIPSECUser
   392  	ExtKeyUsageTimeStamping
   393  	ExtKeyUsageOCSPSigning
   394  	ExtKeyUsageMicrosoftServerGatedCrypto
   395  	ExtKeyUsageNetscapeServerGatedCrypto
   396  )
   397  
   398  // extKeyUsageOIDs contains the mapping between an ExtKeyUsage and its OID.
   399  var extKeyUsageOIDs = []struct {
   400  	extKeyUsage ExtKeyUsage
   401  	oid         asn1.ObjectIdentifier
   402  }{
   403  	{ExtKeyUsageAny, oidExtKeyUsageAny},
   404  	{ExtKeyUsageServerAuth, oidExtKeyUsageServerAuth},
   405  	{ExtKeyUsageClientAuth, oidExtKeyUsageClientAuth},
   406  	{ExtKeyUsageCodeSigning, oidExtKeyUsageCodeSigning},
   407  	{ExtKeyUsageEmailProtection, oidExtKeyUsageEmailProtection},
   408  	{ExtKeyUsageIPSECEndSystem, oidExtKeyUsageIPSECEndSystem},
   409  	{ExtKeyUsageIPSECTunnel, oidExtKeyUsageIPSECTunnel},
   410  	{ExtKeyUsageIPSECUser, oidExtKeyUsageIPSECUser},
   411  	{ExtKeyUsageTimeStamping, oidExtKeyUsageTimeStamping},
   412  	{ExtKeyUsageOCSPSigning, oidExtKeyUsageOCSPSigning},
   413  	{ExtKeyUsageMicrosoftServerGatedCrypto, oidExtKeyUsageMicrosoftServerGatedCrypto},
   414  	{ExtKeyUsageNetscapeServerGatedCrypto, oidExtKeyUsageNetscapeServerGatedCrypto},
   415  }
   416  
   417  func extKeyUsageFromOID(oid asn1.ObjectIdentifier) (eku ExtKeyUsage, ok bool) {
   418  	for _, pair := range extKeyUsageOIDs {
   419  		if oid.Equal(pair.oid) {
   420  			return pair.extKeyUsage, true
   421  		}
   422  	}
   423  	return
   424  }
   425  
   426  func oidFromExtKeyUsage(eku ExtKeyUsage) (oid asn1.ObjectIdentifier, ok bool) {
   427  	for _, pair := range extKeyUsageOIDs {
   428  		if eku == pair.extKeyUsage {
   429  			return pair.oid, true
   430  		}
   431  	}
   432  	return
   433  }
   434  
   435  // A Certificate represents an X.509 certificate.
   436  type Certificate struct {
   437  	Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
   438  	RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
   439  	RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
   440  	RawSubject              []byte // DER encoded Subject
   441  	RawIssuer               []byte // DER encoded Issuer
   442  
   443  	Signature          []byte
   444  	SignatureAlgorithm SignatureAlgorithm
   445  
   446  	PublicKeyAlgorithm PublicKeyAlgorithm
   447  	PublicKey          interface{}
   448  
   449  	Version             int
   450  	SerialNumber        *big.Int
   451  	Issuer              pkix.Name
   452  	Subject             pkix.Name
   453  	NotBefore, NotAfter time.Time // Validity bounds.
   454  	KeyUsage            KeyUsage
   455  
   456  	ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
   457  	UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
   458  
   459  	BasicConstraintsValid bool // if true then the next two fields are valid.
   460  	IsCA                  bool
   461  	MaxPathLen            int
   462  
   463  	SubjectKeyId   []byte
   464  	AuthorityKeyId []byte
   465  
   466  	// Subject Alternate Name values
   467  	DNSNames       []string
   468  	EmailAddresses []string
   469  	IPAddresses    []net.IP
   470  
   471  	// Name constraints
   472  	PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   473  	PermittedDNSDomains         []string
   474  
   475  	PolicyIdentifiers []asn1.ObjectIdentifier
   476  }
   477  
   478  // ErrUnsupportedAlgorithm results from attempting to perform an operation that
   479  // involves algorithms that are not currently implemented.
   480  var ErrUnsupportedAlgorithm = errors.New("crypto/x509: cannot verify signature: algorithm unimplemented")
   481  
   482  // ConstraintViolationError results when a requested usage is not permitted by
   483  // a certificate. For example: checking a signature when the public key isn't a
   484  // certificate signing key.
   485  type ConstraintViolationError struct{}
   486  
   487  func (ConstraintViolationError) Error() string {
   488  	return "crypto/x509: invalid signature: parent certificate cannot sign this kind of certificate"
   489  }
   490  
   491  func (c *Certificate) Equal(other *Certificate) bool {
   492  	return bytes.Equal(c.Raw, other.Raw)
   493  }
   494  
   495  // Entrust have a broken root certificate (CN=Entrust.net Certification
   496  // Authority (2048)) which isn't marked as a CA certificate and is thus invalid
   497  // according to PKIX.
   498  // We recognise this certificate by its SubjectPublicKeyInfo and exempt it
   499  // from the Basic Constraints requirement.
   500  // See http://www.entrust.net/knowledge-base/technote.cfm?tn=7869
   501  //
   502  // TODO(agl): remove this hack once their reissued root is sufficiently
   503  // widespread.
   504  var entrustBrokenSPKI = []byte{
   505  	0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09,
   506  	0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01,
   507  	0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00,
   508  	0x30, 0x82, 0x01, 0x0a, 0x02, 0x82, 0x01, 0x01,
   509  	0x00, 0x97, 0xa3, 0x2d, 0x3c, 0x9e, 0xde, 0x05,
   510  	0xda, 0x13, 0xc2, 0x11, 0x8d, 0x9d, 0x8e, 0xe3,
   511  	0x7f, 0xc7, 0x4b, 0x7e, 0x5a, 0x9f, 0xb3, 0xff,
   512  	0x62, 0xab, 0x73, 0xc8, 0x28, 0x6b, 0xba, 0x10,
   513  	0x64, 0x82, 0x87, 0x13, 0xcd, 0x57, 0x18, 0xff,
   514  	0x28, 0xce, 0xc0, 0xe6, 0x0e, 0x06, 0x91, 0x50,
   515  	0x29, 0x83, 0xd1, 0xf2, 0xc3, 0x2a, 0xdb, 0xd8,
   516  	0xdb, 0x4e, 0x04, 0xcc, 0x00, 0xeb, 0x8b, 0xb6,
   517  	0x96, 0xdc, 0xbc, 0xaa, 0xfa, 0x52, 0x77, 0x04,
   518  	0xc1, 0xdb, 0x19, 0xe4, 0xae, 0x9c, 0xfd, 0x3c,
   519  	0x8b, 0x03, 0xef, 0x4d, 0xbc, 0x1a, 0x03, 0x65,
   520  	0xf9, 0xc1, 0xb1, 0x3f, 0x72, 0x86, 0xf2, 0x38,
   521  	0xaa, 0x19, 0xae, 0x10, 0x88, 0x78, 0x28, 0xda,
   522  	0x75, 0xc3, 0x3d, 0x02, 0x82, 0x02, 0x9c, 0xb9,
   523  	0xc1, 0x65, 0x77, 0x76, 0x24, 0x4c, 0x98, 0xf7,
   524  	0x6d, 0x31, 0x38, 0xfb, 0xdb, 0xfe, 0xdb, 0x37,
   525  	0x02, 0x76, 0xa1, 0x18, 0x97, 0xa6, 0xcc, 0xde,
   526  	0x20, 0x09, 0x49, 0x36, 0x24, 0x69, 0x42, 0xf6,
   527  	0xe4, 0x37, 0x62, 0xf1, 0x59, 0x6d, 0xa9, 0x3c,
   528  	0xed, 0x34, 0x9c, 0xa3, 0x8e, 0xdb, 0xdc, 0x3a,
   529  	0xd7, 0xf7, 0x0a, 0x6f, 0xef, 0x2e, 0xd8, 0xd5,
   530  	0x93, 0x5a, 0x7a, 0xed, 0x08, 0x49, 0x68, 0xe2,
   531  	0x41, 0xe3, 0x5a, 0x90, 0xc1, 0x86, 0x55, 0xfc,
   532  	0x51, 0x43, 0x9d, 0xe0, 0xb2, 0xc4, 0x67, 0xb4,
   533  	0xcb, 0x32, 0x31, 0x25, 0xf0, 0x54, 0x9f, 0x4b,
   534  	0xd1, 0x6f, 0xdb, 0xd4, 0xdd, 0xfc, 0xaf, 0x5e,
   535  	0x6c, 0x78, 0x90, 0x95, 0xde, 0xca, 0x3a, 0x48,
   536  	0xb9, 0x79, 0x3c, 0x9b, 0x19, 0xd6, 0x75, 0x05,
   537  	0xa0, 0xf9, 0x88, 0xd7, 0xc1, 0xe8, 0xa5, 0x09,
   538  	0xe4, 0x1a, 0x15, 0xdc, 0x87, 0x23, 0xaa, 0xb2,
   539  	0x75, 0x8c, 0x63, 0x25, 0x87, 0xd8, 0xf8, 0x3d,
   540  	0xa6, 0xc2, 0xcc, 0x66, 0xff, 0xa5, 0x66, 0x68,
   541  	0x55, 0x02, 0x03, 0x01, 0x00, 0x01,
   542  }
   543  
   544  // CheckSignatureFrom verifies that the signature on c is a valid signature
   545  // from parent.
   546  func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
   547  	// RFC 5280, 4.2.1.9:
   548  	// "If the basic constraints extension is not present in a version 3
   549  	// certificate, or the extension is present but the cA boolean is not
   550  	// asserted, then the certified public key MUST NOT be used to verify
   551  	// certificate signatures."
   552  	// (except for Entrust, see comment above entrustBrokenSPKI)
   553  	if (parent.Version == 3 && !parent.BasicConstraintsValid ||
   554  		parent.BasicConstraintsValid && !parent.IsCA) &&
   555  		!bytes.Equal(c.RawSubjectPublicKeyInfo, entrustBrokenSPKI) {
   556  		return ConstraintViolationError{}
   557  	}
   558  
   559  	if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
   560  		return ConstraintViolationError{}
   561  	}
   562  
   563  	if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   564  		return ErrUnsupportedAlgorithm
   565  	}
   566  
   567  	// TODO(agl): don't ignore the path length constraint.
   568  
   569  	return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
   570  }
   571  
   572  // CheckSignature verifies that signature is a valid signature over signed from
   573  // c's public key.
   574  func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
   575  	var hashType crypto.Hash
   576  
   577  	switch algo {
   578  	case SHA1WithRSA, DSAWithSHA1, ECDSAWithSHA1:
   579  		hashType = crypto.SHA1
   580  	case SHA256WithRSA, DSAWithSHA256, ECDSAWithSHA256:
   581  		hashType = crypto.SHA256
   582  	case SHA384WithRSA, ECDSAWithSHA384:
   583  		hashType = crypto.SHA384
   584  	case SHA512WithRSA, ECDSAWithSHA512:
   585  		hashType = crypto.SHA512
   586  	default:
   587  		return ErrUnsupportedAlgorithm
   588  	}
   589  
   590  	if !hashType.Available() {
   591  		return ErrUnsupportedAlgorithm
   592  	}
   593  	h := hashType.New()
   594  
   595  	h.Write(signed)
   596  	digest := h.Sum(nil)
   597  
   598  	switch pub := c.PublicKey.(type) {
   599  	case *rsa.PublicKey:
   600  		return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
   601  	case *dsa.PublicKey:
   602  		dsaSig := new(dsaSignature)
   603  		if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
   604  			return err
   605  		}
   606  		if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
   607  			return errors.New("DSA signature contained zero or negative values")
   608  		}
   609  		if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
   610  			return errors.New("DSA verification failure")
   611  		}
   612  		return
   613  	case *ecdsa.PublicKey:
   614  		ecdsaSig := new(ecdsaSignature)
   615  		if _, err := asn1.Unmarshal(signature, ecdsaSig); err != nil {
   616  			return err
   617  		}
   618  		if ecdsaSig.R.Sign() <= 0 || ecdsaSig.S.Sign() <= 0 {
   619  			return errors.New("crypto/x509: ECDSA signature contained zero or negative values")
   620  		}
   621  		if !ecdsa.Verify(pub, digest, ecdsaSig.R, ecdsaSig.S) {
   622  			return errors.New("crypto/x509: ECDSA verification failure")
   623  		}
   624  		return
   625  	}
   626  	return ErrUnsupportedAlgorithm
   627  }
   628  
   629  // CheckCRLSignature checks that the signature in crl is from c.
   630  func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
   631  	algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
   632  	return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
   633  }
   634  
   635  type UnhandledCriticalExtension struct{}
   636  
   637  func (h UnhandledCriticalExtension) Error() string {
   638  	return "unhandled critical extension"
   639  }
   640  
   641  type basicConstraints struct {
   642  	IsCA       bool `asn1:"optional"`
   643  	MaxPathLen int  `asn1:"optional,default:-1"`
   644  }
   645  
   646  // RFC 5280 4.2.1.4
   647  type policyInformation struct {
   648  	Policy asn1.ObjectIdentifier
   649  	// policyQualifiers omitted
   650  }
   651  
   652  // RFC 5280, 4.2.1.10
   653  type nameConstraints struct {
   654  	Permitted []generalSubtree `asn1:"optional,tag:0"`
   655  	Excluded  []generalSubtree `asn1:"optional,tag:1"`
   656  }
   657  
   658  type generalSubtree struct {
   659  	Name string `asn1:"tag:2,optional,ia5"`
   660  }
   661  
   662  func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
   663  	asn1Data := keyData.PublicKey.RightAlign()
   664  	switch algo {
   665  	case RSA:
   666  		p := new(rsaPublicKey)
   667  		_, err := asn1.Unmarshal(asn1Data, p)
   668  		if err != nil {
   669  			return nil, err
   670  		}
   671  
   672  		if p.N.Sign() <= 0 {
   673  			return nil, errors.New("x509: RSA modulus is not a positive number")
   674  		}
   675  		if p.E <= 0 {
   676  			return nil, errors.New("x509: RSA public exponent is not a positive number")
   677  		}
   678  
   679  		pub := &rsa.PublicKey{
   680  			E: p.E,
   681  			N: p.N,
   682  		}
   683  		return pub, nil
   684  	case DSA:
   685  		var p *big.Int
   686  		_, err := asn1.Unmarshal(asn1Data, &p)
   687  		if err != nil {
   688  			return nil, err
   689  		}
   690  		paramsData := keyData.Algorithm.Parameters.FullBytes
   691  		params := new(dsaAlgorithmParameters)
   692  		_, err = asn1.Unmarshal(paramsData, params)
   693  		if err != nil {
   694  			return nil, err
   695  		}
   696  		if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
   697  			return nil, errors.New("zero or negative DSA parameter")
   698  		}
   699  		pub := &dsa.PublicKey{
   700  			Parameters: dsa.Parameters{
   701  				P: params.P,
   702  				Q: params.Q,
   703  				G: params.G,
   704  			},
   705  			Y: p,
   706  		}
   707  		return pub, nil
   708  	case ECDSA:
   709  		paramsData := keyData.Algorithm.Parameters.FullBytes
   710  		namedCurveOID := new(asn1.ObjectIdentifier)
   711  		_, err := asn1.Unmarshal(paramsData, namedCurveOID)
   712  		if err != nil {
   713  			return nil, err
   714  		}
   715  		namedCurve := namedCurveFromOID(*namedCurveOID)
   716  		if namedCurve == nil {
   717  			return nil, errors.New("crypto/x509: unsupported elliptic curve")
   718  		}
   719  		x, y := elliptic.Unmarshal(namedCurve, asn1Data)
   720  		if x == nil {
   721  			return nil, errors.New("crypto/x509: failed to unmarshal elliptic curve point")
   722  		}
   723  		pub := &ecdsa.PublicKey{
   724  			Curve: namedCurve,
   725  			X:     x,
   726  			Y:     y,
   727  		}
   728  		return pub, nil
   729  	default:
   730  		return nil, nil
   731  	}
   732  }
   733  
   734  func parseCertificate(in *certificate) (*Certificate, error) {
   735  	out := new(Certificate)
   736  	out.Raw = in.Raw
   737  	out.RawTBSCertificate = in.TBSCertificate.Raw
   738  	out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
   739  	out.RawSubject = in.TBSCertificate.Subject.FullBytes
   740  	out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
   741  
   742  	out.Signature = in.SignatureValue.RightAlign()
   743  	out.SignatureAlgorithm =
   744  		getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
   745  
   746  	out.PublicKeyAlgorithm =
   747  		getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
   748  	var err error
   749  	out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
   750  	if err != nil {
   751  		return nil, err
   752  	}
   753  
   754  	if in.TBSCertificate.SerialNumber.Sign() < 0 {
   755  		return nil, errors.New("negative serial number")
   756  	}
   757  
   758  	out.Version = in.TBSCertificate.Version + 1
   759  	out.SerialNumber = in.TBSCertificate.SerialNumber
   760  
   761  	var issuer, subject pkix.RDNSequence
   762  	if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
   763  		return nil, err
   764  	}
   765  	if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
   766  		return nil, err
   767  	}
   768  
   769  	out.Issuer.FillFromRDNSequence(&issuer)
   770  	out.Subject.FillFromRDNSequence(&subject)
   771  
   772  	out.NotBefore = in.TBSCertificate.Validity.NotBefore
   773  	out.NotAfter = in.TBSCertificate.Validity.NotAfter
   774  
   775  	for _, e := range in.TBSCertificate.Extensions {
   776  		if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
   777  			switch e.Id[3] {
   778  			case 15:
   779  				// RFC 5280, 4.2.1.3
   780  				var usageBits asn1.BitString
   781  				_, err := asn1.Unmarshal(e.Value, &usageBits)
   782  
   783  				if err == nil {
   784  					var usage int
   785  					for i := 0; i < 9; i++ {
   786  						if usageBits.At(i) != 0 {
   787  							usage |= 1 << uint(i)
   788  						}
   789  					}
   790  					out.KeyUsage = KeyUsage(usage)
   791  					continue
   792  				}
   793  			case 19:
   794  				// RFC 5280, 4.2.1.9
   795  				var constraints basicConstraints
   796  				_, err := asn1.Unmarshal(e.Value, &constraints)
   797  
   798  				if err == nil {
   799  					out.BasicConstraintsValid = true
   800  					out.IsCA = constraints.IsCA
   801  					out.MaxPathLen = constraints.MaxPathLen
   802  					continue
   803  				}
   804  			case 17:
   805  				// RFC 5280, 4.2.1.6
   806  
   807  				// SubjectAltName ::= GeneralNames
   808  				//
   809  				// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
   810  				//
   811  				// GeneralName ::= CHOICE {
   812  				//      otherName                       [0]     OtherName,
   813  				//      rfc822Name                      [1]     IA5String,
   814  				//      dNSName                         [2]     IA5String,
   815  				//      x400Address                     [3]     ORAddress,
   816  				//      directoryName                   [4]     Name,
   817  				//      ediPartyName                    [5]     EDIPartyName,
   818  				//      uniformResourceIdentifier       [6]     IA5String,
   819  				//      iPAddress                       [7]     OCTET STRING,
   820  				//      registeredID                    [8]     OBJECT IDENTIFIER }
   821  				var seq asn1.RawValue
   822  				_, err := asn1.Unmarshal(e.Value, &seq)
   823  				if err != nil {
   824  					return nil, err
   825  				}
   826  				if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
   827  					return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
   828  				}
   829  
   830  				parsedName := false
   831  
   832  				rest := seq.Bytes
   833  				for len(rest) > 0 {
   834  					var v asn1.RawValue
   835  					rest, err = asn1.Unmarshal(rest, &v)
   836  					if err != nil {
   837  						return nil, err
   838  					}
   839  					switch v.Tag {
   840  					case 1:
   841  						out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
   842  						parsedName = true
   843  					case 2:
   844  						out.DNSNames = append(out.DNSNames, string(v.Bytes))
   845  						parsedName = true
   846  					case 7:
   847  						switch len(v.Bytes) {
   848  						case net.IPv4len, net.IPv6len:
   849  							out.IPAddresses = append(out.IPAddresses, v.Bytes)
   850  						default:
   851  							return nil, errors.New("x509: certificate contained IP address of length " + strconv.Itoa(len(v.Bytes)))
   852  						}
   853  					}
   854  				}
   855  
   856  				if parsedName {
   857  					continue
   858  				}
   859  				// If we didn't parse any of the names then we
   860  				// fall through to the critical check below.
   861  
   862  			case 30:
   863  				// RFC 5280, 4.2.1.10
   864  
   865  				// NameConstraints ::= SEQUENCE {
   866  				//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
   867  				//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
   868  				//
   869  				// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
   870  				//
   871  				// GeneralSubtree ::= SEQUENCE {
   872  				//      base                    GeneralName,
   873  				//      minimum         [0]     BaseDistance DEFAULT 0,
   874  				//      maximum         [1]     BaseDistance OPTIONAL }
   875  				//
   876  				// BaseDistance ::= INTEGER (0..MAX)
   877  
   878  				var constraints nameConstraints
   879  				_, err := asn1.Unmarshal(e.Value, &constraints)
   880  				if err != nil {
   881  					return nil, err
   882  				}
   883  
   884  				if len(constraints.Excluded) > 0 && e.Critical {
   885  					return out, UnhandledCriticalExtension{}
   886  				}
   887  
   888  				for _, subtree := range constraints.Permitted {
   889  					if len(subtree.Name) == 0 {
   890  						if e.Critical {
   891  							return out, UnhandledCriticalExtension{}
   892  						}
   893  						continue
   894  					}
   895  					out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
   896  				}
   897  				continue
   898  
   899  			case 35:
   900  				// RFC 5280, 4.2.1.1
   901  				var a authKeyId
   902  				_, err = asn1.Unmarshal(e.Value, &a)
   903  				if err != nil {
   904  					return nil, err
   905  				}
   906  				out.AuthorityKeyId = a.Id
   907  				continue
   908  
   909  			case 37:
   910  				// RFC 5280, 4.2.1.12.  Extended Key Usage
   911  
   912  				// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
   913  				//
   914  				// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
   915  				//
   916  				// KeyPurposeId ::= OBJECT IDENTIFIER
   917  
   918  				var keyUsage []asn1.ObjectIdentifier
   919  				_, err = asn1.Unmarshal(e.Value, &keyUsage)
   920  				if err != nil {
   921  					return nil, err
   922  				}
   923  
   924  				for _, u := range keyUsage {
   925  					if extKeyUsage, ok := extKeyUsageFromOID(u); ok {
   926  						out.ExtKeyUsage = append(out.ExtKeyUsage, extKeyUsage)
   927  					} else {
   928  						out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
   929  					}
   930  				}
   931  
   932  				continue
   933  
   934  			case 14:
   935  				// RFC 5280, 4.2.1.2
   936  				var keyid []byte
   937  				_, err = asn1.Unmarshal(e.Value, &keyid)
   938  				if err != nil {
   939  					return nil, err
   940  				}
   941  				out.SubjectKeyId = keyid
   942  				continue
   943  
   944  			case 32:
   945  				// RFC 5280 4.2.1.4: Certificate Policies
   946  				var policies []policyInformation
   947  				if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
   948  					return nil, err
   949  				}
   950  				out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
   951  				for i, policy := range policies {
   952  					out.PolicyIdentifiers[i] = policy.Policy
   953  				}
   954  			}
   955  		}
   956  
   957  		if e.Critical {
   958  			return out, UnhandledCriticalExtension{}
   959  		}
   960  	}
   961  
   962  	return out, nil
   963  }
   964  
   965  // ParseCertificate parses a single certificate from the given ASN.1 DER data.
   966  func ParseCertificate(asn1Data []byte) (*Certificate, error) {
   967  	var cert certificate
   968  	rest, err := asn1.Unmarshal(asn1Data, &cert)
   969  	if err != nil {
   970  		return nil, err
   971  	}
   972  	if len(rest) > 0 {
   973  		return nil, asn1.SyntaxError{Msg: "trailing data"}
   974  	}
   975  
   976  	return parseCertificate(&cert)
   977  }
   978  
   979  // ParseCertificates parses one or more certificates from the given ASN.1 DER
   980  // data. The certificates must be concatenated with no intermediate padding.
   981  func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
   982  	var v []*certificate
   983  
   984  	for len(asn1Data) > 0 {
   985  		cert := new(certificate)
   986  		var err error
   987  		asn1Data, err = asn1.Unmarshal(asn1Data, cert)
   988  		if err != nil {
   989  			return nil, err
   990  		}
   991  		v = append(v, cert)
   992  	}
   993  
   994  	ret := make([]*Certificate, len(v))
   995  	for i, ci := range v {
   996  		cert, err := parseCertificate(ci)
   997  		if err != nil {
   998  			return nil, err
   999  		}
  1000  		ret[i] = cert
  1001  	}
  1002  
  1003  	return ret, nil
  1004  }
  1005  
  1006  func reverseBitsInAByte(in byte) byte {
  1007  	b1 := in>>4 | in<<4
  1008  	b2 := b1>>2&0x33 | b1<<2&0xcc
  1009  	b3 := b2>>1&0x55 | b2<<1&0xaa
  1010  	return b3
  1011  }
  1012  
  1013  var (
  1014  	oidExtensionSubjectKeyId        = []int{2, 5, 29, 14}
  1015  	oidExtensionKeyUsage            = []int{2, 5, 29, 15}
  1016  	oidExtensionExtendedKeyUsage    = []int{2, 5, 29, 37}
  1017  	oidExtensionAuthorityKeyId      = []int{2, 5, 29, 35}
  1018  	oidExtensionBasicConstraints    = []int{2, 5, 29, 19}
  1019  	oidExtensionSubjectAltName      = []int{2, 5, 29, 17}
  1020  	oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
  1021  	oidExtensionNameConstraints     = []int{2, 5, 29, 30}
  1022  )
  1023  
  1024  func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
  1025  	ret = make([]pkix.Extension, 8 /* maximum number of elements. */)
  1026  	n := 0
  1027  
  1028  	if template.KeyUsage != 0 {
  1029  		ret[n].Id = oidExtensionKeyUsage
  1030  		ret[n].Critical = true
  1031  
  1032  		var a [2]byte
  1033  		a[0] = reverseBitsInAByte(byte(template.KeyUsage))
  1034  		a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
  1035  
  1036  		l := 1
  1037  		if a[1] != 0 {
  1038  			l = 2
  1039  		}
  1040  
  1041  		ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
  1042  		if err != nil {
  1043  			return
  1044  		}
  1045  		n++
  1046  	}
  1047  
  1048  	if len(template.ExtKeyUsage) > 0 || len(template.UnknownExtKeyUsage) > 0 {
  1049  		ret[n].Id = oidExtensionExtendedKeyUsage
  1050  
  1051  		var oids []asn1.ObjectIdentifier
  1052  		for _, u := range template.ExtKeyUsage {
  1053  			if oid, ok := oidFromExtKeyUsage(u); ok {
  1054  				oids = append(oids, oid)
  1055  			} else {
  1056  				panic("internal error")
  1057  			}
  1058  		}
  1059  
  1060  		oids = append(oids, template.UnknownExtKeyUsage...)
  1061  
  1062  		ret[n].Value, err = asn1.Marshal(oids)
  1063  		if err != nil {
  1064  			return
  1065  		}
  1066  		n++
  1067  	}
  1068  
  1069  	if template.BasicConstraintsValid {
  1070  		ret[n].Id = oidExtensionBasicConstraints
  1071  		ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
  1072  		ret[n].Critical = true
  1073  		if err != nil {
  1074  			return
  1075  		}
  1076  		n++
  1077  	}
  1078  
  1079  	if len(template.SubjectKeyId) > 0 {
  1080  		ret[n].Id = oidExtensionSubjectKeyId
  1081  		ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
  1082  		if err != nil {
  1083  			return
  1084  		}
  1085  		n++
  1086  	}
  1087  
  1088  	if len(template.AuthorityKeyId) > 0 {
  1089  		ret[n].Id = oidExtensionAuthorityKeyId
  1090  		ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
  1091  		if err != nil {
  1092  			return
  1093  		}
  1094  		n++
  1095  	}
  1096  
  1097  	if len(template.DNSNames) > 0 || len(template.EmailAddresses) > 0 || len(template.IPAddresses) > 0 {
  1098  		ret[n].Id = oidExtensionSubjectAltName
  1099  		var rawValues []asn1.RawValue
  1100  		for _, name := range template.DNSNames {
  1101  			rawValues = append(rawValues, asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)})
  1102  		}
  1103  		for _, email := range template.EmailAddresses {
  1104  			rawValues = append(rawValues, asn1.RawValue{Tag: 1, Class: 2, Bytes: []byte(email)})
  1105  		}
  1106  		for _, rawIP := range template.IPAddresses {
  1107  			// If possible, we always want to encode IPv4 addresses in 4 bytes.
  1108  			ip := rawIP.To4()
  1109  			if ip == nil {
  1110  				ip = rawIP
  1111  			}
  1112  			rawValues = append(rawValues, asn1.RawValue{Tag: 7, Class: 2, Bytes: ip})
  1113  		}
  1114  		ret[n].Value, err = asn1.Marshal(rawValues)
  1115  		if err != nil {
  1116  			return
  1117  		}
  1118  		n++
  1119  	}
  1120  
  1121  	if len(template.PolicyIdentifiers) > 0 {
  1122  		ret[n].Id = oidExtensionCertificatePolicies
  1123  		policies := make([]policyInformation, len(template.PolicyIdentifiers))
  1124  		for i, policy := range template.PolicyIdentifiers {
  1125  			policies[i].Policy = policy
  1126  		}
  1127  		ret[n].Value, err = asn1.Marshal(policies)
  1128  		if err != nil {
  1129  			return
  1130  		}
  1131  		n++
  1132  	}
  1133  
  1134  	if len(template.PermittedDNSDomains) > 0 {
  1135  		ret[n].Id = oidExtensionNameConstraints
  1136  		ret[n].Critical = template.PermittedDNSDomainsCritical
  1137  
  1138  		var out nameConstraints
  1139  		out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
  1140  		for i, permitted := range template.PermittedDNSDomains {
  1141  			out.Permitted[i] = generalSubtree{Name: permitted}
  1142  		}
  1143  		ret[n].Value, err = asn1.Marshal(out)
  1144  		if err != nil {
  1145  			return
  1146  		}
  1147  		n++
  1148  	}
  1149  
  1150  	// Adding another extension here? Remember to update the maximum number
  1151  	// of elements in the make() at the top of the function.
  1152  
  1153  	return ret[0:n], nil
  1154  }
  1155  
  1156  func subjectBytes(cert *Certificate) ([]byte, error) {
  1157  	if len(cert.RawSubject) > 0 {
  1158  		return cert.RawSubject, nil
  1159  	}
  1160  
  1161  	return asn1.Marshal(cert.Subject.ToRDNSequence())
  1162  }
  1163  
  1164  // CreateCertificate creates a new certificate based on a template. The
  1165  // following members of template are used: SerialNumber, Subject, NotBefore,
  1166  // NotAfter, KeyUsage, ExtKeyUsage, UnknownExtKeyUsage, BasicConstraintsValid,
  1167  // IsCA, MaxPathLen, SubjectKeyId, DNSNames, PermittedDNSDomainsCritical,
  1168  // PermittedDNSDomains.
  1169  //
  1170  // The certificate is signed by parent. If parent is equal to template then the
  1171  // certificate is self-signed. The parameter pub is the public key of the
  1172  // signee and priv is the private key of the signer.
  1173  //
  1174  // The returned slice is the certificate in DER encoding.
  1175  //
  1176  // The only supported key types are RSA and ECDSA (*rsa.PublicKey or
  1177  // *ecdsa.PublicKey for pub, *rsa.PrivateKey or *ecdsa.PublicKey for priv).
  1178  func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
  1179  	var publicKeyBytes []byte
  1180  	var publicKeyAlgorithm pkix.AlgorithmIdentifier
  1181  
  1182  	switch pub := pub.(type) {
  1183  	case *rsa.PublicKey:
  1184  		publicKeyBytes, err = asn1.Marshal(rsaPublicKey{
  1185  			N: pub.N,
  1186  			E: pub.E,
  1187  		})
  1188  		publicKeyAlgorithm.Algorithm = oidPublicKeyRSA
  1189  	case *ecdsa.PublicKey:
  1190  		oid, ok := oidFromNamedCurve(pub.Curve)
  1191  		if !ok {
  1192  			return nil, errors.New("x509: unknown elliptic curve")
  1193  		}
  1194  		publicKeyAlgorithm.Algorithm = oidPublicKeyECDSA
  1195  		var paramBytes []byte
  1196  		paramBytes, err = asn1.Marshal(oid)
  1197  		if err != nil {
  1198  			return
  1199  		}
  1200  		publicKeyAlgorithm.Parameters.FullBytes = paramBytes
  1201  		publicKeyBytes = elliptic.Marshal(pub.Curve, pub.X, pub.Y)
  1202  	default:
  1203  		return nil, errors.New("x509: only RSA and ECDSA public keys supported")
  1204  	}
  1205  
  1206  	var signatureAlgorithm pkix.AlgorithmIdentifier
  1207  	var hashFunc crypto.Hash
  1208  
  1209  	switch priv := priv.(type) {
  1210  	case *rsa.PrivateKey:
  1211  		signatureAlgorithm.Algorithm = oidSignatureSHA1WithRSA
  1212  		hashFunc = crypto.SHA1
  1213  	case *ecdsa.PrivateKey:
  1214  		switch priv.Curve {
  1215  		case elliptic.P224(), elliptic.P256():
  1216  			hashFunc = crypto.SHA256
  1217  			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA256
  1218  		case elliptic.P384():
  1219  			hashFunc = crypto.SHA384
  1220  			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA384
  1221  		case elliptic.P521():
  1222  			hashFunc = crypto.SHA512
  1223  			signatureAlgorithm.Algorithm = oidSignatureECDSAWithSHA512
  1224  		default:
  1225  			return nil, errors.New("x509: unknown elliptic curve")
  1226  		}
  1227  	default:
  1228  		return nil, errors.New("x509: only RSA and ECDSA private keys supported")
  1229  	}
  1230  
  1231  	if err != nil {
  1232  		return
  1233  	}
  1234  
  1235  	if len(parent.SubjectKeyId) > 0 {
  1236  		template.AuthorityKeyId = parent.SubjectKeyId
  1237  	}
  1238  
  1239  	extensions, err := buildExtensions(template)
  1240  	if err != nil {
  1241  		return
  1242  	}
  1243  
  1244  	asn1Issuer, err := subjectBytes(parent)
  1245  	if err != nil {
  1246  		return
  1247  	}
  1248  
  1249  	asn1Subject, err := subjectBytes(template)
  1250  	if err != nil {
  1251  		return
  1252  	}
  1253  
  1254  	encodedPublicKey := asn1.BitString{BitLength: len(publicKeyBytes) * 8, Bytes: publicKeyBytes}
  1255  	c := tbsCertificate{
  1256  		Version:            2,
  1257  		SerialNumber:       template.SerialNumber,
  1258  		SignatureAlgorithm: signatureAlgorithm,
  1259  		Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
  1260  		Validity:           validity{template.NotBefore.UTC(), template.NotAfter.UTC()},
  1261  		Subject:            asn1.RawValue{FullBytes: asn1Subject},
  1262  		PublicKey:          publicKeyInfo{nil, publicKeyAlgorithm, encodedPublicKey},
  1263  		Extensions:         extensions,
  1264  	}
  1265  
  1266  	tbsCertContents, err := asn1.Marshal(c)
  1267  	if err != nil {
  1268  		return
  1269  	}
  1270  
  1271  	c.Raw = tbsCertContents
  1272  
  1273  	h := hashFunc.New()
  1274  	h.Write(tbsCertContents)
  1275  	digest := h.Sum(nil)
  1276  
  1277  	var signature []byte
  1278  
  1279  	switch priv := priv.(type) {
  1280  	case *rsa.PrivateKey:
  1281  		signature, err = rsa.SignPKCS1v15(rand, priv, hashFunc, digest)
  1282  	case *ecdsa.PrivateKey:
  1283  		var r, s *big.Int
  1284  		if r, s, err = ecdsa.Sign(rand, priv, digest); err == nil {
  1285  			signature, err = asn1.Marshal(ecdsaSignature{r, s})
  1286  		}
  1287  	default:
  1288  		panic("internal error")
  1289  	}
  1290  
  1291  	if err != nil {
  1292  		return
  1293  	}
  1294  
  1295  	cert, err = asn1.Marshal(certificate{
  1296  		nil,
  1297  		c,
  1298  		signatureAlgorithm,
  1299  		asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1300  	})
  1301  	return
  1302  }
  1303  
  1304  // pemCRLPrefix is the magic string that indicates that we have a PEM encoded
  1305  // CRL.
  1306  var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
  1307  
  1308  // pemType is the type of a PEM encoded CRL.
  1309  var pemType = "X509 CRL"
  1310  
  1311  // ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1312  // encoded CRLs will appear where they should be DER encoded, so this function
  1313  // will transparently handle PEM encoding as long as there isn't any leading
  1314  // garbage.
  1315  func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
  1316  	if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1317  		block, _ := pem.Decode(crlBytes)
  1318  		if block != nil && block.Type == pemType {
  1319  			crlBytes = block.Bytes
  1320  		}
  1321  	}
  1322  	return ParseDERCRL(crlBytes)
  1323  }
  1324  
  1325  // ParseDERCRL parses a DER encoded CRL from the given bytes.
  1326  func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
  1327  	certList = new(pkix.CertificateList)
  1328  	_, err = asn1.Unmarshal(derBytes, certList)
  1329  	if err != nil {
  1330  		certList = nil
  1331  	}
  1332  	return
  1333  }
  1334  
  1335  // CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1336  // contains the given list of revoked certificates.
  1337  //
  1338  // The only supported key type is RSA (*rsa.PrivateKey for priv).
  1339  func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1340  	rsaPriv, ok := priv.(*rsa.PrivateKey)
  1341  	if !ok {
  1342  		return nil, errors.New("x509: non-RSA private keys not supported")
  1343  	}
  1344  	tbsCertList := pkix.TBSCertificateList{
  1345  		Version: 2,
  1346  		Signature: pkix.AlgorithmIdentifier{
  1347  			Algorithm: oidSignatureSHA1WithRSA,
  1348  		},
  1349  		Issuer:              c.Subject.ToRDNSequence(),
  1350  		ThisUpdate:          now.UTC(),
  1351  		NextUpdate:          expiry.UTC(),
  1352  		RevokedCertificates: revokedCerts,
  1353  	}
  1354  
  1355  	tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1356  	if err != nil {
  1357  		return
  1358  	}
  1359  
  1360  	h := sha1.New()
  1361  	h.Write(tbsCertListContents)
  1362  	digest := h.Sum(nil)
  1363  
  1364  	signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
  1365  	if err != nil {
  1366  		return
  1367  	}
  1368  
  1369  	return asn1.Marshal(pkix.CertificateList{
  1370  		TBSCertList: tbsCertList,
  1371  		SignatureAlgorithm: pkix.AlgorithmIdentifier{
  1372  			Algorithm: oidSignatureSHA1WithRSA,
  1373  		},
  1374  		SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1375  	})
  1376  }