ca.go 15 KB

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