ca.go 7.9 KB

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