ca.go 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. package ca
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "reflect"
  10. "github.com/go-chi/chi"
  11. "github.com/pkg/errors"
  12. acmeAPI "github.com/smallstep/certificates/acme/api"
  13. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  14. "github.com/smallstep/certificates/api"
  15. "github.com/smallstep/certificates/authority"
  16. "github.com/smallstep/certificates/db"
  17. "github.com/smallstep/certificates/logging"
  18. "github.com/smallstep/certificates/monitoring"
  19. "github.com/smallstep/certificates/server"
  20. "github.com/smallstep/nosql"
  21. )
  22. type options struct {
  23. configFile string
  24. password []byte
  25. database db.AuthDB
  26. }
  27. func (o *options) apply(opts []Option) {
  28. for _, fn := range opts {
  29. fn(o)
  30. }
  31. }
  32. // Option is the type of options passed to the CA constructor.
  33. type Option func(o *options)
  34. // WithConfigFile sets the given name as the configuration file name in the CA
  35. // options.
  36. func WithConfigFile(name string) Option {
  37. return func(o *options) {
  38. o.configFile = name
  39. }
  40. }
  41. // WithPassword sets the given password as the configured password in the CA
  42. // options.
  43. func WithPassword(password []byte) Option {
  44. return func(o *options) {
  45. o.password = password
  46. }
  47. }
  48. // WithDatabase sets the given authority database to the CA options.
  49. func WithDatabase(db db.AuthDB) Option {
  50. return func(o *options) {
  51. o.database = db
  52. }
  53. }
  54. // CA is the type used to build the complete certificate authority. It builds
  55. // the HTTP server, set ups the middlewares and the HTTP handlers.
  56. type CA struct {
  57. auth *authority.Authority
  58. config *authority.Config
  59. srv *server.Server
  60. opts *options
  61. renewer *TLSRenewer
  62. }
  63. // New creates and initializes the CA with the given configuration and options.
  64. func New(config *authority.Config, opts ...Option) (*CA, error) {
  65. ca := &CA{
  66. config: config,
  67. opts: new(options),
  68. }
  69. ca.opts.apply(opts)
  70. return ca.Init(config)
  71. }
  72. // Init initializes the CA with the given configuration.
  73. func (ca *CA) Init(config *authority.Config) (*CA, error) {
  74. if l := len(ca.opts.password); l > 0 {
  75. ca.config.Password = string(ca.opts.password)
  76. }
  77. var opts []authority.Option
  78. if ca.opts.database != nil {
  79. opts = append(opts, authority.WithDatabase(ca.opts.database))
  80. }
  81. auth, err := authority.New(config, opts...)
  82. if err != nil {
  83. return nil, err
  84. }
  85. tlsConfig, err := ca.getTLSConfig(auth)
  86. if err != nil {
  87. return nil, err
  88. }
  89. // Using chi as the main router
  90. mux := chi.NewRouter()
  91. handler := http.Handler(mux)
  92. // Add regular CA api endpoints in / and /1.0
  93. routerHandler := api.New(auth)
  94. routerHandler.Route(mux)
  95. mux.Route("/1.0", func(r chi.Router) {
  96. routerHandler.Route(r)
  97. })
  98. //Add ACME api endpoints in /acme and /1.0/acme
  99. dns := config.DNSNames[0]
  100. u, err := url.Parse("https://" + config.Address)
  101. if err != nil {
  102. return nil, err
  103. }
  104. port := u.Port()
  105. if port != "" && port != "443" {
  106. dns = fmt.Sprintf("%s:%s", dns, port)
  107. }
  108. prefix := "acme"
  109. acmeDB, err := acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  110. if err != nil {
  111. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  112. }
  113. acmeHandler := acmeAPI.NewHandler(acmeAPI.HandlerOptions{
  114. Backdate: *config.AuthorityConfig.Backdate,
  115. DB: acmeDB,
  116. DNS: dns,
  117. Prefix: prefix,
  118. CA: auth,
  119. })
  120. mux.Route("/"+prefix, func(r chi.Router) {
  121. acmeHandler.Route(r)
  122. })
  123. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  124. // of the ACME spec.
  125. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  126. acmeHandler.Route(r)
  127. })
  128. /*
  129. // helpful routine for logging all routes //
  130. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  131. fmt.Printf("%s %s\n", method, route)
  132. return nil
  133. }
  134. if err := chi.Walk(mux, walkFunc); err != nil {
  135. fmt.Printf("Logging err: %s\n", err.Error())
  136. }
  137. */
  138. // Add monitoring if configured
  139. if len(config.Monitoring) > 0 {
  140. m, err := monitoring.New(config.Monitoring)
  141. if err != nil {
  142. return nil, err
  143. }
  144. handler = m.Middleware(handler)
  145. }
  146. // Add logger if configured
  147. if len(config.Logger) > 0 {
  148. logger, err := logging.New("ca", config.Logger)
  149. if err != nil {
  150. return nil, err
  151. }
  152. handler = logger.Middleware(handler)
  153. }
  154. ca.auth = auth
  155. ca.srv = server.New(config.Address, handler, tlsConfig)
  156. return ca, nil
  157. }
  158. // Run starts the CA calling to the server ListenAndServe method.
  159. func (ca *CA) Run() error {
  160. return ca.srv.ListenAndServe()
  161. }
  162. // Stop stops the CA calling to the server Shutdown method.
  163. func (ca *CA) Stop() error {
  164. ca.renewer.Stop()
  165. if err := ca.auth.Shutdown(); err != nil {
  166. log.Printf("error stopping ca.Authority: %+v\n", err)
  167. }
  168. return ca.srv.Shutdown()
  169. }
  170. // Reload reloads the configuration of the CA and calls to the server Reload
  171. // method.
  172. func (ca *CA) Reload() error {
  173. config, err := authority.LoadConfiguration(ca.opts.configFile)
  174. if err != nil {
  175. return errors.Wrap(err, "error reloading ca configuration")
  176. }
  177. logContinue := func(reason string) {
  178. log.Println(reason)
  179. log.Println("Continuing to run with the original configuration.")
  180. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  181. }
  182. // Do not allow reload if the database configuration has changed.
  183. if !reflect.DeepEqual(ca.config.DB, config.DB) {
  184. logContinue("Reload failed because the database configuration has changed.")
  185. return errors.New("error reloading ca: database configuration cannot change")
  186. }
  187. newCA, err := New(config,
  188. WithPassword(ca.opts.password),
  189. WithConfigFile(ca.opts.configFile),
  190. WithDatabase(ca.auth.GetDatabase()),
  191. )
  192. if err != nil {
  193. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  194. return errors.Wrap(err, "error reloading ca")
  195. }
  196. if err = ca.srv.Reload(newCA.srv); err != nil {
  197. logContinue("Reload failed because server could not be replaced.")
  198. return errors.Wrap(err, "error reloading server")
  199. }
  200. // 1. Stop previous renewer
  201. // 2. Safely shutdown any internal resources (e.g. key manager)
  202. // 3. Replace ca properties
  203. // Do not replace ca.srv
  204. ca.renewer.Stop()
  205. ca.auth.CloseForReload()
  206. ca.auth = newCA.auth
  207. ca.config = newCA.config
  208. ca.opts = newCA.opts
  209. ca.renewer = newCA.renewer
  210. return nil
  211. }
  212. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  213. // server certificate.
  214. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  215. // Create initial TLS certificate
  216. tlsCrt, err := auth.GetTLSCertificate()
  217. if err != nil {
  218. return nil, err
  219. }
  220. // Start tls renewer with the new certificate.
  221. // If a renewer was started, attempt to stop it before.
  222. if ca.renewer != nil {
  223. ca.renewer.Stop()
  224. }
  225. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  226. if err != nil {
  227. return nil, err
  228. }
  229. ca.renewer.Run()
  230. var tlsConfig *tls.Config
  231. if ca.config.TLS != nil {
  232. tlsConfig = ca.config.TLS.TLSConfig()
  233. } else {
  234. tlsConfig = &tls.Config{
  235. MinVersion: tls.VersionTLS12,
  236. }
  237. }
  238. certPool := x509.NewCertPool()
  239. for _, crt := range auth.GetRootCertificates() {
  240. certPool.AddCert(crt)
  241. }
  242. // GetCertificate will only be called if the client supplies SNI
  243. // information or if tlsConfig.Certificates is empty.
  244. // When client requests are made using an IP address (as opposed to a domain
  245. // name) the server does not receive any SNI and may fallback to using the
  246. // first entry in the Certificates attribute; by setting the attribute to
  247. // empty we are implicitly forcing GetCertificate to be the only mechanism
  248. // by which the server can find it's own leaf Certificate.
  249. tlsConfig.Certificates = []tls.Certificate{}
  250. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  251. // Add support for mutual tls to renew certificates
  252. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  253. tlsConfig.ClientCAs = certPool
  254. // Use server's most preferred ciphersuite
  255. tlsConfig.PreferServerCipherSuites = true
  256. return tlsConfig, nil
  257. }