ca.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435
  1. package ca
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "fmt"
  6. "log"
  7. "net/http"
  8. "net/url"
  9. "reflect"
  10. "sync"
  11. "github.com/go-chi/chi"
  12. "github.com/pkg/errors"
  13. "github.com/smallstep/certificates/acme"
  14. acmeAPI "github.com/smallstep/certificates/acme/api"
  15. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  16. "github.com/smallstep/certificates/api"
  17. "github.com/smallstep/certificates/authority"
  18. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  19. "github.com/smallstep/certificates/authority/config"
  20. "github.com/smallstep/certificates/db"
  21. "github.com/smallstep/certificates/logging"
  22. "github.com/smallstep/certificates/monitoring"
  23. "github.com/smallstep/certificates/scep"
  24. scepAPI "github.com/smallstep/certificates/scep/api"
  25. "github.com/smallstep/certificates/server"
  26. "github.com/smallstep/nosql"
  27. )
  28. type options struct {
  29. configFile string
  30. password []byte
  31. issuerPassword []byte
  32. database db.AuthDB
  33. }
  34. func (o *options) apply(opts []Option) {
  35. for _, fn := range opts {
  36. fn(o)
  37. }
  38. }
  39. // Option is the type of options passed to the CA constructor.
  40. type Option func(o *options)
  41. // WithConfigFile sets the given name as the configuration file name in the CA
  42. // options.
  43. func WithConfigFile(name string) Option {
  44. return func(o *options) {
  45. o.configFile = name
  46. }
  47. }
  48. // WithPassword sets the given password as the configured password in the CA
  49. // options.
  50. func WithPassword(password []byte) Option {
  51. return func(o *options) {
  52. o.password = password
  53. }
  54. }
  55. // WithIssuerPassword sets the given password as the configured certificate
  56. // issuer password in the CA options.
  57. func WithIssuerPassword(password []byte) Option {
  58. return func(o *options) {
  59. o.issuerPassword = password
  60. }
  61. }
  62. // WithDatabase sets the given authority database to the CA options.
  63. func WithDatabase(db db.AuthDB) Option {
  64. return func(o *options) {
  65. o.database = db
  66. }
  67. }
  68. // CA is the type used to build the complete certificate authority. It builds
  69. // the HTTP server, set ups the middlewares and the HTTP handlers.
  70. type CA struct {
  71. auth *authority.Authority
  72. config *config.Config
  73. srv *server.Server
  74. insecureSrv *server.Server
  75. opts *options
  76. renewer *TLSRenewer
  77. }
  78. // New creates and initializes the CA with the given configuration and options.
  79. func New(config *config.Config, opts ...Option) (*CA, error) {
  80. ca := &CA{
  81. config: config,
  82. opts: new(options),
  83. }
  84. ca.opts.apply(opts)
  85. return ca.Init(config)
  86. }
  87. // Init initializes the CA with the given configuration.
  88. func (ca *CA) Init(config *config.Config) (*CA, error) {
  89. // Intermediate Password.
  90. if len(ca.opts.password) > 0 {
  91. ca.config.Password = string(ca.opts.password)
  92. }
  93. // Certificate issuer password for RA mode.
  94. if len(ca.opts.issuerPassword) > 0 {
  95. if ca.config.AuthorityConfig != nil && ca.config.AuthorityConfig.CertificateIssuer != nil {
  96. ca.config.AuthorityConfig.CertificateIssuer.Password = string(ca.opts.issuerPassword)
  97. }
  98. }
  99. var opts []authority.Option
  100. if ca.opts.database != nil {
  101. opts = append(opts, authority.WithDatabase(ca.opts.database))
  102. }
  103. auth, err := authority.New(config, opts...)
  104. if err != nil {
  105. return nil, err
  106. }
  107. ca.auth = auth
  108. tlsConfig, err := ca.getTLSConfig(auth)
  109. if err != nil {
  110. return nil, err
  111. }
  112. // Using chi as the main router
  113. mux := chi.NewRouter()
  114. handler := http.Handler(mux)
  115. insecureMux := chi.NewRouter()
  116. insecureHandler := http.Handler(insecureMux)
  117. // Add regular CA api endpoints in / and /1.0
  118. routerHandler := api.New(auth)
  119. routerHandler.Route(mux)
  120. mux.Route("/1.0", func(r chi.Router) {
  121. routerHandler.Route(r)
  122. })
  123. //Add ACME api endpoints in /acme and /1.0/acme
  124. dns := config.DNSNames[0]
  125. u, err := url.Parse("https://" + config.Address)
  126. if err != nil {
  127. return nil, err
  128. }
  129. port := u.Port()
  130. if port != "" && port != "443" {
  131. dns = fmt.Sprintf("%s:%s", dns, port)
  132. }
  133. // ACME Router
  134. prefix := "acme"
  135. var acmeDB acme.DB
  136. if config.DB == nil {
  137. acmeDB = nil
  138. } else {
  139. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  140. if err != nil {
  141. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  142. }
  143. }
  144. acmeHandler := acmeAPI.NewHandler(acmeAPI.HandlerOptions{
  145. Backdate: *config.AuthorityConfig.Backdate,
  146. DB: acmeDB,
  147. DNS: dns,
  148. Prefix: prefix,
  149. CA: auth,
  150. })
  151. mux.Route("/"+prefix, func(r chi.Router) {
  152. acmeHandler.Route(r)
  153. })
  154. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  155. // of the ACME spec.
  156. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  157. acmeHandler.Route(r)
  158. })
  159. // Admin API Router
  160. if config.AuthorityConfig.EnableAdmin {
  161. adminDB := auth.GetAdminDatabase()
  162. if adminDB != nil {
  163. adminHandler := adminAPI.NewHandler(auth)
  164. mux.Route("/admin", func(r chi.Router) {
  165. adminHandler.Route(r)
  166. })
  167. }
  168. }
  169. if ca.shouldServeSCEPEndpoints() {
  170. scepPrefix := "scep"
  171. scepAuthority, err := scep.New(auth, scep.AuthorityOptions{
  172. Service: auth.GetSCEPService(),
  173. DNS: dns,
  174. Prefix: scepPrefix,
  175. })
  176. if err != nil {
  177. return nil, errors.Wrap(err, "error creating SCEP authority")
  178. }
  179. scepRouterHandler := scepAPI.New(scepAuthority)
  180. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  181. // SCEP operations are performed using HTTP, so that's why the API is mounted
  182. // to the insecure mux.
  183. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  184. scepRouterHandler.Route(r)
  185. })
  186. // The RFC also mentions usage of HTTPS, but seems to advise
  187. // against it, because of potential interoperability issues.
  188. // Currently I think it's not bad to use HTTPS also, so that's
  189. // why I've kept the API endpoints in both muxes and both HTTP
  190. // as well as HTTPS can be used to request certificates
  191. // using SCEP.
  192. mux.Route("/"+scepPrefix, func(r chi.Router) {
  193. scepRouterHandler.Route(r)
  194. })
  195. }
  196. // helpful routine for logging all routes
  197. //dumpRoutes(mux)
  198. // Add monitoring if configured
  199. if len(config.Monitoring) > 0 {
  200. m, err := monitoring.New(config.Monitoring)
  201. if err != nil {
  202. return nil, err
  203. }
  204. handler = m.Middleware(handler)
  205. insecureHandler = m.Middleware(insecureHandler)
  206. }
  207. // Add logger if configured
  208. if len(config.Logger) > 0 {
  209. logger, err := logging.New("ca", config.Logger)
  210. if err != nil {
  211. return nil, err
  212. }
  213. handler = logger.Middleware(handler)
  214. insecureHandler = logger.Middleware(insecureHandler)
  215. }
  216. ca.srv = server.New(config.Address, handler, tlsConfig)
  217. // only start the insecure server if the insecure address is configured
  218. // and, currently, also only when it should serve SCEP endpoints.
  219. if ca.shouldServeSCEPEndpoints() && config.InsecureAddress != "" {
  220. // TODO: instead opt for having a single server.Server but two
  221. // http.Servers handling the HTTP and HTTPS handler? The latter
  222. // will probably introduce more complexity in terms of graceful
  223. // reload.
  224. ca.insecureSrv = server.New(config.InsecureAddress, insecureHandler, nil)
  225. }
  226. return ca, nil
  227. }
  228. // Run starts the CA calling to the server ListenAndServe method.
  229. func (ca *CA) Run() error {
  230. var wg sync.WaitGroup
  231. errors := make(chan error, 1)
  232. if ca.insecureSrv != nil {
  233. wg.Add(1)
  234. go func() {
  235. defer wg.Done()
  236. errors <- ca.insecureSrv.ListenAndServe()
  237. }()
  238. }
  239. wg.Add(1)
  240. go func() {
  241. defer wg.Done()
  242. errors <- ca.srv.ListenAndServe()
  243. }()
  244. // wait till error occurs; ensures the servers keep listening
  245. err := <-errors
  246. wg.Wait()
  247. return err
  248. }
  249. // Stop stops the CA calling to the server Shutdown method.
  250. func (ca *CA) Stop() error {
  251. ca.renewer.Stop()
  252. if err := ca.auth.Shutdown(); err != nil {
  253. log.Printf("error stopping ca.Authority: %+v\n", err)
  254. }
  255. var insecureShutdownErr error
  256. if ca.insecureSrv != nil {
  257. insecureShutdownErr = ca.insecureSrv.Shutdown()
  258. }
  259. secureErr := ca.srv.Shutdown()
  260. if insecureShutdownErr != nil {
  261. return insecureShutdownErr
  262. }
  263. return secureErr
  264. }
  265. // Reload reloads the configuration of the CA and calls to the server Reload
  266. // method.
  267. func (ca *CA) Reload() error {
  268. config, err := config.LoadConfiguration(ca.opts.configFile)
  269. if err != nil {
  270. return errors.Wrap(err, "error reloading ca configuration")
  271. }
  272. logContinue := func(reason string) {
  273. log.Println(reason)
  274. log.Println("Continuing to run with the original configuration.")
  275. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  276. }
  277. // Do not allow reload if the database configuration has changed.
  278. if !reflect.DeepEqual(ca.config.DB, config.DB) {
  279. logContinue("Reload failed because the database configuration has changed.")
  280. return errors.New("error reloading ca: database configuration cannot change")
  281. }
  282. newCA, err := New(config,
  283. WithPassword(ca.opts.password),
  284. WithIssuerPassword(ca.opts.issuerPassword),
  285. WithConfigFile(ca.opts.configFile),
  286. WithDatabase(ca.auth.GetDatabase()),
  287. )
  288. if err != nil {
  289. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  290. return errors.Wrap(err, "error reloading ca")
  291. }
  292. if ca.insecureSrv != nil {
  293. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  294. logContinue("Reload failed because insecure server could not be replaced.")
  295. return errors.Wrap(err, "error reloading insecure server")
  296. }
  297. }
  298. if err = ca.srv.Reload(newCA.srv); err != nil {
  299. logContinue("Reload failed because server could not be replaced.")
  300. return errors.Wrap(err, "error reloading server")
  301. }
  302. // 1. Stop previous renewer
  303. // 2. Safely shutdown any internal resources (e.g. key manager)
  304. // 3. Replace ca properties
  305. // Do not replace ca.srv
  306. ca.renewer.Stop()
  307. ca.auth.CloseForReload()
  308. ca.auth = newCA.auth
  309. ca.config = newCA.config
  310. ca.opts = newCA.opts
  311. ca.renewer = newCA.renewer
  312. return nil
  313. }
  314. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  315. // server certificate.
  316. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  317. // Create initial TLS certificate
  318. tlsCrt, err := auth.GetTLSCertificate()
  319. if err != nil {
  320. return nil, err
  321. }
  322. // Start tls renewer with the new certificate.
  323. // If a renewer was started, attempt to stop it before.
  324. if ca.renewer != nil {
  325. ca.renewer.Stop()
  326. }
  327. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  328. if err != nil {
  329. return nil, err
  330. }
  331. ca.renewer.Run()
  332. var tlsConfig *tls.Config
  333. if ca.config.TLS != nil {
  334. tlsConfig = ca.config.TLS.TLSConfig()
  335. } else {
  336. tlsConfig = &tls.Config{
  337. MinVersion: tls.VersionTLS12,
  338. }
  339. }
  340. certPool := x509.NewCertPool()
  341. for _, crt := range auth.GetRootCertificates() {
  342. certPool.AddCert(crt)
  343. }
  344. // GetCertificate will only be called if the client supplies SNI
  345. // information or if tlsConfig.Certificates is empty.
  346. // When client requests are made using an IP address (as opposed to a domain
  347. // name) the server does not receive any SNI and may fallback to using the
  348. // first entry in the Certificates attribute; by setting the attribute to
  349. // empty we are implicitly forcing GetCertificate to be the only mechanism
  350. // by which the server can find it's own leaf Certificate.
  351. tlsConfig.Certificates = []tls.Certificate{}
  352. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  353. // Add support for mutual tls to renew certificates
  354. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  355. tlsConfig.ClientCAs = certPool
  356. // Use server's most preferred ciphersuite
  357. tlsConfig.PreferServerCipherSuites = true
  358. return tlsConfig, nil
  359. }
  360. // shouldMountSCEPEndpoints returns if the CA should be
  361. // configured with endpoints for SCEP. This is assumed to be
  362. // true if a SCEPService exists, which is true in case a
  363. // SCEP provisioner was configured.
  364. func (ca *CA) shouldServeSCEPEndpoints() bool {
  365. return ca.auth.GetSCEPService() != nil
  366. }
  367. //nolint // ignore linters to allow keeping this function around for debugging
  368. func dumpRoutes(mux chi.Routes) {
  369. // helpful routine for logging all routes //
  370. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  371. fmt.Printf("%s %s\n", method, route)
  372. return nil
  373. }
  374. if err := chi.Walk(mux, walkFunc); err != nil {
  375. fmt.Printf("Logging err: %s\n", err.Error())
  376. }
  377. }