ssh.go 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208
  1. package outbound
  2. import (
  3. "bytes"
  4. "context"
  5. "encoding/base64"
  6. "fmt"
  7. "net"
  8. "os"
  9. "runtime"
  10. "strconv"
  11. "strings"
  12. "sync"
  13. N "github.com/metacubex/mihomo/common/net"
  14. "github.com/metacubex/mihomo/component/dialer"
  15. "github.com/metacubex/mihomo/component/proxydialer"
  16. C "github.com/metacubex/mihomo/constant"
  17. "github.com/metacubex/randv2"
  18. "golang.org/x/crypto/ssh"
  19. )
  20. type Ssh struct {
  21. *Base
  22. option *SshOption
  23. client *sshClient // using a standalone struct to avoid its inner loop invalidate the Finalizer
  24. }
  25. type SshOption struct {
  26. BasicOption
  27. Name string `proxy:"name"`
  28. Server string `proxy:"server"`
  29. Port int `proxy:"port"`
  30. UserName string `proxy:"username"`
  31. Password string `proxy:"password,omitempty"`
  32. PrivateKey string `proxy:"private-key,omitempty"`
  33. PrivateKeyPassphrase string `proxy:"private-key-passphrase,omitempty"`
  34. HostKey []string `proxy:"host-key,omitempty"`
  35. HostKeyAlgorithms []string `proxy:"host-key-algorithms,omitempty"`
  36. }
  37. func (s *Ssh) DialContext(ctx context.Context, metadata *C.Metadata, opts ...dialer.Option) (_ C.Conn, err error) {
  38. var cDialer C.Dialer = dialer.NewDialer(s.Base.DialOptions(opts...)...)
  39. if len(s.option.DialerProxy) > 0 {
  40. cDialer, err = proxydialer.NewByName(s.option.DialerProxy, cDialer)
  41. if err != nil {
  42. return nil, err
  43. }
  44. }
  45. client, err := s.client.connect(ctx, cDialer, s.addr)
  46. if err != nil {
  47. return nil, err
  48. }
  49. c, err := client.DialContext(ctx, "tcp", metadata.RemoteAddress())
  50. if err != nil {
  51. return nil, err
  52. }
  53. return NewConn(N.NewRefConn(c, s), s), nil
  54. }
  55. type sshClient struct {
  56. config *ssh.ClientConfig
  57. client *ssh.Client
  58. cMutex sync.Mutex
  59. }
  60. func (s *sshClient) connect(ctx context.Context, cDialer C.Dialer, addr string) (client *ssh.Client, err error) {
  61. s.cMutex.Lock()
  62. defer s.cMutex.Unlock()
  63. if s.client != nil {
  64. return s.client, nil
  65. }
  66. c, err := cDialer.DialContext(ctx, "tcp", addr)
  67. if err != nil {
  68. return nil, err
  69. }
  70. N.TCPKeepAlive(c)
  71. defer func(c net.Conn) {
  72. safeConnClose(c, err)
  73. }(c)
  74. if ctx.Done() != nil {
  75. done := N.SetupContextForConn(ctx, c)
  76. defer done(&err)
  77. }
  78. clientConn, chans, reqs, err := ssh.NewClientConn(c, addr, s.config)
  79. if err != nil {
  80. return nil, err
  81. }
  82. client = ssh.NewClient(clientConn, chans, reqs)
  83. s.client = client
  84. go func() {
  85. _ = client.Wait() // wait shutdown
  86. _ = client.Close()
  87. s.cMutex.Lock()
  88. defer s.cMutex.Unlock()
  89. if s.client == client {
  90. s.client = nil
  91. }
  92. }()
  93. return client, nil
  94. }
  95. func (s *sshClient) Close() error {
  96. s.cMutex.Lock()
  97. defer s.cMutex.Unlock()
  98. if s.client != nil {
  99. return s.client.Close()
  100. }
  101. return nil
  102. }
  103. func closeSsh(s *Ssh) {
  104. _ = s.client.Close()
  105. }
  106. func NewSsh(option SshOption) (*Ssh, error) {
  107. addr := net.JoinHostPort(option.Server, strconv.Itoa(option.Port))
  108. config := ssh.ClientConfig{
  109. User: option.UserName,
  110. HostKeyCallback: ssh.InsecureIgnoreHostKey(),
  111. HostKeyAlgorithms: option.HostKeyAlgorithms,
  112. }
  113. if option.PrivateKey != "" {
  114. var b []byte
  115. var err error
  116. if strings.Contains(option.PrivateKey, "PRIVATE KEY") {
  117. b = []byte(option.PrivateKey)
  118. } else {
  119. b, err = os.ReadFile(C.Path.Resolve(option.PrivateKey))
  120. if err != nil {
  121. return nil, err
  122. }
  123. }
  124. var pKey ssh.Signer
  125. if option.PrivateKeyPassphrase != "" {
  126. pKey, err = ssh.ParsePrivateKeyWithPassphrase(b, []byte(option.PrivateKeyPassphrase))
  127. } else {
  128. pKey, err = ssh.ParsePrivateKey(b)
  129. }
  130. if err != nil {
  131. return nil, err
  132. }
  133. config.Auth = append(config.Auth, ssh.PublicKeys(pKey))
  134. }
  135. if option.Password != "" {
  136. config.Auth = append(config.Auth, ssh.Password(option.Password))
  137. }
  138. if len(option.HostKey) != 0 {
  139. keys := make([]ssh.PublicKey, len(option.HostKey))
  140. for i, hostKey := range option.HostKey {
  141. key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
  142. if err != nil {
  143. return nil, fmt.Errorf("parse host key :%s", key)
  144. }
  145. keys[i] = key
  146. }
  147. config.HostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
  148. serverKey := key.Marshal()
  149. for _, hostKey := range keys {
  150. if bytes.Equal(serverKey, hostKey.Marshal()) {
  151. return nil
  152. }
  153. }
  154. return fmt.Errorf("host key mismatch, server send :%s %s", key.Type(), base64.StdEncoding.EncodeToString(serverKey))
  155. }
  156. }
  157. version := "SSH-2.0-OpenSSH_"
  158. if randv2.IntN(2) == 0 {
  159. version += "7." + strconv.Itoa(randv2.IntN(10))
  160. } else {
  161. version += "8." + strconv.Itoa(randv2.IntN(9))
  162. }
  163. config.ClientVersion = version
  164. outbound := &Ssh{
  165. Base: &Base{
  166. name: option.Name,
  167. addr: addr,
  168. tp: C.Ssh,
  169. udp: false,
  170. iface: option.Interface,
  171. rmark: option.RoutingMark,
  172. prefer: C.NewDNSPrefer(option.IPVersion),
  173. },
  174. option: &option,
  175. client: &sshClient{
  176. config: &config,
  177. },
  178. }
  179. runtime.SetFinalizer(outbound, closeSsh)
  180. return outbound, nil
  181. }