tls_auth.go 7.9 KB

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