ca.go 18 KB

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