authority.go 23 KB

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