authority.go 32 KB

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