ca.go 12 KB

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