4
0

tls.go 13 KB

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