ca.go 10 KB

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