tls.go 13 KB

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