4
0

ssh.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517
  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.db.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("rewnewSSH: cannot renew certificate without validity period")
  219. }
  220. backdate := a.config.AuthorityConfig.Backdate.Duration
  221. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  222. now := time.Now()
  223. va := now.Add(-1 * backdate)
  224. vb := now.Add(duration - backdate)
  225. // Build base certificate with the old key.
  226. // Nonce and serial will be automatically generated on signing.
  227. certTpl := &ssh.Certificate{
  228. Key: oldCert.Key,
  229. CertType: oldCert.CertType,
  230. KeyId: oldCert.KeyId,
  231. ValidPrincipals: oldCert.ValidPrincipals,
  232. Permissions: oldCert.Permissions,
  233. Reserved: oldCert.Reserved,
  234. ValidAfter: uint64(va.Unix()),
  235. ValidBefore: uint64(vb.Unix()),
  236. }
  237. // Get signer from authority keys
  238. var signer ssh.Signer
  239. switch certTpl.CertType {
  240. case ssh.UserCert:
  241. if a.sshCAUserCertSignKey == nil {
  242. return nil, errs.NotImplemented("renewSSH: user certificate signing is not enabled")
  243. }
  244. signer = a.sshCAUserCertSignKey
  245. case ssh.HostCert:
  246. if a.sshCAHostCertSignKey == nil {
  247. return nil, errs.NotImplemented("renewSSH: host certificate signing is not enabled")
  248. }
  249. signer = a.sshCAHostCertSignKey
  250. default:
  251. return nil, errs.InternalServer("renewSSH: unexpected ssh certificate type: %d", certTpl.CertType)
  252. }
  253. // Sign certificate.
  254. cert, err := sshutil.CreateCertificate(certTpl, signer)
  255. if err != nil {
  256. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  257. }
  258. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  259. return nil, errs.Wrap(http.StatusInternalServerError, err, "renewSSH: error storing certificate in db")
  260. }
  261. return cert, nil
  262. }
  263. // RekeySSH creates a signed SSH certificate using the old SSH certificate as a template.
  264. func (a *Authority) RekeySSH(ctx context.Context, oldCert *ssh.Certificate, pub ssh.PublicKey, signOpts ...provisioner.SignOption) (*ssh.Certificate, error) {
  265. var validators []provisioner.SSHCertValidator
  266. for _, op := range signOpts {
  267. switch o := op.(type) {
  268. // validate the ssh.Certificate
  269. case provisioner.SSHCertValidator:
  270. validators = append(validators, o)
  271. default:
  272. return nil, errs.InternalServer("rekeySSH; invalid extra option type %T", o)
  273. }
  274. }
  275. if oldCert.ValidAfter == 0 || oldCert.ValidBefore == 0 {
  276. return nil, errs.BadRequest("rekeySSH; cannot rekey certificate without validity period")
  277. }
  278. backdate := a.config.AuthorityConfig.Backdate.Duration
  279. duration := time.Duration(oldCert.ValidBefore-oldCert.ValidAfter) * time.Second
  280. now := time.Now()
  281. va := now.Add(-1 * backdate)
  282. vb := now.Add(duration - backdate)
  283. // Build base certificate with the new key.
  284. // Nonce and serial will be automatically generated on signing.
  285. cert := &ssh.Certificate{
  286. Key: pub,
  287. CertType: oldCert.CertType,
  288. KeyId: oldCert.KeyId,
  289. ValidPrincipals: oldCert.ValidPrincipals,
  290. Permissions: oldCert.Permissions,
  291. Reserved: oldCert.Reserved,
  292. ValidAfter: uint64(va.Unix()),
  293. ValidBefore: uint64(vb.Unix()),
  294. }
  295. // Get signer from authority keys
  296. var signer ssh.Signer
  297. switch cert.CertType {
  298. case ssh.UserCert:
  299. if a.sshCAUserCertSignKey == nil {
  300. return nil, errs.NotImplemented("rekeySSH; user certificate signing is not enabled")
  301. }
  302. signer = a.sshCAUserCertSignKey
  303. case ssh.HostCert:
  304. if a.sshCAHostCertSignKey == nil {
  305. return nil, errs.NotImplemented("rekeySSH; host certificate signing is not enabled")
  306. }
  307. signer = a.sshCAHostCertSignKey
  308. default:
  309. return nil, errs.BadRequest("rekeySSH; unexpected ssh certificate type: %d", cert.CertType)
  310. }
  311. var err error
  312. // Sign certificate.
  313. cert, err = sshutil.CreateCertificate(cert, signer)
  314. if err != nil {
  315. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSH: error signing certificate")
  316. }
  317. // Apply validators from provisioner.
  318. for _, v := range validators {
  319. if err := v.Valid(cert, provisioner.SignSSHOptions{Backdate: backdate}); err != nil {
  320. return nil, errs.Wrap(http.StatusForbidden, err, "rekeySSH")
  321. }
  322. }
  323. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  324. return nil, errs.Wrap(http.StatusInternalServerError, err, "rekeySSH; error storing certificate in db")
  325. }
  326. return cert, nil
  327. }
  328. // IsValidForAddUser checks if a user provisioner certificate can be issued to
  329. // the given certificate.
  330. func IsValidForAddUser(cert *ssh.Certificate) error {
  331. if cert.CertType != ssh.UserCert {
  332. return errors.New("certificate is not a user certificate")
  333. }
  334. switch len(cert.ValidPrincipals) {
  335. case 0:
  336. return errors.New("certificate does not have any principals")
  337. case 1:
  338. return nil
  339. case 2:
  340. // OIDC provisioners adds a second principal with the email address.
  341. // @ cannot be the first character.
  342. if strings.Index(cert.ValidPrincipals[1], "@") > 0 {
  343. return nil
  344. }
  345. return errors.New("certificate does not have only one principal")
  346. default:
  347. return errors.New("certificate does not have only one principal")
  348. }
  349. }
  350. // SignSSHAddUser signs a certificate that provisions a new user in a server.
  351. func (a *Authority) SignSSHAddUser(ctx context.Context, key ssh.PublicKey, subject *ssh.Certificate) (*ssh.Certificate, error) {
  352. if a.sshCAUserCertSignKey == nil {
  353. return nil, errs.NotImplemented("signSSHAddUser: user certificate signing is not enabled")
  354. }
  355. if err := IsValidForAddUser(subject); err != nil {
  356. return nil, errs.Wrap(http.StatusForbidden, err, "signSSHAddUser")
  357. }
  358. nonce, err := randutil.ASCII(32)
  359. if err != nil {
  360. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser")
  361. }
  362. var serial uint64
  363. if err := binary.Read(rand.Reader, binary.BigEndian, &serial); err != nil {
  364. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error reading random number")
  365. }
  366. signer := a.sshCAUserCertSignKey
  367. principal := subject.ValidPrincipals[0]
  368. addUserPrincipal := a.getAddUserPrincipal()
  369. cert := &ssh.Certificate{
  370. Nonce: []byte(nonce),
  371. Key: key,
  372. Serial: serial,
  373. CertType: ssh.UserCert,
  374. KeyId: principal + "-" + addUserPrincipal,
  375. ValidPrincipals: []string{addUserPrincipal},
  376. ValidAfter: subject.ValidAfter,
  377. ValidBefore: subject.ValidBefore,
  378. Permissions: ssh.Permissions{
  379. CriticalOptions: map[string]string{
  380. "force-command": a.getAddUserCommand(principal),
  381. },
  382. },
  383. SignatureKey: signer.PublicKey(),
  384. }
  385. // Get bytes for signing trailing the signature length.
  386. data := cert.Marshal()
  387. data = data[:len(data)-4]
  388. // Sign the certificate
  389. sig, err := signer.Sign(rand.Reader, data)
  390. if err != nil {
  391. return nil, err
  392. }
  393. cert.Signature = sig
  394. if err = a.db.StoreSSHCertificate(cert); err != nil && err != db.ErrNotImplemented {
  395. return nil, errs.Wrap(http.StatusInternalServerError, err, "signSSHAddUser: error storing certificate in db")
  396. }
  397. return cert, nil
  398. }
  399. // CheckSSHHost checks the given principal has been registered before.
  400. func (a *Authority) CheckSSHHost(ctx context.Context, principal string, token string) (bool, error) {
  401. if a.sshCheckHostFunc != nil {
  402. exists, err := a.sshCheckHostFunc(ctx, principal, token, a.GetRootCertificates())
  403. if err != nil {
  404. return false, errs.Wrap(http.StatusInternalServerError, err,
  405. "checkSSHHost: error from injected checkSSHHost func")
  406. }
  407. return exists, nil
  408. }
  409. exists, err := a.db.IsSSHHost(principal)
  410. if err != nil {
  411. if err == db.ErrNotImplemented {
  412. return false, errs.Wrap(http.StatusNotImplemented, err,
  413. "checkSSHHost: isSSHHost is not implemented")
  414. }
  415. return false, errs.Wrap(http.StatusInternalServerError, err,
  416. "checkSSHHost: error checking if hosts exists")
  417. }
  418. return exists, nil
  419. }
  420. // GetSSHHosts returns a list of valid host principals.
  421. func (a *Authority) GetSSHHosts(ctx context.Context, cert *x509.Certificate) ([]config.Host, error) {
  422. if a.sshGetHostsFunc != nil {
  423. hosts, err := a.sshGetHostsFunc(ctx, cert)
  424. return hosts, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  425. }
  426. hostnames, err := a.db.GetSSHHostPrincipals()
  427. if err != nil {
  428. return nil, errs.Wrap(http.StatusInternalServerError, err, "getSSHHosts")
  429. }
  430. hosts := make([]config.Host, len(hostnames))
  431. for i, hn := range hostnames {
  432. hosts[i] = config.Host{Hostname: hn}
  433. }
  434. return hosts, nil
  435. }
  436. func (a *Authority) getAddUserPrincipal() (cmd string) {
  437. if a.config.SSH.AddUserPrincipal == "" {
  438. return SSHAddUserPrincipal
  439. }
  440. return a.config.SSH.AddUserPrincipal
  441. }
  442. func (a *Authority) getAddUserCommand(principal string) string {
  443. var cmd string
  444. if a.config.SSH.AddUserCommand == "" {
  445. cmd = SSHAddUserCommand
  446. } else {
  447. cmd = a.config.SSH.AddUserCommand
  448. }
  449. return strings.Replace(cmd, "<principal>", principal, -1)
  450. }