4
0

ssh.go 17 KB

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