sign_ssh_options.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496
  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. // SSHCertModifier is the interface used to change properties in an SSH
  18. // certificate.
  19. type SSHCertModifier interface {
  20. SignOption
  21. Modify(cert *ssh.Certificate) error
  22. }
  23. // SSHCertOptionModifier is the interface used to add custom options used
  24. // to modify the SSH certificate.
  25. type SSHCertOptionModifier interface {
  26. SignOption
  27. Option(o SSHOptions) SSHCertModifier
  28. }
  29. // SSHCertValidator is the interface used to validate an SSH certificate.
  30. type SSHCertValidator interface {
  31. SignOption
  32. Valid(cert *ssh.Certificate, opts SSHOptions) error
  33. }
  34. // SSHCertOptionsValidator is the interface used to validate the custom
  35. // options used to modify the SSH certificate.
  36. type SSHCertOptionsValidator interface {
  37. SignOption
  38. Valid(got SSHOptions) error
  39. }
  40. // sshModifierFunc is an adapter to allow the use of ordinary functions as SSH
  41. // certificate modifiers.
  42. type sshModifierFunc func(cert *ssh.Certificate) error
  43. func (f sshModifierFunc) Modify(cert *ssh.Certificate) error {
  44. return f(cert)
  45. }
  46. // SSHOptions contains the options that can be passed to the SignSSH method.
  47. type SSHOptions struct {
  48. CertType string `json:"certType"`
  49. KeyID string `json:"keyID"`
  50. Principals []string `json:"principals"`
  51. ValidAfter TimeDuration `json:"validAfter,omitempty"`
  52. ValidBefore TimeDuration `json:"validBefore,omitempty"`
  53. Backdate time.Duration `json:"-"`
  54. }
  55. // Type returns the uint32 representation of the CertType.
  56. func (o SSHOptions) Type() uint32 {
  57. return sshCertTypeUInt32(o.CertType)
  58. }
  59. // Modify implements SSHCertModifier and sets the SSHOption in the ssh.Certificate.
  60. func (o SSHOptions) Modify(cert *ssh.Certificate) error {
  61. switch o.CertType {
  62. case "": // ignore
  63. case SSHUserCert:
  64. cert.CertType = ssh.UserCert
  65. case SSHHostCert:
  66. cert.CertType = ssh.HostCert
  67. default:
  68. return errors.Errorf("ssh certificate has an unknown type - %s", o.CertType)
  69. }
  70. cert.KeyId = o.KeyID
  71. cert.ValidPrincipals = o.Principals
  72. t := now()
  73. if !o.ValidAfter.IsZero() {
  74. cert.ValidAfter = uint64(o.ValidAfter.RelativeTime(t).Unix())
  75. }
  76. if !o.ValidBefore.IsZero() {
  77. cert.ValidBefore = uint64(o.ValidBefore.RelativeTime(t).Unix())
  78. }
  79. if cert.ValidAfter > 0 && cert.ValidBefore > 0 && cert.ValidAfter > cert.ValidBefore {
  80. return errors.New("ssh certificate valid after cannot be greater than valid before")
  81. }
  82. return nil
  83. }
  84. // match compares two SSHOptions and return an error if they don't match. It
  85. // ignores zero values.
  86. func (o SSHOptions) match(got SSHOptions) error {
  87. if o.CertType != "" && got.CertType != "" && o.CertType != got.CertType {
  88. return errors.Errorf("ssh certificate type does not match - got %v, want %v", got.CertType, o.CertType)
  89. }
  90. if len(o.Principals) > 0 && len(got.Principals) > 0 && !containsAllMembers(o.Principals, got.Principals) {
  91. return errors.Errorf("ssh certificate principals does not match - got %v, want %v", got.Principals, o.Principals)
  92. }
  93. if !o.ValidAfter.IsZero() && !got.ValidAfter.IsZero() && !o.ValidAfter.Equal(&got.ValidAfter) {
  94. return errors.Errorf("ssh certificate valid after does not match - got %v, want %v", got.ValidAfter, o.ValidAfter)
  95. }
  96. if !o.ValidBefore.IsZero() && !got.ValidBefore.IsZero() && !o.ValidBefore.Equal(&got.ValidBefore) {
  97. return errors.Errorf("ssh certificate valid before does not match - got %v, want %v", got.ValidBefore, o.ValidBefore)
  98. }
  99. return nil
  100. }
  101. // sshCertPrincipalsModifier is an SSHCertModifier that sets the
  102. // principals to the SSH certificate.
  103. type sshCertPrincipalsModifier []string
  104. // Modify the ValidPrincipals value of the cert.
  105. func (o sshCertPrincipalsModifier) Modify(cert *ssh.Certificate) error {
  106. cert.ValidPrincipals = []string(o)
  107. return nil
  108. }
  109. // sshCertKeyIDModifier is an SSHCertModifier that sets the given
  110. // Key ID in the SSH certificate.
  111. type sshCertKeyIDModifier string
  112. func (m sshCertKeyIDModifier) Modify(cert *ssh.Certificate) error {
  113. cert.KeyId = string(m)
  114. return nil
  115. }
  116. // sshCertTypeModifier is an SSHCertModifier that sets the
  117. // certificate type.
  118. type sshCertTypeModifier string
  119. // Modify sets the CertType for the ssh certificate.
  120. func (m sshCertTypeModifier) Modify(cert *ssh.Certificate) error {
  121. cert.CertType = sshCertTypeUInt32(string(m))
  122. return nil
  123. }
  124. // sshCertValidAfterModifier is an SSHCertModifier that sets the
  125. // ValidAfter in the SSH certificate.
  126. type sshCertValidAfterModifier uint64
  127. func (m sshCertValidAfterModifier) Modify(cert *ssh.Certificate) error {
  128. cert.ValidAfter = uint64(m)
  129. return nil
  130. }
  131. // sshCertValidBeforeModifier is an SSHCertModifier that sets the
  132. // ValidBefore in the SSH certificate.
  133. type sshCertValidBeforeModifier uint64
  134. func (m sshCertValidBeforeModifier) Modify(cert *ssh.Certificate) error {
  135. cert.ValidBefore = uint64(m)
  136. return nil
  137. }
  138. // sshCertDefaultsModifier implements a SSHCertModifier that
  139. // modifies the certificate with the given options if they are not set.
  140. type sshCertDefaultsModifier SSHOptions
  141. // Modify implements the SSHCertModifier interface.
  142. func (m sshCertDefaultsModifier) Modify(cert *ssh.Certificate) error {
  143. if cert.CertType == 0 {
  144. cert.CertType = sshCertTypeUInt32(m.CertType)
  145. }
  146. if len(cert.ValidPrincipals) == 0 {
  147. cert.ValidPrincipals = m.Principals
  148. }
  149. if cert.ValidAfter == 0 && !m.ValidAfter.IsZero() {
  150. cert.ValidAfter = uint64(m.ValidAfter.Unix())
  151. }
  152. if cert.ValidBefore == 0 && !m.ValidBefore.IsZero() {
  153. cert.ValidBefore = uint64(m.ValidBefore.Unix())
  154. }
  155. return nil
  156. }
  157. // sshDefaultExtensionModifier implements an SSHCertModifier that sets
  158. // the default extensions in an SSH certificate.
  159. type sshDefaultExtensionModifier struct{}
  160. func (m *sshDefaultExtensionModifier) Modify(cert *ssh.Certificate) error {
  161. switch cert.CertType {
  162. // Default to no extensions for HostCert.
  163. case ssh.HostCert:
  164. return nil
  165. case ssh.UserCert:
  166. if cert.Extensions == nil {
  167. cert.Extensions = make(map[string]string)
  168. }
  169. cert.Extensions["permit-X11-forwarding"] = ""
  170. cert.Extensions["permit-agent-forwarding"] = ""
  171. cert.Extensions["permit-port-forwarding"] = ""
  172. cert.Extensions["permit-pty"] = ""
  173. cert.Extensions["permit-user-rc"] = ""
  174. return nil
  175. default:
  176. return errors.New("ssh certificate type has not been set or is invalid")
  177. }
  178. }
  179. // sshDefaultDuration is an SSHCertModifier that sets the certificate
  180. // ValidAfter and ValidBefore if they have not been set. It will fail if a
  181. // CertType has not been set or is not valid.
  182. type sshDefaultDuration struct {
  183. *Claimer
  184. }
  185. func (m *sshDefaultDuration) Option(o SSHOptions) SSHCertModifier {
  186. return sshModifierFunc(func(cert *ssh.Certificate) error {
  187. d, err := m.DefaultSSHCertDuration(cert.CertType)
  188. if err != nil {
  189. return err
  190. }
  191. var backdate uint64
  192. if cert.ValidAfter == 0 {
  193. backdate = uint64(o.Backdate / time.Second)
  194. cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
  195. }
  196. if cert.ValidBefore == 0 {
  197. cert.ValidBefore = cert.ValidAfter + uint64(d/time.Second)
  198. }
  199. // Apply backdate safely
  200. if cert.ValidAfter > backdate {
  201. cert.ValidAfter -= backdate
  202. }
  203. return nil
  204. })
  205. }
  206. // sshLimitDuration adjusts the duration to min(default, remaining provisioning
  207. // credential duration). E.g. if the default is 12hrs but the remaining validity
  208. // of the provisioning credential is only 4hrs, this option will set the value
  209. // to 4hrs (the min of the two values). It will fail if a CertType has not been
  210. // set or is not valid.
  211. type sshLimitDuration struct {
  212. *Claimer
  213. NotAfter time.Time
  214. }
  215. func (m *sshLimitDuration) Option(o SSHOptions) SSHCertModifier {
  216. if m.NotAfter.IsZero() {
  217. defaultDuration := &sshDefaultDuration{m.Claimer}
  218. return defaultDuration.Option(o)
  219. }
  220. return sshModifierFunc(func(cert *ssh.Certificate) error {
  221. d, err := m.DefaultSSHCertDuration(cert.CertType)
  222. if err != nil {
  223. return err
  224. }
  225. var backdate uint64
  226. if cert.ValidAfter == 0 {
  227. backdate = uint64(o.Backdate / time.Second)
  228. cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
  229. }
  230. certValidAfter := time.Unix(int64(cert.ValidAfter), 0)
  231. if certValidAfter.After(m.NotAfter) {
  232. return errors.Errorf("provisioning credential expiration (%s) is before requested certificate validAfter (%s)",
  233. m.NotAfter, certValidAfter)
  234. }
  235. if cert.ValidBefore == 0 {
  236. certValidBefore := certValidAfter.Add(d)
  237. if m.NotAfter.Before(certValidBefore) {
  238. certValidBefore = m.NotAfter
  239. }
  240. cert.ValidBefore = uint64(certValidBefore.Unix())
  241. } else {
  242. certValidBefore := time.Unix(int64(cert.ValidBefore), 0)
  243. if m.NotAfter.Before(certValidBefore) {
  244. return errors.Errorf("provisioning credential expiration (%s) is before requested certificate validBefore (%s)",
  245. m.NotAfter, certValidBefore)
  246. }
  247. }
  248. // Apply backdate safely
  249. if cert.ValidAfter > backdate {
  250. cert.ValidAfter -= backdate
  251. }
  252. return nil
  253. })
  254. }
  255. // sshCertOptionsValidator validates the user SSHOptions with the ones
  256. // usually present in the token.
  257. type sshCertOptionsValidator SSHOptions
  258. // Valid implements SSHCertOptionsValidator and returns nil if both
  259. // SSHOptions match.
  260. func (v sshCertOptionsValidator) Valid(got SSHOptions) error {
  261. want := SSHOptions(v)
  262. return want.match(got)
  263. }
  264. type sshCertValidityValidator struct {
  265. *Claimer
  266. }
  267. func (v *sshCertValidityValidator) Valid(cert *ssh.Certificate, opts SSHOptions) error {
  268. switch {
  269. case cert.ValidAfter == 0:
  270. return errors.New("ssh certificate validAfter cannot be 0")
  271. case cert.ValidBefore < uint64(now().Unix()):
  272. return errors.New("ssh certificate validBefore cannot be in the past")
  273. case cert.ValidBefore < cert.ValidAfter:
  274. return errors.New("ssh certificate validBefore cannot be before validAfter")
  275. }
  276. var min, max time.Duration
  277. switch cert.CertType {
  278. case ssh.UserCert:
  279. min = v.MinUserSSHCertDuration()
  280. max = v.MaxUserSSHCertDuration()
  281. case ssh.HostCert:
  282. min = v.MinHostSSHCertDuration()
  283. max = v.MaxHostSSHCertDuration()
  284. case 0:
  285. return errors.New("ssh certificate type has not been set")
  286. default:
  287. return errors.Errorf("unknown ssh certificate type %d", cert.CertType)
  288. }
  289. // To not take into account the backdate, time.Now() will be used to
  290. // calculate the duration if ValidAfter is in the past.
  291. dur := time.Duration(cert.ValidBefore-cert.ValidAfter) * time.Second
  292. switch {
  293. case dur < min:
  294. return errors.Errorf("requested duration of %s is less than minimum "+
  295. "accepted duration for selected provisioner of %s", dur, min)
  296. case dur > max+opts.Backdate:
  297. return errors.Errorf("requested duration of %s is greater than maximum "+
  298. "accepted duration for selected provisioner of %s", dur, max+opts.Backdate)
  299. default:
  300. return nil
  301. }
  302. }
  303. // sshCertDefaultValidator implements a simple validator for all the
  304. // fields in the SSH certificate.
  305. type sshCertDefaultValidator struct{}
  306. // Valid returns an error if the given certificate does not contain the necessary fields.
  307. func (v *sshCertDefaultValidator) Valid(cert *ssh.Certificate, o SSHOptions) error {
  308. switch {
  309. case len(cert.Nonce) == 0:
  310. return errors.New("ssh certificate nonce cannot be empty")
  311. case cert.Key == nil:
  312. return errors.New("ssh certificate key cannot be nil")
  313. case cert.Serial == 0:
  314. return errors.New("ssh certificate serial cannot be 0")
  315. case cert.CertType != ssh.UserCert && cert.CertType != ssh.HostCert:
  316. return errors.Errorf("ssh certificate has an unknown type: %d", cert.CertType)
  317. case cert.KeyId == "":
  318. return errors.New("ssh certificate key id cannot be empty")
  319. case len(cert.ValidPrincipals) == 0:
  320. return errors.New("ssh certificate valid principals cannot be empty")
  321. case cert.ValidAfter == 0:
  322. return errors.New("ssh certificate validAfter cannot be 0")
  323. case cert.ValidBefore < uint64(now().Unix()):
  324. return errors.New("ssh certificate validBefore cannot be in the past")
  325. case cert.ValidBefore < cert.ValidAfter:
  326. return errors.New("ssh certificate validBefore cannot be before validAfter")
  327. case cert.CertType == ssh.UserCert && len(cert.Extensions) == 0:
  328. return errors.New("ssh certificate extensions cannot be empty")
  329. case cert.SignatureKey == nil:
  330. return errors.New("ssh certificate signature key cannot be nil")
  331. case cert.Signature == nil:
  332. return errors.New("ssh certificate signature cannot be nil")
  333. default:
  334. return nil
  335. }
  336. }
  337. // sshDefaultPublicKeyValidator implements a validator for the certificate key.
  338. type sshDefaultPublicKeyValidator struct{}
  339. // Valid checks that certificate request common name matches the one configured.
  340. func (v sshDefaultPublicKeyValidator) Valid(cert *ssh.Certificate, o SSHOptions) error {
  341. if cert.Key == nil {
  342. return errors.New("ssh certificate key cannot be nil")
  343. }
  344. switch cert.Key.Type() {
  345. case ssh.KeyAlgoRSA:
  346. _, in, ok := sshParseString(cert.Key.Marshal())
  347. if !ok {
  348. return errors.New("ssh certificate key is invalid")
  349. }
  350. key, err := sshParseRSAPublicKey(in)
  351. if err != nil {
  352. return err
  353. }
  354. if key.Size() < keys.MinRSAKeyBytes {
  355. return errors.Errorf("ssh certificate key must be at least %d bits (%d bytes)",
  356. 8*keys.MinRSAKeyBytes, keys.MinRSAKeyBytes)
  357. }
  358. return nil
  359. case ssh.KeyAlgoDSA:
  360. return errors.New("ssh certificate key algorithm (DSA) is not supported")
  361. default:
  362. return nil
  363. }
  364. }
  365. // sshCertKeyIDValidator implements a validator for the KeyId attribute.
  366. type sshCertKeyIDValidator string
  367. // Valid returns an error if the given certificate does not contain the necessary fields.
  368. func (v sshCertKeyIDValidator) Valid(cert *ssh.Certificate, o SSHOptions) error {
  369. if string(v) != cert.KeyId {
  370. return errors.Errorf("invalid ssh certificate KeyId; want %s, but got %s", string(v), cert.KeyId)
  371. }
  372. return nil
  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[group[i]] = struct{}{}
  394. }
  395. for i := 0; i < lsg; i++ {
  396. if _, ok := visit[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. }