ssh.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688
  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(ctx 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. var (
  131. certOptions []sshutil.Option
  132. mods []provisioner.SSHCertModifier
  133. validators []provisioner.SSHCertValidator
  134. )
  135. // Validate given options.
  136. if err := opts.Validate(); err != nil {
  137. return nil, err
  138. }
  139. // Set backdate with the configured value
  140. opts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  141. var prov provisioner.Interface
  142. var webhookCtl webhookController
  143. for _, op := range signOpts {
  144. switch o := op.(type) {
  145. // Capture current provisioner
  146. case provisioner.Interface:
  147. prov = o
  148. // add options to NewCertificate
  149. case provisioner.SSHCertificateOptions:
  150. certOptions = append(certOptions, o.Options(opts)...)
  151. // modify the ssh.Certificate
  152. case provisioner.SSHCertModifier:
  153. mods = append(mods, o)
  154. // validate the ssh.Certificate
  155. case provisioner.SSHCertValidator:
  156. validators = append(validators, o)
  157. // validate the given SSHOptions
  158. case provisioner.SSHCertOptionsValidator:
  159. if err := o.Valid(opts); err != nil {
  160. return nil, errs.BadRequestErr(err, "error validating ssh certificate options")
  161. }
  162. // call webhooks
  163. case webhookController:
  164. webhookCtl = o
  165. default:
  166. return nil, errs.InternalServer("authority.SignSSH: invalid extra option type %T", o)
  167. }
  168. }
  169. // Simulated certificate request with request options.
  170. cr := sshutil.CertificateRequest{
  171. Type: opts.CertType,
  172. KeyID: opts.KeyID,
  173. Principals: opts.Principals,
  174. Key: key,
  175. }
  176. // Call enriching webhooks
  177. if err := callEnrichingWebhooksSSH(webhookCtl, cr); err != nil {
  178. return nil, errs.ApplyOptions(
  179. errs.ForbiddenErr(err, err.Error()),
  180. errs.WithKeyVal("signOptions", signOpts),
  181. )
  182. }
  183. // Create certificate from template.
  184. certificate, err := sshutil.NewCertificate(cr, certOptions...)
  185. if err != nil {
  186. var te *sshutil.TemplateError
  187. if errors.As(err, &te) {
  188. return nil, errs.ApplyOptions(
  189. errs.BadRequestErr(err, err.Error()),
  190. errs.WithKeyVal("signOptions", signOpts),
  191. )
  192. }
  193. // explicitly check for unmarshaling errors, which are most probably caused by JSON template syntax errors
  194. if strings.HasPrefix(err.Error(), "error unmarshaling certificate") {
  195. return nil, errs.InternalServerErr(templatingError(err),
  196. errs.WithKeyVal("signOptions", signOpts),
  197. errs.WithMessage("error applying certificate template"),
  198. )
  199. }
  200. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH")
  201. }
  202. // Get actual *ssh.Certificate and continue with provisioner modifiers.
  203. certTpl := certificate.GetCertificate()
  204. // Use SignSSHOptions to modify the certificate validity. It will be later
  205. // checked or set if not defined.
  206. if err := opts.ModifyValidity(certTpl); err != nil {
  207. return nil, errs.BadRequestErr(err, err.Error())
  208. }
  209. // Use provisioner modifiers.
  210. for _, m := range mods {
  211. if err := m.Modify(certTpl, opts); err != nil {
  212. return nil, errs.ForbiddenErr(err, "error creating ssh certificate")
  213. }
  214. }
  215. // Get signer from authority keys
  216. var signer ssh.Signer
  217. switch certTpl.CertType {
  218. case ssh.UserCert:
  219. if a.sshCAUserCertSignKey == nil {
  220. return nil, errs.NotImplemented("authority.SignSSH: user certificate signing is not enabled")
  221. }
  222. signer = a.sshCAUserCertSignKey
  223. case ssh.HostCert:
  224. if a.sshCAHostCertSignKey == nil {
  225. return nil, errs.NotImplemented("authority.SignSSH: host certificate signing is not enabled")
  226. }
  227. signer = a.sshCAHostCertSignKey
  228. default:
  229. return nil, errs.InternalServer("authority.SignSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  230. }
  231. // Check if authority is allowed to sign the certificate
  232. if err := a.isAllowedToSignSSHCertificate(certTpl); err != nil {
  233. var ee *errs.Error
  234. if errors.As(err, &ee) {
  235. return nil, ee
  236. }
  237. return nil, errs.InternalServerErr(err,
  238. errs.WithMessage("authority.SignSSH: error creating ssh certificate"),
  239. )
  240. }
  241. // Send certificate to webhooks for authorization
  242. if err := callAuthorizingWebhooksSSH(webhookCtl, certificate, certTpl); err != nil {
  243. return nil, errs.ApplyOptions(
  244. errs.ForbiddenErr(err, "authority.SignSSH: error signing certificate"),
  245. )
  246. }
  247. // Sign certificate.
  248. cert, err := sshutil.CreateCertificate(certTpl, signer)
  249. if err != nil {
  250. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error signing certificate")
  251. }
  252. // User provisioners validators.
  253. for _, v := range validators {
  254. if err := v.Valid(cert, opts); err != nil {
  255. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  256. }
  257. }
  258. if err = a.storeSSHCertificate(prov, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  259. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db")
  260. }
  261. return cert, nil
  262. }
  263. // isAllowedToSignSSHCertificate checks if the Authority is allowed to sign the SSH certificate.
  264. func (a *Authority) isAllowedToSignSSHCertificate(cert *ssh.Certificate) error {
  265. return a.policyEngine.IsSSHCertificateAllowed(cert)
  266. }
  267. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  268. func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  269. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  270. return nil, errs.BadRequest("cannot renew a certificate without validity period")
  271. }
  272. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  273. return nil, err
  274. }
  275. // Attempt to extract the provisioner from the token.
  276. var prov provisioner.Interface
  277. if token, ok := provisioner.TokenFromContext(ctx); ok {
  278. prov, _, _ = a.getProvisionerFromToken(token)
  279. }
  280. backdate := a.config.AuthorityConfig.Backdate.Duration
  281. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  282. now := time.Now()
  283. va := now.Add(-1 * backdate)
  284. vb := now.Add(duration - backdate)
  285. // Build base certificate with the old key.
  286. // Nonce and serial will be automatically generated on signing.
  287. certTpl := &ssh.Certificate{
  288. Key: oldCert.Key,
  289. CertType: oldCert.CertType,
  290. KeyId: oldCert.KeyId,
  291. ValidPrincipals: oldCert.ValidPrincipals,
  292. Permissions: oldCert.Permissions,
  293. Reserved: oldCert.Reserved,
  294. ValidAfter: uint64(va.Unix()),
  295. ValidBefore: uint64(vb.Unix()),
  296. }
  297. // Get signer from authority keys
  298. var signer ssh.Signer
  299. switch certTpl.CertType {
  300. case ssh.UserCert:
  301. if a.sshCAUserCertSignKey == nil {
  302. return nil, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  303. }
  304. signer = a.sshCAUserCertSignKey
  305. case ssh.HostCert:
  306. if a.sshCAHostCertSignKey == nil {
  307. return nil, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  308. }
  309. signer = a.sshCAHostCertSignKey
  310. default:
  311. return nil, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  312. }
  313. // Sign certificate.
  314. cert, err := sshutil.CreateCertificate(certTpl, signer)
  315. if err != nil {
  316. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  317. }
  318. if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  319. return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  320. }
  321. return cert, nil
  322. }
  323. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  324. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  325. var validators []provisioner.SSHCertValidator
  326. var prov provisioner.Interface
  327. for _, op := range signOpts {
  328. switch o := op.(type) {
  329. // Capture current provisioner
  330. case provisioner.Interface:
  331. prov = o
  332. // validate the ssh.Certificate
  333. case provisioner.SSHCertValidator:
  334. validators = append(validators, o)
  335. default:
  336. return nil, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  337. }
  338. }
  339. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  340. return nil, errs.BadRequest("cannot rekey a certificate without validity period")
  341. }
  342. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  343. return nil, err
  344. }
  345. backdate := a.config.AuthorityConfig.Backdate.Duration
  346. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  347. now := time.Now()
  348. va := now.Add(-1 * backdate)
  349. vb := now.Add(duration - backdate)
  350. // Build base certificate with the new key.
  351. // Nonce and serial will be automatically generated on signing.
  352. cert := &ssh.Certificate{
  353. Key: pub,
  354. CertType: oldCert.CertType,
  355. KeyId: oldCert.KeyId,
  356. ValidPrincipals: oldCert.ValidPrincipals,
  357. Permissions: oldCert.Permissions,
  358. Reserved: oldCert.Reserved,
  359. ValidAfter: uint64(va.Unix()),
  360. ValidBefore: uint64(vb.Unix()),
  361. }
  362. // Get signer from authority keys
  363. var signer ssh.Signer
  364. switch cert.CertType {
  365. case ssh.UserCert:
  366. if a.sshCAUserCertSignKey == nil {
  367. return nil, errs.NotImplemented("rekeySSH; user certificate signing is not enabled")
  368. }
  369. signer = a.sshCAUserCertSignKey
  370. case ssh.HostCert:
  371. if a.sshCAHostCertSignKey == nil {
  372. return nil, errs.NotImplemented("rekeySSH; host certificate signing is not enabled")
  373. }
  374. signer = a.sshCAHostCertSignKey
  375. default:
  376. return nil, errs.BadRequest("unexpected certificate type '%d'", cert.CertType)
  377. }
  378. var err error
  379. // Sign certificate.
  380. cert, err = sshutil.CreateCertificate(cert, signer)
  381. if err != nil {
  382. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  383. }
  384. // Apply validators from provisioner.
  385. for _, v := range validators {
  386. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  387. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  388. }
  389. }
  390. if err = a.storeRenewedSSHCertificate(prov, oldCert, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  391. return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  392. }
  393. return cert, nil
  394. }
  395. func (a *Authority) storeSSHCertificate(prov provisioner.Interface, cert *ssh.Certificate) error {
  396. type sshCertificateStorer interface {
  397. StoreSSHCertificate(provisioner.Interface, *ssh.Certificate) error
  398. }
  399. // Store certificate in admindb or linkedca
  400. switch s := a.adminDB.(type) {
  401. case sshCertificateStorer:
  402. return s.StoreSSHCertificate(prov, cert)
  403. case db.CertificateStorer:
  404. return s.StoreSSHCertificate(cert)
  405. }
  406. // Store certificate in localdb
  407. switch s := a.db.(type) {
  408. case sshCertificateStorer:
  409. return s.StoreSSHCertificate(prov, cert)
  410. case db.CertificateStorer:
  411. return s.StoreSSHCertificate(cert)
  412. default:
  413. return nil
  414. }
  415. }
  416. func (a *Authority) storeRenewedSSHCertificate(prov provisioner.Interface, parent, cert *ssh.Certificate) error {
  417. type sshRenewerCertificateStorer interface {
  418. StoreRenewedSSHCertificate(p provisioner.Interface, parent, cert *ssh.Certificate) error
  419. }
  420. // Store certificate in admindb or linkedca
  421. switch s := a.adminDB.(type) {
  422. case sshRenewerCertificateStorer:
  423. return s.StoreRenewedSSHCertificate(prov, parent, cert)
  424. case db.CertificateStorer:
  425. return s.StoreSSHCertificate(cert)
  426. }
  427. // Store certificate in localdb
  428. switch s := a.db.(type) {
  429. case sshRenewerCertificateStorer:
  430. return s.StoreRenewedSSHCertificate(prov, parent, cert)
  431. case db.CertificateStorer:
  432. return s.StoreSSHCertificate(cert)
  433. default:
  434. return nil
  435. }
  436. }
  437. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  438. // the given certificate.
  439. func IsValidForAddUser(cert *ssh.Certificate) error {
  440. if cert.CertType != ssh.UserCert {
  441. return errs.Forbidden("certificate is not a user certificate")
  442. }
  443. switch len(cert.ValidPrincipals) {
  444. case 0:
  445. return errs.Forbidden("certificate does not have any principals")
  446. case 1:
  447. return nil
  448. case 2:
  449. // OIDC provisioners adds a second principal with the email address.
  450. // @ cannot be the first character.
  451. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  452. return nil
  453. }
  454. return errs.Forbidden("certificate does not have only one principal")
  455. default:
  456. return errs.Forbidden("certificate does not have only one principal")
  457. }
  458. }
  459. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  460. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  461. if a.sshCAUserCertSignKey == nil {
  462. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  463. }
  464. if err := IsValidForAddUser(subject); err != nil {
  465. return nil, err
  466. }
  467. nonce, err := randutil.ASCII(32)
  468. if err != nil {
  469. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  470. }
  471. var serial uint64
  472. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  473. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  474. }
  475. // Attempt to extract the provisioner from the token.
  476. var prov provisioner.Interface
  477. if token, ok := provisioner.TokenFromContext(ctx); ok {
  478. prov, _, _ = a.getProvisionerFromToken(token)
  479. }
  480. signer := a.sshCAUserCertSignKey
  481. principal := subject.ValidPrincipals[0]
  482. addUserPrincipal := a.getAddUserPrincipal()
  483. cert := &ssh.Certificate{
  484. Nonce: []byte(nonce),
  485. Key: key,
  486. Serial: serial,
  487. CertType: ssh.UserCert,
  488. KeyId: principal + "-" + addUserPrincipal,
  489. ValidPrincipals: []string{addUserPrincipal},
  490. ValidAfter: subject.ValidAfter,
  491. ValidBefore: subject.ValidBefore,
  492. Permissions: ssh.Permissions{
  493. CriticalOptions: map[string]string{
  494. "force-command": a.getAddUserCommand(principal),
  495. },
  496. },
  497. SignatureKey: signer.PublicKey(),
  498. }
  499. // Get bytes for signing trailing the signature length.
  500. data := cert.Marshal()
  501. data = data[:len(data)-4]
  502. // Sign the certificate
  503. sig, err := signer.Sign(rand.Reader, data)
  504. if err != nil {
  505. return nil, err
  506. }
  507. cert.Signature = sig
  508. if err = a.storeRenewedSSHCertificate(prov, subject, cert); err != nil && !errors.Is(err, db.ErrNotImplemented) {
  509. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  510. }
  511. return cert, nil
  512. }
  513. // CheckSSHHost checks the given principal has been registered before.
  514. func (a *Authority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  515. if a.sshCheckHostFunc != nil {
  516. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  517. if err != nil {
  518. return false, errs.Wrap(http.StatusInternalServerError, err,
  519. "checkSSHHost: error from injected checkSSHHost func")
  520. }
  521. return exists, nil
  522. }
  523. exists, err := a.db.IsSSHHost(principal)
  524. if err != nil {
  525. if errors.Is(err, db.ErrNotImplemented) {
  526. return false, errs.Wrap(http.StatusNotImplemented, err,
  527. "checkSSHHost: isSSHHost is not implemented")
  528. }
  529. return false, errs.Wrap(http.StatusInternalServerError, err,
  530. "checkSSHHost: error checking if hosts exists")
  531. }
  532. return exists, nil
  533. }
  534. // GetSSHHosts returns a list of valid host principals.
  535. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  536. if a.GetConfig().AuthorityConfig.DisableGetSSHHosts {
  537. return nil, errs.New(http.StatusNotFound, "ssh hosts list api disabled")
  538. }
  539. if a.sshGetHostsFunc != nil {
  540. hosts, err := a.sshGetHostsFunc(ctx, cert)
  541. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  542. }
  543. hostnames, err := a.db.GetSSHHostPrincipals()
  544. if err != nil {
  545. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  546. }
  547. hosts := make([]config.Host, len(hostnames))
  548. for i, hn := range hostnames {
  549. hosts[i] = config.Host{Hostname: hn}
  550. }
  551. return hosts, nil
  552. }
  553. func (a *Authority) getAddUserPrincipal() (cmd string) {
  554. if a.config.SSH.AddUserPrincipal == "" {
  555. return SSHAddUserPrincipal
  556. }
  557. return a.config.SSH.AddUserPrincipal
  558. }
  559. func (a *Authority) getAddUserCommand(principal string) string {
  560. var cmd string
  561. if a.config.SSH.AddUserCommand == "" {
  562. cmd = SSHAddUserCommand
  563. } else {
  564. cmd = a.config.SSH.AddUserCommand
  565. }
  566. return strings.ReplaceAll(cmd, "<principal>", principal)
  567. }
  568. func callEnrichingWebhooksSSH(webhookCtl webhookController, cr sshutil.CertificateRequest) error {
  569. if webhookCtl == nil {
  570. return nil
  571. }
  572. whEnrichReq, err := webhook.NewRequestBody(
  573. webhook.WithSSHCertificateRequest(cr),
  574. )
  575. if err != nil {
  576. return err
  577. }
  578. if err := webhookCtl.Enrich(whEnrichReq); err != nil {
  579. return err
  580. }
  581. return nil
  582. }
  583. func callAuthorizingWebhooksSSH(webhookCtl webhookController, cert *sshutil.Certificate, certTpl *ssh.Certificate) error {
  584. if webhookCtl == nil {
  585. return nil
  586. }
  587. whAuthBody, err := webhook.NewRequestBody(
  588. webhook.WithSSHCertificate(cert, certTpl),
  589. )
  590. if err != nil {
  591. return err
  592. }
  593. if err := webhookCtl.Authorize(whAuthBody); err != nil {
  594. return err
  595. }
  596. return nil
  597. }