ssh.go 20 KB

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