tls.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. package ca
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/rsa"
  7. "crypto/tls"
  8. "crypto/x509"
  9. "encoding/pem"
  10. "net"
  11. "net/http"
  12. "time"
  13. "github.com/pkg/errors"
  14. "github.com/smallstep/certificates/api"
  15. "golang.org/x/net/http2"
  16. )
  17. // GetClientTLSConfig returns a tls.Config for client use configured with the
  18. // sign certificate, and a new certificate pool with the sign root certificate.
  19. // The client certificate will automatically rotate before expiring.
  20. func (c *Client) GetClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  21. cert, err := TLSCertificate(sign, pk)
  22. if err != nil {
  23. return nil, err
  24. }
  25. renewer, err := NewTLSRenewer(cert, nil)
  26. if err != nil {
  27. return nil, err
  28. }
  29. tlsConfig := getDefaultTLSConfig(sign)
  30. // Note that with GetClientCertificate tlsConfig.Certificates is not used.
  31. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  32. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  33. tlsConfig.PreferServerCipherSuites = true
  34. // Build RootCAs with given root certificate
  35. if pool := getCertPool(sign); pool != nil {
  36. tlsConfig.RootCAs = pool
  37. }
  38. // Apply options if given
  39. tlsCtx := newTLSOptionCtx(c, tlsConfig)
  40. if err := tlsCtx.apply(options); err != nil {
  41. return nil, err
  42. }
  43. // Update renew function with transport
  44. tr, err := getDefaultTransport(tlsConfig)
  45. if err != nil {
  46. return nil, err
  47. }
  48. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  49. // Update client transport
  50. c.client.Transport = tr
  51. // Start renewer
  52. renewer.RunContext(ctx)
  53. return tlsConfig, nil
  54. }
  55. // GetServerTLSConfig returns a tls.Config for server use configured with the
  56. // sign certificate, and a new certificate pool with the sign root certificate.
  57. // The returned tls.Config will only verify the client certificate if provided.
  58. // The server certificate will automatically rotate before expiring.
  59. func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  60. cert, err := TLSCertificate(sign, pk)
  61. if err != nil {
  62. return nil, err
  63. }
  64. renewer, err := NewTLSRenewer(cert, nil)
  65. if err != nil {
  66. return nil, err
  67. }
  68. tlsConfig := getDefaultTLSConfig(sign)
  69. // Note that GetCertificate will only be called if the client supplies SNI
  70. // information or if tlsConfig.Certificates is empty.
  71. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  72. tlsConfig.GetCertificate = renewer.GetCertificate
  73. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  74. tlsConfig.PreferServerCipherSuites = true
  75. // Build RootCAs with given root certificate
  76. if pool := getCertPool(sign); pool != nil {
  77. tlsConfig.ClientCAs = pool
  78. tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  79. // Add RootCAs for refresh client
  80. tlsConfig.RootCAs = pool
  81. }
  82. // Apply options if given
  83. tlsCtx := newTLSOptionCtx(c, tlsConfig)
  84. if err := tlsCtx.apply(options); err != nil {
  85. return nil, err
  86. }
  87. // Update renew function with transport
  88. tr, err := getDefaultTransport(tlsConfig)
  89. if err != nil {
  90. return nil, err
  91. }
  92. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  93. // Update client transport
  94. c.client.Transport = tr
  95. // Start renewer
  96. renewer.RunContext(ctx)
  97. return tlsConfig, nil
  98. }
  99. // Transport returns an http.Transport configured to use the client certificate from the sign response.
  100. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*http.Transport, error) {
  101. tlsConfig, err := c.GetClientTLSConfig(ctx, sign, pk, options...)
  102. if err != nil {
  103. return nil, err
  104. }
  105. return getDefaultTransport(tlsConfig)
  106. }
  107. // Certificate returns the server or client certificate from the sign response.
  108. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  109. if sign.ServerPEM.Certificate == nil {
  110. return nil, errors.New("ca: certificate does not exists")
  111. }
  112. return sign.ServerPEM.Certificate, nil
  113. }
  114. // IntermediateCertificate returns the CA intermediate certificate from the sign
  115. // response.
  116. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  117. if sign.CaPEM.Certificate == nil {
  118. return nil, errors.New("ca: certificate does not exists")
  119. }
  120. return sign.CaPEM.Certificate, nil
  121. }
  122. // RootCertificate returns the root certificate from the sign response.
  123. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  124. if sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  125. return nil, errors.New("ca: certificate does not exists")
  126. }
  127. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  128. if len(lastChain) == 0 {
  129. return nil, errors.New("ca: certificate does not exists")
  130. }
  131. return lastChain[len(lastChain)-1], nil
  132. }
  133. // TLSCertificate creates a new TLS certificate from the sign response and the
  134. // private key used.
  135. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  136. certPEM, err := getPEM(sign.ServerPEM)
  137. if err != nil {
  138. return nil, err
  139. }
  140. caPEM, err := getPEM(sign.CaPEM)
  141. if err != nil {
  142. return nil, err
  143. }
  144. keyPEM, err := getPEM(pk)
  145. if err != nil {
  146. return nil, err
  147. }
  148. chain := append(certPEM, caPEM...)
  149. cert, err := tls.X509KeyPair(chain, keyPEM)
  150. if err != nil {
  151. return nil, errors.Wrap(err, "error creating tls certificate")
  152. }
  153. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  154. if err != nil {
  155. return nil, errors.Wrap(err, "error parsing tls certificate")
  156. }
  157. cert.Leaf = leaf
  158. return &cert, nil
  159. }
  160. // getCertPool returns the transport x509.CertPool or the one from the sign
  161. // request.
  162. func getCertPool(sign *api.SignResponse) *x509.CertPool {
  163. if root, err := RootCertificate(sign); err == nil {
  164. pool := x509.NewCertPool()
  165. pool.AddCert(root)
  166. return pool
  167. }
  168. return nil
  169. }
  170. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  171. if sign.TLSOptions != nil {
  172. return sign.TLSOptions.TLSConfig()
  173. }
  174. return &tls.Config{
  175. MinVersion: tls.VersionTLS12,
  176. }
  177. }
  178. // getDefaultTransport returns an http.Transport with the same parameters than
  179. // http.DefaultTransport, but adds the given tls.Config and configures the
  180. // transport for HTTP/2.
  181. func getDefaultTransport(tlsConfig *tls.Config) (*http.Transport, error) {
  182. tr := &http.Transport{
  183. Proxy: http.ProxyFromEnvironment,
  184. DialContext: (&net.Dialer{
  185. Timeout: 30 * time.Second,
  186. KeepAlive: 30 * time.Second,
  187. DualStack: true,
  188. }).DialContext,
  189. MaxIdleConns: 100,
  190. IdleConnTimeout: 90 * time.Second,
  191. TLSHandshakeTimeout: 10 * time.Second,
  192. ExpectContinueTimeout: 1 * time.Second,
  193. TLSClientConfig: tlsConfig,
  194. }
  195. if err := http2.ConfigureTransport(tr); err != nil {
  196. return nil, errors.Wrap(err, "error configuring transport")
  197. }
  198. return tr, nil
  199. }
  200. func getPEM(i interface{}) ([]byte, error) {
  201. block := new(pem.Block)
  202. switch i := i.(type) {
  203. case api.Certificate:
  204. block.Type = "CERTIFICATE"
  205. block.Bytes = i.Raw
  206. case *x509.Certificate:
  207. block.Type = "CERTIFICATE"
  208. block.Bytes = i.Raw
  209. case *rsa.PrivateKey:
  210. block.Type = "RSA PRIVATE KEY"
  211. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  212. case *ecdsa.PrivateKey:
  213. var err error
  214. block.Type = "EC PRIVATE KEY"
  215. block.Bytes, err = x509.MarshalECPrivateKey(i)
  216. if err != nil {
  217. return nil, errors.Wrap(err, "error marshaling private key")
  218. }
  219. default:
  220. return nil, errors.Errorf("unsupported key type %T", i)
  221. }
  222. return pem.EncodeToMemory(block), nil
  223. }
  224. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  225. return func() (*tls.Certificate, error) {
  226. // Get updated list of roots
  227. if err := ctx.applyRenew(); err != nil {
  228. return nil, err
  229. }
  230. // Get new certificate
  231. sign, err := client.Renew(tr)
  232. if err != nil {
  233. return nil, err
  234. }
  235. return TLSCertificate(sign, pk)
  236. }
  237. }