ca.go 8.5 KB

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