ssh.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701
  1. package authority
  2. import (
  3. "context"
  4. "crypto/rand"
  5. "encoding/binary"
  6. "net/http"
  7. "strings"
  8. "time"
  9. "github.com/pkg/errors"
  10. "github.com/smallstep/certificates/authority/provisioner"
  11. "github.com/smallstep/certificates/db"
  12. "github.com/smallstep/certificates/templates"
  13. "github.com/smallstep/cli/crypto/randutil"
  14. "github.com/smallstep/cli/jose"
  15. "golang.org/x/crypto/ssh"
  16. )
  17. const (
  18. // SSHAddUserPrincipal is the principal that will run the add user command.
  19. // Defaults to "provisioner" but it can be changed in the configuration.
  20. SSHAddUserPrincipal = "provisioner"
  21. // SSHAddUserCommand is the default command to run to add a new user.
  22. // Defaults to "sudo useradd -m <principal>; nc -q0 localhost 22" but it can be changed in the
  23. // configuration. The string "<principal>" will be replace by the new
  24. // principal to add.
  25. SSHAddUserCommand = "sudo useradd -m <principal>; nc -q0 localhost 22"
  26. )
  27. // SSHConfig contains the user and host keys.
  28. type SSHConfig struct {
  29. HostKey string `json:"hostKey"`
  30. UserKey string `json:"userKey"`
  31. Keys []*SSHPublicKey `json:"keys,omitempty"`
  32. AddUserPrincipal string `json:"addUserPrincipal,omitempty"`
  33. AddUserCommand string `json:"addUserCommand,omitempty"`
  34. Bastion *Bastion `json:"bastion,omitempty"`
  35. }
  36. // Bastion contains the custom properties used on bastion.
  37. type Bastion struct {
  38. Hostname string `json:"hostname"`
  39. User string `json:"user,omitempty"`
  40. Port string `json:"port,omitempty"`
  41. Command string `json:"cmd,omitempty"`
  42. Flags string `json:"flags,omitempty"`
  43. }
  44. // Validate checks the fields in SSHConfig.
  45. func (c *SSHConfig) Validate() error {
  46. if c == nil {
  47. return nil
  48. }
  49. for _, k := range c.Keys {
  50. if err := k.Validate(); err != nil {
  51. return err
  52. }
  53. }
  54. return nil
  55. }
  56. // SSHPublicKey contains a public key used by federated CAs to keep old signing
  57. // keys for this ca.
  58. type SSHPublicKey struct {
  59. Type string `json:"type"`
  60. Federated bool `json:"federated"`
  61. Key jose.JSONWebKey `json:"key"`
  62. publicKey ssh.PublicKey
  63. }
  64. // Validate checks the fields in SSHPublicKey.
  65. func (k *SSHPublicKey) Validate() error {
  66. switch {
  67. case k.Type == "":
  68. return errors.New("type cannot be empty")
  69. case k.Type != provisioner.SSHHostCert && k.Type != provisioner.SSHUserCert:
  70. return errors.Errorf("invalid type %s, it must be user or host", k.Type)
  71. case !k.Key.IsPublic():
  72. return errors.New("invalid key type, it must be a public key")
  73. }
  74. key, err := ssh.NewPublicKey(k.Key.Key)
  75. if err != nil {
  76. return errors.Wrap(err, "error creating ssh key")
  77. }
  78. k.publicKey = key
  79. return nil
  80. }
  81. // PublicKey returns the ssh public key.
  82. func (k *SSHPublicKey) PublicKey() ssh.PublicKey {
  83. return k.publicKey
  84. }
  85. // SSHKeys represents the SSH User and Host public keys.
  86. type SSHKeys struct {
  87. UserKeys []ssh.PublicKey
  88. HostKeys []ssh.PublicKey
  89. }
  90. // GetSSHRoots returns the SSH User and Host public keys.
  91. func (a *Authority) GetSSHRoots() (*SSHKeys, error) {
  92. return &SSHKeys{
  93. HostKeys: a.sshCAHostCerts,
  94. UserKeys: a.sshCAUserCerts,
  95. }, nil
  96. }
  97. // GetSSHFederation returns the public keys for federated SSH signers.
  98. func (a *Authority) GetSSHFederation() (*SSHKeys, error) {
  99. return &SSHKeys{
  100. HostKeys: a.sshCAHostFederatedCerts,
  101. UserKeys: a.sshCAUserFederatedCerts,
  102. }, nil
  103. }
  104. // GetSSHConfig returns rendered templates for clients (user) or servers (host).
  105. func (a *Authority) GetSSHConfig(typ string, data map[string]string) ([]templates.Output, error) {
  106. if a.sshCAUserCertSignKey == nil && a.sshCAHostCertSignKey == nil {
  107. return nil, &apiError{
  108. err: errors.New("getSSHConfig: ssh is not configured"),
  109. code: http.StatusNotFound,
  110. }
  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, &apiError{
  124. err: errors.Errorf("getSSHConfig: type %s is not valid", typ),
  125. code: http.StatusBadRequest,
  126. }
  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(user string, hostname string) (*Bastion, error) {
  153. if a.sshBastionFunc != nil {
  154. return a.sshBastionFunc(user, hostname)
  155. }
  156. if a.config.SSH != nil {
  157. if a.config.SSH.Bastion != nil && a.config.SSH.Bastion.Hostname != "" {
  158. return a.config.SSH.Bastion, nil
  159. }
  160. return nil, nil
  161. }
  162. return nil, &apiError{
  163. err: errors.New("getSSHBastion: ssh is not configured"),
  164. code: http.StatusNotFound,
  165. }
  166. }
  167. // authorizeSSHSign loads the provisioner from the token, checks that it has not
  168. // been used again and calls the provisioner AuthorizeSSHSign method. Returns a
  169. // list of methods to apply to the signing flow.
  170. func (a *Authority) authorizeSSHSign(ctx context.Context, ott string) ([]provisioner.SignOption, error) {
  171. var errContext = apiCtx{"ott": ott}
  172. p, err := a.authorizeToken(ctx, ott)
  173. if err != nil {
  174. return nil, &apiError{errors.Wrap(err, "authorizeSSHSign"), http.StatusUnauthorized, errContext}
  175. }
  176. opts, err := p.AuthorizeSSHSign(ctx, ott)
  177. if err != nil {
  178. return nil, &apiError{errors.Wrap(err, "authorizeSSHSign"), http.StatusUnauthorized, errContext}
  179. }
  180. return opts, nil
  181. }
  182. // SignSSH creates a signed SSH certificate with the given public key and options.
  183. func (a *Authority) SignSSH(key ssh.PublicKey, opts provisioner.SSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  184. var mods []provisioner.SSHCertificateModifier
  185. var validators []provisioner.SSHCertificateValidator
  186. for _, op := range signOpts {
  187. switch o := op.(type) {
  188. // modify the ssh.Certificate
  189. case provisioner.SSHCertificateModifier:
  190. mods = append(mods, o)
  191. // modify the ssh.Certificate given the SSHOptions
  192. case provisioner.SSHCertificateOptionModifier:
  193. mods = append(mods, o.Option(opts))
  194. // validate the ssh.Certificate
  195. case provisioner.SSHCertificateValidator:
  196. validators = append(validators, o)
  197. // validate the given SSHOptions
  198. case provisioner.SSHCertificateOptionsValidator:
  199. if err := o.Valid(opts); err != nil {
  200. return nil, &apiError{err: err, code: http.StatusForbidden}
  201. }
  202. default:
  203. return nil, &apiError{
  204. err: errors.Errorf("signSSH: invalid extra option type %T", o),
  205. code: http.StatusInternalServerError,
  206. }
  207. }
  208. }
  209. nonce, err := randutil.ASCII(32)
  210. if err != nil {
  211. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  212. }
  213. var serial uint64
  214. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  215. return nil, &apiError{
  216. err: errors.Wrap(err, "signSSH: error reading random number"),
  217. code: http.StatusInternalServerError,
  218. }
  219. }
  220. // Build base certificate with the key and some random values
  221. cert := &ssh.Certificate{
  222. Nonce: []byte(nonce),
  223. Key: key,
  224. Serial: serial,
  225. }
  226. // Use opts to modify the certificate
  227. if err := opts.Modify(cert); err != nil {
  228. return nil, &apiError{err: err, code: http.StatusForbidden}
  229. }
  230. // Use provisioner modifiers
  231. for _, m := range mods {
  232. if err := m.Modify(cert); err != nil {
  233. return nil, &apiError{err: err, code: http.StatusForbidden}
  234. }
  235. }
  236. // Get signer from authority keys
  237. var signer ssh.Signer
  238. switch cert.CertType {
  239. case ssh.UserCert:
  240. if a.sshCAUserCertSignKey == nil {
  241. return nil, &apiError{
  242. err: errors.New("signSSH: user certificate signing is not enabled"),
  243. code: http.StatusNotImplemented,
  244. }
  245. }
  246. signer = a.sshCAUserCertSignKey
  247. case ssh.HostCert:
  248. if a.sshCAHostCertSignKey == nil {
  249. return nil, &apiError{
  250. err: errors.New("signSSH: host certificate signing is not enabled"),
  251. code: http.StatusNotImplemented,
  252. }
  253. }
  254. signer = a.sshCAHostCertSignKey
  255. default:
  256. return nil, &apiError{
  257. err: errors.Errorf("signSSH: unexpected ssh certificate type: %d", cert.CertType),
  258. code: http.StatusInternalServerError,
  259. }
  260. }
  261. cert.SignatureKey = signer.PublicKey()
  262. // Get bytes for signing trailing the signature length.
  263. data := cert.Marshal()
  264. data = data[:len(data)-4]
  265. // Sign the certificate
  266. sig, err := signer.Sign(rand.Reader, data)
  267. if err != nil {
  268. return nil, &apiError{
  269. err: errors.Wrap(err, "signSSH: error signing certificate"),
  270. code: http.StatusInternalServerError,
  271. }
  272. }
  273. cert.Signature = sig
  274. // User provisioners validators
  275. for _, v := range validators {
  276. if err := v.Valid(cert); err != nil {
  277. return nil, &apiError{err: err, code: http.StatusForbidden}
  278. }
  279. }
  280. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  281. return nil, &apiError{
  282. err: errors.Wrap(err, "signSSH: error storing certificate in db"),
  283. code: http.StatusInternalServerError,
  284. }
  285. }
  286. return cert, nil
  287. }
  288. // authorizeSSHRenew authorizes an SSH certificate renewal request, by
  289. // validating the contents of an SSHPOP token.
  290. func (a *Authority) authorizeSSHRenew(ctx context.Context, token string) (*ssh.Certificate, error) {
  291. errContext := map[string]interface{}{"ott": token}
  292. p, err := a.authorizeToken(ctx, token)
  293. if err != nil {
  294. return nil, &apiError{
  295. err: errors.Wrap(err, "authorizeSSHRenew"),
  296. code: http.StatusUnauthorized,
  297. context: errContext,
  298. }
  299. }
  300. cert, err := p.AuthorizeSSHRenew(ctx, token)
  301. if err != nil {
  302. return nil, &apiError{
  303. err: errors.Wrap(err, "authorizeSSHRenew"),
  304. code: http.StatusUnauthorized,
  305. context: errContext,
  306. }
  307. }
  308. return cert, nil
  309. }
  310. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  311. func (a *Authority) RenewSSH(oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  312. nonce, err := randutil.ASCII(32)
  313. if err != nil {
  314. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  315. }
  316. var serial uint64
  317. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  318. return nil, &apiError{
  319. err: errors.Wrap(err, "renewSSH: error reading random number"),
  320. code: http.StatusInternalServerError,
  321. }
  322. }
  323. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  324. return nil, errors.New("rewnewSSH: cannot renew certificate without validity period")
  325. }
  326. dur := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  327. va := time.Now()
  328. vb := va.Add(dur)
  329. // Build base certificate with the key and some random values
  330. cert := &ssh.Certificate{
  331. Nonce: []byte(nonce),
  332. Key: oldCert.Key,
  333. Serial: serial,
  334. CertType: oldCert.CertType,
  335. KeyId: oldCert.KeyId,
  336. ValidPrincipals: oldCert.ValidPrincipals,
  337. Permissions: oldCert.Permissions,
  338. ValidAfter: uint64(va.Unix()),
  339. ValidBefore: uint64(vb.Unix()),
  340. }
  341. // Get signer from authority keys
  342. var signer ssh.Signer
  343. switch cert.CertType {
  344. case ssh.UserCert:
  345. if a.sshCAUserCertSignKey == nil {
  346. return nil, &apiError{
  347. err: errors.New("renewSSH: user certificate signing is not enabled"),
  348. code: http.StatusNotImplemented,
  349. }
  350. }
  351. signer = a.sshCAUserCertSignKey
  352. case ssh.HostCert:
  353. if a.sshCAHostCertSignKey == nil {
  354. return nil, &apiError{
  355. err: errors.New("renewSSH: host certificate signing is not enabled"),
  356. code: http.StatusNotImplemented,
  357. }
  358. }
  359. signer = a.sshCAHostCertSignKey
  360. default:
  361. return nil, &apiError{
  362. err: errors.Errorf("renewSSH: unexpected ssh certificate type: %d", cert.CertType),
  363. code: http.StatusInternalServerError,
  364. }
  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, &apiError{
  374. err: errors.Wrap(err, "renewSSH: error signing certificate"),
  375. code: http.StatusInternalServerError,
  376. }
  377. }
  378. cert.Signature = sig
  379. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  380. return nil, &apiError{
  381. err: errors.Wrap(err, "renewSSH: error storing certificate in db"),
  382. code: http.StatusInternalServerError,
  383. }
  384. }
  385. return cert, nil
  386. }
  387. // authorizeSSHRekey authorizes an SSH certificate rekey request, by
  388. // validating the contents of an SSHPOP token.
  389. func (a *Authority) authorizeSSHRekey(ctx context.Context, token string) (*ssh.Certificate, []provisioner.SignOption, error) {
  390. errContext := map[string]interface{}{"ott": token}
  391. p, err := a.authorizeToken(ctx, token)
  392. if err != nil {
  393. return nil, nil, &apiError{
  394. err: errors.Wrap(err, "authorizeSSHRenew"),
  395. code: http.StatusUnauthorized,
  396. context: errContext,
  397. }
  398. }
  399. cert, opts, err := p.AuthorizeSSHRekey(ctx, token)
  400. if err != nil {
  401. return nil, nil, &apiError{
  402. err: errors.Wrap(err, "authorizeSSHRekey"),
  403. code: http.StatusUnauthorized,
  404. context: errContext,
  405. }
  406. }
  407. return cert, opts, nil
  408. }
  409. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  410. func (a *Authority) RekeySSH(oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  411. var validators []provisioner.SSHCertificateValidator
  412. for _, op := range signOpts {
  413. switch o := op.(type) {
  414. // validate the ssh.Certificate
  415. case provisioner.SSHCertificateValidator:
  416. validators = append(validators, o)
  417. default:
  418. return nil, &apiError{
  419. err: errors.Errorf("rekeySSH: invalid extra option type %T", o),
  420. code: http.StatusInternalServerError,
  421. }
  422. }
  423. }
  424. nonce, err := randutil.ASCII(32)
  425. if err != nil {
  426. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  427. }
  428. var serial uint64
  429. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  430. return nil, &apiError{
  431. err: errors.Wrap(err, "rekeySSH: error reading random number"),
  432. code: http.StatusInternalServerError,
  433. }
  434. }
  435. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  436. return nil, errors.New("rekeySSH: cannot rekey certificate without validity period")
  437. }
  438. dur := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  439. va := time.Now()
  440. vb := va.Add(dur)
  441. // Build base certificate with the key and some random values
  442. cert := &ssh.Certificate{
  443. Nonce: []byte(nonce),
  444. Key: pub,
  445. Serial: serial,
  446. CertType: oldCert.CertType,
  447. KeyId: oldCert.KeyId,
  448. ValidPrincipals: oldCert.ValidPrincipals,
  449. Permissions: oldCert.Permissions,
  450. ValidAfter: uint64(va.Unix()),
  451. ValidBefore: uint64(vb.Unix()),
  452. }
  453. // Get signer from authority keys
  454. var signer ssh.Signer
  455. switch cert.CertType {
  456. case ssh.UserCert:
  457. if a.sshCAUserCertSignKey == nil {
  458. return nil, &apiError{
  459. err: errors.New("rekeySSH: user certificate signing is not enabled"),
  460. code: http.StatusNotImplemented,
  461. }
  462. }
  463. signer = a.sshCAUserCertSignKey
  464. case ssh.HostCert:
  465. if a.sshCAHostCertSignKey == nil {
  466. return nil, &apiError{
  467. err: errors.New("rekeySSH: host certificate signing is not enabled"),
  468. code: http.StatusNotImplemented,
  469. }
  470. }
  471. signer = a.sshCAHostCertSignKey
  472. default:
  473. return nil, &apiError{
  474. err: errors.Errorf("rekeySSH: unexpected ssh certificate type: %d", cert.CertType),
  475. code: http.StatusInternalServerError,
  476. }
  477. }
  478. cert.SignatureKey = signer.PublicKey()
  479. // Get bytes for signing trailing the signature length.
  480. data := cert.Marshal()
  481. data = data[:len(data)-4]
  482. // Sign the certificate
  483. sig, err := signer.Sign(rand.Reader, data)
  484. if err != nil {
  485. return nil, &apiError{
  486. err: errors.Wrap(err, "rekeySSH: error signing certificate"),
  487. code: http.StatusInternalServerError,
  488. }
  489. }
  490. cert.Signature = sig
  491. // User provisioners validators
  492. for _, v := range validators {
  493. if err := v.Valid(cert); err != nil {
  494. return nil, &apiError{err: err, code: http.StatusForbidden}
  495. }
  496. }
  497. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  498. return nil, &apiError{
  499. err: errors.Wrap(err, "rekeySSH: error storing certificate in db"),
  500. code: http.StatusInternalServerError,
  501. }
  502. }
  503. return cert, nil
  504. }
  505. // authorizeSSHRevoke authorizes an SSH certificate revoke request, by
  506. // validating the contents of an SSHPOP token.
  507. func (a *Authority) authorizeSSHRevoke(ctx context.Context, token string) error {
  508. errContext := map[string]interface{}{"ott": token}
  509. p, err := a.authorizeToken(ctx, token)
  510. if err != nil {
  511. return &apiError{errors.Wrap(err, "authorizeSSHRevoke"), http.StatusUnauthorized, errContext}
  512. }
  513. if err = p.AuthorizeSSHRevoke(ctx, token); err != nil {
  514. return &apiError{errors.Wrap(err, "authorizeSSHRevoke"), http.StatusUnauthorized, errContext}
  515. }
  516. return nil
  517. }
  518. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  519. func (a *Authority) SignSSHAddUser(key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  520. if a.sshCAUserCertSignKey == nil {
  521. return nil, &apiError{
  522. err: errors.New("signSSHAddUser: user certificate signing is not enabled"),
  523. code: http.StatusNotImplemented,
  524. }
  525. }
  526. if subject.CertType != ssh.UserCert {
  527. return nil, &apiError{
  528. err: errors.New("signSSHAddUser: certificate is not a user certificate"),
  529. code: http.StatusForbidden,
  530. }
  531. }
  532. if len(subject.ValidPrincipals) != 1 {
  533. return nil, &apiError{
  534. err: errors.New("signSSHAddUser: certificate does not have only one principal"),
  535. code: http.StatusForbidden,
  536. }
  537. }
  538. nonce, err := randutil.ASCII(32)
  539. if err != nil {
  540. return nil, &apiError{err: err, code: http.StatusInternalServerError}
  541. }
  542. var serial uint64
  543. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  544. return nil, &apiError{
  545. err: errors.Wrap(err, "signSSHAddUser: error reading random number"),
  546. code: http.StatusInternalServerError,
  547. }
  548. }
  549. signer := a.sshCAUserCertSignKey
  550. principal := subject.ValidPrincipals[0]
  551. addUserPrincipal := a.getAddUserPrincipal()
  552. cert := &ssh.Certificate{
  553. Nonce: []byte(nonce),
  554. Key: key,
  555. Serial: serial,
  556. CertType: ssh.UserCert,
  557. KeyId: principal + "-" + addUserPrincipal,
  558. ValidPrincipals: []string{addUserPrincipal},
  559. ValidAfter: subject.ValidAfter,
  560. ValidBefore: subject.ValidBefore,
  561. Permissions: ssh.Permissions{
  562. CriticalOptions: map[string]string{
  563. "force-command": a.getAddUserCommand(principal),
  564. },
  565. },
  566. SignatureKey: signer.PublicKey(),
  567. }
  568. // Get bytes for signing trailing the signature length.
  569. data := cert.Marshal()
  570. data = data[:len(data)-4]
  571. // Sign the certificate
  572. sig, err := signer.Sign(rand.Reader, data)
  573. if err != nil {
  574. return nil, err
  575. }
  576. cert.Signature = sig
  577. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  578. return nil, &apiError{
  579. err: errors.Wrap(err, "signSSHAddUser: error storing certificate in db"),
  580. code: http.StatusInternalServerError,
  581. }
  582. }
  583. return cert, nil
  584. }
  585. // CheckSSHHost checks the given principal has been registered before.
  586. func (a *Authority) CheckSSHHost(principal string) (bool, error) {
  587. exists, err := a.db.IsSSHHost(principal)
  588. if err != nil {
  589. if err == db.ErrNotImplemented {
  590. return false, &apiError{
  591. err: errors.Wrap(err, "checkSSHHost: isSSHHost is not implemented"),
  592. code: http.StatusNotImplemented,
  593. }
  594. }
  595. return false, &apiError{
  596. err: errors.Wrap(err, "checkSSHHost: error checking if hosts exists"),
  597. code: http.StatusInternalServerError,
  598. }
  599. }
  600. return exists, nil
  601. }
  602. // GetSSHHosts returns a list of valid host principals.
  603. func (a *Authority) GetSSHHosts(email string) ([]string, error) {
  604. if a.sshBastionFunc != nil {
  605. return a.sshGetHostsFunc(email)
  606. }
  607. return nil, &apiError{
  608. err: errors.New("getSSHHosts is not configured"),
  609. code: http.StatusNotFound,
  610. }
  611. }
  612. func (a *Authority) getAddUserPrincipal() (cmd string) {
  613. if a.config.SSH.AddUserPrincipal == "" {
  614. return SSHAddUserPrincipal
  615. }
  616. return a.config.SSH.AddUserPrincipal
  617. }
  618. func (a *Authority) getAddUserCommand(principal string) string {
  619. var cmd string
  620. if a.config.SSH.AddUserCommand == "" {
  621. cmd = SSHAddUserCommand
  622. } else {
  623. cmd = a.config.SSH.AddUserCommand
  624. }
  625. return strings.Replace(cmd, "<principal>", principal, -1)
  626. }