authority.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. package authority
  2. import (
  3. "context"
  4. "crypto/sha256"
  5. "crypto/x509"
  6. "encoding/hex"
  7. "log"
  8. "sync"
  9. "time"
  10. "github.com/smallstep/certificates/cas"
  11. "github.com/pkg/errors"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. casapi "github.com/smallstep/certificates/cas/apiv1"
  14. "github.com/smallstep/certificates/db"
  15. "github.com/smallstep/certificates/kms"
  16. kmsapi "github.com/smallstep/certificates/kms/apiv1"
  17. "github.com/smallstep/certificates/templates"
  18. "go.step.sm/crypto/pemutil"
  19. "golang.org/x/crypto/ssh"
  20. )
  21. const (
  22. legacyAuthority = "step-certificate-authority"
  23. )
  24. // Authority implements the Certificate Authority internal interface.
  25. type Authority struct {
  26. config *Config
  27. keyManager kms.KeyManager
  28. provisioners *provisioner.Collection
  29. db db.AuthDB
  30. templates *templates.Templates
  31. // X509 CA
  32. x509CAService cas.CertificateAuthorityService
  33. rootX509Certs []*x509.Certificate
  34. federatedX509Certs []*x509.Certificate
  35. certificates *sync.Map
  36. // SSH CA
  37. sshCAUserCertSignKey ssh.Signer
  38. sshCAHostCertSignKey ssh.Signer
  39. sshCAUserCerts []ssh.PublicKey
  40. sshCAHostCerts []ssh.PublicKey
  41. sshCAUserFederatedCerts []ssh.PublicKey
  42. sshCAHostFederatedCerts []ssh.PublicKey
  43. // Do not re-initialize
  44. initOnce bool
  45. startTime time.Time
  46. // Custom functions
  47. sshBastionFunc func(ctx context.Context, user, hostname string) (*Bastion, error)
  48. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  49. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]Host, error)
  50. getIdentityFunc provisioner.GetIdentityFunc
  51. }
  52. // New creates and initiates a new Authority type.
  53. func New(config *Config, opts ...Option) (*Authority, error) {
  54. err := config.Validate()
  55. if err != nil {
  56. return nil, err
  57. }
  58. var a = &Authority{
  59. config: config,
  60. certificates: new(sync.Map),
  61. }
  62. // Apply options.
  63. for _, fn := range opts {
  64. if err := fn(a); err != nil {
  65. return nil, err
  66. }
  67. }
  68. // Initialize authority from options or configuration.
  69. if err := a.init(); err != nil {
  70. return nil, err
  71. }
  72. return a, nil
  73. }
  74. // NewEmbedded initializes an authority that can be embedded in a different
  75. // project without the limitations of the config.
  76. func NewEmbedded(opts ...Option) (*Authority, error) {
  77. a := &Authority{
  78. config: &Config{},
  79. certificates: new(sync.Map),
  80. }
  81. // Apply options.
  82. for _, fn := range opts {
  83. if err := fn(a); err != nil {
  84. return nil, err
  85. }
  86. }
  87. // Validate required options
  88. switch {
  89. case a.config == nil:
  90. return nil, errors.New("cannot create an authority without a configuration")
  91. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  92. return nil, errors.New("cannot create an authority without a root certificate")
  93. case a.x509CAService == nil && a.config.IntermediateCert == "":
  94. return nil, errors.New("cannot create an authority without an issuer certificate")
  95. case a.x509CAService == nil && a.config.IntermediateKey == "":
  96. return nil, errors.New("cannot create an authority without an issuer signer")
  97. }
  98. // Initialize config required fields.
  99. a.config.init()
  100. // Initialize authority from options or configuration.
  101. if err := a.init(); err != nil {
  102. return nil, err
  103. }
  104. return a, nil
  105. }
  106. // init performs validation and initializes the fields of an Authority struct.
  107. func (a *Authority) init() error {
  108. // Check if handler has already been validated/initialized.
  109. if a.initOnce {
  110. return nil
  111. }
  112. var err error
  113. // Initialize step-ca Database if it's not already initialized with WithDB.
  114. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  115. if a.db == nil {
  116. if a.db, err = db.New(a.config.DB); err != nil {
  117. return err
  118. }
  119. }
  120. // Initialize key manager if it has not been set in the options.
  121. if a.keyManager == nil {
  122. var options kmsapi.Options
  123. if a.config.KMS != nil {
  124. options = *a.config.KMS
  125. }
  126. a.keyManager, err = kms.New(context.Background(), options)
  127. if err != nil {
  128. return err
  129. }
  130. }
  131. // Initialize the X.509 CA Service if it has not been set in the options.
  132. if a.x509CAService == nil {
  133. var options casapi.Options
  134. if a.config.CAS != nil {
  135. options = *a.config.CAS
  136. }
  137. // Read intermediate and create X509 signer for default CAS.
  138. if options.Is(casapi.SoftCAS) {
  139. options.Issuer, err = pemutil.ReadCertificate(a.config.IntermediateCert)
  140. if err != nil {
  141. return err
  142. }
  143. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  144. SigningKey: a.config.IntermediateKey,
  145. Password: []byte(a.config.Password),
  146. })
  147. if err != nil {
  148. return err
  149. }
  150. }
  151. a.x509CAService, err = cas.New(context.Background(), options)
  152. if err != nil {
  153. return err
  154. }
  155. // Get root certificate from CAS.
  156. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  157. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  158. Name: options.Certificateauthority,
  159. })
  160. if err != nil {
  161. return err
  162. }
  163. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  164. sum := sha256.Sum256(resp.RootCertificate.Raw)
  165. log.Printf("Using root fingerprint '%s'", hex.EncodeToString(sum[:]))
  166. }
  167. }
  168. // Read root certificates and store them in the certificates map.
  169. if len(a.rootX509Certs) == 0 {
  170. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  171. for i, path := range a.config.Root {
  172. crt, err := pemutil.ReadCertificate(path)
  173. if err != nil {
  174. return err
  175. }
  176. a.rootX509Certs[i] = crt
  177. }
  178. }
  179. for _, crt := range a.rootX509Certs {
  180. sum := sha256.Sum256(crt.Raw)
  181. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  182. }
  183. // Read federated certificates and store them in the certificates map.
  184. if len(a.federatedX509Certs) == 0 {
  185. a.federatedX509Certs = make([]*x509.Certificate, len(a.config.FederatedRoots))
  186. for i, path := range a.config.FederatedRoots {
  187. crt, err := pemutil.ReadCertificate(path)
  188. if err != nil {
  189. return err
  190. }
  191. a.federatedX509Certs[i] = crt
  192. }
  193. }
  194. for _, crt := range a.federatedX509Certs {
  195. sum := sha256.Sum256(crt.Raw)
  196. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  197. }
  198. // Decrypt and load SSH keys
  199. var tmplVars templates.Step
  200. if a.config.SSH != nil {
  201. if a.config.SSH.HostKey != "" {
  202. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  203. SigningKey: a.config.SSH.HostKey,
  204. Password: []byte(a.config.Password),
  205. })
  206. if err != nil {
  207. return err
  208. }
  209. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(signer)
  210. if err != nil {
  211. return errors.Wrap(err, "error creating ssh signer")
  212. }
  213. // Append public key to list of host certs
  214. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  215. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  216. }
  217. if a.config.SSH.UserKey != "" {
  218. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  219. SigningKey: a.config.SSH.UserKey,
  220. Password: []byte(a.config.Password),
  221. })
  222. if err != nil {
  223. return err
  224. }
  225. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(signer)
  226. if err != nil {
  227. return errors.Wrap(err, "error creating ssh signer")
  228. }
  229. // Append public key to list of user certs
  230. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  231. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  232. }
  233. // Append other public keys
  234. for _, key := range a.config.SSH.Keys {
  235. switch key.Type {
  236. case provisioner.SSHHostCert:
  237. if key.Federated {
  238. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, key.PublicKey())
  239. } else {
  240. a.sshCAHostCerts = append(a.sshCAHostCerts, key.PublicKey())
  241. }
  242. case provisioner.SSHUserCert:
  243. if key.Federated {
  244. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, key.PublicKey())
  245. } else {
  246. a.sshCAUserCerts = append(a.sshCAUserCerts, key.PublicKey())
  247. }
  248. default:
  249. return errors.Errorf("unsupported type %s", key.Type)
  250. }
  251. }
  252. // Configure template variables.
  253. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  254. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  255. // On the templates we skip the first one because there's a distinction
  256. // between the main key and federated keys.
  257. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  258. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  259. }
  260. // Merge global and configuration claims
  261. claimer, err := provisioner.NewClaimer(a.config.AuthorityConfig.Claims, globalProvisionerClaims)
  262. if err != nil {
  263. return err
  264. }
  265. // TODO: should we also be combining the ssh federated roots here?
  266. // If we rotate ssh roots keys, sshpop provisioner will lose ability to
  267. // validate old SSH certificates, unless they are added as federated certs.
  268. sshKeys, err := a.GetSSHRoots(context.Background())
  269. if err != nil {
  270. return err
  271. }
  272. // Initialize provisioners
  273. audiences := a.config.getAudiences()
  274. a.provisioners = provisioner.NewCollection(audiences)
  275. config := provisioner.Config{
  276. Claims: claimer.Claims(),
  277. Audiences: audiences,
  278. DB: a.db,
  279. SSHKeys: &provisioner.SSHKeys{
  280. UserKeys: sshKeys.UserKeys,
  281. HostKeys: sshKeys.HostKeys,
  282. },
  283. GetIdentityFunc: a.getIdentityFunc,
  284. }
  285. // Store all the provisioners
  286. for _, p := range a.config.AuthorityConfig.Provisioners {
  287. if err := p.Init(config); err != nil {
  288. return err
  289. }
  290. if err := a.provisioners.Store(p); err != nil {
  291. return err
  292. }
  293. }
  294. // Configure templates, currently only ssh templates are supported.
  295. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  296. a.templates = a.config.Templates
  297. if a.templates == nil {
  298. a.templates = templates.DefaultTemplates()
  299. }
  300. if a.templates.Data == nil {
  301. a.templates.Data = make(map[string]interface{})
  302. }
  303. a.templates.Data["Step"] = tmplVars
  304. }
  305. // JWT numeric dates are seconds.
  306. a.startTime = time.Now().Truncate(time.Second)
  307. // Set flag indicating that initialization has been completed, and should
  308. // not be repeated.
  309. a.initOnce = true
  310. return nil
  311. }
  312. // GetDatabase returns the authority database. If the configuration does not
  313. // define a database, GetDatabase will return a db.SimpleDB instance.
  314. func (a *Authority) GetDatabase() db.AuthDB {
  315. return a.db
  316. }
  317. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  318. func (a *Authority) Shutdown() error {
  319. if err := a.keyManager.Close(); err != nil {
  320. log.Printf("error closing the key manager: %v", err)
  321. }
  322. return a.db.Shutdown()
  323. }