4
0

tls.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. package ca
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "net"
  8. "net/http"
  9. "os"
  10. "runtime"
  11. "time"
  12. "github.com/pkg/errors"
  13. "github.com/smallstep/certificates/api"
  14. "github.com/smallstep/certificates/ca/identity"
  15. "github.com/smallstep/certificates/internal/cryptoutil"
  16. )
  17. // mTLSDialContext will hold the dial context function to use in
  18. // getDefaultTransport.
  19. var mTLSDialContext func() func(ctx context.Context, network, address string) (net.Conn, error)
  20. // localAddr is the local address to use when dialing an address. This address
  21. // is defined by the environment variable STEP_CLIENT_ADDR.
  22. var localAddr net.Addr
  23. func init() {
  24. // STEP_TLS_TUNNEL is an environment variable that can be set to do an TLS
  25. // over (m)TLS tunnel to step-ca using identity-like credentials. The value
  26. // is a path to a json file with the tunnel host, certificate, key and root
  27. // used to create the (m)TLS tunnel.
  28. //
  29. // The configuration should look like:
  30. // {
  31. // "type": "tTLS",
  32. // "host": "tunnel.example.com:443"
  33. // "crt": "/path/to/tunnel.crt",
  34. // "key": "/path/to/tunnel.key",
  35. // "root": "/path/to/tunnel-root.crt"
  36. // }
  37. //
  38. // This feature is EXPERIMENTAL and might change at any time.
  39. if path := os.Getenv("STEP_TLS_TUNNEL"); path != "" {
  40. id, err := identity.LoadIdentity(path)
  41. if err != nil {
  42. panic(err)
  43. }
  44. if err := id.Validate(); err != nil {
  45. panic(err)
  46. }
  47. host, port, err := net.SplitHostPort(id.Host)
  48. if err != nil {
  49. panic(err)
  50. }
  51. pool, err := id.GetCertPool()
  52. if err != nil {
  53. panic(err)
  54. }
  55. mTLSDialContext = func() func(ctx context.Context, network, address string) (net.Conn, error) {
  56. d := &tls.Dialer{
  57. NetDialer: createDefaultDialer(),
  58. Config: &tls.Config{
  59. MinVersion: tls.VersionTLS12,
  60. RootCAs: pool,
  61. GetClientCertificate: id.GetClientCertificateFunc(),
  62. },
  63. }
  64. return func(ctx context.Context, _, _ string) (net.Conn, error) {
  65. return d.DialContext(ctx, "tcp", net.JoinHostPort(host, port))
  66. }
  67. }
  68. }
  69. // STEP_CLIENT_ADDR is an environment variable that can be set to define the
  70. // local address to use when dialing an address. This can be useful when
  71. // step is run behind a CIDR-based ACL.
  72. //
  73. // STEP_CLIENT_ADDR can be set to an IP ("127.0.0.1", "[::1]"), a hostname
  74. // ("localhost"), or a host:port ("[::1]:0"). If the port is set to
  75. // something other than ":0" and the dialer is created multiple times it
  76. // will fail with an "address already in use" error.
  77. //
  78. // See https://github.com/smallstep/cli/issues/730
  79. if v := os.Getenv("STEP_CLIENT_ADDR"); v != "" {
  80. _, _, err := net.SplitHostPort(v)
  81. if err != nil {
  82. // assuming that the error is a missing port, if it's not it will
  83. // panic below.
  84. v += ":0"
  85. }
  86. localAddr, err = net.ResolveTCPAddr("tcp", v)
  87. if err != nil {
  88. panic(err)
  89. }
  90. }
  91. }
  92. // GetClientTLSConfig returns a tls.Config for client use configured with the
  93. // sign certificate, and a new certificate pool with the sign root certificate.
  94. // The client certificate will automatically rotate before expiring.
  95. func (c *Client) GetClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  96. tlsConfig, _, err := c.getClientTLSConfig(ctx, sign, pk, options)
  97. if err != nil {
  98. return nil, err
  99. }
  100. return tlsConfig, nil
  101. }
  102. func (c *Client) getClientTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options []TLSOption) (*tls.Config, http.RoundTripper, error) {
  103. cert, err := TLSCertificate(sign, pk)
  104. if err != nil {
  105. return nil, nil, err
  106. }
  107. renewer, err := NewTLSRenewer(cert, nil)
  108. if err != nil {
  109. return nil, nil, err
  110. }
  111. tlsConfig := getDefaultTLSConfig(sign)
  112. // Note that with GetClientCertificate tlsConfig.Certificates is not used.
  113. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  114. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  115. // Apply options and initialize mutable tls.Config
  116. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  117. if err := tlsCtx.apply(options); err != nil {
  118. return nil, nil, err
  119. }
  120. tr := getDefaultTransport(tlsConfig)
  121. tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  122. // Add decorator if available, and use the resulting [http.RoundTripper]
  123. // going forward
  124. rt := decorateRoundTripper(tr, c.transportDecorator)
  125. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, rt, pk) //nolint:contextcheck // deeply nested context
  126. // Update client transport
  127. c.SetTransport(rt)
  128. // Start renewer
  129. renewer.RunContext(ctx)
  130. return tlsConfig, rt, nil
  131. }
  132. // GetServerTLSConfig returns a tls.Config for server use configured with the
  133. // sign certificate, and a new certificate pool with the sign root certificate.
  134. // The returned tls.Config will only verify the client certificate if provided.
  135. // The server certificate will automatically rotate before expiring.
  136. func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  137. cert, err := TLSCertificate(sign, pk)
  138. if err != nil {
  139. return nil, err
  140. }
  141. renewer, err := NewTLSRenewer(cert, nil)
  142. if err != nil {
  143. return nil, err
  144. }
  145. tlsConfig := getDefaultTLSConfig(sign)
  146. // Note that GetCertificate will only be called if the client supplies SNI
  147. // information or if tlsConfig.Certificates is empty.
  148. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  149. tlsConfig.GetCertificate = renewer.GetCertificate
  150. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  151. tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  152. // Apply options and initialize mutable tls.Config
  153. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  154. if err := tlsCtx.apply(options); err != nil {
  155. return nil, err
  156. }
  157. // GetConfigForClient allows seamless root and federated roots rotation.
  158. // If the return of the callback is not-nil, it will use the returned
  159. // tls.Config instead of the default one.
  160. tlsConfig.GetConfigForClient = c.buildGetConfigForClient(tlsCtx)
  161. // Update renew function with transport
  162. tr := getDefaultTransport(tlsConfig)
  163. tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  164. // Add decorator if available, and use the resulting [http.RoundTripper]
  165. // going forward
  166. rt := decorateRoundTripper(tr, c.transportDecorator)
  167. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, rt, pk) //nolint:contextcheck // deeply nested context
  168. // Update client transport
  169. c.SetTransport(rt)
  170. // Start renewer
  171. renewer.RunContext(ctx)
  172. return tlsConfig, nil
  173. }
  174. // Transport returns an [http.RoundTripper] configured to use the client
  175. // certificate from the sign response.
  176. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (http.RoundTripper, error) {
  177. _, tr, err := c.getClientTLSConfig(ctx, sign, pk, options)
  178. if err != nil {
  179. return nil, err
  180. }
  181. return tr, nil
  182. }
  183. // buildGetConfigForClient returns an implementation of GetConfigForClient
  184. // callback in tls.Config.
  185. //
  186. // If the implementation returns a nil tls.Config, the original Config will be
  187. // used, but if it's non-nil, the returned Config will be used to handle this
  188. // connection.
  189. func (c *Client) buildGetConfigForClient(ctx *TLSOptionCtx) func(*tls.ClientHelloInfo) (*tls.Config, error) {
  190. return func(*tls.ClientHelloInfo) (*tls.Config, error) {
  191. return ctx.mutableConfig.TLSConfig(), nil
  192. }
  193. }
  194. // buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport.
  195. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) {
  196. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  197. d := createDefaultDialer()
  198. // TLS dialers do not support context, but we can use the context
  199. // deadline if it is set.
  200. if t, ok := ctx.Deadline(); ok {
  201. d.Deadline = t
  202. }
  203. return tls.DialWithDialer(d, network, addr, tlsCtx.mutableConfig.TLSConfig())
  204. }
  205. }
  206. // Certificate returns the server or client certificate from the sign response.
  207. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  208. if sign.ServerPEM.Certificate == nil {
  209. return nil, errors.New("ca: certificate does not exist")
  210. }
  211. return sign.ServerPEM.Certificate, nil
  212. }
  213. // IntermediateCertificate returns the CA intermediate certificate from the sign
  214. // response.
  215. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  216. if sign.CaPEM.Certificate == nil {
  217. return nil, errors.New("ca: certificate does not exist")
  218. }
  219. return sign.CaPEM.Certificate, nil
  220. }
  221. // RootCertificate returns the root certificate from the sign response.
  222. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  223. if sign == nil || sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  224. return nil, errors.New("ca: certificate does not exist")
  225. }
  226. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  227. if len(lastChain) == 0 {
  228. return nil, errors.New("ca: certificate does not exist")
  229. }
  230. return lastChain[len(lastChain)-1], nil
  231. }
  232. // TLSCertificate creates a new TLS certificate from the sign response and the
  233. // private key used.
  234. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  235. certPEM, err := cryptoutil.PEMEncode(sign.ServerPEM.Certificate)
  236. if err != nil {
  237. return nil, err
  238. }
  239. caPEM, err := cryptoutil.PEMEncode(sign.CaPEM.Certificate)
  240. if err != nil {
  241. return nil, err
  242. }
  243. keyPEM, err := cryptoutil.PEMEncode(pk)
  244. if err != nil {
  245. return nil, err
  246. }
  247. //nolint:gocritic // using a new variable for clarity
  248. chain := append(certPEM, caPEM...)
  249. cert, err := tls.X509KeyPair(chain, keyPEM)
  250. if err != nil {
  251. return nil, errors.Wrap(err, "error creating tls certificate")
  252. }
  253. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  254. if err != nil {
  255. return nil, errors.Wrap(err, "error parsing tls certificate")
  256. }
  257. cert.Leaf = leaf
  258. return &cert, nil
  259. }
  260. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  261. if sign.TLSOptions != nil {
  262. return sign.TLSOptions.TLSConfig()
  263. }
  264. return &tls.Config{
  265. MinVersion: tls.VersionTLS12,
  266. }
  267. }
  268. // createDefaultDialer returns a new dialer with the default configuration.
  269. func createDefaultDialer() *net.Dialer {
  270. // With the KeepAlive parameter set to 0, it will be use Golang's default.
  271. return &net.Dialer{
  272. Timeout: 30 * time.Second,
  273. LocalAddr: localAddr,
  274. }
  275. }
  276. // getDefaultTransport returns an http.Transport with the same parameters than
  277. // http.DefaultTransport, but adds the given tls.Config and configures the
  278. // transport for HTTP/2.
  279. func getDefaultTransport(tlsConfig *tls.Config) *http.Transport {
  280. var dialContext func(ctx context.Context, network string, addr string) (net.Conn, error)
  281. switch {
  282. case runtime.GOOS == "js" && runtime.GOARCH == "wasm":
  283. // when running in js/wasm and using the default dialer context all requests
  284. // performed by the CA client resulted in a "protocol not supported" error.
  285. // By setting the dial context to nil requests will be handled by the browser
  286. // fetch API instead. Currently this will always set the dial context to nil,
  287. // but we could implement some additional logic similar to what's found in
  288. // https://github.com/golang/go/pull/46923/files to support a different dial
  289. // context if it is available, required and expected to work.
  290. dialContext = nil
  291. case mTLSDialContext == nil:
  292. d := createDefaultDialer()
  293. dialContext = d.DialContext
  294. default:
  295. dialContext = mTLSDialContext()
  296. }
  297. return &http.Transport{
  298. Proxy: http.ProxyFromEnvironment,
  299. DialContext: dialContext,
  300. ForceAttemptHTTP2: true,
  301. MaxIdleConns: 100,
  302. IdleConnTimeout: 90 * time.Second,
  303. TLSHandshakeTimeout: 10 * time.Second,
  304. ExpectContinueTimeout: 1 * time.Second,
  305. TLSClientConfig: tlsConfig,
  306. }
  307. }
  308. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr http.RoundTripper, pk crypto.PrivateKey) RenewFunc {
  309. return func() (*tls.Certificate, error) {
  310. // Close connections in keep-alive state
  311. defer client.CloseIdleConnections()
  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. }