authority.go 34 KB

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