ca.go 7.5 KB

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