ocsp.go 21 KB

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