src/pkg/crypto/x509/x509.go - The Go Programming Language

Golang

Source file src/pkg/crypto/x509/x509.go

     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/rsa"
    13		"crypto/sha1"
    14		"crypto/x509/pkix"
    15		"encoding/asn1"
    16		"encoding/pem"
    17		"errors"
    18		"io"
    19		"math/big"
    20		"time"
    21	)
    22	
    23	// pkixPublicKey reflects a PKIX public key structure. See SubjectPublicKeyInfo
    24	// in RFC 3280.
    25	type pkixPublicKey struct {
    26		Algo      pkix.AlgorithmIdentifier
    27		BitString asn1.BitString
    28	}
    29	
    30	// ParsePKIXPublicKey parses a DER encoded public key. These values are
    31	// typically found in PEM blocks with "BEGIN PUBLIC KEY".
    32	func ParsePKIXPublicKey(derBytes []byte) (pub interface{}, err error) {
    33		var pki publicKeyInfo
    34		if _, err = asn1.Unmarshal(derBytes, &pki); err != nil {
    35			return
    36		}
    37		algo := getPublicKeyAlgorithmFromOID(pki.Algorithm.Algorithm)
    38		if algo == UnknownPublicKeyAlgorithm {
    39			return nil, errors.New("ParsePKIXPublicKey: unknown public key algorithm")
    40		}
    41		return parsePublicKey(algo, &pki)
    42	}
    43	
    44	// MarshalPKIXPublicKey serialises a public key to DER-encoded PKIX format.
    45	func MarshalPKIXPublicKey(pub interface{}) ([]byte, error) {
    46		var pubBytes []byte
    47	
    48		switch pub := pub.(type) {
    49		case *rsa.PublicKey:
    50			pubBytes, _ = asn1.Marshal(rsaPublicKey{
    51				N: pub.N,
    52				E: pub.E,
    53			})
    54		default:
    55			return nil, errors.New("MarshalPKIXPublicKey: unknown public key type")
    56		}
    57	
    58		pkix := pkixPublicKey{
    59			Algo: pkix.AlgorithmIdentifier{
    60				Algorithm: []int{1, 2, 840, 113549, 1, 1, 1},
    61				// This is a NULL parameters value which is technically
    62				// superfluous, but most other code includes it and, by
    63				// doing this, we match their public key hashes.
    64				Parameters: asn1.RawValue{
    65					Tag: 5,
    66				},
    67			},
    68			BitString: asn1.BitString{
    69				Bytes:     pubBytes,
    70				BitLength: 8 * len(pubBytes),
    71			},
    72		}
    73	
    74		ret, _ := asn1.Marshal(pkix)
    75		return ret, nil
    76	}
    77	
    78	// These structures reflect the ASN.1 structure of X.509 certificates.:
    79	
    80	type certificate struct {
    81		Raw                asn1.RawContent
    82		TBSCertificate     tbsCertificate
    83		SignatureAlgorithm pkix.AlgorithmIdentifier
    84		SignatureValue     asn1.BitString
    85	}
    86	
    87	type tbsCertificate struct {
    88		Raw                asn1.RawContent
    89		Version            int `asn1:"optional,explicit,default:1,tag:0"`
    90		SerialNumber       *big.Int
    91		SignatureAlgorithm pkix.AlgorithmIdentifier
    92		Issuer             asn1.RawValue
    93		Validity           validity
    94		Subject            asn1.RawValue
    95		PublicKey          publicKeyInfo
    96		UniqueId           asn1.BitString   `asn1:"optional,tag:1"`
    97		SubjectUniqueId    asn1.BitString   `asn1:"optional,tag:2"`
    98		Extensions         []pkix.Extension `asn1:"optional,explicit,tag:3"`
    99	}
   100	
   101	type dsaAlgorithmParameters struct {
   102		P, Q, G *big.Int
   103	}
   104	
   105	type dsaSignature struct {
   106		R, S *big.Int
   107	}
   108	
   109	type validity struct {
   110		NotBefore, NotAfter time.Time
   111	}
   112	
   113	type publicKeyInfo struct {
   114		Raw       asn1.RawContent
   115		Algorithm pkix.AlgorithmIdentifier
   116		PublicKey asn1.BitString
   117	}
   118	
   119	// RFC 5280,  4.2.1.1
   120	type authKeyId struct {
   121		Id []byte `asn1:"optional,tag:0"`
   122	}
   123	
   124	type SignatureAlgorithm int
   125	
   126	const (
   127		UnknownSignatureAlgorithm SignatureAlgorithm = iota
   128		MD2WithRSA
   129		MD5WithRSA
   130		SHA1WithRSA
   131		SHA256WithRSA
   132		SHA384WithRSA
   133		SHA512WithRSA
   134		DSAWithSHA1
   135		DSAWithSHA256
   136	)
   137	
   138	type PublicKeyAlgorithm int
   139	
   140	const (
   141		UnknownPublicKeyAlgorithm PublicKeyAlgorithm = iota
   142		RSA
   143		DSA
   144	)
   145	
   146	// OIDs for signature algorithms
   147	//
   148	// pkcs-1 OBJECT IDENTIFIER ::= {
   149	//    iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 }
   150	// 
   151	// 
   152	// RFC 3279 2.2.1 RSA Signature Algorithms
   153	//
   154	// md2WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 2 }
   155	//
   156	// md5WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 4 }
   157	//
   158	// sha-1WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 5 }
   159	// 
   160	// dsaWithSha1 OBJECT IDENTIFIER ::= {
   161	//    iso(1) member-body(2) us(840) x9-57(10040) x9cm(4) 3 } 
   162	//
   163	//
   164	// RFC 4055 5 PKCS #1 Version 1.5
   165	// 
   166	// sha256WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 11 }
   167	//
   168	// sha384WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 12 }
   169	//
   170	// sha512WithRSAEncryption OBJECT IDENTIFIER ::= { pkcs-1 13 }
   171	//
   172	//
   173	// RFC 5758 3.1 DSA Signature Algorithms
   174	//
   175	// dsaWithSha256 OBJECT IDENTIFIER ::= {
   176	//    joint-iso-ccitt(2) country(16) us(840) organization(1) gov(101)
   177	//    csor(3) algorithms(4) id-dsa-with-sha2(3) 2}
   178	//
   179	var (
   180		oidSignatureMD2WithRSA    = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   181		oidSignatureMD5WithRSA    = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   182		oidSignatureSHA1WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   183		oidSignatureSHA256WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   184		oidSignatureSHA384WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   185		oidSignatureSHA512WithRSA = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   186		oidSignatureDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   187		oidSignatureDSAWithSHA256 = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
   188	)
   189	
   190	func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) SignatureAlgorithm {
   191		switch {
   192		case oid.Equal(oidSignatureMD2WithRSA):
   193			return MD2WithRSA
   194		case oid.Equal(oidSignatureMD5WithRSA):
   195			return MD5WithRSA
   196		case oid.Equal(oidSignatureSHA1WithRSA):
   197			return SHA1WithRSA
   198		case oid.Equal(oidSignatureSHA256WithRSA):
   199			return SHA256WithRSA
   200		case oid.Equal(oidSignatureSHA384WithRSA):
   201			return SHA384WithRSA
   202		case oid.Equal(oidSignatureSHA512WithRSA):
   203			return SHA512WithRSA
   204		case oid.Equal(oidSignatureDSAWithSHA1):
   205			return DSAWithSHA1
   206		case oid.Equal(oidSignatureDSAWithSHA256):
   207			return DSAWithSHA256
   208		}
   209		return UnknownSignatureAlgorithm
   210	}
   211	
   212	// RFC 3279, 2.3 Public Key Algorithms
   213	//
   214	// pkcs-1 OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   215	//    rsadsi(113549) pkcs(1) 1 }
   216	//
   217	// rsaEncryption OBJECT IDENTIFIER ::== { pkcs1-1 1 }
   218	//
   219	// id-dsa OBJECT IDENTIFIER ::== { iso(1) member-body(2) us(840)
   220	//    x9-57(10040) x9cm(4) 1 }
   221	var (
   222		oidPublicKeyRsa = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 1}
   223		oidPublicKeyDsa = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 1}
   224	)
   225	
   226	func getPublicKeyAlgorithmFromOID(oid asn1.ObjectIdentifier) PublicKeyAlgorithm {
   227		switch {
   228		case oid.Equal(oidPublicKeyRsa):
   229			return RSA
   230		case oid.Equal(oidPublicKeyDsa):
   231			return DSA
   232		}
   233		return UnknownPublicKeyAlgorithm
   234	}
   235	
   236	// KeyUsage represents the set of actions that are valid for a given key. It's
   237	// a bitmap of the KeyUsage* constants.
   238	type KeyUsage int
   239	
   240	const (
   241		KeyUsageDigitalSignature KeyUsage = 1 << iota
   242		KeyUsageContentCommitment
   243		KeyUsageKeyEncipherment
   244		KeyUsageDataEncipherment
   245		KeyUsageKeyAgreement
   246		KeyUsageCertSign
   247		KeyUsageCRLSign
   248		KeyUsageEncipherOnly
   249		KeyUsageDecipherOnly
   250	)
   251	
   252	// RFC 5280, 4.2.1.12  Extended Key Usage
   253	//
   254	// anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 }
   255	//
   256	// id-kp OBJECT IDENTIFIER ::= { id-pkix 3 }
   257	//
   258	// id-kp-serverAuth             OBJECT IDENTIFIER ::= { id-kp 1 }
   259	// id-kp-clientAuth             OBJECT IDENTIFIER ::= { id-kp 2 }
   260	// id-kp-codeSigning            OBJECT IDENTIFIER ::= { id-kp 3 }
   261	// id-kp-emailProtection        OBJECT IDENTIFIER ::= { id-kp 4 }
   262	// id-kp-timeStamping           OBJECT IDENTIFIER ::= { id-kp 8 }
   263	// id-kp-OCSPSigning            OBJECT IDENTIFIER ::= { id-kp 9 }
   264	var (
   265		oidExtKeyUsageAny             = asn1.ObjectIdentifier{2, 5, 29, 37, 0}
   266		oidExtKeyUsageServerAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 1}
   267		oidExtKeyUsageClientAuth      = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 2}
   268		oidExtKeyUsageCodeSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 3}
   269		oidExtKeyUsageEmailProtection = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 4}
   270		oidExtKeyUsageTimeStamping    = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 8}
   271		oidExtKeyUsageOCSPSigning     = asn1.ObjectIdentifier{1, 3, 6, 1, 5, 5, 7, 3, 9}
   272	)
   273	
   274	// ExtKeyUsage represents an extended set of actions that are valid for a given key.
   275	// Each of the ExtKeyUsage* constants define a unique action.
   276	type ExtKeyUsage int
   277	
   278	const (
   279		ExtKeyUsageAny ExtKeyUsage = iota
   280		ExtKeyUsageServerAuth
   281		ExtKeyUsageClientAuth
   282		ExtKeyUsageCodeSigning
   283		ExtKeyUsageEmailProtection
   284		ExtKeyUsageTimeStamping
   285		ExtKeyUsageOCSPSigning
   286	)
   287	
   288	// A Certificate represents an X.509 certificate.
   289	type Certificate struct {
   290		Raw                     []byte // Complete ASN.1 DER content (certificate, signature algorithm and signature).
   291		RawTBSCertificate       []byte // Certificate part of raw ASN.1 DER content.
   292		RawSubjectPublicKeyInfo []byte // DER encoded SubjectPublicKeyInfo.
   293		RawSubject              []byte // DER encoded Subject
   294		RawIssuer               []byte // DER encoded Issuer
   295	
   296		Signature          []byte
   297		SignatureAlgorithm SignatureAlgorithm
   298	
   299		PublicKeyAlgorithm PublicKeyAlgorithm
   300		PublicKey          interface{}
   301	
   302		Version             int
   303		SerialNumber        *big.Int
   304		Issuer              pkix.Name
   305		Subject             pkix.Name
   306		NotBefore, NotAfter time.Time // Validity bounds.
   307		KeyUsage            KeyUsage
   308	
   309		ExtKeyUsage        []ExtKeyUsage           // Sequence of extended key usages.
   310		UnknownExtKeyUsage []asn1.ObjectIdentifier // Encountered extended key usages unknown to this package.
   311	
   312		BasicConstraintsValid bool // if true then the next two fields are valid.
   313		IsCA                  bool
   314		MaxPathLen            int
   315	
   316		SubjectKeyId   []byte
   317		AuthorityKeyId []byte
   318	
   319		// Subject Alternate Name values
   320		DNSNames       []string
   321		EmailAddresses []string
   322	
   323		// Name constraints
   324		PermittedDNSDomainsCritical bool // if true then the name constraints are marked critical.
   325		PermittedDNSDomains         []string
   326	
   327		PolicyIdentifiers []asn1.ObjectIdentifier
   328	}
   329	
   330	// ErrUnsupportedAlgorithm results from attempting to perform an operation that
   331	// involves algorithms that are not currently implemented.
   332	var ErrUnsupportedAlgorithm = errors.New("crypto/x509: cannot verify signature: algorithm unimplemented")
   333	
   334	// ConstraintViolationError results when a requested usage is not permitted by
   335	// a certificate. For example: checking a signature when the public key isn't a
   336	// certificate signing key.
   337	type ConstraintViolationError struct{}
   338	
   339	func (ConstraintViolationError) Error() string {
   340		return "crypto/x509: invalid signature: parent certificate cannot sign this kind of certificate"
   341	}
   342	
   343	func (c *Certificate) Equal(other *Certificate) bool {
   344		return bytes.Equal(c.Raw, other.Raw)
   345	}
   346	
   347	// CheckSignatureFrom verifies that the signature on c is a valid signature
   348	// from parent.
   349	func (c *Certificate) CheckSignatureFrom(parent *Certificate) (err error) {
   350		// RFC 5280, 4.2.1.9:
   351		// "If the basic constraints extension is not present in a version 3
   352		// certificate, or the extension is present but the cA boolean is not
   353		// asserted, then the certified public key MUST NOT be used to verify
   354		// certificate signatures."
   355		if parent.Version == 3 && !parent.BasicConstraintsValid ||
   356			parent.BasicConstraintsValid && !parent.IsCA {
   357			return ConstraintViolationError{}
   358		}
   359	
   360		if parent.KeyUsage != 0 && parent.KeyUsage&KeyUsageCertSign == 0 {
   361			return ConstraintViolationError{}
   362		}
   363	
   364		if parent.PublicKeyAlgorithm == UnknownPublicKeyAlgorithm {
   365			return ErrUnsupportedAlgorithm
   366		}
   367	
   368		// TODO(agl): don't ignore the path length constraint.
   369	
   370		return parent.CheckSignature(c.SignatureAlgorithm, c.RawTBSCertificate, c.Signature)
   371	}
   372	
   373	// CheckSignature verifies that signature is a valid signature over signed from
   374	// c's public key.
   375	func (c *Certificate) CheckSignature(algo SignatureAlgorithm, signed, signature []byte) (err error) {
   376		var hashType crypto.Hash
   377	
   378		switch algo {
   379		case SHA1WithRSA, DSAWithSHA1:
   380			hashType = crypto.SHA1
   381		case SHA256WithRSA, DSAWithSHA256:
   382			hashType = crypto.SHA256
   383		case SHA384WithRSA:
   384			hashType = crypto.SHA384
   385		case SHA512WithRSA:
   386			hashType = crypto.SHA512
   387		default:
   388			return ErrUnsupportedAlgorithm
   389		}
   390	
   391		h := hashType.New()
   392		if h == nil {
   393			return ErrUnsupportedAlgorithm
   394		}
   395	
   396		h.Write(signed)
   397		digest := h.Sum(nil)
   398	
   399		switch pub := c.PublicKey.(type) {
   400		case *rsa.PublicKey:
   401			return rsa.VerifyPKCS1v15(pub, hashType, digest, signature)
   402		case *dsa.PublicKey:
   403			dsaSig := new(dsaSignature)
   404			if _, err := asn1.Unmarshal(signature, dsaSig); err != nil {
   405				return err
   406			}
   407			if dsaSig.R.Sign() <= 0 || dsaSig.S.Sign() <= 0 {
   408				return errors.New("DSA signature contained zero or negative values")
   409			}
   410			if !dsa.Verify(pub, digest, dsaSig.R, dsaSig.S) {
   411				return errors.New("DSA verification failure")
   412			}
   413			return
   414		}
   415		return ErrUnsupportedAlgorithm
   416	}
   417	
   418	// CheckCRLSignature checks that the signature in crl is from c.
   419	func (c *Certificate) CheckCRLSignature(crl *pkix.CertificateList) (err error) {
   420		algo := getSignatureAlgorithmFromOID(crl.SignatureAlgorithm.Algorithm)
   421		return c.CheckSignature(algo, crl.TBSCertList.Raw, crl.SignatureValue.RightAlign())
   422	}
   423	
   424	type UnhandledCriticalExtension struct{}
   425	
   426	func (h UnhandledCriticalExtension) Error() string {
   427		return "unhandled critical extension"
   428	}
   429	
   430	type basicConstraints struct {
   431		IsCA       bool `asn1:"optional"`
   432		MaxPathLen int  `asn1:"optional,default:-1"`
   433	}
   434	
   435	// RFC 5280 4.2.1.4
   436	type policyInformation struct {
   437		Policy asn1.ObjectIdentifier
   438		// policyQualifiers omitted
   439	}
   440	
   441	// RFC 5280, 4.2.1.10
   442	type nameConstraints struct {
   443		Permitted []generalSubtree `asn1:"optional,tag:0"`
   444		Excluded  []generalSubtree `asn1:"optional,tag:1"`
   445	}
   446	
   447	type generalSubtree struct {
   448		Name string `asn1:"tag:2,optional,ia5"`
   449		Min  int    `asn1:"optional,tag:0"`
   450		Max  int    `asn1:"optional,tag:1"`
   451	}
   452	
   453	func parsePublicKey(algo PublicKeyAlgorithm, keyData *publicKeyInfo) (interface{}, error) {
   454		asn1Data := keyData.PublicKey.RightAlign()
   455		switch algo {
   456		case RSA:
   457			p := new(rsaPublicKey)
   458			_, err := asn1.Unmarshal(asn1Data, p)
   459			if err != nil {
   460				return nil, err
   461			}
   462	
   463			pub := &rsa.PublicKey{
   464				E: p.E,
   465				N: p.N,
   466			}
   467			return pub, nil
   468		case DSA:
   469			var p *big.Int
   470			_, err := asn1.Unmarshal(asn1Data, &p)
   471			if err != nil {
   472				return nil, err
   473			}
   474			paramsData := keyData.Algorithm.Parameters.FullBytes
   475			params := new(dsaAlgorithmParameters)
   476			_, err = asn1.Unmarshal(paramsData, params)
   477			if err != nil {
   478				return nil, err
   479			}
   480			if p.Sign() <= 0 || params.P.Sign() <= 0 || params.Q.Sign() <= 0 || params.G.Sign() <= 0 {
   481				return nil, errors.New("zero or negative DSA parameter")
   482			}
   483			pub := &dsa.PublicKey{
   484				Parameters: dsa.Parameters{
   485					P: params.P,
   486					Q: params.Q,
   487					G: params.G,
   488				},
   489				Y: p,
   490			}
   491			return pub, nil
   492		default:
   493			return nil, nil
   494		}
   495		panic("unreachable")
   496	}
   497	
   498	func parseCertificate(in *certificate) (*Certificate, error) {
   499		out := new(Certificate)
   500		out.Raw = in.Raw
   501		out.RawTBSCertificate = in.TBSCertificate.Raw
   502		out.RawSubjectPublicKeyInfo = in.TBSCertificate.PublicKey.Raw
   503		out.RawSubject = in.TBSCertificate.Subject.FullBytes
   504		out.RawIssuer = in.TBSCertificate.Issuer.FullBytes
   505	
   506		out.Signature = in.SignatureValue.RightAlign()
   507		out.SignatureAlgorithm =
   508			getSignatureAlgorithmFromOID(in.TBSCertificate.SignatureAlgorithm.Algorithm)
   509	
   510		out.PublicKeyAlgorithm =
   511			getPublicKeyAlgorithmFromOID(in.TBSCertificate.PublicKey.Algorithm.Algorithm)
   512		var err error
   513		out.PublicKey, err = parsePublicKey(out.PublicKeyAlgorithm, &in.TBSCertificate.PublicKey)
   514		if err != nil {
   515			return nil, err
   516		}
   517	
   518		if in.TBSCertificate.SerialNumber.Sign() < 0 {
   519			return nil, errors.New("negative serial number")
   520		}
   521	
   522		out.Version = in.TBSCertificate.Version + 1
   523		out.SerialNumber = in.TBSCertificate.SerialNumber
   524	
   525		var issuer, subject pkix.RDNSequence
   526		if _, err := asn1.Unmarshal(in.TBSCertificate.Subject.FullBytes, &subject); err != nil {
   527			return nil, err
   528		}
   529		if _, err := asn1.Unmarshal(in.TBSCertificate.Issuer.FullBytes, &issuer); err != nil {
   530			return nil, err
   531		}
   532	
   533		out.Issuer.FillFromRDNSequence(&issuer)
   534		out.Subject.FillFromRDNSequence(&subject)
   535	
   536		out.NotBefore = in.TBSCertificate.Validity.NotBefore
   537		out.NotAfter = in.TBSCertificate.Validity.NotAfter
   538	
   539		for _, e := range in.TBSCertificate.Extensions {
   540			if len(e.Id) == 4 && e.Id[0] == 2 && e.Id[1] == 5 && e.Id[2] == 29 {
   541				switch e.Id[3] {
   542				case 15:
   543					// RFC 5280, 4.2.1.3
   544					var usageBits asn1.BitString
   545					_, err := asn1.Unmarshal(e.Value, &usageBits)
   546	
   547					if err == nil {
   548						var usage int
   549						for i := 0; i < 9; i++ {
   550							if usageBits.At(i) != 0 {
   551								usage |= 1 << uint(i)
   552							}
   553						}
   554						out.KeyUsage = KeyUsage(usage)
   555						continue
   556					}
   557				case 19:
   558					// RFC 5280, 4.2.1.9
   559					var constraints basicConstraints
   560					_, err := asn1.Unmarshal(e.Value, &constraints)
   561	
   562					if err == nil {
   563						out.BasicConstraintsValid = true
   564						out.IsCA = constraints.IsCA
   565						out.MaxPathLen = constraints.MaxPathLen
   566						continue
   567					}
   568				case 17:
   569					// RFC 5280, 4.2.1.6
   570	
   571					// SubjectAltName ::= GeneralNames
   572					//
   573					// GeneralNames ::= SEQUENCE SIZE (1..MAX) OF GeneralName
   574					//
   575					// GeneralName ::= CHOICE {
   576					//      otherName                       [0]     OtherName,
   577					//      rfc822Name                      [1]     IA5String,
   578					//      dNSName                         [2]     IA5String,
   579					//      x400Address                     [3]     ORAddress,
   580					//      directoryName                   [4]     Name,
   581					//      ediPartyName                    [5]     EDIPartyName,
   582					//      uniformResourceIdentifier       [6]     IA5String,
   583					//      iPAddress                       [7]     OCTET STRING,
   584					//      registeredID                    [8]     OBJECT IDENTIFIER }
   585					var seq asn1.RawValue
   586					_, err := asn1.Unmarshal(e.Value, &seq)
   587					if err != nil {
   588						return nil, err
   589					}
   590					if !seq.IsCompound || seq.Tag != 16 || seq.Class != 0 {
   591						return nil, asn1.StructuralError{Msg: "bad SAN sequence"}
   592					}
   593	
   594					parsedName := false
   595	
   596					rest := seq.Bytes
   597					for len(rest) > 0 {
   598						var v asn1.RawValue
   599						rest, err = asn1.Unmarshal(rest, &v)
   600						if err != nil {
   601							return nil, err
   602						}
   603						switch v.Tag {
   604						case 1:
   605							out.EmailAddresses = append(out.EmailAddresses, string(v.Bytes))
   606							parsedName = true
   607						case 2:
   608							out.DNSNames = append(out.DNSNames, string(v.Bytes))
   609							parsedName = true
   610						}
   611					}
   612	
   613					if parsedName {
   614						continue
   615					}
   616					// If we didn't parse any of the names then we
   617					// fall through to the critical check below.
   618	
   619				case 30:
   620					// RFC 5280, 4.2.1.10
   621	
   622					// NameConstraints ::= SEQUENCE {
   623					//      permittedSubtrees       [0]     GeneralSubtrees OPTIONAL,
   624					//      excludedSubtrees        [1]     GeneralSubtrees OPTIONAL }
   625					//
   626					// GeneralSubtrees ::= SEQUENCE SIZE (1..MAX) OF GeneralSubtree
   627					//
   628					// GeneralSubtree ::= SEQUENCE {
   629					//      base                    GeneralName,
   630					//      minimum         [0]     BaseDistance DEFAULT 0,
   631					//      maximum         [1]     BaseDistance OPTIONAL }
   632					//
   633					// BaseDistance ::= INTEGER (0..MAX)
   634	
   635					var constraints nameConstraints
   636					_, err := asn1.Unmarshal(e.Value, &constraints)
   637					if err != nil {
   638						return nil, err
   639					}
   640	
   641					if len(constraints.Excluded) > 0 && e.Critical {
   642						return out, UnhandledCriticalExtension{}
   643					}
   644	
   645					for _, subtree := range constraints.Permitted {
   646						if subtree.Min > 0 || subtree.Max > 0 || len(subtree.Name) == 0 {
   647							if e.Critical {
   648								return out, UnhandledCriticalExtension{}
   649							}
   650							continue
   651						}
   652						out.PermittedDNSDomains = append(out.PermittedDNSDomains, subtree.Name)
   653					}
   654					continue
   655	
   656				case 35:
   657					// RFC 5280, 4.2.1.1
   658					var a authKeyId
   659					_, err = asn1.Unmarshal(e.Value, &a)
   660					if err != nil {
   661						return nil, err
   662					}
   663					out.AuthorityKeyId = a.Id
   664					continue
   665	
   666				case 37:
   667					// RFC 5280, 4.2.1.12.  Extended Key Usage
   668	
   669					// id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 }
   670					//
   671					// ExtKeyUsageSyntax ::= SEQUENCE SIZE (1..MAX) OF KeyPurposeId
   672					//
   673					// KeyPurposeId ::= OBJECT IDENTIFIER
   674	
   675					var keyUsage []asn1.ObjectIdentifier
   676					_, err = asn1.Unmarshal(e.Value, &keyUsage)
   677					if err != nil {
   678						return nil, err
   679					}
   680	
   681					for _, u := range keyUsage {
   682						switch {
   683						case u.Equal(oidExtKeyUsageAny):
   684							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageAny)
   685						case u.Equal(oidExtKeyUsageServerAuth):
   686							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageServerAuth)
   687						case u.Equal(oidExtKeyUsageClientAuth):
   688							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageClientAuth)
   689						case u.Equal(oidExtKeyUsageCodeSigning):
   690							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageCodeSigning)
   691						case u.Equal(oidExtKeyUsageEmailProtection):
   692							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageEmailProtection)
   693						case u.Equal(oidExtKeyUsageTimeStamping):
   694							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageTimeStamping)
   695						case u.Equal(oidExtKeyUsageOCSPSigning):
   696							out.ExtKeyUsage = append(out.ExtKeyUsage, ExtKeyUsageOCSPSigning)
   697						default:
   698							out.UnknownExtKeyUsage = append(out.UnknownExtKeyUsage, u)
   699						}
   700					}
   701	
   702					continue
   703	
   704				case 14:
   705					// RFC 5280, 4.2.1.2
   706					var keyid []byte
   707					_, err = asn1.Unmarshal(e.Value, &keyid)
   708					if err != nil {
   709						return nil, err
   710					}
   711					out.SubjectKeyId = keyid
   712					continue
   713	
   714				case 32:
   715					// RFC 5280 4.2.1.4: Certificate Policies
   716					var policies []policyInformation
   717					if _, err = asn1.Unmarshal(e.Value, &policies); err != nil {
   718						return nil, err
   719					}
   720					out.PolicyIdentifiers = make([]asn1.ObjectIdentifier, len(policies))
   721					for i, policy := range policies {
   722						out.PolicyIdentifiers[i] = policy.Policy
   723					}
   724				}
   725			}
   726	
   727			if e.Critical {
   728				return out, UnhandledCriticalExtension{}
   729			}
   730		}
   731	
   732		return out, nil
   733	}
   734	
   735	// ParseCertificate parses a single certificate from the given ASN.1 DER data.
   736	func ParseCertificate(asn1Data []byte) (*Certificate, error) {
   737		var cert certificate
   738		rest, err := asn1.Unmarshal(asn1Data, &cert)
   739		if err != nil {
   740			return nil, err
   741		}
   742		if len(rest) > 0 {
   743			return nil, asn1.SyntaxError{Msg: "trailing data"}
   744		}
   745	
   746		return parseCertificate(&cert)
   747	}
   748	
   749	// ParseCertificates parses one or more certificates from the given ASN.1 DER
   750	// data. The certificates must be concatenated with no intermediate padding.
   751	func ParseCertificates(asn1Data []byte) ([]*Certificate, error) {
   752		var v []*certificate
   753	
   754		for len(asn1Data) > 0 {
   755			cert := new(certificate)
   756			var err error
   757			asn1Data, err = asn1.Unmarshal(asn1Data, cert)
   758			if err != nil {
   759				return nil, err
   760			}
   761			v = append(v, cert)
   762		}
   763	
   764		ret := make([]*Certificate, len(v))
   765		for i, ci := range v {
   766			cert, err := parseCertificate(ci)
   767			if err != nil {
   768				return nil, err
   769			}
   770			ret[i] = cert
   771		}
   772	
   773		return ret, nil
   774	}
   775	
   776	func reverseBitsInAByte(in byte) byte {
   777		b1 := in>>4 | in<<4
   778		b2 := b1>>2&0x33 | b1<<2&0xcc
   779		b3 := b2>>1&0x55 | b2<<1&0xaa
   780		return b3
   781	}
   782	
   783	var (
   784		oidExtensionSubjectKeyId        = []int{2, 5, 29, 14}
   785		oidExtensionKeyUsage            = []int{2, 5, 29, 15}
   786		oidExtensionAuthorityKeyId      = []int{2, 5, 29, 35}
   787		oidExtensionBasicConstraints    = []int{2, 5, 29, 19}
   788		oidExtensionSubjectAltName      = []int{2, 5, 29, 17}
   789		oidExtensionCertificatePolicies = []int{2, 5, 29, 32}
   790		oidExtensionNameConstraints     = []int{2, 5, 29, 30}
   791	)
   792	
   793	func buildExtensions(template *Certificate) (ret []pkix.Extension, err error) {
   794		ret = make([]pkix.Extension, 7 /* maximum number of elements. */)
   795		n := 0
   796	
   797		if template.KeyUsage != 0 {
   798			ret[n].Id = oidExtensionKeyUsage
   799			ret[n].Critical = true
   800	
   801			var a [2]byte
   802			a[0] = reverseBitsInAByte(byte(template.KeyUsage))
   803			a[1] = reverseBitsInAByte(byte(template.KeyUsage >> 8))
   804	
   805			l := 1
   806			if a[1] != 0 {
   807				l = 2
   808			}
   809	
   810			ret[n].Value, err = asn1.Marshal(asn1.BitString{Bytes: a[0:l], BitLength: l * 8})
   811			if err != nil {
   812				return
   813			}
   814			n++
   815		}
   816	
   817		if template.BasicConstraintsValid {
   818			ret[n].Id = oidExtensionBasicConstraints
   819			ret[n].Value, err = asn1.Marshal(basicConstraints{template.IsCA, template.MaxPathLen})
   820			ret[n].Critical = true
   821			if err != nil {
   822				return
   823			}
   824			n++
   825		}
   826	
   827		if len(template.SubjectKeyId) > 0 {
   828			ret[n].Id = oidExtensionSubjectKeyId
   829			ret[n].Value, err = asn1.Marshal(template.SubjectKeyId)
   830			if err != nil {
   831				return
   832			}
   833			n++
   834		}
   835	
   836		if len(template.AuthorityKeyId) > 0 {
   837			ret[n].Id = oidExtensionAuthorityKeyId
   838			ret[n].Value, err = asn1.Marshal(authKeyId{template.AuthorityKeyId})
   839			if err != nil {
   840				return
   841			}
   842			n++
   843		}
   844	
   845		if len(template.DNSNames) > 0 {
   846			ret[n].Id = oidExtensionSubjectAltName
   847			rawValues := make([]asn1.RawValue, len(template.DNSNames))
   848			for i, name := range template.DNSNames {
   849				rawValues[i] = asn1.RawValue{Tag: 2, Class: 2, Bytes: []byte(name)}
   850			}
   851			ret[n].Value, err = asn1.Marshal(rawValues)
   852			if err != nil {
   853				return
   854			}
   855			n++
   856		}
   857	
   858		if len(template.PolicyIdentifiers) > 0 {
   859			ret[n].Id = oidExtensionCertificatePolicies
   860			policies := make([]policyInformation, len(template.PolicyIdentifiers))
   861			for i, policy := range template.PolicyIdentifiers {
   862				policies[i].Policy = policy
   863			}
   864			ret[n].Value, err = asn1.Marshal(policies)
   865			if err != nil {
   866				return
   867			}
   868			n++
   869		}
   870	
   871		if len(template.PermittedDNSDomains) > 0 {
   872			ret[n].Id = oidExtensionNameConstraints
   873			ret[n].Critical = template.PermittedDNSDomainsCritical
   874	
   875			var out nameConstraints
   876			out.Permitted = make([]generalSubtree, len(template.PermittedDNSDomains))
   877			for i, permitted := range template.PermittedDNSDomains {
   878				out.Permitted[i] = generalSubtree{Name: permitted}
   879			}
   880			ret[n].Value, err = asn1.Marshal(out)
   881			if err != nil {
   882				return
   883			}
   884			n++
   885		}
   886	
   887		// Adding another extension here? Remember to update the maximum number
   888		// of elements in the make() at the top of the function.
   889	
   890		return ret[0:n], nil
   891	}
   892	
   893	var (
   894		oidSHA1WithRSA = []int{1, 2, 840, 113549, 1, 1, 5}
   895		oidRSA         = []int{1, 2, 840, 113549, 1, 1, 1}
   896	)
   897	
   898	func subjectBytes(cert *Certificate) ([]byte, error) {
   899		if len(cert.RawSubject) > 0 {
   900			return cert.RawSubject, nil
   901		}
   902	
   903		return asn1.Marshal(cert.Subject.ToRDNSequence())
   904	}
   905	
   906	// CreateCertificate creates a new certificate based on a template. The
   907	// following members of template are used: SerialNumber, Subject, NotBefore,
   908	// NotAfter, KeyUsage, BasicConstraintsValid, IsCA, MaxPathLen, SubjectKeyId,
   909	// DNSNames, PermittedDNSDomainsCritical, PermittedDNSDomains.
   910	//
   911	// The certificate is signed by parent. If parent is equal to template then the
   912	// certificate is self-signed. The parameter pub is the public key of the
   913	// signee and priv is the private key of the signer.
   914	//
   915	// The returned slice is the certificate in DER encoding.
   916	//
   917	// The only supported key type is RSA (*rsa.PublicKey for pub, *rsa.PrivateKey
   918	// for priv).
   919	func CreateCertificate(rand io.Reader, template, parent *Certificate, pub interface{}, priv interface{}) (cert []byte, err error) {
   920		rsaPub, ok := pub.(*rsa.PublicKey)
   921		if !ok {
   922			return nil, errors.New("x509: non-RSA public keys not supported")
   923		}
   924	
   925		rsaPriv, ok := priv.(*rsa.PrivateKey)
   926		if !ok {
   927			return nil, errors.New("x509: non-RSA private keys not supported")
   928		}
   929	
   930		asn1PublicKey, err := asn1.Marshal(rsaPublicKey{
   931			N: rsaPub.N,
   932			E: rsaPub.E,
   933		})
   934		if err != nil {
   935			return
   936		}
   937	
   938		if len(parent.SubjectKeyId) > 0 {
   939			template.AuthorityKeyId = parent.SubjectKeyId
   940		}
   941	
   942		extensions, err := buildExtensions(template)
   943		if err != nil {
   944			return
   945		}
   946	
   947		asn1Issuer, err := subjectBytes(parent)
   948		if err != nil {
   949			return
   950		}
   951	
   952		asn1Subject, err := subjectBytes(template)
   953		if err != nil {
   954			return
   955		}
   956	
   957		encodedPublicKey := asn1.BitString{BitLength: len(asn1PublicKey) * 8, Bytes: asn1PublicKey}
   958		c := tbsCertificate{
   959			Version:            2,
   960			SerialNumber:       template.SerialNumber,
   961			SignatureAlgorithm: pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
   962			Issuer:             asn1.RawValue{FullBytes: asn1Issuer},
   963			Validity:           validity{template.NotBefore, template.NotAfter},
   964			Subject:            asn1.RawValue{FullBytes: asn1Subject},
   965			PublicKey:          publicKeyInfo{nil, pkix.AlgorithmIdentifier{Algorithm: oidRSA}, encodedPublicKey},
   966			Extensions:         extensions,
   967		}
   968	
   969		tbsCertContents, err := asn1.Marshal(c)
   970		if err != nil {
   971			return
   972		}
   973	
   974		c.Raw = tbsCertContents
   975	
   976		h := sha1.New()
   977		h.Write(tbsCertContents)
   978		digest := h.Sum(nil)
   979	
   980		signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
   981		if err != nil {
   982			return
   983		}
   984	
   985		cert, err = asn1.Marshal(certificate{
   986			nil,
   987			c,
   988			pkix.AlgorithmIdentifier{Algorithm: oidSHA1WithRSA},
   989			asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
   990		})
   991		return
   992	}
   993	
   994	// pemCRLPrefix is the magic string that indicates that we have a PEM encoded
   995	// CRL.
   996	var pemCRLPrefix = []byte("-----BEGIN X509 CRL")
   997	
   998	// pemType is the type of a PEM encoded CRL.
   999	var pemType = "X509 CRL"
  1000	
  1001	// ParseCRL parses a CRL from the given bytes. It's often the case that PEM
  1002	// encoded CRLs will appear where they should be DER encoded, so this function
  1003	// will transparently handle PEM encoding as long as there isn't any leading
  1004	// garbage.
  1005	func ParseCRL(crlBytes []byte) (certList *pkix.CertificateList, err error) {
  1006		if bytes.HasPrefix(crlBytes, pemCRLPrefix) {
  1007			block, _ := pem.Decode(crlBytes)
  1008			if block != nil && block.Type == pemType {
  1009				crlBytes = block.Bytes
  1010			}
  1011		}
  1012		return ParseDERCRL(crlBytes)
  1013	}
  1014	
  1015	// ParseDERCRL parses a DER encoded CRL from the given bytes.
  1016	func ParseDERCRL(derBytes []byte) (certList *pkix.CertificateList, err error) {
  1017		certList = new(pkix.CertificateList)
  1018		_, err = asn1.Unmarshal(derBytes, certList)
  1019		if err != nil {
  1020			certList = nil
  1021		}
  1022		return
  1023	}
  1024	
  1025	// CreateCRL returns a DER encoded CRL, signed by this Certificate, that
  1026	// contains the given list of revoked certificates.
  1027	//
  1028	// The only supported key type is RSA (*rsa.PrivateKey for priv).
  1029	func (c *Certificate) CreateCRL(rand io.Reader, priv interface{}, revokedCerts []pkix.RevokedCertificate, now, expiry time.Time) (crlBytes []byte, err error) {
  1030		rsaPriv, ok := priv.(*rsa.PrivateKey)
  1031		if !ok {
  1032			return nil, errors.New("x509: non-RSA private keys not supported")
  1033		}
  1034		tbsCertList := pkix.TBSCertificateList{
  1035			Version: 2,
  1036			Signature: pkix.AlgorithmIdentifier{
  1037				Algorithm: oidSignatureSHA1WithRSA,
  1038			},
  1039			Issuer:              c.Subject.ToRDNSequence(),
  1040			ThisUpdate:          now,
  1041			NextUpdate:          expiry,
  1042			RevokedCertificates: revokedCerts,
  1043		}
  1044	
  1045		tbsCertListContents, err := asn1.Marshal(tbsCertList)
  1046		if err != nil {
  1047			return
  1048		}
  1049	
  1050		h := sha1.New()
  1051		h.Write(tbsCertListContents)
  1052		digest := h.Sum(nil)
  1053	
  1054		signature, err := rsa.SignPKCS1v15(rand, rsaPriv, crypto.SHA1, digest)
  1055		if err != nil {
  1056			return
  1057		}
  1058	
  1059		return asn1.Marshal(pkix.CertificateList{
  1060			TBSCertList: tbsCertList,
  1061			SignatureAlgorithm: pkix.AlgorithmIdentifier{
  1062				Algorithm: oidSignatureSHA1WithRSA,
  1063			},
  1064			SignatureValue: asn1.BitString{Bytes: signature, BitLength: len(signature) * 8},
  1065		})
  1066	}