tls.go 7.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244
  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 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. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  32. tlsConfig.PreferServerCipherSuites = true
  33. // Build RootCAs with given root certificate
  34. if pool := c.getCertPool(sign); pool != nil {
  35. tlsConfig.RootCAs = pool
  36. }
  37. // Parse Certificates and build NameToCertificate
  38. tlsConfig.BuildNameToCertificate()
  39. // Update renew function with transport
  40. tr, err := getDefaultTransport(tlsConfig)
  41. if err != nil {
  42. return nil, err
  43. }
  44. renewer.RenewCertificate = getRenewFunc(c, tr, pk)
  45. // Start renewer
  46. renewer.RunContext(ctx)
  47. return tlsConfig, nil
  48. }
  49. // GetServerTLSConfig returns a tls.Config for server use configured with the
  50. // sign certificate, and a new certificate pool with the sign root certificate.
  51. // The 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. tlsConfig.GetCertificate = renewer.GetCertificate
  65. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  66. tlsConfig.PreferServerCipherSuites = true
  67. // Build RootCAs with given root certificate
  68. if pool := c.getCertPool(sign); pool != nil {
  69. tlsConfig.ClientCAs = pool
  70. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  71. // Add RootCAs for refresh client
  72. tlsConfig.RootCAs = pool
  73. }
  74. // Update renew function with transport
  75. tr, err := getDefaultTransport(tlsConfig)
  76. if err != nil {
  77. return nil, err
  78. }
  79. renewer.RenewCertificate = getRenewFunc(c, tr, pk)
  80. // Start renewer
  81. renewer.RunContext(ctx)
  82. return tlsConfig, nil
  83. }
  84. // Transport returns an http.Transport configured to use the client certificate from the sign response.
  85. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey) (*http.Transport, error) {
  86. tlsConfig, err := c.GetClientTLSConfig(ctx, sign, pk)
  87. if err != nil {
  88. return nil, err
  89. }
  90. return getDefaultTransport(tlsConfig)
  91. }
  92. // getCertPool returns the transport x509.CertPool or the one from the sign
  93. // request.
  94. func (c *Client) getCertPool(sign *api.SignResponse) *x509.CertPool {
  95. // Return the transport certPool
  96. if c.certPool != nil {
  97. return c.certPool
  98. }
  99. // Return certificate used in sign request.
  100. if root, err := RootCertificate(sign); err == nil {
  101. pool := x509.NewCertPool()
  102. pool.AddCert(root)
  103. return pool
  104. }
  105. return nil
  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. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  161. if sign.TLSOptions != nil {
  162. return sign.TLSOptions.TLSConfig()
  163. }
  164. return &tls.Config{
  165. MinVersion: tls.VersionTLS12,
  166. }
  167. }
  168. // getDefaultTransport returns an http.Transport with the same parameters than
  169. // http.DefaultTransport, but adds the given tls.Config and configures the
  170. // transport for HTTP/2.
  171. func getDefaultTransport(tlsConfig *tls.Config) (*http.Transport, error) {
  172. tr := &http.Transport{
  173. Proxy: http.ProxyFromEnvironment,
  174. DialContext: (&net.Dialer{
  175. Timeout: 30 * time.Second,
  176. KeepAlive: 30 * time.Second,
  177. DualStack: true,
  178. }).DialContext,
  179. MaxIdleConns: 100,
  180. IdleConnTimeout: 90 * time.Second,
  181. TLSHandshakeTimeout: 10 * time.Second,
  182. ExpectContinueTimeout: 1 * time.Second,
  183. TLSClientConfig: tlsConfig,
  184. }
  185. if err := http2.ConfigureTransport(tr); err != nil {
  186. return nil, errors.Wrap(err, "error configuring transport")
  187. }
  188. return tr, nil
  189. }
  190. func getPEM(i interface{}) ([]byte, error) {
  191. block := new(pem.Block)
  192. switch i := i.(type) {
  193. case api.Certificate:
  194. block.Type = "CERTIFICATE"
  195. block.Bytes = i.Raw
  196. case *x509.Certificate:
  197. block.Type = "CERTIFICATE"
  198. block.Bytes = i.Raw
  199. case *rsa.PrivateKey:
  200. block.Type = "RSA PRIVATE KEY"
  201. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  202. case *ecdsa.PrivateKey:
  203. var err error
  204. block.Type = "EC PRIVATE KEY"
  205. block.Bytes, err = x509.MarshalECPrivateKey(i)
  206. if err != nil {
  207. return nil, errors.Wrap(err, "error marshaling private key")
  208. }
  209. default:
  210. return nil, errors.Errorf("unsupported key type %T", i)
  211. }
  212. return pem.EncodeToMemory(block), nil
  213. }
  214. func getRenewFunc(client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  215. return func() (*tls.Certificate, error) {
  216. sign, err := client.Renew(tr)
  217. if err != nil {
  218. return nil, err
  219. }
  220. return TLSCertificate(sign, pk)
  221. }
  222. }