-
-
Notifications
You must be signed in to change notification settings - Fork 280
Expand file tree
/
Copy pathProxyBridge.c
More file actions
3292 lines (2812 loc) · 102 KB
/
ProxyBridge.c
File metadata and controls
3292 lines (2812 loc) · 102 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
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
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include <winsock2.h>
#include <windows.h>
#include "ProxyBridge.h"
#include <ws2tcpip.h>
#include <iphlpapi.h>
#include <psapi.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "windivert.h"
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "ws2_32.lib")
#define MAXBUF 0xFFFF
#define LOCAL_PROXY_PORT 34010
#define LOCAL_UDP_RELAY_PORT 34011 // its running UDP port still make sure to not run on same port as TCP, opening same port and tcp and udp cause issue and handling port at relay server response injection
#define MAX_PROCESS_NAME 256
#define VERSION "3.2.0"
#define PID_CACHE_SIZE 1024
#define PID_CACHE_TTL_MS 1000
#define NUM_PACKET_THREADS 4
#define CONNECTION_HASH_SIZE 256
#define SOCKS5_BUFFER_SIZE 1024
#define HTTP_BUFFER_SIZE 1024
#define FILTER_BUFFER_SIZE 512
#define LOG_BUFFER_SIZE 1024
typedef struct PROCESS_RULE {
UINT32 rule_id;
char process_name[MAX_PROCESS_NAME];
char *target_hosts; // Dynamic: IP filter "*", "192.168.*.*", "10.0.0.1;172.16.0.0"
char *target_ports; // Dynamic: Port filter "*", "80", "80;443", "8000-9000"
RuleProtocol protocol; // TCP, UDP, or BOTH
RuleAction action;
BOOL enabled;
struct PROCESS_RULE *next;
} PROCESS_RULE;
#define SOCKS5_VERSION 0x05
#define SOCKS5_CMD_CONNECT 0x01
#define SOCKS5_CMD_UDP_ASSOCIATE 0x03
#define SOCKS5_ATYP_IPV4 0x01
#define SOCKS5_AUTH_NONE 0x00
typedef struct CONNECTION_INFO {
UINT16 src_port;
UINT32 src_ip;
UINT32 orig_dest_ip;
UINT16 orig_dest_port;
BOOL is_tracked;
ULONGLONG last_activity; // GetTickCount64() timestamp for cleanup
struct CONNECTION_INFO *next;
} CONNECTION_INFO;
typedef struct {
SOCKET client_socket;
UINT32 orig_dest_ip;
UINT16 orig_dest_port;
} CONNECTION_CONFIG;
typedef struct {
SOCKET from_socket;
SOCKET to_socket;
} TRANSFER_CONFIG;
// Track logged connections to avoid dupli
typedef struct LOGGED_CONNECTION {
DWORD pid;
UINT32 dest_ip;
UINT16 dest_port;
RuleAction action;
struct LOGGED_CONNECTION *next;
} LOGGED_CONNECTION;
// Impoved slow speed due to PID checking // Added pid cache
typedef struct PID_CACHE_ENTRY {
UINT32 src_ip;
UINT16 src_port;
DWORD pid;
DWORD timestamp;
BOOL is_udp;
struct PID_CACHE_ENTRY *next;
} PID_CACHE_ENTRY;
static CONNECTION_INFO *connection_hash_table[CONNECTION_HASH_SIZE] = {NULL};
static LOGGED_CONNECTION *logged_connections = NULL;
static PROCESS_RULE *rules_list = NULL;
static UINT32 g_next_rule_id = 1;
static HANDLE lock = NULL;
static HANDLE windivert_handle = INVALID_HANDLE_VALUE;
static HANDLE packet_thread[NUM_PACKET_THREADS] = {NULL};
static HANDLE proxy_thread = NULL;
static HANDLE udp_relay_thread = NULL;
static HANDLE cleanup_thread = NULL;
static PID_CACHE_ENTRY *pid_cache[PID_CACHE_SIZE] = {NULL};
static BOOL g_has_active_rules = FALSE;
static SOCKET udp_relay_socket = INVALID_SOCKET;
static SOCKET socks5_udp_socket = INVALID_SOCKET;
static SOCKET socks5_udp_send_socket = INVALID_SOCKET;
static struct sockaddr_in socks5_udp_relay_addr;
static BOOL udp_associate_connected = FALSE;
static DWORD last_udp_connect_attempt = 0;
static BOOL running = FALSE;
static DWORD g_current_process_id = 0;
static BOOL g_traffic_logging_enabled = TRUE;
static char g_proxy_host[256] = ""; // Can be IP address or hostname
static UINT16 g_proxy_port = 0;
static UINT16 g_local_relay_port = LOCAL_PROXY_PORT;
static ProxyType g_proxy_type = PROXY_TYPE_SOCKS5;
static char g_proxy_username[256] = "";
static char g_proxy_password[256] = "";
static BOOL g_dns_via_proxy = TRUE;
static BOOL g_localhost_via_proxy = FALSE; // default disabled for security - most proxy server block localhost for ssrf and also many app might not work if localhost trafic goes to remote server if proxy server is on diffrent machine
static LogCallback g_log_callback = NULL;
static ConnectionCallback g_connection_callback = NULL;
static void log_message(const char *msg, ...)
{
if (g_log_callback == NULL) return;
char buffer[LOG_BUFFER_SIZE];
va_list args;
va_start(args, msg);
vsnprintf(buffer, sizeof(buffer), msg, args);
va_end(args);
g_log_callback(buffer);
}
// Extract filename from full path C:\path\chrome.exe >> chrome.exe
static const char* extract_filename(const char* path)
{
if (!path) return "";
const char* last_backslash = strrchr(path, '\\');
const char* last_slash = strrchr(path, '/');
const char* last_separator = (last_backslash > last_slash) ? last_backslash : last_slash;
return last_separator ? (last_separator + 1) : path;
}
static inline char* skip_whitespace(char *str)
{
while (*str == ' ' || *str == '\t')
str++;
return str;
}
static void format_ip_address(UINT32 ip, char *buffer, size_t size)
{
snprintf(buffer, size, "%d.%d.%d.%d",
(ip >> 0) & 0xFF, (ip >> 8) & 0xFF,
(ip >> 16) & 0xFF, (ip >> 24) & 0xFF);
}
typedef BOOL (*token_match_func)(const char *token, const void *data);
static BOOL parse_token_list(const char *list, const char *delimiters, token_match_func match_func, const void *match_data)
{
if (list == NULL || list[0] == '\0' || strcmp(list, "*") == 0)
return TRUE;
size_t len = strlen(list) + 1;
char *list_copy = (char *)malloc(len);
if (list_copy == NULL)
return FALSE;
strncpy_s(list_copy, len, list, _TRUNCATE);
BOOL matched = FALSE;
char *context = NULL;
char *token = strtok_s(list_copy, delimiters, &context);
while (token != NULL)
{
token = skip_whitespace(token);
if (match_func(token, match_data))
{
matched = TRUE;
break;
}
token = strtok_s(NULL, delimiters, &context);
}
free(list_copy);
return matched;
}
static void configure_tcp_socket(SOCKET sock, int bufsize, DWORD timeout)
{
int nodelay = 1;
setsockopt(sock, IPPROTO_TCP, TCP_NODELAY, (char*)&nodelay, sizeof(nodelay));
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&bufsize, sizeof(bufsize));
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&bufsize, sizeof(bufsize));
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));
}
static void configure_udp_socket(SOCKET sock, int bufsize, DWORD timeout)
{
setsockopt(sock, SOL_SOCKET, SO_RCVBUF, (char*)&bufsize, sizeof(bufsize));
setsockopt(sock, SOL_SOCKET, SO_SNDBUF, (char*)&bufsize, sizeof(bufsize));
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, (char*)&timeout, sizeof(timeout));
setsockopt(sock, SOL_SOCKET, SO_SNDTIMEO, (char*)&timeout, sizeof(timeout));
}
static int send_all(SOCKET sock, const char *buf, int len)
{
int sent = 0;
while (sent < len) {
int n = send(sock, buf + sent, len - sent, 0);
if (n == SOCKET_ERROR) return SOCKET_ERROR;
sent += n;
}
return sent;
}
static UINT32 parse_ipv4(const char *ip);
static UINT32 resolve_hostname(const char *hostname);
static int socks5_connect(SOCKET s, UINT32 dest_ip, UINT16 dest_port);
static int socks5_udp_associate(SOCKET s, struct sockaddr_in *relay_addr);
static DWORD WINAPI udp_relay_server(LPVOID arg);
static BOOL match_ip_pattern(const char *pattern, UINT32 ip);
static BOOL match_port_pattern(const char *pattern, UINT16 port);
static BOOL match_ip_list(const char *ip_list, UINT32 ip);
static BOOL match_port_list(const char *port_list, UINT16 port);
static BOOL match_process_pattern(const char *pattern, const char *process_name);
static BOOL match_process_list(const char *process_list, const char *process_name);
static int http_connect(SOCKET s, UINT32 dest_ip, UINT16 dest_port);
static DWORD WINAPI local_proxy_server(LPVOID arg);
static DWORD WINAPI connection_handler(LPVOID arg);
static DWORD WINAPI transfer_handler(LPVOID arg);
static DWORD WINAPI packet_processor(LPVOID arg);
static DWORD get_process_id_from_connection(UINT32 src_ip, UINT16 src_port);
static DWORD get_process_id_from_udp_connection(UINT32 src_ip, UINT16 src_port);
static BOOL get_process_name_from_pid(DWORD pid, char *name, DWORD name_size);
static RuleAction match_rule(const char *process_name, UINT32 dest_ip, UINT16 dest_port, BOOL is_udp);
static RuleAction check_process_rule(UINT32 src_ip, UINT16 src_port, UINT32 dest_ip, UINT16 dest_port, BOOL is_udp, DWORD *out_pid);
static void add_connection(UINT16 src_port, UINT32 src_ip, UINT32 dest_ip, UINT16 dest_port);
static BOOL get_connection(UINT16 src_port, UINT32 *dest_ip, UINT16 *dest_port);
static BOOL is_connection_tracked(UINT16 src_port);
static void remove_connection(UINT16 src_port);
static void cleanup_stale_connections(void);
static BOOL is_connection_already_logged(DWORD pid, UINT32 dest_ip, UINT16 dest_port, RuleAction action);
static void add_logged_connection(DWORD pid, UINT32 dest_ip, UINT16 dest_port, RuleAction action);
static void clear_logged_connections(void);
static BOOL is_broadcast_or_multicast(UINT32 ip);
static DWORD get_cached_pid(UINT32 src_ip, UINT16 src_port, BOOL is_udp);
static void cache_pid(UINT32 src_ip, UINT16 src_port, DWORD pid, BOOL is_udp);
static void clear_pid_cache(void);
static void update_has_active_rules(void);
static DWORD WINAPI packet_processor(LPVOID arg)
{
unsigned char packet[MAXBUF];
UINT packet_len;
WINDIVERT_ADDRESS addr;
PWINDIVERT_IPHDR ip_header;
PWINDIVERT_TCPHDR tcp_header;
PWINDIVERT_UDPHDR udp_header;
while (running)
{
if (!WinDivertRecv(windivert_handle, packet, sizeof(packet), &packet_len, &addr))
{
if (GetLastError() == ERROR_INVALID_HANDLE)
break;
log_message("Failed to receive packet (%lu)", GetLastError());
continue;
}
PWINDIVERT_IPV6HDR ipv6_header = NULL;
WinDivertHelperParsePacket(packet, packet_len, &ip_header, &ipv6_header, NULL,
NULL, NULL, &tcp_header, &udp_header, NULL, NULL, NULL, NULL);
if (ip_header == NULL)
{
// IPv6 traffic pass directly without proxying
if (ipv6_header != NULL)
{
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
}
continue;
}
if (udp_header != NULL && tcp_header == NULL)
{
if (addr.Outbound)
{
if (udp_header->SrcPort == htons(LOCAL_UDP_RELAY_PORT))
{
UINT16 dst_port = ntohs(udp_header->DstPort);
UINT32 orig_dest_ip;
UINT16 orig_dest_port;
if (get_connection(dst_port, &orig_dest_ip, &orig_dest_port))
{
// Restore both source IP and port to original destination
ip_header->SrcAddr = orig_dest_ip;
udp_header->SrcPort = htons(orig_dest_port);
} addr.Outbound = FALSE;
}
else if (is_connection_tracked(ntohs(udp_header->SrcPort)))
{
UINT16 src_port = ntohs(udp_header->SrcPort);
UINT32 temp_addr = ip_header->DstAddr;
udp_header->DstPort = htons(LOCAL_UDP_RELAY_PORT);
ip_header->DstAddr = ip_header->SrcAddr;
ip_header->SrcAddr = temp_addr;
addr.Outbound = FALSE;
}
else
{
UINT16 src_port = ntohs(udp_header->SrcPort);
UINT32 src_ip = ip_header->SrcAddr;
UINT32 dest_ip = ip_header->DstAddr;
UINT16 dest_port = ntohs(udp_header->DstPort);
// if no rule configuree all connection direct with no checks avoid unwanted memory and pocessing whcich could delay
if (!g_has_active_rules && g_connection_callback == NULL)
{
// No rules and no logging - pass through immediately (no checksum needed for unmodified packets)
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
}
RuleAction action;
DWORD pid = 0;
if (dest_port == 53 && !g_dns_via_proxy)
action = RULE_ACTION_DIRECT;
else
action = check_process_rule(src_ip, src_port, dest_ip, dest_port, TRUE, &pid);
// override PROXY to DIRECT if localhost proxy is disabled and destination is localhost
BYTE dest_first_octet = (dest_ip >> 0) & 0xFF;
if (action == RULE_ACTION_PROXY && !g_localhost_via_proxy && dest_first_octet == 127)
action = RULE_ACTION_DIRECT;
// Override PROXY to DIRECT for critical IPs and ports
if (action == RULE_ACTION_PROXY && is_broadcast_or_multicast(dest_ip))
action = RULE_ACTION_DIRECT;
// Override PROXY to DIRECT for DHCP ports (67=server, 68=client)
if (action == RULE_ACTION_PROXY && (dest_port == 67 || dest_port == 68))
action = RULE_ACTION_DIRECT;
// only log if callback is set
// reuse pid from check_process_rule
// CLI use no log flag
if (g_connection_callback != NULL && pid > 0)
{
char process_name[MAX_PROCESS_NAME];
if (pid > 0 && get_process_name_from_pid(pid, process_name, sizeof(process_name)))
{
if (!is_connection_already_logged(pid, dest_ip, dest_port, action))
{
char dest_ip_str[32];
format_ip_address(dest_ip, dest_ip_str, sizeof(dest_ip_str));
char proxy_info[128];
if (action == RULE_ACTION_PROXY)
{
snprintf(proxy_info, sizeof(proxy_info), "Proxy SOCKS5://%s:%d (UDP)",
g_proxy_host, g_proxy_port);
}
else if (action == RULE_ACTION_DIRECT)
{
snprintf(proxy_info, sizeof(proxy_info), "Direct (UDP)");
}
else if (action == RULE_ACTION_BLOCK)
{
snprintf(proxy_info, sizeof(proxy_info), "Blocked (UDP)");
}
const char* display_name = extract_filename(process_name);
g_connection_callback(display_name, pid, dest_ip_str, dest_port, proxy_info);
if (g_traffic_logging_enabled)
{
add_logged_connection(pid, dest_ip, dest_port, action);
}
}
}
}
if (action == RULE_ACTION_BLOCK)
{
continue;
}
if (action == RULE_ACTION_PROXY)
{
add_connection(src_port, src_ip, dest_ip, dest_port);
// redirect to UDP relay server at 127.0.0.1:34011
udp_header->DstPort = htons(LOCAL_UDP_RELAY_PORT);
ip_header->DstAddr = htonl(INADDR_LOOPBACK);
// check if source is localhos
BYTE src_first_octet = (ntohl(ip_header->SrcAddr) >> 24) & 0xFF;
BOOL src_is_loopback = (src_first_octet == 127);
if (!src_is_loopback)
{
// for non loopback source: mark as inbound
addr.Outbound = FALSE;
}
// for loopback we need keep as outbound (127.x.x.x -> 127.0.0.1)
// for a fucking stupid reason i missed this part for 6 months
}
}
}
else
{
if (udp_header->DstPort != htons(LOCAL_UDP_RELAY_PORT))
{
// Unmodified packet no checksum needed
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
}
}
// Modified UDP packet calculate checksums
WinDivertHelperCalcChecksums(packet, packet_len, &addr, 0);
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
} // TCP packets only from here
if (tcp_header == NULL)
continue;
if (addr.Outbound)
{
if (tcp_header->SrcPort == htons(g_local_relay_port))
{
UINT16 dst_port = ntohs(tcp_header->DstPort);
UINT32 orig_dest_ip;
UINT16 orig_dest_port;
if (get_connection(dst_port, &orig_dest_ip, &orig_dest_port))
tcp_header->SrcPort = htons(orig_dest_port);
BYTE src_first = (ntohl(ip_header->SrcAddr) >> 24) & 0xFF;
BYTE dst_first = (ntohl(ip_header->DstAddr) >> 24) & 0xFF;
BOOL is_loopback = (src_first == 127 && dst_first == 127);
if (!is_loopback)
{
UINT32 temp_addr = ip_header->DstAddr;
ip_header->DstAddr = ip_header->SrcAddr;
ip_header->SrcAddr = temp_addr;
addr.Outbound = FALSE;
}
if (tcp_header->Fin || tcp_header->Rst)
remove_connection(dst_port);
}
else if (is_connection_tracked(ntohs(tcp_header->SrcPort)))
{
UINT16 src_port = ntohs(tcp_header->SrcPort);
if (tcp_header->Fin || tcp_header->Rst)
remove_connection(src_port);
tcp_header->DstPort = htons(g_local_relay_port);
BYTE src_first = (ntohl(ip_header->SrcAddr) >> 24) & 0xFF;
BYTE dst_first = (ntohl(ip_header->DstAddr) >> 24) & 0xFF;
BOOL is_loopback = (src_first == 127 && dst_first == 127);
if (!is_loopback)
{
UINT32 temp_addr = ip_header->DstAddr;
ip_header->DstAddr = ip_header->SrcAddr;
ip_header->SrcAddr = temp_addr;
addr.Outbound = FALSE;
}
}
else
{
UINT16 src_port = ntohs(tcp_header->SrcPort);
UINT32 src_ip = ip_header->SrcAddr;
UINT32 orig_dest_ip = ip_header->DstAddr;
UINT16 orig_dest_port = ntohs(tcp_header->DstPort);
// avoid rule pocess and packet process if no rules
if (!g_has_active_rules && g_connection_callback == NULL)
{
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
}
RuleAction action;
DWORD pid = 0;
if (orig_dest_port == 53 && !g_dns_via_proxy)
action = RULE_ACTION_DIRECT;
else
action = check_process_rule(src_ip, src_port, orig_dest_ip, orig_dest_port, FALSE, &pid);
BYTE orig_dest_first_octet = (orig_dest_ip >> 0) & 0xFF;
if (action == RULE_ACTION_PROXY && !g_localhost_via_proxy && orig_dest_first_octet == 127)
action = RULE_ACTION_DIRECT;
// Override PROXY to DIRECT for criticl ips
if (action == RULE_ACTION_PROXY && is_broadcast_or_multicast(orig_dest_ip))
action = RULE_ACTION_DIRECT;
// only new TCP/SYN inital fist packet
if (g_connection_callback != NULL && tcp_header->Syn && !tcp_header->Ack && pid > 0)
{
char process_name[MAX_PROCESS_NAME];
if (pid > 0 && get_process_name_from_pid(pid, process_name, sizeof(process_name)))
{
if (!is_connection_already_logged(pid, orig_dest_ip, orig_dest_port, action))
{
char dest_ip_str[32];
snprintf(dest_ip_str, sizeof(dest_ip_str), "%d.%d.%d.%d",
(orig_dest_ip >> 0) & 0xFF, (orig_dest_ip >> 8) & 0xFF,
(orig_dest_ip >> 16) & 0xFF, (orig_dest_ip >> 24) & 0xFF);
char proxy_info[128];
if (action == RULE_ACTION_PROXY)
{
snprintf(proxy_info, sizeof(proxy_info), "Proxy %s://%s:%d",
g_proxy_type == PROXY_TYPE_HTTP ? "HTTP" : "SOCKS5",
g_proxy_host, g_proxy_port);
}
else if (action == RULE_ACTION_DIRECT)
{
snprintf(proxy_info, sizeof(proxy_info), "Direct");
}
else if (action == RULE_ACTION_BLOCK)
{
snprintf(proxy_info, sizeof(proxy_info), "Blocked");
}
const char* display_name = extract_filename(process_name);
g_connection_callback(display_name, pid, dest_ip_str, orig_dest_port, proxy_info);
if (g_traffic_logging_enabled)
{
add_logged_connection(pid, orig_dest_ip, orig_dest_port, action);
}
}
}
}
if (action == RULE_ACTION_DIRECT)
{
// Unmodified packet no checksum needed
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
}
else if (action == RULE_ACTION_BLOCK)
{
// Drop the packet - don't send it anywhere
continue;
}
else if (action == RULE_ACTION_PROXY)
{
add_connection(src_port, src_ip, orig_dest_ip, orig_dest_port);
tcp_header->DstPort = htons(g_local_relay_port);
// check if this is localhost -> localhost traffic
BYTE src_first_octet = (ntohl(ip_header->SrcAddr) >> 24) & 0xFF;
BYTE dst_first_octet = (ntohl(ip_header->DstAddr) >> 24) & 0xFF;
BOOL is_loopback_to_loopback = (src_first_octet == 127 && dst_first_octet == 127);
if (is_loopback_to_loopback)
{
// for localhost -> localhost just change port, keep as outbound
// dont swap IPs Windows loopback routing needs both to stay 127.x.x.x
log_message("[PACKET] Loopback redirect: 127.x.x.x:%d -> 127.x.x.x:%d (relay port %d)",
ntohs(tcp_header->SrcPort), orig_dest_port, g_local_relay_port);
// addr.Outbound stays TRUE
}
else
{
// for normal traffic: swap IPs and mark as inbound (standard relay behavior)
UINT32 temp_addr = ip_header->DstAddr;
ip_header->DstAddr = ip_header->SrcAddr;
ip_header->SrcAddr = temp_addr;
addr.Outbound = FALSE;
}
}
}
}
else
{
if (tcp_header->DstPort != htons(g_local_relay_port))
{
// Unmodified return packet no checksum needed
WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr);
continue;
}
}
// Modified TCP packet calculate checksums
WinDivertHelperCalcChecksums(packet, packet_len, &addr, 0);
if (!WinDivertSend(windivert_handle, packet, packet_len, NULL, &addr))
{
log_message("Failed to send packet (%lu)", GetLastError());
}
}
return 0;
}
static UINT32 parse_ipv4(const char *ip)
{
unsigned int a, b, c, d;
if (sscanf_s(ip, "%u.%u.%u.%u", &a, &b, &c, &d) != 4)
return 0;
if (a > 255 || b > 255 || c > 255 || d > 255)
return 0;
return (a << 0) | (b << 8) | (c << 16) | (d << 24);
}
// Resolve hostname to IPv4 address (supports both IP addresses and domain names)
static UINT32 resolve_hostname(const char *hostname)
{
if (hostname == NULL || hostname[0] == '\0')
return 0;
// First try to parse as IP address
UINT32 ip = parse_ipv4(hostname);
if (ip != 0)
return ip;
// Not an IP address, try DNS resolution
struct addrinfo hints, *result = NULL;
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_INET; // IPv4 only
hints.ai_socktype = SOCK_STREAM;
if (getaddrinfo(hostname, NULL, &hints, &result) != 0)
{
log_message("Failed to resolve hostname: %s", hostname);
return 0;
}
if (result == NULL || result->ai_family != AF_INET)
{
if (result != NULL)
freeaddrinfo(result);
log_message("No IPv4 address found for hostname: %s", hostname);
return 0;
}
struct sockaddr_in *addr = (struct sockaddr_in *)result->ai_addr;
UINT32 resolved_ip = addr->sin_addr.s_addr;
freeaddrinfo(result);
log_message("Resolved %s to %d.%d.%d.%d", hostname,
(resolved_ip >> 0) & 0xFF, (resolved_ip >> 8) & 0xFF,
(resolved_ip >> 16) & 0xFF, (resolved_ip >> 24) & 0xFF);
return resolved_ip;
}
static DWORD get_process_id_from_connection(UINT32 src_ip, UINT16 src_port)
{
// check cache first
DWORD cached_pid = get_cached_pid(src_ip, src_port, FALSE);
if (cached_pid != 0)
return cached_pid;
MIB_TCPTABLE_OWNER_PID *tcp_table = NULL;
DWORD size = 0;
DWORD pid = 0;
if (GetExtendedTcpTable(NULL, &size, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0) != ERROR_INSUFFICIENT_BUFFER)
{
return 0;
}
tcp_table = (MIB_TCPTABLE_OWNER_PID *)malloc(size);
if (tcp_table == NULL)
{
return 0;
}
if (GetExtendedTcpTable(tcp_table, &size, FALSE, AF_INET,
TCP_TABLE_OWNER_PID_ALL, 0) != NO_ERROR)
{
free(tcp_table);
return 0;
}
for (DWORD i = 0; i < tcp_table->dwNumEntries; i++)
{
MIB_TCPROW_OWNER_PID *row = &tcp_table->table[i];
if (row->dwLocalAddr == src_ip &&
ntohs((UINT16)row->dwLocalPort) == src_port)
{
pid = row->dwOwningPid;
break;
}
}
free(tcp_table);
// store cache the result
if (pid != 0)
cache_pid(src_ip, src_port, pid, FALSE);
return pid;
}
// Get process ID for UDP connection
static DWORD get_process_id_from_udp_connection(UINT32 src_ip, UINT16 src_port)
{
DWORD cached_pid = get_cached_pid(src_ip, src_port, TRUE);
if (cached_pid != 0)
return cached_pid;
MIB_UDPTABLE_OWNER_PID *udp_table = NULL;
DWORD size = 0;
DWORD pid = 0;
if (GetExtendedUdpTable(NULL, &size, FALSE, AF_INET,
UDP_TABLE_OWNER_PID, 0) != ERROR_INSUFFICIENT_BUFFER)
{
return 0;
}
udp_table = (MIB_UDPTABLE_OWNER_PID *)malloc(size);
if (udp_table == NULL)
{
return 0;
}
if (GetExtendedUdpTable(udp_table, &size, FALSE, AF_INET,
UDP_TABLE_OWNER_PID, 0) != NO_ERROR)
{
free(udp_table);
return 0;
}
// First pass: Try exact match (IP + port)
for (DWORD i = 0; i < udp_table->dwNumEntries; i++)
{
MIB_UDPROW_OWNER_PID *row = &udp_table->table[i];
if (row->dwLocalAddr == src_ip &&
ntohs((UINT16)row->dwLocalPort) == src_port)
{
pid = row->dwOwningPid;
break;
}
}
// Second pass: If not found, try matching port on 0.0.0.0 (INADDR_ANY)
// Many UDP applications bind to 0.0.0.0:port instead of specific IP
if (pid == 0)
{
for (DWORD i = 0; i < udp_table->dwNumEntries; i++)
{
MIB_UDPROW_OWNER_PID *row = &udp_table->table[i];
if (row->dwLocalAddr == 0 && // 0.0.0.0 (INADDR_ANY)
ntohs((UINT16)row->dwLocalPort) == src_port)
{
pid = row->dwOwningPid;
break;
}
}
}
free(udp_table);
if (pid != 0)
cache_pid(src_ip, src_port, pid, TRUE);
return pid;
}
static BOOL get_process_name_from_pid(DWORD pid, char *name, DWORD name_size)
{
HANDLE hProcess;
char full_path[MAX_PATH];
DWORD path_len = MAX_PATH;
if (pid == 0)
{
return FALSE;
}
// ERROR in getting process name for PID 4 reserved by system
// SMB is managed by system process
if (pid == 4)
{
strncpy_s(name, name_size, "System", _TRUNCATE);
return TRUE;
}
hProcess = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid);
if (hProcess == NULL)
{
return FALSE;
}
if (QueryFullProcessImageNameA(hProcess, 0, full_path, &path_len))
{
strncpy_s(name, name_size, full_path, _TRUNCATE);
CloseHandle(hProcess);
return TRUE;
}
CloseHandle(hProcess);
return FALSE;
}
// Match IP pattern against IP address
// Supports: "*" (all), "192.168.1.1" (exact), "192.168.*.*" (wildcard)
static BOOL match_ip_pattern(const char *pattern, UINT32 ip)
{
if (pattern == NULL || strcmp(pattern, "*") == 0)
return TRUE;
// check for IP range
char *dash = strchr(pattern, '-');
if (dash != NULL)
{
char start_ip_str[64], end_ip_str[64];
size_t start_len = dash - pattern;
if (start_len >= sizeof(start_ip_str))
return FALSE;
strncpy_s(start_ip_str, sizeof(start_ip_str), pattern, start_len);
start_ip_str[start_len] = '\0';
strncpy_s(end_ip_str, sizeof(end_ip_str), dash + 1, _TRUNCATE);
// parse start and end IPs
UINT32 start_ip = 0, end_ip = 0;
int s1, s2, s3, s4, e1, e2, e3, e4;
if (sscanf_s(start_ip_str, "%d.%d.%d.%d", &s1, &s2, &s3, &s4) == 4 &&
sscanf_s(end_ip_str, "%d.%d.%d.%d", &e1, &e2, &e3, &e4) == 4)
{
start_ip = (s1 << 0) | (s2 << 8) | (s3 << 16) | (s4 << 24);
end_ip = (e1 << 0) | (e2 << 8) | (e3 << 16) | (e4 << 24);
// checking as network byte order would be wrong, compare as little-endian UINT32
// change to big-endian for proper comparison
UINT32 ip_be = ((ip & 0xFF) << 24) | ((ip & 0xFF00) << 8) | ((ip & 0xFF0000) >> 8) | ((ip & 0xFF000000) >> 24);
UINT32 start_be = ((start_ip & 0xFF) << 24) | ((start_ip & 0xFF00) << 8) | ((start_ip & 0xFF0000) >> 8) | ((start_ip & 0xFF000000) >> 24);
UINT32 end_be = ((end_ip & 0xFF) << 24) | ((end_ip & 0xFF00) << 8) | ((end_ip & 0xFF0000) >> 8) | ((end_ip & 0xFF000000) >> 24);
return (ip_be >= start_be && ip_be <= end_be);
}
return FALSE;
}
// Extract 4 octets from IP (little-endian)
unsigned char ip_octets[4];
ip_octets[0] = (ip >> 0) & 0xFF;
ip_octets[1] = (ip >> 8) & 0xFF;
ip_octets[2] = (ip >> 16) & 0xFF;
ip_octets[3] = (ip >> 24) & 0xFF;
// Parse pattern manually
char pattern_copy[256];
strncpy_s(pattern_copy, sizeof(pattern_copy), pattern, _TRUNCATE);
char pattern_octets[4][16];
int octet_count = 0;
int char_idx = 0;
for (int i = 0; i <= (int)strlen(pattern_copy) && octet_count < 4; i++)
{
if (pattern_copy[i] == '.' || pattern_copy[i] == '\0')
{
pattern_octets[octet_count][char_idx] = '\0';
octet_count++;
char_idx = 0;
if (pattern_copy[i] == '\0')
break;
}
else
{
if (char_idx < 15)
pattern_octets[octet_count][char_idx++] = pattern_copy[i];
}
}
if (octet_count != 4)
return FALSE;
for (int i = 0; i < 4; i++)
{
if (strcmp(pattern_octets[i], "*") == 0)
continue;
int pattern_val = atoi(pattern_octets[i]);
if (pattern_val != ip_octets[i])
return FALSE;
}
return TRUE;
}
// Match port pattern: "*", "80", "8000-9000"
static BOOL match_port_pattern(const char *pattern, UINT16 port)
{
if (pattern == NULL || strcmp(pattern, "*") == 0)
return TRUE;
char *dash = strchr(pattern, '-');
if (dash != NULL)
{
int start_port = atoi(pattern);
int end_port = atoi(dash + 1);
return (port >= start_port && port <= end_port);
}
return (port == atoi(pattern));
}
static BOOL ip_match_wrapper(const char *token, const void *data)
{
return match_ip_pattern(token, *(const UINT32*)data);
}
// Match IP list: "192.168.*.*;10.0.0.1"
static BOOL match_ip_list(const char *ip_list, UINT32 ip)
{
return parse_token_list(ip_list, ";", ip_match_wrapper, &ip);
}
static BOOL port_match_wrapper(const char *token, const void *data)
{
return match_port_pattern(token, *(const UINT16*)data);
}
// Match port list: "80;443;8000-9000"
static BOOL match_port_list(const char *port_list, UINT16 port)
{
return parse_token_list(port_list, ",;", port_match_wrapper, &port);
}
// Match process name with wildcard support
// Supports: "*" (all),
// "chrome.exe" (exact), "fire*.exe" (wildcard), "*.bin" (extension wildcard)
// added support for full paths - C:\Program Files\Google\Chrome\Application\chrome.exe
// Nedd to Test all combination at sanme time
static BOOL match_process_pattern(const char *pattern, const char *process_full_path)
{
if (pattern == NULL || strcmp(pattern, "*") == 0)
return TRUE;
// Extract just the filename from the full path for comparison
// Windows path sucks
const char *filename = strrchr(process_full_path, '\\');
if (filename != NULL)
filename++; // Skip the backslash
else
filename = process_full_path; // No path separator, use as-is
size_t pattern_len = strlen(pattern);
size_t name_len = strlen(filename);
size_t full_path_len = strlen(process_full_path);
// Check if pattern contains path separators (backslash or forward slash)
BOOL is_full_path_pattern = (strchr(pattern, '\\') != NULL || strchr(pattern, '/') != NULL);
// check if pattern has path seperator match for full path
const char *match_target = is_full_path_pattern ? process_full_path : filename; // match against filename only
size_t target_len = is_full_path_pattern ? full_path_len : name_len;
// check for * at the end: "fire*" or "C:\Program Files\*"
if (pattern_len > 0 && pattern[pattern_len - 1] == '*')
{
// Match prefix: "fire*" matches "firefox.exe"
return _strnicmp(pattern, match_target, pattern_len - 1) == 0;
}
// Check for wildcard at the beginning: "*.exe"
if (pattern_len > 1 && pattern[0] == '*')
{
// Match suffix: "*.exe" matches "chrome.exe"
const char *pattern_suffix = pattern + 1;
size_t suffix_len = pattern_len - 1;
if (target_len >= suffix_len)
{
return _stricmp(match_target + target_len - suffix_len, pattern_suffix) == 0;
}
return FALSE;
}
// check for * in the middle: "fire*.exe" or C:\Program Files\*\chrome.exe
const char *star = strchr(pattern, '*');
if (star != NULL)
{