ssh.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535
  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/config"
  12. "github.com/smallstep/certificates/authority/provisioner"
  13. "github.com/smallstep/certificates/db"
  14. "github.com/smallstep/certificates/errs"
  15. "github.com/smallstep/certificates/templates"
  16. "go.step.sm/crypto/randutil"
  17. "go.step.sm/crypto/sshutil"
  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. // GetSSHRoots returns the SSH User and Host public keys.
  31. func (a *Authority) GetSSHRoots(context.Context) (*config.SSHKeys, error) {
  32. return &config.SSHKeys{
  33. HostKeys: a.sshCAHostCerts,
  34. UserKeys: a.sshCAUserCerts,
  35. }, nil
  36. }
  37. // GetSSHFederation returns the public keys for federated SSH signers.
  38. func (a *Authority) GetSSHFederation(context.Context) (*config.SSHKeys, error) {
  39. return &config.SSHKeys{
  40. HostKeys: a.sshCAHostFederatedCerts,
  41. UserKeys: a.sshCAUserFederatedCerts,
  42. }, nil
  43. }
  44. // GetSSHConfig returns rendered templates for clients (user) or servers (host).
  45. func (a *Authority) GetSSHConfig(ctx context.Context, typ string, data map[string]string) ([]templates.Output, error) {
  46. if a.sshCAUserCertSignKey == nil && a.sshCAHostCertSignKey == nil {
  47. return nil, errs.NotFound("getSSHConfig: ssh is not configured")
  48. }
  49. if a.templates == nil {
  50. return nil, errs.NotFound("getSSHConfig: ssh templates are not configured")
  51. }
  52. var ts []templates.Template
  53. switch typ {
  54. case provisioner.SSHUserCert:
  55. if a.templates != nil && a.templates.SSH != nil {
  56. ts = a.templates.SSH.User
  57. }
  58. case provisioner.SSHHostCert:
  59. if a.templates != nil && a.templates.SSH != nil {
  60. ts = a.templates.SSH.Host
  61. }
  62. default:
  63. return nil, errs.BadRequest("getSSHConfig: type %s is not valid", typ)
  64. }
  65. // Merge user and default data
  66. var mergedData map[string]interface{}
  67. if len(data) == 0 {
  68. mergedData = a.templates.Data
  69. } else {
  70. mergedData = make(map[string]interface{}, len(a.templates.Data)+1)
  71. mergedData["User"] = data
  72. for k, v := range a.templates.Data {
  73. mergedData[k] = v
  74. }
  75. }
  76. // Render templates
  77. output := []templates.Output{}
  78. for _, t := range ts {
  79. if err := t.Load(); err != nil {
  80. return nil, err
  81. }
  82. // Check for required variables.
  83. if err := t.ValidateRequiredData(data); err != nil {
  84. return nil, errs.BadRequestErr(err, errs.WithMessage("%v, please use `--set <key=value>` flag", err))
  85. }
  86. o, err := t.Output(mergedData)
  87. if err != nil {
  88. return nil, err
  89. }
  90. output = append(output, o)
  91. }
  92. return output, nil
  93. }
  94. // GetSSHBastion returns the bastion configuration, for the given pair user,
  95. // hostname.
  96. func (a *Authority) GetSSHBastion(ctx context.Context, user string, hostname string) (*config.Bastion, error) {
  97. if a.sshBastionFunc != nil {
  98. bs, err := a.sshBastionFunc(ctx, user, hostname)
  99. return bs, errs.Wrap(http.StatusInternalServerError, err, "authority.GetSSHBastion")
  100. }
  101. if a.config.SSH != nil {
  102. if a.config.SSH.Bastion != nil && a.config.SSH.Bastion.Hostname != "" {
  103. // Do not return a bastion for a bastion host.
  104. //
  105. // This condition might fail if a different name or IP is used.
  106. // Trying to resolve hostnames to IPs and compare them won't be a
  107. // complete solution because it depends on the network
  108. // configuration, of the CA and clients and can also return false
  109. // positives. Although not perfect, this simple solution will work
  110. // in most cases.
  111. if !strings.EqualFold(hostname, a.config.SSH.Bastion.Hostname) {
  112. return a.config.SSH.Bastion, nil
  113. }
  114. }
  115. return nil, nil
  116. }
  117. return nil, errs.NotFound("authority.GetSSHBastion; ssh is not configured")
  118. }
  119. // SignSSH creates a signed SSH certificate with the given public key and options.
  120. func (a *Authority) SignSSH(ctx context.Context, key ssh.PublicKey, opts provisioner.SignSSHOptions, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  121. var (
  122. certOptions []sshutil.Option
  123. mods []provisioner.SSHCertModifier
  124. validators []provisioner.SSHCertValidator
  125. )
  126. // Validate given options.
  127. if err := opts.Validate(); err != nil {
  128. return nil, errs.Wrap(http.StatusBadRequest, err, "authority.SignSSH")
  129. }
  130. // Set backdate with the configured value
  131. opts.Backdate = a.config.AuthorityConfig.Backdate.Duration
  132. for _, op := range signOpts {
  133. switch o := op.(type) {
  134. // add options to NewCertificate
  135. case provisioner.SSHCertificateOptions:
  136. certOptions = append(certOptions, o.Options(opts)...)
  137. // modify the ssh.Certificate
  138. case provisioner.SSHCertModifier:
  139. mods = append(mods, o)
  140. // validate the ssh.Certificate
  141. case provisioner.SSHCertValidator:
  142. validators = append(validators, o)
  143. // validate the given SSHOptions
  144. case provisioner.SSHCertOptionsValidator:
  145. if err := o.Valid(opts); err != nil {
  146. return nil, errs.Wrap(http.StatusForbidden, err, "authority.SignSSH")
  147. }
  148. default:
  149. return nil, errs.InternalServer("authority.SignSSH: invalid extra option type %T", o)
  150. }
  151. }
  152. // Simulated certificate request with request options.
  153. cr := sshutil.CertificateRequest{
  154. Type: opts.CertType,
  155. KeyID: opts.KeyID,
  156. Principals: opts.Principals,
  157. Key: key,
  158. }
  159. // Create certificate from template.
  160. certificate, err := sshutil.NewCertificate(cr, certOptions...)
  161. if err != nil {
  162. if _, ok := err.(*sshutil.TemplateError); ok {
  163. return nil, errs.NewErr(http.StatusBadRequest, err,
  164. errs.WithMessage(err.Error()),
  165. errs.WithKeyVal("signOptions", signOpts),
  166. )
  167. }
  168. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH")
  169. }
  170. // Get actual *ssh.Certificate and continue with provisioner modifiers.
  171. certTpl := certificate.GetCertificate()
  172. // Use SignSSHOptions to modify the certificate validity. It will be later
  173. // checked or set if not defined.
  174. if err := opts.ModifyValidity(certTpl); err != nil {
  175. return nil, errs.Wrap(http.StatusBadRequest, err, "authority.SignSSH")
  176. }
  177. // Use provisioner modifiers.
  178. for _, m := range mods {
  179. if err := m.Modify(certTpl, opts); err != nil {
  180. return nil, errs.Wrap(http.StatusForbidden, err, "authority.SignSSH")
  181. }
  182. }
  183. // Get signer from authority keys
  184. var signer ssh.Signer
  185. switch certTpl.CertType {
  186. case ssh.UserCert:
  187. if a.sshCAUserCertSignKey == nil {
  188. return nil, errs.NotImplemented("authority.SignSSH: user certificate signing is not enabled")
  189. }
  190. signer = a.sshCAUserCertSignKey
  191. case ssh.HostCert:
  192. if a.sshCAHostCertSignKey == nil {
  193. return nil, errs.NotImplemented("authority.SignSSH: host certificate signing is not enabled")
  194. }
  195. signer = a.sshCAHostCertSignKey
  196. default:
  197. return nil, errs.InternalServer("authority.SignSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  198. }
  199. // Sign certificate.
  200. cert, err := sshutil.CreateCertificate(certTpl, signer)
  201. if err != nil {
  202. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error signing certificate")
  203. }
  204. // User provisioners validators.
  205. for _, v := range validators {
  206. if err := v.Valid(cert, opts); err != nil {
  207. return nil, errs.Wrap(http.StatusForbidden, err, "authority.SignSSH")
  208. }
  209. }
  210. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  211. return nil, errs.Wrap(http.StatusInternalServerError, err, "authority.SignSSH: error storing certificate in db")
  212. }
  213. return cert, nil
  214. }
  215. // RenewSSH creates a signed SSH certificate using the old SSH certificate as a template.
  216. func (a *Authority) RenewSSH(ctx context.Context, oldCert *ssh.Certificate) (*ssh.Certificate, error) {
  217. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  218. return nil, errs.BadRequest("renewSSH: cannot renew certificate without validity period")
  219. }
  220. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  221. return nil, err
  222. }
  223. backdate := a.config.AuthorityConfig.Backdate.Duration
  224. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  225. now := time.Now()
  226. va := now.Add(-1 * backdate)
  227. vb := now.Add(duration - backdate)
  228. // Build base certificate with the old key.
  229. // Nonce and serial will be automatically generated on signing.
  230. certTpl := &ssh.Certificate{
  231. Key: oldCert.Key,
  232. CertType: oldCert.CertType,
  233. KeyId: oldCert.KeyId,
  234. ValidPrincipals: oldCert.ValidPrincipals,
  235. Permissions: oldCert.Permissions,
  236. Reserved: oldCert.Reserved,
  237. ValidAfter: uint64(va.Unix()),
  238. ValidBefore: uint64(vb.Unix()),
  239. }
  240. // Get signer from authority keys
  241. var signer ssh.Signer
  242. switch certTpl.CertType {
  243. case ssh.UserCert:
  244. if a.sshCAUserCertSignKey == nil {
  245. return nil, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  246. }
  247. signer = a.sshCAUserCertSignKey
  248. case ssh.HostCert:
  249. if a.sshCAHostCertSignKey == nil {
  250. return nil, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  251. }
  252. signer = a.sshCAHostCertSignKey
  253. default:
  254. return nil, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  255. }
  256. // Sign certificate.
  257. cert, err := sshutil.CreateCertificate(certTpl, signer)
  258. if err != nil {
  259. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  260. }
  261. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  262. return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  263. }
  264. return cert, nil
  265. }
  266. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  267. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  268. var validators []provisioner.SSHCertValidator
  269. for _, op := range signOpts {
  270. switch o := op.(type) {
  271. // validate the ssh.Certificate
  272. case provisioner.SSHCertValidator:
  273. validators = append(validators, o)
  274. default:
  275. return nil, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  276. }
  277. }
  278. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  279. return nil, errs.BadRequest("rekeySSH; cannot rekey certificate without validity period")
  280. }
  281. if err := a.authorizeSSHCertificate(ctx, oldCert); err != nil {
  282. return nil, err
  283. }
  284. backdate := a.config.AuthorityConfig.Backdate.Duration
  285. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  286. now := time.Now()
  287. va := now.Add(-1 * backdate)
  288. vb := now.Add(duration - backdate)
  289. // Build base certificate with the new key.
  290. // Nonce and serial will be automatically generated on signing.
  291. cert := &ssh.Certificate{
  292. Key: pub,
  293. CertType: oldCert.CertType,
  294. KeyId: oldCert.KeyId,
  295. ValidPrincipals: oldCert.ValidPrincipals,
  296. Permissions: oldCert.Permissions,
  297. Reserved: oldCert.Reserved,
  298. ValidAfter: uint64(va.Unix()),
  299. ValidBefore: uint64(vb.Unix()),
  300. }
  301. // Get signer from authority keys
  302. var signer ssh.Signer
  303. switch cert.CertType {
  304. case ssh.UserCert:
  305. if a.sshCAUserCertSignKey == nil {
  306. return nil, errs.NotImplemented("rekeySSH; user certificate signing is not enabled")
  307. }
  308. signer = a.sshCAUserCertSignKey
  309. case ssh.HostCert:
  310. if a.sshCAHostCertSignKey == nil {
  311. return nil, errs.NotImplemented("rekeySSH; host certificate signing is not enabled")
  312. }
  313. signer = a.sshCAHostCertSignKey
  314. default:
  315. return nil, errs.BadRequest("rekeySSH; unexpected ssh certificate type: %d", cert.CertType)
  316. }
  317. var err error
  318. // Sign certificate.
  319. cert, err = sshutil.CreateCertificate(cert, signer)
  320. if err != nil {
  321. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  322. }
  323. // Apply validators from provisioner.
  324. for _, v := range validators {
  325. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  326. return nil, errs.Wrap(http.StatusForbidden, err, "rekeySSH")
  327. }
  328. }
  329. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  330. return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  331. }
  332. return cert, nil
  333. }
  334. func (a *Authority) storeSSHCertificate(cert *ssh.Certificate) error {
  335. type sshCertificateStorer interface {
  336. StoreSSHCertificate(crt *ssh.Certificate) error
  337. }
  338. if s, ok := a.adminDB.(sshCertificateStorer); ok {
  339. return s.StoreSSHCertificate(cert)
  340. }
  341. return a.db.StoreSSHCertificate(cert)
  342. }
  343. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  344. // the given certificate.
  345. func IsValidForAddUser(cert *ssh.Certificate) error {
  346. if cert.CertType != ssh.UserCert {
  347. return errors.New("certificate is not a user certificate")
  348. }
  349. switch len(cert.ValidPrincipals) {
  350. case 0:
  351. return errors.New("certificate does not have any principals")
  352. case 1:
  353. return nil
  354. case 2:
  355. // OIDC provisioners adds a second principal with the email address.
  356. // @ cannot be the first character.
  357. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  358. return nil
  359. }
  360. return errors.New("certificate does not have only one principal")
  361. default:
  362. return errors.New("certificate does not have only one principal")
  363. }
  364. }
  365. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  366. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  367. if a.sshCAUserCertSignKey == nil {
  368. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  369. }
  370. if err := IsValidForAddUser(subject); err != nil {
  371. return nil, errs.Wrap(http.StatusForbidden, err, "signSSHAddUser")
  372. }
  373. nonce, err := randutil.ASCII(32)
  374. if err != nil {
  375. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  376. }
  377. var serial uint64
  378. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  379. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  380. }
  381. signer := a.sshCAUserCertSignKey
  382. principal := subject.ValidPrincipals[0]
  383. addUserPrincipal := a.getAddUserPrincipal()
  384. cert := &ssh.Certificate{
  385. Nonce: []byte(nonce),
  386. Key: key,
  387. Serial: serial,
  388. CertType: ssh.UserCert,
  389. KeyId: principal + "-" + addUserPrincipal,
  390. ValidPrincipals: []string{addUserPrincipal},
  391. ValidAfter: subject.ValidAfter,
  392. ValidBefore: subject.ValidBefore,
  393. Permissions: ssh.Permissions{
  394. CriticalOptions: map[string]string{
  395. "force-command": a.getAddUserCommand(principal),
  396. },
  397. },
  398. SignatureKey: signer.PublicKey(),
  399. }
  400. // Get bytes for signing trailing the signature length.
  401. data := cert.Marshal()
  402. data = data[:len(data)-4]
  403. // Sign the certificate
  404. sig, err := signer.Sign(rand.Reader, data)
  405. if err != nil {
  406. return nil, err
  407. }
  408. cert.Signature = sig
  409. if err = a.storeSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  410. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  411. }
  412. return cert, nil
  413. }
  414. // CheckSSHHost checks the given principal has been registered before.
  415. func (a *Authority) CheckSSHHost(ctx context.Context, principal string, token string) (bool, error) {
  416. if a.sshCheckHostFunc != nil {
  417. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  418. if err != nil {
  419. return false, errs.Wrap(http.StatusInternalServerError, err,
  420. "checkSSHHost: error from injected checkSSHHost func")
  421. }
  422. return exists, nil
  423. }
  424. exists, err := a.db.IsSSHHost(principal)
  425. if err != nil {
  426. if err == db.ErrNotImplemented {
  427. return false, errs.Wrap(http.StatusNotImplemented, err,
  428. "checkSSHHost: isSSHHost is not implemented")
  429. }
  430. return false, errs.Wrap(http.StatusInternalServerError, err,
  431. "checkSSHHost: error checking if hosts exists")
  432. }
  433. return exists, nil
  434. }
  435. // GetSSHHosts returns a list of valid host principals.
  436. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  437. if a.sshGetHostsFunc != nil {
  438. hosts, err := a.sshGetHostsFunc(ctx, cert)
  439. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  440. }
  441. hostnames, err := a.db.GetSSHHostPrincipals()
  442. if err != nil {
  443. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  444. }
  445. hosts := make([]config.Host, len(hostnames))
  446. for i, hn := range hostnames {
  447. hosts[i] = config.Host{Hostname: hn}
  448. }
  449. return hosts, nil
  450. }
  451. func (a *Authority) getAddUserPrincipal() (cmd string) {
  452. if a.config.SSH.AddUserPrincipal == "" {
  453. return SSHAddUserPrincipal
  454. }
  455. return a.config.SSH.AddUserPrincipal
  456. }
  457. func (a *Authority) getAddUserCommand(principal string) string {
  458. var cmd string
  459. if a.config.SSH.AddUserCommand == "" {
  460. cmd = SSHAddUserCommand
  461. } else {
  462. cmd = a.config.SSH.AddUserCommand
  463. }
  464. return strings.Replace(cmd, "<principal>", principal, -1)
  465. }