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