ca.go 13 KB

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