sign_ssh_options.go 15 KB

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