4
0

ssh.go 23 KB

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