-
Notifications
You must be signed in to change notification settings - Fork 0
/
socks5.cpp
425 lines (366 loc) · 11.2 KB
/
socks5.cpp
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
// 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 2 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, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//
// Author: Matías Fontanini
// Contact: [email protected]
#include <cstdlib>
#include <cstring>
#include <unistd.h>
#include <stdint.h>
#include <signal.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <netdb.h>
#include <pthread.h>
#include <iostream>
#include <memory>
#include <string>
#include <sstream>
#include <algorithm>
#include <set>
#ifndef SERVER_PORT
#define SERVER_PORT 5555
#endif
#define MAXPENDING 200
#define BUF_SIZE 256
#ifndef USERNAME
#define USERNAME "username"
#endif
#ifndef PASSWORD
#define PASSWORD "password"
#endif
using namespace std;
/* Command constants */
#define CMD_CONNECT 1
#define CMD_BIND 2
#define CMD_UDP_ASSOCIATIVE 3
/* Address type constants */
#define ATYP_IPV4 1
#define ATYP_DNAME 3
#define ATYP_IPV6 4
/* Connection methods */
#define METHOD_NOAUTH 0
#define METHOD_AUTH 2
#define METHOD_NOTAVAILABLE 0xff
/* Responses */
#define RESP_SUCCEDED 0
#define RESP_GEN_ERROR 1
/* Handshake */
struct MethodIdentificationPacket {
uint8_t version, nmethods;
/* uint8_t methods[nmethods]; */
} __attribute__((packed));
struct MethodSelectionPacket {
uint8_t version, method;
MethodSelectionPacket(uint8_t met) : version(5), method(met) {}
} __attribute__((packed));
/* Requests */
struct SOCKS5RequestHeader {
uint8_t version, cmd, rsv /* = 0x00 */, atyp;
} __attribute__((packed));
struct SOCK5IP4RequestBody {
uint32_t ip_dst;
uint16_t port;
} __attribute__((packed));
struct SOCK5DNameRequestBody {
uint8_t length;
/* uint8_t dname[length]; */
} __attribute__((packed));
/* Responses */
struct SOCKS5Response {
uint8_t version, cmd, rsv /* = 0x00 */, atyp;
uint32_t ip_src;
uint16_t port_src;
SOCKS5Response(bool succeded = true) : version(5), cmd(succeded ? RESP_SUCCEDED : RESP_GEN_ERROR), rsv(0), atyp(ATYP_IPV4) { }
} __attribute__((packed));
class Lock {
pthread_mutex_t mutex;
public:
Lock() {
pthread_mutex_init(&mutex, NULL);
}
~Lock() {
pthread_mutex_destroy(&mutex);
}
inline void lock() {
pthread_mutex_lock(&mutex);
}
inline void unlock() {
pthread_mutex_unlock(&mutex);
}
};
class Event {
pthread_mutex_t mutex;
pthread_cond_t condition;
public:
Event() {
pthread_mutex_init(&mutex, 0);
pthread_cond_init(&condition, 0);
}
~Event() {
pthread_mutex_destroy(&mutex);
pthread_cond_destroy(&condition);
}
inline void lock() {
pthread_mutex_lock(&mutex);
}
inline void unlock() {
pthread_mutex_unlock(&mutex);
}
inline void signal() {
pthread_cond_signal(&condition);
}
inline void broadcastSignal() {
pthread_cond_broadcast(&condition);
}
inline void wait(){
pthread_cond_wait(&condition, &mutex);
}
};
Lock get_host_lock;
Event client_lock;
uint32_t client_count = 0, max_clients = 10;
void sig_handler(int signum) {
}
int create_listen_socket(struct sockaddr_in &echoclient) {
int serversock;
struct sockaddr_in echoserver;
/* Create the TCP socket */
if ((serversock = socket(PF_INET, SOCK_STREAM, IPPROTO_TCP)) < 0) {
cout << "[-] Could not create socket.\n";
return -1;
}
/* Construct the server sockaddr_in structure */
memset(&echoserver, 0, sizeof(echoserver)); /* Clear struct */
echoserver.sin_family = AF_INET; /* Internet/IP */
echoserver.sin_addr.s_addr = htonl(INADDR_ANY); /* Incoming addr */
echoserver.sin_port = htons(SERVER_PORT); /* server port */
/* Bind the server socket */
if (bind(serversock, (struct sockaddr *) &echoserver, sizeof(echoserver)) < 0) {
cout << "[-] Bind error.\n";
return -1;
}
/* Listen on the server socket */
if (listen(serversock, MAXPENDING) < 0) {
cout << "[-] Listen error.\n";
return -1;
}
return serversock;
}
int recv_sock(int sock, char *buffer, uint32_t size) {
int index = 0, ret;
while(size) {
if((ret = recv(sock, &buffer[index], size, 0)) <= 0)
return (!ret) ? index : -1;
index += ret;
size -= ret;
}
return index;
}
int send_sock(int sock, const char *buffer, uint32_t size) {
int index = 0, ret;
while(size) {
if((ret = send(sock, &buffer[index], size, 0)) <= 0)
return (!ret) ? index : -1;
index += ret;
size -= ret;
}
return index;
}
string int_to_str(uint32_t ip) {
ostringstream oss;
for (unsigned i=0; i<4; i++) {
oss << ((ip >> (i*8) ) & 0xFF);
if(i != 3)
oss << '.';
}
return oss.str();
}
int connect_to_host(uint32_t ip, uint16_t port) {
struct sockaddr_in serv_addr;
struct hostent *server;
int sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
return -1;
bzero((char *) &serv_addr, sizeof(serv_addr));
serv_addr.sin_family = AF_INET;
string ip_string = int_to_str(ip);
get_host_lock.lock();
server = gethostbyname(ip_string.c_str());
if(!server) {
get_host_lock.unlock();
return -1;
}
bcopy((char *)server->h_addr, (char *)&serv_addr.sin_addr.s_addr, server->h_length);
get_host_lock.unlock();
serv_addr.sin_port = htons(port);
return !connect(sockfd, (const sockaddr*)&serv_addr, sizeof(serv_addr)) ? sockfd : -1;
}
int read_variable_string(int sock, uint8_t *buffer, uint8_t max_sz) {
if(recv_sock(sock, (char*)buffer, 1) != 1 || buffer[0] > max_sz)
return false;
uint8_t sz = buffer[0];
if(recv_sock(sock, (char*)buffer, sz) != sz)
return -1;
return sz;
}
bool check_auth(int sock) {
uint8_t buffer[128];
if(recv_sock(sock, (char*)buffer, 1) != 1 || buffer[0] != 1)
return false;
int sz = read_variable_string(sock, buffer, 127);
if(sz == -1)
return false;
buffer[sz] = 0;
if(strcmp((char*)buffer, USERNAME))
return false;
sz = read_variable_string(sock, buffer, 127);
if(sz == -1)
return false;
buffer[sz] = 0;
if(strcmp((char*)buffer, PASSWORD))
return false;
buffer[0] = 1;
buffer[1] = 0;
return send_sock(sock, (const char*)buffer, 2) == 2;
}
bool handle_handshake(int sock, char *buffer) {
MethodIdentificationPacket packet;
int read_size = recv_sock(sock, (char*)&packet, sizeof(MethodIdentificationPacket));
if(read_size != sizeof(MethodIdentificationPacket) || packet.version != 5)
return false;
if(recv_sock(sock, buffer, packet.nmethods) != packet.nmethods)
return false;
MethodSelectionPacket response(METHOD_NOTAVAILABLE);
for(unsigned i(0); i < packet.nmethods; ++i) {
#ifdef ALLOW_NO_AUTH
if(buffer[i] == METHOD_NOAUTH)
response.method = METHOD_NOAUTH;
#endif
if(buffer[i] == METHOD_AUTH)
response.method = METHOD_AUTH;
}
if(send_sock(sock, (const char*)&response, sizeof(MethodSelectionPacket)) != sizeof(MethodSelectionPacket) || response.method == METHOD_NOTAVAILABLE)
return false;
return (response.method == METHOD_AUTH) ? check_auth(sock) : true;
}
void set_fds(int sock1, int sock2, fd_set *fds) {
FD_ZERO (fds);
FD_SET (sock1, fds);
FD_SET (sock2, fds);
}
void do_proxy(int client, int conn, char *buffer) {
fd_set readfds;
int result, nfds = max(client, conn)+1;
set_fds(client, conn, &readfds);
while((result = select(nfds, &readfds, 0, 0, 0)) > 0) {
if (FD_ISSET (client, &readfds)) {
int recvd = recv(client, buffer, 256, 0);
if(recvd <= 0)
return;
send_sock(conn, buffer, recvd);
}
if (FD_ISSET (conn, &readfds)) {
int recvd = recv(conn, buffer, 256, 0);
if(recvd <= 0)
return;
send_sock(client, buffer, recvd);
}
set_fds(client, conn, &readfds);
}
}
bool handle_request(int sock, char *buffer) {
SOCKS5RequestHeader header;
recv_sock(sock, (char*)&header, sizeof(SOCKS5RequestHeader));
if(header.version != 5 || header.cmd != CMD_CONNECT || header.rsv != 0)
return false;
int client_sock = -1;
switch(header.atyp) {
case ATYP_IPV4:
{
SOCK5IP4RequestBody req;
if(recv_sock(sock, (char*)&req, sizeof(SOCK5IP4RequestBody)) != sizeof(SOCK5IP4RequestBody))
return false;
client_sock = connect_to_host(req.ip_dst, ntohs(req.port));
break;
}
case ATYP_DNAME:
break;
default:
return false;
}
if(client_sock == -1)
return false;
SOCKS5Response response;
response.ip_src = 0;
response.port_src = SERVER_PORT;
send_sock(sock, (const char*)&response, sizeof(SOCKS5Response));
do_proxy(client_sock, sock, buffer);
shutdown(client_sock, SHUT_RDWR);
close(client_sock);
return true;
}
void *handle_connection(void *arg) {
int sock = (uint64_t)arg;
char *buffer = new char[BUF_SIZE];
if(handle_handshake(sock, buffer))
handle_request(sock, buffer);
shutdown(sock, SHUT_RDWR);
close(sock);
delete[] buffer;
client_lock.lock();
client_count--;
if(client_count == max_clients - 1)
client_lock.signal();
client_lock.unlock();
return 0;
}
bool spawn_thread(pthread_t *thread, void *data) {
pthread_attr_t attr;
pthread_attr_init(&attr);
pthread_attr_setstacksize(&attr, 64 * 1024);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
return !pthread_create(thread, &attr, handle_connection, data);
}
void parse_args(int argc, char *argv[]) {
if(argc == 2)
max_clients = atoi(argv[1]);
}
int main(int argc, char *argv[]) {
struct sockaddr_in echoclient;
int listen_sock = create_listen_socket(echoclient);
if(listen_sock == -1) {
cout << "[-] Failed to create server\n";
return 1;
}
parse_args(argc, argv);
signal(SIGPIPE, sig_handler);
while(true) {
uint32_t clientlen = sizeof(echoclient);
int clientsock;
client_lock.lock();
if(client_count == max_clients)
client_lock.wait();
client_lock.unlock();
if ((clientsock = accept(listen_sock, (struct sockaddr *) &echoclient, &clientlen)) > 0) {
client_lock.lock();
client_count++;
client_lock.unlock();
pthread_t thread;
spawn_thread(&thread, (void*)clientsock);
}
}
}