tls_auth.go 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  1. package v1
  2. import (
  3. "bytes"
  4. "crypto"
  5. "crypto/x509"
  6. "encoding/pem"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "time"
  13. "github.com/gin-gonic/gin"
  14. log "github.com/sirupsen/logrus"
  15. "golang.org/x/crypto/ocsp"
  16. )
  17. type TLSAuth struct {
  18. AllowedOUs []string
  19. CrlPath string
  20. revocationCache map[string]cacheEntry
  21. cacheExpiration time.Duration
  22. logger *log.Entry
  23. }
  24. type cacheEntry struct {
  25. revoked bool
  26. timestamp time.Time
  27. }
  28. func (ta *TLSAuth) ocspQuery(server string, cert *x509.Certificate, issuer *x509.Certificate) (*ocsp.Response, error) {
  29. req, err := ocsp.CreateRequest(cert, issuer, &ocsp.RequestOptions{Hash: crypto.SHA256})
  30. if err != nil {
  31. ta.logger.Errorf("TLSAuth: error creating OCSP request: %s", err)
  32. return nil, err
  33. }
  34. httpRequest, err := http.NewRequest(http.MethodPost, server, bytes.NewBuffer(req))
  35. if err != nil {
  36. ta.logger.Error("TLSAuth: cannot create HTTP request for OCSP")
  37. return nil, err
  38. }
  39. ocspURL, err := url.Parse(server)
  40. if err != nil {
  41. ta.logger.Error("TLSAuth: cannot parse OCSP URL")
  42. return nil, err
  43. }
  44. httpRequest.Header.Add("Content-Type", "application/ocsp-request")
  45. httpRequest.Header.Add("Accept", "application/ocsp-response")
  46. httpRequest.Header.Add("host", ocspURL.Host)
  47. httpClient := &http.Client{}
  48. httpResponse, err := httpClient.Do(httpRequest)
  49. if err != nil {
  50. ta.logger.Error("TLSAuth: cannot send HTTP request to OCSP")
  51. return nil, err
  52. }
  53. defer httpResponse.Body.Close()
  54. output, err := io.ReadAll(httpResponse.Body)
  55. if err != nil {
  56. ta.logger.Error("TLSAuth: cannot read HTTP response from OCSP")
  57. return nil, err
  58. }
  59. ocspResponse, err := ocsp.ParseResponseForCert(output, cert, issuer)
  60. return ocspResponse, err
  61. }
  62. func (ta *TLSAuth) isExpired(cert *x509.Certificate) bool {
  63. now := time.Now().UTC()
  64. if cert.NotAfter.UTC().Before(now) {
  65. ta.logger.Errorf("TLSAuth: client certificate is expired (NotAfter: %s)", cert.NotAfter.UTC())
  66. return true
  67. }
  68. if cert.NotBefore.UTC().After(now) {
  69. ta.logger.Errorf("TLSAuth: client certificate is not yet valid (NotBefore: %s)", cert.NotBefore.UTC())
  70. return true
  71. }
  72. return false
  73. }
  74. // isOCSPRevoked checks if the client certificate is revoked by any of the OCSP servers present in the certificate.
  75. // It returns a boolean indicating if the certificate is revoked and a boolean indicating if the OCSP check was successful and could be cached.
  76. func (ta *TLSAuth) isOCSPRevoked(cert *x509.Certificate, issuer *x509.Certificate) (bool, bool) {
  77. if cert.OCSPServer == nil || len(cert.OCSPServer) == 0 {
  78. ta.logger.Infof("TLSAuth: no OCSP Server present in client certificate, skipping OCSP verification")
  79. return false, true
  80. }
  81. for _, server := range cert.OCSPServer {
  82. ocspResponse, err := ta.ocspQuery(server, cert, issuer)
  83. if err != nil {
  84. ta.logger.Errorf("TLSAuth: error querying OCSP server %s: %s", server, err)
  85. continue
  86. }
  87. switch ocspResponse.Status {
  88. case ocsp.Good:
  89. return false, true
  90. case ocsp.Revoked:
  91. ta.logger.Errorf("TLSAuth: client certificate is revoked by server %s", server)
  92. return true, true
  93. case ocsp.Unknown:
  94. log.Debugf("unknow OCSP status for server %s", server)
  95. continue
  96. }
  97. }
  98. log.Infof("Could not get any valid OCSP response, assuming the cert is revoked")
  99. return true, false
  100. }
  101. // isCRLRevoked checks if the client certificate is revoked by the CRL present in the CrlPath.
  102. // It returns a boolean indicating if the certificate is revoked and a boolean indicating if the CRL check was successful and could be cached.
  103. func (ta *TLSAuth) isCRLRevoked(cert *x509.Certificate) (bool, bool) {
  104. if ta.CrlPath == "" {
  105. ta.logger.Info("no crl_path, skipping CRL check")
  106. return false, true
  107. }
  108. crlContent, err := os.ReadFile(ta.CrlPath)
  109. if err != nil {
  110. ta.logger.Errorf("could not read CRL file, skipping check: %s", err)
  111. return false, false
  112. }
  113. crlBinary, rest := pem.Decode(crlContent)
  114. if len(rest) > 0 {
  115. ta.logger.Warn("CRL file contains more than one PEM block, ignoring the rest")
  116. }
  117. crl, err := x509.ParseRevocationList(crlBinary.Bytes)
  118. if err != nil {
  119. ta.logger.Errorf("could not parse CRL file, skipping check: %s", err)
  120. return false, false
  121. }
  122. now := time.Now().UTC()
  123. if now.After(crl.NextUpdate) {
  124. ta.logger.Warn("CRL has expired, will still validate the cert against it.")
  125. }
  126. if now.Before(crl.ThisUpdate) {
  127. ta.logger.Warn("CRL is not yet valid, will still validate the cert against it.")
  128. }
  129. for _, revoked := range crl.RevokedCertificateEntries {
  130. if revoked.SerialNumber.Cmp(cert.SerialNumber) == 0 {
  131. ta.logger.Warn("client certificate is revoked by CRL")
  132. return true, true
  133. }
  134. }
  135. return false, true
  136. }
  137. func (ta *TLSAuth) isRevoked(cert *x509.Certificate, issuer *x509.Certificate) (bool, error) {
  138. sn := cert.SerialNumber.String()
  139. if cacheValue, ok := ta.revocationCache[sn]; ok {
  140. if time.Now().UTC().Sub(cacheValue.timestamp) < ta.cacheExpiration {
  141. ta.logger.Debugf("TLSAuth: using cached value for cert %s: %t", sn, cacheValue.revoked)
  142. return cacheValue.revoked, nil
  143. }
  144. ta.logger.Debugf("TLSAuth: cached value expired, removing from cache")
  145. delete(ta.revocationCache, sn)
  146. } else {
  147. ta.logger.Tracef("TLSAuth: no cached value for cert %s", sn)
  148. }
  149. revokedByOCSP, cacheOCSP := ta.isOCSPRevoked(cert, issuer)
  150. revokedByCRL, cacheCRL := ta.isCRLRevoked(cert)
  151. revoked := revokedByOCSP || revokedByCRL
  152. if cacheOCSP && cacheCRL {
  153. ta.revocationCache[sn] = cacheEntry{
  154. revoked: revoked,
  155. timestamp: time.Now().UTC(),
  156. }
  157. }
  158. return revoked, nil
  159. }
  160. func (ta *TLSAuth) isInvalid(cert *x509.Certificate, issuer *x509.Certificate) (bool, error) {
  161. if ta.isExpired(cert) {
  162. return true, nil
  163. }
  164. revoked, err := ta.isRevoked(cert, issuer)
  165. if err != nil {
  166. //Fail securely, if we can't check the revocation status, let's consider the cert invalid
  167. //We may change this in the future based on users feedback, but this seems the most sensible thing to do
  168. return true, fmt.Errorf("could not check for client certification revocation status: %w", err)
  169. }
  170. return revoked, nil
  171. }
  172. func (ta *TLSAuth) SetAllowedOu(allowedOus []string) error {
  173. for _, ou := range allowedOus {
  174. //disallow empty ou
  175. if ou == "" {
  176. return fmt.Errorf("empty ou isn't allowed")
  177. }
  178. //drop & warn on duplicate ou
  179. ok := true
  180. for _, validOu := range ta.AllowedOUs {
  181. if validOu == ou {
  182. ta.logger.Warningf("dropping duplicate ou %s", ou)
  183. ok = false
  184. }
  185. }
  186. if ok {
  187. ta.AllowedOUs = append(ta.AllowedOUs, ou)
  188. }
  189. }
  190. return nil
  191. }
  192. func (ta *TLSAuth) ValidateCert(c *gin.Context) (bool, string, error) {
  193. //Checks cert validity, Returns true + CN if client cert matches requested OU
  194. var clientCert *x509.Certificate
  195. if c.Request.TLS == nil || len(c.Request.TLS.PeerCertificates) == 0 {
  196. //do not error if it's not TLS or there are no peer certs
  197. return false, "", nil
  198. }
  199. if len(c.Request.TLS.VerifiedChains) > 0 {
  200. validOU := false
  201. clientCert = c.Request.TLS.VerifiedChains[0][0]
  202. for _, ou := range clientCert.Subject.OrganizationalUnit {
  203. for _, allowedOu := range ta.AllowedOUs {
  204. if allowedOu == ou {
  205. validOU = true
  206. break
  207. }
  208. }
  209. }
  210. if !validOU {
  211. return false, "", fmt.Errorf("client certificate OU (%v) doesn't match expected OU (%v)",
  212. clientCert.Subject.OrganizationalUnit, ta.AllowedOUs)
  213. }
  214. revoked, err := ta.isInvalid(clientCert, c.Request.TLS.VerifiedChains[0][1])
  215. if err != nil {
  216. ta.logger.Errorf("TLSAuth: error checking if client certificate is revoked: %s", err)
  217. return false, "", fmt.Errorf("could not check for client certification revocation status: %w", err)
  218. }
  219. if revoked {
  220. return false, "", fmt.Errorf("client certificate for CN=%s OU=%s is revoked", clientCert.Subject.CommonName, clientCert.Subject.OrganizationalUnit)
  221. }
  222. ta.logger.Debugf("client OU %v is allowed vs required OU %v", clientCert.Subject.OrganizationalUnit, ta.AllowedOUs)
  223. return true, clientCert.Subject.CommonName, nil
  224. }
  225. return false, "", fmt.Errorf("no verified cert in request")
  226. }
  227. func NewTLSAuth(allowedOus []string, crlPath string, cacheExpiration time.Duration, logger *log.Entry) (*TLSAuth, error) {
  228. ta := &TLSAuth{
  229. revocationCache: map[string]cacheEntry{},
  230. cacheExpiration: cacheExpiration,
  231. CrlPath: crlPath,
  232. logger: logger,
  233. }
  234. err := ta.SetAllowedOu(allowedOus)
  235. if err != nil {
  236. return nil, err
  237. }
  238. return ta, nil
  239. }