authority.go 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900
  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. // CRL vars
  68. crlTicker *time.Ticker
  69. crlStopper chan struct{}
  70. crlMutex sync.Mutex
  71. // If true, do not re-initialize
  72. initOnce bool
  73. startTime time.Time
  74. // Custom functions
  75. sshBastionFunc func(ctx context.Context, user, hostname string) (*config.Bastion, error)
  76. sshCheckHostFunc func(ctx context.Context, principal string, tok string, roots []*x509.Certificate) (bool, error)
  77. sshGetHostsFunc func(ctx context.Context, cert *x509.Certificate) ([]config.Host, error)
  78. getIdentityFunc provisioner.GetIdentityFunc
  79. authorizeRenewFunc provisioner.AuthorizeRenewFunc
  80. authorizeSSHRenewFunc provisioner.AuthorizeSSHRenewFunc
  81. // Constraints and Policy engines
  82. constraintsEngine *constraints.Engine
  83. policyEngine *policy.Engine
  84. adminMutex sync.RWMutex
  85. // If true, do not initialize the authority
  86. skipInit bool
  87. // If true, do not output initialization logs
  88. quietInit bool
  89. }
  90. // Info contains information about the authority.
  91. type Info struct {
  92. StartTime time.Time
  93. RootX509Certs []*x509.Certificate
  94. SSHCAUserPublicKey []byte
  95. SSHCAHostPublicKey []byte
  96. DNSNames []string
  97. }
  98. // New creates and initiates a new Authority type.
  99. func New(cfg *config.Config, opts ...Option) (*Authority, error) {
  100. err := cfg.Validate()
  101. if err != nil {
  102. return nil, err
  103. }
  104. var a = &Authority{
  105. config: cfg,
  106. certificates: new(sync.Map),
  107. }
  108. // Apply options.
  109. for _, fn := range opts {
  110. if err := fn(a); err != nil {
  111. return nil, err
  112. }
  113. }
  114. if !a.skipInit {
  115. // Initialize authority from options or configuration.
  116. if err := a.init(); err != nil {
  117. return nil, err
  118. }
  119. }
  120. return a, nil
  121. }
  122. // NewEmbedded initializes an authority that can be embedded in a different
  123. // project without the limitations of the config.
  124. func NewEmbedded(opts ...Option) (*Authority, error) {
  125. a := &Authority{
  126. config: &config.Config{},
  127. certificates: new(sync.Map),
  128. }
  129. // Apply options.
  130. for _, fn := range opts {
  131. if err := fn(a); err != nil {
  132. return nil, err
  133. }
  134. }
  135. // Validate required options
  136. switch {
  137. case a.config == nil:
  138. return nil, errors.New("cannot create an authority without a configuration")
  139. case len(a.rootX509Certs) == 0 && a.config.Root.HasEmpties():
  140. return nil, errors.New("cannot create an authority without a root certificate")
  141. case a.x509CAService == nil && a.config.IntermediateCert == "":
  142. return nil, errors.New("cannot create an authority without an issuer certificate")
  143. case a.x509CAService == nil && a.config.IntermediateKey == "":
  144. return nil, errors.New("cannot create an authority without an issuer signer")
  145. }
  146. // Initialize config required fields.
  147. a.config.Init()
  148. if !a.skipInit {
  149. // Initialize authority from options or configuration.
  150. if err := a.init(); err != nil {
  151. return nil, err
  152. }
  153. }
  154. return a, nil
  155. }
  156. type authorityKey struct{}
  157. // NewContext adds the given authority to the context.
  158. func NewContext(ctx context.Context, a *Authority) context.Context {
  159. return context.WithValue(ctx, authorityKey{}, a)
  160. }
  161. // FromContext returns the current authority from the given context.
  162. func FromContext(ctx context.Context) (a *Authority, ok bool) {
  163. a, ok = ctx.Value(authorityKey{}).(*Authority)
  164. return
  165. }
  166. // MustFromContext returns the current authority from the given context. It will
  167. // panic if the authority is not in the context.
  168. func MustFromContext(ctx context.Context) *Authority {
  169. if a, ok := FromContext(ctx); !ok {
  170. panic("authority is not in the context")
  171. } else {
  172. return a
  173. }
  174. }
  175. // ReloadAdminResources reloads admins and provisioners from the DB.
  176. func (a *Authority) ReloadAdminResources(ctx context.Context) error {
  177. var (
  178. provList provisioner.List
  179. adminList []*linkedca.Admin
  180. )
  181. if a.config.AuthorityConfig.EnableAdmin {
  182. provs, err := a.adminDB.GetProvisioners(ctx)
  183. if err != nil {
  184. return admin.WrapErrorISE(err, "error getting provisioners to initialize authority")
  185. }
  186. provList, err = provisionerListToCertificates(provs)
  187. if err != nil {
  188. return admin.WrapErrorISE(err, "error converting provisioner list to certificates")
  189. }
  190. adminList, err = a.adminDB.GetAdmins(ctx)
  191. if err != nil {
  192. return admin.WrapErrorISE(err, "error getting admins to initialize authority")
  193. }
  194. } else {
  195. provList = a.config.AuthorityConfig.Provisioners
  196. adminList = a.config.AuthorityConfig.Admins
  197. }
  198. provisionerConfig, err := a.generateProvisionerConfig(ctx)
  199. if err != nil {
  200. return admin.WrapErrorISE(err, "error generating provisioner config")
  201. }
  202. // Create provisioner collection.
  203. provClxn := provisioner.NewCollection(provisionerConfig.Audiences)
  204. for _, p := range provList {
  205. if err := p.Init(provisionerConfig); err != nil {
  206. return err
  207. }
  208. if err := provClxn.Store(p); err != nil {
  209. return err
  210. }
  211. }
  212. // Create admin collection.
  213. adminClxn := administrator.NewCollection(provClxn)
  214. for _, adm := range adminList {
  215. p, ok := provClxn.Load(adm.ProvisionerId)
  216. if !ok {
  217. return admin.NewErrorISE("provisioner %s not found when loading admin %s",
  218. adm.ProvisionerId, adm.Id)
  219. }
  220. if err := adminClxn.Store(adm, p); err != nil {
  221. return err
  222. }
  223. }
  224. a.config.AuthorityConfig.Provisioners = provList
  225. a.provisioners = provClxn
  226. a.config.AuthorityConfig.Admins = adminList
  227. a.admins = adminClxn
  228. return nil
  229. }
  230. // init performs validation and initializes the fields of an Authority struct.
  231. func (a *Authority) init() error {
  232. // Check if handler has already been validated/initialized.
  233. if a.initOnce {
  234. return nil
  235. }
  236. var err error
  237. ctx := NewContext(context.Background(), a)
  238. // Set password if they are not set.
  239. var configPassword []byte
  240. if a.config.Password != "" {
  241. configPassword = []byte(a.config.Password)
  242. }
  243. if configPassword != nil && a.password == nil {
  244. a.password = configPassword
  245. }
  246. if a.sshHostPassword == nil {
  247. a.sshHostPassword = a.password
  248. }
  249. if a.sshUserPassword == nil {
  250. a.sshUserPassword = a.password
  251. }
  252. // Automatically enable admin for all linked cas.
  253. if a.linkedCAToken != "" {
  254. a.config.AuthorityConfig.EnableAdmin = true
  255. }
  256. // Initialize step-ca Database if it's not already initialized with WithDB.
  257. // If a.config.DB is nil then a simple, barebones in memory DB will be used.
  258. if a.db == nil {
  259. if a.db, err = db.New(a.config.DB); err != nil {
  260. return err
  261. }
  262. }
  263. // Initialize key manager if it has not been set in the options.
  264. if a.keyManager == nil {
  265. var options kmsapi.Options
  266. if a.config.KMS != nil {
  267. options = *a.config.KMS
  268. }
  269. a.keyManager, err = kms.New(ctx, options)
  270. if err != nil {
  271. return err
  272. }
  273. }
  274. // Initialize linkedca client if necessary. On a linked RA, the issuer
  275. // configuration might come from majordomo.
  276. var linkedcaClient *linkedCaClient
  277. if a.config.AuthorityConfig.EnableAdmin && a.linkedCAToken != "" && a.adminDB == nil {
  278. linkedcaClient, err = newLinkedCAClient(a.linkedCAToken)
  279. if err != nil {
  280. return err
  281. }
  282. // If authorityId is configured make sure it matches the one in the token
  283. if id := a.config.AuthorityConfig.AuthorityID; id != "" && !strings.EqualFold(id, linkedcaClient.authorityID) {
  284. return errors.New("error initializing linkedca: token authority and configured authority do not match")
  285. }
  286. a.config.AuthorityConfig.AuthorityID = linkedcaClient.authorityID
  287. linkedcaClient.Run()
  288. }
  289. // Initialize the X.509 CA Service if it has not been set in the options.
  290. if a.x509CAService == nil {
  291. var options casapi.Options
  292. if a.config.AuthorityConfig.Options != nil {
  293. options = *a.config.AuthorityConfig.Options
  294. }
  295. // AuthorityID might be empty. It's always available linked CAs/RAs.
  296. options.AuthorityID = a.config.AuthorityConfig.AuthorityID
  297. // Configure linked RA
  298. if linkedcaClient != nil && options.CertificateAuthority == "" {
  299. conf, err := linkedcaClient.GetConfiguration(ctx)
  300. if err != nil {
  301. return err
  302. }
  303. if conf.RaConfig != nil {
  304. options.CertificateAuthority = conf.RaConfig.CaUrl
  305. options.CertificateAuthorityFingerprint = conf.RaConfig.Fingerprint
  306. options.CertificateIssuer = &casapi.CertificateIssuer{
  307. Type: conf.RaConfig.Provisioner.Type.String(),
  308. Provisioner: conf.RaConfig.Provisioner.Name,
  309. }
  310. // Configure the RA authority type if needed
  311. if options.Type == "" {
  312. options.Type = casapi.StepCAS
  313. }
  314. }
  315. // Remote configuration is currently only supported on a linked RA
  316. if sc := conf.ServerConfig; sc != nil {
  317. if a.config.Address == "" {
  318. a.config.Address = sc.Address
  319. }
  320. if len(a.config.DNSNames) == 0 {
  321. a.config.DNSNames = sc.DnsNames
  322. }
  323. }
  324. }
  325. // Set the issuer password if passed in the flags.
  326. if options.CertificateIssuer != nil && a.issuerPassword != nil {
  327. options.CertificateIssuer.Password = string(a.issuerPassword)
  328. }
  329. // Read intermediate and create X509 signer for default CAS.
  330. if options.Is(casapi.SoftCAS) {
  331. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  332. if err != nil {
  333. return err
  334. }
  335. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  336. SigningKey: a.config.IntermediateKey,
  337. Password: a.password,
  338. })
  339. if err != nil {
  340. return err
  341. }
  342. // If not defined with an option, add intermediates to the list of
  343. // certificates used for name constraints validation at issuance
  344. // time.
  345. if len(a.intermediateX509Certs) == 0 {
  346. a.intermediateX509Certs = append(a.intermediateX509Certs, options.CertificateChain...)
  347. }
  348. }
  349. a.x509CAService, err = cas.New(ctx, options)
  350. if err != nil {
  351. return err
  352. }
  353. // Get root certificate from CAS.
  354. if srv, ok := a.x509CAService.(casapi.CertificateAuthorityGetter); ok {
  355. resp, err := srv.GetCertificateAuthority(&casapi.GetCertificateAuthorityRequest{
  356. Name: options.CertificateAuthority,
  357. })
  358. if err != nil {
  359. return err
  360. }
  361. a.rootX509Certs = append(a.rootX509Certs, resp.RootCertificate)
  362. }
  363. }
  364. // Read root certificates and store them in the certificates map.
  365. if len(a.rootX509Certs) == 0 {
  366. a.rootX509Certs = make([]*x509.Certificate, 0, len(a.config.Root))
  367. for _, path := range a.config.Root {
  368. crts, err := pemutil.ReadCertificateBundle(path)
  369. if err != nil {
  370. return err
  371. }
  372. a.rootX509Certs = append(a.rootX509Certs, crts...)
  373. }
  374. }
  375. for _, crt := range a.rootX509Certs {
  376. sum := sha256.Sum256(crt.Raw)
  377. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  378. }
  379. a.rootX509CertPool = x509.NewCertPool()
  380. for _, cert := range a.rootX509Certs {
  381. a.rootX509CertPool.AddCert(cert)
  382. }
  383. // Read federated certificates and store them in the certificates map.
  384. if len(a.federatedX509Certs) == 0 {
  385. a.federatedX509Certs = make([]*x509.Certificate, 0, len(a.config.FederatedRoots))
  386. for _, path := range a.config.FederatedRoots {
  387. crts, err := pemutil.ReadCertificateBundle(path)
  388. if err != nil {
  389. return err
  390. }
  391. a.federatedX509Certs = append(a.federatedX509Certs, crts...)
  392. }
  393. }
  394. for _, crt := range a.federatedX509Certs {
  395. sum := sha256.Sum256(crt.Raw)
  396. a.certificates.Store(hex.EncodeToString(sum[:]), crt)
  397. }
  398. // Decrypt and load SSH keys
  399. var tmplVars templates.Step
  400. if a.config.SSH != nil {
  401. if a.config.SSH.HostKey != "" {
  402. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  403. SigningKey: a.config.SSH.HostKey,
  404. Password: a.sshHostPassword,
  405. })
  406. if err != nil {
  407. return err
  408. }
  409. // If our signer is from sshagentkms, just unwrap it instead of
  410. // wrapping it in another layer, and this prevents crypto from
  411. // erroring out with: ssh: unsupported key type *agent.Key
  412. switch s := signer.(type) {
  413. case *sshagentkms.WrappedSSHSigner:
  414. a.sshCAHostCertSignKey = s.Signer
  415. case crypto.Signer:
  416. a.sshCAHostCertSignKey, err = ssh.NewSignerFromSigner(s)
  417. default:
  418. return errors.Errorf("unsupported signer type %T", signer)
  419. }
  420. if err != nil {
  421. return errors.Wrap(err, "error creating ssh signer")
  422. }
  423. // Append public key to list of host certs
  424. a.sshCAHostCerts = append(a.sshCAHostCerts, a.sshCAHostCertSignKey.PublicKey())
  425. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, a.sshCAHostCertSignKey.PublicKey())
  426. }
  427. if a.config.SSH.UserKey != "" {
  428. signer, err := a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  429. SigningKey: a.config.SSH.UserKey,
  430. Password: a.sshUserPassword,
  431. })
  432. if err != nil {
  433. return err
  434. }
  435. // If our signer is from sshagentkms, just unwrap it instead of
  436. // wrapping it in another layer, and this prevents crypto from
  437. // erroring out with: ssh: unsupported key type *agent.Key
  438. switch s := signer.(type) {
  439. case *sshagentkms.WrappedSSHSigner:
  440. a.sshCAUserCertSignKey = s.Signer
  441. case crypto.Signer:
  442. a.sshCAUserCertSignKey, err = ssh.NewSignerFromSigner(s)
  443. default:
  444. return errors.Errorf("unsupported signer type %T", signer)
  445. }
  446. if err != nil {
  447. return errors.Wrap(err, "error creating ssh signer")
  448. }
  449. // Append public key to list of user certs
  450. a.sshCAUserCerts = append(a.sshCAUserCerts, a.sshCAUserCertSignKey.PublicKey())
  451. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, a.sshCAUserCertSignKey.PublicKey())
  452. }
  453. // Append other public keys and add them to the template variables.
  454. for _, key := range a.config.SSH.Keys {
  455. publicKey := key.PublicKey()
  456. switch key.Type {
  457. case provisioner.SSHHostCert:
  458. if key.Federated {
  459. a.sshCAHostFederatedCerts = append(a.sshCAHostFederatedCerts, publicKey)
  460. } else {
  461. a.sshCAHostCerts = append(a.sshCAHostCerts, publicKey)
  462. }
  463. case provisioner.SSHUserCert:
  464. if key.Federated {
  465. a.sshCAUserFederatedCerts = append(a.sshCAUserFederatedCerts, publicKey)
  466. } else {
  467. a.sshCAUserCerts = append(a.sshCAUserCerts, publicKey)
  468. }
  469. default:
  470. return errors.Errorf("unsupported type %s", key.Type)
  471. }
  472. }
  473. }
  474. // Configure template variables. On the template variables HostFederatedKeys
  475. // and UserFederatedKeys we will skip the actual CA that will be available
  476. // in HostKey and UserKey.
  477. //
  478. // We cannot do it in the previous blocks because this configuration can be
  479. // injected using options.
  480. if a.sshCAHostCertSignKey != nil {
  481. tmplVars.SSH.HostKey = a.sshCAHostCertSignKey.PublicKey()
  482. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts[1:]...)
  483. } else {
  484. tmplVars.SSH.HostFederatedKeys = append(tmplVars.SSH.HostFederatedKeys, a.sshCAHostFederatedCerts...)
  485. }
  486. if a.sshCAUserCertSignKey != nil {
  487. tmplVars.SSH.UserKey = a.sshCAUserCertSignKey.PublicKey()
  488. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts[1:]...)
  489. } else {
  490. tmplVars.SSH.UserFederatedKeys = append(tmplVars.SSH.UserFederatedKeys, a.sshCAUserFederatedCerts...)
  491. }
  492. if a.config.AuthorityConfig.EnableAdmin {
  493. // Initialize step-ca Admin Database if it's not already initialized using
  494. // WithAdminDB.
  495. if a.adminDB == nil {
  496. if linkedcaClient != nil {
  497. a.adminDB = linkedcaClient
  498. } else {
  499. a.adminDB, err = adminDBNosql.New(a.db.(nosql.DB), admin.DefaultAuthorityID)
  500. if err != nil {
  501. return err
  502. }
  503. }
  504. }
  505. provs, err := a.adminDB.GetProvisioners(ctx)
  506. if err != nil {
  507. return admin.WrapErrorISE(err, "error loading provisioners to initialize authority")
  508. }
  509. if len(provs) == 0 && !strings.EqualFold(a.config.AuthorityConfig.DeploymentType, "linked") {
  510. // Migration will currently only be kicked off once, because either one or more provisioners
  511. // are migrated or a default JWK provisioner will be created in the DB. It won't run for
  512. // linked or hosted deployments. Not for linked, because that case is explicitly checked
  513. // for above. Not for hosted, because there'll be at least an existing OIDC provisioner.
  514. var firstJWKProvisioner *linkedca.Provisioner
  515. if len(a.config.AuthorityConfig.Provisioners) > 0 {
  516. // Existing provisioners detected; try migrating them to DB storage.
  517. a.initLogf("Starting migration of provisioners")
  518. for _, p := range a.config.AuthorityConfig.Provisioners {
  519. lp, err := ProvisionerToLinkedca(p)
  520. if err != nil {
  521. return admin.WrapErrorISE(err, "error transforming provisioner %q while migrating", p.GetName())
  522. }
  523. // Store the provisioner to be migrated
  524. if err := a.adminDB.CreateProvisioner(ctx, lp); err != nil {
  525. return admin.WrapErrorISE(err, "error creating provisioner %q while migrating", p.GetName())
  526. }
  527. // Mark the first JWK provisioner, so that it can be used for administration purposes
  528. if firstJWKProvisioner == nil && lp.Type == linkedca.Provisioner_JWK {
  529. firstJWKProvisioner = lp
  530. a.initLogf("Migrated JWK provisioner %q with admin permissions", p.GetName())
  531. } else {
  532. a.initLogf("Migrated %s provisioner %q", p.GetType(), p.GetName())
  533. }
  534. }
  535. c := a.config
  536. if c.WasLoadedFromFile() {
  537. // The provisioners in the configuration file can be deleted from
  538. // the file by editing it. Automatic rewriting of the file was considered
  539. // to be too surprising for users and not the right solution for all
  540. // use cases, so we leave it up to users to this themselves.
  541. a.initLogf("Provisioners that were migrated can now be removed from `ca.json` by editing it")
  542. }
  543. a.initLogf("Finished migrating provisioners")
  544. }
  545. // Create first JWK provisioner for remote administration purposes if none exists yet
  546. if firstJWKProvisioner == nil {
  547. firstJWKProvisioner, err = CreateFirstProvisioner(ctx, a.adminDB, string(a.password))
  548. if err != nil {
  549. return admin.WrapErrorISE(err, "error creating first provisioner")
  550. }
  551. a.initLogf("Created JWK provisioner %q with admin permissions", firstJWKProvisioner.GetName())
  552. }
  553. // Create first super admin, belonging to the first JWK provisioner
  554. // TODO(hs): pass a user-provided first super admin subject to here. With `ca init` it's
  555. // added to the DB immediately if using remote management. But when migrating from
  556. // ca.json to the DB, this option doesn't exist. Adding a flag just to do it during
  557. // migration isn't nice. We could opt for a user to change it afterwards. There exist
  558. // cases in which creation of `step` could lock out a user from API access. This is the
  559. // case if `step` isn't allowed to be signed by Name Constraints or the X.509 policy.
  560. // We have protection for that when creating and updating a policy, but if a policy or
  561. // Name Constraints are in use at the time of migration, that could lock the user out.
  562. superAdminSubject := "step"
  563. if err := a.adminDB.CreateAdmin(ctx, &linkedca.Admin{
  564. ProvisionerId: firstJWKProvisioner.Id,
  565. Subject: superAdminSubject,
  566. Type: linkedca.Admin_SUPER_ADMIN,
  567. }); err != nil {
  568. return admin.WrapErrorISE(err, "error creating first admin")
  569. }
  570. a.initLogf("Created super admin %q for JWK provisioner %q", superAdminSubject, firstJWKProvisioner.GetName())
  571. }
  572. }
  573. // Load Provisioners and Admins
  574. if err := a.ReloadAdminResources(ctx); err != nil {
  575. return err
  576. }
  577. // Check if a KMS with decryption capability is required and available
  578. if a.requiresDecrypter() {
  579. if _, ok := a.keyManager.(kmsapi.Decrypter); !ok {
  580. return errors.New("keymanager doesn't provide crypto.Decrypter")
  581. }
  582. }
  583. // TODO: decide if this is a good approach for providing the SCEP functionality
  584. // It currently mirrors the logic for the x509CAService
  585. if a.requiresSCEPService() && a.scepService == nil {
  586. var options scep.Options
  587. // Read intermediate and create X509 signer and decrypter for default CAS.
  588. options.CertificateChain, err = pemutil.ReadCertificateBundle(a.config.IntermediateCert)
  589. if err != nil {
  590. return err
  591. }
  592. options.CertificateChain = append(options.CertificateChain, a.rootX509Certs...)
  593. options.Signer, err = a.keyManager.CreateSigner(&kmsapi.CreateSignerRequest{
  594. SigningKey: a.config.IntermediateKey,
  595. Password: a.password,
  596. })
  597. if err != nil {
  598. return err
  599. }
  600. if km, ok := a.keyManager.(kmsapi.Decrypter); ok {
  601. options.Decrypter, err = km.CreateDecrypter(&kmsapi.CreateDecrypterRequest{
  602. DecryptionKey: a.config.IntermediateKey,
  603. Password: a.password,
  604. })
  605. if err != nil {
  606. return err
  607. }
  608. }
  609. a.scepService, err = scep.NewService(ctx, options)
  610. if err != nil {
  611. return err
  612. }
  613. // TODO: mimick the x509CAService GetCertificateAuthority here too?
  614. }
  615. // Load X509 constraints engine.
  616. //
  617. // This is currently only available in CA mode.
  618. if size := len(a.intermediateX509Certs); size > 0 {
  619. last := a.intermediateX509Certs[size-1]
  620. constraintCerts := make([]*x509.Certificate, 0, size+1)
  621. constraintCerts = append(constraintCerts, a.intermediateX509Certs...)
  622. for _, root := range a.rootX509Certs {
  623. if bytes.Equal(last.RawIssuer, root.RawSubject) && bytes.Equal(last.AuthorityKeyId, root.SubjectKeyId) {
  624. constraintCerts = append(constraintCerts, root)
  625. }
  626. }
  627. a.constraintsEngine = constraints.New(constraintCerts...)
  628. }
  629. // Load x509 and SSH Policy Engines
  630. if err := a.reloadPolicyEngines(ctx); err != nil {
  631. return err
  632. }
  633. // Configure templates, currently only ssh templates are supported.
  634. if a.sshCAHostCertSignKey != nil || a.sshCAUserCertSignKey != nil {
  635. a.templates = a.config.Templates
  636. if a.templates == nil {
  637. a.templates = templates.DefaultTemplates()
  638. }
  639. if a.templates.Data == nil {
  640. a.templates.Data = make(map[string]interface{})
  641. }
  642. a.templates.Data["Step"] = tmplVars
  643. }
  644. // Start the CRL generator, we can assume the configuration is validated.
  645. if a.config.CRL.IsEnabled() {
  646. // Default cache duration to the default one
  647. if v := a.config.CRL.CacheDuration; v == nil || v.Duration <= 0 {
  648. a.config.CRL.CacheDuration = config.DefaultCRLCacheDuration
  649. }
  650. // Start CRL generator
  651. if err := a.startCRLGenerator(); err != nil {
  652. return err
  653. }
  654. }
  655. // JWT numeric dates are seconds.
  656. a.startTime = time.Now().Truncate(time.Second)
  657. // Set flag indicating that initialization has been completed, and should
  658. // not be repeated.
  659. a.initOnce = true
  660. return nil
  661. }
  662. // initLogf is used to log initialization information. The output
  663. // can be disabled by starting the CA with the `--quiet` flag.
  664. func (a *Authority) initLogf(format string, v ...any) {
  665. if !a.quietInit {
  666. log.Printf(format, v...)
  667. }
  668. }
  669. // GetID returns the define authority id or a zero uuid.
  670. func (a *Authority) GetID() string {
  671. const zeroUUID = "00000000-0000-0000-0000-000000000000"
  672. if id := a.config.AuthorityConfig.AuthorityID; id != "" {
  673. return id
  674. }
  675. return zeroUUID
  676. }
  677. // GetDatabase returns the authority database. If the configuration does not
  678. // define a database, GetDatabase will return a db.SimpleDB instance.
  679. func (a *Authority) GetDatabase() db.AuthDB {
  680. return a.db
  681. }
  682. // GetAdminDatabase returns the admin database, if one exists.
  683. func (a *Authority) GetAdminDatabase() admin.DB {
  684. return a.adminDB
  685. }
  686. // GetConfig returns the config.
  687. func (a *Authority) GetConfig() *config.Config {
  688. return a.config
  689. }
  690. // GetInfo returns information about the authority.
  691. func (a *Authority) GetInfo() Info {
  692. ai := Info{
  693. StartTime: a.startTime,
  694. RootX509Certs: a.rootX509Certs,
  695. DNSNames: a.config.DNSNames,
  696. }
  697. if a.sshCAUserCertSignKey != nil {
  698. ai.SSHCAUserPublicKey = ssh.MarshalAuthorizedKey(a.sshCAUserCertSignKey.PublicKey())
  699. }
  700. if a.sshCAHostCertSignKey != nil {
  701. ai.SSHCAHostPublicKey = ssh.MarshalAuthorizedKey(a.sshCAHostCertSignKey.PublicKey())
  702. }
  703. return ai
  704. }
  705. // IsAdminAPIEnabled returns a boolean indicating whether the Admin API has
  706. // been enabled.
  707. func (a *Authority) IsAdminAPIEnabled() bool {
  708. return a.config.AuthorityConfig.EnableAdmin
  709. }
  710. // Shutdown safely shuts down any clients, databases, etc. held by the Authority.
  711. func (a *Authority) Shutdown() error {
  712. if a.crlTicker != nil {
  713. a.crlTicker.Stop()
  714. close(a.crlStopper)
  715. }
  716. if err := a.keyManager.Close(); err != nil {
  717. log.Printf("error closing the key manager: %v", err)
  718. }
  719. return a.db.Shutdown()
  720. }
  721. // CloseForReload closes internal services, to allow a safe reload.
  722. func (a *Authority) CloseForReload() {
  723. if a.crlTicker != nil {
  724. a.crlTicker.Stop()
  725. close(a.crlStopper)
  726. }
  727. if err := a.keyManager.Close(); err != nil {
  728. log.Printf("error closing the key manager: %v", err)
  729. }
  730. if client, ok := a.adminDB.(*linkedCaClient); ok {
  731. client.Stop()
  732. }
  733. }
  734. // IsRevoked returns whether or not a certificate has been
  735. // revoked before.
  736. func (a *Authority) IsRevoked(sn string) (bool, error) {
  737. // Check the passive revocation table.
  738. if lca, ok := a.adminDB.(interface {
  739. IsRevoked(string) (bool, error)
  740. }); ok {
  741. return lca.IsRevoked(sn)
  742. }
  743. return a.db.IsRevoked(sn)
  744. }
  745. // requiresDecrypter returns whether the Authority
  746. // requires a KMS that provides a crypto.Decrypter
  747. // Currently this is only required when SCEP is
  748. // enabled.
  749. func (a *Authority) requiresDecrypter() bool {
  750. return a.requiresSCEPService()
  751. }
  752. // requiresSCEPService iterates over the configured provisioners
  753. // and determines if one of them is a SCEP provisioner.
  754. func (a *Authority) requiresSCEPService() bool {
  755. for _, p := range a.config.AuthorityConfig.Provisioners {
  756. if p.GetType() == provisioner.TypeSCEP {
  757. return true
  758. }
  759. }
  760. return false
  761. }
  762. // GetSCEPService returns the configured SCEP Service.
  763. //
  764. // TODO: this function is intended to exist temporarily in order to make SCEP
  765. // work more easily. It can be made more correct by using the right
  766. // interfaces/abstractions after it works as expected.
  767. func (a *Authority) GetSCEPService() *scep.Service {
  768. return a.scepService
  769. }
  770. func (a *Authority) startCRLGenerator() error {
  771. if !a.config.CRL.IsEnabled() {
  772. return nil
  773. }
  774. // Check that there is a valid CRL in the DB right now. If it doesn't exist
  775. // or is expired, generate one now
  776. _, ok := a.db.(db.CertificateRevocationListDB)
  777. if !ok {
  778. return errors.Errorf("CRL Generation requested, but database does not support CRL generation")
  779. }
  780. // Always create a new CRL on startup in case the CA has been down and the
  781. // time to next expected CRL update is less than the cache duration.
  782. if err := a.GenerateCertificateRevocationList(); err != nil {
  783. return errors.Wrap(err, "could not generate a CRL")
  784. }
  785. a.crlStopper = make(chan struct{}, 1)
  786. a.crlTicker = time.NewTicker(a.config.CRL.TickerDuration())
  787. go func() {
  788. for {
  789. select {
  790. case <-a.crlTicker.C:
  791. log.Println("Regenerating CRL")
  792. if err := a.GenerateCertificateRevocationList(); err != nil {
  793. log.Printf("error regenerating the CRL: %v", err)
  794. }
  795. case <-a.crlStopper:
  796. return
  797. }
  798. }
  799. }()
  800. return nil
  801. }