ca.go 8.9 KB

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