eycorsican / go-tun2socks

A tun2socks implementation written in Go.
MIT License
1.3k stars 432 forks source link

Where to encrypt TCP data? #96

Closed JimJayLee closed 4 years ago

JimJayLee commented 4 years ago
func (conn *tcpConn) Receive(data []byte) error {
    if err := conn.receiveCheck(); err != nil {
        return err
    }
    log("(conn *tcpConn) Receive data before encode ", data)
    // encode
    data = encode(data)
    n, err := conn.sndPipeWriter.Write(data)
    if err != nil {
        return NewLWIPError(LWIP_ERR_CLSD)
    }
    C.tcp_recved(conn.pcb, C.u16_t(n))
    return NewLWIPError(LWIP_ERR_OK)
}

After a successful proxy connection, I encrypted the data in Receive. As the comment indicates, the data is about to send to server from TUN.

// Receive will be called when data arrives from TUN.

func (conn *tcpConn) Read(data []byte) (int, error) {
    conn.Lock()
    if conn.state == tcpReceiveClosed {
        conn.Unlock()
        return 0, io.EOF
    }
    if conn.state >= tcpClosing {
        conn.Unlock()
        return 0, io.ErrClosedPipe
    }
    conn.Unlock()

    // Handler should get EOF.
    n, err := conn.sndPipeReader.Read(data)
    log("(conn *tcpConn) Read data ", data[:n])
    if err == io.ErrClosedPipe {
        err = io.EOF
    }
    return n, err
}

I notice that the Read would be invoked after the Receive, and the data read from conn.sndPipeReader is encrypted for sure.

As for the Decryption part, I put it in the Write for it receives data from Internet.

// Write writes data to TUN. Write(data []byte) (int, error)

func (conn *tcpConn) Write(data []byte) (int, error) {
    totalWritten := 0

    conn.canWrite.L.Lock()
    defer conn.canWrite.L.Unlock()

    // decode
    data = decode(data)
    log("(conn *tcpConn) Write decodedData ", data)
    for len(data) > 0 {
        // codes remain unchanged
    }

    return totalWritten, nil
}

It seems not working. PLEASE HELP. REMOVE THE CODES FOR ENCRYPTION, EVERYTHING WORKS.