sign_ssh_options.go 15 KB

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