authority.go 21 KB

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