ca.go 6.3 KB

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