-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathethtap.cpp
More file actions
461 lines (433 loc) · 11.4 KB
/
ethtap.cpp
File metadata and controls
461 lines (433 loc) · 11.4 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
/*
DCNet access point services.
Copyright (C) 2025 Flyinghead <flyinghead.github@gmail.com>
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 <https://www.gnu.org/licenses/>.
*/
#include <stdio.h>
#include <stdlib.h>
#include <cerrno>
#include <fcntl.h>
#include <error.h>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/select.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <arpa/inet.h>
#include <linux/if_tun.h>
#include <pwd.h>
#include <grp.h>
#include <signal.h>
#include <sys/wait.h>
#include <string>
#include <cassert>
#include <ctime>
constexpr int MAX_CONNECTIONS = 64;
constexpr time_t READ_TIMEOUT = 35 * 60;
int child_pipe = -1;
std::string remoteEndpoint;
const char *dnsmasq_conf = "dnsmasq.conf";
const char *start_ip = "172.20.1.0";
bool setNonBlocking(int fd)
{
int flags = fcntl(fd, F_GETFL, 0);
if (flags == -1)
flags = 0;
flags |= O_NONBLOCK;
if (fcntl(fd, F_SETFL, flags) != 0) {
perror("fcntl(O_NONBLOCK)");
return false;
}
return true;
}
void startDnsmasq(const std::string& ifname, const std::string& ipaddr)
{
// fork twice to keep an intermediate child with su privileges,
// that can kill dnsmasq on exit.
int pipefd[2];
if (pipe(pipefd)) {
perror("pipe");
return;
}
int childpid = fork();
if (childpid < 0) {
perror("fork");
close(pipefd[0]);
close(pipefd[1]);
return;
}
if (childpid > 0)
{
// close the read end
close(pipefd[0]);
// save the write end
child_pipe = pipefd[1];
// parent is done
return;
}
// close the write end
close(pipefd[1]);
// fork dnsmasq
int dnsmasq_pid = fork();
if (dnsmasq_pid < 0) {
perror("fork(dnsmasq)");
exit(1);
}
if (dnsmasq_pid == 0)
{
// grandchild execs dnsmasq
char confarg[512];
snprintf(confarg, sizeof(confarg), "--conf-file=%s", dnsmasq_conf);
execl("/usr/sbin/dnsmasq", "dnsmasq",
confarg,
("--interface=" + ifname).c_str(),
("--dhcp-range=" + ipaddr + "," + ipaddr).c_str(),
nullptr);
perror("execl");
exit(1);
}
// child waits on the pipe then kills dnsmasq
char c;
ssize_t l = read(pipefd[0], &c, 1);
(void)l;
kill(dnsmasq_pid, SIGTERM);
waitpid(dnsmasq_pid, nullptr, 0);
exit(0);
}
void stopDnsmasq()
{
if (child_pipe != 1)
close(child_pipe);
}
void handleProlog(int sock)
{
timeval tv {};
tv.tv_sec = 3;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
uint16_t size;
uint8_t buf[6];
if (read(sock, &size, sizeof(size)) != sizeof(size)
|| size != sizeof(buf)
|| read(sock, buf, sizeof(buf)) != sizeof(buf)
|| memcmp(buf, "DCNET", 5)) {
fprintf(stderr, "Invalid prolog or timeout\n");
exit(1);
}
if (buf[5] != 1) {
fprintf(stderr, "Unknown protocol version: %d\n", buf[5]);
exit(1);
}
// reset recv timeout to default
tv.tv_sec = 0;
setsockopt(sock, SOL_SOCKET, SO_RCVTIMEO, &tv, sizeof(tv));
}
static const char *getDate()
{
time_t now;
time(&now);
char *nowstr = ctime(&now);
nowstr[strlen(nowstr) - 1] = '\0';
return nowstr;
}
static void logend() {
printf("[%s] Link to %s closed\n", getDate(), remoteEndpoint.c_str());
}
void handleConnection(int sock)
{
handleProlog(sock);
printf("[%s] Connection from %s\n", getDate(), remoteEndpoint.c_str());
int tap_fd = open("/dev/net/tun", O_RDWR | O_CLOEXEC);
if (tap_fd < 0)
error(-1, errno, "/dev/net/tun");
// Set tap mode
ifreq ifr {};
ifr.ifr_flags = IFF_TAP | IFF_NO_PI;
if (ioctl(tap_fd, TUNSETIFF, &ifr))
error(-1, errno, "ioctl(TUNSETIFF)");
// Set interface IP address
std::string ifname(ifr.ifr_name);
if (ifname.substr(0, 3) != "tap" || !isdigit(ifname[3])) {
fprintf(stderr, "Unknown interface %s. Aborting\n", ifname.c_str());
exit(1);
}
int ifnum = atoi(&ifname[3]);
if (ifnum >= MAX_CONNECTIONS) {
fprintf(stderr, "Maximum BBA connections reached: %d\n", ifnum);
exit(1);
}
in_addr inaddr;
inet_aton(start_ip, &inaddr);
inaddr.s_addr = htonl(ntohl(inaddr.s_addr) + ifnum * 2);
std::string ipaddr = inet_ntoa(inaddr);
printf("%s: interface %s - IP address %s\n", remoteEndpoint.c_str(), ifname.c_str(), ipaddr.c_str());
sockaddr_in *ifaddr = (sockaddr_in *)&ifr.ifr_addr;
ifaddr->sin_family = AF_INET;
inet_pton(AF_INET, ipaddr.c_str(), &ifaddr->sin_addr);
// Create a dummy IPv4 socket because these ioctls must be done on a socket.
int dummy = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
if (ioctl(dummy, SIOCSIFADDR, &ifr))
error(-1, errno, "ioctl(SIOCSIFADDR)");
// Set network mask
ifaddr = (sockaddr_in *)&ifr.ifr_netmask;
ifaddr->sin_family = AF_INET;
inet_pton(AF_INET, "255.255.255.254", &ifaddr->sin_addr);
if (ioctl(dummy, SIOCSIFNETMASK, &ifr))
error(-1, errno, "ioctl(SIOCSIFNETMASK)");
// Set interface up
ioctl(dummy, SIOCGIFFLAGS, &ifr);
ifr.ifr_flags |= (IFF_UP | IFF_RUNNING);
if (ioctl(dummy, SIOCSIFFLAGS, &ifr))
error(-1, errno, "ioctl(SIOCSIFFLAGS)");
close(dummy);
ipaddr[ipaddr.length() - 1] += 1;
startDnsmasq(ifname, ipaddr);
// Leave superuser mode
uid_t gid = 65534;
group *grp = getgrnam("nogroup");
if (grp != nullptr)
gid = grp->gr_gid;
if (setgid(gid))
error(-1, errno, "setgid");
uid_t uid = 65534;
passwd *user = getpwnam("nobody");
if (user != nullptr)
uid = user->pw_uid;
if (setuid(uid))
error(-1, errno, "setuid");
atexit(logend);
setNonBlocking(tap_fd);
setNonBlocking(sock);
uint8_t inbuf[1600];
uint8_t outbuf[1600];
unsigned inbuflen = 0;
unsigned outbuflen = 0;
time_t last_sock_read = time(NULL);
for (;;)
{
fd_set readfds;
FD_ZERO(&readfds);
if (inbuflen < sizeof(inbuf))
FD_SET(sock, &readfds);
if (outbuflen == 0)
// Don't read from tap until the current frame is sent out
FD_SET(tap_fd, &readfds);
fd_set writefds;
FD_ZERO(&writefds);
if (inbuflen > 2)
{
// Only write full frames to tap
uint16_t framelen = *(uint16_t *)&inbuf[0];
assert(framelen + 2u < sizeof(inbuf));
if (inbuflen >= framelen + 2u)
FD_SET(tap_fd, &writefds);
}
if (outbuflen > 0)
FD_SET(sock, &writefds);
int nfds = (sock > tap_fd ? sock : tap_fd) + 1;
timeval tv;
tv.tv_sec = READ_TIMEOUT - (time(NULL) - last_sock_read);
if (tv.tv_sec <= 0) {
fprintf(stderr, "No data received for 35 min. Closing connection\n");
break;
}
tv.tv_usec = 0;
if (select(nfds, &readfds, &writefds, nullptr, &tv) == -1)
{
if (errno == EINTR)
continue;
perror("select");
break;
}
if (FD_ISSET(tap_fd, &readfds))
{
ssize_t ret = read(tap_fd, outbuf + 2, sizeof(outbuf) - 2u);
if (ret < 0)
{
if (errno != EINTR && errno != EWOULDBLOCK) {
perror("read(tap)");
break;
}
ret = 0;
}
else if (ret == 0) {
break;
}
if (ret > 0)
{
uint8_t mac0 = outbuf[2];
if ((mac0 & 1) && mac0 != 0xff) {
//printf("Out frame: multicast filtered\n");
}
else
{
//printf("Out frame: %zd\n", ret);
*(uint16_t *)&outbuf[0] = ret;
outbuflen = ret + 2;
FD_SET(sock, &writefds);
}
}
}
if (FD_ISSET(sock, &readfds))
{
ssize_t ret = read(sock, inbuf + inbuflen, sizeof(inbuf) - (size_t)inbuflen);
if (ret < 0)
{
if (errno != EINTR && errno != EWOULDBLOCK) {
perror("read(socket)");
break;
}
ret = 0;
}
else if (ret == 0) {
//fprintf(stderr, "socket read EOF\n");
break;
}
if (ret > 0) {
inbuflen += ret;
FD_SET(tap_fd, &writefds);
last_sock_read = time(NULL);
}
}
if (FD_ISSET(tap_fd, &writefds))
{
uint16_t framelen = *(uint16_t *)&inbuf[0];
if (inbuflen >= framelen + 2u)
{
//printf("In frame: %d\n", framelen);
ssize_t ret = write(tap_fd, inbuf + 2, framelen);
if (ret < 0) {
if (errno != EINTR && errno != EWOULDBLOCK) {
perror("write(tap)");
break;
}
ret = 0;
}
if (ret > 0)
{
if (ret != framelen)
fprintf(stderr, "WARNING: tap write truncated %d -> %zd\n", framelen, ret);
inbuflen -= framelen + 2;
if (inbuflen > 0)
memmove(inbuf, inbuf + framelen + 2, (size_t)inbuflen);
}
}
}
if (FD_ISSET(sock, &writefds))
{
ssize_t ret = write(sock, outbuf, (size_t)outbuflen);
if (ret < 0) {
if (errno == EINTR && errno != EWOULDBLOCK) {
perror("write(socket)");
break;
}
ret = 0;
}
if (ret > 0)
{
//printf("Out sent(%d) -> %zd\n", outbuflen, ret);
outbuflen -= ret;
if (outbuflen > 0)
memmove(outbuf, outbuf + ret, (size_t)outbuflen);
}
}
/*
int i = read(tap_fd, buf, sizeof(buf));
if (i < 0)
error(-1, errno, "read(tap)");
if (i <= 0)
break;
printf("Frame: dest %02x:%02x:%02x:%02x:%02x:%02x "
"src %02x:%02x:%02x:%02x:%02x:%02x, payload %d bytes, total %d bytes\n",
buf[0], buf[1], buf[2], buf[3], buf[4], buf[5],
buf[6], buf[7], buf[8], buf[9], buf[10], buf[11],
*(uint16_t *)&buf[12], i);
*/
}
close(sock);
close(tap_fd);
stopDnsmasq();
exit(0);
}
int main(int argc, char *argv[])
{
setvbuf(stdout, nullptr, _IOLBF, BUFSIZ);
signal(SIGCHLD, SIG_IGN);
int opt;
while ((opt = getopt(argc, argv, "d:i:")) != -1) {
switch (opt) {
case 'd':
dnsmasq_conf = optarg;
break;
case 'i':
start_ip = optarg;
break;
}
}
#ifdef IPV4_ONLY
int ssock = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
sockaddr_in serveraddr{};
serveraddr.sin_family = AF_INET;
serveraddr.sin_addr.s_addr = INADDR_ANY;
serveraddr.sin_port = htons(7655);
#else
int ssock = socket(AF_INET6, SOCK_STREAM, 0);
// allow IPv4 too
const int v6only = 0;
setsockopt(ssock, IPPROTO_IPV6, IPV6_V6ONLY, (const char *)&v6only, sizeof(v6only));
sockaddr_in6 serveraddr = { AF_INET6, htons(7655), 0, in6addr_any, 0 };
#endif
const int reuseAddr = 1;
setsockopt(ssock, SOL_SOCKET, SO_REUSEADDR, (const char *)&reuseAddr, sizeof(reuseAddr));
if (::bind(ssock, (sockaddr *)&serveraddr, sizeof(serveraddr)) < 0) {
close(ssock);
error(1, errno, "bind");
}
listen(ssock, 5);
for (;;)
{
sockaddr_storage src_addr;
socklen_t addr_len = sizeof(src_addr);
int sock = accept(ssock, (sockaddr *)&src_addr, &addr_len);
if (sock < 0) {
perror("accept");
break;
}
#ifdef IPV4_ONLY
sockaddr_in *ipv4addr = (sockaddr_in *)&src_addr;
remoteEndpoint = inet_ntoa(ipv4addr->sin_addr) + std::string(":") + std::to_string(ntohs(ipv4addr->sin_port));
#else
char hostname[255];
int port;
if (src_addr.ss_family == AF_INET) {
inet_ntop(AF_INET, &((sockaddr_in *)&src_addr)->sin_addr, hostname, sizeof(hostname));
port = ((sockaddr_in *)&src_addr)->sin_port;
}
else {
inet_ntop(AF_INET6, &((sockaddr_in6 *)&src_addr)->sin6_addr, hostname, sizeof(hostname));
if (!strncmp(hostname, "::ffff:", 7))
// Get rid of the IPv6 prefix for IPv4-mapped addresses
memmove(hostname, hostname + 7, strlen(hostname) + 1 - 7);
port = ((sockaddr_in6 *)&src_addr)->sin6_port;
}
remoteEndpoint = hostname + std::string(":") + std::to_string(ntohs(port));
#endif
if (fork() == 0) {
close(ssock);
handleConnection(sock);
}
close(sock);
}
close(ssock);
return 0;
}