ca.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. "github.com/smallstep/certificates/server"
  21. "github.com/smallstep/nosql"
  22. )
  23. type options struct {
  24. configFile string
  25. password []byte
  26. database db.AuthDB
  27. }
  28. func (o *options) apply(opts []Option) {
  29. for _, fn := range opts {
  30. fn(o)
  31. }
  32. }
  33. // Option is the type of options passed to the CA constructor.
  34. type Option func(o *options)
  35. // WithConfigFile sets the given name as the configuration file name in the CA
  36. // options.
  37. func WithConfigFile(name string) Option {
  38. return func(o *options) {
  39. o.configFile = name
  40. }
  41. }
  42. // WithPassword sets the given password as the configured password in the CA
  43. // options.
  44. func WithPassword(password []byte) Option {
  45. return func(o *options) {
  46. o.password = password
  47. }
  48. }
  49. // WithDatabase sets the given authority database to the CA options.
  50. func WithDatabase(db db.AuthDB) Option {
  51. return func(o *options) {
  52. o.database = db
  53. }
  54. }
  55. // CA is the type used to build the complete certificate authority. It builds
  56. // the HTTP server, set ups the middlewares and the HTTP handlers.
  57. type CA struct {
  58. auth *authority.Authority
  59. config *authority.Config
  60. srv *server.Server
  61. opts *options
  62. renewer *TLSRenewer
  63. }
  64. // New creates and initializes the CA with the given configuration and options.
  65. func New(config *authority.Config, opts ...Option) (*CA, error) {
  66. ca := &CA{
  67. config: config,
  68. opts: new(options),
  69. }
  70. ca.opts.apply(opts)
  71. return ca.Init(config)
  72. }
  73. // Init initializes the CA with the given configuration.
  74. func (ca *CA) Init(config *authority.Config) (*CA, error) {
  75. if l := len(ca.opts.password); l > 0 {
  76. ca.config.Password = string(ca.opts.password)
  77. }
  78. var opts []authority.Option
  79. if ca.opts.database != nil {
  80. opts = append(opts, authority.WithDatabase(ca.opts.database))
  81. }
  82. auth, err := authority.New(config, opts...)
  83. if err != nil {
  84. return nil, err
  85. }
  86. tlsConfig, err := ca.getTLSConfig(auth)
  87. if err != nil {
  88. return nil, err
  89. }
  90. // Using chi as the main router
  91. mux := chi.NewRouter()
  92. handler := http.Handler(mux)
  93. // Add regular CA api endpoints in / and /1.0
  94. routerHandler := api.New(auth)
  95. routerHandler.Route(mux)
  96. mux.Route("/1.0", func(r chi.Router) {
  97. routerHandler.Route(r)
  98. })
  99. //Add ACME api endpoints in /acme and /1.0/acme
  100. dns := config.DNSNames[0]
  101. u, err := url.Parse("https://" + config.Address)
  102. if err != nil {
  103. return nil, err
  104. }
  105. port := u.Port()
  106. if port != "" && port != "443" {
  107. dns = fmt.Sprintf("%s:%s", dns, port)
  108. }
  109. prefix := "acme"
  110. acmeAuth, err := acme.New(auth, acme.AuthorityOptions{
  111. Backdate: *config.AuthorityConfig.Backdate,
  112. DB: auth.GetDatabase().(nosql.DB),
  113. DNS: dns,
  114. Prefix: prefix,
  115. })
  116. if err != nil {
  117. return nil, errors.Wrap(err, "error creating ACME authority")
  118. }
  119. acmeRouterHandler := acmeAPI.New(acmeAuth)
  120. mux.Route("/"+prefix, func(r chi.Router) {
  121. acmeRouterHandler.Route(r)
  122. })
  123. // Use 2.0 because, at the moment, our ACME api is only compatible with v2.0
  124. // of the ACME spec.
  125. mux.Route("/2.0/"+prefix, func(r chi.Router) {
  126. acmeRouterHandler.Route(r)
  127. })
  128. // TODO: THIS SHOULDN'T HAPPEN (or should become configurable)
  129. // Current SCEP client I'm testing with doesn't seem to easily trust untrusted certs.
  130. tlsConfig = nil
  131. scepPrefix := "scep"
  132. scepAuthority, err := scep.New(auth, scep.AuthorityOptions{
  133. //Certificates: certificates,
  134. //AuthConfig: *config.AuthorityConfig,
  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 := scep.NewAPI(scepAuthority)
  144. mux.Route("/"+scepPrefix, func(r chi.Router) {
  145. scepRouterHandler.Route(r)
  146. })
  147. /*
  148. // helpful routine for logging all routes //
  149. walkFunc := func(method string, route string, handler http.Handler, middlewares ...func(http.Handler) http.Handler) error {
  150. fmt.Printf("%s %s\n", method, route)
  151. return nil
  152. }
  153. if err := chi.Walk(mux, walkFunc); err != nil {
  154. fmt.Printf("Logging err: %s\n", err.Error())
  155. }
  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. WithConfigFile(ca.opts.configFile),
  209. WithDatabase(ca.auth.GetDatabase()),
  210. )
  211. if err != nil {
  212. logContinue("Reload failed because the CA with new configuration could not be initialized.")
  213. return errors.Wrap(err, "error reloading ca")
  214. }
  215. if err = ca.srv.Reload(newCA.srv); err != nil {
  216. logContinue("Reload failed because server could not be replaced.")
  217. return errors.Wrap(err, "error reloading server")
  218. }
  219. // 1. Stop previous renewer
  220. // 2. Replace ca properties
  221. // Do not replace ca.srv
  222. ca.renewer.Stop()
  223. ca.auth = newCA.auth
  224. ca.config = newCA.config
  225. ca.opts = newCA.opts
  226. ca.renewer = newCA.renewer
  227. return nil
  228. }
  229. // getTLSConfig returns a TLSConfig for the CA server with a self-renewing
  230. // server certificate.
  231. func (ca *CA) getTLSConfig(auth *authority.Authority) (*tls.Config, error) {
  232. // Create initial TLS certificate
  233. tlsCrt, err := auth.GetTLSCertificate()
  234. if err != nil {
  235. return nil, err
  236. }
  237. // Start tls renewer with the new certificate.
  238. // If a renewer was started, attempt to stop it before.
  239. if ca.renewer != nil {
  240. ca.renewer.Stop()
  241. }
  242. ca.renewer, err = NewTLSRenewer(tlsCrt, auth.GetTLSCertificate)
  243. if err != nil {
  244. return nil, err
  245. }
  246. ca.renewer.Run()
  247. var tlsConfig *tls.Config
  248. if ca.config.TLS != nil {
  249. tlsConfig = ca.config.TLS.TLSConfig()
  250. } else {
  251. tlsConfig = &tls.Config{
  252. MinVersion: tls.VersionTLS12,
  253. }
  254. }
  255. certPool := x509.NewCertPool()
  256. for _, crt := range auth.GetRootCertificates() {
  257. certPool.AddCert(crt)
  258. }
  259. // GetCertificate will only be called if the client supplies SNI
  260. // information or if tlsConfig.Certificates is empty.
  261. // When client requests are made using an IP address (as opposed to a domain
  262. // name) the server does not receive any SNI and may fallback to using the
  263. // first entry in the Certificates attribute; by setting the attribute to
  264. // empty we are implicitly forcing GetCertificate to be the only mechanism
  265. // by which the server can find it's own leaf Certificate.
  266. tlsConfig.Certificates = []tls.Certificate{}
  267. tlsConfig.GetCertificate = ca.renewer.GetCertificateForCA
  268. // Add support for mutual tls to renew certificates
  269. tlsConfig.ClientAuth = tls.VerifyClientCertIfGiven
  270. tlsConfig.ClientCAs = certPool
  271. // Use server's most preferred ciphersuite
  272. tlsConfig.PreferServerCipherSuites = true
  273. return tlsConfig, nil
  274. }