4
0

ssh.go 17 KB

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