tls.go 7.4 KB

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