ssh.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. // Check if authority is allowed to sign the certificate
  216. if err := a.isAllowedToSignSSHCertificate(certTpl); err != nil {
  217. var pe *policy.NamePolicyError
  218. if errors.As(err, &pe) && pe.Reason == policy.NotAllowed {
  219. return nil, &errs.Error{
  220. // NOTE: custom forbidden error, so that denied name is sent to client
  221. // as well as shown in the logs.
  222. Status: http.StatusForbidden,
  223. Err: fmt.Errorf("authority not allowed to sign: %w", err),
  224. Msg: fmt.Sprintf("The request was forbidden by the certificate authority: %s", err.Error()),
  225. }
  226. }
  227. return nil, errs.InternalServerErr(err,
  228. errs.WithMessage("authority.SignSSH: error creating ssh certificate"),
  229. )
  230. }
  231. // Sign certificate.
  232. cert, err := sshutil.CreateCertificate(certTpl, signer)
  233. if err != nil {
  234. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error signing certificate")
  235. }
  236. // User provisioners validators.
  237. for _, v := range validators {
  238. if err := v.Valid(cert, opts); err != nil {
  239. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  240. }
  241. }
  242. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  243. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db")
  244. }
  245. return cert, nil
  246. }
  247. // isAllowedToSignSSHCertificate checks if the Authority is allowed to sign the SSH certificate.
  248. func (a *Authority) isAllowedToSignSSHCertificate(cert *ssh.Certificate) error {
  249. return a.policyEngine.IsSSHCertificateAllowed(cert)
  250. }
  251. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  252. func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  253. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  254. return nil, errs.BadRequest("cannot renew a certificate without validity period")
  255. }
  256. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  257. return nil, err
  258. }
  259. backdate := a.config.AuthorityConfig.Backdate.Duration
  260. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  261. now := time.Now()
  262. va := now.Add(-1 * backdate)
  263. vb := now.Add(duration - backdate)
  264. // Build base certificate with the old key.
  265. // Nonce and serial will be automatically generated on signing.
  266. certTpl := &ssh.Certificate{
  267. Key: oldCert.Key,
  268. CertType: oldCert.CertType,
  269. KeyId: oldCert.KeyId,
  270. ValidPrincipals: oldCert.ValidPrincipals,
  271. Permissions: oldCert.Permissions,
  272. Reserved: oldCert.Reserved,
  273. ValidAfter: uint64(va.Unix()),
  274. ValidBefore: uint64(vb.Unix()),
  275. }
  276. // Get signer from authority keys
  277. var signer ssh.Signer
  278. switch certTpl.CertType {
  279. case ssh.UserCert:
  280. if a.sshCAUserCertSignKey == nil {
  281. return nil, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  282. }
  283. signer = a.sshCAUserCertSignKey
  284. case ssh.HostCert:
  285. if a.sshCAHostCertSignKey == nil {
  286. return nil, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  287. }
  288. signer = a.sshCAHostCertSignKey
  289. default:
  290. return nil, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  291. }
  292. // Sign certificate.
  293. cert, err := sshutil.CreateCertificate(certTpl, signer)
  294. if err != nil {
  295. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  296. }
  297. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  298. return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  299. }
  300. return cert, nil
  301. }
  302. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  303. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  304. var validators []provisioner.SSHCertValidator
  305. for _, op := range signOpts {
  306. switch o := op.(type) {
  307. // validate the ssh.Certificate
  308. case provisioner.SSHCertValidator:
  309. validators = append(validators, o)
  310. default:
  311. return nil, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  312. }
  313. }
  314. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  315. return nil, errs.BadRequest("cannot rekey a certificate without validity period")
  316. }
  317. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  318. return nil, err
  319. }
  320. backdate := a.config.AuthorityConfig.Backdate.Duration
  321. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  322. now := time.Now()
  323. va := now.Add(-1 * backdate)
  324. vb := now.Add(duration - backdate)
  325. // Build base certificate with the new key.
  326. // Nonce and serial will be automatically generated on signing.
  327. cert := &ssh.Certificate{
  328. Key: pub,
  329. CertType: oldCert.CertType,
  330. KeyId: oldCert.KeyId,
  331. ValidPrincipals: oldCert.ValidPrincipals,
  332. Permissions: oldCert.Permissions,
  333. Reserved: oldCert.Reserved,
  334. ValidAfter: uint64(va.Unix()),
  335. ValidBefore: uint64(vb.Unix()),
  336. }
  337. // Get signer from authority keys
  338. var signer ssh.Signer
  339. switch cert.CertType {
  340. case ssh.UserCert:
  341. if a.sshCAUserCertSignKey == nil {
  342. return nil, errs.NotImplemented("rekeySSH; user certificate signing is not enabled")
  343. }
  344. signer = a.sshCAUserCertSignKey
  345. case ssh.HostCert:
  346. if a.sshCAHostCertSignKey == nil {
  347. return nil, errs.NotImplemented("rekeySSH; host certificate signing is not enabled")
  348. }
  349. signer = a.sshCAHostCertSignKey
  350. default:
  351. return nil, errs.BadRequest("unexpected certificate type '%d'", cert.CertType)
  352. }
  353. var err error
  354. // Sign certificate.
  355. cert, err = sshutil.CreateCertificate(cert, signer)
  356. if err != nil {
  357. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  358. }
  359. // Apply validators from provisioner.
  360. for _, v := range validators {
  361. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  362. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  363. }
  364. }
  365. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  366. return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  367. }
  368. return cert, nil
  369. }
  370. func (a *Authority) storeSSHCertificate(cert *ssh.Certificate) error {
  371. type sshCertificateStorer interface {
  372. StoreSSHCertificate(crt *ssh.Certificate) error
  373. }
  374. if s, ok := a.adminDB.(sshCertificateStorer); ok {
  375. return s.StoreSSHCertificate(cert)
  376. }
  377. return a.db.StoreSSHCertificate(cert)
  378. }
  379. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  380. // the given certificate.
  381. func IsValidForAddUser(cert *ssh.Certificate) error {
  382. if cert.CertType != ssh.UserCert {
  383. return errs.Forbidden("certificate is not a user certificate")
  384. }
  385. switch len(cert.ValidPrincipals) {
  386. case 0:
  387. return errs.Forbidden("certificate does not have any principals")
  388. case 1:
  389. return nil
  390. case 2:
  391. // OIDC provisioners adds a second principal with the email address.
  392. // @ cannot be the first character.
  393. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  394. return nil
  395. }
  396. return errs.Forbidden("certificate does not have only one principal")
  397. default:
  398. return errs.Forbidden("certificate does not have only one principal")
  399. }
  400. }
  401. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  402. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  403. if a.sshCAUserCertSignKey == nil {
  404. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  405. }
  406. if err := IsValidForAddUser(subject); err != nil {
  407. return nil, err
  408. }
  409. nonce, err := randutil.ASCII(32)
  410. if err != nil {
  411. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  412. }
  413. var serial uint64
  414. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  415. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  416. }
  417. signer := a.sshCAUserCertSignKey
  418. principal := subject.ValidPrincipals[0]
  419. addUserPrincipal := a.getAddUserPrincipal()
  420. cert := &ssh.Certificate{
  421. Nonce: []byte(nonce),
  422. Key: key,
  423. Serial: serial,
  424. CertType: ssh.UserCert,
  425. KeyId: principal + "-" + addUserPrincipal,
  426. ValidPrincipals: []string{addUserPrincipal},
  427. ValidAfter: subject.ValidAfter,
  428. ValidBefore: subject.ValidBefore,
  429. Permissions: ssh.Permissions{
  430. CriticalOptions: map[string]string{
  431. "force-command": a.getAddUserCommand(principal),
  432. },
  433. },
  434. SignatureKey: signer.PublicKey(),
  435. }
  436. // Get bytes for signing trailing the signature length.
  437. data := cert.Marshal()
  438. data = data[:len(data)-4]
  439. // Sign the certificate
  440. sig, err := signer.Sign(rand.Reader, data)
  441. if err != nil {
  442. return nil, err
  443. }
  444. cert.Signature = sig
  445. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  446. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  447. }
  448. return cert, nil
  449. }
  450. // CheckSSHHost checks the given principal has been registered before.
  451. func (a *Authority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  452. if a.sshCheckHostFunc != nil {
  453. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  454. if err != nil {
  455. return false, errs.Wrap(http.StatusInternalServerError, err,
  456. "checkSSHHost: error from injected checkSSHHost func")
  457. }
  458. return exists, nil
  459. }
  460. exists, err := a.db.IsSSHHost(principal)
  461. if err != nil {
  462. if err == db.ErrNotImplemented {
  463. return false, errs.Wrap(http.StatusNotImplemented, err,
  464. "checkSSHHost: isSSHHost is not implemented")
  465. }
  466. return false, errs.Wrap(http.StatusInternalServerError, err,
  467. "checkSSHHost: error checking if hosts exists")
  468. }
  469. return exists, nil
  470. }
  471. // GetSSHHosts returns a list of valid host principals.
  472. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  473. if a.sshGetHostsFunc != nil {
  474. hosts, err := a.sshGetHostsFunc(ctx, cert)
  475. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  476. }
  477. hostnames, err := a.db.GetSSHHostPrincipals()
  478. if err != nil {
  479. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  480. }
  481. hosts := make([]config.Host, len(hostnames))
  482. for i, hn := range hostnames {
  483. hosts[i] = config.Host{Hostname: hn}
  484. }
  485. return hosts, nil
  486. }
  487. func (a *Authority) getAddUserPrincipal() (cmd string) {
  488. if a.config.SSH.AddUserPrincipal == "" {
  489. return SSHAddUserPrincipal
  490. }
  491. return a.config.SSH.AddUserPrincipal
  492. }
  493. func (a *Authority) getAddUserCommand(principal string) string {
  494. var cmd string
  495. if a.config.SSH.AddUserCommand == "" {
  496. cmd = SSHAddUserCommand
  497. } else {
  498. cmd = a.config.SSH.AddUserCommand
  499. }
  500. return strings.ReplaceAll(cmd, "<principal>", principal)
  501. }