ssh.go 17 KB

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