ca.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624
  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"
  17. "github.com/go-chi/chi/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. //Add ACME api endpoints in /acme and /1.0/acme
  173. dns := cfg.DNSNames[0]
  174. u, err := url.Parse("https://" + cfg.Address)
  175. if err != nil {
  176. return nil, err
  177. }
  178. port := u.Port()
  179. if port != "" && port != "443" {
  180. dns = fmt.Sprintf("%s:%s", dns, port)
  181. }
  182. // ACME Router is only available if we have a database.
  183. var acmeDB acme.DB
  184. var acmeLinker acme.Linker
  185. if cfg.DB != nil {
  186. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  187. if err != nil {
  188. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  189. }
  190. acmeLinker = acme.NewLinker(dns, "acme")
  191. mux.Route("/acme", func(r chi.Router) {
  192. acmeAPI.Route(r)
  193. })
  194. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  195. // of the ACME spec.
  196. mux.Route("/2.0/acme", func(r chi.Router) {
  197. acmeAPI.Route(r)
  198. })
  199. }
  200. // Admin API Router
  201. if cfg.AuthorityConfig.EnableAdmin {
  202. adminDB := auth.GetAdminDatabase()
  203. if adminDB != nil {
  204. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  205. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  206. webhookAdminResponder := adminAPI.NewWebhookAdminResponder()
  207. mux.Route("/admin", func(r chi.Router) {
  208. adminAPI.Route(
  209. r,
  210. adminAPI.WithACMEResponder(acmeAdminResponder),
  211. adminAPI.WithPolicyResponder(policyAdminResponder),
  212. adminAPI.WithWebhookResponder(webhookAdminResponder),
  213. )
  214. })
  215. }
  216. }
  217. var scepAuthority *scep.Authority
  218. if ca.shouldServeSCEPEndpoints() {
  219. scepPrefix := "scep"
  220. scepAuthority, err = scep.New(auth, scep.AuthorityOptions{
  221. Service: auth.GetSCEPService(),
  222. DNS: dns,
  223. Prefix: scepPrefix,
  224. })
  225. if err != nil {
  226. return nil, errors.Wrap(err, "error creating SCEP authority")
  227. }
  228. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  229. // SCEP operations are performed using HTTP, so that's why the API is mounted
  230. // to the insecure mux.
  231. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  232. scepAPI.Route(r)
  233. })
  234. // The RFC also mentions usage of HTTPS, but seems to advise
  235. // against it, because of potential interoperability issues.
  236. // Currently I think it's not bad to use HTTPS also, so that's
  237. // why I've kept the API endpoints in both muxes and both HTTP
  238. // as well as HTTPS can be used to request certificates
  239. // using SCEP.
  240. mux.Route("/"+scepPrefix, func(r chi.Router) {
  241. scepAPI.Route(r)
  242. })
  243. }
  244. // helpful routine for logging all routes
  245. //dumpRoutes(mux)
  246. // Add monitoring if configured
  247. if len(cfg.Monitoring) > 0 {
  248. m, err := monitoring.New(cfg.Monitoring)
  249. if err != nil {
  250. return nil, err
  251. }
  252. handler = m.Middleware(handler)
  253. insecureHandler = m.Middleware(insecureHandler)
  254. }
  255. // Add logger if configured
  256. if len(cfg.Logger) > 0 {
  257. logger, err := logging.New("ca", cfg.Logger)
  258. if err != nil {
  259. return nil, err
  260. }
  261. handler = logger.Middleware(handler)
  262. insecureHandler = logger.Middleware(insecureHandler)
  263. }
  264. // Create context with all the necessary values.
  265. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  266. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  267. ca.srv.BaseContext = func(net.Listener) context.Context {
  268. return baseContext
  269. }
  270. // only start the insecure server if the insecure address is configured
  271. // and, currently, also only when it should serve SCEP endpoints.
  272. if ca.shouldServeSCEPEndpoints() && cfg.InsecureAddress != "" {
  273. // TODO: instead opt for having a single server.Server but two
  274. // http.Servers handling the HTTP and HTTPS handler? The latter
  275. // will probably introduce more complexity in terms of graceful
  276. // reload.
  277. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  278. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  279. return baseContext
  280. }
  281. }
  282. return ca, nil
  283. }
  284. // buildContext builds the server base context.
  285. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  286. ctx := authority.NewContext(context.Background(), a)
  287. if authDB := a.GetDatabase(); authDB != nil {
  288. ctx = db.NewContext(ctx, authDB)
  289. }
  290. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  291. ctx = admin.NewContext(ctx, adminDB)
  292. }
  293. if scepAuthority != nil {
  294. ctx = scep.NewContext(ctx, scepAuthority)
  295. }
  296. if acmeDB != nil {
  297. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  298. }
  299. return ctx
  300. }
  301. // Run starts the CA calling to the server ListenAndServe method.
  302. func (ca *CA) Run() error {
  303. var wg sync.WaitGroup
  304. errs := make(chan error, 1)
  305. if !ca.opts.quiet {
  306. authorityInfo := ca.auth.GetInfo()
  307. log.Printf("Starting %s", step.Version())
  308. log.Printf("Documentation: https://u.step.sm/docs/ca")
  309. log.Printf("Community Discord: https://u.step.sm/discord")
  310. if step.Contexts().GetCurrent() != nil {
  311. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  312. }
  313. log.Printf("Config file: %s", ca.getConfigFileOutput())
  314. baseURL := fmt.Sprintf("https://%s%s",
  315. authorityInfo.DNSNames[0],
  316. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  317. log.Printf("The primary server URL is %s", baseURL)
  318. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  319. if len(authorityInfo.DNSNames) > 1 {
  320. log.Printf("Additional configured hostnames: %s",
  321. strings.Join(authorityInfo.DNSNames[1:], ", "))
  322. }
  323. for _, crt := range authorityInfo.RootX509Certs {
  324. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  325. }
  326. if authorityInfo.SSHCAHostPublicKey != nil {
  327. log.Printf("SSH Host CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAHostPublicKey))
  328. }
  329. if authorityInfo.SSHCAUserPublicKey != nil {
  330. log.Printf("SSH User CA Key: %s\n", bytes.TrimSpace(authorityInfo.SSHCAUserPublicKey))
  331. }
  332. }
  333. wg.Add(1)
  334. go func() {
  335. defer wg.Done()
  336. ca.runCompactJob()
  337. }()
  338. if ca.insecureSrv != nil {
  339. wg.Add(1)
  340. go func() {
  341. defer wg.Done()
  342. errs <- ca.insecureSrv.ListenAndServe()
  343. }()
  344. }
  345. wg.Add(1)
  346. go func() {
  347. defer wg.Done()
  348. errs <- ca.srv.ListenAndServe()
  349. }()
  350. // wait till error occurs; ensures the servers keep listening
  351. err := <-errs
  352. wg.Wait()
  353. return err
  354. }
  355. // Stop stops the CA calling to the server Shutdown method.
  356. func (ca *CA) Stop() error {
  357. close(ca.compactStop)
  358. ca.renewer.Stop()
  359. if err := ca.auth.Shutdown(); err != nil {
  360. log.Printf("error stopping ca.Authority: %+v\n", err)
  361. }
  362. var insecureShutdownErr error
  363. if ca.insecureSrv != nil {
  364. insecureShutdownErr = ca.insecureSrv.Shutdown()
  365. }
  366. secureErr := ca.srv.Shutdown()
  367. if insecureShutdownErr != nil {
  368. return insecureShutdownErr
  369. }
  370. return secureErr
  371. }
  372. // Reload reloads the configuration of the CA and calls to the server Reload
  373. // method.
  374. func (ca *CA) Reload() error {
  375. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  376. if err != nil {
  377. return errors.Wrap(err, "error reloading ca configuration")
  378. }
  379. logContinue := func(reason string) {
  380. log.Println(reason)
  381. log.Println("Continuing to run with the original configuration.")
  382. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  383. }
  384. // Do not allow reload if the database configuration has changed.
  385. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  386. logContinue("Reload failed because the database configuration has changed.")
  387. return errors.New("error reloading ca: database configuration cannot change")
  388. }
  389. newCA, err := New(cfg,
  390. WithPassword(ca.opts.password),
  391. WithSSHHostPassword(ca.opts.sshHostPassword),
  392. WithSSHUserPassword(ca.opts.sshUserPassword),
  393. WithIssuerPassword(ca.opts.issuerPassword),
  394. WithLinkedCAToken(ca.opts.linkedCAToken),
  395. WithQuiet(ca.opts.quiet),
  396. WithConfigFile(ca.opts.configFile),
  397. WithDatabase(ca.auth.GetDatabase()),
  398. )
  399. if err != nil {
  400. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  401. return errors.Wrap(err, "error reloading ca")
  402. }
  403. if ca.insecureSrv != nil {
  404. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  405. logContinue("Reload failed because insecure server could not be replaced.")
  406. return errors.Wrap(err, "error reloading insecure server")
  407. }
  408. }
  409. if err = ca.srv.Reload(newCA.srv); err != nil {
  410. logContinue("Reload failed because server could not be replaced.")
  411. return errors.Wrap(err, "error reloading server")
  412. }
  413. // 1. Stop previous renewer
  414. // 2. Safely shutdown any internal resources (e.g. key manager)
  415. // 3. Replace ca properties
  416. // Do not replace ca.srv
  417. ca.renewer.Stop()
  418. ca.auth.CloseForReload()
  419. ca.auth = newCA.auth
  420. ca.config = newCA.config
  421. ca.opts = newCA.opts
  422. ca.renewer = newCA.renewer
  423. return nil
  424. }
  425. // get TLSConfig returns separate TLSConfigs for server and client with the
  426. // same self-renewing certificate.
  427. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, *tls.Config, error) {
  428. // Create initial TLS certificate
  429. tlsCrt, err := auth.GetTLSCertificate()
  430. if err != nil {
  431. return nil, nil, err
  432. }
  433. // Start tls renewer with the new certificate.
  434. // If a renewer was started, attempt to stop it before.
  435. if ca.renewer != nil {
  436. ca.renewer.Stop()
  437. }
  438. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  439. if err != nil {
  440. return nil, nil, err
  441. }
  442. ca.renewer.Run()
  443. var serverTLSConfig *tls.Config
  444. if ca.config.TLS != nil {
  445. serverTLSConfig = ca.config.TLS.TLSConfig()
  446. } else {
  447. serverTLSConfig = &tls.Config{
  448. MinVersion: tls.VersionTLS12,
  449. }
  450. }
  451. // GetCertificate will only be called if the client supplies SNI
  452. // information or if tlsConfig.Certificates is empty.
  453. // When client requests are made using an IP address (as opposed to a domain
  454. // name) the server does not receive any SNI and may fallback to using the
  455. // first entry in the Certificates attribute; by setting the attribute to
  456. // empty we are implicitly forcing GetCertificate to be the only mechanism
  457. // by which the server can find it's own leaf Certificate.
  458. serverTLSConfig.Certificates = []tls.Certificate{}
  459. clientTLSConfig := serverTLSConfig.Clone()
  460. serverTLSConfig.GetCertificate = ca.renewer.GetCertificateForCA
  461. clientTLSConfig.GetClientCertificate = ca.renewer.GetClientCertificate
  462. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  463. certPool := x509.NewCertPool()
  464. // initialize a certificate pool with root CA certificates to trust when connecting
  465. // to webhook servers
  466. rootCAsPool, err := x509.SystemCertPool()
  467. if err != nil {
  468. return nil, nil, err
  469. }
  470. for _, crt := range auth.GetRootCertificates() {
  471. certPool.AddCert(crt)
  472. rootCAsPool.AddCert(crt)
  473. }
  474. // adding the intermediate CA certificates to the pool will allow clients that
  475. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  476. // added here are used when building a certificate chain.
  477. intermediates := tlsCrt.Certificate[1:]
  478. for _, certBytes := range intermediates {
  479. cert, err := x509.ParseCertificate(certBytes)
  480. if err != nil {
  481. return nil, nil, err
  482. }
  483. certPool.AddCert(cert)
  484. rootCAsPool.AddCert(cert)
  485. }
  486. // Add support for mutual tls to renew certificates
  487. serverTLSConfig.ClientAuth = tls.VerifyClientCertIfGiven
  488. serverTLSConfig.ClientCAs = certPool
  489. clientTLSConfig.RootCAs = rootCAsPool
  490. return serverTLSConfig, clientTLSConfig, nil
  491. }
  492. // shouldServeSCEPEndpoints returns if the CA should be
  493. // configured with endpoints for SCEP. This is assumed to be
  494. // true if a SCEPService exists, which is true in case a
  495. // SCEP provisioner was configured.
  496. func (ca *CA) shouldServeSCEPEndpoints() bool {
  497. return ca.auth.GetSCEPService() != nil
  498. }
  499. //nolint:unused // useful for debugging
  500. func dumpRoutes(mux chi.Routes) {
  501. // helpful routine for logging all routes
  502. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  503. fmt.Printf("%s %s\n", method, route)
  504. return nil
  505. }
  506. if err := chi.Walk(mux, walkFunc); err != nil {
  507. fmt.Printf("Logging err: %s\n", err.Error())
  508. }
  509. }
  510. func (ca *CA) getConfigFileOutput() string {
  511. if ca.config.WasLoadedFromFile() {
  512. return ca.config.Filepath()
  513. }
  514. return "loaded from token"
  515. }
  516. // runCompactJob will run the value log garbage collector if the nosql database
  517. // supports it.
  518. func (ca *CA) runCompactJob() {
  519. caDB, ok := ca.auth.GetDatabase().(*db.DB)
  520. if !ok {
  521. return
  522. }
  523. compactor, ok := caDB.DB.(nosql.Compactor)
  524. if !ok {
  525. return
  526. }
  527. // Compact database at start.
  528. runCompact(compactor)
  529. // Compact database every minute.
  530. ticker := time.NewTicker(time.Minute)
  531. defer ticker.Stop()
  532. for {
  533. select {
  534. case <-ca.compactStop:
  535. return
  536. case <-ticker.C:
  537. runCompact(compactor)
  538. }
  539. }
  540. }
  541. // runCompact executes the compact job until it returns an error.
  542. func runCompact(c nosql.Compactor) {
  543. for err := error(nil); err == nil; {
  544. err = c.Compact(0.7)
  545. }
  546. }