ca.go 15 KB

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