sing-box/protocol/ssh/outbound.go

200 lines
5.2 KiB
Go
Raw Normal View History

2024-11-02 00:39:02 +08:00
package ssh
2022-08-21 19:36:08 +08:00
import (
2023-02-08 16:20:48 +08:00
"bytes"
2022-08-21 19:36:08 +08:00
"context"
2023-02-08 16:20:48 +08:00
"encoding/base64"
2022-08-21 19:36:08 +08:00
"math/rand"
"net"
"os"
"strconv"
2023-09-19 19:59:07 +08:00
"strings"
2022-08-21 19:36:08 +08:00
"sync"
"github.com/sagernet/sing-box/adapter"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing-box/adapter/outbound"
2022-08-21 19:36:08 +08:00
"github.com/sagernet/sing-box/common/dialer"
C "github.com/sagernet/sing-box/constant"
"github.com/sagernet/sing-box/log"
"github.com/sagernet/sing-box/option"
"github.com/sagernet/sing/common"
E "github.com/sagernet/sing/common/exceptions"
2024-11-02 00:39:02 +08:00
"github.com/sagernet/sing/common/logger"
2022-08-21 19:36:08 +08:00
M "github.com/sagernet/sing/common/metadata"
N "github.com/sagernet/sing/common/network"
"golang.org/x/crypto/ssh"
)
2024-11-02 00:39:02 +08:00
func RegisterOutbound(registry *outbound.Registry) {
outbound.Register[option.SSHOutboundOptions](registry, C.TypeSSH, NewOutbound)
}
2022-08-21 19:36:08 +08:00
2024-11-02 00:39:02 +08:00
var _ adapter.InterfaceUpdateListener = (*Outbound)(nil)
type Outbound struct {
outbound.Adapter
2022-08-21 19:36:08 +08:00
ctx context.Context
2024-11-02 00:39:02 +08:00
logger logger.ContextLogger
2022-08-21 19:36:08 +08:00
dialer N.Dialer
serverAddr M.Socksaddr
user string
2023-02-08 16:20:48 +08:00
hostKey []ssh.PublicKey
2022-08-21 19:36:08 +08:00
hostKeyAlgorithms []string
clientVersion string
authMethod []ssh.AuthMethod
clientAccess sync.Mutex
clientConn net.Conn
client *ssh.Client
}
2024-11-02 00:39:02 +08:00
func NewOutbound(ctx context.Context, router adapter.Router, logger log.ContextLogger, tag string, options option.SSHOutboundOptions) (adapter.Outbound, error) {
outboundDialer, err := dialer.New(ctx, options.DialerOptions)
2023-08-08 16:14:03 +08:00
if err != nil {
return nil, err
}
2024-11-02 00:39:02 +08:00
outbound := &Outbound{
2024-11-21 18:10:41 +08:00
Adapter: outbound.NewAdapterWithDialerOptions(C.TypeSSH, tag, []string{N.NetworkTCP}, options.DialerOptions),
2022-08-21 19:36:08 +08:00
ctx: ctx,
2024-11-02 00:39:02 +08:00
logger: logger,
2023-08-08 16:14:03 +08:00
dialer: outboundDialer,
2022-08-21 19:36:08 +08:00
serverAddr: options.ServerOptions.Build(),
user: options.User,
hostKeyAlgorithms: options.HostKeyAlgorithms,
clientVersion: options.ClientVersion,
}
if outbound.serverAddr.Port == 0 {
outbound.serverAddr.Port = 22
}
if outbound.user == "" {
outbound.user = "root"
}
if outbound.clientVersion == "" {
outbound.clientVersion = randomVersion()
}
if options.Password != "" {
outbound.authMethod = append(outbound.authMethod, ssh.Password(options.Password))
}
2023-09-19 19:59:07 +08:00
if len(options.PrivateKey) > 0 || options.PrivateKeyPath != "" {
2022-08-21 19:36:08 +08:00
var privateKey []byte
2023-09-19 19:59:07 +08:00
if len(options.PrivateKey) > 0 {
privateKey = []byte(strings.Join(options.PrivateKey, "\n"))
2022-08-21 19:36:08 +08:00
} else {
var err error
privateKey, err = os.ReadFile(os.ExpandEnv(options.PrivateKeyPath))
if err != nil {
return nil, E.Cause(err, "read private key")
}
}
var signer ssh.Signer
var err error
if options.PrivateKeyPassphrase == "" {
signer, err = ssh.ParsePrivateKey(privateKey)
} else {
signer, err = ssh.ParsePrivateKeyWithPassphrase(privateKey, []byte(options.PrivateKeyPassphrase))
}
if err != nil {
return nil, E.Cause(err, "parse private key")
}
outbound.authMethod = append(outbound.authMethod, ssh.PublicKeys(signer))
}
2023-02-08 16:20:48 +08:00
if len(options.HostKey) > 0 {
for _, hostKey := range options.HostKey {
key, _, _, _, err := ssh.ParseAuthorizedKey([]byte(hostKey))
if err != nil {
return nil, E.New("parse host key ", key)
}
outbound.hostKey = append(outbound.hostKey, key)
}
}
2022-08-21 19:36:08 +08:00
return outbound, nil
}
func randomVersion() string {
version := "SSH-2.0-OpenSSH_"
if rand.Intn(2) == 0 {
version += "7." + strconv.Itoa(rand.Intn(10))
} else {
version += "8." + strconv.Itoa(rand.Intn(9))
}
return version
}
2024-11-02 00:39:02 +08:00
func (s *Outbound) connect() (*ssh.Client, error) {
2022-08-21 19:36:08 +08:00
if s.client != nil {
return s.client, nil
}
s.clientAccess.Lock()
defer s.clientAccess.Unlock()
if s.client != nil {
return s.client, nil
}
conn, err := s.dialer.DialContext(s.ctx, N.NetworkTCP, s.serverAddr)
if err != nil {
return nil, err
}
config := &ssh.ClientConfig{
User: s.user,
Auth: s.authMethod,
ClientVersion: s.clientVersion,
HostKeyAlgorithms: s.hostKeyAlgorithms,
2022-10-09 20:43:01 +08:00
HostKeyCallback: func(hostname string, remote net.Addr, key ssh.PublicKey) error {
2023-02-08 16:20:48 +08:00
if len(s.hostKey) == 0 {
return nil
}
serverKey := key.Marshal()
for _, hostKey := range s.hostKey {
if bytes.Equal(serverKey, hostKey.Marshal()) {
return nil
}
}
return E.New("host key mismatch, server send ", key.Type(), " ", base64.StdEncoding.EncodeToString(serverKey))
2022-10-09 20:43:01 +08:00
},
2022-08-21 19:36:08 +08:00
}
clientConn, chans, reqs, err := ssh.NewClientConn(conn, s.serverAddr.Addr.String(), config)
if err != nil {
conn.Close()
return nil, E.Cause(err, "connect to ssh server")
}
client := ssh.NewClient(clientConn, chans, reqs)
s.clientConn = conn
s.client = client
go func() {
client.Wait()
conn.Close()
s.clientAccess.Lock()
s.client = nil
s.clientConn = nil
s.clientAccess.Unlock()
}()
return client, nil
}
2024-11-02 00:39:02 +08:00
func (s *Outbound) InterfaceUpdated() {
2022-11-06 10:36:19 +08:00
common.Close(s.clientConn)
2023-07-23 14:42:19 +08:00
return
2022-11-06 10:36:19 +08:00
}
2024-11-02 00:39:02 +08:00
func (s *Outbound) Close() error {
2022-08-21 19:36:08 +08:00
return common.Close(s.clientConn)
}
2024-11-02 00:39:02 +08:00
func (s *Outbound) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
2022-08-21 19:36:08 +08:00
client, err := s.connect()
if err != nil {
return nil, err
}
return client.Dial(network, destination.String())
}
2024-11-02 00:39:02 +08:00
func (s *Outbound) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
2022-08-21 19:36:08 +08:00
return nil, os.ErrInvalid
}