sign_ssh_options.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  1. package provisioner
  2. import (
  3. "crypto/rsa"
  4. "encoding/binary"
  5. "encoding/json"
  6. "fmt"
  7. "math/big"
  8. "strings"
  9. "time"
  10. "github.com/pkg/errors"
  11. "github.com/smallstep/certificates/authority/policy"
  12. "github.com/smallstep/certificates/errs"
  13. "go.step.sm/crypto/keyutil"
  14. "golang.org/x/crypto/ssh"
  15. )
  16. const (
  17. // SSHUserCert is the string used to represent ssh.UserCert.
  18. SSHUserCert = "user"
  19. // SSHHostCert is the string used to represent ssh.HostCert.
  20. SSHHostCert = "host"
  21. )
  22. // SSHCertModifier is the interface used to change properties in an SSH
  23. // certificate.
  24. type SSHCertModifier interface {
  25. SignOption
  26. Modify(cert *ssh.Certificate, opts SignSSHOptions) error
  27. }
  28. // SSHCertValidator is the interface used to validate an SSH certificate.
  29. type SSHCertValidator interface {
  30. SignOption
  31. Valid(cert *ssh.Certificate, opts SignSSHOptions) error
  32. }
  33. // SSHCertOptionsValidator is the interface used to validate the custom
  34. // options used to modify the SSH certificate.
  35. type SSHCertOptionsValidator interface {
  36. SignOption
  37. Valid(got SignSSHOptions) error
  38. }
  39. // SignSSHOptions contains the options that can be passed to the SignSSH method.
  40. type SignSSHOptions struct {
  41. CertType string `json:"certType"`
  42. KeyID string `json:"keyID"`
  43. Principals []string `json:"principals"`
  44. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  45. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  46. TemplateData json.RawMessage `json:"templateData,omitempty"`
  47. Backdate time.Duration `json:"-"`
  48. }
  49. // Validate validates the given SignSSHOptions.
  50. func (o SignSSHOptions) Validate() error {
  51. if o.CertType != "" && o.CertType != SSHUserCert && o.CertType != SSHHostCert {
  52. return errs.BadRequest("certType '%s' is not valid", o.CertType)
  53. }
  54. for _, p := range o.Principals {
  55. if p == "" {
  56. return errs.BadRequest("principals cannot contain empty values")
  57. }
  58. }
  59. return nil
  60. }
  61. // Type returns the uint32 representation of the CertType.
  62. func (o SignSSHOptions) Type() uint32 {
  63. return sshCertTypeUInt32(o.CertType)
  64. }
  65. // Modify implements SSHCertModifier and sets the SSHOption in the ssh.Certificate.
  66. func (o SignSSHOptions) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  67. switch o.CertType {
  68. case "": // ignore
  69. case SSHUserCert:
  70. cert.CertType = ssh.UserCert
  71. case SSHHostCert:
  72. cert.CertType = ssh.HostCert
  73. default:
  74. return errs.BadRequest("ssh certificate has an unknown type '%s'", o.CertType)
  75. }
  76. cert.KeyId = o.KeyID
  77. cert.ValidPrincipals = o.Principals
  78. return o.ModifyValidity(cert)
  79. }
  80. // ModifyValidity modifies only the ValidAfter and ValidBefore on the given
  81. // ssh.Certificate.
  82. func (o SignSSHOptions) ModifyValidity(cert *ssh.Certificate) error {
  83. t := now()
  84. if !o.ValidAfter.IsZero() {
  85. cert.ValidAfter = uint64(o.ValidAfter.RelativeTime(t).Unix())
  86. }
  87. if !o.ValidBefore.IsZero() {
  88. cert.ValidBefore = uint64(o.ValidBefore.RelativeTime(t).Unix())
  89. }
  90. if cert.ValidAfter > 0 && cert.ValidBefore > 0 && cert.ValidAfter > cert.ValidBefore {
  91. return errs.BadRequest("ssh certificate validAfter cannot be greater than validBefore")
  92. }
  93. return nil
  94. }
  95. // match compares two SSHOptions and return an error if they don't match. It
  96. // ignores zero values.
  97. func (o SignSSHOptions) match(got SignSSHOptions) error {
  98. if o.CertType != "" && got.CertType != "" && o.CertType != got.CertType {
  99. return errs.Forbidden("ssh certificate type does not match - got %v, want %v", got.CertType, o.CertType)
  100. }
  101. if len(o.Principals) > 0 && len(got.Principals) > 0 && !containsAllMembers(o.Principals, got.Principals) {
  102. return errs.Forbidden("ssh certificate principals does not match - got %v, want %v", got.Principals, o.Principals)
  103. }
  104. if !o.ValidAfter.IsZero() && !got.ValidAfter.IsZero() && !o.ValidAfter.Equal(&got.ValidAfter) {
  105. return errs.Forbidden("ssh certificate validAfter does not match - got %v, want %v", got.ValidAfter, o.ValidAfter)
  106. }
  107. if !o.ValidBefore.IsZero() && !got.ValidBefore.IsZero() && !o.ValidBefore.Equal(&got.ValidBefore) {
  108. return errs.Forbidden("ssh certificate validBefore does not match - got %v, want %v", got.ValidBefore, o.ValidBefore)
  109. }
  110. return nil
  111. }
  112. // sshCertPrincipalsModifier is an SSHCertModifier that sets the
  113. // principals to the SSH certificate.
  114. type sshCertPrincipalsModifier []string
  115. // Modify the ValidPrincipals value of the cert.
  116. func (o sshCertPrincipalsModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  117. cert.ValidPrincipals = []string(o)
  118. return nil
  119. }
  120. // sshCertKeyIDModifier is an SSHCertModifier that sets the given
  121. // Key ID in the SSH certificate.
  122. type sshCertKeyIDModifier string
  123. func (m sshCertKeyIDModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  124. cert.KeyId = string(m)
  125. return nil
  126. }
  127. // sshCertTypeModifier is an SSHCertModifier that sets the
  128. // certificate type.
  129. type sshCertTypeModifier string
  130. // Modify sets the CertType for the ssh certificate.
  131. func (m sshCertTypeModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  132. cert.CertType = sshCertTypeUInt32(string(m))
  133. return nil
  134. }
  135. // sshCertValidAfterModifier is an SSHCertModifier that sets the
  136. // ValidAfter in the SSH certificate.
  137. type sshCertValidAfterModifier uint64
  138. func (m sshCertValidAfterModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  139. cert.ValidAfter = uint64(m)
  140. return nil
  141. }
  142. // sshCertValidBeforeModifier is an SSHCertModifier that sets the
  143. // ValidBefore in the SSH certificate.
  144. type sshCertValidBeforeModifier uint64
  145. func (m sshCertValidBeforeModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  146. cert.ValidBefore = uint64(m)
  147. return nil
  148. }
  149. // sshCertDefaultsModifier implements a SSHCertModifier that
  150. // modifies the certificate with the given options if they are not set.
  151. type sshCertDefaultsModifier SignSSHOptions
  152. // Modify implements the SSHCertModifier interface.
  153. func (m sshCertDefaultsModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  154. if cert.CertType == 0 {
  155. cert.CertType = sshCertTypeUInt32(m.CertType)
  156. }
  157. if len(cert.ValidPrincipals) == 0 {
  158. cert.ValidPrincipals = m.Principals
  159. }
  160. if cert.ValidAfter == 0 && !m.ValidAfter.IsZero() {
  161. cert.ValidAfter = uint64(m.ValidAfter.Unix())
  162. }
  163. if cert.ValidBefore == 0 && !m.ValidBefore.IsZero() {
  164. cert.ValidBefore = uint64(m.ValidBefore.Unix())
  165. }
  166. return nil
  167. }
  168. // sshDefaultExtensionModifier implements an SSHCertModifier that sets
  169. // the default extensions in an SSH certificate.
  170. type sshDefaultExtensionModifier struct{}
  171. func (m *sshDefaultExtensionModifier) Modify(cert *ssh.Certificate, _ SignSSHOptions) error {
  172. switch cert.CertType {
  173. // Default to no extensions for HostCert.
  174. case ssh.HostCert:
  175. return nil
  176. case ssh.UserCert:
  177. if cert.Extensions == nil {
  178. cert.Extensions = make(map[string]string)
  179. }
  180. cert.Extensions["permit-X11-forwarding"] = ""
  181. cert.Extensions["permit-agent-forwarding"] = ""
  182. cert.Extensions["permit-port-forwarding"] = ""
  183. cert.Extensions["permit-pty"] = ""
  184. cert.Extensions["permit-user-rc"] = ""
  185. return nil
  186. default:
  187. return errs.BadRequest("ssh certificate has an unknown type '%d'", cert.CertType)
  188. }
  189. }
  190. // sshDefaultDuration is an SSHCertModifier that sets the certificate
  191. // ValidAfter and ValidBefore if they have not been set. It will fail if a
  192. // CertType has not been set or is not valid.
  193. type sshDefaultDuration struct {
  194. *Claimer
  195. }
  196. // Modify implements SSHCertModifier and sets the validity if it has not been
  197. // set, but it always applies the backdate.
  198. func (m *sshDefaultDuration) Modify(cert *ssh.Certificate, o SignSSHOptions) error {
  199. d, err := m.DefaultSSHCertDuration(cert.CertType)
  200. if err != nil {
  201. return err
  202. }
  203. var backdate uint64
  204. if cert.ValidAfter == 0 {
  205. backdate = uint64(o.Backdate / time.Second)
  206. cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
  207. }
  208. if cert.ValidBefore == 0 {
  209. cert.ValidBefore = cert.ValidAfter + uint64(d/time.Second)
  210. }
  211. // Apply backdate safely
  212. if cert.ValidAfter > backdate {
  213. cert.ValidAfter -= backdate
  214. }
  215. return nil
  216. }
  217. // sshLimitDuration adjusts the duration to min(default, remaining provisioning
  218. // credential duration). E.g. if the default is 12hrs but the remaining validity
  219. // of the provisioning credential is only 4hrs, this option will set the value
  220. // to 4hrs (the min of the two values). It will fail if a CertType has not been
  221. // set or is not valid.
  222. type sshLimitDuration struct {
  223. *Claimer
  224. NotAfter time.Time
  225. }
  226. // Modify implements SSHCertModifier and modifies the validity of the
  227. // certificate to expire before the configured limit.
  228. func (m *sshLimitDuration) Modify(cert *ssh.Certificate, o SignSSHOptions) error {
  229. if m.NotAfter.IsZero() {
  230. defaultDuration := &sshDefaultDuration{m.Claimer}
  231. return defaultDuration.Modify(cert, o)
  232. }
  233. // Make sure the duration is within the limits.
  234. d, err := m.DefaultSSHCertDuration(cert.CertType)
  235. if err != nil {
  236. return err
  237. }
  238. var backdate uint64
  239. if cert.ValidAfter == 0 {
  240. backdate = uint64(o.Backdate / time.Second)
  241. cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
  242. }
  243. certValidAfter := time.Unix(int64(cert.ValidAfter), 0)
  244. if certValidAfter.After(m.NotAfter) {
  245. return errs.Forbidden("provisioning credential expiration (%s) is before requested certificate validAfter (%s)",
  246. m.NotAfter, certValidAfter)
  247. }
  248. if cert.ValidBefore == 0 {
  249. certValidBefore := certValidAfter.Add(d)
  250. if m.NotAfter.Before(certValidBefore) {
  251. certValidBefore = m.NotAfter
  252. }
  253. cert.ValidBefore = uint64(certValidBefore.Unix())
  254. } else {
  255. certValidBefore := time.Unix(int64(cert.ValidBefore), 0)
  256. if m.NotAfter.Before(certValidBefore) {
  257. return errs.Forbidden("provisioning credential expiration (%s) is before requested certificate validBefore (%s)",
  258. m.NotAfter, certValidBefore)
  259. }
  260. }
  261. // Apply backdate safely
  262. if cert.ValidAfter > backdate {
  263. cert.ValidAfter -= backdate
  264. }
  265. return nil
  266. }
  267. // sshCertOptionsValidator validates the user SSHOptions with the ones
  268. // usually present in the token.
  269. type sshCertOptionsValidator SignSSHOptions
  270. // Valid implements SSHCertOptionsValidator and returns nil if both
  271. // SSHOptions match.
  272. func (v sshCertOptionsValidator) Valid(got SignSSHOptions) error {
  273. want := SignSSHOptions(v)
  274. return want.match(got)
  275. }
  276. // sshCertOptionsRequireValidator defines which elements in the SignSSHOptions are required.
  277. type sshCertOptionsRequireValidator struct {
  278. CertType bool
  279. KeyID bool
  280. Principals bool
  281. }
  282. func (v *sshCertOptionsRequireValidator) Valid(got SignSSHOptions) error {
  283. switch {
  284. case v.CertType && got.CertType == "":
  285. return errs.BadRequest("ssh certificate certType cannot be empty")
  286. case v.KeyID && got.KeyID == "":
  287. return errs.BadRequest("ssh certificate keyID cannot be empty")
  288. case v.Principals && len(got.Principals) == 0:
  289. return errs.BadRequest("ssh certificate principals cannot be empty")
  290. default:
  291. return nil
  292. }
  293. }
  294. type sshCertValidityValidator struct {
  295. *Claimer
  296. }
  297. func (v *sshCertValidityValidator) Valid(cert *ssh.Certificate, opts SignSSHOptions) error {
  298. switch {
  299. case cert.ValidAfter == 0:
  300. return errs.BadRequest("ssh certificate validAfter cannot be 0")
  301. case cert.ValidBefore < uint64(now().Unix()):
  302. return errs.BadRequest("ssh certificate validBefore cannot be in the past")
  303. case cert.ValidBefore < cert.ValidAfter:
  304. return errs.BadRequest("ssh certificate validBefore cannot be before validAfter")
  305. }
  306. var min, max time.Duration
  307. switch cert.CertType {
  308. case ssh.UserCert:
  309. min = v.MinUserSSHCertDuration()
  310. max = v.MaxUserSSHCertDuration()
  311. case ssh.HostCert:
  312. min = v.MinHostSSHCertDuration()
  313. max = v.MaxHostSSHCertDuration()
  314. case 0:
  315. return errs.BadRequest("ssh certificate type has not been set")
  316. default:
  317. return errs.BadRequest("ssh certificate has an unknown type '%d'", cert.CertType)
  318. }
  319. // To not take into account the backdate, time.Now() will be used to
  320. // calculate the duration if ValidAfter is in the past.
  321. dur := time.Duration(cert.ValidBefore-cert.ValidAfter) * time.Second
  322. switch {
  323. case dur < min:
  324. return errs.Forbidden("requested duration of %s is less than minimum accepted duration for selected provisioner of %s", dur, min)
  325. case dur > max+opts.Backdate:
  326. return errs.Forbidden("requested duration of %s is greater than maximum accepted duration for selected provisioner of %s", dur, max+opts.Backdate)
  327. default:
  328. return nil
  329. }
  330. }
  331. // sshCertDefaultValidator implements a simple validator for all the
  332. // fields in the SSH certificate.
  333. type sshCertDefaultValidator struct{}
  334. // Valid returns an error if the given certificate does not contain the
  335. // necessary fields. We skip ValidPrincipals and Extensions as with custom
  336. // templates you can set them empty.
  337. func (v *sshCertDefaultValidator) Valid(cert *ssh.Certificate, o SignSSHOptions) error {
  338. switch {
  339. case len(cert.Nonce) == 0:
  340. return errs.Forbidden("ssh certificate nonce cannot be empty")
  341. case cert.Key == nil:
  342. return errs.Forbidden("ssh certificate key cannot be nil")
  343. case cert.Serial == 0:
  344. return errs.Forbidden("ssh certificate serial cannot be 0")
  345. case cert.CertType != ssh.UserCert && cert.CertType != ssh.HostCert:
  346. return errs.Forbidden("ssh certificate has an unknown type '%d'", cert.CertType)
  347. case cert.KeyId == "":
  348. return errs.Forbidden("ssh certificate key id cannot be empty")
  349. case cert.ValidAfter == 0:
  350. return errs.Forbidden("ssh certificate validAfter cannot be 0")
  351. case cert.ValidBefore < uint64(now().Unix()):
  352. return errs.Forbidden("ssh certificate validBefore cannot be in the past")
  353. case cert.ValidBefore < cert.ValidAfter:
  354. return errs.Forbidden("ssh certificate validBefore cannot be before validAfter")
  355. case cert.SignatureKey == nil:
  356. return errs.Forbidden("ssh certificate signature key cannot be nil")
  357. case cert.Signature == nil:
  358. return errs.Forbidden("ssh certificate signature cannot be nil")
  359. default:
  360. return nil
  361. }
  362. }
  363. // sshDefaultPublicKeyValidator implements a validator for the certificate key.
  364. type sshDefaultPublicKeyValidator struct{}
  365. // Valid checks that certificate request common name matches the one configured.
  366. //
  367. // TODO: this is the only validator that checks the key type. We should execute
  368. // this before the signing. We should add a new validations interface or extend
  369. // SSHCertOptionsValidator with the key.
  370. func (v sshDefaultPublicKeyValidator) Valid(cert *ssh.Certificate, o SignSSHOptions) error {
  371. if cert.Key == nil {
  372. return errs.BadRequest("ssh certificate key cannot be nil")
  373. }
  374. switch cert.Key.Type() {
  375. case ssh.KeyAlgoRSA:
  376. _, in, ok := sshParseString(cert.Key.Marshal())
  377. if !ok {
  378. return errs.BadRequest("ssh certificate key is invalid")
  379. }
  380. key, err := sshParseRSAPublicKey(in)
  381. if err != nil {
  382. return errs.BadRequestErr(err, "error parsing public key")
  383. }
  384. if key.Size() < keyutil.MinRSAKeyBytes {
  385. return errs.Forbidden("ssh certificate key must be at least %d bits (%d bytes)",
  386. 8*keyutil.MinRSAKeyBytes, keyutil.MinRSAKeyBytes)
  387. }
  388. return nil
  389. case ssh.KeyAlgoDSA:
  390. return errs.BadRequest("ssh certificate key algorithm (DSA) is not supported")
  391. default:
  392. return nil
  393. }
  394. }
  395. // sshNamePolicyValidator validates that the certificate (to be signed)
  396. // contains only allowed principals.
  397. type sshNamePolicyValidator struct {
  398. hostPolicyEngine policy.HostPolicy
  399. userPolicyEngine policy.UserPolicy
  400. }
  401. // newSSHNamePolicyValidator return a new SSH allow/deny validator.
  402. func newSSHNamePolicyValidator(host policy.HostPolicy, user policy.UserPolicy) *sshNamePolicyValidator {
  403. return &sshNamePolicyValidator{
  404. hostPolicyEngine: host,
  405. userPolicyEngine: user,
  406. }
  407. }
  408. // Valid validates that the certificate (to be signed) contains only allowed principals.
  409. func (v *sshNamePolicyValidator) Valid(cert *ssh.Certificate, _ SignSSHOptions) error {
  410. if v.hostPolicyEngine == nil && v.userPolicyEngine == nil {
  411. // no policy configured at all; allow anything
  412. return nil
  413. }
  414. // Check the policy type to execute based on type of the certificate.
  415. // We don't allow user certs if only a host policy engine is configured and
  416. // the same for host certs: if only a user policy engine is configured, host
  417. // certs are denied. When both policy engines are configured, the type of
  418. // cert determines which policy engine is used.
  419. switch cert.CertType {
  420. case ssh.HostCert:
  421. // when no host policy engine is configured, but a user policy engine is
  422. // configured, the host certificate is denied.
  423. if v.hostPolicyEngine == nil && v.userPolicyEngine != nil {
  424. return errors.New("SSH host certificate not authorized")
  425. }
  426. return v.hostPolicyEngine.IsSSHCertificateAllowed(cert)
  427. case ssh.UserCert:
  428. // when no user policy engine is configured, but a host policy engine is
  429. // configured, the user certificate is denied.
  430. if v.userPolicyEngine == nil && v.hostPolicyEngine != nil {
  431. return errors.New("SSH user certificate not authorized")
  432. }
  433. return v.userPolicyEngine.IsSSHCertificateAllowed(cert)
  434. default:
  435. return fmt.Errorf("unexpected SSH certificate type %d", cert.CertType) // satisfy return; shouldn't happen
  436. }
  437. }
  438. // sshCertTypeUInt32
  439. func sshCertTypeUInt32(ct string) uint32 {
  440. switch ct {
  441. case SSHUserCert:
  442. return ssh.UserCert
  443. case SSHHostCert:
  444. return ssh.HostCert
  445. default:
  446. return 0
  447. }
  448. }
  449. // containsAllMembers reports whether all members of subgroup are within group.
  450. func containsAllMembers(group, subgroup []string) bool {
  451. lg, lsg := len(group), len(subgroup)
  452. if lsg > lg || (lg > 0 && lsg == 0) {
  453. return false
  454. }
  455. visit := make(map[string]struct{}, lg)
  456. for i := 0; i < lg; i++ {
  457. visit[strings.ToLower(group[i])] = struct{}{}
  458. }
  459. for i := 0; i < lsg; i++ {
  460. if _, ok := visit[strings.ToLower(subgroup[i])]; !ok {
  461. return false
  462. }
  463. }
  464. return true
  465. }
  466. func sshParseString(in []byte) (out, rest []byte, ok bool) {
  467. if len(in) < 4 {
  468. return
  469. }
  470. length := binary.BigEndian.Uint32(in)
  471. in = in[4:]
  472. if uint32(len(in)) < length {
  473. return
  474. }
  475. out = in[:length]
  476. rest = in[length:]
  477. ok = true
  478. return
  479. }
  480. func sshParseRSAPublicKey(in []byte) (*rsa.PublicKey, error) {
  481. var w struct {
  482. E *big.Int
  483. N *big.Int
  484. Rest []byte `ssh:"rest"`
  485. }
  486. if err := ssh.Unmarshal(in, &w); err != nil {
  487. return nil, errors.Wrap(err, "error unmarshalling public key")
  488. }
  489. if w.E.BitLen() > 24 {
  490. return nil, errors.New("invalid public key: exponent too large")
  491. }
  492. e := w.E.Int64()
  493. if e < 3 || e&1 == 0 {
  494. return nil, errors.New("invalid public key: incorrect exponent")
  495. }
  496. var key rsa.PublicKey
  497. key.E = int(e)
  498. key.N = w.N
  499. return &key, nil
  500. }