sign_ssh_options.go 16 KB

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