You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

772 lines
24 KiB

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