-
Notifications
You must be signed in to change notification settings - Fork 29
/
Copy pathrelay.go
167 lines (139 loc) · 3.61 KB
/
relay.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
// Relay is a package that provides functionality for relaying network traffic.
package main
import (
"bufio"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/netip"
"os"
"os/signal"
"strings"
"syscall"
"github.com/peterbourgon/ff/v4"
"github.com/peterbourgon/ff/v4/ffhelp"
)
const BUFFER_SIZE = 2048
func run(ctx context.Context, l *slog.Logger, bind string) error {
listener, err := net.Listen("tcp", bind)
if err != nil {
return err
}
defer listener.Close()
for {
select {
case <-ctx.Done():
return nil
default:
conn, err := listener.Accept()
if err != nil {
l.Error("failed to accept connection", "error", err.Error())
continue
}
src := netip.MustParseAddrPort(conn.RemoteAddr().String())
// Check if srcIP is in the whitelist
if !connFilter.isSourceAllowed(src.Addr()) {
l.Debug("blocked connection", "address", src)
conn.Close()
continue
}
go handleConnection(l, conn)
}
}
}
func handleConnection(l *slog.Logger, lConn net.Conn) {
reader := bufio.NewReader(lConn)
header, _ := reader.ReadBytes(byte(13))
if len(header) < 1 {
lConn.Close()
return
}
inputHeader := strings.Split(string(header[:len(header)-1]), "@")
if len(inputHeader) < 2 {
lConn.Close()
return
}
network := "tcp"
if inputHeader[0] == "udp" {
network = "udp"
}
address := strings.Replace(inputHeader[1], "$", ":", -1)
dh, _, err := net.SplitHostPort(address)
if err != nil {
lConn.Close()
return
}
// check if ip is not blocked
blockFlag := false
addr, err := netip.ParseAddr(dh)
if err != nil {
// the host may not be an IP, try to resolve it
ips, err := net.LookupIP(dh)
if err != nil {
lConn.Close()
return
}
// parse the first IP and use it
addr, _ = netip.AddrFromSlice(ips[0])
}
// If the address is invalid or not allowed as a destination, set the block flag.
blockFlag = !addr.IsValid() || !connFilter.isDestinationAllowed(addr)
if blockFlag {
l.Debug("destination host is blocked", "address", address)
lConn.Close()
return
}
switch network {
case "tcp":
rConn, err := net.Dial(network, address)
if err != nil {
l.Error("failed to dial", "protocol", network, "address", address, "error", err.Error())
lConn.Close()
return
}
go handleTCP(lConn, rConn)
case "udp":
go handleUDPOverTCP(l, lConn, address)
}
l.Debug("relaying connection", "protocol", network, "address", address)
}
// Copy reads from src and writes to dst until either EOF is reached on src or
// an error occurs. It returns the number of bytes copied and any error
// encountered. Copy uses a fixed-size buffer to efficiently copy data between
// the source and destination.
func Copy(src io.Reader, dst io.Writer) {
buf := make([]byte, BUFFER_SIZE)
_, err := io.CopyBuffer(dst, src, buf[:cap(buf)])
if err != nil {
fmt.Println(err)
}
}
func main() {
fs := ff.NewFlagSet("bepass-relay")
var (
verbose = fs.Bool('v', "verbose", "enable verbose logging")
bind = fs.String('b', "bind", "0.0.0.0:6666", "bind address")
)
err := ff.Parse(fs, os.Args[1:])
switch {
case errors.Is(err, ff.ErrHelp):
fmt.Fprintf(os.Stderr, "%s\n", ffhelp.Flags(fs))
os.Exit(0)
case err != nil:
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
l := slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelInfo}))
if *verbose {
l = slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: slog.LevelDebug}))
}
ctx, _ := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
if err := run(ctx, l, *bind); err != nil {
fmt.Fprintf(os.Stderr, "error: %v\n", err)
os.Exit(1)
}
<-ctx.Done()
}