ssh.go 18 KB

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