ca.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  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. opts *options
  63. renewer *TLSRenewer
  64. }
  65. // New creates and initializes the CA with the given configuration and options.
  66. func New(config *authority.Config, opts ...Option) (*CA, error) {
  67. ca := &CA{
  68. config: config,
  69. opts: new(options),
  70. }
  71. ca.opts.apply(opts)
  72. return ca.Init(config)
  73. }
  74. // Init initializes the CA with the given configuration.
  75. func (ca *CA) Init(config *authority.Config) (*CA, error) {
  76. if l := len(ca.opts.password); l > 0 {
  77. ca.config.Password = string(ca.opts.password)
  78. }
  79. var opts []authority.Option
  80. if ca.opts.database != nil {
  81. opts = append(opts, authority.WithDatabase(ca.opts.database))
  82. }
  83. auth, err := authority.New(config, opts...)
  84. if err != nil {
  85. return nil, err
  86. }
  87. tlsConfig, err := ca.getTLSConfig(auth)
  88. if err != nil {
  89. return nil, err
  90. }
  91. // Using chi as the main router
  92. mux := chi.NewRouter()
  93. handler := http.Handler(mux)
  94. // Add regular CA api endpoints in / and /1.0
  95. routerHandler := api.New(auth)
  96. routerHandler.Route(mux)
  97. mux.Route("/1.0", func(r chi.Router) {
  98. routerHandler.Route(r)
  99. })
  100. //Add ACME api endpoints in /acme and /1.0/acme
  101. dns := config.DNSNames[0]
  102. u, err := url.Parse("https://" + config.Address)
  103. if err != nil {
  104. return nil, err
  105. }
  106. port := u.Port()
  107. if port != "" && port != "443" {
  108. dns = fmt.Sprintf("%s:%s", dns, port)
  109. }
  110. prefix := "acme"
  111. acmeAuth, err := acme.New(auth, acme.AuthorityOptions{
  112. Backdate: *config.AuthorityConfig.Backdate,
  113. DB: auth.GetDatabase().(nosql.DB),
  114. DNS: dns,
  115. Prefix: prefix,
  116. })
  117. if err != nil {
  118. return nil, errors.Wrap(err, "error creating ACME authority")
  119. }
  120. acmeRouterHandler := acmeAPI.New(acmeAuth)
  121. mux.Route("/"+prefix, func(r chi.Router) {
  122. acmeRouterHandler.Route(r)
  123. })
  124. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  125. // of the ACME spec.
  126. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  127. acmeRouterHandler.Route(r)
  128. })
  129. // TODO: THIS SHOULDN'T HAPPEN (or should become configurable)
  130. // Current SCEP client I'm testing with doesn't seem to easily trust untrusted certs.
  131. // Idea: provide a second mux/handler that runs without TLS. It probably should only
  132. // have routes that are intended to be ran without TLS, like the SCEP ones. Look into
  133. // option to not enable it in case no SCEP providers are configured. It might
  134. // be nice to still include the SCEP routes in the secure handler too, for
  135. // client that do understand HTTPS. The RFC does not seem to explicitly exclude HTTPS
  136. // usage, but it mentions some caveats related to managing web PKI certificates as
  137. // well as certificates via SCEP.
  138. tlsConfig = nil
  139. // TODO: get the SCEP service
  140. scepPrefix := "scep"
  141. scepAuthority, err := scep.New(auth, scep.AuthorityOptions{
  142. IntermediateCertificatePath: config.IntermediateCert,
  143. Service: auth.GetSCEPService(),
  144. Backdate: *config.AuthorityConfig.Backdate,
  145. DB: auth.GetDatabase().(nosql.DB),
  146. DNS: dns,
  147. Prefix: scepPrefix,
  148. })
  149. if err != nil {
  150. return nil, errors.Wrap(err, "error creating SCEP authority")
  151. }
  152. scepRouterHandler := scepAPI.New(scepAuthority)
  153. mux.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. }
  166. // Add logger if configured
  167. if len(config.Logger) > 0 {
  168. logger, err := logging.New("ca", config.Logger)
  169. if err != nil {
  170. return nil, err
  171. }
  172. handler = logger.Middleware(handler)
  173. }
  174. ca.auth = auth
  175. ca.srv = server.New(config.Address, handler, tlsConfig)
  176. return ca, nil
  177. }
  178. // Run starts the CA calling to the server ListenAndServe method.
  179. func (ca *CA) Run() error {
  180. return ca.srv.ListenAndServe()
  181. }
  182. // Stop stops the CA calling to the server Shutdown method.
  183. func (ca *CA) Stop() error {
  184. ca.renewer.Stop()
  185. if err := ca.auth.Shutdown(); err != nil {
  186. log.Printf("error stopping ca.Authority: %+v\n", err)
  187. }
  188. return ca.srv.Shutdown()
  189. }
  190. // Reload reloads the configuration of the CA and calls to the server Reload
  191. // method.
  192. func (ca *CA) Reload() error {
  193. config, err := authority.LoadConfiguration(ca.opts.configFile)
  194. if err != nil {
  195. return errors.Wrap(err, "error reloading ca configuration")
  196. }
  197. logContinue := func(reason string) {
  198. log.Println(reason)
  199. log.Println("Continuing to run with the original configuration.")
  200. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  201. }
  202. // Do not allow reload if the database configuration has changed.
  203. if !reflect.DeepEqual(ca.config.DB, config.DB) {
  204. logContinue("Reload failed because the database configuration has changed.")
  205. return errors.New("error reloading ca: database configuration cannot change")
  206. }
  207. newCA, err := New(config,
  208. WithPassword(ca.opts.password),
  209. WithConfigFile(ca.opts.configFile),
  210. WithDatabase(ca.auth.GetDatabase()),
  211. )
  212. if err != nil {
  213. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  214. return errors.Wrap(err, "error reloading ca")
  215. }
  216. if err = ca.srv.Reload(newCA.srv); err != nil {
  217. logContinue("Reload failed because server could not be replaced.")
  218. return errors.Wrap(err, "error reloading server")
  219. }
  220. // 1. Stop previous renewer
  221. // 2. Safely shutdown any internal resources (e.g. key manager)
  222. // 3. Replace ca properties
  223. // Do not replace ca.srv
  224. ca.renewer.Stop()
  225. ca.auth.CloseForReload()
  226. ca.auth = newCA.auth
  227. ca.config = newCA.config
  228. ca.opts = newCA.opts
  229. ca.renewer = newCA.renewer
  230. return nil
  231. }
  232. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  233. // server certificate.
  234. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  235. // Create initial TLS certificate
  236. tlsCrt, err := auth.GetTLSCertificate()
  237. if err != nil {
  238. return nil, err
  239. }
  240. // Start tls renewer with the new certificate.
  241. // If a renewer was started, attempt to stop it before.
  242. if ca.renewer != nil {
  243. ca.renewer.Stop()
  244. }
  245. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  246. if err != nil {
  247. return nil, err
  248. }
  249. ca.renewer.Run()
  250. var tlsConfig *tls.Config
  251. if ca.config.TLS != nil {
  252. tlsConfig = ca.config.TLS.TLSConfig()
  253. } else {
  254. tlsConfig = &tls.Config{
  255. MinVersion: tls.VersionTLS12,
  256. }
  257. }
  258. certPool := x509.NewCertPool()
  259. for _, crt := range auth.GetRootCertificates() {
  260. certPool.AddCert(crt)
  261. }
  262. // GetCertificate will only be called if the client supplies SNI
  263. // information or if tlsConfig.Certificates is empty.
  264. // When client requests are made using an IP address (as opposed to a domain
  265. // name) the server does not receive any SNI and may fallback to using the
  266. // first entry in the Certificates attribute; by setting the attribute to
  267. // empty we are implicitly forcing GetCertificate to be the only mechanism
  268. // by which the server can find it's own leaf Certificate.
  269. tlsConfig.Certificates = []tls.Certificate{}
  270. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  271. // Add support for mutual tls to renew certificates
  272. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  273. tlsConfig.ClientCAs = certPool
  274. // Use server's most preferred ciphersuite
  275. tlsConfig.PreferServerCipherSuites = true
  276. return tlsConfig, nil
  277. }
  278. func dumpRoutes(mux chi.Routes) {
  279. // helpful routine for logging all routes //
  280. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  281. fmt.Printf("%s %s\n", method, route)
  282. return nil
  283. }
  284. if err := chi.Walk(mux, walkFunc); err != nil {
  285. fmt.Printf("Logging err: %s\n", err.Error())
  286. }
  287. }