ca.go 15 KB

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