authority.go 32 KB

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