ssh.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550
  1. package authority
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "crypto/x509"
  6. "encoding/binary"
  7. "net/http"
  8. "strings"
  9. "time"
  10. "github.com/smallstep/certificates/authority/config"
  11. "github.com/smallstep/certificates/authority/provisioner"
  12. "github.com/smallstep/certificates/db"
  13. "github.com/smallstep/certificates/errs"
  14. "github.com/smallstep/certificates/templates"
  15. "go.step.sm/crypto/randutil"
  16. "go.step.sm/crypto/sshutil"
  17. "golang.org/x/crypto/ssh"
  18. )
  19. const (
  20. // SSHAddUserPrincipal is the principal that will run the add user command.
  21. // Defaults to "provisioner" but it can be changed in the configuration.
  22. SSHAddUserPrincipal = "provisioner"
  23. // SSHAddUserCommand is the default command to run to add a new user.
  24. // Defaults to "sudo useradd -m <principal>; nc -q0 localhost 22" but it can be changed in the
  25. // configuration. The string "<principal>" will be replace by the new
  26. // principal to add.
  27. SSHAddUserCommand = "sudo useradd -m <principal>; nc -q0 localhost 22"
  28. )
  29. // GetSSHRoots returns the SSH User and Host public keys.
  30. func (a *Authority) GetSSHRoots(context.Context) (*config.SSHKeys, error) {
  31. return &config.SSHKeys{
  32. HostKeys: a.sshCAHostCerts,
  33. UserKeys: a.sshCAUserCerts,
  34. }, nil
  35. }
  36. // GetSSHFederation returns the public keys for federated SSH signers.
  37. func (a *Authority) GetSSHFederation(context.Context) (*config.SSHKeys, error) {
  38. return &config.SSHKeys{
  39. HostKeys: a.sshCAHostFederatedCerts,
  40. UserKeys: a.sshCAUserFederatedCerts,
  41. }, nil
  42. }
  43. // GetSSHConfig returns rendered templates for clients (user) or servers (host).
  44. func (a *Authority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  45. if a.sshCAUserCertSignKey == nil && a.sshCAHostCertSignKey == nil {
  46. return nil, errs.NotFound("getSSHConfig: ssh is not configured")
  47. }
  48. if a.templates == nil {
  49. return nil, errs.NotFound("getSSHConfig: ssh templates are not configured")
  50. }
  51. var ts []templates.Template
  52. switch typ {
  53. case provisioner.SSHUserCert:
  54. if a.templates != nil && a.templates.SSH != nil {
  55. ts = a.templates.SSH.User
  56. }
  57. case provisioner.SSHHostCert:
  58. if a.templates != nil && a.templates.SSH != nil {
  59. ts = a.templates.SSH.Host
  60. }
  61. default:
  62. return nil, errs.BadRequest("invalid certificate type '%s'", typ)
  63. }
  64. // Merge user and default data
  65. var mergedData map[string]interface{}
  66. if len(data) == 0 {
  67. mergedData = a.templates.Data
  68. } else {
  69. mergedData = make(map[string]interface{}, len(a.templates.Data)+1)
  70. mergedData["User"] = data
  71. for k, v := range a.templates.Data {
  72. mergedData[k] = v
  73. }
  74. }
  75. // Render templates
  76. output := []templates.Output{}
  77. for _, t := range ts {
  78. if err := t.Load(); err != nil {
  79. return nil, err
  80. }
  81. // Check for required variables.
  82. if err := t.ValidateRequiredData(data); err != nil {
  83. return nil, errs.BadRequestErr(err, "%v, please use `--set <key=value>` flag", err)
  84. }
  85. o, err := t.Output(mergedData)
  86. if err != nil {
  87. return nil, err
  88. }
  89. // Backwards compatibility for version of the cli older than v0.18.0.
  90. // Before v0.18.0 we were not passing any value for SSHTemplateVersionKey
  91. // from the cli.
  92. if o.Name == "step_includes.tpl" && data[templates.SSHTemplateVersionKey] == "" {
  93. o.Type = templates.File
  94. o.Path = strings.TrimPrefix(o.Path, "${STEPPATH}/")
  95. }
  96. output = append(output, o)
  97. }
  98. return output, nil
  99. }
  100. // GetSSHBastion returns the bastion configuration, for the given pair user,
  101. // hostname.
  102. func (a *Authority) GetSSHBastion(ctx context.Context, user, hostname string) (*config.Bastion, error) {
  103. if a.sshBastionFunc != nil {
  104. bs, err := a.sshBastionFunc(ctx, user, hostname)
  105. return bs, errs.Wrap(http.StatusInternalServerError, err, "authority.GetSSHBastion")
  106. }
  107. if a.config.SSH != nil {
  108. if a.config.SSH.Bastion != nil && a.config.SSH.Bastion.Hostname != "" {
  109. // Do not return a bastion for a bastion host.
  110. //
  111. // This condition might fail if a different name or IP is used.
  112. // Trying to resolve hostnames to IPs and compare them won't be a
  113. // complete solution because it depends on the network
  114. // configuration, of the CA and clients and can also return false
  115. // positives. Although not perfect, this simple solution will work
  116. // in most cases.
  117. if !strings.EqualFold(hostname, a.config.SSH.Bastion.Hostname) {
  118. return a.config.SSH.Bastion, nil
  119. }
  120. }
  121. return nil, nil
  122. }
  123. return nil, errs.NotFound("authority.GetSSHBastion; ssh is not configured")
  124. }
  125. // SignSSH creates a signed SSH certificate with the given public key and options.
  126. func (a *Authority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  127. var (
  128. certOptions []sshutil.Option
  129. mods []provisioner.SSHCertModifier
  130. validators []provisioner.SSHCertValidator
  131. )
  132. // Validate given options.
  133. if err := opts.Validate(); err != nil {
  134. return nil, err
  135. }
  136. // Set backdate with the configured value
  137. opts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  138. for _, op := range signOpts {
  139. switch o := op.(type) {
  140. // add options to NewCertificate
  141. case provisioner.SSHCertificateOptions:
  142. certOptions = append(certOptions, o.Options(opts)...)
  143. // modify the ssh.Certificate
  144. case provisioner.SSHCertModifier:
  145. mods = append(mods, o)
  146. // validate the ssh.Certificate
  147. case provisioner.SSHCertValidator:
  148. validators = append(validators, o)
  149. // validate the given SSHOptions
  150. case provisioner.SSHCertOptionsValidator:
  151. if err := o.Valid(opts); err != nil {
  152. return nil, errs.BadRequestErr(err, "error validating ssh certificate options")
  153. }
  154. default:
  155. return nil, errs.InternalServer("authority.SignSSH: invalid extra option type %T", o)
  156. }
  157. }
  158. // Simulated certificate request with request options.
  159. cr := sshutil.CertificateRequest{
  160. Type: opts.CertType,
  161. KeyID: opts.KeyID,
  162. Principals: opts.Principals,
  163. Key: key,
  164. }
  165. // Create certificate from template.
  166. certificate, err := sshutil.NewCertificate(cr, certOptions...)
  167. if err != nil {
  168. if _, ok := err.(*sshutil.TemplateError); ok {
  169. return nil, errs.ApplyOptions(
  170. errs.BadRequestErr(err, err.Error()),
  171. errs.WithKeyVal("signOptions", signOpts),
  172. )
  173. }
  174. // explicitly check for unmarshaling errors, which are most probably caused by JSON template syntax errors
  175. if strings.HasPrefix(err.Error(), "error unmarshaling certificate") {
  176. return nil, errs.InternalServerErr(templatingError(err),
  177. errs.WithKeyVal("signOptions", signOpts),
  178. errs.WithMessage("error applying certificate template"),
  179. )
  180. }
  181. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH")
  182. }
  183. // Get actual *ssh.Certificate and continue with provisioner modifiers.
  184. certTpl := certificate.GetCertificate()
  185. // Use SignSSHOptions to modify the certificate validity. It will be later
  186. // checked or set if not defined.
  187. if err := opts.ModifyValidity(certTpl); err != nil {
  188. return nil, errs.BadRequestErr(err, err.Error())
  189. }
  190. // Use provisioner modifiers.
  191. for _, m := range mods {
  192. if err := m.Modify(certTpl, opts); err != nil {
  193. return nil, errs.ForbiddenErr(err, "error creating ssh certificate")
  194. }
  195. }
  196. // Get signer from authority keys
  197. var signer ssh.Signer
  198. switch certTpl.CertType {
  199. case ssh.UserCert:
  200. if a.sshCAUserCertSignKey == nil {
  201. return nil, errs.NotImplemented("authority.SignSSH: user certificate signing is not enabled")
  202. }
  203. signer = a.sshCAUserCertSignKey
  204. case ssh.HostCert:
  205. if a.sshCAHostCertSignKey == nil {
  206. return nil, errs.NotImplemented("authority.SignSSH: host certificate signing is not enabled")
  207. }
  208. signer = a.sshCAHostCertSignKey
  209. default:
  210. return nil, errs.InternalServer("authority.SignSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  211. }
  212. // Sign certificate.
  213. cert, err := sshutil.CreateCertificate(certTpl, signer)
  214. if err != nil {
  215. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error signing certificate")
  216. }
  217. // User provisioners validators.
  218. for _, v := range validators {
  219. if err := v.Valid(cert, opts); err != nil {
  220. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  221. }
  222. }
  223. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  224. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db")
  225. }
  226. return cert, nil
  227. }
  228. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  229. func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  230. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  231. return nil, errs.BadRequest("cannot renew a certificate without validity period")
  232. }
  233. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  234. return nil, err
  235. }
  236. backdate := a.config.AuthorityConfig.Backdate.Duration
  237. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  238. now := time.Now()
  239. va := now.Add(-1 * backdate)
  240. vb := now.Add(duration - backdate)
  241. // Build base certificate with the old key.
  242. // Nonce and serial will be automatically generated on signing.
  243. certTpl := &ssh.Certificate{
  244. Key: oldCert.Key,
  245. CertType: oldCert.CertType,
  246. KeyId: oldCert.KeyId,
  247. ValidPrincipals: oldCert.ValidPrincipals,
  248. Permissions: oldCert.Permissions,
  249. Reserved: oldCert.Reserved,
  250. ValidAfter: uint64(va.Unix()),
  251. ValidBefore: uint64(vb.Unix()),
  252. }
  253. // Get signer from authority keys
  254. var signer ssh.Signer
  255. switch certTpl.CertType {
  256. case ssh.UserCert:
  257. if a.sshCAUserCertSignKey == nil {
  258. return nil, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  259. }
  260. signer = a.sshCAUserCertSignKey
  261. case ssh.HostCert:
  262. if a.sshCAHostCertSignKey == nil {
  263. return nil, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  264. }
  265. signer = a.sshCAHostCertSignKey
  266. default:
  267. return nil, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  268. }
  269. // Sign certificate.
  270. cert, err := sshutil.CreateCertificate(certTpl, signer)
  271. if err != nil {
  272. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  273. }
  274. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  275. return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  276. }
  277. return cert, nil
  278. }
  279. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  280. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  281. var validators []provisioner.SSHCertValidator
  282. for _, op := range signOpts {
  283. switch o := op.(type) {
  284. // validate the ssh.Certificate
  285. case provisioner.SSHCertValidator:
  286. validators = append(validators, o)
  287. default:
  288. return nil, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  289. }
  290. }
  291. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  292. return nil, errs.BadRequest("cannot rekey 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 new key.
  303. // Nonce and serial will be automatically generated on signing.
  304. cert := &ssh.Certificate{
  305. Key: pub,
  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 cert.CertType {
  317. case ssh.UserCert:
  318. if a.sshCAUserCertSignKey == nil {
  319. return nil, errs.NotImplemented("rekeySSH; 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("rekeySSH; host certificate signing is not enabled")
  325. }
  326. signer = a.sshCAHostCertSignKey
  327. default:
  328. return nil, errs.BadRequest("unexpected certificate type '%d'", cert.CertType)
  329. }
  330. var err error
  331. // Sign certificate.
  332. cert, err = sshutil.CreateCertificate(cert, signer)
  333. if err != nil {
  334. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  335. }
  336. // Apply validators from provisioner.
  337. for _, v := range validators {
  338. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  339. return nil, errs.ForbiddenErr(err, "error validating ssh certificate")
  340. }
  341. }
  342. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  343. return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  344. }
  345. return cert, nil
  346. }
  347. func (a *Authority) storeSSHCertificate(cert *ssh.Certificate) error {
  348. type sshCertificateStorer interface {
  349. StoreSSHCertificate(crt *ssh.Certificate) error
  350. }
  351. if s, ok := a.adminDB.(sshCertificateStorer); ok {
  352. return s.StoreSSHCertificate(cert)
  353. }
  354. return a.db.StoreSSHCertificate(cert)
  355. }
  356. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  357. // the given certificate.
  358. func IsValidForAddUser(cert *ssh.Certificate) error {
  359. if cert.CertType != ssh.UserCert {
  360. return errs.Forbidden("certificate is not a user certificate")
  361. }
  362. switch len(cert.ValidPrincipals) {
  363. case 0:
  364. return errs.Forbidden("certificate does not have any principals")
  365. case 1:
  366. return nil
  367. case 2:
  368. // OIDC provisioners adds a second principal with the email address.
  369. // @ cannot be the first character.
  370. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  371. return nil
  372. }
  373. return errs.Forbidden("certificate does not have only one principal")
  374. default:
  375. return errs.Forbidden("certificate does not have only one principal")
  376. }
  377. }
  378. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  379. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  380. if a.sshCAUserCertSignKey == nil {
  381. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  382. }
  383. if err := IsValidForAddUser(subject); err != nil {
  384. return nil, err
  385. }
  386. nonce, err := randutil.ASCII(32)
  387. if err != nil {
  388. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  389. }
  390. var serial uint64
  391. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  392. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  393. }
  394. signer := a.sshCAUserCertSignKey
  395. principal := subject.ValidPrincipals[0]
  396. addUserPrincipal := a.getAddUserPrincipal()
  397. cert := &ssh.Certificate{
  398. Nonce: []byte(nonce),
  399. Key: key,
  400. Serial: serial,
  401. CertType: ssh.UserCert,
  402. KeyId: principal + "-" + addUserPrincipal,
  403. ValidPrincipals: []string{addUserPrincipal},
  404. ValidAfter: subject.ValidAfter,
  405. ValidBefore: subject.ValidBefore,
  406. Permissions: ssh.Permissions{
  407. CriticalOptions: map[string]string{
  408. "force-command": a.getAddUserCommand(principal),
  409. },
  410. },
  411. SignatureKey: signer.PublicKey(),
  412. }
  413. // Get bytes for signing trailing the signature length.
  414. data := cert.Marshal()
  415. data = data[:len(data)-4]
  416. // Sign the certificate
  417. sig, err := signer.Sign(rand.Reader, data)
  418. if err != nil {
  419. return nil, err
  420. }
  421. cert.Signature = sig
  422. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  423. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  424. }
  425. return cert, nil
  426. }
  427. // CheckSSHHost checks the given principal has been registered before.
  428. func (a *Authority) CheckSSHHost(ctx context.Context, principal, token string) (bool, error) {
  429. if a.sshCheckHostFunc != nil {
  430. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  431. if err != nil {
  432. return false, errs.Wrap(http.StatusInternalServerError, err,
  433. "checkSSHHost: error from injected checkSSHHost func")
  434. }
  435. return exists, nil
  436. }
  437. exists, err := a.db.IsSSHHost(principal)
  438. if err != nil {
  439. if err == db.ErrNotImplemented {
  440. return false, errs.Wrap(http.StatusNotImplemented, err,
  441. "checkSSHHost: isSSHHost is not implemented")
  442. }
  443. return false, errs.Wrap(http.StatusInternalServerError, err,
  444. "checkSSHHost: error checking if hosts exists")
  445. }
  446. return exists, nil
  447. }
  448. // GetSSHHosts returns a list of valid host principals.
  449. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  450. if a.sshGetHostsFunc != nil {
  451. hosts, err := a.sshGetHostsFunc(ctx, cert)
  452. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  453. }
  454. hostnames, err := a.db.GetSSHHostPrincipals()
  455. if err != nil {
  456. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  457. }
  458. hosts := make([]config.Host, len(hostnames))
  459. for i, hn := range hostnames {
  460. hosts[i] = config.Host{Hostname: hn}
  461. }
  462. return hosts, nil
  463. }
  464. func (a *Authority) getAddUserPrincipal() (cmd string) {
  465. if a.config.SSH.AddUserPrincipal == "" {
  466. return SSHAddUserPrincipal
  467. }
  468. return a.config.SSH.AddUserPrincipal
  469. }
  470. func (a *Authority) getAddUserCommand(principal string) string {
  471. var cmd string
  472. if a.config.SSH.AddUserCommand == "" {
  473. cmd = SSHAddUserCommand
  474. } else {
  475. cmd = a.config.SSH.AddUserCommand
  476. }
  477. return strings.ReplaceAll(cmd, "<principal>", principal)
  478. }