sign_ssh_options.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  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. // sshCertificateValidityModifier is a SSHCertificateModifier 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 sshCertificateValidityModifier struct {
  171. *Claimer
  172. }
  173. func (m *sshCertificateValidityModifier) Modify(cert *ssh.Certificate) error {
  174. var d, min, max time.Duration
  175. switch cert.CertType {
  176. case ssh.UserCert:
  177. d = m.DefaultUserSSHCertDuration()
  178. min = m.MinUserSSHCertDuration()
  179. max = m.MaxUserSSHCertDuration()
  180. case ssh.HostCert:
  181. d = m.DefaultHostSSHCertDuration()
  182. min = m.MinHostSSHCertDuration()
  183. max = m.MaxHostSSHCertDuration()
  184. case 0:
  185. return errors.New("ssh certificate type has not been set")
  186. default:
  187. return errors.Errorf("unknown ssh certificate type %d", cert.CertType)
  188. }
  189. if cert.ValidAfter == 0 {
  190. cert.ValidAfter = uint64(now().Truncate(time.Second).Unix())
  191. }
  192. if cert.ValidBefore == 0 {
  193. t := time.Unix(int64(cert.ValidAfter), 0)
  194. cert.ValidBefore = uint64(t.Add(d).Unix())
  195. }
  196. diff := time.Duration(cert.ValidBefore-cert.ValidAfter) * time.Second
  197. switch {
  198. case diff < min:
  199. return errors.Errorf("ssh certificate duration cannot be lower than %s", min)
  200. case diff > max:
  201. return errors.Errorf("ssh certificate duration cannot be greater than %s", max)
  202. default:
  203. return nil
  204. }
  205. }
  206. // sshCertificateOptionsValidator validates the user SSHOptions with the ones
  207. // usually present in the token.
  208. type sshCertificateOptionsValidator SSHOptions
  209. // Valid implements SSHCertificateOptionsValidator and returns nil if both
  210. // SSHOptions match.
  211. func (v sshCertificateOptionsValidator) Valid(got SSHOptions) error {
  212. want := SSHOptions(v)
  213. return want.match(got)
  214. }
  215. // sshCertificateDefaultValidator implements a simple validator for all the
  216. // fields in the SSH certificate.
  217. type sshCertificateDefaultValidator struct{}
  218. // Valid returns an error if the given certificate does not contain the necessary fields.
  219. func (v *sshCertificateDefaultValidator) Valid(cert *ssh.Certificate) error {
  220. switch {
  221. case len(cert.Nonce) == 0:
  222. return errors.New("ssh certificate nonce cannot be empty")
  223. case cert.Key == nil:
  224. return errors.New("ssh certificate key cannot be nil")
  225. case cert.Serial == 0:
  226. return errors.New("ssh certificate serial cannot be 0")
  227. case cert.CertType != ssh.UserCert && cert.CertType != ssh.HostCert:
  228. return errors.Errorf("ssh certificate has an unknown type: %d", cert.CertType)
  229. case cert.KeyId == "":
  230. return errors.New("ssh certificate key id cannot be empty")
  231. case len(cert.ValidPrincipals) == 0:
  232. return errors.New("ssh certificate valid principals cannot be empty")
  233. case cert.ValidAfter == 0:
  234. return errors.New("ssh certificate validAfter cannot be 0")
  235. case cert.ValidBefore < uint64(now().Unix()):
  236. return errors.New("ssh certificate validBefore cannot be in the past")
  237. case cert.ValidBefore < cert.ValidAfter:
  238. return errors.New("ssh certificate validBefore cannot be before validAfter")
  239. case cert.CertType == ssh.UserCert && len(cert.Extensions) == 0:
  240. return errors.New("ssh certificate extensions cannot be empty")
  241. case cert.SignatureKey == nil:
  242. return errors.New("ssh certificate signature key cannot be nil")
  243. case cert.Signature == nil:
  244. return errors.New("ssh certificate signature cannot be nil")
  245. default:
  246. return nil
  247. }
  248. }
  249. // sshDefaultPublicKeyValidator implements a validator for the certificate key.
  250. type sshDefaultPublicKeyValidator struct{}
  251. // Valid checks that certificate request common name matches the one configured.
  252. func (v sshDefaultPublicKeyValidator) Valid(cert *ssh.Certificate) error {
  253. if cert.Key == nil {
  254. return errors.New("ssh certificate key cannot be nil")
  255. }
  256. switch cert.Key.Type() {
  257. case ssh.KeyAlgoRSA:
  258. _, in, ok := sshParseString(cert.Key.Marshal())
  259. if !ok {
  260. return errors.New("ssh certificate key is invalid")
  261. }
  262. key, err := sshParseRSAPublicKey(in)
  263. if err != nil {
  264. return err
  265. }
  266. if key.Size() < keys.MinRSAKeyBytes {
  267. return errors.Errorf("ssh certificate key must be at least %d bits (%d bytes)",
  268. 8*keys.MinRSAKeyBytes, keys.MinRSAKeyBytes)
  269. }
  270. return nil
  271. case ssh.KeyAlgoDSA:
  272. return errors.New("ssh certificate key algorithm (DSA) is not supported")
  273. default:
  274. return nil
  275. }
  276. }
  277. // sshCertTypeUInt32
  278. func sshCertTypeUInt32(ct string) uint32 {
  279. switch ct {
  280. case SSHUserCert:
  281. return ssh.UserCert
  282. case SSHHostCert:
  283. return ssh.HostCert
  284. default:
  285. return 0
  286. }
  287. }
  288. // containsAllMembers reports whether all members of subgroup are within group.
  289. func containsAllMembers(group, subgroup []string) bool {
  290. lg, lsg := len(group), len(subgroup)
  291. if lsg > lg || (lg > 0 && lsg == 0) {
  292. return false
  293. }
  294. visit := make(map[string]struct{}, lg)
  295. for i := 0; i < lg; i++ {
  296. visit[group[i]] = struct{}{}
  297. }
  298. for i := 0; i < lsg; i++ {
  299. if _, ok := visit[subgroup[i]]; !ok {
  300. return false
  301. }
  302. }
  303. return true
  304. }
  305. func sshParseString(in []byte) (out, rest []byte, ok bool) {
  306. if len(in) < 4 {
  307. return
  308. }
  309. length := binary.BigEndian.Uint32(in)
  310. in = in[4:]
  311. if uint32(len(in)) < length {
  312. return
  313. }
  314. out = in[:length]
  315. rest = in[length:]
  316. ok = true
  317. return
  318. }
  319. func sshParseRSAPublicKey(in []byte) (*rsa.PublicKey, error) {
  320. var w struct {
  321. E *big.Int
  322. N *big.Int
  323. Rest []byte `ssh:"rest"`
  324. }
  325. if err := ssh.Unmarshal(in, &w); err != nil {
  326. return nil, errors.Wrap(err, "error unmarshalling public key")
  327. }
  328. if w.E.BitLen() > 24 {
  329. return nil, errors.New("invalid public key: exponent too large")
  330. }
  331. e := w.E.Int64()
  332. if e < 3 || e&1 == 0 {
  333. return nil, errors.New("invalid public key: incorrect exponent")
  334. }
  335. var key rsa.PublicKey
  336. key.E = int(e)
  337. key.N = w.N
  338. return &key, nil
  339. }