Search code examples
gosocks5

socks5 proxy using go


I wanted to know if it is possible to listen to a local port ex: 1080 socks5, and all connections on that port be made a proxy to use an external host:port socks5

func main() {
    l, err := net.Listen("tcp", "127.0.0.1:1080")
    if err != nil {
        fmt.Print(err)
    }
    defer l.Close()

    for {
        conn, err := l.Accept()
        if err != nil {
            fmt.Print(err)
        }

        go handle(conn)
    }
}

func handle(conn net.Conn) {
    defer conn.Close()

    dialect, err := proxy.SOCKS5("tcp", "externalhost:externalport", nil, proxy.Direct)

    newConn, err := dialect.Dial("tcp", "targethost:targetport")
    if err != nil {
        log.Printf("Connection error: %s", err.Error())
    }

    go func() {
        _, err = io.Copy(newConn, conn)
        if err != nil {
            log.Printf("Connection error: %s", err.Error())
        }
    }()

    _, err = io.Copy(conn, newConn)
    if err != nil {
        log.Printf("Connection error: %s", err.Error())
    }
}
func handle(conn net.Conn) {
    defer conn.Close()
}

I would need to get the destination addres and validate if the connection is socks5 and then perform the proxy with the external ip and pass it in the dialect.dial


Solution

  • It sounds like you want this:

    1. A tool that listens on your local machine using TCP at a particular port
    2. You can make socks5-protocol requests to that port, and it should forward these requests all to one other socks5 server on another remote machine.
    3. That socks5 server is responsible for making the connections to the targets in the socks5-protocol requests

    In that case, you only need a basic TCP proxy. Your tool doesn't need to look inside the socks5 request, and it doesn't need proxy.SOCKS5 to connect to the remote machine. You just want all connections to your local endpoint to be forwarded to your remote endpoint.

    Your current code would largely work, exception you should just use net.Dial (instead of dialect.Dial) to connect to "externalhost:externalport", and you don't need to create the proxy.SOCKS5 dialer.