ocsp.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778
  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 responses and parse failures will result in a ParseError.
  400. // Error 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 responses and parse failures will result in a ParseError.
  411. // Error 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. var singleResp singleResponse
  439. if cert == nil {
  440. singleResp = basicResp.TBSResponseData.Responses[0]
  441. } else {
  442. match := false
  443. for _, resp := range basicResp.TBSResponseData.Responses {
  444. if cert == nil || cert.SerialNumber.Cmp(resp.CertID.SerialNumber) == 0 {
  445. singleResp = resp
  446. match = true
  447. break
  448. }
  449. }
  450. if !match {
  451. return nil, ParseError("no response matching the supplied certificate")
  452. }
  453. }
  454. ret := &Response{
  455. TBSResponseData: basicResp.TBSResponseData.Raw,
  456. Signature: basicResp.Signature.RightAlign(),
  457. SignatureAlgorithm: getSignatureAlgorithmFromOID(basicResp.SignatureAlgorithm.Algorithm),
  458. Extensions: singleResp.SingleExtensions,
  459. SerialNumber: singleResp.CertID.SerialNumber,
  460. ProducedAt: basicResp.TBSResponseData.ProducedAt,
  461. ThisUpdate: singleResp.ThisUpdate,
  462. NextUpdate: singleResp.NextUpdate,
  463. }
  464. // Handle the ResponderID CHOICE tag. ResponderID can be flattened into
  465. // TBSResponseData once https://go-review.googlesource.com/34503 has been
  466. // released.
  467. rawResponderID := basicResp.TBSResponseData.RawResponderID
  468. switch rawResponderID.Tag {
  469. case 1: // Name
  470. var rdn pkix.RDNSequence
  471. if rest, err := asn1.Unmarshal(rawResponderID.Bytes, &rdn); err != nil || len(rest) != 0 {
  472. return nil, ParseError("invalid responder name")
  473. }
  474. ret.RawResponderName = rawResponderID.Bytes
  475. case 2: // KeyHash
  476. if rest, err := asn1.Unmarshal(rawResponderID.Bytes, &ret.ResponderKeyHash); err != nil || len(rest) != 0 {
  477. return nil, ParseError("invalid responder key hash")
  478. }
  479. default:
  480. return nil, ParseError("invalid responder id tag")
  481. }
  482. if len(basicResp.Certificates) > 0 {
  483. ret.Certificate, err = x509.ParseCertificate(basicResp.Certificates[0].FullBytes)
  484. if err != nil {
  485. return nil, err
  486. }
  487. if err := ret.CheckSignatureFrom(ret.Certificate); err != nil {
  488. return nil, ParseError("bad signature on embedded certificate: " + err.Error())
  489. }
  490. if issuer != nil {
  491. if err := issuer.CheckSignature(ret.Certificate.SignatureAlgorithm, ret.Certificate.RawTBSCertificate, ret.Certificate.Signature); err != nil {
  492. return nil, ParseError("bad OCSP signature: " + err.Error())
  493. }
  494. }
  495. } else if issuer != nil {
  496. if err := ret.CheckSignatureFrom(issuer); err != nil {
  497. return nil, ParseError("bad OCSP signature: " + err.Error())
  498. }
  499. }
  500. for _, ext := range singleResp.SingleExtensions {
  501. if ext.Critical {
  502. return nil, ParseError("unsupported critical extension")
  503. }
  504. }
  505. for h, oid := range hashOIDs {
  506. if singleResp.CertID.HashAlgorithm.Algorithm.Equal(oid) {
  507. ret.IssuerHash = h
  508. break
  509. }
  510. }
  511. if ret.IssuerHash == 0 {
  512. return nil, ParseError("unsupported issuer hash algorithm")
  513. }
  514. switch {
  515. case bool(singleResp.Good):
  516. ret.Status = Good
  517. case bool(singleResp.Unknown):
  518. ret.Status = Unknown
  519. default:
  520. ret.Status = Revoked
  521. ret.RevokedAt = singleResp.Revoked.RevocationTime
  522. ret.RevocationReason = int(singleResp.Revoked.Reason)
  523. }
  524. return ret, nil
  525. }
  526. // RequestOptions contains options for constructing OCSP requests.
  527. type RequestOptions struct {
  528. // Hash contains the hash function that should be used when
  529. // constructing the OCSP request. If zero, SHA-1 will be used.
  530. Hash crypto.Hash
  531. }
  532. func (opts *RequestOptions) hash() crypto.Hash {
  533. if opts == nil || opts.Hash == 0 {
  534. // SHA-1 is nearly universally used in OCSP.
  535. return crypto.SHA1
  536. }
  537. return opts.Hash
  538. }
  539. // CreateRequest returns a DER-encoded, OCSP request for the status of cert. If
  540. // opts is nil then sensible defaults are used.
  541. func CreateRequest(cert, issuer *x509.Certificate, opts *RequestOptions) ([]byte, error) {
  542. hashFunc := opts.hash()
  543. // OCSP seems to be the only place where these raw hash identifiers are
  544. // used. I took the following from
  545. // http://msdn.microsoft.com/en-us/library/ff635603.aspx
  546. _, ok := hashOIDs[hashFunc]
  547. if !ok {
  548. return nil, x509.ErrUnsupportedAlgorithm
  549. }
  550. if !hashFunc.Available() {
  551. return nil, x509.ErrUnsupportedAlgorithm
  552. }
  553. h := opts.hash().New()
  554. var publicKeyInfo struct {
  555. Algorithm pkix.AlgorithmIdentifier
  556. PublicKey asn1.BitString
  557. }
  558. if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
  559. return nil, err
  560. }
  561. h.Write(publicKeyInfo.PublicKey.RightAlign())
  562. issuerKeyHash := h.Sum(nil)
  563. h.Reset()
  564. h.Write(issuer.RawSubject)
  565. issuerNameHash := h.Sum(nil)
  566. req := &Request{
  567. HashAlgorithm: hashFunc,
  568. IssuerNameHash: issuerNameHash,
  569. IssuerKeyHash: issuerKeyHash,
  570. SerialNumber: cert.SerialNumber,
  571. }
  572. return req.Marshal()
  573. }
  574. // CreateResponse returns a DER-encoded OCSP response with the specified contents.
  575. // The fields in the response are populated as follows:
  576. //
  577. // The responder cert is used to populate the responder's name field, and the
  578. // certificate itself is provided alongside the OCSP response signature.
  579. //
  580. // The issuer cert is used to puplate the IssuerNameHash and IssuerKeyHash fields.
  581. //
  582. // The template is used to populate the SerialNumber, RevocationStatus, RevokedAt,
  583. // RevocationReason, ThisUpdate, and NextUpdate fields.
  584. //
  585. // If template.IssuerHash is not set, SHA1 will be used.
  586. //
  587. // The ProducedAt date is automatically set to the current date, to the nearest minute.
  588. func CreateResponse(issuer, responderCert *x509.Certificate, template Response, priv crypto.Signer) ([]byte, error) {
  589. var publicKeyInfo struct {
  590. Algorithm pkix.AlgorithmIdentifier
  591. PublicKey asn1.BitString
  592. }
  593. if _, err := asn1.Unmarshal(issuer.RawSubjectPublicKeyInfo, &publicKeyInfo); err != nil {
  594. return nil, err
  595. }
  596. if template.IssuerHash == 0 {
  597. template.IssuerHash = crypto.SHA1
  598. }
  599. hashOID := getOIDFromHashAlgorithm(template.IssuerHash)
  600. if hashOID == nil {
  601. return nil, errors.New("unsupported issuer hash algorithm")
  602. }
  603. if !template.IssuerHash.Available() {
  604. return nil, fmt.Errorf("issuer hash algorithm %v not linked into binary", template.IssuerHash)
  605. }
  606. h := template.IssuerHash.New()
  607. h.Write(publicKeyInfo.PublicKey.RightAlign())
  608. issuerKeyHash := h.Sum(nil)
  609. h.Reset()
  610. h.Write(issuer.RawSubject)
  611. issuerNameHash := h.Sum(nil)
  612. innerResponse := singleResponse{
  613. CertID: certID{
  614. HashAlgorithm: pkix.AlgorithmIdentifier{
  615. Algorithm: hashOID,
  616. Parameters: asn1.RawValue{Tag: 5 /* ASN.1 NULL */},
  617. },
  618. NameHash: issuerNameHash,
  619. IssuerKeyHash: issuerKeyHash,
  620. SerialNumber: template.SerialNumber,
  621. },
  622. ThisUpdate: template.ThisUpdate.UTC(),
  623. NextUpdate: template.NextUpdate.UTC(),
  624. SingleExtensions: template.ExtraExtensions,
  625. }
  626. switch template.Status {
  627. case Good:
  628. innerResponse.Good = true
  629. case Unknown:
  630. innerResponse.Unknown = true
  631. case Revoked:
  632. innerResponse.Revoked = revokedInfo{
  633. RevocationTime: template.RevokedAt.UTC(),
  634. Reason: asn1.Enumerated(template.RevocationReason),
  635. }
  636. }
  637. rawResponderID := asn1.RawValue{
  638. Class: 2, // context-specific
  639. Tag: 1, // Name (explicit tag)
  640. IsCompound: true,
  641. Bytes: responderCert.RawSubject,
  642. }
  643. tbsResponseData := responseData{
  644. Version: 0,
  645. RawResponderID: rawResponderID,
  646. ProducedAt: time.Now().Truncate(time.Minute).UTC(),
  647. Responses: []singleResponse{innerResponse},
  648. }
  649. tbsResponseDataDER, err := asn1.Marshal(tbsResponseData)
  650. if err != nil {
  651. return nil, err
  652. }
  653. hashFunc, signatureAlgorithm, err := signingParamsForPublicKey(priv.Public(), template.SignatureAlgorithm)
  654. if err != nil {
  655. return nil, err
  656. }
  657. responseHash := hashFunc.New()
  658. responseHash.Write(tbsResponseDataDER)
  659. signature, err := priv.Sign(rand.Reader, responseHash.Sum(nil), hashFunc)
  660. if err != nil {
  661. return nil, err
  662. }
  663. response := basicResponse{
  664. TBSResponseData: tbsResponseData,
  665. SignatureAlgorithm: signatureAlgorithm,
  666. Signature: asn1.BitString{
  667. Bytes: signature,
  668. BitLength: 8 * len(signature),
  669. },
  670. }
  671. if template.Certificate != nil {
  672. response.Certificates = []asn1.RawValue{
  673. asn1.RawValue{FullBytes: template.Certificate.Raw},
  674. }
  675. }
  676. responseDER, err := asn1.Marshal(response)
  677. if err != nil {
  678. return nil, err
  679. }
  680. return asn1.Marshal(responseASN1{
  681. Status: asn1.Enumerated(Success),
  682. Response: responseBytes{
  683. ResponseType: idPKIXOCSPBasic,
  684. Response: responseDER,
  685. },
  686. })
  687. }