ocsp.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714
  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 unused 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:0,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. func getOIDFromHashAlgorithm(target crypto.Hash) asn1.ObjectIdentifier {
  235. for hash, oid := range hashOIDs {
  236. if hash == target {
  237. return oid
  238. }
  239. }
  240. return nil
  241. }
  242. // This is the exposed reflection of the internal OCSP structures.
  243. // The status values that can be expressed in OCSP. See RFC 6960.
  244. const (
  245. // Good means that the certificate is valid.
  246. Good = iota
  247. // Revoked means that the certificate has been deliberately revoked.
  248. Revoked
  249. // Unknown means that the OCSP responder doesn't know about the certificate.
  250. Unknown
  251. // ServerFailed is unused and was never used (see
  252. // https://go-review.googlesource.com/#/c/18944). ParseResponse will
  253. // return a ResponseError when an error response is parsed.
  254. ServerFailed
  255. )
  256. // The enumerated reasons for revoking a certificate. See RFC 5280.
  257. const (
  258. Unspecified = iota
  259. KeyCompromise = iota
  260. CACompromise = iota
  261. AffiliationChanged = iota
  262. Superseded = iota
  263. CessationOfOperation = iota
  264. CertificateHold = iota
  265. _ = iota
  266. RemoveFromCRL = iota
  267. PrivilegeWithdrawn = iota
  268. AACompromise = iota
  269. )
  270. // Request represents an OCSP request. See RFC 6960.
  271. type Request struct {
  272. HashAlgorithm crypto.Hash
  273. IssuerNameHash []byte
  274. IssuerKeyHash []byte
  275. SerialNumber *big.Int
  276. }
  277. // Marshal marshals the OCSP request to ASN.1 DER encoded form.
  278. func (req *Request) Marshal() ([]byte, error) {
  279. hashAlg := getOIDFromHashAlgorithm(req.HashAlgorithm)
  280. if hashAlg == nil {
  281. return nil, errors.New("Unknown hash algorithm")
  282. }
  283. return asn1.Marshal(ocspRequest{
  284. tbsRequest{
  285. Version: 0,
  286. RequestList: []request{
  287. {
  288. Cert: certID{
  289. pkix.AlgorithmIdentifier{
  290. Algorithm: hashAlg,
  291. Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
  292. },
  293. req.IssuerNameHash,
  294. req.IssuerKeyHash,
  295. req.SerialNumber,
  296. },
  297. },
  298. },
  299. },
  300. })
  301. }
  302. // Response represents an OCSP response containing a single SingleResponse. See
  303. // RFC 6960.
  304. type Response struct {
  305. // Status is one of {Good, Revoked, Unknown}
  306. Status int
  307. SerialNumber *big.Int
  308. ProducedAt, ThisUpdate, NextUpdate, RevokedAt time.Time
  309. RevocationReason int
  310. Certificate *x509.Certificate
  311. // TBSResponseData contains the raw bytes of the signed response. If
  312. // Certificate is nil then this can be used to verify Signature.
  313. TBSResponseData []byte
  314. Signature []byte
  315. SignatureAlgorithm x509.SignatureAlgorithm
  316. // Extensions contains raw X.509 extensions from the singleExtensions field
  317. // of the OCSP response. When parsing certificates, this can be used to
  318. // extract non-critical extensions that are not parsed by this package. When
  319. // marshaling OCSP responses, the Extensions field is ignored, see
  320. // ExtraExtensions.
  321. Extensions []pkix.Extension
  322. // ExtraExtensions contains extensions to be copied, raw, into any marshaled
  323. // OCSP response (in the singleExtensions field). Values override any
  324. // extensions that would otherwise be produced based on the other fields. The
  325. // ExtraExtensions field is not populated when parsing certificates, see
  326. // Extensions.
  327. ExtraExtensions []pkix.Extension
  328. }
  329. // These are pre-serialized error responses for the various non-success codes
  330. // defined by OCSP. The Unauthorized code in particular can be used by an OCSP
  331. // responder that supports only pre-signed responses as a response to requests
  332. // for certificates with unknown status. See RFC 5019.
  333. var (
  334. MalformedRequestErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x01}
  335. InternalErrorErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x02}
  336. TryLaterErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x03}
  337. SigRequredErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x05}
  338. UnauthorizedErrorResponse = []byte{0x30, 0x03, 0x0A, 0x01, 0x06}
  339. )
  340. // CheckSignatureFrom checks that the signature in resp is a valid signature
  341. // from issuer. This should only be used if resp.Certificate is nil. Otherwise,
  342. // the OCSP response contained an intermediate certificate that created the
  343. // signature. That signature is checked by ParseResponse and only
  344. // resp.Certificate remains to be validated.
  345. func (resp *Response) CheckSignatureFrom(issuer *x509.Certificate) error {
  346. return issuer.CheckSignature(resp.SignatureAlgorithm, resp.TBSResponseData, resp.Signature)
  347. }
  348. // ParseError results from an invalid OCSP response.
  349. type ParseError string
  350. func (p ParseError) Error() string {
  351. return string(p)
  352. }
  353. // ParseRequest parses an OCSP request in DER form. It only supports
  354. // requests for a single certificate. Signed requests are not supported.
  355. // If a request includes a signature, it will result in a ParseError.
  356. func ParseRequest(bytes []byte) (*Request, error) {
  357. var req ocspRequest
  358. rest, err := asn1.Unmarshal(bytes, &req)
  359. if err != nil {
  360. return nil, err
  361. }
  362. if len(rest) > 0 {
  363. return nil, ParseError("trailing data in OCSP request")
  364. }
  365. if len(req.TBSRequest.RequestList) == 0 {
  366. return nil, ParseError("OCSP request contains no request body")
  367. }
  368. innerRequest := req.TBSRequest.RequestList[0]
  369. hashFunc := getHashAlgorithmFromOID(innerRequest.Cert.HashAlgorithm.Algorithm)
  370. if hashFunc == crypto.Hash(0) {
  371. return nil, ParseError("OCSP request uses unknown hash function")
  372. }
  373. return &Request{
  374. HashAlgorithm: hashFunc,
  375. IssuerNameHash: innerRequest.Cert.NameHash,
  376. IssuerKeyHash: innerRequest.Cert.IssuerKeyHash,
  377. SerialNumber: innerRequest.Cert.SerialNumber,
  378. }, nil
  379. }
  380. // ParseResponse parses an OCSP response in DER form. It only supports
  381. // responses for a single certificate. If the response contains a certificate
  382. // then the signature over the response is checked. If issuer is not nil then
  383. // it will be used to validate the signature or embedded certificate.
  384. //
  385. // Invalid signatures or parse failures will result in a ParseError. Error
  386. // responses will result in a ResponseError.
  387. func ParseResponse(bytes []byte, issuer *x509.Certificate) (*Response, error) {
  388. return ParseResponseForCert(bytes, nil, issuer)
  389. }
  390. // ParseResponseForCert parses an OCSP response in DER form and searches for a
  391. // Response relating to cert. If such a Response is found and the OCSP response
  392. // contains a certificate then the signature over the response is checked. If
  393. // issuer is not nil then it will be used to validate the signature or embedded
  394. // certificate.
  395. //
  396. // Invalid signatures or parse failures will result in a ParseError. Error
  397. // responses will result in a ResponseError.
  398. func ParseResponseForCert(bytes []byte, cert, issuer *x509.Certificate) (*Response, error) {
  399. var resp responseASN1
  400. rest, err := asn1.Unmarshal(bytes, &resp)
  401. if err != nil {
  402. return nil, err
  403. }
  404. if len(rest) > 0 {
  405. return nil, ParseError("trailing data in OCSP response")
  406. }
  407. if status := ResponseStatus(resp.Status); status != Success {
  408. return nil, ResponseError{status}
  409. }
  410. if !resp.Response.ResponseType.Equal(idPKIXOCSPBasic) {
  411. return nil, ParseError("bad OCSP response type")
  412. }
  413. var basicResp basicResponse
  414. rest, err = asn1.Unmarshal(resp.Response.Response, &basicResp)
  415. if err != nil {
  416. return nil, err
  417. }
  418. if len(basicResp.Certificates) > 1 {
  419. return nil, ParseError("OCSP response contains bad number of certificates")
  420. }
  421. if n := len(basicResp.TBSResponseData.Responses); n == 0 || cert == nil && n > 1 {
  422. return nil, ParseError("OCSP response contains bad number of responses")
  423. }
  424. ret := &Response{
  425. TBSResponseData: basicResp.TBSResponseData.Raw,
  426. Signature: basicResp.Signature.RightAlign(),
  427. SignatureAlgorithm: getSignatureAlgorithmFromOID(basicResp.SignatureAlgorithm.Algorithm),
  428. }
  429. if len(basicResp.Certificates) > 0 {
  430. ret.Certificate, err = x509.ParseCertificate(basicResp.Certificates[0].FullBytes)
  431. if err != nil {
  432. return nil, err
  433. }
  434. if err := ret.CheckSignatureFrom(ret.Certificate); err != nil {
  435. return nil, ParseError("bad OCSP signature")
  436. }
  437. if issuer != nil {
  438. if err := issuer.CheckSignature(ret.Certificate.SignatureAlgorithm, ret.Certificate.RawTBSCertificate, ret.Certificate.Signature); err != nil {
  439. return nil, ParseError("bad signature on embedded certificate")
  440. }
  441. }
  442. } else if issuer != nil {
  443. if err := ret.CheckSignatureFrom(issuer); err != nil {
  444. return nil, ParseError("bad OCSP signature")
  445. }
  446. }
  447. var r singleResponse
  448. for _, resp := range basicResp.TBSResponseData.Responses {
  449. if cert == nil || cert.SerialNumber.Cmp(resp.CertID.SerialNumber) == 0 {
  450. r = resp
  451. break
  452. }
  453. }
  454. for _, ext := range r.SingleExtensions {
  455. if ext.Critical {
  456. return nil, ParseError("unsupported critical extension")
  457. }
  458. }
  459. ret.Extensions = r.SingleExtensions
  460. ret.SerialNumber = r.CertID.SerialNumber
  461. switch {
  462. case bool(r.Good):
  463. ret.Status = Good
  464. case bool(r.Unknown):
  465. ret.Status = Unknown
  466. default:
  467. ret.Status = Revoked
  468. ret.RevokedAt = r.Revoked.RevocationTime
  469. ret.RevocationReason = int(r.Revoked.Reason)
  470. }
  471. ret.ProducedAt = basicResp.TBSResponseData.ProducedAt
  472. ret.ThisUpdate = r.ThisUpdate
  473. ret.NextUpdate = r.NextUpdate
  474. return ret, nil
  475. }
  476. // RequestOptions contains options for constructing OCSP requests.
  477. type RequestOptions struct {
  478. // Hash contains the hash function that should be used when
  479. // constructing the OCSP request. If zero, SHA-1 will be used.
  480. Hash crypto.Hash
  481. }
  482. func (opts *RequestOptions) hash() crypto.Hash {
  483. if opts == nil || opts.Hash == 0 {
  484. // SHA-1 is nearly universally used in OCSP.
  485. return crypto.SHA1
  486. }
  487. return opts.Hash
  488. }
  489. // CreateRequest returns a DER-encoded, OCSP request for the status of cert. If
  490. // opts is nil then sensible defaults are used.
  491. func CreateRequest(cert, issuer *x509.Certificate, opts *RequestOptions) ([]byte, error) {
  492. hashFunc := opts.hash()
  493. // OCSP seems to be the only place where these raw hash identifiers are
  494. // used. I took the following from
  495. // http://msdn.microsoft.com/en-us/library/ff635603.aspx
  496. _, ok := hashOIDs[hashFunc]
  497. if !ok {
  498. return nil, x509.ErrUnsupportedAlgorithm
  499. }
  500. if !hashFunc.Available() {
  501. return nil, x509.ErrUnsupportedAlgorithm
  502. }
  503. h := opts.hash().New()
  504. var publicKeyInfo struct {
  505. Algorithm pkix.AlgorithmIdentifier
  506. PublicKey asn1.BitString
  507. }
  508. if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
  509. return nil, err
  510. }
  511. h.Write(publicKeyInfo.PublicKey.RightAlign())
  512. issuerKeyHash := h.Sum(nil)
  513. h.Reset()
  514. h.Write(issuer.RawSubject)
  515. issuerNameHash := h.Sum(nil)
  516. req := &Request{
  517. HashAlgorithm: hashFunc,
  518. IssuerNameHash: issuerNameHash,
  519. IssuerKeyHash: issuerKeyHash,
  520. SerialNumber: cert.SerialNumber,
  521. }
  522. return req.Marshal()
  523. }
  524. // CreateResponse returns a DER-encoded OCSP response with the specified contents.
  525. // The fields in the response are populated as follows:
  526. //
  527. // The responder cert is used to populate the ResponderName field, and the certificate
  528. // itself is provided alongside the OCSP response signature.
  529. //
  530. // The issuer cert is used to puplate the IssuerNameHash and IssuerKeyHash fields.
  531. // (SHA-1 is used for the hash function; this is not configurable.)
  532. //
  533. // The template is used to populate the SerialNumber, RevocationStatus, RevokedAt,
  534. // RevocationReason, ThisUpdate, and NextUpdate fields.
  535. //
  536. // The ProducedAt date is automatically set to the current date, to the nearest minute.
  537. func CreateResponse(issuer, responderCert *x509.Certificate, template Response, priv crypto.Signer) ([]byte, error) {
  538. var publicKeyInfo struct {
  539. Algorithm pkix.AlgorithmIdentifier
  540. PublicKey asn1.BitString
  541. }
  542. if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
  543. return nil, err
  544. }
  545. h := sha1.New()
  546. h.Write(publicKeyInfo.PublicKey.RightAlign())
  547. issuerKeyHash := h.Sum(nil)
  548. h.Reset()
  549. h.Write(issuer.RawSubject)
  550. issuerNameHash := h.Sum(nil)
  551. innerResponse := singleResponse{
  552. CertID: certID{
  553. HashAlgorithm: pkix.AlgorithmIdentifier{
  554. Algorithm: hashOIDs[crypto.SHA1],
  555. Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
  556. },
  557. NameHash: issuerNameHash,
  558. IssuerKeyHash: issuerKeyHash,
  559. SerialNumber: template.SerialNumber,
  560. },
  561. ThisUpdate: template.ThisUpdate.UTC(),
  562. NextUpdate: template.NextUpdate.UTC(),
  563. SingleExtensions: template.ExtraExtensions,
  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. responderName := asn1.RawValue{
  577. Class: 2, // context-specific
  578. Tag: 1, // explicit tag
  579. IsCompound: true,
  580. Bytes: responderCert.RawSubject,
  581. }
  582. tbsResponseData := responseData{
  583. Version: 0,
  584. RawResponderName: responderName,
  585. ProducedAt: time.Now().Truncate(time.Minute).UTC(),
  586. Responses: []singleResponse{innerResponse},
  587. }
  588. tbsResponseDataDER, err := asn1.Marshal(tbsResponseData)
  589. if err != nil {
  590. return nil, err
  591. }
  592. hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
  593. if err != nil {
  594. return nil, err
  595. }
  596. responseHash := hashFunc.New()
  597. responseHash.Write(tbsResponseDataDER)
  598. signature, err := priv.Sign(rand.Reader, responseHash.Sum(nil), hashFunc)
  599. if err != nil {
  600. return nil, err
  601. }
  602. response := basicResponse{
  603. TBSResponseData: tbsResponseData,
  604. SignatureAlgorithm: signatureAlgorithm,
  605. Signature: asn1.BitString{
  606. Bytes: signature,
  607. BitLength: 8 * len(signature),
  608. },
  609. }
  610. if template.Certificate != nil {
  611. response.Certificates = []asn1.RawValue{
  612. asn1.RawValue{FullBytes: template.Certificate.Raw},
  613. }
  614. }
  615. responseDER, err := asn1.Marshal(response)
  616. if err != nil {
  617. return nil, err
  618. }
  619. return asn1.Marshal(responseASN1{
  620. Status: asn1.Enumerated(Success),
  621. Response: responseBytes{
  622. ResponseType: idPKIXOCSPBasic,
  623. Response: responseDER,
  624. },
  625. })
  626. }