ca.go 11 KB

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