ca.go 10 KB

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