ssh.go 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171
  1. package outbound
  2. import (
  3. "context"
  4. "math/rand"
  5. "net"
  6. "os"
  7. "strconv"
  8. "sync"
  9. "github.com/sagernet/sing-box/adapter"
  10. "github.com/sagernet/sing-box/common/dialer"
  11. C "github.com/sagernet/sing-box/constant"
  12. "github.com/sagernet/sing-box/log"
  13. "github.com/sagernet/sing-box/option"
  14. "github.com/sagernet/sing/common"
  15. E "github.com/sagernet/sing/common/exceptions"
  16. M "github.com/sagernet/sing/common/metadata"
  17. N "github.com/sagernet/sing/common/network"
  18. "golang.org/x/crypto/ssh"
  19. )
  20. var _ adapter.Outbound = (*SSH)(nil)
  21. type SSH struct {
  22. myOutboundAdapter
  23. ctx context.Context
  24. dialer N.Dialer
  25. serverAddr M.Socksaddr
  26. user string
  27. hostKeyAlgorithms []string
  28. clientVersion string
  29. authMethod []ssh.AuthMethod
  30. clientAccess sync.Mutex
  31. clientConn net.Conn
  32. client *ssh.Client
  33. }
  34. func NewSSH(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SSHOutboundOptions) (*SSH, error) {
  35. outbound := &SSH{
  36. myOutboundAdapter: myOutboundAdapter{
  37. protocol: C.TypeSSH,
  38. network: []string{N.NetworkTCP},
  39. router: router,
  40. logger: logger,
  41. tag: tag,
  42. },
  43. ctx: ctx,
  44. dialer: dialer.New(router, options.DialerOptions),
  45. serverAddr: options.ServerOptions.Build(),
  46. user: options.User,
  47. hostKeyAlgorithms: options.HostKeyAlgorithms,
  48. clientVersion: options.ClientVersion,
  49. }
  50. if outbound.serverAddr.Port == 0 {
  51. outbound.serverAddr.Port = 22
  52. }
  53. if outbound.user == "" {
  54. outbound.user = "root"
  55. }
  56. if outbound.clientVersion == "" {
  57. outbound.clientVersion = randomVersion()
  58. }
  59. if options.Password != "" {
  60. outbound.authMethod = append(outbound.authMethod, ssh.Password(options.Password))
  61. }
  62. if options.PrivateKey != "" || options.PrivateKeyPath != "" {
  63. var privateKey []byte
  64. if options.PrivateKey != "" {
  65. privateKey = []byte(options.PrivateKey)
  66. } else {
  67. var err error
  68. privateKey, err = os.ReadFile(os.ExpandEnv(options.PrivateKeyPath))
  69. if err != nil {
  70. return nil, E.Cause(err, "read private key")
  71. }
  72. }
  73. var signer ssh.Signer
  74. var err error
  75. if options.PrivateKeyPassphrase == "" {
  76. signer, err = ssh.ParsePrivateKey(privateKey)
  77. } else {
  78. signer, err = ssh.ParsePrivateKeyWithPassphrase(privateKey, []byte(options.PrivateKeyPassphrase))
  79. }
  80. if err != nil {
  81. return nil, E.Cause(err, "parse private key")
  82. }
  83. outbound.authMethod = append(outbound.authMethod, ssh.PublicKeys(signer))
  84. }
  85. return outbound, nil
  86. }
  87. func randomVersion() string {
  88. version := "SSH-2.0-OpenSSH_"
  89. if rand.Intn(2) == 0 {
  90. version += "7." + strconv.Itoa(rand.Intn(10))
  91. } else {
  92. version += "8." + strconv.Itoa(rand.Intn(9))
  93. }
  94. return version
  95. }
  96. func (s *SSH) connect() (*ssh.Client, error) {
  97. if s.client != nil {
  98. return s.client, nil
  99. }
  100. s.clientAccess.Lock()
  101. defer s.clientAccess.Unlock()
  102. if s.client != nil {
  103. return s.client, nil
  104. }
  105. conn, err := s.dialer.DialContext(s.ctx, N.NetworkTCP, s.serverAddr)
  106. if err != nil {
  107. return nil, err
  108. }
  109. config := &ssh.ClientConfig{
  110. User: s.user,
  111. Auth: s.authMethod,
  112. ClientVersion: s.clientVersion,
  113. HostKeyAlgorithms: s.hostKeyAlgorithms,
  114. }
  115. clientConn, chans, reqs, err := ssh.NewClientConn(conn, s.serverAddr.Addr.String(), config)
  116. if err != nil {
  117. conn.Close()
  118. return nil, E.Cause(err, "connect to ssh server")
  119. }
  120. client := ssh.NewClient(clientConn, chans, reqs)
  121. s.clientConn = conn
  122. s.client = client
  123. go func() {
  124. client.Wait()
  125. conn.Close()
  126. s.clientAccess.Lock()
  127. s.client = nil
  128. s.clientConn = nil
  129. s.clientAccess.Unlock()
  130. }()
  131. return client, nil
  132. }
  133. func (s *SSH) Close() error {
  134. return common.Close(s.clientConn)
  135. }
  136. func (s *SSH) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
  137. client, err := s.connect()
  138. if err != nil {
  139. return nil, err
  140. }
  141. return client.Dial(network, destination.String())
  142. }
  143. func (s *SSH) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
  144. return nil, os.ErrInvalid
  145. }
  146. func (s *SSH) NewConnection(ctx context.Context, conn net.Conn, metadata adapter.InboundContext) error {
  147. return NewConnection(ctx, s, conn, metadata)
  148. }
  149. func (s *SSH) NewPacketConnection(ctx context.Context, conn N.PacketConn, metadata adapter.InboundContext) error {
  150. return os.ErrInvalid
  151. }