tls.go 7.9 KB

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