ocsp.go 20 KB

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