ca.go 15 KB

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