ssh.go 20 KB

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