ca.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478
  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. policyAdminResponder := adminAPI.NewPolicyAdminResponder(auth, adminDB)
  188. adminHandler := adminAPI.NewHandler(auth, adminDB, acmeDB, acmeAdminResponder, policyAdminResponder)
  189. mux.Route("/admin", func(r chi.Router) {
  190. adminHandler.Route(r)
  191. })
  192. }
  193. }
  194. if ca.shouldServeSCEPEndpoints() {
  195. scepPrefix := "scep"
  196. scepAuthority, err := scep.New(auth, scep.AuthorityOptions{
  197. Service: auth.GetSCEPService(),
  198. DNS: dns,
  199. Prefix: scepPrefix,
  200. })
  201. if err != nil {
  202. return nil, errors.Wrap(err, "error creating SCEP authority")
  203. }
  204. scepRouterHandler := scepAPI.New(scepAuthority)
  205. // According to the RFC (https://tools.ietf.org/html/rfc8894#section-7.10),
  206. // SCEP operations are performed using HTTP, so that's why the API is mounted
  207. // to the insecure mux.
  208. insecureMux.Route("/"+scepPrefix, func(r chi.Router) {
  209. scepRouterHandler.Route(r)
  210. })
  211. // The RFC also mentions usage of HTTPS, but seems to advise
  212. // against it, because of potential interoperability issues.
  213. // Currently I think it's not bad to use HTTPS also, so that's
  214. // why I've kept the API endpoints in both muxes and both HTTP
  215. // as well as HTTPS can be used to request certificates
  216. // using SCEP.
  217. mux.Route("/"+scepPrefix, func(r chi.Router) {
  218. scepRouterHandler.Route(r)
  219. })
  220. }
  221. // helpful routine for logging all routes
  222. //dumpRoutes(mux)
  223. // Add monitoring if configured
  224. if len(cfg.Monitoring) > 0 {
  225. m, err := monitoring.New(cfg.Monitoring)
  226. if err != nil {
  227. return nil, err
  228. }
  229. handler = m.Middleware(handler)
  230. insecureHandler = m.Middleware(insecureHandler)
  231. }
  232. // Add logger if configured
  233. if len(cfg.Logger) > 0 {
  234. logger, err := logging.New("ca", cfg.Logger)
  235. if err != nil {
  236. return nil, err
  237. }
  238. handler = logger.Middleware(handler)
  239. insecureHandler = logger.Middleware(insecureHandler)
  240. }
  241. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  242. // only start the insecure server if the insecure address is configured
  243. // and, currently, also only when it should serve SCEP endpoints.
  244. if ca.shouldServeSCEPEndpoints() && cfg.InsecureAddress != "" {
  245. // TODO: instead opt for having a single server.Server but two
  246. // http.Servers handling the HTTP and HTTPS handler? The latter
  247. // will probably introduce more complexity in terms of graceful
  248. // reload.
  249. ca.insecureSrv = server.New(cfg.InsecureAddress, insecureHandler, nil)
  250. }
  251. return ca, nil
  252. }
  253. // Run starts the CA calling to the server ListenAndServe method.
  254. func (ca *CA) Run() error {
  255. var wg sync.WaitGroup
  256. errs := make(chan error, 1)
  257. if ca.insecureSrv != nil {
  258. wg.Add(1)
  259. go func() {
  260. defer wg.Done()
  261. errs <- ca.insecureSrv.ListenAndServe()
  262. }()
  263. }
  264. wg.Add(1)
  265. go func() {
  266. defer wg.Done()
  267. errs <- ca.srv.ListenAndServe()
  268. }()
  269. // wait till error occurs; ensures the servers keep listening
  270. err := <-errs
  271. wg.Wait()
  272. return err
  273. }
  274. // Stop stops the CA calling to the server Shutdown method.
  275. func (ca *CA) Stop() error {
  276. ca.renewer.Stop()
  277. if err := ca.auth.Shutdown(); err != nil {
  278. log.Printf("error stopping ca.Authority: %+v\n", err)
  279. }
  280. var insecureShutdownErr error
  281. if ca.insecureSrv != nil {
  282. insecureShutdownErr = ca.insecureSrv.Shutdown()
  283. }
  284. secureErr := ca.srv.Shutdown()
  285. if insecureShutdownErr != nil {
  286. return insecureShutdownErr
  287. }
  288. return secureErr
  289. }
  290. // Reload reloads the configuration of the CA and calls to the server Reload
  291. // method.
  292. func (ca *CA) Reload() error {
  293. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  294. if err != nil {
  295. return errors.Wrap(err, "error reloading ca configuration")
  296. }
  297. logContinue := func(reason string) {
  298. log.Println(reason)
  299. log.Println("Continuing to run with the original configuration.")
  300. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  301. }
  302. // Do not allow reload if the database configuration has changed.
  303. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  304. logContinue("Reload failed because the database configuration has changed.")
  305. return errors.New("error reloading ca: database configuration cannot change")
  306. }
  307. newCA, err := New(cfg,
  308. WithPassword(ca.opts.password),
  309. WithSSHHostPassword(ca.opts.sshHostPassword),
  310. WithSSHUserPassword(ca.opts.sshUserPassword),
  311. WithIssuerPassword(ca.opts.issuerPassword),
  312. WithLinkedCAToken(ca.opts.linkedCAToken),
  313. WithConfigFile(ca.opts.configFile),
  314. WithDatabase(ca.auth.GetDatabase()),
  315. )
  316. if err != nil {
  317. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  318. return errors.Wrap(err, "error reloading ca")
  319. }
  320. if ca.insecureSrv != nil {
  321. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  322. logContinue("Reload failed because insecure server could not be replaced.")
  323. return errors.Wrap(err, "error reloading insecure server")
  324. }
  325. }
  326. if err = ca.srv.Reload(newCA.srv); err != nil {
  327. logContinue("Reload failed because server could not be replaced.")
  328. return errors.Wrap(err, "error reloading server")
  329. }
  330. // 1. Stop previous renewer
  331. // 2. Safely shutdown any internal resources (e.g. key manager)
  332. // 3. Replace ca properties
  333. // Do not replace ca.srv
  334. ca.renewer.Stop()
  335. ca.auth.CloseForReload()
  336. ca.auth = newCA.auth
  337. ca.config = newCA.config
  338. ca.opts = newCA.opts
  339. ca.renewer = newCA.renewer
  340. return nil
  341. }
  342. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  343. // server certificate.
  344. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  345. // Create initial TLS certificate
  346. tlsCrt, err := auth.GetTLSCertificate()
  347. if err != nil {
  348. return nil, err
  349. }
  350. // Start tls renewer with the new certificate.
  351. // If a renewer was started, attempt to stop it before.
  352. if ca.renewer != nil {
  353. ca.renewer.Stop()
  354. }
  355. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  356. if err != nil {
  357. return nil, err
  358. }
  359. ca.renewer.Run()
  360. var tlsConfig *tls.Config
  361. if ca.config.TLS != nil {
  362. tlsConfig = ca.config.TLS.TLSConfig()
  363. } else {
  364. tlsConfig = &tls.Config{
  365. MinVersion: tls.VersionTLS12,
  366. }
  367. }
  368. // GetCertificate will only be called if the client supplies SNI
  369. // information or if tlsConfig.Certificates is empty.
  370. // When client requests are made using an IP address (as opposed to a domain
  371. // name) the server does not receive any SNI and may fallback to using the
  372. // first entry in the Certificates attribute; by setting the attribute to
  373. // empty we are implicitly forcing GetCertificate to be the only mechanism
  374. // by which the server can find it's own leaf Certificate.
  375. tlsConfig.Certificates = []tls.Certificate{}
  376. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  377. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  378. certPool := x509.NewCertPool()
  379. for _, crt := range auth.GetRootCertificates() {
  380. certPool.AddCert(crt)
  381. }
  382. // adding the intermediate CA certificates to the pool will allow clients that
  383. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  384. // added here are used when building a certificate chain.
  385. intermediates := tlsCrt.Certificate[1:]
  386. for _, certBytes := range intermediates {
  387. cert, err := x509.ParseCertificate(certBytes)
  388. if err != nil {
  389. return nil, err
  390. }
  391. certPool.AddCert(cert)
  392. }
  393. // Add support for mutual tls to renew certificates
  394. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  395. tlsConfig.ClientCAs = certPool
  396. // Use server's most preferred ciphersuite
  397. tlsConfig.PreferServerCipherSuites = true
  398. return tlsConfig, nil
  399. }
  400. // shouldServeSCEPEndpoints returns if the CA should be
  401. // configured with endpoints for SCEP. This is assumed to be
  402. // true if a SCEPService exists, which is true in case a
  403. // SCEP provisioner was configured.
  404. func (ca *CA) shouldServeSCEPEndpoints() bool {
  405. return ca.auth.GetSCEPService() != nil
  406. }
  407. //nolint // ignore linters to allow keeping this function around for debugging
  408. func dumpRoutes(mux chi.Routes) {
  409. // helpful routine for logging all routes //
  410. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  411. fmt.Printf("%s %s\n", method, route)
  412. return nil
  413. }
  414. if err := chi.Walk(mux, walkFunc); err != nil {
  415. fmt.Printf("Logging err: %s\n", err.Error())
  416. }
  417. }