authority.go 31 KB

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