tls.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392
  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: getDefaultDialer(),
  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.Transport, 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. //nolint:staticcheck // Use mutable tls.Config on renew
  125. tr.DialTLS = c.buildDialTLS(tlsCtx)
  126. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  127. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk) //nolint:contextcheck // deeply nested context
  128. // Update client transport
  129. c.SetTransport(tr)
  130. // Start renewer
  131. renewer.RunContext(ctx)
  132. return tlsConfig, tr, nil
  133. }
  134. // GetServerTLSConfig returns a tls.Config for server use configured with the
  135. // sign certificate, and a new certificate pool with the sign root certificate.
  136. // The returned tls.Config will only verify the client certificate if provided.
  137. // The server certificate will automatically rotate before expiring.
  138. func (c *Client) GetServerTLSConfig(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*tls.Config, error) {
  139. cert, err := TLSCertificate(sign, pk)
  140. if err != nil {
  141. return nil, err
  142. }
  143. renewer, err := NewTLSRenewer(cert, nil)
  144. if err != nil {
  145. return nil, err
  146. }
  147. tlsConfig := getDefaultTLSConfig(sign)
  148. // Note that GetCertificate will only be called if the client supplies SNI
  149. // information or if tlsConfig.Certificates is empty.
  150. // Without tlsConfig.Certificates there's not need to use tlsConfig.BuildNameToCertificate()
  151. tlsConfig.GetCertificate = renewer.GetCertificate
  152. tlsConfig.GetClientCertificate = renewer.GetClientCertificate
  153. tlsConfig.ClientAuth = tls.RequireAndVerifyClientCert
  154. // Apply options and initialize mutable tls.Config
  155. tlsCtx := newTLSOptionCtx(c, tlsConfig, sign)
  156. if err := tlsCtx.apply(options); err != nil {
  157. return nil, err
  158. }
  159. // GetConfigForClient allows seamless root and federated roots rotation.
  160. // If the return of the callback is not-nil, it will use the returned
  161. // tls.Config instead of the default one.
  162. tlsConfig.GetConfigForClient = c.buildGetConfigForClient(tlsCtx)
  163. // Update renew function with transport
  164. tr := getDefaultTransport(tlsConfig)
  165. //nolint:staticcheck // Use mutable tls.Config on renew
  166. tr.DialTLS = c.buildDialTLS(tlsCtx)
  167. // tr.DialTLSContext = c.buildDialTLSContext(tlsCtx)
  168. renewer.RenewCertificate = getRenewFunc(tlsCtx, c, tr, pk) //nolint:contextcheck // deeply nested context
  169. // Update client transport
  170. c.SetTransport(tr)
  171. // Start renewer
  172. renewer.RunContext(ctx)
  173. return tlsConfig, nil
  174. }
  175. // Transport returns an http.Transport configured to use the client certificate from the sign response.
  176. func (c *Client) Transport(ctx context.Context, sign *api.SignResponse, pk crypto.PrivateKey, options ...TLSOption) (*http.Transport, 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. // buildDialTLS returns an implementation of DialTLS callback in http.Transport.
  195. func (c *Client) buildDialTLS(ctx *TLSOptionCtx) func(network, addr string) (net.Conn, error) {
  196. return func(network, addr string) (net.Conn, error) {
  197. return tls.DialWithDialer(getDefaultDialer(), network, addr, ctx.mutableConfig.TLSConfig())
  198. }
  199. }
  200. //nolint:unused // buildDialTLSContext returns an implementation of DialTLSContext callback in http.Transport.
  201. func (c *Client) buildDialTLSContext(tlsCtx *TLSOptionCtx) func(ctx context.Context, network, addr string) (net.Conn, error) {
  202. return func(ctx context.Context, network, addr string) (net.Conn, error) {
  203. d := getDefaultDialer()
  204. // TLS dialers do not support context, but we can use the context
  205. // deadline if it is set.
  206. if t, ok := ctx.Deadline(); ok {
  207. d.Deadline = t
  208. }
  209. return tls.DialWithDialer(d, network, addr, tlsCtx.mutableConfig.TLSConfig())
  210. }
  211. }
  212. // Certificate returns the server or client certificate from the sign response.
  213. func Certificate(sign *api.SignResponse) (*x509.Certificate, error) {
  214. if sign.ServerPEM.Certificate == nil {
  215. return nil, errors.New("ca: certificate does not exist")
  216. }
  217. return sign.ServerPEM.Certificate, nil
  218. }
  219. // IntermediateCertificate returns the CA intermediate certificate from the sign
  220. // response.
  221. func IntermediateCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  222. if sign.CaPEM.Certificate == nil {
  223. return nil, errors.New("ca: certificate does not exist")
  224. }
  225. return sign.CaPEM.Certificate, nil
  226. }
  227. // RootCertificate returns the root certificate from the sign response.
  228. func RootCertificate(sign *api.SignResponse) (*x509.Certificate, error) {
  229. if sign == nil || sign.TLS == nil || len(sign.TLS.VerifiedChains) == 0 {
  230. return nil, errors.New("ca: certificate does not exist")
  231. }
  232. lastChain := sign.TLS.VerifiedChains[len(sign.TLS.VerifiedChains)-1]
  233. if len(lastChain) == 0 {
  234. return nil, errors.New("ca: certificate does not exist")
  235. }
  236. return lastChain[len(lastChain)-1], nil
  237. }
  238. // TLSCertificate creates a new TLS certificate from the sign response and the
  239. // private key used.
  240. func TLSCertificate(sign *api.SignResponse, pk crypto.PrivateKey) (*tls.Certificate, error) {
  241. certPEM, err := getPEM(sign.ServerPEM)
  242. if err != nil {
  243. return nil, err
  244. }
  245. caPEM, err := getPEM(sign.CaPEM)
  246. if err != nil {
  247. return nil, err
  248. }
  249. keyPEM, err := getPEM(pk)
  250. if err != nil {
  251. return nil, err
  252. }
  253. //nolint:gocritic // using a new variable for clarity
  254. chain := append(certPEM, caPEM...)
  255. cert, err := tls.X509KeyPair(chain, keyPEM)
  256. if err != nil {
  257. return nil, errors.Wrap(err, "error creating tls certificate")
  258. }
  259. leaf, err := x509.ParseCertificate(cert.Certificate[0])
  260. if err != nil {
  261. return nil, errors.Wrap(err, "error parsing tls certificate")
  262. }
  263. cert.Leaf = leaf
  264. return &cert, nil
  265. }
  266. func getDefaultTLSConfig(sign *api.SignResponse) *tls.Config {
  267. if sign.TLSOptions != nil {
  268. return sign.TLSOptions.TLSConfig()
  269. }
  270. return &tls.Config{
  271. MinVersion: tls.VersionTLS12,
  272. }
  273. }
  274. // getDefaultDialer returns a new dialer with the default configuration.
  275. func getDefaultDialer() *net.Dialer {
  276. // With the KeepAlive parameter set to 0, it will be use Golang's default.
  277. return &net.Dialer{
  278. Timeout: 30 * time.Second,
  279. LocalAddr: localAddr,
  280. }
  281. }
  282. // getDefaultTransport returns an http.Transport with the same parameters than
  283. // http.DefaultTransport, but adds the given tls.Config and configures the
  284. // transport for HTTP/2.
  285. func getDefaultTransport(tlsConfig *tls.Config) *http.Transport {
  286. var dialContext func(ctx context.Context, network string, addr string) (net.Conn, error)
  287. switch {
  288. case runtime.GOOS == "js" && runtime.GOARCH == "wasm":
  289. // when running in js/wasm and using the default dialer context all requests
  290. // performed by the CA client resulted in a "protocol not supported" error.
  291. // By setting the dial context to nil requests will be handled by the browser
  292. // fetch API instead. Currently this will always set the dial context to nil,
  293. // but we could implement some additional logic similar to what's found in
  294. // https://github.com/golang/go/pull/46923/files to support a different dial
  295. // context if it is available, required and expected to work.
  296. dialContext = nil
  297. case mTLSDialContext == nil:
  298. d := getDefaultDialer()
  299. dialContext = d.DialContext
  300. default:
  301. dialContext = mTLSDialContext()
  302. }
  303. return &http.Transport{
  304. Proxy: http.ProxyFromEnvironment,
  305. DialContext: dialContext,
  306. ForceAttemptHTTP2: true,
  307. MaxIdleConns: 100,
  308. IdleConnTimeout: 90 * time.Second,
  309. TLSHandshakeTimeout: 10 * time.Second,
  310. ExpectContinueTimeout: 1 * time.Second,
  311. TLSClientConfig: tlsConfig,
  312. }
  313. }
  314. func getPEM(i interface{}) ([]byte, error) {
  315. block := new(pem.Block)
  316. switch i := i.(type) {
  317. case api.Certificate:
  318. block.Type = "CERTIFICATE"
  319. block.Bytes = i.Raw
  320. case *x509.Certificate:
  321. block.Type = "CERTIFICATE"
  322. block.Bytes = i.Raw
  323. case *rsa.PrivateKey:
  324. block.Type = "RSA PRIVATE KEY"
  325. block.Bytes = x509.MarshalPKCS1PrivateKey(i)
  326. case *ecdsa.PrivateKey:
  327. var err error
  328. block.Type = "EC PRIVATE KEY"
  329. block.Bytes, err = x509.MarshalECPrivateKey(i)
  330. if err != nil {
  331. return nil, errors.Wrap(err, "error marshaling private key")
  332. }
  333. case ed25519.PrivateKey:
  334. var err error
  335. block.Type = "PRIVATE KEY"
  336. block.Bytes, err = x509.MarshalPKCS8PrivateKey(i)
  337. if err != nil {
  338. return nil, errors.Wrap(err, "error marshaling private key")
  339. }
  340. default:
  341. return nil, errors.Errorf("unsupported key type %T", i)
  342. }
  343. return pem.EncodeToMemory(block), nil
  344. }
  345. func getRenewFunc(ctx *TLSOptionCtx, client *Client, tr *http.Transport, pk crypto.PrivateKey) RenewFunc {
  346. return func() (*tls.Certificate, error) {
  347. // Get updated list of roots
  348. if err := ctx.applyRenew(); err != nil {
  349. return nil, err
  350. }
  351. // Get new certificate
  352. sign, err := client.Renew(tr)
  353. if err != nil {
  354. return nil, err
  355. }
  356. return TLSCertificate(sign, pk)
  357. }
  358. }