sign_ssh_options.go 14 KB

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