authority.go 19 KB

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