ca.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. "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. acmeAuth, err := acme.New(auth, acme.AuthorityOptions{
  110. Backdate: *config.AuthorityConfig.Backdate,
  111. DB: auth.GetDatabase().(nosql.DB),
  112. DNS: dns,
  113. Prefix: prefix,
  114. })
  115. if err != nil {
  116. return nil, errors.Wrap(err, "error creating ACME authority")
  117. }
  118. acmeRouterHandler := acmeAPI.New(acmeAuth)
  119. mux.Route("/"+prefix, func(r chi.Router) {
  120. acmeRouterHandler.Route(r)
  121. })
  122. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  123. // of the ACME spec.
  124. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  125. acmeRouterHandler.Route(r)
  126. })
  127. /*
  128. // helpful routine for logging all routes //
  129. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  130. fmt.Printf("%s %s\n", method, route)
  131. return nil
  132. }
  133. if err := chi.Walk(mux, walkFunc); err != nil {
  134. fmt.Printf("Logging err: %s\n", err.Error())
  135. }
  136. */
  137. // Add monitoring if configured
  138. if len(config.Monitoring) > 0 {
  139. m, err := monitoring.New(config.Monitoring)
  140. if err != nil {
  141. return nil, err
  142. }
  143. handler = m.Middleware(handler)
  144. }
  145. // Add logger if configured
  146. if len(config.Logger) > 0 {
  147. logger, err := logging.New("ca", config.Logger)
  148. if err != nil {
  149. return nil, err
  150. }
  151. handler = logger.Middleware(handler)
  152. }
  153. ca.auth = auth
  154. ca.srv = server.New(config.Address, handler, tlsConfig)
  155. return ca, nil
  156. }
  157. // Run starts the CA calling to the server ListenAndServe method.
  158. func (ca *CA) Run() error {
  159. return ca.srv.ListenAndServe()
  160. }
  161. // Stop stops the CA calling to the server Shutdown method.
  162. func (ca *CA) Stop() error {
  163. ca.renewer.Stop()
  164. if err := ca.auth.Shutdown(); err != nil {
  165. log.Printf("error stopping ca.Authority: %+v\n", err)
  166. }
  167. return ca.srv.Shutdown()
  168. }
  169. // Reload reloads the configuration of the CA and calls to the server Reload
  170. // method.
  171. func (ca *CA) Reload() error {
  172. config, err := authority.LoadConfiguration(ca.opts.configFile)
  173. if err != nil {
  174. return errors.Wrap(err, "error reloading ca configuration")
  175. }
  176. logContinue := func(reason string) {
  177. log.Println(reason)
  178. log.Println("Continuing to run with the original configuration.")
  179. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  180. }
  181. // Do not allow reload if the database configuration has changed.
  182. if !reflect.DeepEqual(ca.config.DB, config.DB) {
  183. logContinue("Reload failed because the database configuration has changed.")
  184. return errors.New("error reloading ca: database configuration cannot change")
  185. }
  186. newCA, err := New(config,
  187. WithPassword(ca.opts.password),
  188. WithConfigFile(ca.opts.configFile),
  189. WithDatabase(ca.auth.GetDatabase()),
  190. )
  191. if err != nil {
  192. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  193. return errors.Wrap(err, "error reloading ca")
  194. }
  195. if err = ca.srv.Reload(newCA.srv); err != nil {
  196. logContinue("Reload failed because server could not be replaced.")
  197. return errors.Wrap(err, "error reloading server")
  198. }
  199. // 1. Stop previous renewer
  200. // 2. Replace ca properties
  201. // Do not replace ca.srv
  202. ca.renewer.Stop()
  203. ca.auth = newCA.auth
  204. ca.config = newCA.config
  205. ca.opts = newCA.opts
  206. ca.renewer = newCA.renewer
  207. return nil
  208. }
  209. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  210. // server certificate.
  211. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  212. // Create initial TLS certificate
  213. tlsCrt, err := auth.GetTLSCertificate()
  214. if err != nil {
  215. return nil, err
  216. }
  217. // Start tls renewer with the new certificate.
  218. // If a renewer was started, attempt to stop it before.
  219. if ca.renewer != nil {
  220. ca.renewer.Stop()
  221. }
  222. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  223. if err != nil {
  224. return nil, err
  225. }
  226. ca.renewer.Run()
  227. var tlsConfig *tls.Config
  228. if ca.config.TLS != nil {
  229. tlsConfig = ca.config.TLS.TLSConfig()
  230. } else {
  231. tlsConfig = &tls.Config{
  232. MinVersion: tls.VersionTLS12,
  233. }
  234. }
  235. certPool := x509.NewCertPool()
  236. for _, crt := range auth.GetRootCertificates() {
  237. certPool.AddCert(crt)
  238. }
  239. // GetCertificate will only be called if the client supplies SNI
  240. // information or if tlsConfig.Certificates is empty.
  241. // When client requests are made using an IP address (as opposed to a domain
  242. // name) the server does not receive any SNI and may fallback to using the
  243. // first entry in the Certificates attribute; by setting the attribute to
  244. // empty we are implicitly forcing GetCertificate to be the only mechanism
  245. // by which the server can find it's own leaf Certificate.
  246. tlsConfig.Certificates = []tls.Certificate{}
  247. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  248. // Add support for mutual tls to renew certificates
  249. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  250. tlsConfig.ClientCAs = certPool
  251. // Use server's most preferred ciphersuite
  252. tlsConfig.PreferServerCipherSuites = true
  253. return tlsConfig, nil
  254. }