ca.go 13 KB

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