authority.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743
  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/kms"
  15. kmsapi "go.step.sm/crypto/kms/apiv1"
  16. "go.step.sm/crypto/kms/sshagentkms"
  17. "go.step.sm/crypto/pemutil"
  18. "go.step.sm/linkedca"
  19. "github.com/smallstep/certificates/authority/admin"
  20. adminDBNosql "github.com/smallstep/certificates/authority/admin/db/nosql"
  21. "github.com/smallstep/certificates/authority/administrator"
  22. "github.com/smallstep/certificates/authority/config"
  23. "github.com/smallstep/certificates/authority/policy"
  24. "github.com/smallstep/certificates/authority/provisioner"
  25. "github.com/smallstep/certificates/cas"
  26. casapi "github.com/smallstep/certificates/cas/apiv1"
  27. "github.com/smallstep/certificates/db"
  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. a.config.AuthorityConfig.AuthorityID = linkedcaClient.authorityID
  275. linkedcaClient.Run()
  276. }
  277. // Initialize the X.509 CA Service if it has not been set in the options.
  278. if a.x509CAService == nil {
  279. var options casapi.Options
  280. if a.config.AuthorityConfig.Options != nil {
  281. options = *a.config.AuthorityConfig.Options
  282. }
  283. // AuthorityID might be empty. It's always available linked CAs/RAs.
  284. options.AuthorityID = a.config.AuthorityConfig.AuthorityID
  285. // Configure linked RA
  286. if linkedcaClient != nil && options.CertificateAuthority == "" {
  287. conf, err := linkedcaClient.GetConfiguration(ctx)
  288. if err != nil {
  289. return err
  290. }
  291. if conf.RaConfig != nil {
  292. options.CertificateAuthority = conf.RaConfig.CaUrl
  293. options.CertificateAuthorityFingerprint = conf.RaConfig.Fingerprint
  294. options.CertificateIssuer = &casapi.CertificateIssuer{
  295. Type: conf.RaConfig.Provisioner.Type.String(),
  296. Provisioner: conf.RaConfig.Provisioner.Name,
  297. }
  298. // Configure the RA authority type if needed
  299. if options.Type == "" {
  300. options.Type = casapi.StepCAS
  301. }
  302. }
  303. // Remote configuration is currently only supported on a linked RA
  304. if sc := conf.ServerConfig; sc != nil {
  305. if a.config.Address == "" {
  306. a.config.Address = sc.Address
  307. }
  308. if len(a.config.DNSNames) == 0 {
  309. a.config.DNSNames = sc.DnsNames
  310. }
  311. }
  312. }
  313. // Set the issuer password if passed in the flags.
  314. if options.CertificateIssuer != nil && a.issuerPassword != nil {
  315. options.CertificateIssuer.Password = string(a.issuerPassword)
  316. }
  317. // Read intermediate and create X509 signer for default CAS.
  318. if options.Is(casapi.SoftCAS) {
  319. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  320. if err != nil {
  321. return err
  322. }
  323. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  324. SigningKey: a.config.IntermediateKey,
  325. Password: a.password,
  326. })
  327. if err != nil {
  328. return err
  329. }
  330. }
  331. a.x509CAService, err = cas.New(ctx, options)
  332. if err != nil {
  333. return err
  334. }
  335. // Get root certificate from CAS.
  336. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  337. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  338. Name: options.CertificateAuthority,
  339. })
  340. if err != nil {
  341. return err
  342. }
  343. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  344. }
  345. }
  346. // Read root certificates and store them in the certificates map.
  347. if len(a.rootX509Certs) == 0 {
  348. a.rootX509Certs = make([]*x509.Certificate, len(a.config.Root))
  349. for i, path := range a.config.Root {
  350. crt, err := pemutil.ReadCertificate(path)
  351. if err != nil {
  352. return err
  353. }
  354. a.rootX509Certs[i] = crt
  355. }
  356. }
  357. for _, crt := range a.rootX509Certs {
  358. sum := sha256.Sum256(crt.Raw)
  359. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  360. }
  361. a.rootX509CertPool = x509.NewCertPool()
  362. for _, cert := range a.rootX509Certs {
  363. a.rootX509CertPool.AddCert(cert)
  364. }
  365. // Read federated certificates and store them in the certificates map.
  366. if len(a.federatedX509Certs) == 0 {
  367. a.federatedX509Certs = make([]*x509.Certificate, len(a.config.FederatedRoots))
  368. for i, path := range a.config.FederatedRoots {
  369. crt, err := pemutil.ReadCertificate(path)
  370. if err != nil {
  371. return err
  372. }
  373. a.federatedX509Certs[i] = crt
  374. }
  375. }
  376. for _, crt := range a.federatedX509Certs {
  377. sum := sha256.Sum256(crt.Raw)
  378. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  379. }
  380. // Decrypt and load SSH keys
  381. var tmplVars templates.Step
  382. if a.config.SSH != nil {
  383. if a.config.SSH.HostKey != "" {
  384. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  385. SigningKey: a.config.SSH.HostKey,
  386. Password: a.sshHostPassword,
  387. })
  388. if err != nil {
  389. return err
  390. }
  391. // If our signer is from sshagentkms, just unwrap it instead of
  392. // wrapping it in another layer, and this prevents crypto from
  393. // erroring out with: ssh: unsupported key type *agent.Key
  394. switch s := signer.(type) {
  395. case *sshagentkms.WrappedSSHSigner:
  396. a.sshCAHostCertSignKey = s.Signer
  397. case crypto.Signer:
  398. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(s)
  399. default:
  400. return errors.Errorf("unsupported signer type %T", signer)
  401. }
  402. if err != nil {
  403. return errors.Wrap(err, "error creating ssh signer")
  404. }
  405. // Append public key to list of host certs
  406. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  407. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  408. }
  409. if a.config.SSH.UserKey != "" {
  410. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  411. SigningKey: a.config.SSH.UserKey,
  412. Password: a.sshUserPassword,
  413. })
  414. if err != nil {
  415. return err
  416. }
  417. // If our signer is from sshagentkms, just unwrap it instead of
  418. // wrapping it in another layer, and this prevents crypto from
  419. // erroring out with: ssh: unsupported key type *agent.Key
  420. switch s := signer.(type) {
  421. case *sshagentkms.WrappedSSHSigner:
  422. a.sshCAUserCertSignKey = s.Signer
  423. case crypto.Signer:
  424. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(s)
  425. default:
  426. return errors.Errorf("unsupported signer type %T", signer)
  427. }
  428. if err != nil {
  429. return errors.Wrap(err, "error creating ssh signer")
  430. }
  431. // Append public key to list of user certs
  432. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  433. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  434. }
  435. // Append other public keys and add them to the template variables.
  436. for _, key := range a.config.SSH.Keys {
  437. publicKey := key.PublicKey()
  438. switch key.Type {
  439. case provisioner.SSHHostCert:
  440. if key.Federated {
  441. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, publicKey)
  442. } else {
  443. a.sshCAHostCerts = append(a.sshCAHostCerts, publicKey)
  444. }
  445. case provisioner.SSHUserCert:
  446. if key.Federated {
  447. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, publicKey)
  448. } else {
  449. a.sshCAUserCerts = append(a.sshCAUserCerts, publicKey)
  450. }
  451. default:
  452. return errors.Errorf("unsupported type %s", key.Type)
  453. }
  454. }
  455. }
  456. // Configure template variables. On the template variables HostFederatedKeys
  457. // and UserFederatedKeys we will skip the actual CA that will be available
  458. // in HostKey and UserKey.
  459. //
  460. // We cannot do it in the previous blocks because this configuration can be
  461. // injected using options.
  462. if a.sshCAHostCertSignKey != nil {
  463. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  464. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  465. } else {
  466. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts...)
  467. }
  468. if a.sshCAUserCertSignKey != nil {
  469. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  470. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  471. } else {
  472. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts...)
  473. }
  474. // Check if a KMS with decryption capability is required and available
  475. if a.requiresDecrypter() {
  476. if _, ok := a.keyManager.(kmsapi.Decrypter); !ok {
  477. return errors.New("keymanager doesn't provide crypto.Decrypter")
  478. }
  479. }
  480. // TODO: decide if this is a good approach for providing the SCEP functionality
  481. // It currently mirrors the logic for the x509CAService
  482. if a.requiresSCEPService() && a.scepService == nil {
  483. var options scep.Options
  484. // Read intermediate and create X509 signer and decrypter for default CAS.
  485. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  486. if err != nil {
  487. return err
  488. }
  489. options.CertificateChain = append(options.CertificateChain, a.rootX509Certs...)
  490. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  491. SigningKey: a.config.IntermediateKey,
  492. Password: a.password,
  493. })
  494. if err != nil {
  495. return err
  496. }
  497. if km, ok := a.keyManager.(kmsapi.Decrypter); ok {
  498. options.Decrypter, err = km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  499. DecryptionKey: a.config.IntermediateKey,
  500. Password: a.password,
  501. })
  502. if err != nil {
  503. return err
  504. }
  505. }
  506. a.scepService, err = scep.NewService(ctx, options)
  507. if err != nil {
  508. return err
  509. }
  510. // TODO: mimick the x509CAService GetCertificateAuthority here too?
  511. }
  512. if a.config.AuthorityConfig.EnableAdmin {
  513. // Initialize step-ca Admin Database if it's not already initialized using
  514. // WithAdminDB.
  515. if a.adminDB == nil {
  516. if linkedcaClient != nil {
  517. a.adminDB = linkedcaClient
  518. } else {
  519. a.adminDB, err = adminDBNosql.New(a.db.(nosql.DB), admin.DefaultAuthorityID)
  520. if err != nil {
  521. return err
  522. }
  523. }
  524. }
  525. provs, err := a.adminDB.GetProvisioners(ctx)
  526. if err != nil {
  527. return admin.WrapErrorISE(err, "error loading provisioners to initialize authority")
  528. }
  529. if len(provs) == 0 && !strings.EqualFold(a.config.AuthorityConfig.DeploymentType, "linked") {
  530. // Create First Provisioner
  531. prov, err := CreateFirstProvisioner(ctx, a.adminDB, string(a.password))
  532. if err != nil {
  533. return admin.WrapErrorISE(err, "error creating first provisioner")
  534. }
  535. // Create first admin
  536. if err := a.adminDB.CreateAdmin(ctx, &linkedca.Admin{
  537. ProvisionerId: prov.Id,
  538. Subject: "step",
  539. Type: linkedca.Admin_SUPER_ADMIN,
  540. }); err != nil {
  541. return admin.WrapErrorISE(err, "error creating first admin")
  542. }
  543. }
  544. }
  545. // Load Provisioners and Admins
  546. if err := a.ReloadAdminResources(ctx); err != nil {
  547. return err
  548. }
  549. // Load x509 and SSH Policy Engines
  550. if err := a.reloadPolicyEngines(ctx); err != nil {
  551. return err
  552. }
  553. // Configure templates, currently only ssh templates are supported.
  554. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  555. a.templates = a.config.Templates
  556. if a.templates == nil {
  557. a.templates = templates.DefaultTemplates()
  558. }
  559. if a.templates.Data == nil {
  560. a.templates.Data = make(map[string]interface{})
  561. }
  562. a.templates.Data["Step"] = tmplVars
  563. }
  564. // JWT numeric dates are seconds.
  565. a.startTime = time.Now().Truncate(time.Second)
  566. // Set flag indicating that initialization has been completed, and should
  567. // not be repeated.
  568. a.initOnce = true
  569. return nil
  570. }
  571. // GetID returns the define authority id or a zero uuid.
  572. func (a *Authority) GetID() string {
  573. const zeroUUID = "00000000-0000-0000-0000-000000000000"
  574. if id := a.config.AuthorityConfig.AuthorityID; id != "" {
  575. return id
  576. }
  577. return zeroUUID
  578. }
  579. // GetDatabase returns the authority database. If the configuration does not
  580. // define a database, GetDatabase will return a db.SimpleDB instance.
  581. func (a *Authority) GetDatabase() db.AuthDB {
  582. return a.db
  583. }
  584. // GetAdminDatabase returns the admin database, if one exists.
  585. func (a *Authority) GetAdminDatabase() admin.DB {
  586. return a.adminDB
  587. }
  588. // GetConfig returns the config.
  589. func (a *Authority) GetConfig() *config.Config {
  590. return a.config
  591. }
  592. // GetInfo returns information about the authority.
  593. func (a *Authority) GetInfo() Info {
  594. ai := Info{
  595. StartTime: a.startTime,
  596. RootX509Certs: a.rootX509Certs,
  597. DNSNames: a.config.DNSNames,
  598. }
  599. if a.sshCAUserCertSignKey != nil {
  600. ai.SSHCAUserPublicKey = ssh.MarshalAuthorizedKey(a.sshCAUserCertSignKey.PublicKey())
  601. }
  602. if a.sshCAHostCertSignKey != nil {
  603. ai.SSHCAHostPublicKey = ssh.MarshalAuthorizedKey(a.sshCAHostCertSignKey.PublicKey())
  604. }
  605. return ai
  606. }
  607. // IsAdminAPIEnabled returns a boolean indicating whether the Admin API has
  608. // been enabled.
  609. func (a *Authority) IsAdminAPIEnabled() bool {
  610. return a.config.AuthorityConfig.EnableAdmin
  611. }
  612. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  613. func (a *Authority) Shutdown() error {
  614. if err := a.keyManager.Close(); err != nil {
  615. log.Printf("error closing the key manager: %v", err)
  616. }
  617. return a.db.Shutdown()
  618. }
  619. // CloseForReload closes internal services, to allow a safe reload.
  620. func (a *Authority) CloseForReload() {
  621. if err := a.keyManager.Close(); err != nil {
  622. log.Printf("error closing the key manager: %v", err)
  623. }
  624. if client, ok := a.adminDB.(*linkedCaClient); ok {
  625. client.Stop()
  626. }
  627. }
  628. // IsRevoked returns whether or not a certificate has been
  629. // revoked before.
  630. func (a *Authority) IsRevoked(sn string) (bool, error) {
  631. // Check the passive revocation table.
  632. if lca, ok := a.adminDB.(interface {
  633. IsRevoked(string) (bool, error)
  634. }); ok {
  635. return lca.IsRevoked(sn)
  636. }
  637. return a.db.IsRevoked(sn)
  638. }
  639. // requiresDecrypter returns whether the Authority
  640. // requires a KMS that provides a crypto.Decrypter
  641. // Currently this is only required when SCEP is
  642. // enabled.
  643. func (a *Authority) requiresDecrypter() bool {
  644. return a.requiresSCEPService()
  645. }
  646. // requiresSCEPService iterates over the configured provisioners
  647. // and determines if one of them is a SCEP provisioner.
  648. func (a *Authority) requiresSCEPService() bool {
  649. for _, p := range a.config.AuthorityConfig.Provisioners {
  650. if p.GetType() == provisioner.TypeSCEP {
  651. return true
  652. }
  653. }
  654. return false
  655. }
  656. // GetSCEPService returns the configured SCEP Service
  657. // TODO: this function is intended to exist temporarily
  658. // in order to make SCEP work more easily. It can be
  659. // made more correct by using the right interfaces/abstractions
  660. // after it works as expected.
  661. func (a *Authority) GetSCEPService() *scep.Service {
  662. return a.scepService
  663. }