ocsp.go 23 KB

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