tls.go 13 KB

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