tls.go 12 KB

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