4
0

ca.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. package ca
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "crypto/x509"
  6. "fmt"
  7. "log"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "reflect"
  12. "strings"
  13. "sync"
  14. "github.com/go-chi/chi"
  15. "github.com/pkg/errors"
  16. "github.com/smallstep/certificates/acme"
  17. acmeAPI "github.com/smallstep/certificates/acme/api"
  18. acmeNoSQL "github.com/smallstep/certificates/acme/db/nosql"
  19. "github.com/smallstep/certificates/api"
  20. "github.com/smallstep/certificates/authority"
  21. "github.com/smallstep/certificates/authority/admin"
  22. adminAPI "github.com/smallstep/certificates/authority/admin/api"
  23. "github.com/smallstep/certificates/authority/config"
  24. "github.com/smallstep/certificates/db"
  25. "github.com/smallstep/certificates/logging"
  26. "github.com/smallstep/certificates/monitoring"
  27. "github.com/smallstep/certificates/scep"
  28. scepAPI "github.com/smallstep/certificates/scep/api"
  29. "github.com/smallstep/certificates/server"
  30. "github.com/smallstep/nosql"
  31. "go.step.sm/cli-utils/step"
  32. "go.step.sm/crypto/x509util"
  33. )
  34. type options struct {
  35. configFile string
  36. linkedCAToken string
  37. quiet bool
  38. password []byte
  39. issuerPassword []byte
  40. sshHostPassword []byte
  41. sshUserPassword []byte
  42. database db.AuthDB
  43. }
  44. func (o *options) apply(opts []Option) {
  45. for _, fn := range opts {
  46. fn(o)
  47. }
  48. }
  49. // Option is the type of options passed to the CA constructor.
  50. type Option func(o *options)
  51. // WithConfigFile sets the given name as the configuration file name in the CA
  52. // options.
  53. func WithConfigFile(name string) Option {
  54. return func(o *options) {
  55. o.configFile = name
  56. }
  57. }
  58. // WithPassword sets the given password as the configured password in the CA
  59. // options.
  60. func WithPassword(password []byte) Option {
  61. return func(o *options) {
  62. o.password = password
  63. }
  64. }
  65. // WithSSHHostPassword sets the given password to decrypt the key used to sign
  66. // ssh host certificates.
  67. func WithSSHHostPassword(password []byte) Option {
  68. return func(o *options) {
  69. o.sshHostPassword = password
  70. }
  71. }
  72. // WithSSHUserPassword sets the given password to decrypt the key used to sign
  73. // ssh user certificates.
  74. func WithSSHUserPassword(password []byte) Option {
  75. return func(o *options) {
  76. o.sshUserPassword = password
  77. }
  78. }
  79. // WithIssuerPassword sets the given password as the configured certificate
  80. // issuer password in the CA options.
  81. func WithIssuerPassword(password []byte) Option {
  82. return func(o *options) {
  83. o.issuerPassword = password
  84. }
  85. }
  86. // WithDatabase sets the given authority database to the CA options.
  87. func WithDatabase(d db.AuthDB) Option {
  88. return func(o *options) {
  89. o.database = d
  90. }
  91. }
  92. // WithLinkedCAToken sets the token used to authenticate with the linkedca.
  93. func WithLinkedCAToken(token string) Option {
  94. return func(o *options) {
  95. o.linkedCAToken = token
  96. }
  97. }
  98. // WithQuiet sets the quiet flag.
  99. func WithQuiet(quiet bool) Option {
  100. return func(o *options) {
  101. o.quiet = quiet
  102. }
  103. }
  104. // CA is the type used to build the complete certificate authority. It builds
  105. // the HTTP server, set ups the middlewares and the HTTP handlers.
  106. type CA struct {
  107. auth *authority.Authority
  108. config *config.Config
  109. srv *server.Server
  110. insecureSrv *server.Server
  111. opts *options
  112. renewer *TLSRenewer
  113. }
  114. // New creates and initializes the CA with the given configuration and options.
  115. func New(cfg *config.Config, opts ...Option) (*CA, error) {
  116. ca := &CA{
  117. config: cfg,
  118. opts: new(options),
  119. }
  120. ca.opts.apply(opts)
  121. return ca.Init(cfg)
  122. }
  123. // Init initializes the CA with the given configuration.
  124. func (ca *CA) Init(cfg *config.Config) (*CA, error) {
  125. // Set password, it's ok to set nil password, the ca will prompt for them if
  126. // they are required.
  127. opts := []authority.Option{
  128. authority.WithPassword(ca.opts.password),
  129. authority.WithSSHHostPassword(ca.opts.sshHostPassword),
  130. authority.WithSSHUserPassword(ca.opts.sshUserPassword),
  131. authority.WithIssuerPassword(ca.opts.issuerPassword),
  132. }
  133. if ca.opts.linkedCAToken != "" {
  134. opts = append(opts, authority.WithLinkedCAToken(ca.opts.linkedCAToken))
  135. }
  136. if ca.opts.database != nil {
  137. opts = append(opts, authority.WithDatabase(ca.opts.database))
  138. }
  139. auth, err := authority.New(cfg, opts...)
  140. if err != nil {
  141. return nil, err
  142. }
  143. ca.auth = auth
  144. tlsConfig, err := ca.getTLSConfig(auth)
  145. if err != nil {
  146. return nil, err
  147. }
  148. // Using chi as the main router
  149. mux := chi.NewRouter()
  150. handler := http.Handler(mux)
  151. // Add regular CA api endpoints in / and /1.0
  152. api.Route(mux)
  153. mux.Route("/1.0", func(r chi.Router) {
  154. api.Route(r)
  155. })
  156. //Add ACME api endpoints in /acme and /1.0/acme
  157. dns := cfg.DNSNames[0]
  158. u, err := url.Parse("https://" + cfg.Address)
  159. if err != nil {
  160. return nil, err
  161. }
  162. port := u.Port()
  163. if port != "" && port != "443" {
  164. dns = fmt.Sprintf("%s:%s", dns, port)
  165. }
  166. // ACME Router is only available if we have a database.
  167. var acmeDB acme.DB
  168. var acmeLinker acme.Linker
  169. if cfg.DB != nil {
  170. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  171. if err != nil {
  172. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  173. }
  174. acmeLinker = acme.NewLinker(dns, "acme")
  175. mux.Route("/acme", func(r chi.Router) {
  176. acmeAPI.Route(r)
  177. })
  178. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  179. // of the ACME spec.
  180. mux.Route("/2.0/acme", func(r chi.Router) {
  181. acmeAPI.Route(r)
  182. })
  183. }
  184. // Admin API Router
  185. if cfg.AuthorityConfig.EnableAdmin {
  186. adminDB := auth.GetAdminDatabase()
  187. if adminDB != nil {
  188. acmeAdminResponder := adminAPI.NewACMEAdminResponder()
  189. policyAdminResponder := adminAPI.NewPolicyAdminResponder()
  190. mux.Route("/admin", func(r chi.Router) {
  191. adminAPI.Route(r, acmeAdminResponder, policyAdminResponder)
  192. })
  193. }
  194. }
  195. var scepAuthority *scep.Authority
  196. if ca.shouldServeSCEPEndpoints() {
  197. scepPrefix := "scep"
  198. scepAuthority, err = scep.New(auth, scep.AuthorityOptions{
  199. Service: auth.GetSCEPService(),
  200. DNS: dns,
  201. Prefix: scepPrefix,
  202. })
  203. if err != nil {
  204. return nil, errors.Wrap(err, "error creating SCEP authority")
  205. }
  206. // The RFC also mentions usage of HTTPS, but seems to advise
  207. // against it, because of potential interoperability issues.
  208. // Currently I think it's not bad to use HTTPS also, so that's
  209. // why I've kept the API endpoints in both muxes and both HTTP
  210. // as well as HTTPS can be used to request certificates
  211. // using SCEP.
  212. mux.Route("/"+scepPrefix, func(r chi.Router) {
  213. scepAPI.Route(r)
  214. })
  215. }
  216. // helpful routine for logging all routes
  217. //dumpRoutes(mux)
  218. // Add monitoring if configured
  219. if len(cfg.Monitoring) > 0 {
  220. m, err := monitoring.New(cfg.Monitoring)
  221. if err != nil {
  222. return nil, err
  223. }
  224. handler = m.Middleware(handler)
  225. }
  226. // Add logger if configured
  227. if len(cfg.Logger) > 0 {
  228. logger, err := logging.New("ca", cfg.Logger)
  229. if err != nil {
  230. return nil, err
  231. }
  232. handler = logger.Middleware(handler)
  233. }
  234. // Create context with all the necessary values.
  235. baseContext := buildContext(auth, scepAuthority, acmeDB, acmeLinker)
  236. if cfg.Address != "" {
  237. ca.srv = server.New(cfg.Address, handler, tlsConfig)
  238. ca.srv.BaseContext = func(net.Listener) context.Context {
  239. return baseContext
  240. }
  241. }
  242. if 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, handler, nil)
  248. ca.insecureSrv.BaseContext = func(net.Listener) context.Context {
  249. return baseContext
  250. }
  251. }
  252. return ca, nil
  253. }
  254. // buildContext builds the server base context.
  255. func buildContext(a *authority.Authority, scepAuthority *scep.Authority, acmeDB acme.DB, acmeLinker acme.Linker) context.Context {
  256. ctx := authority.NewContext(context.Background(), a)
  257. if authDB := a.GetDatabase(); authDB != nil {
  258. ctx = db.NewContext(ctx, authDB)
  259. }
  260. if adminDB := a.GetAdminDatabase(); adminDB != nil {
  261. ctx = admin.NewContext(ctx, adminDB)
  262. }
  263. if scepAuthority != nil {
  264. ctx = scep.NewContext(ctx, scepAuthority)
  265. }
  266. if acmeDB != nil {
  267. ctx = acme.NewContext(ctx, acmeDB, acme.NewClient(), acmeLinker, nil)
  268. }
  269. return ctx
  270. }
  271. // Run starts the CA calling to the server ListenAndServe method.
  272. func (ca *CA) Run() error {
  273. var wg sync.WaitGroup
  274. errs := make(chan error, 1)
  275. if !ca.opts.quiet {
  276. authorityInfo := ca.auth.GetInfo()
  277. log.Printf("Starting %s", step.Version())
  278. log.Printf("Documentation: https://u.step.sm/docs/ca")
  279. log.Printf("Community Discord: https://u.step.sm/discord")
  280. if step.Contexts().GetCurrent() != nil {
  281. log.Printf("Current context: %s", step.Contexts().GetCurrent().Name)
  282. }
  283. log.Printf("Config file: %s", ca.opts.configFile)
  284. if ca.config.Address != "" {
  285. baseURL := fmt.Sprintf("https://%s%s",
  286. authorityInfo.DNSNames[0],
  287. ca.config.Address[strings.LastIndex(ca.config.Address, ":"):])
  288. log.Printf("The primary server URL is %s", baseURL)
  289. log.Printf("Root certificates are available at %s/roots.pem", baseURL)
  290. }
  291. if len(authorityInfo.DNSNames) > 1 {
  292. log.Printf("Additional configured hostnames: %s",
  293. strings.Join(authorityInfo.DNSNames[1:], ", "))
  294. }
  295. for _, crt := range authorityInfo.RootX509Certs {
  296. log.Printf("X.509 Root Fingerprint: %s", x509util.Fingerprint(crt))
  297. }
  298. if authorityInfo.SSHCAHostPublicKey != nil {
  299. log.Printf("SSH Host CA Key: %s\n", authorityInfo.SSHCAHostPublicKey)
  300. }
  301. if authorityInfo.SSHCAUserPublicKey != nil {
  302. log.Printf("SSH User CA Key: %s\n", authorityInfo.SSHCAUserPublicKey)
  303. }
  304. }
  305. if ca.insecureSrv != nil {
  306. wg.Add(1)
  307. go func() {
  308. defer wg.Done()
  309. errs <- ca.insecureSrv.ListenAndServe()
  310. }()
  311. }
  312. if ca.srv != nil {
  313. wg.Add(1)
  314. go func() {
  315. defer wg.Done()
  316. errs <- ca.srv.ListenAndServe()
  317. }()
  318. }
  319. // wait till error occurs; ensures the servers keep listening
  320. err := <-errs
  321. wg.Wait()
  322. return err
  323. }
  324. // Stop stops the CA calling to the server Shutdown method.
  325. func (ca *CA) Stop() error {
  326. ca.renewer.Stop()
  327. if err := ca.auth.Shutdown(); err != nil {
  328. log.Printf("error stopping ca.Authority: %+v\n", err)
  329. }
  330. var insecureShutdownErr error
  331. if ca.insecureSrv != nil {
  332. insecureShutdownErr = ca.insecureSrv.Shutdown()
  333. }
  334. secureErr := ca.srv.Shutdown()
  335. if insecureShutdownErr != nil {
  336. return insecureShutdownErr
  337. }
  338. return secureErr
  339. }
  340. // Reload reloads the configuration of the CA and calls to the server Reload
  341. // method.
  342. func (ca *CA) Reload() error {
  343. cfg, err := config.LoadConfiguration(ca.opts.configFile)
  344. if err != nil {
  345. return errors.Wrap(err, "error reloading ca configuration")
  346. }
  347. logContinue := func(reason string) {
  348. log.Println(reason)
  349. log.Println("Continuing to run with the original configuration.")
  350. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  351. }
  352. // Do not allow reload if the database configuration has changed.
  353. if !reflect.DeepEqual(ca.config.DB, cfg.DB) {
  354. logContinue("Reload failed because the database configuration has changed.")
  355. return errors.New("error reloading ca: database configuration cannot change")
  356. }
  357. newCA, err := New(cfg,
  358. WithPassword(ca.opts.password),
  359. WithSSHHostPassword(ca.opts.sshHostPassword),
  360. WithSSHUserPassword(ca.opts.sshUserPassword),
  361. WithIssuerPassword(ca.opts.issuerPassword),
  362. WithLinkedCAToken(ca.opts.linkedCAToken),
  363. WithQuiet(ca.opts.quiet),
  364. WithConfigFile(ca.opts.configFile),
  365. WithDatabase(ca.auth.GetDatabase()),
  366. )
  367. if err != nil {
  368. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  369. return errors.Wrap(err, "error reloading ca")
  370. }
  371. if ca.insecureSrv != nil {
  372. if err = ca.insecureSrv.Reload(newCA.insecureSrv); err != nil {
  373. logContinue("Reload failed because insecure server could not be replaced.")
  374. return errors.Wrap(err, "error reloading insecure server")
  375. }
  376. }
  377. if err = ca.srv.Reload(newCA.srv); err != nil {
  378. logContinue("Reload failed because server could not be replaced.")
  379. return errors.Wrap(err, "error reloading server")
  380. }
  381. // 1. Stop previous renewer
  382. // 2. Safely shutdown any internal resources (e.g. key manager)
  383. // 3. Replace ca properties
  384. // Do not replace ca.srv
  385. ca.renewer.Stop()
  386. ca.auth.CloseForReload()
  387. ca.auth = newCA.auth
  388. ca.config = newCA.config
  389. ca.opts = newCA.opts
  390. ca.renewer = newCA.renewer
  391. return nil
  392. }
  393. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  394. // server certificate.
  395. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  396. // Create initial TLS certificate
  397. tlsCrt, err := auth.GetTLSCertificate()
  398. if err != nil {
  399. return nil, err
  400. }
  401. // Start tls renewer with the new certificate.
  402. // If a renewer was started, attempt to stop it before.
  403. if ca.renewer != nil {
  404. ca.renewer.Stop()
  405. }
  406. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  407. if err != nil {
  408. return nil, err
  409. }
  410. ca.renewer.Run()
  411. var tlsConfig *tls.Config
  412. if ca.config.TLS != nil {
  413. tlsConfig = ca.config.TLS.TLSConfig()
  414. } else {
  415. tlsConfig = &tls.Config{
  416. MinVersion: tls.VersionTLS12,
  417. }
  418. }
  419. // GetCertificate will only be called if the client supplies SNI
  420. // information or if tlsConfig.Certificates is empty.
  421. // When client requests are made using an IP address (as opposed to a domain
  422. // name) the server does not receive any SNI and may fallback to using the
  423. // first entry in the Certificates attribute; by setting the attribute to
  424. // empty we are implicitly forcing GetCertificate to be the only mechanism
  425. // by which the server can find it's own leaf Certificate.
  426. tlsConfig.Certificates = []tls.Certificate{}
  427. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  428. // initialize a certificate pool with root CA certificates to trust when doing mTLS.
  429. certPool := x509.NewCertPool()
  430. for _, crt := range auth.GetRootCertificates() {
  431. certPool.AddCert(crt)
  432. }
  433. // adding the intermediate CA certificates to the pool will allow clients that
  434. // do mTLS but don't send an intermediate to successfully connect. The intermediates
  435. // added here are used when building a certificate chain.
  436. intermediates := tlsCrt.Certificate[1:]
  437. for _, certBytes := range intermediates {
  438. cert, err := x509.ParseCertificate(certBytes)
  439. if err != nil {
  440. return nil, err
  441. }
  442. certPool.AddCert(cert)
  443. }
  444. // Add support for mutual tls to renew certificates
  445. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  446. tlsConfig.ClientCAs = certPool
  447. return tlsConfig, nil
  448. }
  449. // shouldServeSCEPEndpoints returns if the CA should be
  450. // configured with endpoints for SCEP. This is assumed to be
  451. // true if a SCEPService exists, which is true in case a
  452. // SCEP provisioner was configured.
  453. func (ca *CA) shouldServeSCEPEndpoints() bool {
  454. return ca.auth.GetSCEPService() != nil
  455. }
  456. // nolint // ignore linters to allow keeping this function around for debugging
  457. func dumpRoutes(mux chi.Routes) {
  458. // helpful routine for logging all routes //
  459. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  460. fmt.Printf("%s %s\n", method, route)
  461. return nil
  462. }
  463. if err := chi.Walk(mux, walkFunc); err != nil {
  464. fmt.Printf("Logging err: %s\n", err.Error())
  465. }
  466. }