ca.go 7.5 KB

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