Add socks5 proxy

This commit is contained in:
Zoltan Papp
2023-12-13 16:58:31 +01:00
parent cec4232860
commit 9c6c944e46
5 changed files with 105 additions and 11 deletions

43
iface/uspproxy/proxy.go Normal file
View File

@@ -0,0 +1,43 @@
package uspproxy
import (
"context"
"net"
"github.com/armon/go-socks5"
log "github.com/sirupsen/logrus"
)
type Dialer interface {
Dial(ctx context.Context, network, addr string) (net.Conn, error)
}
// Proxy todo close server
type Proxy struct {
server *socks5.Server
}
func NewSocks5(dialer Dialer) (*Proxy, error) {
conf := &socks5.Config{
Dial: dialer.Dial,
}
server, err := socks5.New(conf)
if err != nil {
log.Debugf("failed to init socks5 proxy: %s", err)
return nil, err
}
return &Proxy{
server: server,
}, nil
}
func (s *Proxy) ListenAndServe(addr string) error {
go func() {
err := s.server.ListenAndServe("tcp", addr)
if err != nil {
log.Debugf("failed to start socks5 proxy: %s", err)
}
}()
return nil
}

55
iface/uspproxy/tun.go Normal file
View File

@@ -0,0 +1,55 @@
package uspproxy
import (
"context"
"net"
"net/netip"
log "github.com/sirupsen/logrus"
"golang.zx2c4.com/wireguard/tun"
"golang.zx2c4.com/wireguard/tun/netstack"
)
type NSDialer struct {
net *netstack.Net
}
func (d *NSDialer) Dial(ctx context.Context, network, addr string) (net.Conn, error) {
conn, err := d.net.Dial(network, addr)
if err != nil {
log.Debugf("failed to deal connection: %s", err)
}
return conn, err
}
type NetStackTun struct {
address string
proxy *Proxy
}
func NewNetStackTun(address string) *NetStackTun {
return &NetStackTun{
address: address,
}
}
func (t *NetStackTun) Create() (tun.Device, error) {
nsTunDev, tunNet, err := netstack.CreateNetTUN(
[]netip.Addr{netip.MustParseAddr(t.address)},
[]netip.Addr{netip.MustParseAddr("8.8.8.8")},
1420)
if err != nil {
return nil, err
}
dialer := &NSDialer{tunNet}
t.proxy, err = NewSocks5(dialer)
if err != nil {
// close nsTunDev
return nil, err
}
err = t.proxy.ListenAndServe("127.0.0.1:1234")
return nsTunDev, nil
}