ca.go 16 KB

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