ca.go 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318
  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/db"
  18. "github.com/smallstep/certificates/logging"
  19. "github.com/smallstep/certificates/monitoring"
  20. "github.com/smallstep/certificates/server"
  21. "github.com/smallstep/nosql"
  22. )
  23. type options struct {
  24. configFile string
  25. password []byte
  26. issuerPassword []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. // WithIssuerPassword sets the given password as the configured certificate
  51. // issuer password in the CA options.
  52. func WithIssuerPassword(password []byte) Option {
  53. return func(o *options) {
  54. o.issuerPassword = password
  55. }
  56. }
  57. // WithDatabase sets the given authority database to the CA options.
  58. func WithDatabase(db db.AuthDB) Option {
  59. return func(o *options) {
  60. o.database = db
  61. }
  62. }
  63. // CA is the type used to build the complete certificate authority. It builds
  64. // the HTTP server, set ups the middlewares and the HTTP handlers.
  65. type CA struct {
  66. auth *authority.Authority
  67. config *authority.Config
  68. srv *server.Server
  69. opts *options
  70. renewer *TLSRenewer
  71. }
  72. // New creates and initializes the CA with the given configuration and options.
  73. func New(config *authority.Config, opts ...Option) (*CA, error) {
  74. ca := &CA{
  75. config: config,
  76. opts: new(options),
  77. }
  78. ca.opts.apply(opts)
  79. return ca.Init(config)
  80. }
  81. // Init initializes the CA with the given configuration.
  82. func (ca *CA) Init(config *authority.Config) (*CA, error) {
  83. // Intermediate Password.
  84. if len(ca.opts.password) > 0 {
  85. ca.config.Password = string(ca.opts.password)
  86. }
  87. // Certificate issuer password for RA mode.
  88. if len(ca.opts.issuerPassword) > 0 {
  89. if ca.config.AuthorityConfig != nil && ca.config.AuthorityConfig.CertificateIssuer != nil {
  90. ca.config.AuthorityConfig.CertificateIssuer.Password = string(ca.opts.issuerPassword)
  91. }
  92. }
  93. var opts []authority.Option
  94. if ca.opts.database != nil {
  95. opts = append(opts, authority.WithDatabase(ca.opts.database))
  96. }
  97. auth, err := authority.New(config, opts...)
  98. if err != nil {
  99. return nil, err
  100. }
  101. tlsConfig, err := ca.getTLSConfig(auth)
  102. if err != nil {
  103. return nil, err
  104. }
  105. // Using chi as the main router
  106. mux := chi.NewRouter()
  107. handler := http.Handler(mux)
  108. // Add regular CA api endpoints in / and /1.0
  109. routerHandler := api.New(auth)
  110. routerHandler.Route(mux)
  111. mux.Route("/1.0", func(r chi.Router) {
  112. routerHandler.Route(r)
  113. })
  114. //Add ACME api endpoints in /acme and /1.0/acme
  115. dns := config.DNSNames[0]
  116. u, err := url.Parse("https://" + config.Address)
  117. if err != nil {
  118. return nil, err
  119. }
  120. port := u.Port()
  121. if port != "" && port != "443" {
  122. dns = fmt.Sprintf("%s:%s", dns, port)
  123. }
  124. prefix := "acme"
  125. var acmeDB acme.DB
  126. if config.DB == nil {
  127. acmeDB = nil
  128. } else {
  129. acmeDB, err = acmeNoSQL.New(auth.GetDatabase().(nosql.DB))
  130. if err != nil {
  131. return nil, errors.Wrap(err, "error configuring ACME DB interface")
  132. }
  133. }
  134. acmeHandler := acmeAPI.NewHandler(acmeAPI.HandlerOptions{
  135. Backdate: *config.AuthorityConfig.Backdate,
  136. DB: acmeDB,
  137. DNS: dns,
  138. Prefix: prefix,
  139. CA: auth,
  140. })
  141. mux.Route("/"+prefix, func(r chi.Router) {
  142. acmeHandler.Route(r)
  143. })
  144. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  145. // of the ACME spec.
  146. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  147. acmeHandler.Route(r)
  148. })
  149. // helpful routine for logging all routes //
  150. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  151. fmt.Printf("%s %s\n", method, route)
  152. return nil
  153. }
  154. if err := chi.Walk(mux, walkFunc); err != nil {
  155. fmt.Printf("Logging err: %s\n", err.Error())
  156. }
  157. // Add monitoring if configured
  158. if len(config.Monitoring) > 0 {
  159. m, err := monitoring.New(config.Monitoring)
  160. if err != nil {
  161. return nil, err
  162. }
  163. handler = m.Middleware(handler)
  164. }
  165. // Add logger if configured
  166. if len(config.Logger) > 0 {
  167. logger, err := logging.New("ca", config.Logger)
  168. if err != nil {
  169. return nil, err
  170. }
  171. handler = logger.Middleware(handler)
  172. }
  173. ca.auth = auth
  174. ca.srv = server.New(config.Address, handler, tlsConfig)
  175. return ca, nil
  176. }
  177. // Run starts the CA calling to the server ListenAndServe method.
  178. func (ca *CA) Run() error {
  179. return ca.srv.ListenAndServe()
  180. }
  181. // Stop stops the CA calling to the server Shutdown method.
  182. func (ca *CA) Stop() error {
  183. ca.renewer.Stop()
  184. if err := ca.auth.Shutdown(); err != nil {
  185. log.Printf("error stopping ca.Authority: %+v\n", err)
  186. }
  187. return ca.srv.Shutdown()
  188. }
  189. // Reload reloads the configuration of the CA and calls to the server Reload
  190. // method.
  191. func (ca *CA) Reload() error {
  192. config, err := authority.LoadConfiguration(ca.opts.configFile)
  193. if err != nil {
  194. return errors.Wrap(err, "error reloading ca configuration")
  195. }
  196. logContinue := func(reason string) {
  197. log.Println(reason)
  198. log.Println("Continuing to run with the original configuration.")
  199. log.Println("You can force a restart by sending a SIGTERM signal and then restarting the step-ca.")
  200. }
  201. // Do not allow reload if the database configuration has changed.
  202. if !reflect.DeepEqual(ca.config.DB, config.DB) {
  203. logContinue("Reload failed because the database configuration has changed.")
  204. return errors.New("error reloading ca: database configuration cannot change")
  205. }
  206. newCA, err := New(config,
  207. WithPassword(ca.opts.password),
  208. WithIssuerPassword(ca.opts.issuerPassword),
  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. }