4
0

ssh.go 20 KB

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