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