sign_ssh_options.go 14 KB

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