ca.go 15 KB

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