ssh.go 18 KB

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