ca.go 15 KB

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