tls.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302
  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. tlsConfig, _, err := c.getClientTLSConfig(ctx, sign, pk, options)
  22. if err != nil {
  23. return nil, err
  24. }
  25. return tlsConfig, nil
  26. }
  27. func (c *Client) getClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options []TLSOption) (*tls.Config, *http.Transport, error) {
  28. cert, err := TLSCertificate(sign, pk)
  29. if err != nil {
  30. return nil, nil, err
  31. }
  32. renewer, err := NewTLSRenewer(cert, nil)
  33. if err != nil {
  34. return nil, nil, err
  35. }
  36. tlsConfig := getDefaultTLSConfig(sign)
  37. // Note that with GetClientCertificate tlsConfig.Certificates is not used.
  38. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  39. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  40. tlsConfig.PreferServerCipherSuites = true
  41. // Apply options and initialize mutable tls.Config
  42. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  43. if err := tlsCtx.apply(options); err != nil {
  44. return nil, nil, err
  45. }
  46. // Update renew function with transport
  47. tr, err := getDefaultTransport(tlsConfig)
  48. if err != nil {
  49. return nil, nil, err
  50. }
  51. // Use mutable tls.Config on renew
  52. tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck
  53. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  54. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  55. // Update client transport
  56. c.SetTransport(tr)
  57. // Start renewer
  58. renewer.RunContext(ctx)
  59. return tlsConfig, tr, nil
  60. }
  61. // GetServerTLSConfig returns a tls.Config for server use configured with the
  62. // sign certificate, and a new certificate pool with the sign root certificate.
  63. // The returned tls.Config will only verify the client certificate if provided.
  64. // The server certificate will automatically rotate before expiring.
  65. func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  66. cert, err := TLSCertificate(sign, pk)
  67. if err != nil {
  68. return nil, err
  69. }
  70. renewer, err := NewTLSRenewer(cert, nil)
  71. if err != nil {
  72. return nil, err
  73. }
  74. tlsConfig := getDefaultTLSConfig(sign)
  75. // Note that GetCertificate will only be called if the client supplies SNI
  76. // information or if tlsConfig.Certificates is empty.
  77. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  78. tlsConfig.GetCertificate = renewer.GetCertificate
  79. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  80. tlsConfig.PreferServerCipherSuites = true
  81. tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  82. // Apply options and initialize mutable tls.Config
  83. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  84. if err := tlsCtx.apply(options); err != nil {
  85. return nil, err
  86. }
  87. // GetConfigForClient allows seamless root and federated roots rotation.
  88. // If the return of the callback is not-nil, it will use the returned
  89. // tls.Config instead of the default one.
  90. tlsConfig.GetConfigForClient = c.buildGetConfigForClient(tlsCtx)
  91. // Update renew function with transport
  92. tr, err := getDefaultTransport(tlsConfig)
  93. if err != nil {
  94. return nil, err
  95. }
  96. // Use mutable tls.Config on renew
  97. tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck
  98. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  99. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  100. // Update client transport
  101. c.SetTransport(tr)
  102. // Start renewer
  103. renewer.RunContext(ctx)
  104. return tlsConfig, nil
  105. }
  106. // Transport returns an http.Transport configured to use the client certificate from the sign response.
  107. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*http.Transport, error) {
  108. _, tr, err := c.getClientTLSConfig(ctx, sign, pk, options)
  109. if err != nil {
  110. return nil, err
  111. }
  112. return tr, nil
  113. }
  114. // buildGetConfigForClient returns an implementation of GetConfigForClient
  115. // callback in tls.Config.
  116. //
  117. // If the implementation returns a nil tls.Config, the original Config will be
  118. // used, but if it's non-nil, the returned Config will be used to handle this
  119. // connection.
  120. func (c *Client) buildGetConfigForClient(ctx *TLSOptionCtx) func(*tls.ClientHelloInfo) (*tls.Config, error) {
  121. return func(*tls.ClientHelloInfo) (*tls.Config, error) {
  122. return ctx.mutableConfig.TLSConfig(), nil
  123. }
  124. }
  125. // buildDialTLS returns an implementation of DialTLS callback in http.Transport.
  126. func (c *Client) buildDialTLS(ctx *TLSOptionCtx) func(network, addr string) (net.Conn, error) {
  127. return func(network, addr string) (net.Conn, error) {
  128. return tls.DialWithDialer(&net.Dialer{
  129. Timeout: 30 * time.Second,
  130. KeepAlive: 30 * time.Second,
  131. DualStack: true,
  132. }, network, addr, ctx.mutableConfig.TLSConfig())
  133. }
  134. }
  135. // buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport.
  136. // nolint:unused
  137. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) {
  138. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  139. // TLS dialers do not support context, but we can use the context
  140. // deadline if it is set.
  141. var deadline time.Time
  142. if t, ok := ctx.Deadline(); ok {
  143. deadline = t
  144. }
  145. return tls.DialWithDialer(&net.Dialer{
  146. Timeout: 30 * time.Second,
  147. KeepAlive: 30 * time.Second,
  148. Deadline: deadline,
  149. DualStack: true,
  150. }, network, addr, tlsCtx.mutableConfig.TLSConfig())
  151. }
  152. }
  153. // Certificate returns the server or client certificate from the sign response.
  154. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  155. if sign.ServerPEM.Certificate == nil {
  156. return nil, errors.New("ca: certificate does not exist")
  157. }
  158. return sign.ServerPEM.Certificate, nil
  159. }
  160. // IntermediateCertificate returns the CA intermediate certificate from the sign
  161. // response.
  162. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  163. if sign.CaPEM.Certificate == nil {
  164. return nil, errors.New("ca: certificate does not exist")
  165. }
  166. return sign.CaPEM.Certificate, nil
  167. }
  168. // RootCertificate returns the root certificate from the sign response.
  169. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  170. if sign == nil || sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  171. return nil, errors.New("ca: certificate does not exist")
  172. }
  173. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  174. if len(lastChain) == 0 {
  175. return nil, errors.New("ca: certificate does not exist")
  176. }
  177. return lastChain[len(lastChain)-1], nil
  178. }
  179. // TLSCertificate creates a new TLS certificate from the sign response and the
  180. // private key used.
  181. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  182. certPEM, err := getPEM(sign.ServerPEM)
  183. if err != nil {
  184. return nil, err
  185. }
  186. caPEM, err := getPEM(sign.CaPEM)
  187. if err != nil {
  188. return nil, err
  189. }
  190. keyPEM, err := getPEM(pk)
  191. if err != nil {
  192. return nil, err
  193. }
  194. chain := append(certPEM, caPEM...)
  195. cert, err := tls.X509KeyPair(chain, keyPEM)
  196. if err != nil {
  197. return nil, errors.Wrap(err, "error creating tls certificate")
  198. }
  199. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  200. if err != nil {
  201. return nil, errors.Wrap(err, "error parsing tls certificate")
  202. }
  203. cert.Leaf = leaf
  204. return &cert, nil
  205. }
  206. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  207. if sign.TLSOptions != nil {
  208. return sign.TLSOptions.TLSConfig()
  209. }
  210. return &tls.Config{
  211. MinVersion: tls.VersionTLS12,
  212. }
  213. }
  214. // getDefaultTransport returns an http.Transport with the same parameters than
  215. // http.DefaultTransport, but adds the given tls.Config and configures the
  216. // transport for HTTP/2.
  217. func getDefaultTransport(tlsConfig *tls.Config) (*http.Transport, error) {
  218. tr := &http.Transport{
  219. Proxy: http.ProxyFromEnvironment,
  220. DialContext: (&net.Dialer{
  221. Timeout: 30 * time.Second,
  222. KeepAlive: 30 * time.Second,
  223. DualStack: true,
  224. }).DialContext,
  225. MaxIdleConns: 100,
  226. IdleConnTimeout: 90 * time.Second,
  227. TLSHandshakeTimeout: 10 * time.Second,
  228. ExpectContinueTimeout: 1 * time.Second,
  229. TLSClientConfig: tlsConfig,
  230. }
  231. if err := http2.ConfigureTransport(tr); err != nil {
  232. return nil, errors.Wrap(err, "error configuring transport")
  233. }
  234. return tr, nil
  235. }
  236. func getPEM(i interface{}) ([]byte, error) {
  237. block := new(pem.Block)
  238. switch i := i.(type) {
  239. case api.Certificate:
  240. block.Type = "CERTIFICATE"
  241. block.Bytes = i.Raw
  242. case *x509.Certificate:
  243. block.Type = "CERTIFICATE"
  244. block.Bytes = i.Raw
  245. case *rsa.PrivateKey:
  246. block.Type = "RSA PRIVATE KEY"
  247. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  248. case *ecdsa.PrivateKey:
  249. var err error
  250. block.Type = "EC PRIVATE KEY"
  251. block.Bytes, err = x509.MarshalECPrivateKey(i)
  252. if err != nil {
  253. return nil, errors.Wrap(err, "error marshaling private key")
  254. }
  255. default:
  256. return nil, errors.Errorf("unsupported key type %T", i)
  257. }
  258. return pem.EncodeToMemory(block), nil
  259. }
  260. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  261. return func() (*tls.Certificate, error) {
  262. // Get updated list of roots
  263. if err := ctx.applyRenew(); err != nil {
  264. return nil, err
  265. }
  266. // Get new certificate
  267. sign, err := client.Renew(tr)
  268. if err != nil {
  269. return nil, err
  270. }
  271. return TLSCertificate(sign, pk)
  272. }
  273. }