tls.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. package ca
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/ecdsa"
  6. "crypto/ed25519"
  7. "crypto/rsa"
  8. "crypto/tls"
  9. "crypto/x509"
  10. "encoding/pem"
  11. "net"
  12. "net/http"
  13. "os"
  14. "time"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/certificates/api"
  17. "github.com/smallstep/certificates/ca/identity"
  18. )
  19. // mTLSDialContext will hold the dial context function to use in
  20. // getDefaultTransport.
  21. var mTLSDialContext func() func(ctx context.Context, network, address string) (net.Conn, error)
  22. func init() {
  23. // STEP_TLS_TUNNEL is an environment variable that can be set to do an TLS
  24. // over (m)TLS tunnel to step-ca using identity-like credentials. The value
  25. // is a path to a json file with the tunnel host, certificate, key and root
  26. // used to create the (m)TLS tunnel.
  27. //
  28. // The configuration should look like:
  29. // {
  30. // "type": "tTLS",
  31. // "host": "tunnel.example.com:443"
  32. // "crt": "/path/to/tunnel.crt",
  33. // "key": "/path/to/tunnel.key",
  34. // "root": "/path/to/tunnel-root.crt"
  35. // }
  36. //
  37. // This feature is EXPERIMENTAL and might change at any time.
  38. if path := os.Getenv("STEP_TLS_TUNNEL"); path != "" {
  39. id, err := identity.LoadIdentity(path)
  40. if err != nil {
  41. panic(err)
  42. }
  43. if err := id.Validate(); err != nil {
  44. panic(err)
  45. }
  46. host, port, err := net.SplitHostPort(id.Host)
  47. if err != nil {
  48. panic(err)
  49. }
  50. pool, err := id.GetCertPool()
  51. if err != nil {
  52. panic(err)
  53. }
  54. mTLSDialContext = func() func(ctx context.Context, network, address string) (net.Conn, error) {
  55. d := &tls.Dialer{
  56. NetDialer: getDefaultDialer(),
  57. Config: &tls.Config{
  58. RootCAs: pool,
  59. GetClientCertificate: id.GetClientCertificateFunc(),
  60. },
  61. }
  62. return func(ctx context.Context, network, address string) (net.Conn, error) {
  63. return d.DialContext(ctx, "tcp", net.JoinHostPort(host, port))
  64. }
  65. }
  66. }
  67. }
  68. // GetClientTLSConfig returns a tls.Config for client use configured with the
  69. // sign certificate, and a new certificate pool with the sign root certificate.
  70. // The client certificate will automatically rotate before expiring.
  71. func (c *Client) GetClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  72. tlsConfig, _, err := c.getClientTLSConfig(ctx, sign, pk, options)
  73. if err != nil {
  74. return nil, err
  75. }
  76. return tlsConfig, nil
  77. }
  78. func (c *Client) getClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options []TLSOption) (*tls.Config, *http.Transport, error) {
  79. cert, err := TLSCertificate(sign, pk)
  80. if err != nil {
  81. return nil, nil, err
  82. }
  83. renewer, err := NewTLSRenewer(cert, nil)
  84. if err != nil {
  85. return nil, nil, err
  86. }
  87. tlsConfig := getDefaultTLSConfig(sign)
  88. // Note that with GetClientCertificate tlsConfig.Certificates is not used.
  89. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  90. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  91. tlsConfig.PreferServerCipherSuites = true
  92. // Apply options and initialize mutable tls.Config
  93. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  94. if err := tlsCtx.apply(options); err != nil {
  95. return nil, nil, err
  96. }
  97. // Update renew function with transport
  98. tr := getDefaultTransport(tlsConfig)
  99. // Use mutable tls.Config on renew
  100. tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck
  101. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  102. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  103. // Update client transport
  104. c.SetTransport(tr)
  105. // Start renewer
  106. renewer.RunContext(ctx)
  107. return tlsConfig, tr, nil
  108. }
  109. // GetServerTLSConfig returns a tls.Config for server use configured with the
  110. // sign certificate, and a new certificate pool with the sign root certificate.
  111. // The returned tls.Config will only verify the client certificate if provided.
  112. // The server certificate will automatically rotate before expiring.
  113. func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  114. cert, err := TLSCertificate(sign, pk)
  115. if err != nil {
  116. return nil, err
  117. }
  118. renewer, err := NewTLSRenewer(cert, nil)
  119. if err != nil {
  120. return nil, err
  121. }
  122. tlsConfig := getDefaultTLSConfig(sign)
  123. // Note that GetCertificate will only be called if the client supplies SNI
  124. // information or if tlsConfig.Certificates is empty.
  125. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  126. tlsConfig.GetCertificate = renewer.GetCertificate
  127. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  128. tlsConfig.PreferServerCipherSuites = true
  129. tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  130. // Apply options and initialize mutable tls.Config
  131. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  132. if err := tlsCtx.apply(options); err != nil {
  133. return nil, err
  134. }
  135. // GetConfigForClient allows seamless root and federated roots rotation.
  136. // If the return of the callback is not-nil, it will use the returned
  137. // tls.Config instead of the default one.
  138. tlsConfig.GetConfigForClient = c.buildGetConfigForClient(tlsCtx)
  139. // Update renew function with transport
  140. tr := getDefaultTransport(tlsConfig)
  141. // Use mutable tls.Config on renew
  142. tr.DialTLS = c.buildDialTLS(tlsCtx) // nolint:staticcheck
  143. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  144. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk)
  145. // Update client transport
  146. c.SetTransport(tr)
  147. // Start renewer
  148. renewer.RunContext(ctx)
  149. return tlsConfig, nil
  150. }
  151. // Transport returns an http.Transport configured to use the client certificate from the sign response.
  152. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*http.Transport, error) {
  153. _, tr, err := c.getClientTLSConfig(ctx, sign, pk, options)
  154. if err != nil {
  155. return nil, err
  156. }
  157. return tr, nil
  158. }
  159. // buildGetConfigForClient returns an implementation of GetConfigForClient
  160. // callback in tls.Config.
  161. //
  162. // If the implementation returns a nil tls.Config, the original Config will be
  163. // used, but if it's non-nil, the returned Config will be used to handle this
  164. // connection.
  165. func (c *Client) buildGetConfigForClient(ctx *TLSOptionCtx) func(*tls.ClientHelloInfo) (*tls.Config, error) {
  166. return func(*tls.ClientHelloInfo) (*tls.Config, error) {
  167. return ctx.mutableConfig.TLSConfig(), nil
  168. }
  169. }
  170. // buildDialTLS returns an implementation of DialTLS callback in http.Transport.
  171. func (c *Client) buildDialTLS(ctx *TLSOptionCtx) func(network, addr string) (net.Conn, error) {
  172. return func(network, addr string) (net.Conn, error) {
  173. return tls.DialWithDialer(getDefaultDialer(), network, addr, ctx.mutableConfig.TLSConfig())
  174. }
  175. }
  176. // buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport.
  177. // nolint:unused
  178. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) {
  179. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  180. d := getDefaultDialer()
  181. // TLS dialers do not support context, but we can use the context
  182. // deadline if it is set.
  183. if t, ok := ctx.Deadline(); ok {
  184. d.Deadline = t
  185. }
  186. return tls.DialWithDialer(d, network, addr, tlsCtx.mutableConfig.TLSConfig())
  187. }
  188. }
  189. // Certificate returns the server or client certificate from the sign response.
  190. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  191. if sign.ServerPEM.Certificate == nil {
  192. return nil, errors.New("ca: certificate does not exist")
  193. }
  194. return sign.ServerPEM.Certificate, nil
  195. }
  196. // IntermediateCertificate returns the CA intermediate certificate from the sign
  197. // response.
  198. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  199. if sign.CaPEM.Certificate == nil {
  200. return nil, errors.New("ca: certificate does not exist")
  201. }
  202. return sign.CaPEM.Certificate, nil
  203. }
  204. // RootCertificate returns the root certificate from the sign response.
  205. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  206. if sign == nil || sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  207. return nil, errors.New("ca: certificate does not exist")
  208. }
  209. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  210. if len(lastChain) == 0 {
  211. return nil, errors.New("ca: certificate does not exist")
  212. }
  213. return lastChain[len(lastChain)-1], nil
  214. }
  215. // TLSCertificate creates a new TLS certificate from the sign response and the
  216. // private key used.
  217. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  218. certPEM, err := getPEM(sign.ServerPEM)
  219. if err != nil {
  220. return nil, err
  221. }
  222. caPEM, err := getPEM(sign.CaPEM)
  223. if err != nil {
  224. return nil, err
  225. }
  226. keyPEM, err := getPEM(pk)
  227. if err != nil {
  228. return nil, err
  229. }
  230. chain := append(certPEM, caPEM...)
  231. cert, err := tls.X509KeyPair(chain, keyPEM)
  232. if err != nil {
  233. return nil, errors.Wrap(err, "error creating tls certificate")
  234. }
  235. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  236. if err != nil {
  237. return nil, errors.Wrap(err, "error parsing tls certificate")
  238. }
  239. cert.Leaf = leaf
  240. return &cert, nil
  241. }
  242. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  243. if sign.TLSOptions != nil {
  244. return sign.TLSOptions.TLSConfig()
  245. }
  246. return &tls.Config{
  247. MinVersion: tls.VersionTLS12,
  248. }
  249. }
  250. // getDefaultDialer returns a new dialer with the default configuration.
  251. func getDefaultDialer() *net.Dialer {
  252. return &net.Dialer{
  253. Timeout: 30 * time.Second,
  254. KeepAlive: 30 * time.Second,
  255. }
  256. }
  257. // getDefaultTransport returns an http.Transport with the same parameters than
  258. // http.DefaultTransport, but adds the given tls.Config and configures the
  259. // transport for HTTP/2.
  260. func getDefaultTransport(tlsConfig *tls.Config) *http.Transport {
  261. var dialContext func(ctx context.Context, network string, addr string) (net.Conn, error)
  262. if mTLSDialContext == nil {
  263. d := getDefaultDialer()
  264. dialContext = d.DialContext
  265. } else {
  266. dialContext = mTLSDialContext()
  267. }
  268. return &http.Transport{
  269. Proxy: http.ProxyFromEnvironment,
  270. DialContext: dialContext,
  271. ForceAttemptHTTP2: true,
  272. MaxIdleConns: 100,
  273. IdleConnTimeout: 90 * time.Second,
  274. TLSHandshakeTimeout: 10 * time.Second,
  275. ExpectContinueTimeout: 1 * time.Second,
  276. TLSClientConfig: tlsConfig,
  277. }
  278. }
  279. func getPEM(i interface{}) ([]byte, error) {
  280. block := new(pem.Block)
  281. switch i := i.(type) {
  282. case api.Certificate:
  283. block.Type = "CERTIFICATE"
  284. block.Bytes = i.Raw
  285. case *x509.Certificate:
  286. block.Type = "CERTIFICATE"
  287. block.Bytes = i.Raw
  288. case *rsa.PrivateKey:
  289. block.Type = "RSA PRIVATE KEY"
  290. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  291. case *ecdsa.PrivateKey:
  292. var err error
  293. block.Type = "EC PRIVATE KEY"
  294. block.Bytes, err = x509.MarshalECPrivateKey(i)
  295. if err != nil {
  296. return nil, errors.Wrap(err, "error marshaling private key")
  297. }
  298. case ed25519.PrivateKey:
  299. var err error
  300. block.Type = "PRIVATE KEY"
  301. block.Bytes, err = x509.MarshalPKCS8PrivateKey(i)
  302. if err != nil {
  303. return nil, errors.Wrap(err, "error marshaling private key")
  304. }
  305. default:
  306. return nil, errors.Errorf("unsupported key type %T", i)
  307. }
  308. return pem.EncodeToMemory(block), nil
  309. }
  310. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  311. return func() (*tls.Certificate, error) {
  312. // Get updated list of roots
  313. if err := ctx.applyRenew(); err != nil {
  314. return nil, err
  315. }
  316. // Get new certificate
  317. sign, err := client.Renew(tr)
  318. if err != nil {
  319. return nil, err
  320. }
  321. return TLSCertificate(sign, pk)
  322. }
  323. }