ssh.go 21 KB

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