sign_ssh_options.go 16 KB

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