sign_ssh_options.go 16 KB

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