ssh.go 21 KB

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