revoke.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341
  1. // Package revoke provides functionality for checking the validity of
  2. // a cert. Specifically, the temporal validity of the certificate is
  3. // checked first, then any CRL and OCSP url in the cert is checked.
  4. package revoke
  5. import (
  6. "bytes"
  7. "crypto"
  8. "crypto/x509"
  9. "crypto/x509/pkix"
  10. "encoding/base64"
  11. "encoding/pem"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "io/ioutil"
  16. "net/http"
  17. neturl "net/url"
  18. "sync"
  19. "time"
  20. "golang.org/x/crypto/ocsp"
  21. "github.com/cloudflare/cfssl/helpers"
  22. "github.com/cloudflare/cfssl/log"
  23. )
  24. // HTTPClient is an instance of http.Client that will be used for all HTTP requests.
  25. var HTTPClient = http.DefaultClient
  26. // HardFail determines whether the failure to check the revocation
  27. // status of a certificate (i.e. due to network failure) causes
  28. // verification to fail (a hard failure).
  29. var HardFail = false
  30. // CRLSet associates a PKIX certificate list with the URL the CRL is
  31. // fetched from.
  32. var CRLSet = map[string]*pkix.CertificateList{}
  33. var crlLock = new(sync.Mutex)
  34. // We can't handle LDAP certificates, so this checks to see if the
  35. // URL string points to an LDAP resource so that we can ignore it.
  36. func ldapURL(url string) bool {
  37. u, err := neturl.Parse(url)
  38. if err != nil {
  39. log.Warningf("error parsing url %s: %v", url, err)
  40. return false
  41. }
  42. if u.Scheme == "ldap" {
  43. return true
  44. }
  45. return false
  46. }
  47. // revCheck should check the certificate for any revocations. It
  48. // returns a pair of booleans: the first indicates whether the certificate
  49. // is revoked, the second indicates whether the revocations were
  50. // successfully checked.. This leads to the following combinations:
  51. //
  52. // false, false: an error was encountered while checking revocations.
  53. //
  54. // false, true: the certificate was checked successfully and
  55. // it is not revoked.
  56. //
  57. // true, true: the certificate was checked successfully and
  58. // it is revoked.
  59. //
  60. // true, false: failure to check revocation status causes
  61. // verification to fail
  62. func revCheck(cert *x509.Certificate) (revoked, ok bool, err error) {
  63. for _, url := range cert.CRLDistributionPoints {
  64. if ldapURL(url) {
  65. log.Infof("skipping LDAP CRL: %s", url)
  66. continue
  67. }
  68. if revoked, ok, err := certIsRevokedCRL(cert, url); !ok {
  69. log.Warning("error checking revocation via CRL")
  70. if HardFail {
  71. return true, false, err
  72. }
  73. return false, false, err
  74. } else if revoked {
  75. log.Info("certificate is revoked via CRL")
  76. return true, true, err
  77. }
  78. }
  79. if revoked, ok, err := certIsRevokedOCSP(cert, HardFail); !ok {
  80. log.Warning("error checking revocation via OCSP")
  81. if HardFail {
  82. return true, false, err
  83. }
  84. return false, false, err
  85. } else if revoked {
  86. log.Info("certificate is revoked via OCSP")
  87. return true, true, err
  88. }
  89. return false, true, nil
  90. }
  91. // fetchCRL fetches and parses a CRL.
  92. func fetchCRL(url string) (*pkix.CertificateList, error) {
  93. resp, err := HTTPClient.Get(url)
  94. if err != nil {
  95. return nil, err
  96. }
  97. defer resp.Body.Close()
  98. if resp.StatusCode >= 300 {
  99. return nil, errors.New("failed to retrieve CRL")
  100. }
  101. body, err := crlRead(resp.Body)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return x509.ParseCRL(body)
  106. }
  107. func getIssuer(cert *x509.Certificate) *x509.Certificate {
  108. var issuer *x509.Certificate
  109. var err error
  110. for _, issuingCert := range cert.IssuingCertificateURL {
  111. issuer, err = fetchRemote(issuingCert)
  112. if err != nil {
  113. continue
  114. }
  115. break
  116. }
  117. return issuer
  118. }
  119. // check a cert against a specific CRL. Returns the same bool pair
  120. // as revCheck, plus an error if one occurred.
  121. func certIsRevokedCRL(cert *x509.Certificate, url string) (revoked, ok bool, err error) {
  122. crlLock.Lock()
  123. crl, ok := CRLSet[url]
  124. if ok && crl == nil {
  125. ok = false
  126. delete(CRLSet, url)
  127. }
  128. crlLock.Unlock()
  129. var shouldFetchCRL = true
  130. if ok {
  131. if !crl.HasExpired(time.Now()) {
  132. shouldFetchCRL = false
  133. }
  134. }
  135. issuer := getIssuer(cert)
  136. if shouldFetchCRL {
  137. var err error
  138. crl, err = fetchCRL(url)
  139. if err != nil {
  140. log.Warningf("failed to fetch CRL: %v", err)
  141. return false, false, err
  142. }
  143. // check CRL signature
  144. if issuer != nil {
  145. err = issuer.CheckCRLSignature(crl)
  146. if err != nil {
  147. log.Warningf("failed to verify CRL: %v", err)
  148. return false, false, err
  149. }
  150. }
  151. crlLock.Lock()
  152. CRLSet[url] = crl
  153. crlLock.Unlock()
  154. }
  155. for _, revoked := range crl.TBSCertList.RevokedCertificates {
  156. if cert.SerialNumber.Cmp(revoked.SerialNumber) == 0 {
  157. log.Info("Serial number match: intermediate is revoked.")
  158. return true, true, err
  159. }
  160. }
  161. return false, true, err
  162. }
  163. // VerifyCertificate ensures that the certificate passed in hasn't
  164. // expired and checks the CRL for the server.
  165. func VerifyCertificate(cert *x509.Certificate) (revoked, ok bool) {
  166. revoked, ok, _ = VerifyCertificateError(cert)
  167. return revoked, ok
  168. }
  169. // VerifyCertificateError ensures that the certificate passed in hasn't
  170. // expired and checks the CRL for the server.
  171. func VerifyCertificateError(cert *x509.Certificate) (revoked, ok bool, err error) {
  172. if !time.Now().Before(cert.NotAfter) {
  173. msg := fmt.Sprintf("Certificate expired %s\n", cert.NotAfter)
  174. log.Info(msg)
  175. return true, true, fmt.Errorf(msg)
  176. } else if !time.Now().After(cert.NotBefore) {
  177. msg := fmt.Sprintf("Certificate isn't valid until %s\n", cert.NotBefore)
  178. log.Info(msg)
  179. return true, true, fmt.Errorf(msg)
  180. }
  181. return revCheck(cert)
  182. }
  183. func fetchRemote(url string) (*x509.Certificate, error) {
  184. resp, err := HTTPClient.Get(url)
  185. if err != nil {
  186. return nil, err
  187. }
  188. defer resp.Body.Close()
  189. in, err := remoteRead(resp.Body)
  190. if err != nil {
  191. return nil, err
  192. }
  193. p, _ := pem.Decode(in)
  194. if p != nil {
  195. return helpers.ParseCertificatePEM(in)
  196. }
  197. return x509.ParseCertificate(in)
  198. }
  199. var ocspOpts = ocsp.RequestOptions{
  200. Hash: crypto.SHA1,
  201. }
  202. func certIsRevokedOCSP(leaf *x509.Certificate, strict bool) (revoked, ok bool, e error) {
  203. var err error
  204. ocspURLs := leaf.OCSPServer
  205. if len(ocspURLs) == 0 {
  206. // OCSP not enabled for this certificate.
  207. return false, true, nil
  208. }
  209. issuer := getIssuer(leaf)
  210. if issuer == nil {
  211. return false, false, nil
  212. }
  213. ocspRequest, err := ocsp.CreateRequest(leaf, issuer, &ocspOpts)
  214. if err != nil {
  215. return revoked, ok, err
  216. }
  217. for _, server := range ocspURLs {
  218. resp, err := sendOCSPRequest(server, ocspRequest, leaf, issuer)
  219. if err != nil {
  220. if strict {
  221. return revoked, ok, err
  222. }
  223. continue
  224. }
  225. // There wasn't an error fetching the OCSP status.
  226. ok = true
  227. if resp.Status != ocsp.Good {
  228. // The certificate was revoked.
  229. revoked = true
  230. }
  231. return revoked, ok, err
  232. }
  233. return revoked, ok, err
  234. }
  235. // sendOCSPRequest attempts to request an OCSP response from the
  236. // server. The error only indicates a failure to *fetch* the
  237. // certificate, and *does not* mean the certificate is valid.
  238. func sendOCSPRequest(server string, req []byte, leaf, issuer *x509.Certificate) (*ocsp.Response, error) {
  239. var resp *http.Response
  240. var err error
  241. if len(req) > 256 {
  242. buf := bytes.NewBuffer(req)
  243. resp, err = HTTPClient.Post(server, "application/ocsp-request", buf)
  244. } else {
  245. reqURL := server + "/" + neturl.QueryEscape(base64.StdEncoding.EncodeToString(req))
  246. resp, err = HTTPClient.Get(reqURL)
  247. }
  248. if err != nil {
  249. return nil, err
  250. }
  251. defer resp.Body.Close()
  252. if resp.StatusCode != http.StatusOK {
  253. return nil, errors.New("failed to retrieve OSCP")
  254. }
  255. body, err := ocspRead(resp.Body)
  256. if err != nil {
  257. return nil, err
  258. }
  259. switch {
  260. case bytes.Equal(body, ocsp.UnauthorizedErrorResponse):
  261. return nil, errors.New("OSCP unauthorized")
  262. case bytes.Equal(body, ocsp.MalformedRequestErrorResponse):
  263. return nil, errors.New("OSCP malformed")
  264. case bytes.Equal(body, ocsp.InternalErrorErrorResponse):
  265. return nil, errors.New("OSCP internal error")
  266. case bytes.Equal(body, ocsp.TryLaterErrorResponse):
  267. return nil, errors.New("OSCP try later")
  268. case bytes.Equal(body, ocsp.SigRequredErrorResponse):
  269. return nil, errors.New("OSCP signature required")
  270. }
  271. return ocsp.ParseResponseForCert(body, leaf, issuer)
  272. }
  273. var crlRead = ioutil.ReadAll
  274. // SetCRLFetcher sets the function to use to read from the http response body
  275. func SetCRLFetcher(fn func(io.Reader) ([]byte, error)) {
  276. crlRead = fn
  277. }
  278. var remoteRead = ioutil.ReadAll
  279. // SetRemoteFetcher sets the function to use to read from the http response body
  280. func SetRemoteFetcher(fn func(io.Reader) ([]byte, error)) {
  281. remoteRead = fn
  282. }
  283. var ocspRead = ioutil.ReadAll
  284. // SetOCSPFetcher sets the function to use to read from the http response body
  285. func SetOCSPFetcher(fn func(io.Reader) ([]byte, error)) {
  286. ocspRead = fn
  287. }