ssh.go 20 KB

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