bootstrap.go 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. package ca
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/tls"
  6. "net"
  7. "net/http"
  8. "strings"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/api"
  11. "go.step.sm/crypto/jose"
  12. )
  13. type tokenClaims struct {
  14. SHA string `json:"sha"`
  15. jose.Claims
  16. }
  17. // Bootstrap is a helper function that initializes a client with the
  18. // configuration in the bootstrap token.
  19. func Bootstrap(token string) (*Client, error) {
  20. tok, err := jose.ParseSigned(token)
  21. if err != nil {
  22. return nil, errors.Wrap(err, "error parsing token")
  23. }
  24. var claims tokenClaims
  25. if err := tok.UnsafeClaimsWithoutVerification(&claims); err != nil {
  26. return nil, errors.Wrap(err, "error parsing token")
  27. }
  28. // Validate bootstrap token
  29. switch {
  30. case claims.SHA == "":
  31. return nil, errors.New("invalid bootstrap token: sha claim is not present")
  32. case !strings.HasPrefix(strings.ToLower(claims.Audience[0]), "http"):
  33. return nil, errors.New("invalid bootstrap token: aud claim is not a url")
  34. }
  35. return NewClient(claims.Audience[0], WithRootSHA256(claims.SHA))
  36. }
  37. // BootstrapClient is a helper function that using the given bootstrap token
  38. // return an http.Client configured with a Transport prepared to do TLS
  39. // connections using the client certificate returned by the certificate
  40. // authority. By default the server will kick off a routine that will renew the
  41. // certificate after 2/3rd of the certificate's lifetime has expired.
  42. //
  43. // Usage:
  44. //
  45. // // Default example with certificate rotation.
  46. // client, err := ca.BootstrapClient(ctx.Background(), token)
  47. //
  48. // // Example canceling automatic certificate rotation.
  49. // ctx, cancel := context.WithCancel(context.Background())
  50. // defer cancel()
  51. // client, err := ca.BootstrapClient(ctx, token)
  52. // if err != nil {
  53. // return err
  54. // }
  55. // resp, err := client.Get("https://internal.smallstep.com")
  56. func BootstrapClient(ctx context.Context, token string, options ...TLSOption) (*http.Client, error) {
  57. b, err := createBootstrap(token)
  58. if err != nil {
  59. return nil, err
  60. }
  61. // Make sure the tlsConfig has all supported roots on RootCAs.
  62. //
  63. // The roots request is only supported if identity certificates are not
  64. // required. In all cases the current root is also added after applying all
  65. // options too.
  66. if !b.RequireClientAuth {
  67. options = append(options, AddRootsToRootCAs())
  68. }
  69. transport, err := b.Client.Transport(ctx, b.SignResponse, b.PrivateKey, options...)
  70. if err != nil {
  71. return nil, err
  72. }
  73. return &http.Client{
  74. Transport: transport,
  75. }, nil
  76. }
  77. // BootstrapServer is a helper function that using the given token returns the
  78. // given http.Server configured with a TLS certificate signed by the Certificate
  79. // Authority. By default the server will kick off a routine that will renew the
  80. // certificate after 2/3rd of the certificate's lifetime has expired.
  81. //
  82. // Without any extra option the server will be configured for mTLS, it will
  83. // require and verify clients certificates, but options can be used to drop this
  84. // requirement, the most common will be only verify the certs if given with
  85. // ca.VerifyClientCertIfGiven(), or add extra CAs with
  86. // ca.AddClientCA(*x509.Certificate).
  87. //
  88. // Usage:
  89. //
  90. // // Default example with certificate rotation.
  91. // srv, err := ca.BootstrapServer(context.Background(), token, &http.Server{
  92. // Addr: ":443",
  93. // Handler: handler,
  94. // })
  95. //
  96. // // Example canceling automatic certificate rotation.
  97. // ctx, cancel := context.WithCancel(context.Background())
  98. // defer cancel()
  99. // srv, err := ca.BootstrapServer(ctx, token, &http.Server{
  100. // Addr: ":443",
  101. // Handler: handler,
  102. // })
  103. // if err != nil {
  104. // return err
  105. // }
  106. // srv.ListenAndServeTLS("", "")
  107. func BootstrapServer(ctx context.Context, token string, base *http.Server, options ...TLSOption) (*http.Server, error) {
  108. if base.TLSConfig != nil {
  109. return nil, errors.New("server TLSConfig is already set")
  110. }
  111. b, err := createBootstrap(token)
  112. if err != nil {
  113. return nil, err
  114. }
  115. // Make sure the tlsConfig has all supported roots on RootCAs.
  116. //
  117. // The roots request is only supported if identity certificates are not
  118. // required. In all cases the current root is also added after applying all
  119. // options too.
  120. if !b.RequireClientAuth {
  121. options = append(options, AddRootsToCAs())
  122. }
  123. tlsConfig, err := b.Client.GetServerTLSConfig(ctx, b.SignResponse, b.PrivateKey, options...)
  124. if err != nil {
  125. return nil, err
  126. }
  127. base.TLSConfig = tlsConfig
  128. return base, nil
  129. }
  130. // BootstrapListener is a helper function that using the given token returns a
  131. // TLS listener which accepts connections from an inner listener and wraps each
  132. // connection with Server.
  133. //
  134. // Without any extra option the server will be configured for mTLS, it will
  135. // require and verify clients certificates, but options can be used to drop this
  136. // requirement, the most common will be only verify the certs if given with
  137. // ca.VerifyClientCertIfGiven(), or add extra CAs with
  138. // ca.AddClientCA(*x509.Certificate).
  139. //
  140. // Usage:
  141. //
  142. // inner, err := net.Listen("tcp", ":443")
  143. // if err != nil {
  144. // return nil
  145. // }
  146. // ctx, cancel := context.WithCancel(context.Background())
  147. // defer cancel()
  148. // lis, err := ca.BootstrapListener(ctx, token, inner)
  149. // if err != nil {
  150. // return err
  151. // }
  152. // srv := grpc.NewServer()
  153. // ... // register services
  154. // srv.Serve(lis)
  155. func BootstrapListener(ctx context.Context, token string, inner net.Listener, options ...TLSOption) (net.Listener, error) {
  156. b, err := createBootstrap(token)
  157. if err != nil {
  158. return nil, err
  159. }
  160. // Make sure the tlsConfig has all supported roots on RootCAs.
  161. //
  162. // The roots request is only supported if identity certificates are not
  163. // required. In all cases the current root is also added after applying all
  164. // options too.
  165. if !b.RequireClientAuth {
  166. options = append(options, AddRootsToCAs())
  167. }
  168. tlsConfig, err := b.Client.GetServerTLSConfig(ctx, b.SignResponse, b.PrivateKey, options...)
  169. if err != nil {
  170. return nil, err
  171. }
  172. return tls.NewListener(inner, tlsConfig), nil
  173. }
  174. type bootstrap struct {
  175. Client *Client
  176. RequireClientAuth bool
  177. SignResponse *api.SignResponse
  178. PrivateKey crypto.PrivateKey
  179. }
  180. func createBootstrap(token string) (*bootstrap, error) {
  181. client, err := Bootstrap(token)
  182. if err != nil {
  183. return nil, err
  184. }
  185. version, err := client.Version()
  186. if err != nil {
  187. return nil, err
  188. }
  189. req, pk, err := CreateSignRequest(token)
  190. if err != nil {
  191. return nil, err
  192. }
  193. sign, err := client.Sign(req)
  194. if err != nil {
  195. return nil, err
  196. }
  197. return &bootstrap{
  198. Client: client,
  199. RequireClientAuth: version.RequireClientAuthentication,
  200. SignResponse: sign,
  201. PrivateKey: pk,
  202. }, nil
  203. }