-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
645 lines (530 loc) · 17.3 KB
/
main.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
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
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
// Copyright 2022 Namecoin Developers.
// This file is part of heteronculous-horklump.
//
// heteronculous-horklump is free software: you can redistribute it and/or
// modify it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// heteronculous-horklump is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with heteronculous-horklump. If not, see
// <https://www.gnu.org/licenses/>.
package main
/*
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdlib.h>
#include <string.h>
*/
import "C"
import (
"bufio"
"bytes"
"crypto/rand"
"encoding/binary"
"encoding/hex"
"errors"
"fmt"
go_log "log"
"math"
"net"
"net/http"
"net/url"
"os"
"os/exec"
"runtime"
"strconv"
"strings"
"sync"
"syscall"
"time"
"unsafe"
"github.com/hlandau/dexlogconfig" //nolint:depguard // Required for logging configuration
"github.com/hlandau/xlog" //nolint:depguard // Required for logging
"github.com/oraoto/go-pidfd" //nolint:depguard // Required for pidfd operations
"github.com/robertmin1/socks5/v4" //nolint:depguard // Required for SOCKS5 proxy operations
"github.com/u-root/u-root/pkg/strace" //nolint:depguard // Required for system call tracing
"golang.org/x/sys/unix"
easyconfig "gopkg.in/hlandau/easyconfig.v1"
)
var (
log, _ = xlog.New("horklump")
UDPProtolNum byte = 0x11
nullByte = "\x00"
)
var authData []struct {
username string
password string
}
var exitAddr sync.Map
type HTTPDialer struct {
Host string
Username string
Password string
}
// Config is a struct to store the program's configuration values.
type Config struct {
Program string `usage:"Program Name"`
SocksTCP string `default:"127.0.0.1:9050"`
Args []string `usage:"Program Arguments"`
KillProg bool `default:"false" usage:"Kill the Program in case of a Proxy Leak (bool)"`
LogLeaks bool `default:"false" usage:"Allow Proxy Leaks but Log any that Occur (bool)"`
EnvVar bool `default:"true" usage:"Use the Environment Vars TOR_SOCKS_HOST and TOR_SOCKS_PORT (bool)"` //nolint:lll
Redirect string `default:"socks5" usage:"Incase of leak redirect to the desired proxy(socks5,http,trans)"` //nolint:lll
Proxyuser string `default:"" usage:"Proxy username in case of proxy redirection"`
Proxypass string `default:"" usage:"Proxy password in case of proxy redirection"`
OneCircuit bool `default:"false" usage:"Disable random SOCKS behavior"`
WhitelistLoopback bool `default:"false" usage:"Whitelist outgoing IP connections to loopback addresses (e.g. 127.0.0.1)"` //nolint:lll
}
// FullAddress is the network address and port
type FullAddress struct {
// Addr is the network address.
Addr string
// IP is the network address as an IP.
//
// This may not be used by all endpoint types.
IP net.IP
// Family is the address family.
Family uint16
// Port is the transport port.
//
// This may not be used by all endpoint types.
Port uint16
}
func main() {
// Create a Config and initialize it with default values.
cfg := Config{}
config := easyconfig.Configurator{
ProgramName: "horklump",
}
config.ParseFatal(&cfg)
dexlogconfig.Init()
// initialize authData
initializeAuthData()
// Create a new command struct for the specific program and arguments
program := exec.Command(cfg.Program, cfg.Args...)
program.Stdin, program.Stdout, program.Stderr = os.Stdin, os.Stdout, os.Stderr
if cfg.EnvVar {
cfg.SocksTCP = SetEnv(cfg)
}
if cfg.Proxyuser == "" || cfg.Proxypass == "" {
username, err := GenerateRandomCredentials()
if err != nil {
panic(err)
}
password, err := GenerateRandomCredentials()
if err != nil {
panic(err)
}
cfg.Proxyuser = username
cfg.Proxypass = password
}
// Start the program with tracing and handle the CONNECT system call events.
if err := strace.Trace(program, func(t strace.Task, record *strace.TraceRecord) error {
if record.Event == strace.SyscallEnter && record.Syscall.Sysno == unix.SYS_CONNECT {
if err := HandleConnect(t, record, program, cfg); err != nil {
return err
}
} else if record.Event == strace.SyscallExit && record.Syscall.Sysno == unix.SYS_CONNECT {
_, ok := exitAddr.Load(record.PID)
if ok {
if err := Socksify(record.Syscall.Args, record, t, cfg); err != nil {
return err
}
}
}
return nil
}); err != nil {
panic(err)
}
}
func IsIPAddressAllowed(address FullAddress, cfg Config) bool {
if cfg.SocksTCP == address.String() {
return true
}
if cfg.WhitelistLoopback && address.IP.IsLoopback() {
return true
}
return false
}
func IsAddressAllowed(address FullAddress, cfg Config) bool {
switch address.Family {
case unix.AF_UNIX:
return true
case unix.AF_INET:
return IsIPAddressAllowed(address, cfg)
case unix.AF_INET6:
return IsIPAddressAllowed(address, cfg)
default:
return false
}
}
func HandleConnect(task strace.Task, record *strace.TraceRecord, program *exec.Cmd, cfg Config) error {
// Parse the IP and Port.
address, err := ParseAddress(task, record.Syscall.Args)
if err != nil {
return fmt.Errorf("failed to parse address: %w", err)
}
IPPort := address.String()
if IsAddressAllowed(address, cfg) { //nolint
log.Infof("Connecting to %v", IPPort)
} else {
// Dump Stack Trace and Process Information
if err := DumpStackTrace(record.PID); err != nil {
return err
}
if cfg.LogLeaks {
log.Warnf("Proxy Leak detected, but allowed : %v", IPPort)
return nil
}
if cfg.KillProg {
KillApp(program, IPPort)
return nil
}
if cfg.Redirect != "" {
exitAddr.Store(record.PID, IPPort)
log.Infof("Redirecting connections from %v to %v", IPPort, cfg.SocksTCP)
err := RedirectConns(record.Syscall.Args, cfg, record)
if err != nil {
return fmt.Errorf("failed to redirect connections: %w", err)
}
return nil
// TODO: handle invalid flag
// Incase trans proxy will require a different implementation a switch will be used.
}
err := BlockSyscall(record.PID, IPPort)
if err != nil {
return fmt.Errorf("failed to block syscall for PID %d and IPPort %s: %w", record.PID, IPPort, err)
}
}
return nil
}
// ParseAddress reads an sockaddr struct from the given address and converts it
// to the FullAddress format. It supports AF_UNIX, AF_INET and AF_INET6
// addresses
func ParseAddress(t strace.Task, args strace.SyscallArguments) (FullAddress, error) { //nolint
addr := args[1].Pointer()
addrlen := args[2].Uint()
socketaddr, err := strace.CaptureAddress(t, addr, addrlen)
if err != nil {
return FullAddress{}, fmt.Errorf("failed to parse socket address: %w", err)
}
famBuf := bytes.NewBuffer(socketaddr[:2])
var fam uint16
if err := binary.Read(famBuf, binary.NativeEndian, &fam); err != nil {
return FullAddress{}, fmt.Errorf("error while reading binary data: %w", err)
}
// Get the rest of the fields based on the address family.
switch fam {
case unix.AF_UNIX:
path := socketaddr[2:]
if len(path) > unix.PathMax {
return FullAddress{}, unix.EINVAL
}
// Drop the terminating NUL (if one exists) and everything after
// it for filesystem (non-abstract) addresses.
if len(path) > 0 && path[0] != 0 {
if n := bytes.IndexByte(path[1:], 0); n >= 0 {
path = path[:n+1]
}
}
return FullAddress{
Family: fam,
Addr: string(path),
}, nil
case unix.AF_INET:
var inet4Addr unix.RawSockaddrInet4
famBuf = bytes.NewBuffer(socketaddr)
if err := binary.Read(famBuf, binary.BigEndian, &inet4Addr); err != nil {
return FullAddress{}, unix.EFAULT
}
ip := net.IP(inet4Addr.Addr[:])
out := FullAddress{
Family: fam,
Addr: ip.String(),
IP: ip,
Port: inet4Addr.Port,
}
if out.Addr == "\x00\x00\x00\x00" {
out.Addr = ""
}
return out, nil
case unix.AF_INET6:
var inet6Addr unix.RawSockaddrInet6
famBuf = bytes.NewBuffer(socketaddr)
if err := binary.Read(famBuf, binary.BigEndian, &inet6Addr); err != nil {
return FullAddress{}, unix.EFAULT
}
ip := net.IP(inet6Addr.Addr[:])
out := FullAddress{
Family: fam,
Addr: ip.String(),
IP: ip,
Port: inet6Addr.Port,
}
// if isLinkLocal(out.Addr) {
// out.NIC = NICID(a.Scope_id)
//}
if out.Addr == strings.Repeat(nullByte, net.IPv6len) {
out.Addr = ""
}
return out, nil
default:
return FullAddress{
Family: fam,
}, nil
}
}
// Kill the application in case of a proxy leak.
func KillApp(program *exec.Cmd, iPPort string) {
err := program.Process.Signal(syscall.SIGKILL)
if err != nil {
log.Errorf("Failed to kill the application: %v", err)
panic(err)
}
log.Warnf("Proxy Leak Detected : %v. Killing the Application.", iPPort)
}
// Setting environment variables.
func SetEnv(cfg Config) string {
host, port := os.Getenv("TOR_SOCKS_HOST"), os.Getenv("TOR_SOCKS_PORT")
TCPhost, TCPport, _ := net.SplitHostPort(cfg.SocksTCP)
// Handling some edge cases, incase only one Environment variable is provided.
switch {
case (host == "" && port != ""):
return TCPhost + ":" + port
case (host != "" && port == ""):
return host + ":" + TCPport
case (host != "" && port != ""):
return host + ":" + port
default:
return cfg.SocksTCP
}
}
// Blocking a syscall by changing the syscall number, converting it to a syscall that doesn't exist.
func BlockSyscall(pid int, ipport string) error {
// Trace the syscall
if err := syscall.PtraceSyscall(pid, 0); err != nil {
return fmt.Errorf("error while tracing syscall for process with PID %d: %w", pid, err)
}
if err := unix.Waitid(unix.P_PID, pid, nil, unix.WEXITED, nil); err != nil {
return fmt.Errorf("error while waiting for process with PID %d: %w", pid, err)
}
// Struct to store the current register values from unix.PtraceGetRegs
regs := &unix.PtraceRegs{}
if err := unix.PtraceGetRegs(pid, regs); err != nil {
return fmt.Errorf("error while getting register values from process with PID %d: %w", pid, err)
}
// Set to invalid syscall and set the new register values
regs.Rax = math.MaxUint64
if err := unix.PtraceSetRegs(pid, regs); err != nil {
return fmt.Errorf("error while setting register values for process with PID %d: %w", pid, err)
}
if err := syscall.PtraceSyscall(pid, 0); err != nil {
return fmt.Errorf("error while tracing syscall for process with PID %d: %w", pid, err)
}
if err := unix.Waitid(unix.P_PID, pid, nil, unix.WEXITED, nil); err != nil {
return fmt.Errorf("error while waiting for process with PID %d: %w", pid, err)
}
log.Warnf("Blocking -> %v", ipport)
return nil
}
func RedirectConns(args strace.SyscallArguments, cfg Config, record *strace.TraceRecord) error {
// Extrating the address that holds the IP/Port information
addr := args[1].Pointer()
addrlen := args[2].Uint()
host, port, _ := net.SplitHostPort(cfg.SocksTCP)
parsedhost := net.ParseIP(host)
pokeData := make([]byte, addrlen)
// Support for UDP will be implemented
// Switch is used to differentiate if the proxy is IPv4/IPv5/UDP/Invalid Proxy
switch {
// If ip is not IPv4 address, To4 returns nil
case parsedhost.To4() != nil:
var addrStruct C.struct_sockaddr_in
addrStruct.sin_family = C.AF_INET
intPort, _ := strconv.Atoi(port)
addrStruct.sin_port = C.htons(C.in_port_t(intPort))
ip := C.CString(host)
defer C.free(unsafe.Pointer(ip)) //nolint
addrStruct.sin_addr.s_addr = C.inet_addr(ip)
pokeData = C.GoBytes(unsafe.Pointer(&addrStruct), C.sizeof_struct_sockaddr_in) //nolint
// If ip is not IPv6 address, To16 returns nil
case parsedhost.To16() != nil:
hostData := parsedhost.To16()
var addrStruct C.struct_sockaddr_in6
addrStruct.sin6_family = C.AF_INET6
intPort, _ := strconv.Atoi(port)
addrStruct.sin6_port = C.htons(C.in_port_t(intPort))
C.memcpy(unsafe.Pointer(&addrStruct.sin6_addr), unsafe.Pointer(&hostData[0]), C.size_t(len(hostData))) //nolint
pokeData = C.GoBytes(unsafe.Pointer(&addrStruct), C.int(unsafe.Sizeof(addrStruct))) //nolint
case parsedhost.To4()[0] == UDPProtolNum:
log.Error("Support for UDP will be implemented")
default:
return errors.New("invalid ip address")
}
// Poking our proxy IP/Port to the address containing the original address
if _, err := unix.PtracePokeData(record.PID, uintptr(addr), pokeData); err != nil {
return fmt.Errorf("error poking data into process with PID %d: %w", record.PID, err)
}
log.Infof("Connecting to %v", cfg.SocksTCP)
return nil
}
func Socksify(args strace.SyscallArguments, record *strace.TraceRecord, t strace.Task, cfg Config) error {
username, password := cfg.Proxyuser, cfg.Proxypass
if !cfg.OneCircuit {
idxBytes := make([]byte, 1) // generate random index
if _, err := rand.Read(idxBytes); err != nil {
panic(err)
}
idx := int(idxBytes[0]) % len(authData) // get random auth data
username = authData[idx].username
password = authData[idx].password
}
addr, _ := exitAddr.LoadAndDelete(record.PID)
IPPort := fmt.Sprintf("%v", addr)
fd := record.Syscall.Args[0].Uint()
p, err := pidfd.Open(record.PID, 0)
if err != nil {
return fmt.Errorf("error opening PID file descriptor: %w", err)
}
listenfd, err := p.GetFd(int(fd), 0)
if err != nil {
return fmt.Errorf("error getting listen file descriptor: %w", err)
}
file := os.NewFile(uintptr(listenfd), "")
conn, err := net.FileConn(file)
if err != nil {
return fmt.Errorf("error creating connection from file: %w", err)
}
switch cfg.Redirect {
case "socks5":
const timeout = 10
cl, err := socks5.NewClient(IPPort, username, password, timeout, timeout)
if err != nil {
return err
}
_, err = cl.Dial("tcp", IPPort, conn)
if err != nil {
return fmt.Errorf("an error occurred while running dial : %w", err)
}
case "http":
cl, err := NewHTTPClient(cfg.SocksTCP, username, password)
if err != nil {
return err
}
_, err = cl.Dial("tcp", IPPort, conn)
if err != nil {
return err
}
}
return nil // Support more proxies
}
func DumpStackTrace(pid int) error {
// Create or open the log file in append mode
logFile, err := os.OpenFile("stack_trace.log", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) //nolint
if err != nil {
return err
}
defer logFile.Close()
// Set the log output to the log file
go_log.SetOutput(logFile)
commPath := fmt.Sprintf("/proc/%d/cmdline", pid)
commBytes, err := os.ReadFile(commPath)
if err != nil {
return err
}
// Split the contents by null byte to separate command and arguments
cmdline := strings.Split(string(commBytes), "\x00")
// Add a separator with date and time for the new instance of the program
separator := fmt.Sprintf("----------- New Instance: %s ------------", time.Now().Format("2006-01-02 15:04:05"))
go_log.Println(separator)
// Add the PID and Process Name and Args.
go_log.Printf("PID :%v", pid)
go_log.Printf("Program and Arguments:%v\n", cmdline)
// Get the stack trace
const stackSize = 8192
stack := make([]byte, stackSize) // 8192 bytes
length := runtime.Stack(stack, true)
// Write the stack trace to the log file
go_log.Println(string(stack[:length]))
return nil
}
func (i FullAddress) String() string {
switch {
case i.IP == nil:
return i.Addr
case i.IP.To4() != nil:
return fmt.Sprintf("%s:%d", i.Addr, i.Port)
case i.IP.To16() != nil:
return fmt.Sprintf("[%s]:%d", i.Addr, i.Port)
default:
return i.Addr
}
}
func GenerateRandomCredentials() (string, error) {
const credentialLength = 48
bytes := make([]byte, credentialLength)
if _, err := rand.Read(bytes); err != nil {
return "", err
}
return hex.EncodeToString(bytes), nil
}
func initializeAuthData() {
for range [10]int{} {
username, _ := GenerateRandomCredentials()
password, _ := GenerateRandomCredentials()
authData = append(authData, struct {
username string
password string
}{username, password})
}
}
func NewHTTPClient(addr, username, password string) (*HTTPDialer, error) {
httpDialer := &HTTPDialer{
Host: addr,
Username: username,
Password: password,
}
return httpDialer, nil
}
// Dial establishes a connection to the provided address through an HTTP proxy.
// It sends an HTTP CONNECT request to the proxy server and returns the established
// connection if successful. If an error occurs, the connection is closed and the error is returned.
func (h *HTTPDialer) Dial(_, addr string, httpconn net.Conn) (net.Conn, error) {
conn := httpconn
reqURL, err := url.Parse("http://" + addr)
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to parse URL: %w", err)
}
req := &http.Request{
Method: http.MethodConnect,
URL: reqURL,
Host: addr,
Header: make(http.Header),
}
// Set authentication details.
req.SetBasicAuth(h.Username, h.Password)
err = req.Write(conn)
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to write request: %w", err)
}
r := bufio.NewReader(conn)
resp, err := http.ReadResponse(r, req)
if err != nil {
conn.Close()
return nil, fmt.Errorf("failed to read response: %w", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
conn.Close()
return nil, fmt.Errorf("connect proxy error: %v", strings.SplitN(resp.Status, " ", 2)[1]) //nolint
}
return conn, nil
}