The Go Programming Language

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

release.r60.3. Except as noted, this content is licensed under a Creative Commons Attribution 3.0 License.