ssh.go 18 KB

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