ca.go 12 KB

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