github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/crypto/ocsp/ocsp.go (about)

     1  // Copyright 2013 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 ocsp parses OCSP responses as specified in RFC 2560. OCSP responses
     6  // are signed messages attesting to the validity of a certificate for a small
     7  // period of time. This is used to manage revocation for X.509 certificates.
     8  package ocsp // import "golang.org/x/crypto/ocsp"
     9  
    10  import (
    11  	"crypto"
    12  	"crypto/ecdsa"
    13  	"crypto/elliptic"
    14  	"crypto/rand"
    15  	"crypto/rsa"
    16  	"crypto/sha1"
    17  	"crypto/x509"
    18  	"crypto/x509/pkix"
    19  	"encoding/asn1"
    20  	"errors"
    21  	"math/big"
    22  	"time"
    23  )
    24  
    25  var idPKIXOCSPBasic = asn1.ObjectIdentifier([]int{1, 3, 6, 1, 5, 5, 7, 48, 1, 1})
    26  
    27  // These are internal structures that reflect the ASN.1 structure of an OCSP
    28  // response. See RFC 2560, section 4.2.
    29  
    30  const (
    31  	ocspSuccess       = 0
    32  	ocspMalformed     = 1
    33  	ocspInternalError = 2
    34  	ocspTryLater      = 3
    35  	ocspSigRequired   = 4
    36  	ocspUnauthorized  = 5
    37  )
    38  
    39  type certID struct {
    40  	HashAlgorithm pkix.AlgorithmIdentifier
    41  	NameHash      []byte
    42  	IssuerKeyHash []byte
    43  	SerialNumber  *big.Int
    44  }
    45  
    46  // https://tools.ietf.org/html/rfc2560#section-4.1.1
    47  type ocspRequest struct {
    48  	TBSRequest tbsRequest
    49  }
    50  
    51  type tbsRequest struct {
    52  	Version       int              `asn1:"explicit,tag:0,default:0,optional"`
    53  	RequestorName pkix.RDNSequence `asn1:"explicit,tag:1,optional"`
    54  	RequestList   []request
    55  }
    56  
    57  type request struct {
    58  	Cert certID
    59  }
    60  
    61  type responseASN1 struct {
    62  	Status   asn1.Enumerated
    63  	Response responseBytes `asn1:"explicit,tag:0"`
    64  }
    65  
    66  type responseBytes struct {
    67  	ResponseType asn1.ObjectIdentifier
    68  	Response     []byte
    69  }
    70  
    71  type basicResponse struct {
    72  	TBSResponseData    responseData
    73  	SignatureAlgorithm pkix.AlgorithmIdentifier
    74  	Signature          asn1.BitString
    75  	Certificates       []asn1.RawValue `asn1:"explicit,tag:0,optional"`
    76  }
    77  
    78  type responseData struct {
    79  	Raw              asn1.RawContent
    80  	Version          int           `asn1:"optional,default:1,explicit,tag:0"`
    81  	RawResponderName asn1.RawValue `asn1:"optional,explicit,tag:1"`
    82  	KeyHash          []byte        `asn1:"optional,explicit,tag:2"`
    83  	ProducedAt       time.Time     `asn1:"generalized"`
    84  	Responses        []singleResponse
    85  }
    86  
    87  type singleResponse struct {
    88  	CertID           certID
    89  	Good             asn1.Flag        `asn1:"tag:0,optional"`
    90  	Revoked          revokedInfo      `asn1:"tag:1,optional"`
    91  	Unknown          asn1.Flag        `asn1:"tag:2,optional"`
    92  	ThisUpdate       time.Time        `asn1:"generalized"`
    93  	NextUpdate       time.Time        `asn1:"generalized,explicit,tag:0,optional"`
    94  	SingleExtensions []pkix.Extension `asn1:"explicit,tag:1,optional"`
    95  }
    96  
    97  type revokedInfo struct {
    98  	RevocationTime time.Time       `asn1:"generalized"`
    99  	Reason         asn1.Enumerated `asn1:"explicit,tag:0,optional"`
   100  }
   101  
   102  var (
   103  	oidSignatureMD2WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 2}
   104  	oidSignatureMD5WithRSA      = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 4}
   105  	oidSignatureSHA1WithRSA     = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 5}
   106  	oidSignatureSHA256WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 11}
   107  	oidSignatureSHA384WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 12}
   108  	oidSignatureSHA512WithRSA   = asn1.ObjectIdentifier{1, 2, 840, 113549, 1, 1, 13}
   109  	oidSignatureDSAWithSHA1     = asn1.ObjectIdentifier{1, 2, 840, 10040, 4, 3}
   110  	oidSignatureDSAWithSHA256   = asn1.ObjectIdentifier{2, 16, 840, 1, 101, 4, 3, 2}
   111  	oidSignatureECDSAWithSHA1   = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 1}
   112  	oidSignatureECDSAWithSHA256 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 2}
   113  	oidSignatureECDSAWithSHA384 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 3}
   114  	oidSignatureECDSAWithSHA512 = asn1.ObjectIdentifier{1, 2, 840, 10045, 4, 3, 4}
   115  )
   116  
   117  var hashOIDs = map[crypto.Hash]asn1.ObjectIdentifier{
   118  	crypto.SHA1:   asn1.ObjectIdentifier([]int{1, 3, 14, 3, 2, 26}),
   119  	crypto.SHA256: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 1}),
   120  	crypto.SHA384: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 2}),
   121  	crypto.SHA512: asn1.ObjectIdentifier([]int{2, 16, 840, 1, 101, 3, 4, 2, 3}),
   122  }
   123  
   124  // TODO(rlb): This is also from crypto/x509, so same comment as AGL's below
   125  var signatureAlgorithmDetails = []struct {
   126  	algo       x509.SignatureAlgorithm
   127  	oid        asn1.ObjectIdentifier
   128  	pubKeyAlgo x509.PublicKeyAlgorithm
   129  	hash       crypto.Hash
   130  }{
   131  	{x509.MD2WithRSA, oidSignatureMD2WithRSA, x509.RSA, crypto.Hash(0) /* no value for MD2 */},
   132  	{x509.MD5WithRSA, oidSignatureMD5WithRSA, x509.RSA, crypto.MD5},
   133  	{x509.SHA1WithRSA, oidSignatureSHA1WithRSA, x509.RSA, crypto.SHA1},
   134  	{x509.SHA256WithRSA, oidSignatureSHA256WithRSA, x509.RSA, crypto.SHA256},
   135  	{x509.SHA384WithRSA, oidSignatureSHA384WithRSA, x509.RSA, crypto.SHA384},
   136  	{x509.SHA512WithRSA, oidSignatureSHA512WithRSA, x509.RSA, crypto.SHA512},
   137  	{x509.DSAWithSHA1, oidSignatureDSAWithSHA1, x509.DSA, crypto.SHA1},
   138  	{x509.DSAWithSHA256, oidSignatureDSAWithSHA256, x509.DSA, crypto.SHA256},
   139  	{x509.ECDSAWithSHA1, oidSignatureECDSAWithSHA1, x509.ECDSA, crypto.SHA1},
   140  	{x509.ECDSAWithSHA256, oidSignatureECDSAWithSHA256, x509.ECDSA, crypto.SHA256},
   141  	{x509.ECDSAWithSHA384, oidSignatureECDSAWithSHA384, x509.ECDSA, crypto.SHA384},
   142  	{x509.ECDSAWithSHA512, oidSignatureECDSAWithSHA512, x509.ECDSA, crypto.SHA512},
   143  }
   144  
   145  // TODO(rlb): This is also from crypto/x509, so same comment as AGL's below
   146  func signingParamsForPublicKey(pub interface{}, requestedSigAlgo x509.SignatureAlgorithm) (hashFunc crypto.Hash, sigAlgo pkix.AlgorithmIdentifier, err error) {
   147  	var pubType x509.PublicKeyAlgorithm
   148  
   149  	switch pub := pub.(type) {
   150  	case *rsa.PublicKey:
   151  		pubType = x509.RSA
   152  		hashFunc = crypto.SHA256
   153  		sigAlgo.Algorithm = oidSignatureSHA256WithRSA
   154  		sigAlgo.Parameters = asn1.RawValue{
   155  			Tag: 5,
   156  		}
   157  
   158  	case *ecdsa.PublicKey:
   159  		pubType = x509.ECDSA
   160  
   161  		switch pub.Curve {
   162  		case elliptic.P224(), elliptic.P256():
   163  			hashFunc = crypto.SHA256
   164  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA256
   165  		case elliptic.P384():
   166  			hashFunc = crypto.SHA384
   167  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA384
   168  		case elliptic.P521():
   169  			hashFunc = crypto.SHA512
   170  			sigAlgo.Algorithm = oidSignatureECDSAWithSHA512
   171  		default:
   172  			err = errors.New("x509: unknown elliptic curve")
   173  		}
   174  
   175  	default:
   176  		err = errors.New("x509: only RSA and ECDSA keys supported")
   177  	}
   178  
   179  	if err != nil {
   180  		return
   181  	}
   182  
   183  	if requestedSigAlgo == 0 {
   184  		return
   185  	}
   186  
   187  	found := false
   188  	for _, details := range signatureAlgorithmDetails {
   189  		if details.algo == requestedSigAlgo {
   190  			if details.pubKeyAlgo != pubType {
   191  				err = errors.New("x509: requested SignatureAlgorithm does not match private key type")
   192  				return
   193  			}
   194  			sigAlgo.Algorithm, hashFunc = details.oid, details.hash
   195  			if hashFunc == 0 {
   196  				err = errors.New("x509: cannot sign with hash function requested")
   197  				return
   198  			}
   199  			found = true
   200  			break
   201  		}
   202  	}
   203  
   204  	if !found {
   205  		err = errors.New("x509: unknown SignatureAlgorithm")
   206  	}
   207  
   208  	return
   209  }
   210  
   211  // TODO(agl): this is taken from crypto/x509 and so should probably be exported
   212  // from crypto/x509 or crypto/x509/pkix.
   213  func getSignatureAlgorithmFromOID(oid asn1.ObjectIdentifier) x509.SignatureAlgorithm {
   214  	for _, details := range signatureAlgorithmDetails {
   215  		if oid.Equal(details.oid) {
   216  			return details.algo
   217  		}
   218  	}
   219  	return x509.UnknownSignatureAlgorithm
   220  }
   221  
   222  // TODO(rlb): This is not taken from crypto/x509, but it's of the same general form.
   223  func getHashAlgorithmFromOID(target asn1.ObjectIdentifier) crypto.Hash {
   224  	for hash, oid := range hashOIDs {
   225  		if oid.Equal(target) {
   226  			return hash
   227  		}
   228  	}
   229  	return crypto.Hash(0)
   230  }
   231  
   232  // This is the exposed reflection of the internal OCSP structures.
   233  
   234  // The status values that can be expressed in OCSP.  See RFC 6960.
   235  const (
   236  	// Good means that the certificate is valid.
   237  	Good = iota
   238  	// Revoked means that the certificate has been deliberately revoked.
   239  	Revoked = iota
   240  	// Unknown means that the OCSP responder doesn't know about the certificate.
   241  	Unknown = iota
   242  	// ServerFailed means that the OCSP responder failed to process the request.
   243  	ServerFailed = iota
   244  )
   245  
   246  // The enumerated reasons for revoking a certificate.  See RFC 5280.
   247  const (
   248  	Unspecified          = iota
   249  	KeyCompromise        = iota
   250  	CACompromise         = iota
   251  	AffiliationChanged   = iota
   252  	Superseded           = iota
   253  	CessationOfOperation = iota
   254  	CertificateHold      = iota
   255  	_                    = iota
   256  	RemoveFromCRL        = iota
   257  	PrivilegeWithdrawn   = iota
   258  	AACompromise         = iota
   259  )
   260  
   261  // Request represents an OCSP request. See RFC 6960.
   262  type Request struct {
   263  	HashAlgorithm  crypto.Hash
   264  	IssuerNameHash []byte
   265  	IssuerKeyHash  []byte
   266  	SerialNumber   *big.Int
   267  }
   268  
   269  // Response represents an OCSP response containing a single SingleResponse. See
   270  // RFC 6960.
   271  type Response struct {
   272  	// Status is one of {Good, Revoked, Unknown, ServerFailed}
   273  	Status                                        int
   274  	SerialNumber                                  *big.Int
   275  	ProducedAt, ThisUpdate, NextUpdate, RevokedAt time.Time
   276  	RevocationReason                              int
   277  	Certificate                                   *x509.Certificate
   278  	// TBSResponseData contains the raw bytes of the signed response. If
   279  	// Certificate is nil then this can be used to verify Signature.
   280  	TBSResponseData    []byte
   281  	Signature          []byte
   282  	SignatureAlgorithm x509.SignatureAlgorithm
   283  
   284  	// Extensions contains raw X.509 extensions from the singleExtensions field
   285  	// of the OCSP response. When parsing certificates, this can be used to
   286  	// extract non-critical extensions that are not parsed by this package. When
   287  	// marshaling OCSP responses, the Extensions field is ignored, see
   288  	// ExtraExtensions.
   289  	Extensions []pkix.Extension
   290  
   291  	// ExtraExtensions contains extensions to be copied, raw, into any marshaled
   292  	// OCSP response (in the singleExtensions field). Values override any
   293  	// extensions that would otherwise be produced based on the other fields. The
   294  	// ExtraExtensions field is not populated when parsing certificates, see
   295  	// Extensions.
   296  	ExtraExtensions []pkix.Extension
   297  }
   298  
   299  // These are pre-serialized error responses for the various non-success codes
   300  // defined by OCSP. The Unauthorized code in particular can be used by an OCSP
   301  // responder that supports only pre-signed responses as a response to requests
   302  // for certificates with unknown status. See RFC 5019.
   303  var (
   304  	MalformedRequestErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x01}
   305  	InternalErrorErrorResponse    = []byte{0x30, 0x03, 0x0A, 0x01, 0x02}
   306  	TryLaterErrorResponse         = []byte{0x30, 0x03, 0x0A, 0x01, 0x03}
   307  	SigRequredErrorResponse       = []byte{0x30, 0x03, 0x0A, 0x01, 0x05}
   308  	UnauthorizedErrorResponse     = []byte{0x30, 0x03, 0x0A, 0x01, 0x06}
   309  )
   310  
   311  // CheckSignatureFrom checks that the signature in resp is a valid signature
   312  // from issuer. This should only be used if resp.Certificate is nil. Otherwise,
   313  // the OCSP response contained an intermediate certificate that created the
   314  // signature. That signature is checked by ParseResponse and only
   315  // resp.Certificate remains to be validated.
   316  func (resp *Response) CheckSignatureFrom(issuer *x509.Certificate) error {
   317  	return issuer.CheckSignature(resp.SignatureAlgorithm, resp.TBSResponseData, resp.Signature)
   318  }
   319  
   320  // ParseError results from an invalid OCSP response.
   321  type ParseError string
   322  
   323  func (p ParseError) Error() string {
   324  	return string(p)
   325  }
   326  
   327  // ParseRequest parses an OCSP request in DER form. It only supports
   328  // requests for a single certificate. Signed requests are not supported.
   329  // If a request includes a signature, it will result in a ParseError.
   330  func ParseRequest(bytes []byte) (*Request, error) {
   331  	var req ocspRequest
   332  	rest, err := asn1.Unmarshal(bytes, &req)
   333  	if err != nil {
   334  		return nil, err
   335  	}
   336  	if len(rest) > 0 {
   337  		return nil, ParseError("trailing data in OCSP request")
   338  	}
   339  
   340  	if len(req.TBSRequest.RequestList) == 0 {
   341  		return nil, ParseError("OCSP request contains no request body")
   342  	}
   343  	innerRequest := req.TBSRequest.RequestList[0]
   344  
   345  	hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)
   346  	if hashFunc == crypto.Hash(0) {
   347  		return nil, ParseError("OCSP request uses unknown hash function")
   348  	}
   349  
   350  	return &Request{
   351  		HashAlgorithm:  hashFunc,
   352  		IssuerNameHash: innerRequest.Cert.NameHash,
   353  		IssuerKeyHash:  innerRequest.Cert.IssuerKeyHash,
   354  		SerialNumber:   innerRequest.Cert.SerialNumber,
   355  	}, nil
   356  }
   357  
   358  // ParseResponse parses an OCSP response in DER form. It only supports
   359  // responses for a single certificate. If the response contains a certificate
   360  // then the signature over the response is checked. If issuer is not nil then
   361  // it will be used to validate the signature or embedded certificate. Invalid
   362  // signatures or parse failures will result in a ParseError.
   363  func ParseResponse(bytes []byte, issuer *x509.Certificate) (*Response, error) {
   364  	var resp responseASN1
   365  	rest, err := asn1.Unmarshal(bytes, &resp)
   366  	if err != nil {
   367  		return nil, err
   368  	}
   369  	if len(rest) > 0 {
   370  		return nil, ParseError("trailing data in OCSP response")
   371  	}
   372  
   373  	ret := new(Response)
   374  	if resp.Status != ocspSuccess {
   375  		ret.Status = ServerFailed
   376  		return ret, nil
   377  	}
   378  
   379  	if !resp.Response.ResponseType.Equal(idPKIXOCSPBasic) {
   380  		return nil, ParseError("bad OCSP response type")
   381  	}
   382  
   383  	var basicResp basicResponse
   384  	rest, err = asn1.Unmarshal(resp.Response.Response, &basicResp)
   385  	if err != nil {
   386  		return nil, err
   387  	}
   388  
   389  	if len(basicResp.Certificates) > 1 {
   390  		return nil, ParseError("OCSP response contains bad number of certificates")
   391  	}
   392  
   393  	if len(basicResp.TBSResponseData.Responses) != 1 {
   394  		return nil, ParseError("OCSP response contains bad number of responses")
   395  	}
   396  
   397  	ret.TBSResponseData = basicResp.TBSResponseData.Raw
   398  	ret.Signature = basicResp.Signature.RightAlign()
   399  	ret.SignatureAlgorithm = getSignatureAlgorithmFromOID(basicResp.SignatureAlgorithm.Algorithm)
   400  
   401  	if len(basicResp.Certificates) > 0 {
   402  		ret.Certificate, err = x509.ParseCertificate(basicResp.Certificates[0].FullBytes)
   403  		if err != nil {
   404  			return nil, err
   405  		}
   406  
   407  		if err := ret.CheckSignatureFrom(ret.Certificate); err != nil {
   408  			return nil, ParseError("bad OCSP signature")
   409  		}
   410  
   411  		if issuer != nil {
   412  			if err := issuer.CheckSignature(ret.Certificate.SignatureAlgorithm, ret.Certificate.RawTBSCertificate, ret.Certificate.Signature); err != nil {
   413  				return nil, ParseError("bad signature on embedded certificate")
   414  			}
   415  		}
   416  	} else if issuer != nil {
   417  		if err := ret.CheckSignatureFrom(issuer); err != nil {
   418  			return nil, ParseError("bad OCSP signature")
   419  		}
   420  	}
   421  
   422  	r := basicResp.TBSResponseData.Responses[0]
   423  
   424  	for _, ext := range r.SingleExtensions {
   425  		if ext.Critical {
   426  			return nil, ParseError("unsupported critical extension")
   427  		}
   428  	}
   429  	ret.Extensions = r.SingleExtensions
   430  
   431  	ret.SerialNumber = r.CertID.SerialNumber
   432  
   433  	switch {
   434  	case bool(r.Good):
   435  		ret.Status = Good
   436  	case bool(r.Unknown):
   437  		ret.Status = Unknown
   438  	default:
   439  		ret.Status = Revoked
   440  		ret.RevokedAt = r.Revoked.RevocationTime
   441  		ret.RevocationReason = int(r.Revoked.Reason)
   442  	}
   443  
   444  	ret.ProducedAt = basicResp.TBSResponseData.ProducedAt
   445  	ret.ThisUpdate = r.ThisUpdate
   446  	ret.NextUpdate = r.NextUpdate
   447  
   448  	return ret, nil
   449  }
   450  
   451  // RequestOptions contains options for constructing OCSP requests.
   452  type RequestOptions struct {
   453  	// Hash contains the hash function that should be used when
   454  	// constructing the OCSP request. If zero, SHA-1 will be used.
   455  	Hash crypto.Hash
   456  }
   457  
   458  func (opts *RequestOptions) hash() crypto.Hash {
   459  	if opts == nil || opts.Hash == 0 {
   460  		// SHA-1 is nearly universally used in OCSP.
   461  		return crypto.SHA1
   462  	}
   463  	return opts.Hash
   464  }
   465  
   466  // CreateRequest returns a DER-encoded, OCSP request for the status of cert. If
   467  // opts is nil then sensible defaults are used.
   468  func CreateRequest(cert, issuer *x509.Certificate, opts *RequestOptions) ([]byte, error) {
   469  	hashFunc := opts.hash()
   470  
   471  	// OCSP seems to be the only place where these raw hash identifiers are
   472  	// used. I took the following from
   473  	// http://msdn.microsoft.com/en-us/library/ff635603.aspx
   474  	var hashOID asn1.ObjectIdentifier
   475  	hashOID, ok := hashOIDs[hashFunc]
   476  	if !ok {
   477  		return nil, x509.ErrUnsupportedAlgorithm
   478  	}
   479  
   480  	if !hashFunc.Available() {
   481  		return nil, x509.ErrUnsupportedAlgorithm
   482  	}
   483  	h := opts.hash().New()
   484  
   485  	var publicKeyInfo struct {
   486  		Algorithm pkix.AlgorithmIdentifier
   487  		PublicKey asn1.BitString
   488  	}
   489  	if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
   490  		return nil, err
   491  	}
   492  
   493  	h.Write(publicKeyInfo.PublicKey.RightAlign())
   494  	issuerKeyHash := h.Sum(nil)
   495  
   496  	h.Reset()
   497  	h.Write(issuer.RawSubject)
   498  	issuerNameHash := h.Sum(nil)
   499  
   500  	return asn1.Marshal(ocspRequest{
   501  		tbsRequest{
   502  			Version: 0,
   503  			RequestList: []request{
   504  				{
   505  					Cert: certID{
   506  						pkix.AlgorithmIdentifier{
   507  							Algorithm:  hashOID,
   508  							Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
   509  						},
   510  						issuerNameHash,
   511  						issuerKeyHash,
   512  						cert.SerialNumber,
   513  					},
   514  				},
   515  			},
   516  		},
   517  	})
   518  }
   519  
   520  // CreateResponse returns a DER-encoded OCSP response with the specified contents.
   521  // The fields in the response are populated as follows:
   522  //
   523  // The responder cert is used to populate the ResponderName field, and the certificate
   524  // itself is provided alongside the OCSP response signature.
   525  //
   526  // The issuer cert is used to puplate the IssuerNameHash and IssuerKeyHash fields.
   527  // (SHA-1 is used for the hash function; this is not configurable.)
   528  //
   529  // The template is used to populate the SerialNumber, RevocationStatus, RevokedAt,
   530  // RevocationReason, ThisUpdate, and NextUpdate fields.
   531  //
   532  // The ProducedAt date is automatically set to the current date, to the nearest minute.
   533  func CreateResponse(issuer, responderCert *x509.Certificate, template Response, priv crypto.Signer) ([]byte, error) {
   534  	var publicKeyInfo struct {
   535  		Algorithm pkix.AlgorithmIdentifier
   536  		PublicKey asn1.BitString
   537  	}
   538  	if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
   539  		return nil, err
   540  	}
   541  
   542  	h := sha1.New()
   543  	h.Write(publicKeyInfo.PublicKey.RightAlign())
   544  	issuerKeyHash := h.Sum(nil)
   545  
   546  	h.Reset()
   547  	h.Write(issuer.RawSubject)
   548  	issuerNameHash := h.Sum(nil)
   549  
   550  	innerResponse := singleResponse{
   551  		CertID: certID{
   552  			HashAlgorithm: pkix.AlgorithmIdentifier{
   553  				Algorithm:  hashOIDs[crypto.SHA1],
   554  				Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
   555  			},
   556  			NameHash:      issuerNameHash,
   557  			IssuerKeyHash: issuerKeyHash,
   558  			SerialNumber:  template.SerialNumber,
   559  		},
   560  		ThisUpdate:       template.ThisUpdate.UTC(),
   561  		NextUpdate:       template.NextUpdate.UTC(),
   562  		SingleExtensions: template.ExtraExtensions,
   563  	}
   564  
   565  	switch template.Status {
   566  	case Good:
   567  		innerResponse.Good = true
   568  	case Unknown:
   569  		innerResponse.Unknown = true
   570  	case Revoked:
   571  		innerResponse.Revoked = revokedInfo{
   572  			RevocationTime: template.RevokedAt.UTC(),
   573  			Reason:         asn1.Enumerated(template.RevocationReason),
   574  		}
   575  	}
   576  
   577  	responderName := asn1.RawValue{
   578  		Class:      2, // context-specific
   579  		Tag:        1, // explicit tag
   580  		IsCompound: true,
   581  		Bytes:      responderCert.RawSubject,
   582  	}
   583  	tbsResponseData := responseData{
   584  		Version:          0,
   585  		RawResponderName: responderName,
   586  		ProducedAt:       time.Now().Truncate(time.Minute).UTC(),
   587  		Responses:        []singleResponse{innerResponse},
   588  	}
   589  
   590  	tbsResponseDataDER, err := asn1.Marshal(tbsResponseData)
   591  	if err != nil {
   592  		return nil, err
   593  	}
   594  
   595  	hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
   596  	if err != nil {
   597  		return nil, err
   598  	}
   599  
   600  	responseHash := hashFunc.New()
   601  	responseHash.Write(tbsResponseDataDER)
   602  	signature, err := priv.Sign(rand.Reader, responseHash.Sum(nil), hashFunc)
   603  	if err != nil {
   604  		return nil, err
   605  	}
   606  
   607  	response := basicResponse{
   608  		TBSResponseData:    tbsResponseData,
   609  		SignatureAlgorithm: signatureAlgorithm,
   610  		Signature: asn1.BitString{
   611  			Bytes:     signature,
   612  			BitLength: 8 * len(signature),
   613  		},
   614  	}
   615  	if template.Certificate != nil {
   616  		response.Certificates = []asn1.RawValue{
   617  			asn1.RawValue{FullBytes: template.Certificate.Raw},
   618  		}
   619  	}
   620  	responseDER, err := asn1.Marshal(response)
   621  	if err != nil {
   622  		return nil, err
   623  	}
   624  
   625  	return asn1.Marshal(responseASN1{
   626  		Status: ocspSuccess,
   627  		Response: responseBytes{
   628  			ResponseType: idPKIXOCSPBasic,
   629  			Response:     responseDER,
   630  		},
   631  	})
   632  }