tls.go 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  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:deprecated
  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:deprecated
  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. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) {
  137. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  138. // TLS dialers do not support context, but we can use the context
  139. // deadline if it is set.
  140. var deadline time.Time
  141. if t, ok := ctx.Deadline(); ok {
  142. deadline = t
  143. }
  144. return tls.DialWithDialer(&net.Dialer{
  145. Timeout: 30 * time.Second,
  146. KeepAlive: 30 * time.Second,
  147. Deadline: deadline,
  148. DualStack: true,
  149. }, network, addr, tlsCtx.mutableConfig.TLSConfig())
  150. }
  151. }
  152. // Certificate returns the server or client certificate from the sign response.
  153. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  154. if sign.ServerPEM.Certificate == nil {
  155. return nil, errors.New("ca: certificate does not exist")
  156. }
  157. return sign.ServerPEM.Certificate, nil
  158. }
  159. // IntermediateCertificate returns the CA intermediate certificate from the sign
  160. // response.
  161. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  162. if sign.CaPEM.Certificate == nil {
  163. return nil, errors.New("ca: certificate does not exist")
  164. }
  165. return sign.CaPEM.Certificate, nil
  166. }
  167. // RootCertificate returns the root certificate from the sign response.
  168. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  169. if sign == nil || sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  170. return nil, errors.New("ca: certificate does not exist")
  171. }
  172. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  173. if len(lastChain) == 0 {
  174. return nil, errors.New("ca: certificate does not exist")
  175. }
  176. return lastChain[len(lastChain)-1], nil
  177. }
  178. // TLSCertificate creates a new TLS certificate from the sign response and the
  179. // private key used.
  180. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  181. certPEM, err := getPEM(sign.ServerPEM)
  182. if err != nil {
  183. return nil, err
  184. }
  185. caPEM, err := getPEM(sign.CaPEM)
  186. if err != nil {
  187. return nil, err
  188. }
  189. keyPEM, err := getPEM(pk)
  190. if err != nil {
  191. return nil, err
  192. }
  193. chain := append(certPEM, caPEM...)
  194. cert, err := tls.X509KeyPair(chain, keyPEM)
  195. if err != nil {
  196. return nil, errors.Wrap(err, "error creating tls certificate")
  197. }
  198. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  199. if err != nil {
  200. return nil, errors.Wrap(err, "error parsing tls certificate")
  201. }
  202. cert.Leaf = leaf
  203. return &cert, nil
  204. }
  205. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  206. if sign.TLSOptions != nil {
  207. return sign.TLSOptions.TLSConfig()
  208. }
  209. return &tls.Config{
  210. MinVersion: tls.VersionTLS12,
  211. }
  212. }
  213. // getDefaultTransport returns an http.Transport with the same parameters than
  214. // http.DefaultTransport, but adds the given tls.Config and configures the
  215. // transport for HTTP/2.
  216. func getDefaultTransport(tlsConfig *tls.Config) (*http.Transport, error) {
  217. tr := &http.Transport{
  218. Proxy: http.ProxyFromEnvironment,
  219. DialContext: (&net.Dialer{
  220. Timeout: 30 * time.Second,
  221. KeepAlive: 30 * time.Second,
  222. DualStack: true,
  223. }).DialContext,
  224. MaxIdleConns: 100,
  225. IdleConnTimeout: 90 * time.Second,
  226. TLSHandshakeTimeout: 10 * time.Second,
  227. ExpectContinueTimeout: 1 * time.Second,
  228. TLSClientConfig: tlsConfig,
  229. }
  230. if err := http2.ConfigureTransport(tr); err != nil {
  231. return nil, errors.Wrap(err, "error configuring transport")
  232. }
  233. return tr, nil
  234. }
  235. func getPEM(i interface{}) ([]byte, error) {
  236. block := new(pem.Block)
  237. switch i := i.(type) {
  238. case api.Certificate:
  239. block.Type = "CERTIFICATE"
  240. block.Bytes = i.Raw
  241. case *x509.Certificate:
  242. block.Type = "CERTIFICATE"
  243. block.Bytes = i.Raw
  244. case *rsa.PrivateKey:
  245. block.Type = "RSA PRIVATE KEY"
  246. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  247. case *ecdsa.PrivateKey:
  248. var err error
  249. block.Type = "EC PRIVATE KEY"
  250. block.Bytes, err = x509.MarshalECPrivateKey(i)
  251. if err != nil {
  252. return nil, errors.Wrap(err, "error marshaling private key")
  253. }
  254. default:
  255. return nil, errors.Errorf("unsupported key type %T", i)
  256. }
  257. return pem.EncodeToMemory(block), nil
  258. }
  259. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  260. return func() (*tls.Certificate, error) {
  261. // Get updated list of roots
  262. if err := ctx.applyRenew(); err != nil {
  263. return nil, err
  264. }
  265. // Get new certificate
  266. sign, err := client.Renew(tr)
  267. if err != nil {
  268. return nil, err
  269. }
  270. return TLSCertificate(sign, pk)
  271. }
  272. }