ca.go 15 KB

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