sign_ssh_options.go 16 KB

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