ca.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  1. package ca
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "log"
  6. "net/http"
  7. "github.com/go-chi/chi"
  8. "github.com/pkg/errors"
  9. "github.com/smallstep/certificates/api"
  10. "github.com/smallstep/certificates/authority"
  11. "github.com/smallstep/certificates/logging"
  12. "github.com/smallstep/certificates/monitoring"
  13. "github.com/smallstep/certificates/server"
  14. )
  15. type options struct {
  16. configFile string
  17. password []byte
  18. }
  19. func (o *options) apply(opts []Option) {
  20. for _, fn := range opts {
  21. fn(o)
  22. }
  23. }
  24. // Option is the type of options passed to the CA constructor.
  25. type Option func(o *options)
  26. // WithConfigFile sets the given name as the configuration file name in the CA
  27. // options.
  28. func WithConfigFile(name string) Option {
  29. return func(o *options) {
  30. o.configFile = name
  31. }
  32. }
  33. // WithPassword sets the given password as the configured password in the CA
  34. // options.
  35. func WithPassword(password []byte) Option {
  36. return func(o *options) {
  37. o.password = password
  38. }
  39. }
  40. // CA is the type used to build the complete certificate authority. It builds
  41. // the HTTP server, set ups the middlewares and the HTTP handlers.
  42. type CA struct {
  43. auth *authority.Authority
  44. config *authority.Config
  45. srv *server.Server
  46. opts *options
  47. renewer *TLSRenewer
  48. }
  49. // New creates and initializes the CA with the given configuration and options.
  50. func New(config *authority.Config, opts ...Option) (*CA, error) {
  51. ca := &CA{
  52. config: config,
  53. opts: new(options),
  54. }
  55. ca.opts.apply(opts)
  56. return ca.Init(config)
  57. }
  58. // Init initializes the CA with the given configuration.
  59. func (ca *CA) Init(config *authority.Config) (*CA, error) {
  60. if l := len(ca.opts.password); l > 0 {
  61. ca.config.Password = string(ca.opts.password)
  62. }
  63. auth, err := authority.New(config)
  64. if err != nil {
  65. return nil, err
  66. }
  67. tlsConfig, err := ca.getTLSConfig(auth)
  68. if err != nil {
  69. return nil, err
  70. }
  71. // Using chi as the main router
  72. mux := chi.NewRouter()
  73. handler := http.Handler(mux)
  74. // Add api endpoints in / and /1.0
  75. routerHandler := api.New(auth)
  76. routerHandler.Route(mux)
  77. mux.Route("/1.0", func(r chi.Router) {
  78. routerHandler.Route(r)
  79. })
  80. // Add monitoring if configured
  81. if len(config.Monitoring) > 0 {
  82. m, err := monitoring.New(config.Monitoring)
  83. if err != nil {
  84. return nil, err
  85. }
  86. handler = m.Middleware(handler)
  87. }
  88. // Add logger if configured
  89. if len(config.Logger) > 0 {
  90. logger, err := logging.New("ca", config.Logger)
  91. if err != nil {
  92. return nil, err
  93. }
  94. handler = logger.Middleware(handler)
  95. }
  96. ca.auth = auth
  97. ca.srv = server.New(config.Address, handler, tlsConfig)
  98. return ca, nil
  99. }
  100. // Run starts the CA calling to the server ListenAndServe method.
  101. func (ca *CA) Run() error {
  102. return ca.srv.ListenAndServe()
  103. }
  104. // Stop stops the CA calling to the server Shutdown method.
  105. func (ca *CA) Stop() error {
  106. ca.renewer.Stop()
  107. if err := ca.auth.Shutdown(); err != nil {
  108. log.Printf("error stopping ca.Authority: %+v\n", err)
  109. }
  110. return ca.srv.Shutdown()
  111. }
  112. // Reload reloads the configuration of the CA and calls to the server Reload
  113. // method.
  114. func (ca *CA) Reload() error {
  115. var hasDB bool
  116. if ca.config.DB != nil {
  117. hasDB = true
  118. }
  119. if ca.opts.configFile == "" {
  120. return errors.New("error reloading ca: configuration file is not set")
  121. }
  122. config, err := authority.LoadConfiguration(ca.opts.configFile)
  123. if err != nil {
  124. return errors.Wrap(err, "error reloading ca configuration")
  125. }
  126. logShutDown := func(ss ...string) {
  127. for _, s := range ss {
  128. log.Println(s)
  129. }
  130. log.Println("Continuing to serve requests may result in inconsistent state. Shutting Down ...")
  131. }
  132. logContinue := func(reason string) {
  133. log.Println(reason)
  134. log.Println("Continuing to run with the original configuration.")
  135. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  136. }
  137. // Shut down the old authority (shut down the database). If New or Reload
  138. // fails then the CA will continue to run but the database will have been
  139. // shutdown, which will cause errors.
  140. if err := ca.auth.Shutdown(); err != nil {
  141. if hasDB {
  142. logShutDown("Attempt to shut down the ca.Authority has failed.")
  143. return ca.Stop()
  144. }
  145. logContinue("Reload failed because the ca.Authority could not be shut down.")
  146. return err
  147. }
  148. newCA, err := New(config, WithPassword(ca.opts.password), WithConfigFile(ca.opts.configFile))
  149. if err != nil {
  150. if hasDB {
  151. logShutDown("Attempt to initialize a CA with the new configuration has failed.",
  152. "The database has already been shutdown.")
  153. return ca.Stop()
  154. }
  155. logContinue("Reload failed because the CA with new configuration could " +
  156. "not be initialized.")
  157. return errors.Wrap(err, "error reloading ca")
  158. }
  159. if err = ca.srv.Reload(newCA.srv); err != nil {
  160. if hasDB {
  161. logShutDown("Attempt to replace the old CA server has failed.",
  162. "The database has already been shutdown.")
  163. return ca.Stop()
  164. }
  165. logContinue("Reload failed because server could not be replaced.")
  166. return errors.Wrap(err, "error reloading server")
  167. }
  168. // 1. Stop previous renewer
  169. // 2. Replace ca properties
  170. // Do not replace ca.srv
  171. ca.renewer.Stop()
  172. ca.auth = newCA.auth
  173. ca.config = newCA.config
  174. ca.opts = newCA.opts
  175. ca.renewer = newCA.renewer
  176. return nil
  177. }
  178. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  179. // server certificate.
  180. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  181. // Create initial TLS certificate
  182. tlsCrt, err := auth.GetTLSCertificate()
  183. if err != nil {
  184. return nil, err
  185. }
  186. // Start tls renewer with the new certificate.
  187. // If a renewer was started, attempt to stop it before.
  188. if ca.renewer != nil {
  189. ca.renewer.Stop()
  190. }
  191. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  192. if err != nil {
  193. return nil, err
  194. }
  195. ca.renewer.Run()
  196. var tlsConfig *tls.Config
  197. if ca.config.TLS != nil {
  198. tlsConfig = ca.config.TLS.TLSConfig()
  199. } else {
  200. tlsConfig = &tls.Config{
  201. MinVersion: tls.VersionTLS12,
  202. }
  203. }
  204. certPool := x509.NewCertPool()
  205. for _, crt := range auth.GetRootCertificates() {
  206. certPool.AddCert(crt)
  207. }
  208. // GetCertificate will only be called if the client supplies SNI
  209. // information or if tlsConfig.Certificates is empty.
  210. // When client requests are made using an IP address (as opposed to a domain
  211. // name) the server does not receive any SNI and may fallback to using the
  212. // first entry in the Certificates attribute; by setting the attribute to
  213. // empty we are implicitly forcing GetCertificate to be the only mechanism
  214. // by which the server can find it's own leaf Certificate.
  215. tlsConfig.Certificates = []tls.Certificate{}
  216. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  217. // Add support for mutual tls to renew certificates
  218. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  219. tlsConfig.ClientCAs = certPool
  220. // Use server's most preferred ciphersuite
  221. tlsConfig.PreferServerCipherSuites = true
  222. return tlsConfig, nil
  223. }