authority.go 31 KB

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