ssh.go 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704
  1. package authority
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/x509"
  6. "encoding/binary"
  7. "errors"
  8. "net/http"
  9. "strings"
  10. "time"
  11. "golang.org/x/crypto/ssh"
  12. "go.step.sm/crypto/randutil"
  13. "go.step.sm/crypto/sshutil"
  14. "github.com/smallstep/certificates/authority/config"
  15. "github.com/smallstep/certificates/authority/provisioner"
  16. "github.com/smallstep/certificates/db"
  17. "github.com/smallstep/certificates/errs"
  18. "github.com/smallstep/certificates/templates"
  19. "github.com/smallstep/certificates/webhook"
  20. )
  21. const (
  22. // SSHAddUserPrincipal is the principal that will run the add user command.
  23. // Defaults to "provisioner" but it can be changed in the configuration.
  24. SSHAddUserPrincipal = "provisioner"
  25. // SSHAddUserCommand is the default command to run to add a new user.
  26. // Defaults to "sudo useradd -m <principal>; nc -q0 localhost 22" but it can be changed in the
  27. // configuration. The string "<principal>" will be replace by the new
  28. // principal to add.
  29. SSHAddUserCommand = "sudo useradd -m <principal>; nc -q0 localhost 22"
  30. )
  31. // GetSSHRoots returns the SSH User and Host public keys.
  32. func (a *Authority) GetSSHRoots(context.Context) (*config.SSHKeys, error) {
  33. return &config.SSHKeys{
  34. HostKeys: a.sshCAHostCerts,
  35. UserKeys: a.sshCAUserCerts,
  36. }, nil
  37. }
  38. // GetSSHFederation returns the public keys for federated SSH signers.
  39. func (a *Authority) GetSSHFederation(context.Context) (*config.SSHKeys, error) {
  40. return &config.SSHKeys{
  41. HostKeys: a.sshCAHostFederatedCerts,
  42. UserKeys: a.sshCAUserFederatedCerts,
  43. }, nil
  44. }
  45. // GetSSHConfig returns rendered templates for clients (user) or servers (host).
  46. func (a *Authority) GetSSHConfig(_ context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  47. if a.sshCAUserCertSignKey == nil && a.sshCAHostCertSignKey == nil {
  48. return nil, errs.NotFound("getSSHConfig: ssh is not configured")
  49. }
  50. if a.templates == nil {
  51. return nil, errs.NotFound("getSSHConfig: ssh templates are not configured")
  52. }
  53. var ts []templates.Template
  54. switch typ {
  55. case provisioner.SSHUserCert:
  56. if a.templates != nil && a.templates.SSH != nil {
  57. ts = a.templates.SSH.User
  58. }
  59. case provisioner.SSHHostCert:
  60. if a.templates != nil && a.templates.SSH != nil {
  61. ts = a.templates.SSH.Host
  62. }
  63. default:
  64. return nil, errs.BadRequest("invalid certificate type '%s'", typ)
  65. }
  66. // Merge user and default data
  67. var mergedData map[string]interface{}
  68. if len(data) == 0 {
  69. mergedData = a.templates.Data
  70. } else {
  71. mergedData = make(map[string]interface{}, len(a.templates.Data)+1)
  72. mergedData["User"] = data
  73. for k, v := range a.templates.Data {
  74. mergedData[k] = v
  75. }
  76. }
  77. // Render templates
  78. output := []templates.Output{}
  79. for _, t := range ts {
  80. if err := t.Load(); err != nil {
  81. return nil, err
  82. }
  83. // Check for required variables.
  84. if err := t.ValidateRequiredData(data); err != nil {
  85. return nil, errs.BadRequestErr(err, "%v, please use `--set <key=value>` flag", err)
  86. }
  87. o, err := t.Output(mergedData)
  88. if err != nil {
  89. return nil, err
  90. }
  91. // Backwards compatibility for version of the cli older than v0.18.0.
  92. // Before v0.18.0 we were not passing any value for SSHTemplateVersionKey
  93. // from the cli.
  94. if o.Name == "step_includes.tpl" && data[templates.SSHTemplateVersionKey] == "" {
  95. o.Type = templates.File
  96. o.Path = strings.TrimPrefix(o.Path, "${STEPPATH}/")
  97. }
  98. output = append(output, o)
  99. }
  100. return output, nil
  101. }
  102. // GetSSHBastion returns the bastion configuration, for the given pair user,
  103. // hostname.
  104. func (a *Authority) GetSSHBastion(ctx context.Context, user, hostname string) (*config.Bastion, error) {
  105. if a.sshBastionFunc != nil {
  106. bs, err := a.sshBastionFunc(ctx, user, hostname)
  107. return bs, errs.Wrap(http.StatusInternalServerError, err, "authority.GetSSHBastion")
  108. }
  109. if a.config.SSH != nil {
  110. if a.config.SSH.Bastion != nil && a.config.SSH.Bastion.Hostname != "" {
  111. // Do not return a bastion for a bastion host.
  112. //
  113. // This condition might fail if a different name or IP is used.
  114. // Trying to resolve hostnames to IPs and compare them won't be a
  115. // complete solution because it depends on the network
  116. // configuration, of the CA and clients and can also return false
  117. // positives. Although not perfect, this simple solution will work
  118. // in most cases.
  119. if !strings.EqualFold(hostname, a.config.SSH.Bastion.Hostname) {
  120. return a.config.SSH.Bastion, nil
  121. }
  122. }
  123. //nolint:nilnil // legacy
  124. return nil, nil
  125. }
  126. return nil, errs.NotFound("authority.GetSSHBastion; ssh is not configured")
  127. }
  128. // SignSSH creates a signed SSH certificate with the given public key and options.
  129. func (a *Authority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  130. cert, prov, err := a.signSSH(ctx, key, opts, signOpts...)
  131. a.meter.SSHSigned(prov, err)
  132. return cert, err
  133. }
  134. func (a *Authority) signSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, provisioner.Interface, error) {
  135. var (
  136. certOptions []sshutil.Option
  137. mods []provisioner.SSHCertModifier
  138. validators []provisioner.SSHCertValidator
  139. )
  140. // Validate given options.
  141. if err := opts.Validate(); err != nil {
  142. return nil, nil, err
  143. }
  144. // Set backdate with the configured value
  145. opts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  146. var prov provisioner.Interface
  147. var webhookCtl webhookController
  148. for _, op := range signOpts {
  149. switch o := op.(type) {
  150. // Capture current provisioner
  151. case provisioner.Interface:
  152. prov = o
  153. // add options to NewCertificate
  154. case provisioner.SSHCertificateOptions:
  155. certOptions = append(certOptions, o.Options(opts)...)
  156. // modify the ssh.Certificate
  157. case provisioner.SSHCertModifier:
  158. mods = append(mods, o)
  159. // validate the ssh.Certificate
  160. case provisioner.SSHCertValidator:
  161. validators = append(validators, o)
  162. // validate the given SSHOptions
  163. case provisioner.SSHCertOptionsValidator:
  164. if err := o.Valid(opts); err != nil {
  165. return nil, prov, errs.BadRequestErr(err, "error validating ssh certificate options")
  166. }
  167. // call webhooks
  168. case webhookController:
  169. webhookCtl = o
  170. default:
  171. return nil, prov, errs.InternalServer("authority.SignSSH: invalid extra option type %T", o)
  172. }
  173. }
  174. // Simulated certificate request with request options.
  175. cr := sshutil.CertificateRequest{
  176. Type: opts.CertType,
  177. KeyID: opts.KeyID,
  178. Principals: opts.Principals,
  179. Key: key,
  180. }
  181. // Call enriching webhooks
  182. if err := a.callEnrichingWebhooksSSH(ctx, prov, webhookCtl, cr); err != nil {
  183. return nil, prov, errs.ApplyOptions(
  184. errs.ForbiddenErr(err, err.Error()),
  185. errs.WithKeyVal("signOptions", signOpts),
  186. )
  187. }
  188. // Create certificate from template.
  189. certificate, err := sshutil.NewCertificate(cr, certOptions...)
  190. if err != nil {
  191. var te *sshutil.TemplateError
  192. switch {
  193. case errors.As(err, &te):
  194. return nil, prov, errs.ApplyOptions(
  195. errs.BadRequestErr(err, err.Error()),
  196. errs.WithKeyVal("signOptions", signOpts),
  197. )
  198. case strings.HasPrefix(err.Error(), "error unmarshaling certificate"):
  199. // explicitly check for unmarshaling errors, which are most probably caused by JSON template syntax errors
  200. return nil, prov, errs.InternalServerErr(templatingError(err),
  201. errs.WithKeyVal("signOptions", signOpts),
  202. errs.WithMessage("error applying certificate template"),
  203. )
  204. default:
  205. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH")
  206. }
  207. }
  208. // Get actual *ssh.Certificate and continue with provisioner modifiers.
  209. certTpl := certificate.GetCertificate()
  210. // Use SignSSHOptions to modify the certificate validity. It will be later
  211. // checked or set if not defined.
  212. if err := opts.ModifyValidity(certTpl); err != nil {
  213. return nil, prov, errs.BadRequestErr(err, err.Error())
  214. }
  215. // Use provisioner modifiers.
  216. for _, m := range mods {
  217. if err := m.Modify(certTpl, opts); err != nil {
  218. return nil, prov, errs.ForbiddenErr(err, "error creating ssh certificate")
  219. }
  220. }
  221. // Get signer from authority keys
  222. var signer ssh.Signer
  223. switch certTpl.CertType {
  224. case ssh.UserCert:
  225. if a.sshCAUserCertSignKey == nil {
  226. return nil, prov, errs.NotImplemented("authority.SignSSH: user certificate signing is not enabled")
  227. }
  228. signer = a.sshCAUserCertSignKey
  229. case ssh.HostCert:
  230. if a.sshCAHostCertSignKey == nil {
  231. return nil, prov, errs.NotImplemented("authority.SignSSH: host certificate signing is not enabled")
  232. }
  233. signer = a.sshCAHostCertSignKey
  234. default:
  235. return nil, prov, errs.InternalServer("authority.SignSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  236. }
  237. // Check if authority is allowed to sign the certificate
  238. if err := a.isAllowedToSignSSHCertificate(certTpl); err != nil {
  239. var ee *errs.Error
  240. if errors.As(err, &ee) {
  241. return nil, prov, ee
  242. }
  243. return nil, prov, errs.InternalServerErr(err,
  244. errs.WithMessage("authority.SignSSH: error creating ssh certificate"),
  245. )
  246. }
  247. // Send certificate to webhooks for authorization
  248. if err := a.callAuthorizingWebhooksSSH(ctx, prov, webhookCtl, certificate, certTpl); err != nil {
  249. return nil, prov, errs.ApplyOptions(
  250. errs.ForbiddenErr(err, "authority.SignSSH: error signing certificate"),
  251. )
  252. }
  253. // Sign certificate.
  254. cert, err := sshutil.CreateCertificate(certTpl, signer)
  255. if err != nil {
  256. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error signing certificate")
  257. }
  258. // User provisioners validators.
  259. for _, v := range validators {
  260. if err := v.Valid(cert, opts); err != nil {
  261. return nil, prov, errs.ForbiddenErr(err, "error validating ssh certificate")
  262. }
  263. }
  264. if err := a.storeSSHCertificate(prov, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  265. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db")
  266. }
  267. return cert, prov, nil
  268. }
  269. // isAllowedToSignSSHCertificate checks if the Authority is allowed to sign the SSH certificate.
  270. func (a *Authority) isAllowedToSignSSHCertificate(cert *ssh.Certificate) error {
  271. return a.policyEngine.IsSSHCertificateAllowed(cert)
  272. }
  273. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  274. func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  275. cert, prov, err := a.renewSSH(ctx, oldCert)
  276. a.meter.SSHRenewed(prov, err)
  277. return cert, err
  278. }
  279. func (a *Authority) renewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, provisioner.Interface, error) {
  280. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  281. return nil, nil, errs.BadRequest("cannot renew a certificate without validity period")
  282. }
  283. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  284. return nil, nil, err
  285. }
  286. // Attempt to extract the provisioner from the token.
  287. var prov provisioner.Interface
  288. if token, ok := provisioner.TokenFromContext(ctx); ok {
  289. prov, _, _ = a.getProvisionerFromToken(token)
  290. }
  291. backdate := a.config.AuthorityConfig.Backdate.Duration
  292. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  293. now := time.Now()
  294. va := now.Add(-1 * backdate)
  295. vb := now.Add(duration - backdate)
  296. // Build base certificate with the old key.
  297. // Nonce and serial will be automatically generated on signing.
  298. certTpl := &ssh.Certificate{
  299. Key: oldCert.Key,
  300. CertType: oldCert.CertType,
  301. KeyId: oldCert.KeyId,
  302. ValidPrincipals: oldCert.ValidPrincipals,
  303. Permissions: oldCert.Permissions,
  304. Reserved: oldCert.Reserved,
  305. ValidAfter: uint64(va.Unix()),
  306. ValidBefore: uint64(vb.Unix()),
  307. }
  308. // Get signer from authority keys
  309. var signer ssh.Signer
  310. switch certTpl.CertType {
  311. case ssh.UserCert:
  312. if a.sshCAUserCertSignKey == nil {
  313. return nil, prov, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  314. }
  315. signer = a.sshCAUserCertSignKey
  316. case ssh.HostCert:
  317. if a.sshCAHostCertSignKey == nil {
  318. return nil, prov, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  319. }
  320. signer = a.sshCAHostCertSignKey
  321. default:
  322. return nil, prov, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  323. }
  324. // Sign certificate.
  325. cert, err := sshutil.CreateCertificate(certTpl, signer)
  326. if err != nil {
  327. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  328. }
  329. if err := a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  330. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  331. }
  332. return cert, prov, nil
  333. }
  334. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  335. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  336. cert, prov, err := a.rekeySSH(ctx, oldCert, pub, signOpts...)
  337. a.meter.SSHRekeyed(prov, err)
  338. return cert, err
  339. }
  340. func (a *Authority) rekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, provisioner.Interface, error) {
  341. var prov provisioner.Interface
  342. var validators []provisioner.SSHCertValidator
  343. for _, op := range signOpts {
  344. switch o := op.(type) {
  345. // Capture current provisioner
  346. case provisioner.Interface:
  347. prov = o
  348. // validate the ssh.Certificate
  349. case provisioner.SSHCertValidator:
  350. validators = append(validators, o)
  351. default:
  352. return nil, prov, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  353. }
  354. }
  355. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  356. return nil, prov, errs.BadRequest("cannot rekey a certificate without validity period")
  357. }
  358. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  359. return nil, prov, err
  360. }
  361. backdate := a.config.AuthorityConfig.Backdate.Duration
  362. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  363. now := time.Now()
  364. va := now.Add(-1 * backdate)
  365. vb := now.Add(duration - backdate)
  366. // Build base certificate with the new key.
  367. // Nonce and serial will be automatically generated on signing.
  368. cert := &ssh.Certificate{
  369. Key: pub,
  370. CertType: oldCert.CertType,
  371. KeyId: oldCert.KeyId,
  372. ValidPrincipals: oldCert.ValidPrincipals,
  373. Permissions: oldCert.Permissions,
  374. Reserved: oldCert.Reserved,
  375. ValidAfter: uint64(va.Unix()),
  376. ValidBefore: uint64(vb.Unix()),
  377. }
  378. // Get signer from authority keys
  379. var signer ssh.Signer
  380. switch cert.CertType {
  381. case ssh.UserCert:
  382. if a.sshCAUserCertSignKey == nil {
  383. return nil, prov, errs.NotImplemented("rekeySSH; user certificate signing is not enabled")
  384. }
  385. signer = a.sshCAUserCertSignKey
  386. case ssh.HostCert:
  387. if a.sshCAHostCertSignKey == nil {
  388. return nil, prov, errs.NotImplemented("rekeySSH; host certificate signing is not enabled")
  389. }
  390. signer = a.sshCAHostCertSignKey
  391. default:
  392. return nil, prov, errs.BadRequest("unexpected certificate type '%d'", cert.CertType)
  393. }
  394. var err error
  395. // Sign certificate.
  396. cert, err = sshutil.CreateCertificate(cert, signer)
  397. if err != nil {
  398. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  399. }
  400. // Apply validators from provisioner.
  401. for _, v := range validators {
  402. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  403. return nil, prov, errs.ForbiddenErr(err, "error validating ssh certificate")
  404. }
  405. }
  406. if err := a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  407. return nil, prov, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  408. }
  409. return cert, prov, nil
  410. }
  411. func (a *Authority) storeSSHCertificate(prov provisioner.Interface, cert *ssh.Certificate) error {
  412. type sshCertificateStorer interface {
  413. StoreSSHCertificate(provisioner.Interface, *ssh.Certificate) error
  414. }
  415. // Store certificate in admindb or linkedca
  416. switch s := a.adminDB.(type) {
  417. case sshCertificateStorer:
  418. return s.StoreSSHCertificate(prov, cert)
  419. case db.CertificateStorer:
  420. return s.StoreSSHCertificate(cert)
  421. }
  422. // Store certificate in localdb
  423. switch s := a.db.(type) {
  424. case sshCertificateStorer:
  425. return s.StoreSSHCertificate(prov, cert)
  426. case db.CertificateStorer:
  427. return s.StoreSSHCertificate(cert)
  428. default:
  429. return nil
  430. }
  431. }
  432. func (a *Authority) storeRenewedSSHCertificate(prov provisioner.Interface, parent, cert *ssh.Certificate) error {
  433. type sshRenewerCertificateStorer interface {
  434. StoreRenewedSSHCertificate(p provisioner.Interface, parent, cert *ssh.Certificate) error
  435. }
  436. // Store certificate in admindb or linkedca
  437. switch s := a.adminDB.(type) {
  438. case sshRenewerCertificateStorer:
  439. return s.StoreRenewedSSHCertificate(prov, parent, cert)
  440. case db.CertificateStorer:
  441. return s.StoreSSHCertificate(cert)
  442. }
  443. // Store certificate in localdb
  444. switch s := a.db.(type) {
  445. case sshRenewerCertificateStorer:
  446. return s.StoreRenewedSSHCertificate(prov, parent, cert)
  447. case db.CertificateStorer:
  448. return s.StoreSSHCertificate(cert)
  449. default:
  450. return nil
  451. }
  452. }
  453. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  454. // the given certificate.
  455. func IsValidForAddUser(cert *ssh.Certificate) error {
  456. if cert.CertType != ssh.UserCert {
  457. return errs.Forbidden("certificate is not a user certificate")
  458. }
  459. switch len(cert.ValidPrincipals) {
  460. case 0:
  461. return errs.Forbidden("certificate does not have any principals")
  462. case 1:
  463. return nil
  464. case 2:
  465. // OIDC provisioners adds a second principal with the email address.
  466. // @ cannot be the first character.
  467. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  468. return nil
  469. }
  470. return errs.Forbidden("certificate does not have only one principal")
  471. default:
  472. return errs.Forbidden("certificate does not have only one principal")
  473. }
  474. }
  475. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  476. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  477. if a.sshCAUserCertSignKey == nil {
  478. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  479. }
  480. if err := IsValidForAddUser(subject); err != nil {
  481. return nil, err
  482. }
  483. nonce, err := randutil.ASCII(32)
  484. if err != nil {
  485. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  486. }
  487. var serial uint64
  488. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  489. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  490. }
  491. // Attempt to extract the provisioner from the token.
  492. var prov provisioner.Interface
  493. if token, ok := provisioner.TokenFromContext(ctx); ok {
  494. prov, _, _ = a.getProvisionerFromToken(token)
  495. }
  496. signer := a.sshCAUserCertSignKey
  497. principal := subject.ValidPrincipals[0]
  498. addUserPrincipal := a.getAddUserPrincipal()
  499. cert := &ssh.Certificate{
  500. Nonce: []byte(nonce),
  501. Key: key,
  502. Serial: serial,
  503. CertType: ssh.UserCert,
  504. KeyId: principal + "-" + addUserPrincipal,
  505. ValidPrincipals: []string{addUserPrincipal},
  506. ValidAfter: subject.ValidAfter,
  507. ValidBefore: subject.ValidBefore,
  508. Permissions: ssh.Permissions{
  509. CriticalOptions: map[string]string{
  510. "force-command": a.getAddUserCommand(principal),
  511. },
  512. },
  513. SignatureKey: signer.PublicKey(),
  514. }
  515. // Get bytes for signing trailing the signature length.
  516. data := cert.Marshal()
  517. data = data[:len(data)-4]
  518. // Sign the certificate
  519. sig, err := signer.Sign(rand.Reader, data)
  520. if err != nil {
  521. return nil, err
  522. }
  523. cert.Signature = sig
  524. if err = a.storeRenewedSSHCertificate(prov, subject, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  525. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  526. }
  527. return cert, nil
  528. }
  529. // CheckSSHHost checks the given principal has been registered before.
  530. func (a *Authority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  531. if a.sshCheckHostFunc != nil {
  532. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  533. if err != nil {
  534. return false, errs.Wrap(http.StatusInternalServerError, err,
  535. "checkSSHHost: error from injected checkSSHHost func")
  536. }
  537. return exists, nil
  538. }
  539. exists, err := a.db.IsSSHHost(principal)
  540. if err != nil {
  541. if errors.Is(err, db.ErrNotImplemented) {
  542. return false, errs.Wrap(http.StatusNotImplemented, err,
  543. "checkSSHHost: isSSHHost is not implemented")
  544. }
  545. return false, errs.Wrap(http.StatusInternalServerError, err,
  546. "checkSSHHost: error checking if hosts exists")
  547. }
  548. return exists, nil
  549. }
  550. // GetSSHHosts returns a list of valid host principals.
  551. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  552. if a.GetConfig().AuthorityConfig.DisableGetSSHHosts {
  553. return nil, errs.New(http.StatusNotFound, "ssh hosts list api disabled")
  554. }
  555. if a.sshGetHostsFunc != nil {
  556. hosts, err := a.sshGetHostsFunc(ctx, cert)
  557. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  558. }
  559. hostnames, err := a.db.GetSSHHostPrincipals()
  560. if err != nil {
  561. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  562. }
  563. hosts := make([]config.Host, len(hostnames))
  564. for i, hn := range hostnames {
  565. hosts[i] = config.Host{Hostname: hn}
  566. }
  567. return hosts, nil
  568. }
  569. func (a *Authority) getAddUserPrincipal() (cmd string) {
  570. if a.config.SSH.AddUserPrincipal == "" {
  571. return SSHAddUserPrincipal
  572. }
  573. return a.config.SSH.AddUserPrincipal
  574. }
  575. func (a *Authority) getAddUserCommand(principal string) string {
  576. var cmd string
  577. if a.config.SSH.AddUserCommand == "" {
  578. cmd = SSHAddUserCommand
  579. } else {
  580. cmd = a.config.SSH.AddUserCommand
  581. }
  582. return strings.ReplaceAll(cmd, "<principal>", principal)
  583. }
  584. func (a *Authority) callEnrichingWebhooksSSH(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, cr sshutil.CertificateRequest) (err error) {
  585. if webhookCtl == nil {
  586. return
  587. }
  588. defer func() { a.meter.SSHWebhookEnriched(prov, err) }()
  589. var whEnrichReq *webhook.RequestBody
  590. if whEnrichReq, err = webhook.NewRequestBody(
  591. webhook.WithSSHCertificateRequest(cr),
  592. ); err == nil {
  593. err = webhookCtl.Enrich(ctx, whEnrichReq)
  594. }
  595. return
  596. }
  597. func (a *Authority) callAuthorizingWebhooksSSH(ctx context.Context, prov provisioner.Interface, webhookCtl webhookController, cert *sshutil.Certificate, certTpl *ssh.Certificate) (err error) {
  598. if webhookCtl == nil {
  599. return
  600. }
  601. defer func() { a.meter.SSHWebhookAuthorized(prov, err) }()
  602. var whAuthBody *webhook.RequestBody
  603. if whAuthBody, err = webhook.NewRequestBody(
  604. webhook.WithSSHCertificate(cert, certTpl),
  605. ); err == nil {
  606. err = webhookCtl.Authorize(ctx, whAuthBody)
  607. }
  608. return
  609. }