ssh.go 18 KB

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