forked from jcramb/revshell
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsock.cc
494 lines (401 loc) · 14.3 KB
/
sock.cc
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
////////////////////////////////////////////////////////////////////////////////
// sock.cc
// author: [email protected]
#include "sock.h"
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/stat.h>
#include <sys/time.h>
#include <ifaddrs.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <netdb.h>
#include <poll.h>
#include <cstring>
#include <cstdio>
#include "core.h"
#define SOCKET_BACKLOG 10
////////////////////////////////////////////////////////////////////////////////
// helper funcs
bool sock_is_blocking(int fd) {
return fcntl(fd, F_GETFL) & O_NONBLOCK;
}
int sock_set_blocking(int fd, bool blocking) {
int flags = fcntl(fd, F_GETFL);
int nflags = blocking ? flags & ~O_NONBLOCK : flags | O_NONBLOCK;
return fcntl(fd, F_SETFL, nflags);
}
static inline void * get_in_addr(struct sockaddr * sa) {
if (sa->sa_family == AF_INET) {
return &(((struct sockaddr_in*)sa)->sin_addr);
} else {
return &(((struct sockaddr_in6*)sa)->sin6_addr);
}
}
////////////////////////////////////////////////////////////////////////////////
// return ip address of local system's default interface
const char * sock_get_ip(std::string iface) {
struct ifaddrs *ifaddrs, *index;
static char addr_str[INET_ADDRSTRLEN];
// obtain address info
getifaddrs(&ifaddrs);
// loop through interfaces
for (index = ifaddrs; index != NULL; index = index->ifa_next) {
// only consider IPv4, check if it matches specified interface
if (index->ifa_addr->sa_family == AF_INET &&
(iface.empty() || iface == index->ifa_name)) {
// convert address to presentable format
void * sai = &((struct sockaddr_in*)index->ifa_addr)->sin_addr;
inet_ntop(AF_INET, sai, addr_str, INET_ADDRSTRLEN);
}
}
freeifaddrs(ifaddrs);
return addr_str;
}
////////////////////////////////////////////////////////////////////////////////
// construct sock_info containing details for a socket connection
sock_info::sock_info(std::string _s_ip, int _s_port,
std::string _d_ip, int _d_port) {
strncpy(s_ip, _s_ip.c_str(), sizeof(s_ip));
strncpy(d_ip, _d_ip.c_str(), sizeof(d_ip));
s_port = _s_port;
d_port = _d_port;
}
////////////////////////////////////////////////////////////////////////////////
// tcp_stream ctors / dtors
tcp_stream::tcp_stream() {
m_type = SOCK_INVALID;
m_connlimit = -1;
m_sock = -1;
}
tcp_stream::~tcp_stream() {
this->close();
}
////////////////////////////////////////////////////////////////////////////////
// common func - send binary buffer over a tcp socket
int tcp_stream::send(const char * buf, int len, int sock) {
if (m_type == SOCK_CLIENT) {
sock = m_sock;
} else if (m_type == SOCK_SERVER) {
if (sock == m_sock) {
LOG("error: attempt to send over server listening sock!\n");
return -1;
} else if (sock <= 0 && m_client_socks.size() > 1) {
LOG("error: attempt to send over invalid sock (%d)\n", sock);
return -1;
} else if (m_client_socks.size() == 1) {
sock = *m_client_socks.begin();
}
}
int bytes_sent = 0;
while (bytes_sent < len) {
int bytes = ::send(sock, buf + bytes_sent, len - bytes_sent, 0);
if (bytes < 0) {
LOG("error: (send)[%d] %s\n", sock, strerror(errno));
break;
}
bytes_sent += bytes;
}
return bytes_sent;
}
////////////////////////////////////////////////////////////////////////////////
// common func - receive all bytes waiting on socket
int tcp_stream::recv(char * buf, int len, int sock) {
if (m_type == SOCK_CLIENT) {
sock = m_sock;
} else if (m_type == SOCK_SERVER && sock <= 0) {
LOG("error: attempt to recv over invalid sock (%d)\n", sock);
return -1;
}
int bytes = ::recv(sock, buf, len, 0);
if (bytes < 0) {
LOG("error: (recv)[%d] (%s)\n", sock, strerror(errno));
return -1;
}
return bytes;
}
////////////////////////////////////////////////////////////////////////////////
// clean up stream details
void tcp_stream::close(int sock) {
LOG("tcp_stream: socket closed [m_sock %2d | sock %2d]\n", m_sock, sock);
// are we closing a client socket?
if (m_client_socks.find(sock) != m_client_socks.end()) {
m_client_socks.erase(sock);
m_sockinfo.erase(sock);
::close(sock);
// otherwise, are we meant to close everything?
} else if (m_sock == sock || sock == -1) {
if (m_sock > 0) {
::close(m_sock);
m_sock = -1;
}
for (auto sock : m_client_socks) {
::close(sock);
}
m_type = SOCK_INVALID;
m_client_socks.clear();
m_sockinfo.clear();
// we may be trying to close an already closed socket if we get here
} else {
LOG("error: attempt to close invalid socket (%d)\n", sock);
}
}
////////////////////////////////////////////////////////////////////////////////
// client func - establish connection to server
int tcp_stream::connect(std::string host, int port) {
struct addrinfo hints, *server, *index;
char addr_str[INET6_ADDRSTRLEN];
int ai_result;
// configure hints for tcp connection
memset(&hints, 0, sizeof(hints));
hints.ai_family = AF_UNSPEC;
hints.ai_socktype = SOCK_STREAM;
// convert port to string
char _port[8] = {0};
port = CLAMP(port, 0, 65535);
snprintf(_port, sizeof(_port), "%d", port);
// obtain address info for server
if ((ai_result = getaddrinfo(host.c_str(), _port, &hints, &server)) != 0) {
LOG("error: %s\n", gai_strerror(ai_result));
return -1;
}
// loop through results, connect to first possible
for (index = server; index != NULL; index = index->ai_next) {
// try to open a tcp socket for this result
if ((m_sock = socket(index->ai_family,
index->ai_socktype,
index->ai_protocol)) < 0) {
LOG("error: (socket) %s\n", strerror(errno));
continue;
}
// connect to server using new socket
if (::connect(m_sock, index->ai_addr, index->ai_addrlen) < 0) {
LOG("error: (connect) %s\n", strerror(errno));
this->close();
continue;
}
// obtain presentable address of server
inet_ntop(index->ai_family,
get_in_addr((struct sockaddr*)index->ai_addr),
addr_str,
sizeof(addr_str));
// get local port assignment (not IPv6 friendly)
struct sockaddr_in sin;
socklen_t len = sizeof(sin);
if (getsockname(m_sock, (struct sockaddr *)&sin, &len) < 0) {
LOG("error: getsockname (%s)\n", strerror(errno));
}
int s_port = ntohs(sin.sin_port);
// success!
m_type = SOCK_CLIENT;
LOG("info: [%d] connected to %s:%d\n", m_sock, addr_str, port);
std::shared_ptr<sock_info> si;
si.reset(new sock_info(sock_get_ip(), s_port, addr_str, port));
m_sockinfo[m_sock] = si;
break;
}
// clean up address info
freeaddrinfo(server);
return index != NULL ? m_sock : -1;
}
////////////////////////////////////////////////////////////////////////////////
// server func - limit number of possible client connections
void tcp_stream::conn_limit(int limit) {
if (m_type != SOCK_SERVER) {
LOG("error: conn_limit invalid on non-server streams\n");
} else {
m_connlimit = limit;
}
}
////////////////////////////////////////////////////////////////////////////////
// server func - disconnect all client connections
void tcp_stream::disconnect_clients() {
for (int sock : m_client_socks) {
this->close(sock);
m_sockinfo.erase(sock);
}
m_client_socks.clear();
}
////////////////////////////////////////////////////////////////////////////////
// server func - send data buffer across all active connections
int tcp_stream::broadcast(const char * buf, int len) {
// verify that this is a server stream
if (m_type != SOCK_SERVER) {
LOG("error: broadcast on a non-server tcp stream\n");
return -1;
}
int err = 0;
for (auto sock : m_client_socks) {
int bytes = this->send(buf, len, sock);
if (bytes < 0) {
LOG("error: broadcast failed for sock (%d)[%d]\n", sock, bytes);
err = bytes;
}
}
return err;
}
////////////////////////////////////////////////////////////////////////////////
// server func - bind and listen to a tcp port
int tcp_stream::bind(int port) {
struct addrinfo hints, *ai, *index;
char addr_str[INET6_ADDRSTRLEN];
int ai_result;
// configure hints for tcp connection
memset(&hints, 0, sizeof(hints));
hints.ai_socktype = SOCK_STREAM;
hints.ai_family = AF_INET;
hints.ai_flags = AI_PASSIVE;
// convert port to string
char _port[8] = {0};
port = CLAMP(port, 0, 65535);
snprintf(_port, sizeof(_port), "%d", port);
// obtain address info for server port
if ((ai_result = getaddrinfo(NULL, _port, &hints, &ai)) != 0) {
LOG("error:: %s\n", gai_strerror(ai_result));
return -1;
}
// loop through results and bind to first possible
for (index = ai; index != NULL; index = index->ai_next) {
// attempt to open socket
if ((m_sock = socket(index->ai_family,
index->ai_socktype,
index->ai_protocol)) < 0) {
LOG("error: (socket) %s\n", strerror(errno));
continue;
}
// avoid "address already in use" errors
int optval = 1;
setsockopt(m_sock, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(int));
// bind socket to server port
if (::bind(m_sock, index->ai_addr, index->ai_addrlen) < 0) {
LOG("error: (bind) %s\n", strerror(errno));
continue;
}
// start listening for connections
if (::listen(m_sock, SOCKET_BACKLOG) < 0) {
LOG("error: (listen) %s\n", strerror(errno));
this->close();
continue;
}
// success!
m_type = SOCK_SERVER;
// obtain presentable address of server
inet_ntop(index->ai_family,
get_in_addr((struct sockaddr*)index->ai_addr),
addr_str,
sizeof(addr_str));
// store sock info
std::shared_ptr<sock_info> si;
si.reset(new sock_info(sock_get_ip(), port));
strncpy(si->s_ip, addr_str, sizeof(si->s_ip));
si->s_port = port;
m_sockinfo[m_sock] = si;
break;
}
freeaddrinfo(ai);
return index != NULL ? m_sock : -1;
}
////////////////////////////////////////////////////////////////////////////////
// server func - accept pending client connections (non-blocking)
int tcp_stream::poll_accept(int timeout_ms) {
// sanity check
if (m_type != SOCK_SERVER) {
LOG("error: poll_accept on non-server stream! (%d)\n", m_sock);
return -1;
}
struct pollfd fd_array;
fd_array.fd = m_sock;
fd_array.events = POLLIN;
int retval = poll(&fd_array, 1, 0); // 0ms wait
if (retval <= 0 && errno == EINTR) {
return 0;
} else if (retval <= 0) {
LOG("error: poll failed (%s)\n", strerror(errno));
return -1;
}
int sock;
if ((sock = this->accept()) < 0) {
return sock;
}
// non-blocking accepts return non-blocking client sockets
sock_set_blocking(sock, false);
return sock;
}
////////////////////////////////////////////////////////////////////////////////
// server func - accept client connection (blocking)
int tcp_stream::accept() {
struct sockaddr_storage client;
char client_ip[INET6_ADDRSTRLEN];
socklen_t len = sizeof(client);
int client_sock;
// check that we're respecting the connection limit
if (m_connlimit != -1 && m_client_socks.size() >= m_connlimit) {
LOG("error: connlimit rejection (%d)\n", m_sock);
return SOCK_LIMIT;
}
// wait for client to connect
if ((client_sock = ::accept(m_sock, (struct sockaddr*)&client, &len)) < 0) {
LOG("error: (accept) %s\n", strerror(errno));
return -1;
}
// request connected client information
inet_ntop(client.ss_family,
get_in_addr((struct sockaddr*)&client),
client_ip,
sizeof(client_ip));
int s_port = m_sockinfo[m_sock]->s_port;
int d_port = ntohs(((struct sockaddr_in*)&client)->sin_port);
LOG("info: connection %s:%d to %s:%d\n",
client_ip, d_port, src_ip(), src_port());
// success!
std::shared_ptr<sock_info> si;
si.reset(new sock_info(sock_get_ip(), s_port, client_ip, d_port));
m_sockinfo[m_sock] = si;
// store client socket
m_client_socks.emplace(client_sock);
return client_sock;
}
////////////////////////////////////////////////////////////////////////////////
// getter funcs - return sock information
const sock_info * tcp_stream::sockinfo(int sock) {
if (sock == -1) sock = m_sock;
if (m_sockinfo.find(sock) == m_sockinfo.end()) {
LOG("error: (sockinfo) invalid sock\n");
return NULL;
}
return m_sockinfo[sock].get();
}
const char * tcp_stream::src_ip(int sock) {
if (sock == -1) sock = m_sock;
if (m_sockinfo.find(sock) == m_sockinfo.end()) {
LOG("error: (src_ip) invalid sock\n");
return NULL;
}
return m_sockinfo[sock]->s_ip;
}
const char * tcp_stream::dst_ip(int sock) {
if (sock == -1) sock = m_sock;
if (m_sockinfo.find(sock) == m_sockinfo.end()) {
LOG("error: (dst_ip) invalid sock\n");
return NULL;
}
return m_sockinfo[sock]->d_ip;
}
int tcp_stream::src_port(int sock) {
if (sock == -1) sock = m_sock;
if (m_sockinfo.find(sock) == m_sockinfo.end()) {
LOG("error: (src_port) invalid sock\n");
return -1;
}
return m_sockinfo[sock]->s_port;
}
int tcp_stream::dst_port(int sock) {
if (sock == -1) sock = m_sock;
if (m_sockinfo.find(sock) == m_sockinfo.end()) {
LOG("error: (dst_port) invalid sock\n");
return -1;
}
return m_sockinfo[sock]->d_port;
}
////////////////////////////////////////////////////////////////////////////////