authority.go 33 KB

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