ca.go 14 KB

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