-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.go
More file actions
297 lines (230 loc) · 7.99 KB
/
server.go
File metadata and controls
297 lines (230 loc) · 7.99 KB
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
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
//go:build !windows
package main
import (
"flag"
"fmt"
"log"
"net"
"net/netip"
"os"
"os/exec"
"os/signal"
"strings"
"syscall"
"time"
)
func init() {
cmds = append(cmds, ServerSubCommand())
}
type serverCommand struct {
fs *flag.FlagSet
iface string
src string
port int
address string
}
func ServerSubCommand() *serverCommand {
gc := &serverCommand{
fs: flag.NewFlagSet("server", flag.ContinueOnError),
}
gc.fs.StringVar(&gc.address, "address", "", "Manually set external/interface address")
gc.fs.StringVar(&gc.iface, "interface", "", "interface for server listener")
gc.fs.StringVar(&gc.src, "src", "", "Source address for server to listen for client requests")
gc.fs.IntVar(&gc.port, "port", 4344, "The port the egress detector server will listen on")
return gc
}
func (g *serverCommand) Name() string {
return g.fs.Name()
}
func (g *serverCommand) PrintUsage() {
g.fs.Usage()
}
func (g *serverCommand) Init(args []string) error {
err := g.fs.Parse(args)
if err != nil {
return err
}
if g.iface == "" {
return fmt.Errorf("no interface specified, please specify an interface")
}
if g.src == "" {
log.Println("No src address specified, will use 0.0.0.0/0")
g.src = "0.0.0.0/0"
} else {
_, _, err := net.ParseCIDR(g.src)
if err != nil {
log.Fatal("failed to parse -src as a cidr: ", err)
}
}
if g.address != "" {
if net.ParseIP(g.address) == nil {
return fmt.Errorf("could not parse ip address from %s", g.address)
}
} else {
if g.iface == "" {
return fmt.Errorf("no interface or address were specified")
}
ifaces, err := net.Interfaces()
if err != nil {
return fmt.Errorf("unable to get list of interfaces: %w", err)
}
found := false
for _, iface := range ifaces {
if iface.Name == g.iface {
if g.address == "" {
addrs, err := iface.Addrs()
if err != nil {
return fmt.Errorf("no local address for the server was identified")
}
if len(addrs) == 0 {
return fmt.Errorf("no local address for the interface was identified")
}
fmt.Printf("selecting %q address from interface %q (use -address to override)", addrs[0].String(), iface.Name)
g.address = getIp(addrs[0].String())
}
found = true
break
}
}
if !found {
return fmt.Errorf("could not find interface by name of '%s', are you sure that is correct?", g.iface)
}
}
return nil
}
func getIp(addr string) string {
for i := len(addr) - 1; i > 0; i-- {
if addr[i] == ':' || addr[i] == '/' {
return addr[:i]
}
}
return addr
}
func (g *serverCommand) Run() error {
if syscall.Getuid() != 0 {
return fmt.Errorf("the server is not running as the root user, it will not be able to run iptables")
}
iptablesExecutable := "iptables"
if netip.MustParseAddr(g.address).Is6() {
iptablesExecutable = "ip6tables"
}
if _, err := exec.LookPath(iptablesExecutable); err != nil {
return fmt.Errorf("unable to find %q in your $PATH", iptablesExecutable)
}
log.Printf("[*] Inserting %s rule to redirect connections from %s to %s, egressinator port %d/tcp\n", iptablesExecutable, g.address, g.src, g.port)
output, err := exec.Command(iptablesExecutable, "-t", "filter", "-I", "INPUT", "-s", g.src, "-i",
g.iface, "-p", "tcp", "-m", "tcp", "--dport", fmt.Sprintf("%d", g.port), "-j", "ACCEPT").CombinedOutput()
if err != nil {
fmt.Println(string(output))
return fmt.Errorf("unable to add %s rule to allow tcp input to port %d: %w", iptablesExecutable, g.port, err)
}
output, err = exec.Command(iptablesExecutable, "-t", "filter", "-I", "INPUT", "-s", g.src, "-i",
g.iface, "-p", "udp", "-m", "udp", "--dport", fmt.Sprintf("%d", g.port), "-j", "ACCEPT").CombinedOutput()
if err != nil {
fmt.Println(string(output))
return fmt.Errorf("unable to add %s rule to allow udp input to port %d: %w", iptablesExecutable, g.port, err)
}
output, err = exec.Command(iptablesExecutable, "-t", "nat", "-I", "PREROUTING", "-s", g.src, "-i",
g.iface, "-p", "tcp", "--dport", "1:65535", "-j", "DNAT",
"--to-destination", fmt.Sprintf("%s:%d", g.address, g.port)).CombinedOutput()
if err != nil {
fmt.Println(string(output))
return fmt.Errorf("unable to set %s to redirect all tcp connection attempts to egress server: %w", iptablesExecutable, err)
}
output, err = exec.Command(iptablesExecutable, "-t", "nat", "-I", "PREROUTING", "-s", g.src, "-i",
g.iface, "-p", "udp", "--dport", "1:65535", "-j", "DNAT",
"--to-destination", fmt.Sprintf("%s:%d", g.address, g.port)).CombinedOutput()
if err != nil {
fmt.Println(string(output))
return fmt.Errorf("unable to set %s to redirect all udp connection attempts to egress server: %w", iptablesExecutable, err)
}
defer func() {
output, err := exec.Command(iptablesExecutable, "-t", "filter", "-D", "INPUT", "-s", g.src, "-i",
g.iface, "-p", "tcp", "-m", "tcp", "--dport", fmt.Sprintf("%d", g.port), "-j", "ACCEPT").CombinedOutput()
if err != nil {
fmt.Println(string(output))
log.Printf("Unable to delete tcp %s rule to allow input to port %d: %s", iptablesExecutable, g.port, err)
}
err = exec.Command(iptablesExecutable, "-t", "nat", "-D", "PREROUTING", "-s", g.src, "-i",
g.iface, "-p", "tcp", "--dport", "1:65535", "-j", "DNAT",
"--to-destination", fmt.Sprintf("%s:%d", g.address, g.port)).Run()
if err != nil {
log.Fatal("Unable to delete tcp", iptablesExecutable, " rules, you may have to do this yourself.", err)
}
output, err = exec.Command(iptablesExecutable, "-t", "filter", "-D", "INPUT", "-s", g.src, "-i",
g.iface, "-p", "udp", "-m", "udp", "--dport", fmt.Sprintf("%d", g.port), "-j", "ACCEPT").CombinedOutput()
if err != nil {
fmt.Println(string(output))
log.Printf("unable to delete %s udp rule to allow input to port %d: %s", iptablesExecutable, g.port, err)
}
err = exec.Command(iptablesExecutable, "-t", "nat", "-D", "PREROUTING", "-s", g.src, "-i",
g.iface, "-p", "udp", "--dport", "1:65535", "-j", "DNAT",
"--to-destination", fmt.Sprintf("%s:%d", g.address, g.port)).Run()
if err != nil {
log.Fatal("unable to delete udp", iptablesExecutable, " rules, you may have to do this yourself.", err)
}
}()
c := make(chan os.Signal, 1)
connections := make(chan net.Conn)
signal.Notify(c, os.Interrupt)
listener, err := net.Listen("tcp", fmt.Sprintf("%s:%d", g.address, g.port))
if err != nil {
return fmt.Errorf("unable to start tcp listener: %w", err)
}
go acceptConnection(connections, listener)
listener, err = net.Listen("udp", fmt.Sprintf("%s:%d", g.address, g.port))
if err != nil {
return fmt.Errorf("unable to start udp listener: %w", err)
}
go acceptConnection(connections, listener)
for {
select {
case <-c:
log.Println("Got ctrl c, shutting down and removing iptables rules...")
listener.Close()
return nil
case newConn := <-connections:
go func() {
defer newConn.Close()
newConn.SetDeadline(time.Now().Add(10 * time.Second))
log.Printf("[*] Got connection from %s\n", newConn.RemoteAddr().String())
buff := make([]byte, 256)
n, err := newConn.Read(buff)
if err != nil {
return
}
selfReportedPort := strings.Split(string(buff[:n]), ":")
if len(selfReportedPort) == 0 {
log.Println("\t[i] Potentially invalid, client didnt self report port")
return
}
if len(selfReportedPort) != 2 {
log.Printf("\t[i] Potentially invalid, send data, but it wasnt in the correct format '%s'\n", string(buff[:n]))
return
}
if selfReportedPort[0] != "egressor" {
log.Printf("\t[i] Potentially invalid, send data, but it wasnt in the correct format '%s'\n", string(buff[:n]))
return
}
log.Printf("[i] Client said '%s'/tcp was successful\n", selfReportedPort[1])
}()
}
}
}
func acceptConnection(connections chan net.Conn, listener net.Listener) {
for {
conn, err := listener.Accept()
if err != nil {
if os.IsTimeout(err) {
continue
}
if netErr, ok := err.(net.Error); ok && netErr.Temporary() {
continue
}
log.Fatal("error accepting connection: ", err)
}
go func() {
connections <- conn
}()
}
}