ssh.go 23 KB

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