authority.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558
  1. package authority
  2. import (
  3. "context"
  4. "crypto"
  5. "crypto/sha256"
  6. "crypto/x509"
  7. "encoding/hex"
  8. "log"
  9. "sync"
  10. "time"
  11. "github.com/smallstep/certificates/cas"
  12. "github.com/smallstep/certificates/scep"
  13. "go.step.sm/linkedca"
  14. "github.com/pkg/errors"
  15. "github.com/smallstep/certificates/authority/admin"
  16. adminDBNosql "github.com/smallstep/certificates/authority/admin/db/nosql"
  17. "github.com/smallstep/certificates/authority/administrator"
  18. "github.com/smallstep/certificates/authority/config"
  19. "github.com/smallstep/certificates/authority/provisioner"
  20. casapi "github.com/smallstep/certificates/cas/apiv1"
  21. "github.com/smallstep/certificates/db"
  22. "github.com/smallstep/certificates/kms"
  23. kmsapi "github.com/smallstep/certificates/kms/apiv1"
  24. "github.com/smallstep/certificates/kms/sshagentkms"
  25. "github.com/smallstep/certificates/templates"
  26. "github.com/smallstep/nosql"
  27. "go.step.sm/crypto/pemutil"
  28. "golang.org/x/crypto/ssh"
  29. )
  30. // Authority implements the Certificate Authority internal interface.
  31. type Authority struct {
  32. config *config.Config
  33. keyManager kms.KeyManager
  34. provisioners *provisioner.Collection
  35. admins *administrator.Collection
  36. db db.AuthDB
  37. adminDB admin.DB
  38. templates *templates.Templates
  39. // X509 CA
  40. x509CAService cas.CertificateAuthorityService
  41. rootX509Certs []*x509.Certificate
  42. rootX509CertPool *x509.CertPool
  43. federatedX509Certs []*x509.Certificate
  44. certificates *sync.Map
  45. // SCEP CA
  46. scepService *scep.Service
  47. // SSH CA
  48. sshCAUserCertSignKey ssh.Signer
  49. sshCAHostCertSignKey ssh.Signer
  50. sshCAUserCerts []ssh.PublicKey
  51. sshCAHostCerts []ssh.PublicKey
  52. sshCAUserFederatedCerts []ssh.PublicKey
  53. sshCAHostFederatedCerts []ssh.PublicKey
  54. // Do not re-initialize
  55. initOnce bool
  56. startTime time.Time
  57. // Custom functions
  58. sshBastionFunc func(ctx context.Context, user, hostname string) (*config.Bastion, error)
  59. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  60. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]config.Host, error)
  61. getIdentityFunc provisioner.GetIdentityFunc
  62. adminMutex sync.RWMutex
  63. }
  64. // New creates and initiates a new Authority type.
  65. func New(config *config.Config, opts ...Option) (*Authority, error) {
  66. err := config.Validate()
  67. if err != nil {
  68. return nil, err
  69. }
  70. var a = &Authority{
  71. config: config,
  72. certificates: new(sync.Map),
  73. }
  74. // Apply options.
  75. for _, fn := range opts {
  76. if err := fn(a); err != nil {
  77. return nil, err
  78. }
  79. }
  80. // Initialize authority from options or configuration.
  81. if err := a.init(); err != nil {
  82. return nil, err
  83. }
  84. return a, nil
  85. }
  86. // NewEmbedded initializes an authority that can be embedded in a different
  87. // project without the limitations of the config.
  88. func NewEmbedded(opts ...Option) (*Authority, error) {
  89. a := &Authority{
  90. config: &config.Config{},
  91. certificates: new(sync.Map),
  92. }
  93. // Apply options.
  94. for _, fn := range opts {
  95. if err := fn(a); err != nil {
  96. return nil, err
  97. }
  98. }
  99. // Validate required options
  100. switch {
  101. case a.config == nil:
  102. return nil, errors.New("cannot create an authority without a configuration")
  103. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  104. return nil, errors.New("cannot create an authority without a root certificate")
  105. case a.x509CAService == nil && a.config.IntermediateCert == "":
  106. return nil, errors.New("cannot create an authority without an issuer certificate")
  107. case a.x509CAService == nil && a.config.IntermediateKey == "":
  108. return nil, errors.New("cannot create an authority without an issuer signer")
  109. }
  110. // Initialize config required fields.
  111. a.config.Init()
  112. // Initialize authority from options or configuration.
  113. if err := a.init(); err != nil {
  114. return nil, err
  115. }
  116. return a, nil
  117. }
  118. // reloadAdminResources reloads admins and provisioners from the DB.
  119. func (a *Authority) reloadAdminResources(ctx context.Context) error {
  120. var (
  121. provList provisioner.List
  122. adminList []*linkedca.Admin
  123. )
  124. if a.config.AuthorityConfig.EnableAdmin {
  125. provs, err := a.adminDB.GetProvisioners(ctx)
  126. if err != nil {
  127. return admin.WrapErrorISE(err, "error getting provisioners to initialize authority")
  128. }
  129. provList, err = provisionerListToCertificates(provs)
  130. if err != nil {
  131. return admin.WrapErrorISE(err, "error converting provisioner list to certificates")
  132. }
  133. adminList, err = a.adminDB.GetAdmins(ctx)
  134. if err != nil {
  135. return admin.WrapErrorISE(err, "error getting admins to initialize authority")
  136. }
  137. } else {
  138. provList = a.config.AuthorityConfig.Provisioners
  139. adminList = a.config.AuthorityConfig.Admins
  140. }
  141. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  142. if err != nil {
  143. return admin.WrapErrorISE(err, "error generating provisioner config")
  144. }
  145. // Create provisioner collection.
  146. provClxn := provisioner.NewCollection(provisionerConfig.Audiences)
  147. for _, p := range provList {
  148. if err := p.Init(*provisionerConfig); err != nil {
  149. return err
  150. }
  151. if err := provClxn.Store(p); err != nil {
  152. return err
  153. }
  154. }
  155. // Create admin collection.
  156. adminClxn := administrator.NewCollection(provClxn)
  157. for _, adm := range adminList {
  158. p, ok := provClxn.Load(adm.ProvisionerId)
  159. if !ok {
  160. return admin.NewErrorISE("provisioner %s not found when loading admin %s",
  161. adm.ProvisionerId, adm.Id)
  162. }
  163. if err := adminClxn.Store(adm, p); err != nil {
  164. return err
  165. }
  166. }
  167. a.config.AuthorityConfig.Provisioners = provList
  168. a.provisioners = provClxn
  169. a.config.AuthorityConfig.Admins = adminList
  170. a.admins = adminClxn
  171. return nil
  172. }
  173. // init performs validation and initializes the fields of an Authority struct.
  174. func (a *Authority) init() error {
  175. // Check if handler has already been validated/initialized.
  176. if a.initOnce {
  177. return nil
  178. }
  179. var err error
  180. // Initialize step-ca Database if it's not already initialized with WithDB.
  181. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  182. if a.db == nil {
  183. if a.db, err = db.New(a.config.DB); err != nil {
  184. return err
  185. }
  186. }
  187. // Initialize key manager if it has not been set in the options.
  188. if a.keyManager == nil {
  189. var options kmsapi.Options
  190. if a.config.KMS != nil {
  191. options = *a.config.KMS
  192. }
  193. a.keyManager, err = kms.New(context.Background(), options)
  194. if err != nil {
  195. return err
  196. }
  197. }
  198. // Initialize the X.509 CA Service if it has not been set in the options.
  199. if a.x509CAService == nil {
  200. var options casapi.Options
  201. if a.config.AuthorityConfig.Options != nil {
  202. options = *a.config.AuthorityConfig.Options
  203. }
  204. // Read intermediate and create X509 signer for default CAS.
  205. if options.Is(casapi.SoftCAS) {
  206. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  207. if err != nil {
  208. return err
  209. }
  210. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  211. SigningKey: a.config.IntermediateKey,
  212. Password: []byte(a.config.Password),
  213. })
  214. if err != nil {
  215. return err
  216. }
  217. }
  218. a.x509CAService, err = cas.New(context.Background(), options)
  219. if err != nil {
  220. return err
  221. }
  222. // Get root certificate from CAS.
  223. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  224. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  225. Name: options.CertificateAuthority,
  226. })
  227. if err != nil {
  228. return err
  229. }
  230. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  231. sum := sha256.Sum256(resp.RootCertificate.Raw)
  232. log.Printf("Using root fingerprint '%s'", hex.EncodeToString(sum[:]))
  233. }
  234. }
  235. // Read root certificates and store them in the certificates map.
  236. if len(a.rootX509Certs) == 0 {
  237. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  238. for i, path := range a.config.Root {
  239. crt, err := pemutil.ReadCertificate(path)
  240. if err != nil {
  241. return err
  242. }
  243. a.rootX509Certs[i] = crt
  244. }
  245. }
  246. for _, crt := range a.rootX509Certs {
  247. sum := sha256.Sum256(crt.Raw)
  248. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  249. }
  250. a.rootX509CertPool = x509.NewCertPool()
  251. for _, cert := range a.rootX509Certs {
  252. a.rootX509CertPool.AddCert(cert)
  253. }
  254. // Read federated certificates and store them in the certificates map.
  255. if len(a.federatedX509Certs) == 0 {
  256. a.federatedX509Certs = make([]*x509.Certificate, len(a.config.FederatedRoots))
  257. for i, path := range a.config.FederatedRoots {
  258. crt, err := pemutil.ReadCertificate(path)
  259. if err != nil {
  260. return err
  261. }
  262. a.federatedX509Certs[i] = crt
  263. }
  264. }
  265. for _, crt := range a.federatedX509Certs {
  266. sum := sha256.Sum256(crt.Raw)
  267. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  268. }
  269. // Decrypt and load SSH keys
  270. var tmplVars templates.Step
  271. if a.config.SSH != nil {
  272. if a.config.SSH.HostKey != "" {
  273. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  274. SigningKey: a.config.SSH.HostKey,
  275. Password: []byte(a.config.Password),
  276. })
  277. if err != nil {
  278. return err
  279. }
  280. // If our signer is from sshagentkms, just unwrap it instead of
  281. // wrapping it in another layer, and this prevents crypto from
  282. // erroring out with: ssh: unsupported key type *agent.Key
  283. switch s := signer.(type) {
  284. case *sshagentkms.WrappedSSHSigner:
  285. a.sshCAHostCertSignKey = s.Sshsigner
  286. case crypto.Signer:
  287. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(s)
  288. default:
  289. return errors.Errorf("unsupported signer type %T", signer)
  290. }
  291. if err != nil {
  292. return errors.Wrap(err, "error creating ssh signer")
  293. }
  294. // Append public key to list of host certs
  295. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  296. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  297. }
  298. if a.config.SSH.UserKey != "" {
  299. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  300. SigningKey: a.config.SSH.UserKey,
  301. Password: []byte(a.config.Password),
  302. })
  303. if err != nil {
  304. return err
  305. }
  306. // If our signer is from sshagentkms, just unwrap it instead of
  307. // wrapping it in another layer, and this prevents crypto from
  308. // erroring out with: ssh: unsupported key type *agent.Key
  309. switch s := signer.(type) {
  310. case *sshagentkms.WrappedSSHSigner:
  311. a.sshCAUserCertSignKey = s.Sshsigner
  312. case crypto.Signer:
  313. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(s)
  314. default:
  315. return errors.Errorf("unsupported signer type %T", signer)
  316. }
  317. if err != nil {
  318. return errors.Wrap(err, "error creating ssh signer")
  319. }
  320. // Append public key to list of user certs
  321. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  322. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  323. }
  324. // Append other public keys
  325. for _, key := range a.config.SSH.Keys {
  326. switch key.Type {
  327. case provisioner.SSHHostCert:
  328. if key.Federated {
  329. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, key.PublicKey())
  330. } else {
  331. a.sshCAHostCerts = append(a.sshCAHostCerts, key.PublicKey())
  332. }
  333. case provisioner.SSHUserCert:
  334. if key.Federated {
  335. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, key.PublicKey())
  336. } else {
  337. a.sshCAUserCerts = append(a.sshCAUserCerts, key.PublicKey())
  338. }
  339. default:
  340. return errors.Errorf("unsupported type %s", key.Type)
  341. }
  342. }
  343. // Configure template variables.
  344. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  345. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  346. // On the templates we skip the first one because there's a distinction
  347. // between the main key and federated keys.
  348. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  349. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  350. }
  351. // Check if a KMS with decryption capability is required and available
  352. if a.requiresDecrypter() {
  353. if _, ok := a.keyManager.(kmsapi.Decrypter); !ok {
  354. return errors.New("keymanager doesn't provide crypto.Decrypter")
  355. }
  356. }
  357. // Check if a KMS with decryption capability is required and available
  358. if a.requiresDecrypter() {
  359. if _, ok := a.keyManager.(kmsapi.Decrypter); !ok {
  360. return errors.New("keymanager doesn't provide crypto.Decrypter")
  361. }
  362. }
  363. // TODO: decide if this is a good approach for providing the SCEP functionality
  364. // It currently mirrors the logic for the x509CAService
  365. if a.requiresSCEPService() && a.scepService == nil {
  366. var options scep.Options
  367. // Read intermediate and create X509 signer and decrypter for default CAS.
  368. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  369. if err != nil {
  370. return err
  371. }
  372. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  373. SigningKey: a.config.IntermediateKey,
  374. Password: []byte(a.config.Password),
  375. })
  376. if err != nil {
  377. return err
  378. }
  379. if km, ok := a.keyManager.(kmsapi.Decrypter); ok {
  380. options.Decrypter, err = km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  381. DecryptionKey: a.config.IntermediateKey,
  382. Password: []byte(a.config.Password),
  383. })
  384. if err != nil {
  385. return err
  386. }
  387. }
  388. a.scepService, err = scep.NewService(context.Background(), options)
  389. if err != nil {
  390. return err
  391. }
  392. // TODO: mimick the x509CAService GetCertificateAuthority here too?
  393. }
  394. if a.config.AuthorityConfig.EnableAdmin {
  395. // Initialize step-ca Admin Database if it's not already initialized using
  396. // WithAdminDB.
  397. if a.adminDB == nil {
  398. // Check if AuthConfig already exists
  399. a.adminDB, err = adminDBNosql.New(a.db.(nosql.DB), admin.DefaultAuthorityID)
  400. if err != nil {
  401. return err
  402. }
  403. }
  404. provs, err := a.adminDB.GetProvisioners(context.Background())
  405. if err != nil {
  406. return admin.WrapErrorISE(err, "error loading provisioners to initialize authority")
  407. }
  408. if len(provs) == 0 {
  409. // Create First Provisioner
  410. prov, err := CreateFirstProvisioner(context.Background(), a.adminDB, a.config.Password)
  411. if err != nil {
  412. return admin.WrapErrorISE(err, "error creating first provisioner")
  413. }
  414. // Create first admin
  415. if err := a.adminDB.CreateAdmin(context.Background(), &linkedca.Admin{
  416. ProvisionerId: prov.Id,
  417. Subject: "step",
  418. Type: linkedca.Admin_SUPER_ADMIN,
  419. }); err != nil {
  420. return admin.WrapErrorISE(err, "error creating first admin")
  421. }
  422. }
  423. }
  424. // Load Provisioners and Admins
  425. if err := a.reloadAdminResources(context.Background()); err != nil {
  426. return err
  427. }
  428. // Configure templates, currently only ssh templates are supported.
  429. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  430. a.templates = a.config.Templates
  431. if a.templates == nil {
  432. a.templates = templates.DefaultTemplates()
  433. }
  434. if a.templates.Data == nil {
  435. a.templates.Data = make(map[string]interface{})
  436. }
  437. a.templates.Data["Step"] = tmplVars
  438. }
  439. // JWT numeric dates are seconds.
  440. a.startTime = time.Now().Truncate(time.Second)
  441. // Set flag indicating that initialization has been completed, and should
  442. // not be repeated.
  443. a.initOnce = true
  444. return nil
  445. }
  446. // GetDatabase returns the authority database. If the configuration does not
  447. // define a database, GetDatabase will return a db.SimpleDB instance.
  448. func (a *Authority) GetDatabase() db.AuthDB {
  449. return a.db
  450. }
  451. // GetAdminDatabase returns the admin database, if one exists.
  452. func (a *Authority) GetAdminDatabase() admin.DB {
  453. return a.adminDB
  454. }
  455. // IsAdminAPIEnabled returns a boolean indicating whether the Admin API has
  456. // been enabled.
  457. func (a *Authority) IsAdminAPIEnabled() bool {
  458. return a.config.AuthorityConfig.EnableAdmin
  459. }
  460. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  461. func (a *Authority) Shutdown() error {
  462. if err := a.keyManager.Close(); err != nil {
  463. log.Printf("error closing the key manager: %v", err)
  464. }
  465. return a.db.Shutdown()
  466. }
  467. // CloseForReload closes internal services, to allow a safe reload.
  468. func (a *Authority) CloseForReload() {
  469. if err := a.keyManager.Close(); err != nil {
  470. log.Printf("error closing the key manager: %v", err)
  471. }
  472. }
  473. // requiresDecrypter returns whether the Authority
  474. // requires a KMS that provides a crypto.Decrypter
  475. // Currently this is only required when SCEP is
  476. // enabled.
  477. func (a *Authority) requiresDecrypter() bool {
  478. return a.requiresSCEPService()
  479. }
  480. // requiresSCEPService iterates over the configured provisioners
  481. // and determines if one of them is a SCEP provisioner.
  482. func (a *Authority) requiresSCEPService() bool {
  483. for _, p := range a.config.AuthorityConfig.Provisioners {
  484. if p.GetType() == provisioner.TypeSCEP {
  485. return true
  486. }
  487. }
  488. return false
  489. }
  490. // GetSCEPService returns the configured SCEP Service
  491. // TODO: this function is intended to exist temporarily
  492. // in order to make SCEP work more easily. It can be
  493. // made more correct by using the right interfaces/abstractions
  494. // after it works as expected.
  495. func (a *Authority) GetSCEPService() *scep.Service {
  496. return a.scepService
  497. }