ca.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769
  1. package ca
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/tls"
  6. "crypto/x509"
  7. "errors"
  8. "fmt"
  9. "log"
  10. "net"
  11. "net/http"
  12. "net/url"
  13. "reflect"
  14. "strings"
  15. "time"
  16. "github.com/coreos/go-systemd/v22/daemon"
  17. "github.com/go-chi/chi/v5"
  18. "github.com/go-chi/chi/v5/middleware"
  19. "golang.org/x/sync/errgroup"
  20. "github.com/smallstep/cli-utils/step"
  21. "github.com/smallstep/nosql"
  22. "go.step.sm/crypto/x509util"
  23. "github.com/smallstep/certificates/acme"
  24. acmeAPI "github.com/smallstep/certificates/acme/api"
  25. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  26. "github.com/smallstep/certificates/api"
  27. "github.com/smallstep/certificates/authority"
  28. "github.com/smallstep/certificates/authority/admin"
  29. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  30. "github.com/smallstep/certificates/authority/config"
  31. "github.com/smallstep/certificates/cas/apiv1"
  32. "github.com/smallstep/certificates/db"
  33. "github.com/smallstep/certificates/est"
  34. estAPI "github.com/smallstep/certificates/est/api"
  35. "github.com/smallstep/certificates/internal/httptransport"
  36. "github.com/smallstep/certificates/internal/metrix"
  37. "github.com/smallstep/certificates/logging"
  38. "github.com/smallstep/certificates/middleware/requestid"
  39. "github.com/smallstep/certificates/monitoring"
  40. "github.com/smallstep/certificates/scep"
  41. scepAPI "github.com/smallstep/certificates/scep/api"
  42. "github.com/smallstep/certificates/server"
  43. )
  44. type options struct {
  45. configFile string
  46. linkedCAToken string
  47. quiet bool
  48. password []byte
  49. issuerPassword []byte
  50. sshHostPassword []byte
  51. sshUserPassword []byte
  52. database db.AuthDB
  53. x509CAService apiv1.CertificateAuthorityService
  54. tlsConfig *tls.Config
  55. }
  56. func (o *options) apply(opts []Option) {
  57. for _, fn := range opts {
  58. fn(o)
  59. }
  60. }
  61. // Option is the type of options passed to the CA constructor.
  62. type Option func(o *options)
  63. // WithConfigFile sets the given name as the configuration file name in the CA
  64. // options.
  65. func WithConfigFile(name string) Option {
  66. return func(o *options) {
  67. o.configFile = name
  68. }
  69. }
  70. // WithX509CAService provides the x509CAService to be used for signing x509 requests
  71. func WithX509CAService(svc apiv1.CertificateAuthorityService) Option {
  72. return func(o *options) {
  73. o.x509CAService = svc
  74. }
  75. }
  76. // WithPassword sets the given password as the configured password in the CA
  77. // options.
  78. func WithPassword(password []byte) Option {
  79. return func(o *options) {
  80. o.password = password
  81. }
  82. }
  83. // WithSSHHostPassword sets the given password to decrypt the key used to sign
  84. // ssh host certificates.
  85. func WithSSHHostPassword(password []byte) Option {
  86. return func(o *options) {
  87. o.sshHostPassword = password
  88. }
  89. }
  90. // WithSSHUserPassword sets the given password to decrypt the key used to sign
  91. // ssh user certificates.
  92. func WithSSHUserPassword(password []byte) Option {
  93. return func(o *options) {
  94. o.sshUserPassword = password
  95. }
  96. }
  97. // WithIssuerPassword sets the given password as the configured certificate
  98. // issuer password in the CA options.
  99. func WithIssuerPassword(password []byte) Option {
  100. return func(o *options) {
  101. o.issuerPassword = password
  102. }
  103. }
  104. // WithDatabase sets the given authority database to the CA options.
  105. func WithDatabase(d db.AuthDB) Option {
  106. return func(o *options) {
  107. o.database = d
  108. }
  109. }
  110. // WithTLSConfig sets the TLS configuration to be used by the HTTP(s) server
  111. // spun by step-ca.
  112. func WithTLSConfig(t *tls.Config) Option {
  113. return func(o *options) {
  114. o.tlsConfig = t
  115. }
  116. }
  117. // WithLinkedCAToken sets the token used to authenticate with the linkedca.
  118. func WithLinkedCAToken(token string) Option {
  119. return func(o *options) {
  120. o.linkedCAToken = token
  121. }
  122. }
  123. // WithQuiet sets the quiet flag.
  124. func WithQuiet(quiet bool) Option {
  125. return func(o *options) {
  126. o.quiet = quiet
  127. }
  128. }
  129. // CA is the type used to build the complete certificate authority. It builds
  130. // the HTTP server, set ups the middlewares and the HTTP handlers.
  131. type CA struct {
  132. auth *authority.Authority
  133. config *config.Config
  134. srv *server.Server
  135. insecureSrv *server.Server
  136. metricsSrv *server.Server
  137. opts *options
  138. renewer *TLSRenewer
  139. compactStop chan struct{}
  140. }
  141. // New creates and initializes the CA with the given configuration and options.
  142. func New(cfg *config.Config, opts ...Option) (*CA, error) {
  143. ca := &CA{
  144. config: cfg,
  145. opts: new(options),
  146. compactStop: make(chan struct{}),
  147. }
  148. ca.opts.apply(opts)
  149. return ca.Init(cfg)
  150. }
  151. // Init initializes the CA with the given configuration.
  152. func (ca *CA) Init(cfg *config.Config) (*CA, error) {
  153. // Set password, it's ok to set nil password, the ca will prompt for them if
  154. // they are required.
  155. opts := []authority.Option{
  156. authority.WithPassword(ca.opts.password),
  157. authority.WithSSHHostPassword(ca.opts.sshHostPassword),
  158. authority.WithSSHUserPassword(ca.opts.sshUserPassword),
  159. authority.WithIssuerPassword(ca.opts.issuerPassword),
  160. }
  161. if ca.opts.linkedCAToken != "" {
  162. opts = append(opts, authority.WithLinkedCAToken(ca.opts.linkedCAToken))
  163. }
  164. if ca.opts.database != nil {
  165. opts = append(opts, authority.WithDatabase(ca.opts.database))
  166. }
  167. if ca.opts.quiet {
  168. opts = append(opts, authority.WithQuietInit())
  169. }
  170. if ca.opts.x509CAService != nil {
  171. opts = append(opts, authority.WithX509CAService(ca.opts.x509CAService))
  172. }
  173. var meter *metrix.Meter
  174. if ca.config.MetricsAddress != "" {
  175. meter = metrix.New()
  176. opts = append(opts, authority.WithMeter(meter))
  177. }
  178. webhookTransport := httptransport.New()
  179. opts = append(opts,
  180. authority.WithWebhookClient(&http.Client{Transport: webhookTransport}),
  181. )
  182. auth, err := authority.New(cfg, opts...)
  183. if err != nil {
  184. return nil, err
  185. }
  186. ca.auth = auth
  187. var tlsConfig *tls.Config
  188. var clientTLSConfig *tls.Config
  189. if ca.opts.tlsConfig != nil {
  190. // try using the tls Configuration supplied by the caller
  191. log.Print("Using tls configuration supplied by the application")
  192. tlsConfig = ca.opts.tlsConfig
  193. clientTLSConfig = ca.opts.tlsConfig
  194. } else {
  195. // default to using the step-ca x509 Signer Interface
  196. log.Print("Building new tls configuration using step-ca x509 Signer Interface")
  197. tlsConfig, clientTLSConfig, err = ca.getTLSConfig(auth)
  198. if err != nil {
  199. return nil, err
  200. }
  201. }
  202. webhookTransport.TLSClientConfig = clientTLSConfig
  203. // Using chi as the main router
  204. mux := chi.NewRouter()
  205. handler := http.Handler(mux)
  206. insecureMux := chi.NewRouter()
  207. insecureHandler := http.Handler(insecureMux)
  208. // Add HEAD middleware
  209. mux.Use(middleware.GetHead)
  210. insecureMux.Use(middleware.GetHead)
  211. // Add regular CA api endpoints in / and /1.0
  212. api.Route(mux)
  213. mux.Route("/1.0", func(r chi.Router) {
  214. api.Route(r)
  215. })
  216. // Mount the CRL to the insecure mux
  217. insecureMux.Get("/crl", api.CRL)
  218. insecureMux.Get("/1.0/crl", api.CRL)
  219. // Add ACME api endpoints in /acme and /1.0/acme
  220. dns := cfg.DNSNames[0]
  221. u, err := url.Parse("https://" + cfg.Address)
  222. if err != nil {
  223. return nil, err
  224. }
  225. port := u.Port()
  226. if port != "" && port != "443" {
  227. dns = fmt.Sprintf("%s:%s", dns, port)
  228. }
  229. // ACME Router is only available if we have a database.
  230. var acmeDB acme.DB
  231. var acmeLinker acme.Linker
  232. if cfg.DB == nil && auth.HasACMEProvisioner() {
  233. log.Println("WARNING: No database is configured. ACME provisioners are disabled.")
  234. }
  235. if cfg.DB != nil {
  236. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  237. if err != nil {
  238. return nil, fmt.Errorf("error configuring ACME DB interface: %w", err)
  239. }
  240. acmeLinker = acme.NewLinker(dns, "acme")
  241. mux.Route("/acme", func(r chi.Router) {
  242. acmeAPI.Route(r)
  243. })
  244. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  245. // of the ACME spec.
  246. mux.Route("/2.0/acme", func(r chi.Router) {
  247. acmeAPI.Route(r)
  248. })
  249. }
  250. // Admin API Router
  251. if cfg.AuthorityConfig.EnableAdmin {
  252. adminDB := auth.GetAdminDatabase()
  253. if adminDB != nil {
  254. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  255. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  256. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  257. mux.Route("/admin", func(r chi.Router) {
  258. adminAPI.Route(
  259. r,
  260. adminAPI.WithACMEResponder(acmeAdminResponder),
  261. adminAPI.WithPolicyResponder(policyAdminResponder),
  262. adminAPI.WithWebhookResponder(webhookAdminResponder),
  263. )
  264. })
  265. }
  266. }
  267. var scepAuthority *scep.Authority
  268. if ca.shouldServeSCEPEndpoints() {
  269. // get the SCEP authority configuration. Validation is
  270. // performed within the authority instantiation process.
  271. scepAuthority = auth.GetSCEP()
  272. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  273. // SCEP operations are performed using HTTP, so that's why the API is mounted
  274. // to the insecure mux.
  275. scepPrefix := "scep"
  276. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  277. scepAPI.Route(r)
  278. })
  279. // The RFC also mentions usage of HTTPS, but seems to advise
  280. // against it, because of potential interoperability issues.
  281. // Currently I think it's not bad to use HTTPS also, so that's
  282. // why I've kept the API endpoints in both muxes and both HTTP
  283. // as well as HTTPS can be used to request certificates
  284. // using SCEP.
  285. mux.Route("/"+scepPrefix, func(r chi.Router) {
  286. scepAPI.Route(r)
  287. })
  288. }
  289. // EST endpoints (HTTPS only)
  290. var estAuthority *est.Authority
  291. if estAuth := auth.GetEST(); estAuth != nil {
  292. // EST is served on /.well-known/<optional-label>/est; we use the provisioner
  293. // name as label.
  294. // TODO(hs): decide whether we want to go with this, or also want to support
  295. // some form of default EST provisioner that can be requested at the path without
  296. // a label set.
  297. estPrefix := "/.well-known/{label}/est"
  298. estAuthority = estAuth
  299. mux.Route(estPrefix, func(r chi.Router) {
  300. estAPI.Route(r)
  301. })
  302. }
  303. // helpful routine for logging all routes
  304. //dumpRoutes(mux)
  305. //dumpRoutes(insecureMux)
  306. // Add monitoring if configured
  307. if len(cfg.Monitoring) > 0 {
  308. m, err := monitoring.New(cfg.Monitoring)
  309. if err != nil {
  310. return nil, err
  311. }
  312. handler = m.Middleware(handler)
  313. insecureHandler = m.Middleware(insecureHandler)
  314. }
  315. // Add logger if configured
  316. var legacyTraceHeader string
  317. if len(cfg.Logger) > 0 {
  318. logger, err := logging.New("ca", cfg.Logger)
  319. if err != nil {
  320. return nil, err
  321. }
  322. legacyTraceHeader = logger.GetTraceHeader()
  323. handler = logger.Middleware(handler)
  324. insecureHandler = logger.Middleware(insecureHandler)
  325. }
  326. // always use request ID middleware; traceHeader is provided for backwards compatibility (for now)
  327. handler = requestid.New(legacyTraceHeader).Middleware(handler)
  328. insecureHandler = requestid.New(legacyTraceHeader).Middleware(insecureHandler)
  329. // Create context with all the necessary values.
  330. baseContext := buildContext(auth, scepAuthority, estAuthority, acmeDB, acmeLinker)
  331. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  332. ca.srv.BaseContext = func(net.Listener) context.Context {
  333. return baseContext
  334. }
  335. // only start the insecure server if the insecure address is configured
  336. // and, currently, also only when it should serve SCEP endpoints.
  337. if ca.shouldServeInsecureServer() {
  338. // TODO: instead opt for having a single server.Server but two
  339. // http.Servers handling the HTTP and HTTPS handler? The latter
  340. // will probably introduce more complexity in terms of graceful
  341. // reload.
  342. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  343. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  344. return baseContext
  345. }
  346. }
  347. if meter != nil {
  348. ca.metricsSrv = server.New(ca.config.MetricsAddress, meter, nil)
  349. ca.metricsSrv.BaseContext = func(net.Listener) context.Context {
  350. return baseContext
  351. }
  352. }
  353. return ca, nil
  354. }
  355. // shouldServeInsecureServer returns whether or not the insecure
  356. // server should also be started. This is (currently) only the case
  357. // if the insecure address has been configured AND when a SCEP
  358. // provisioner is configured or when a CRL is configured.
  359. func (ca *CA) shouldServeInsecureServer() bool {
  360. switch {
  361. case ca.config.InsecureAddress == "":
  362. return false
  363. case ca.shouldServeSCEPEndpoints():
  364. return true
  365. case ca.config.CRL.IsEnabled():
  366. return true
  367. default:
  368. return false
  369. }
  370. }
  371. // buildContext builds the server base context.
  372. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, estAuthority *est.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  373. ctx := authority.NewContext(context.Background(), a)
  374. if authDB := a.GetDatabase(); authDB != nil {
  375. ctx = db.NewContext(ctx, authDB)
  376. }
  377. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  378. ctx = admin.NewContext(ctx, adminDB)
  379. }
  380. if scepAuthority != nil {
  381. ctx = scep.NewContext(ctx, scepAuthority)
  382. }
  383. if estAuthority != nil {
  384. ctx = est.NewContext(ctx, estAuthority)
  385. }
  386. if acmeDB != nil {
  387. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  388. }
  389. return ctx
  390. }
  391. // Run starts the CA calling to the server ListenAndServe method.
  392. func (ca *CA) Run() error {
  393. if !ca.opts.quiet {
  394. authorityInfo := ca.auth.GetInfo()
  395. log.Printf("Starting %s", step.Version())
  396. log.Printf("Documentation: https://u.step.sm/docs/ca")
  397. log.Printf("Community Discord: https://u.step.sm/discord")
  398. if step.Contexts().GetCurrent() != nil {
  399. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  400. }
  401. log.Printf("Config file: %s", ca.getConfigFileOutput())
  402. baseURL := fmt.Sprintf("https://%s%s",
  403. authorityInfo.DNSNames[0],
  404. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  405. log.Printf("The primary server URL is %s", baseURL)
  406. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  407. if len(authorityInfo.DNSNames) > 1 {
  408. log.Printf("Additional configured hostnames: %s",
  409. strings.Join(authorityInfo.DNSNames[1:], ", "))
  410. }
  411. for _, crt := range authorityInfo.RootX509Certs {
  412. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  413. }
  414. if authorityInfo.SSHCAHostPublicKey != nil {
  415. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  416. }
  417. if authorityInfo.SSHCAUserPublicKey != nil {
  418. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  419. }
  420. }
  421. eg := new(errgroup.Group)
  422. eg.Go(func() error {
  423. ca.runCompactJob()
  424. return nil
  425. })
  426. if ca.insecureSrv != nil {
  427. eg.Go(func() error {
  428. return ca.insecureSrv.ListenAndServe()
  429. })
  430. }
  431. if ca.metricsSrv != nil {
  432. eg.Go(func() error {
  433. return ca.metricsSrv.ListenAndServe()
  434. })
  435. }
  436. eg.Go(func() error {
  437. return ca.srv.ListenAndServe()
  438. })
  439. _, _ = daemon.SdNotify(true, daemon.SdNotifyReady)
  440. err := eg.Wait()
  441. _, _ = daemon.SdNotify(true, daemon.SdNotifyStopping)
  442. // if the error is not the usual HTTP server closed error, it is
  443. // highly likely that an error occurred when starting one of the
  444. // CA servers, possibly because of a port already being in use or
  445. // some part of the configuration not being correct. This case is
  446. // handled by stopping the CA in its entirety.
  447. if !errors.Is(err, http.ErrServerClosed) {
  448. log.Println("shutting down due to startup error ...")
  449. if stopErr := ca.Stop(); stopErr != nil {
  450. err = fmt.Errorf("failed stopping CA after error occurred: %w: %w", err, stopErr)
  451. } else {
  452. err = fmt.Errorf("stopped CA after error occurred: %w", err)
  453. }
  454. }
  455. return err
  456. }
  457. // Stop stops the CA calling to the server Shutdown method.
  458. func (ca *CA) Stop() error {
  459. close(ca.compactStop)
  460. if ca.renewer != nil {
  461. ca.renewer.Stop()
  462. }
  463. if err := ca.auth.Shutdown(); err != nil {
  464. log.Printf("error stopping ca.Authority: %+v\n", err)
  465. }
  466. // Concurrently shutdown services
  467. var eg errgroup.Group
  468. if ca.insecureSrv != nil {
  469. eg.Go(func() error {
  470. return ca.insecureSrv.Shutdown()
  471. })
  472. }
  473. if ca.metricsSrv != nil {
  474. eg.Go(func() error {
  475. return ca.metricsSrv.Shutdown()
  476. })
  477. }
  478. if ca.srv != nil {
  479. eg.Go(func() error {
  480. return ca.srv.Shutdown()
  481. })
  482. }
  483. // Return first error
  484. return eg.Wait()
  485. }
  486. // Reload reloads the configuration of the CA and calls to the server Reload
  487. // method.
  488. func (ca *CA) Reload() error {
  489. _, _ = daemon.SdNotify(true, daemon.SdNotifyReloading)
  490. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  491. if err != nil {
  492. return fmt.Errorf("error reloading ca configuration: %w", err)
  493. }
  494. logContinue := func(reason string) {
  495. log.Println(reason)
  496. log.Println("Continuing to run with the original configuration.")
  497. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  498. }
  499. // Do not allow reload if the database configuration has changed.
  500. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  501. logContinue("Reload failed because the database configuration has changed.")
  502. return errors.New("error reloading ca: database configuration cannot change")
  503. }
  504. newCA, err := New(cfg,
  505. WithPassword(ca.opts.password),
  506. WithSSHHostPassword(ca.opts.sshHostPassword),
  507. WithSSHUserPassword(ca.opts.sshUserPassword),
  508. WithIssuerPassword(ca.opts.issuerPassword),
  509. WithLinkedCAToken(ca.opts.linkedCAToken),
  510. WithQuiet(ca.opts.quiet),
  511. WithConfigFile(ca.opts.configFile),
  512. WithDatabase(ca.auth.GetDatabase()),
  513. )
  514. if err != nil {
  515. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  516. return fmt.Errorf("error reloading ca: %w", err)
  517. }
  518. if ca.insecureSrv != nil {
  519. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  520. logContinue("Reload failed because insecure server could not be replaced.")
  521. return fmt.Errorf("error reloading insecure server: %w", err)
  522. }
  523. }
  524. if ca.metricsSrv != nil {
  525. if err = ca.metricsSrv.Reload(newCA.metricsSrv); err != nil {
  526. logContinue("Reload failed because metrics server could not be replaced.")
  527. return fmt.Errorf("error reloading metrics server: %w", err)
  528. }
  529. }
  530. if err = ca.srv.Reload(newCA.srv); err != nil {
  531. logContinue("Reload failed because server could not be replaced.")
  532. return fmt.Errorf("error reloading server: %w", err)
  533. }
  534. // 1. Stop previous renewer
  535. // 2. Safely shutdown any internal resources (e.g. key manager)
  536. // 3. Replace ca properties
  537. // Do not replace ca.srv
  538. if ca.renewer != nil {
  539. ca.renewer.Stop()
  540. }
  541. ca.auth.CloseForReload()
  542. ca.auth = newCA.auth
  543. ca.config = newCA.config
  544. ca.opts = newCA.opts
  545. ca.renewer = newCA.renewer
  546. _, _ = daemon.SdNotify(true, daemon.SdNotifyReady)
  547. return nil
  548. }
  549. // get TLSConfig returns separate TLSConfigs for server and client with the
  550. // same self-renewing certificate.
  551. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  552. // Create initial TLS certificate
  553. tlsCrt, err := auth.GetTLSCertificate()
  554. if err != nil {
  555. return nil, nil, err
  556. }
  557. // Start tls renewer with the new certificate.
  558. // If a renewer was started, attempt to stop it before.
  559. if ca.renewer != nil {
  560. ca.renewer.Stop()
  561. }
  562. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  563. if err != nil {
  564. return nil, nil, err
  565. }
  566. ca.renewer.Run()
  567. var serverTLSConfig *tls.Config
  568. if ca.config.TLS != nil {
  569. serverTLSConfig = ca.config.TLS.TLSConfig()
  570. } else {
  571. serverTLSConfig = &tls.Config{
  572. MinVersion: tls.VersionTLS12,
  573. }
  574. }
  575. // GetCertificate will only be called if the client supplies SNI
  576. // information or if tlsConfig.Certificates is empty.
  577. // When client requests are made using an IP address (as opposed to a domain
  578. // name) the server does not receive any SNI and may fallback to using the
  579. // first entry in the Certificates attribute; by setting the attribute to
  580. // empty we are implicitly forcing GetCertificate to be the only mechanism
  581. // by which the server can find it's own leaf Certificate.
  582. serverTLSConfig.Certificates = []tls.Certificate{}
  583. clientTLSConfig := serverTLSConfig.Clone()
  584. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  585. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  586. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  587. certPool := x509.NewCertPool()
  588. // initialize a certificate pool with root CA certificates to trust when connecting
  589. // to webhook servers
  590. rootCAsPool, err := x509.SystemCertPool()
  591. if err != nil {
  592. return nil, nil, err
  593. }
  594. for _, crt := range auth.GetRootCertificates() {
  595. certPool.AddCert(crt)
  596. rootCAsPool.AddCert(crt)
  597. }
  598. // adding the intermediate CA certificates to the pool will allow clients that
  599. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  600. // added here are used when building a certificate chain.
  601. intermediates := tlsCrt.Certificate[1:]
  602. for _, certBytes := range intermediates {
  603. cert, err := x509.ParseCertificate(certBytes)
  604. if err != nil {
  605. return nil, nil, err
  606. }
  607. certPool.AddCert(cert)
  608. rootCAsPool.AddCert(cert)
  609. }
  610. // Add support for mutual tls to renew certificates
  611. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  612. serverTLSConfig.ClientCAs = certPool
  613. clientTLSConfig.RootCAs = rootCAsPool
  614. return serverTLSConfig, clientTLSConfig, nil
  615. }
  616. // shouldServeSCEPEndpoints returns if the CA should be
  617. // configured with endpoints for SCEP. This is assumed to be
  618. // true if a SCEPService exists, which is true in case at
  619. // least one SCEP provisioner was configured.
  620. func (ca *CA) shouldServeSCEPEndpoints() bool {
  621. return ca.auth.GetSCEP() != nil
  622. }
  623. //nolint:unused // useful for debugging
  624. func dumpRoutes(mux chi.Routes) {
  625. // helpful routine for logging all routes
  626. walkFunc := func(method string, route string, _ http.Handler, _ ...func(http.Handler) http.Handler) error {
  627. fmt.Printf("%s %s\n", method, route)
  628. return nil
  629. }
  630. if err := chi.Walk(mux, walkFunc); err != nil {
  631. fmt.Printf("Logging err: %s\n", err.Error())
  632. }
  633. }
  634. func (ca *CA) getConfigFileOutput() string {
  635. if ca.config.WasLoadedFromFile() {
  636. return ca.config.Filepath()
  637. }
  638. return "loaded from token"
  639. }
  640. // runCompactJob will run the value log garbage collector if the nosql database
  641. // supports it.
  642. func (ca *CA) runCompactJob() {
  643. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  644. if !ok {
  645. return
  646. }
  647. compactor, ok := caDB.DB.(nosql.Compactor)
  648. if !ok {
  649. return
  650. }
  651. // Compact database at start.
  652. runCompact(compactor)
  653. // Compact database every minute.
  654. ticker := time.NewTicker(time.Minute)
  655. defer ticker.Stop()
  656. for {
  657. select {
  658. case <-ca.compactStop:
  659. return
  660. case <-ticker.C:
  661. runCompact(compactor)
  662. }
  663. }
  664. }
  665. // runCompact executes the compact job until it returns an error.
  666. func runCompact(c nosql.Compactor) {
  667. for err := error(nil); err == nil; {
  668. err = c.Compact(0.7)
  669. }
  670. }