4
0

tls.go 8.8 KB

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