ssh.go 17 KB

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