-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathh2polar.c
2329 lines (2162 loc) · 77.6 KB
/
h2polar.c
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
/*
h2Polar - lightweight http/s proxy written in C with ssl intercepting 'n traffic features.
RedToor, 2021 - https://github.com/PowerScript/h2Polar
This program 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.
This program 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 this program. If not, see <http://www.gnu.org/licenses/>.
*/
#ifdef _WIN32
#include <Winsock2.h>
#include <TlHelp32.h>
#include <Shlobj.h>
#include <gdiplus.h>
#include <ws2tcpip.h>
#include <Winhttp.h>
#else
#include <sys/socket.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <unistd.h>
#include <netdb.h>
#include <fcntl.h>
#include <pthread.h>
#include <string.h>
#include <ctype.h>
#include <errno.h>
#include <stdlib.h>
#include <arpa/inet.h>
#endif
#include <stdio.h>
#include <time.h>
#ifdef OPENSSL
#include <openssl/crypto.h>
#include <openssl/x509.h>
#include <openssl/x509v3.h>
#include <openssl/pem.h>
#include <openssl/ssl.h>
#include <openssl/err.h>
#define __CA_COUNTRY "CO"
#define __CA_COMPANY "PowerScript"
#define __CA_HOST "h2Polar"
#define __CA_AFTER 31536000L
#define __CA_FILE "h2Polar.cer"
#define __CA_KEYFILE "h2Polar.key"
#endif
#ifdef THREAD_POOL
#include <pthread.h>
#define __POOL_NTHREAD 20
#endif
#define __AUTHOR "RedToor"
#define __VERSION "2023.08.27.1358"
#define __CAPTURE_FILE "h2Polar.log"
#define __DOWNLOAD_FOLDER "%s"
#define __CONFIG_FILE "h2polar.cfg"
#define __PAC_FILE "/h2Polar.pac"
#define __INIT_SIZE_BUFFER 8192
#define __INTERFACE_BIND "127.0.0.1"
#define __TIMEOUT_CONNECT 4
#define __TIMEOUT_TUNNEL 30
#define __PORT_BIND 51234
#define __MAX_CLIENT 100
#define COMMENT_RULE '#'
#define SETTING_FORMAT "%s = %s[^\n]\n"
#define DELIMITER_RULE_INFO "|"
#define DELIMITER_RULE "\r\n"
#define DOWNLOAD_CONTENT_SLASH_REMPLACE ','
#define MAX_URL_SIZE 2048
#define MAX_HOSTNAME_SIZE 512
#define MAX_ARG_1_SIZE 1024
#define MAX_ARG_2_SIZE 1024
#define MAX_STR_VALUE_HEADER_SIZE 100
#define true 1
#define false 0
typedef int bool;
#ifdef THREAD_POOL
typedef struct _job {
int socket;
struct _job* next;
} job, *pjob;
typedef struct {
pthread_mutex_t look;
pthread_cond_t work_cond;
pthread_cond_t working_cond;
pjob fjob;
pjob ljob;
size_t executing;
size_t nthreads;
bool stop;
} thread_pool, *pthread_pool;
#endif
enum {
_INTERFACE,
PORT,
TLS_MITM,
POOL_NTHREADS,
TIMEOUT_CONNECT,
TIMEOUT_TUNNEL,
INIT_BUFFER_SIZE
};
typedef enum
{
PROXY_TO_PAGE,
PROXY_TO_CLIENT,
CLIENT_TO_PROXY,
PAGE_TO_PROXY
} PROXY_FLOW;
typedef enum
{
INIT,
HEAD_REQUEST,
BODY_REQUEST,
HEAD_RESPONSE,
BODY_RESPONSE,
FINISHED,
INIT_KEEPALIVE
} HTTP_STAGE;
typedef enum {
SWITCHING_PROTOCOLS = 101
} HTTP_STATUS;
typedef enum {
UNKNOW,
ALL,
CONNECT,
GET,
PUT,
POST,
HEAD,
DELETE_,
OPTIONS,
TRACE
} PROXY_METHOD;
typedef enum {
DIRECT,
CAPTURE,
MODIFY_BODY_REQUEST,
MODIFY_BODY_RESPONSE,
REDIRECT,
REJECT,
SCREENSHOT,
FAKE_TLS_EXT_HOSTNAME,
REMOVE_HEADER_REQUEST,
REMOVE_HEADER_RESPONSE,
ADD_HEADER_REQUEST,
ADD_HEADER_RESPONSE,
DOWNLOAD_CONTENT
} PROXY_ACTION;
typedef struct {
char url[MAX_URL_SIZE];
char hostname[MAX_HOSTNAME_SIZE];
char tls_ext_hostname[MAX_HOSTNAME_SIZE];
int port;
char method[8];
char version_protocol;
} reqinfo, *preqinfo;
typedef struct {
bool chunked;
struct {
bool keep_alive;
bool upgrade;
} connection;
u_int content_length;
char* content_length_offset;
char content_type[MAX_STR_VALUE_HEADER_SIZE];
char upgrade[MAX_STR_VALUE_HEADER_SIZE];
} headers, *pheaders;
typedef struct {
char* pointer;
u_int written;
u_int size_block;
} buffer, *pbuffer;
typedef struct _domain_cache
{
char domain[MAX_HOSTNAME_SIZE];
u_long ip;
struct _domain_cache* next;
} domain_cache, *pdomain_cache;
typedef struct
{
char hostname[MAX_HOSTNAME_SIZE];
u_int port;
} redirect, *predirect;
typedef struct
{
char hostname[MAX_HOSTNAME_SIZE];
} fake_tls_ext_hostname, *pfake_tls_ext_hostname;
typedef struct
{
char content_type[24];
} download_content, *pdownload_content;
typedef struct
{
char* prefix;
char* inject;
u_int prefix_length;
u_int inject_length;
} injection, *pinjection;
typedef struct
{
char header[2048];
u_int header_length;
} head, *phead;
typedef struct _rule {
PROXY_ACTION action;
char domain[MAX_HOSTNAME_SIZE];
char url[MAX_URL_SIZE];
bool ssl;
u_int port;
u_int method;
void* extra_data;
struct _rule* next;
} rule, *prule;
typedef struct _action {
PROXY_ACTION action;
void* extra_data;
struct _action* next;
} action, *paction;
typedef struct _client_connection {
struct sockaddr_in client_addr;
int client_socket;
} client_connection, *pclient_connection;
#ifdef OPENSSL
char hex_map[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
u_char alpn_protocol[] = { 8, 'h', 't', 't', 'p', '/', '1', '.', '1' };
u_int lentgh = sizeof(alpn_protocol);
typedef struct _certificate_cache
{
char cache_hash[200];
X509* certificate;
struct _certificate_cache* next;
} certificate_cache, *pcertificate_cache;
typedef struct {
X509* certificate;
SSL_CTX* context;
SSL* connection;
} ssl_layer, *pssl_layer;
#endif
typedef struct {
int error_code;
int sock_browser;
int sock_page;
int response_code;
client_connection connection;
PROXY_METHOD method;
PROXY_ACTION action;
HTTP_STAGE stage;
buffer head_request;
buffer body_request;
buffer head_response;
buffer body_response;
paction actions;
reqinfo info;
headers headers_request;
headers headers_response;
u_long thread_id;
bool ssl;
bool connection_established;
u_int nrequests;
#ifdef OPENSSL
pssl_layer ssl_page;
pssl_layer ssl_browser;
char* ssl_error;
#endif
} client, *pclient;
struct {
char _interface[20];
u_int port;
u_int nthreads;
u_long timeout_connect;
u_long timeout_tunnel;
u_int init_buffer_size;
u_int tls_mitm;
char* cfg_file;
#ifdef OPENSSL
X509* certificate;
EVP_PKEY* client_key;
EVP_PKEY* certificate_key;
X509_NAME* ca_issuer;
#ifdef CA_MEM_CACHE
pcertificate_cache certificate_cache;
#endif
#endif
#ifdef DEBUG
pthread_mutex_t stdout_lock;
#endif
#ifdef DNS_MEM_CACHE
pthread_mutex_t domain_cache_lock;
#endif
pthread_mutex_t certificate_cache_lock;
pdomain_cache domain_cache;
int socket;
prule proxy_rules;
buffer pac_request;
} proxy_config, *pproxy_config;
struct {
char* phttpsd2s;
char* parse_http_url;
char* parse_http_url_port;
char* parse_https_url;
char* parse_https_url_port;
char* parse_response_code;
char* transfer_encoding;
char* proxy_connection;
char* keep_alive;
char* content_lentgh;
char* content_lentghinject;
char* content_type;
char* upgrade;
char* websocket;
char* hostname;
char* parse_hostname;
char* connection;
char* screenshot;
char* format_int_value_header;
char* format_str_value_header;
char* chunked;
char* endchunk;
char* accept_encoding;
char* head_connection_established;
char* http_get;
char* http_post;
char* http_put;
char* http_connect;
char* http_head;
char* http_delete;
char* head_pac_response;
char* pac_response_1;
char* pac_response_2;
char* pac_response_3;
} const_char, *pconst_char;
char* PROXY_ACTIONS[] = { [DIRECT] = "DIRECT", [CAPTURE] = "CAPTURE", [MODIFY_BODY_REQUEST] = "MODIFY_BODY_REQUEST", [MODIFY_BODY_RESPONSE] = "MODIFY_BODY_RESPONSE", [REDIRECT] = "REDIRECT",
[REJECT] = "REJECT", [SCREENSHOT] = "SCREENSHOT", [FAKE_TLS_EXT_HOSTNAME] = "FAKE_TLS_EXT_HOSTNAME",
[REMOVE_HEADER_REQUEST] = "REMOVE_HEADER_REQUEST", [REMOVE_HEADER_RESPONSE] = "REMOVE_HEADER_RESPONSE",
[ADD_HEADER_REQUEST] = "ADD_HEADER_REQUEST", [ADD_HEADER_RESPONSE] = "ADD_HEADER_RESPONSE", [DOWNLOAD_CONTENT] = "DOWNLOAD_CONTENT" };
char* PROXY_METHODS[] = { [UNKNOW] = "UNKNOW", [ALL] = "ALL", [CONNECT] = "CONNECT", [GET] = "GET", [PUT] = "PUT", [POST] = "POST", [HEAD] = "HEAD", [DELETE_] = "DELETE", [OPTIONS] = "OPTIONS", [TRACE] = "TRACE" };
char* KEY_SETTING[] = { [_INTERFACE] = "INTERFACE", [PORT] = "PORT", [POOL_NTHREADS] = "POOL_NTHREADS", [TIMEOUT_CONNECT] = "TIMEOUT_CONNECT",
[TIMEOUT_TUNNEL] = "TIMEOUT_TUNNEL", [INIT_BUFFER_SIZE] = "INIT_BUFFER_SIZE", [TLS_MITM] = "TLS_MITM"};
#define RETN_OK return true;
#define RETN_FAIL return false;
#ifdef _WIN32
#define GET_SYSTEM_ERROR() WSAGetLastError()
#else
#define GET_SYSTEM_ERROR() errno
#endif
#ifndef DEBUG
#define LOGGER(FORMAT, ...)
#else
char* HTTP_SSL[] = { "NO", "YES" };
char* PROXY_STAGES[] = { [INIT] = "INIT", [HEAD_REQUEST] = "HEAD_REQUEST", [BODY_REQUEST] = "BODY_REQUEST", [HEAD_RESPONSE] = "HEAD_RESPONSE", [BODY_RESPONSE] = "BODY_RESPONSE", [FINISHED] = "FINISHED", [INIT_KEEPALIVE] = "INIT_KEEPALIVE" };
#define LOGGER(FORMAT, ...) pthread_mutex_lock(&proxy_config.stdout_lock); \
printf("%d\t%20s\t%lu\t%lu\t" FORMAT ".\n", __LINE__, __FUNCTION__, pthread_self(), GET_SYSTEM_ERROR(), ##__VA_ARGS__); \
pthread_mutex_unlock(&proxy_config.stdout_lock);
#endif
#define ADD_ITEM(array, item) if (array == 0){ array = item; } else { item->next = array; } array = item;
#define ITER_LLIST(item, array) for (item=array; item; item=item->next)
#define CHECK_OP(execute) if (!execute) goto __exception;
#define IF_EXTRADATA(action) action == MODIFY_BODY_RESPONSE || MODIFY_BODY_REQUEST == action || REDIRECT == action || action == FAKE_TLS_EXT_HOSTNAME || DOWNLOAD_CONTENT == action
#define ADD_ACTION(actions, naction) ADD_ITEM(actions, naction)
#define ADD_RULE(nrule) ADD_ITEM(proxy_config.proxy_rules, nrule)
#define ADD_DOMAIN_CACHE(ndomain_cache) ADD_ITEM(proxy_config.domain_cache, ndomain_cache)
#define ADD_CERTIFICATE_CACHE(ncertificate_cache) ADD_ITEM(proxy_config.certificate_cache, ncertificate_cache)
#define IF_ZERO(expr) if ((expr) != 0){ LOGGER("__exception") RETN_FAIL }
#define IF_GZERO(expr) if ((expr) <= 0){ LOGGER("__exception") RETN_FAIL }
#define CHECK_REALLOC(castype, function, pointer, ...) if ((pointer = (castype*)function(__VA_ARGS__)) == 0){ LOGGER("__except_heap_corruption") exit(1); }
#define CHECK_ALLOC(castype, function, pointer, ...) CHECK_REALLOC(castype, function, pointer, __VA_ARGS__, sizeof(castype))
#define STR2INT(X) #X
#define IN2STR(X) STR2INT(X)
void load_strings()
{
strcpy(proxy_config._interface, __INTERFACE_BIND);
proxy_config.port = __PORT_BIND;
proxy_config.timeout_connect = __TIMEOUT_CONNECT * 1000;
proxy_config.timeout_tunnel = __TIMEOUT_TUNNEL * 1000;
proxy_config.init_buffer_size = __INIT_SIZE_BUFFER;
proxy_config.cfg_file = __CONFIG_FILE;
#ifdef THREAD_POOL
proxy_config.nthreads = __POOL_NTHREAD;
#endif
const_char.http_get = "GET";
const_char.http_post = "POST";
const_char.http_connect = "CONNECT";
const_char.http_put = "PUT";
const_char.http_head = "HEAD";
const_char.http_delete = "DELETE";
const_char.parse_http_url = "http://%" IN2STR(MAX_HOSTNAME_SIZE) "[^/]%" IN2STR(MAX_URL_SIZE) "s";
const_char.parse_http_url_port = "http://%" IN2STR(MAX_HOSTNAME_SIZE) "[^:]:%d%" IN2STR(MAX_URL_SIZE) "[^\n]";
const_char.parse_https_url = "https://%" IN2STR(MAX_HOSTNAME_SIZE) "[^/]%" IN2STR(MAX_URL_SIZE) "s";
const_char.parse_https_url_port = "https://%" IN2STR(MAX_HOSTNAME_SIZE) "[^:]:%d%" IN2STR(MAX_URL_SIZE) "[^\n]";
const_char.parse_response_code = "%*s %d %*s\r\n";
const_char.transfer_encoding = "Transfer-Encoding:";
const_char.content_lentgh = "Content-Length:";
const_char.content_lentghinject = "Content-Length: %d";
const_char.content_type = "Content-Type:";
const_char.proxy_connection = "Proxy-Connection:";
const_char.connection = "Connection:";
const_char.accept_encoding = "Accept-Encoding:";
const_char.upgrade = "Upgrade:";
const_char.hostname = "Host:";
const_char.parse_hostname = "Host: %s\r\n\r\n";
const_char.format_int_value_header = "%*s %d";
const_char.format_str_value_header = "%*s %" IN2STR(MAX_STR_VALUE_HEADER_SIZE) "s";
const_char.chunked = "chunked";
const_char.websocket = "websocket";
const_char.keep_alive = "keep-alive";
const_char.endchunk = "0\r\n\r\n";
const_char.screenshot = "sc";
const_char.head_pac_response = "HTTP/1.0 200\r\nContent-Type: application/x-ns-proxy-autoconfig\r\nConnection: Close\r\nContent-Length: %d\r\n\r\n";
const_char.head_connection_established = "HTTP/1.1 200 Connection established\r\n\r\n";
const_char.pac_response_1 = "function FindProxyForURL(url, host){if(";
const_char.pac_response_2 = "dnsDomainIs(host, \"%s\")||";
const_char.pac_response_3 = "){return \"PROXY %s:%d\"}return \"DIRECT\"}";
const_char.phttpsd2s = "https://";
}
#ifdef OPENSSL
void delete_extention(X509* dst_cert, int nid, int where)
{
X509_EXTENSION* ext = 0;
int ex = 0;
if ((ex = X509_get_ext_by_NID(dst_cert, nid, where)) >= 0) {
if ((ext = X509_delete_ext(dst_cert, ex))){
X509_EXTENSION_free(ext);
}
}
}
size_t bin2hex(const unsigned char* bin, size_t bin_lentgh, char* str, size_t str_lentgh)
{
char* p = 0;
size_t i = 0;
if (str_lentgh < (bin_lentgh + 1)){
return 0;
}
p = str;
for (i = 0; i < bin_lentgh; ++i){
*p++ = hex_map[*bin >> 4];
*p++ = hex_map[*bin & 0xf];
++bin;
}
*p = 0;
return p - str;
}
EVP_PKEY* generate_rsa_key()
{
EVP_PKEY* pkey = 0;
RSA * rsa = 0;
if(!(pkey = EVP_PKEY_new())){
RETN_FAIL
}
if(!(rsa = RSA_generate_key(2048, RSA_F4, NULL, NULL))){
RETN_FAIL
}
if(!EVP_PKEY_assign_RSA(pkey, rsa)){
EVP_PKEY_free(pkey);
RETN_FAIL
}
return pkey;
}
X509* generate_x509(EVP_PKEY* pkey)
{
X509 * x509 = 0;
X509_NAME * gname = 0;
if(!(x509 = X509_new())){
RETN_FAIL
}
X509_set_version(x509, 2);
ASN1_INTEGER_set(X509_get_serialNumber(x509), 0);
X509_gmtime_adj(X509_get_notBefore(x509), 0);
X509_gmtime_adj(X509_get_notAfter(x509), __CA_AFTER);
X509_set_pubkey(x509, pkey);
gname = X509_get_subject_name(x509);
X509_NAME_add_entry_by_txt(gname, "C", MBSTRING_ASC, (unsigned char *)__CA_COUNTRY, -1, -1, 0);
X509_NAME_add_entry_by_txt(gname, "O", MBSTRING_ASC, (unsigned char *)__CA_COMPANY, -1, -1, 0);
X509_NAME_add_entry_by_txt(gname, "CN", MBSTRING_ASC, (unsigned char *)__CA_HOST, -1, -1, 0);
X509_set_issuer_name(x509, gname);
if(!X509_sign(x509, pkey, EVP_sha1())){
X509_free(x509);
RETN_FAIL
}
return x509;
}
bool load_ssl_files()
{
BIO* bio = 0;
if (!(bio = BIO_new_file(__CA_FILE, "rb"))) goto __exception;
if (!(proxy_config.certificate = PEM_read_bio_X509(bio, 0, 0, 0))) goto __exception;
BIO_free(bio);
if (!(bio = BIO_new_file(__CA_KEYFILE, "rb"))) goto __exception;
if (!(proxy_config.certificate_key = PEM_read_bio_PrivateKey(bio, 0, 0, 0))) goto __exception;
BIO_free(bio);
if (!(proxy_config.client_key = generate_rsa_key())) goto __exception;
if (!(proxy_config.ca_issuer = X509_get_subject_name(proxy_config.certificate))) goto __exception;
RETN_OK
__exception:
LOGGER("Error loading CA, KEY files: %s", ERR_error_string(ERR_get_error(), 0))
RETN_FAIL
}
bool generate_ssl_files()
{
FILE* certificate = 0;
FILE* certificate_key = 0;
IF_GZERO(proxy_config.client_key = generate_rsa_key())
IF_GZERO(proxy_config.certificate_key = generate_rsa_key())
IF_GZERO(proxy_config.certificate = generate_x509(proxy_config.certificate_key))
proxy_config.ca_issuer = X509_get_subject_name(proxy_config.certificate);
IF_GZERO(certificate = fopen(__CA_FILE, "wb"))
IF_GZERO(certificate_key = fopen(__CA_KEYFILE, "wb"))
PEM_write_PrivateKey(certificate_key, proxy_config.certificate_key, 0, 0,0, 0, 0);
PEM_write_X509(certificate, proxy_config.certificate);
fclose(certificate);
fclose(certificate_key);
RETN_OK
}
bool page_ssl_handshake(pclient request)
{
IF_GZERO(request->ssl_page = (pssl_layer)calloc(1, sizeof(ssl_layer)));
IF_GZERO(request->ssl_page->context = SSL_CTX_new(SSLv23_client_method()));
if ((request->ssl_page->connection = SSL_new(request->ssl_page->context)) <= 0){
RETN_FAIL
}
if ((request->error_code = SSL_set_fd(request->ssl_page->connection, request->sock_page) <= 0)) goto __exception;
if ((request->error_code = SSL_set_tlsext_host_name(request->ssl_page->connection, request->info.tls_ext_hostname)) <= 0) goto __exception;
SSL_set_alpn_protos(request->ssl_page->connection, alpn_protocol, lentgh);
if ((request->error_code = SSL_connect(request->ssl_page->connection)) <= 0) goto __exception;
if ((request->ssl_page->certificate = SSL_get_peer_certificate(request->ssl_page->connection)) <= 0) goto __exception;
RETN_OK
__exception:
request->ssl_error = ERR_error_string(SSL_get_error(request->ssl_page->connection, request->error_code), 0);
RETN_FAIL
}
bool browser_ssl_handshake(pclient request)
{
IF_GZERO(request->ssl_browser->context = SSL_CTX_new(SSLv23_server_method()));
if ((request->error_code = SSL_CTX_use_certificate(request->ssl_browser->context, request->ssl_browser->certificate)) != 1) goto __exception;
if ((request->error_code = SSL_CTX_use_PrivateKey(request->ssl_browser->context, proxy_config.client_key)) != 1) goto __exception;
if ((request->ssl_browser->connection = SSL_new(request->ssl_browser->context)) <= 0) goto __exception;
if ((request->error_code = SSL_set_fd(request->ssl_browser->connection, request->sock_browser)) <= 0) goto __exception;
if ((request->error_code = SSL_accept(request->ssl_browser->connection)) <= 0) goto __exception;
RETN_OK
__exception:
request->ssl_error = ERR_error_string(SSL_get_error(request->ssl_browser->connection, request->error_code), 0);
RETN_FAIL
}
bool clone_certificate(pclient request)
{
CHECK_ALLOC(ssl_layer, calloc, request->ssl_browser, 1);
#ifdef CA_MEM_CACHE
pcertificate_cache certificate = 0;
char cache_hash[200] = {0};
char hash_name[sizeof(request->ssl_page->certificate->sha1_hash) * 2 + 1] = {0};
bin2hex(request->ssl_page->certificate->sha1_hash, sizeof(request->ssl_page->certificate->sha1_hash), hash_name, sizeof(hash_name));
sprintf(cache_hash, "%s", hash_name);
pthread_mutex_lock(&proxy_config.certificate_cache_lock);
ITER_LLIST(certificate, proxy_config.certificate_cache){
if (strcmp(certificate->cache_hash, cache_hash) == 0){
IF_GZERO(request->ssl_browser->certificate = X509_dup(certificate->certificate));
pthread_mutex_unlock(&proxy_config.certificate_cache_lock);
RETN_OK
}
}
pthread_mutex_unlock(&proxy_config.certificate_cache_lock);
#endif
if ((request->ssl_browser->certificate = X509_dup(request->ssl_page->certificate)) <= 0) goto __exception;
delete_extention(request->ssl_browser->certificate, NID_crl_distribution_points, -1);
delete_extention(request->ssl_browser->certificate, NID_info_access, -1);
delete_extention(request->ssl_browser->certificate, NID_authority_key_identifier, -1);
delete_extention(request->ssl_browser->certificate, NID_certificate_policies, 0);
if ((request->error_code = X509_set_pubkey(request->ssl_browser->certificate, proxy_config.client_key)) == 0) goto __exception;
X509_set_issuer_name(request->ssl_browser->certificate, proxy_config.ca_issuer);
if (!(request->error_code = X509_sign(request->ssl_browser->certificate, proxy_config.certificate_key, EVP_sha256()))) goto __exception;
#ifdef CA_MEM_CACHE
CHECK_ALLOC(certificate_cache, calloc, certificate, 1)
IF_GZERO(certificate->certificate = X509_dup(request->ssl_browser->certificate));
strcpy(certificate->cache_hash, cache_hash);
pthread_mutex_lock(&proxy_config.certificate_cache_lock);
ADD_CERTIFICATE_CACHE(certificate)
pthread_mutex_unlock(&proxy_config.certificate_cache_lock);
#endif
RETN_OK
__exception:
request->ssl_error = ERR_error_string(ERR_get_error(), 0);
RETN_FAIL
}
bool ssl_handshake(pclient request)
{
LOGGER("-->ssl pinning")
IF_GZERO(page_ssl_handshake(request))
IF_GZERO(clone_certificate(request))
IF_GZERO(send(request->sock_browser, const_char.head_connection_established, 39, 0));
IF_GZERO(browser_ssl_handshake(request))
request->head_request.written = 0;
memset((void*)&request->info.url, 0, MAX_URL_SIZE);
memset((void*)&request->headers_request, 0, sizeof(headers));
RETN_OK
}
#endif
char* strnstr(char* hay, int haysize, char* needle, int needlesize)
{
int haypos = 0;
int needlepos = 0;
haysize -= needlesize;
for (haypos = 0; haypos <= haysize; haypos++) {
for (needlepos = 0; needlepos < needlesize; needlepos++){
if (tolower(hay[haypos + needlepos]) != tolower(needle[needlepos])){
break;
}
}
if (needlepos == needlesize) {
return hay + haypos;
}
}
RETN_FAIL
}
int get_num_dig(unsigned size)
{
if (size >= 1000000000) return 10;
if (size >= 100000000) return 9;
if (size >= 10000000) return 8;
if (size >= 1000000) return 7;
if (size >= 100000) return 6;
if (size >= 10000) return 5;
if (size >= 1000) return 4;
if (size >= 100) return 3;
if (size >= 10) return 2;
return 1;
}
#ifdef DEBUG
void printer(char* data, int size)
{
pthread_mutex_lock(&proxy_config.stdout_lock);
printf("------------------------------------------------------------------------\n");
char a, line[17], c;
int j;
for (int i = 0; i < size; i++){
c = data[i];
printf(" %.2x", (unsigned char)c);
a = (c >= 32 && c <= 128) ? (unsigned char)c : '.';
line[i % 16] = a;
if ((i != 0 && (i + 1) % 16 == 0) || i == size - 1)
{
line[i % 16 + 1] = '\0';
printf(" ");
for (j = strlen(line); j < 16; j++)
{
printf(" ");
}
printf("%s \n", line);
}
}
printf("\n-----------------------------------------------------------------------%d\n", size);
pthread_mutex_unlock(&proxy_config.stdout_lock);
}
#endif
#ifdef _WIN32
void write_bmp(HBITMAP bitmap, HDC hDC, LPTSTR filename)
{
BITMAP bmp = {0};
BITMAPFILEHEADER hdr = {0};
PBITMAPINFO pbmi = 0;
PBITMAPINFOHEADER pbih = 0;
u_long dwTmp = 0;
u_long cb = 0;
WORD cClrBits = 0;
HANDLE hf = 0;
LPBYTE lpBits = 0;
BYTE* hp = 0;
if (GetObject(bitmap, sizeof(BITMAP), (LPSTR)&bmp)){
cClrBits = (WORD)(bmp.bmPlanes * bmp.bmBitsPixel);
if (cClrBits == 1){ cClrBits = 1; }
else if (cClrBits <= 4) {
cClrBits = 4;
} else if (cClrBits <= 8) {
cClrBits = 8;
} else if (cClrBits <= 16){
cClrBits = 16;
} else if (cClrBits <= 24){
cClrBits = 24;
} else {
cClrBits = 32;
} if (cClrBits != 24){
pbmi = (PBITMAPINFO) LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER) + sizeof(RGBQUAD) * (1 << cClrBits));
}else{
pbmi = (PBITMAPINFO) LocalAlloc(LPTR, sizeof(BITMAPINFOHEADER));
}
pbmi->bmiHeader.biSize = sizeof(BITMAPINFOHEADER);
pbmi->bmiHeader.biWidth = bmp.bmWidth;
pbmi->bmiHeader.biHeight = bmp.bmHeight;
pbmi->bmiHeader.biPlanes = bmp.bmPlanes;
pbmi->bmiHeader.biBitCount = bmp.bmBitsPixel;
if (cClrBits < 24){
pbmi->bmiHeader.biClrUsed = (1 << cClrBits);
}
pbmi->bmiHeader.biCompression = BI_RGB;
pbmi->bmiHeader.biSizeImage = (pbmi->bmiHeader.biWidth + 7) / 8 * pbmi->bmiHeader.biHeight * cClrBits;
pbmi->bmiHeader.biClrImportant = 0;
pbih = (PBITMAPINFOHEADER) pbmi;
if ((lpBits = (LPBYTE)GlobalAlloc(GMEM_FIXED, pbih->biSizeImage)) != 0){
if (GetDIBits(hDC, bitmap, 0, (WORD) pbih->biHeight, lpBits, pbmi, DIB_RGB_COLORS)){
if ((hf = CreateFile(filename, GENERIC_READ | GENERIC_WRITE, (u_long) 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, (HANDLE)NULL)) != INVALID_HANDLE_VALUE){
hdr.bfType = 0x4D42;
hdr.bfSize = (u_long)(sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof(RGBQUAD) + pbih->biSizeImage);
hdr.bfReserved1 = 0;
hdr.bfReserved2 = 0;
hdr.bfOffBits = (u_long) sizeof(BITMAPFILEHEADER) + pbih->biSize + pbih->biClrUsed * sizeof (RGBQUAD);
WriteFile(hf, (LPVOID)&hdr, sizeof(BITMAPFILEHEADER), (LPu_long) &dwTmp, NULL);
WriteFile(hf, (LPVOID)pbih, sizeof(BITMAPINFOHEADER) + pbih->biClrUsed * sizeof (RGBQUAD), (LPu_long) &dwTmp, NULL);
cb = pbih->biSizeImage;
hp = lpBits;
WriteFile(hf, (LPSTR)hp, (int)cb, (LPu_long)&dwTmp, NULL);
CloseHandle(hf);
}
}
GlobalFree((HGLOBAL)lpBits);
}
GlobalFree((HGLOBAL)pbmi);
}
}
bool generate_bmp(int x, int y, int width, int height)
{
HDC hdc = 0;
HBITMAP hbitmap = 0;
time_t t = time(NULL);
struct tm tm = *localtime(&t);
char bmp_file[MAX_PATH] = {0};
sprintf(bmp_file, "%s-%d%02d%02d-%02d%02d%02d.bmp", const_char.screenshot, tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec);
IF_GZERO(hdc = CreateCompatibleDC(0));
IF_GZERO(hbitmap = CreateCompatibleBitmap(GetDC(0), width, height));
IF_GZERO(SelectObject(hdc, hbitmap));
BitBlt(hdc, 0, 0, width, height, GetDC(0), x, y, SRCCOPY);
write_bmp(hbitmap, hdc, bmp_file);
DeleteObject(hbitmap);
DeleteDC(hdc);
RETN_OK
}
#endif
bool compare(char* init, int count, char* str, int count2)
{
if (count2 == 0) RETN_OK
if (count != count2) RETN_FAIL
for (int i = 0; i < count; ++i){
if (init[i] != str[i]) RETN_FAIL
}
RETN_OK
}
bool url_filter(char* mask_filter, char* str, char delimiter)
{
u_int size_incomming = 0;
u_int size_domain = 0;
int count = 0;
int count2 = 0;
int read = 0;
int read2 = 0;
bool end = false;
size_incomming = strlen(mask_filter) + 1;
size_domain = strlen(str) + 1;
for (int i = 0; i < size_domain; ++i){
if (str[i] != delimiter && str[i] != '\0') {count++;}
if (str[i] == delimiter || str[i] == '\0') {
if (end) RETN_FAIL
for (int d = 0; d < (size_incomming - read2); ++d){
if (mask_filter[read2 + d] != delimiter && mask_filter[read2 + d] != '\0') count2++;
if (mask_filter[read2 + d] == delimiter) break;
if (mask_filter[read2 + d] == '\0') end = true;
}
if (mask_filter[read2] == '!'){
end = true;
break;
}
if (compare(str + read, count, mask_filter + read2, count2) == false) RETN_FAIL
read += count + 1;
read2 += count2 + 1;
count = 0;
count2 = 0;
}
}
return end;
}
bool hostname_filter(char* mask_filter, char* input, char delimiter)
{
int string_length = strlen(input) - 1;
int m = strlen(mask_filter) - 1;
bool mask = false;
for (int i = string_length; i != -1 ; --i)
{
if (input[i] == delimiter){
mask = false;
}
if (mask_filter[m] == '*') {
mask = true;
if(m == 0){
RETN_OK
}
m--;
}
if (input[i] != mask_filter[m] && !mask){
RETN_FAIL
}
if (!mask)
{
m--;
}
}
RETN_OK
}
void generate_pac_response()
{
prule proxy_rule = 0;
u_int body_length = 0;
body_length = 39 + 35 + strlen(proxy_config._interface) + get_num_dig(proxy_config.port);
ITER_LLIST(proxy_rule, proxy_config.proxy_rules){
body_length += strlen(proxy_rule->domain) + 23;
}
body_length -= 2;
proxy_config.pac_request.size_block = body_length + 140;
CHECK_ALLOC(char, calloc, proxy_config.pac_request.pointer, proxy_config.pac_request.size_block)
sprintf(proxy_config.pac_request.pointer, const_char.head_pac_response, body_length);
proxy_config.pac_request.written += strlen(proxy_config.pac_request.pointer);
memcpy(proxy_config.pac_request.pointer + proxy_config.pac_request.written, const_char.pac_response_1, 39);
proxy_config.pac_request.written += 39;
ITER_LLIST(proxy_rule, proxy_config.proxy_rules){
sprintf(proxy_config.pac_request.pointer + proxy_config.pac_request.written, const_char.pac_response_2, proxy_rule->domain);
proxy_config.pac_request.written += strlen(proxy_rule->domain) + 23;
}
proxy_config.pac_request.written -= 2;
sprintf(proxy_config.pac_request.pointer + proxy_config.pac_request.written, const_char.pac_response_3, proxy_config._interface, proxy_config.port);
proxy_config.pac_request.written += strlen(proxy_config.pac_request.pointer + proxy_config.pac_request.written);
}
void free_proxy_actions(pclient request)
{
paction actions = request->actions;
paction backup = 0;
while (actions){
if (IF_EXTRADATA(actions->action)){
free(actions->extra_data);
}
backup = actions;
actions = actions->next;
free(backup);
}
}
void close_handle(pclient request)
{
LOGGER("<+free/closing objects/sockets")
if (request != 0){
if (request->sock_browser > 0){
#ifdef _WIN32
closesocket(request->sock_browser);
#else
shutdown(request->sock_browser, SHUT_RDWR);
close(request->sock_browser);
#endif
}
if (request->sock_page > 0){
#ifdef _WIN32
closesocket(request->sock_page);
#else
shutdown(request->sock_page, SHUT_RDWR);
close(request->sock_page);
#endif
}
if (request->head_request.size_block > 0){
free(request->head_request.pointer);
}
if (request->body_request.size_block > 0){
free(request->body_request.pointer);
}
if (request->head_response.size_block > 0){
free(request->head_response.pointer);
}
if (request->body_response.size_block > 0){
free(request->body_response.pointer);
}
free_proxy_actions(request);
#ifdef OPENSSL
if (request->ssl_browser > 0){
if (request->ssl_browser->certificate > 0){
X509_free(request->ssl_browser->certificate);
}
if (request->ssl_browser->connection > 0){
SSL_shutdown(request->ssl_browser->connection);
SSL_free(request->ssl_browser->connection);
}
if (request->ssl_browser->context > 0){
SSL_CTX_free(request->ssl_browser->context);
}
free(request->ssl_browser);
}
if (request->ssl_page > 0){
if (request->ssl_page->certificate > 0){
X509_free(request->ssl_page->certificate);
}
if (request->ssl_page->connection > 0){
SSL_shutdown(request->ssl_page->connection);
SSL_free(request->ssl_page->connection);
}
if (request->ssl_page->context > 0){
SSL_CTX_free(request->ssl_page->context);
}
free(request->ssl_page);
}
#endif
free(request);
}
}
bool get_method(char* buffer, u_int* method)
{
if (strncmp(buffer, PROXY_METHODS[ALL], 3) == 0){
*method = ALL;
RETN_OK
} else if (strncmp(buffer, PROXY_METHODS[GET], 3) == 0){
*method = GET;
RETN_OK
}else if (strncmp(buffer, PROXY_METHODS[POST], 4) == 0){
*method = POST;
RETN_OK
} else if (strncmp(buffer, PROXY_METHODS[CONNECT], 7) == 0){
*method = CONNECT;