ca.go 17 KB

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