revoke.go 8.2 KB

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