ssh.go 21 KB

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