authority.go 18 KB

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