5 #include <sys/socket.h>
7 #include <netinet/in.h>
13 #include <linux/if_tun.h>
21 #if __has_include(<sys/random.h>)
22 #include <sys/random.h>
24 int getrandom(void* buf, size_t len, unsigned int flags) {
25 FILE* f = fopen("/dev/urandom", "r");
26 int res = fread(buf, len, 1, f);
33 // Note that ordering of the first three uint16_ts must match the wire!
36 uint16_t frag_flags: 3,
41 static_assert(sizeof(struct pkt_hdr) == 8);
43 // Have to leave room to add a TCP header plus above header (after dropping IP header)
44 #define PACKET_READ_OFFS sizeof(pkt_hdr)
45 #define PACKET_READ_SIZE (1500 - PACKET_READ_OFFS)
47 static int tun_alloc(char *dev, const char* local_ip, const char* remote_ip, int queues, int *fds)
56 memset(&ifr, 0, sizeof(ifr));
58 /* Flags: IFF_TUN - TUN device (no Ethernet headers)
59 * IFF_TAP - TAP device
61 * IFF_NO_PI - Do not provide packet information
63 ifr.ifr_flags = IFF_TUN | IFF_NO_PI | IFF_MULTI_QUEUE;
64 strncpy(ifr.ifr_name, dev, IFNAMSIZ);
66 for (i = 0; i < queues; i++) {
67 if((fd = open("/dev/net/tun", O_RDWR)) < 0)
69 err = ioctl(fd, TUNSETIFF, (void *) &ifr);
77 sprintf(buf, "ip link set dev %s mtu %ld", dev, PACKET_READ_SIZE - 20);
81 sprintf(buf, "ip addr add %s/32 dev %s", local_ip, dev);
85 sprintf(buf, "ip link set %s up", dev);
89 sprintf(buf, "ip route add %s/32 dev %s", remote_ip, dev);
95 for (--i; i >= 0; i--)
100 static int check_ip_header(const unsigned char* buf, ssize_t buf_len, int16_t expected_type, struct pkt_hdr *gen_hdr) {
106 if ((buf[0] & 0xf0) != (4 << 4)) {
111 uint8_t num_words = buf[0] & 0xf;
112 int header_size = num_words * 4;
113 if (header_size < 20) {
114 fprintf(stderr, "Invalid IPv4 IHL size (%d)\n", header_size);
118 /*if ((((uint16_t)buf[2]) << 8 | buf[3]) != buf_len) {
119 //fprintf(stderr, "Packet len %u != %ld\n", ((uint16_t)buf[2]) << 8 | buf[3], buf_len);
123 if (expected_type > 0 && buf[9] != expected_type) {
124 fprintf(stderr, "Packet type %u, not %u\n", buf[9], expected_type);
129 memcpy(gen_hdr, buf + 2, 6); // len, id, frag offset
130 gen_hdr->proto = buf[9];
131 gen_hdr->padding = 0;
137 void print_packet(const unsigned char* buf, ssize_t buf_len) {
138 for (ssize_t i = 0; i < buf_len; ) {
139 for (int j = 0; i < buf_len && j < 20; i++, j++)
140 fprintf(stderr, "%02x", buf[i]);
141 fprintf(stderr, "\n");
145 static uint32_t data_checksum(const unsigned char* buf, size_t len) {
151 sum += (*buf++) << 8;
152 if (sum & 0x80000000)
153 sum = (sum & 0xFFFF) + (sum >> 16);
163 static uint16_t finalize_data_checksum(uint32_t sum) {
165 sum = (sum & 0xFFFF) + (sum >> 16);
167 return (uint16_t)(~sum);
170 static uint16_t tcp_checksum(const unsigned char* buff, size_t len, in_addr_t src_addr, in_addr_t dest_addr)
172 uint16_t *ip_src = (uint16_t*)&src_addr, *ip_dst = (uint16_t*)&dest_addr;
173 uint32_t sum = data_checksum(buff, len);
179 sum += htons(IPPROTO_TCP);
182 return finalize_data_checksum(sum);
185 static std::atomic<uint32_t> highest_recvd_seq(0), cur_seq(0);
186 static std::atomic<uint16_t> local_port(0);
187 static uint16_t remote_port;
188 static bool are_server;
190 static void build_tcp_header(unsigned char* buf, uint32_t len, int syn, int synack, in_addr_t src_addr, in_addr_t dest_addr) {
191 buf[0 ] = local_port >> 8; // src port
192 buf[1 ] = local_port; // src port
193 buf[2 ] = remote_port >> 8; // dst port
194 buf[3 ] = remote_port; // dst port
196 uint32_t seq = cur_seq.fetch_add((syn || synack) ? 1 : len, std::memory_order_acq_rel);
197 buf[4 ] = seq >> (8 * 3); // SEQ
198 buf[5 ] = seq >> (8 * 2); // SEQ
199 buf[6 ] = seq >> (8 * 1); // SEQ
200 buf[7 ] = seq >> (8 * 0); // SEQ
202 uint32_t their_seq = highest_recvd_seq.load(std::memory_order_relaxed);
203 buf[8 ] = their_seq >> (8 * 3); // ACK
204 buf[9 ] = their_seq >> (8 * 2); // ACK
205 buf[10] = their_seq >> (8 * 1); // ACK
206 buf[11] = their_seq >> (8 * 0); // ACK
208 bool longpkt = syn || synack;
209 buf[12] = (longpkt ? 6 : 5) << 4; // data offset
211 buf[13] = 1 << 1; // SYN
213 buf[13] = (1 << 1) | (1 << 4); // SYN + ACK
215 buf[13] = 1 << 4; // ACK
217 buf[13] = 3 << 3; // PSH + ACK
218 buf[14] = 0xff; // Window Size
219 buf[15] = 0xff; // Window Size
221 buf[16] = 0x00; // Checksum
222 buf[17] = 0x00; // Checksum
223 buf[18] = 0x00; // URG Pointer
224 buf[19] = 0x00; // URG Pointer
227 buf[20] = 0x01; // NOP
228 buf[21] = 0x03; // Window Scale
229 buf[22] = 0x03; // Window Scale Option Length
230 buf[23] = 0x0e; // 1GB Window Size (0xffff << 0x0e)
233 uint16_t checksum = tcp_checksum(buf, len + 20 + (longpkt ? 4 : 0), src_addr, dest_addr);
234 buf[16] = checksum; // Checksum
235 buf[17] = checksum >> 8; // Checksum
238 static void build_ip_header(unsigned char* buf, struct pkt_hdr hdr, const in_addr_t& src_addr, const in_addr_t& dest_addr) {
239 buf[0 ] = (4 << 4) | 5; // IPv4 + IHL of 5 (20 bytes)
240 buf[1 ] = 0; // DSCP 0 + ECN 0
241 memcpy(buf + 2, &hdr, 6); // length, identification, flags, and offset
242 buf[8 ] = 255; // TTL
243 buf[9 ] = hdr.proto; // Protocol Number
244 buf[10] = 0; // Checksum
245 buf[11] = 0; // Checksum
247 memcpy(buf + 12, &src_addr, 4);
248 memcpy(buf + 16, &dest_addr, 4);
250 uint16_t checksum = finalize_data_checksum(data_checksum(buf, 20));
252 buf[11] = checksum >> 8;
255 const signed char p_util_hexdigit[256] =
256 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
257 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
258 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
259 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
260 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
261 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
262 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
263 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
264 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
265 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
266 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
267 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
268 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
269 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
270 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
271 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
273 uint32_t hex_to_num(const unsigned char* buf) {
274 const unsigned char* pbegin = buf;
275 while (p_util_hexdigit[*buf] != -1)
279 unsigned char* p1 = (unsigned char*)&res;
280 unsigned char* pend = p1 + 4;
281 while (buf >= pbegin && p1 < pend) {
282 *p1 = p_util_hexdigit[*buf--];
284 *p1 |= ((unsigned char)p_util_hexdigit[*buf--] << 4);
292 #define TUN_IF_COUNT 4
294 static int fd[TUN_IF_COUNT];
295 static struct sockaddr_in dest;
296 static in_addr_t src, tun_src, tun_dest;
297 static uint64_t tcp_init_magic;
299 #define PENDING_MESSAGES_BUFF_SIZE (0x800)
300 #define THREAD_POLL_SLEEP_MICS 250
301 struct MessageQueue {
302 std::tuple<sockaddr_in, std::array<unsigned char, PACKET_READ_SIZE + PACKET_READ_OFFS>, ssize_t> messagesPendingRingBuff[PENDING_MESSAGES_BUFF_SIZE];
303 std::atomic<uint16_t> nextPendingMessage, nextUndefinedMessage;
304 MessageQueue() : nextPendingMessage(0), nextUndefinedMessage(0) {}
305 MessageQueue(MessageQueue&& q) =delete;
306 MessageQueue(MessageQueue& q) =delete;
309 static MessageQueue tcp_to_tun_queue;
310 static std::chrono::steady_clock::time_point last_ack_recv;
312 static void tcp_to_tun() {
313 unsigned char buf[PACKET_READ_SIZE + PACKET_READ_OFFS];
314 struct sockaddr_in pkt_src;
315 memset(&pkt_src, 0, sizeof(pkt_src));
318 socklen_t hostsz = sizeof(pkt_src);
319 ssize_t nread = recvfrom(fdr, buf, sizeof(buf), 0, (struct sockaddr*)&pkt_src, &hostsz);
321 fprintf (stderr, "Failed to read tcp raw sock\n");
325 if (tcp_to_tun_queue.nextPendingMessage == (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
328 auto& new_msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextUndefinedMessage];
329 std::get<0>(new_msg) = pkt_src;
330 memcpy(std::get<1>(new_msg).data(), buf, nread);
331 std::get<2>(new_msg) = nread;
333 tcp_to_tun_queue.nextUndefinedMessage = (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
337 static void tcp_to_tun_queue_process() {
339 while (tcp_to_tun_queue.nextUndefinedMessage == tcp_to_tun_queue.nextPendingMessage) {
340 std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
343 auto& msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextPendingMessage];
345 const sockaddr_in& pkt_src = std::get<0>(msg);
346 unsigned char* buf = std::get<1>(msg).data();
347 ssize_t nread = std::get<2>(msg);
349 int header_size = check_ip_header(buf, nread, 0x06, NULL); // Only support TCP
353 if (nread - header_size < 20) {
354 fprintf(stderr, "Short TCP packet\n");
358 unsigned char* tcp_buf = buf + header_size;
360 if (((tcp_buf[2] << 8) | tcp_buf[3]) != local_port) continue;
362 bool syn = tcp_buf[13] & (1 << 1);
363 bool ack = tcp_buf[13] & (1 << 4);
365 if (are_server && syn && !ack) {
366 // We're a server and just got a client
367 if (tcp_buf[4 ] != uint8_t(tcp_init_magic >> (7 * 8)) ||
368 tcp_buf[5 ] != uint8_t(tcp_init_magic >> (6 * 8)) ||
369 tcp_buf[6 ] != uint8_t(tcp_init_magic >> (5 * 8)) ||
370 tcp_buf[7 ] != uint8_t(tcp_init_magic >> (4 * 8)) ||
371 tcp_buf[8 ] != uint8_t(tcp_init_magic >> (3 * 8)) ||
372 tcp_buf[9 ] != uint8_t(tcp_init_magic >> (2 * 8)) ||
373 tcp_buf[10] != uint8_t(tcp_init_magic >> (1 * 8)) ||
374 tcp_buf[11] != uint8_t(tcp_init_magic >> (0 * 8)))
377 fprintf(stderr, "Got SYN, sending SYNACK\n");
378 remote_port = (tcp_buf[0] << 8) | tcp_buf[1];
382 if (((tcp_buf[0] << 8) | tcp_buf[1]) != remote_port) continue;
383 if (pkt_src.sin_addr.s_addr != dest.sin_addr.s_addr) continue;
385 uint8_t num_words = (tcp_buf[12] & 0xf0) >> 4;
386 int tcp_header_size = num_words * 4;
387 if (tcp_header_size < 20) {
388 fprintf(stderr, "Invalid TCP header size (%d)\n", tcp_header_size);
392 highest_recvd_seq = ((((uint32_t)tcp_buf[4]) << (8 * 3)) |
393 (((uint32_t)tcp_buf[5]) << (8 * 2)) |
394 (((uint32_t)tcp_buf[6]) << (8 * 1)) |
395 (((uint32_t)tcp_buf[7]) << (8 * 0))) +
396 (syn ? 1 : nread - header_size - tcp_header_size);
399 last_ack_recv = std::chrono::steady_clock::now();
401 if (are_server && syn && !ack) {
402 build_tcp_header(tcp_buf, 0, 0, 1, src, dest.sin_addr.s_addr);
404 ssize_t res = sendto(fdr, tcp_buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
407 fprintf(stderr, "Failed to send SYNACK with err %d (%s)\n", err, strerror(err));
410 if (nread < (ssize_t)(tcp_header_size + header_size + sizeof(struct pkt_hdr))) continue;
412 memcpy(&hdr, tcp_buf + tcp_header_size, sizeof(struct pkt_hdr));
413 tcp_buf += tcp_header_size + sizeof(struct pkt_hdr) - 20; // IPv4 header is 20 bytes
415 // Replace TCP + pkt_hdr with IPv4 header
416 build_ip_header(tcp_buf, hdr, tun_dest, tun_src);
418 write(fd[0], tcp_buf, nread - tcp_header_size - header_size + 20 + 8);
420 } while ((tcp_to_tun_queue.nextPendingMessage = (tcp_to_tun_queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
423 static std::atomic_int tun_if_thread(0), tun_if_process_thread(0);
424 static std::atomic_bool pause_tun_read_reinit_tcp(false);
425 static MessageQueue tun_to_tcp_queue[TUN_IF_COUNT];
427 static void tun_to_tcp() {
428 unsigned char buf[PACKET_READ_SIZE];
430 int thread = tun_if_thread.fetch_add(1);
431 MessageQueue& queue = tun_to_tcp_queue[thread];
434 ssize_t nread = read(fd[thread], buf, sizeof(buf));
435 if (pause_tun_read_reinit_tcp)
439 fprintf (stderr, "Failed to read tun if\n");
443 if (queue.nextPendingMessage == (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
446 auto& new_msg = queue.messagesPendingRingBuff[queue.nextUndefinedMessage];
447 memcpy(std::get<1>(new_msg).data() + PACKET_READ_OFFS, buf, nread);
448 std::get<2>(new_msg) = nread;
450 queue.nextUndefinedMessage = (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
454 static void tun_to_tcp_queue_process() {
455 int thread = tun_if_process_thread.fetch_add(1);
456 MessageQueue& queue = tun_to_tcp_queue[thread];
459 while (queue.nextUndefinedMessage == queue.nextPendingMessage) {
460 std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
462 if (pause_tun_read_reinit_tcp)
465 auto& msg = queue.messagesPendingRingBuff[queue.nextPendingMessage];
467 unsigned char* buf = std::get<1>(msg).data();
468 ssize_t nread = std::get<2>(msg);
471 int header_size = check_ip_header(buf + PACKET_READ_OFFS, nread, -1, &hdr); // Any paket type is okay
472 if (header_size < 20)
475 if (header_size > nread) {
476 fprintf(stderr, "Short packet\n");
480 if ((size_t)nread > 1500 - 20 - sizeof(struct pkt_hdr)) { // Packets must fit in 1500 bytes with a TCP and packet hdr
481 fprintf(stderr, "Long packet\n");
485 unsigned char* tcp_start = buf + PACKET_READ_OFFS + header_size - 20 - sizeof(struct pkt_hdr);
486 memcpy(tcp_start + 20, &hdr, sizeof(struct pkt_hdr));
487 build_tcp_header(tcp_start, nread - header_size + sizeof(struct pkt_hdr), 0, 0, src, dest.sin_addr.s_addr);
489 ssize_t res = sendto(fdr, tcp_start, nread + 20 + sizeof(struct pkt_hdr) - header_size, 0, (struct sockaddr*)&dest, sizeof(dest));
492 fprintf(stderr, "Failed to send with err %d (%s)\n", err, strerror(err));
495 } while ((queue.nextPendingMessage = (queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
500 // Send SYN and SYN/ACK
504 if (local_port) // Doing a re-init
505 pause_tun_read_reinit_tcp = true;
507 uint16_t local_port_tmp = 0;
508 while (local_port_tmp < 1024)
509 assert(getrandom(&local_port_tmp, sizeof(local_port_tmp), 0) == sizeof(local_port_tmp));
511 local_port = local_port_tmp;
514 uint32_t starting_ack = 0, starting_seq = 0;
515 memcpy(&starting_ack, &tcp_init_magic, 4);
516 memcpy(&starting_seq, ((const unsigned char*)&tcp_init_magic) + 4, 4);
517 highest_recvd_seq = starting_ack;
518 cur_seq = starting_seq;
520 if (!pause_tun_read_reinit_tcp) { // Not doing a re-init
521 std::thread t(&tcp_to_tun);
522 std::thread t2(&tcp_to_tun_queue_process);
527 unsigned char buf[1500];
529 build_tcp_header(buf, 0, 1, 0, src, dest.sin_addr.s_addr);
530 ssize_t res = sendto(fdr, buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
533 fprintf(stderr, "Failed to send initial SYN with err %d (%s)\n", err, strerror(err));
539 for (i = 0; i < 1000 && highest_recvd_seq == starting_ack; i++)
540 std::this_thread::sleep_for(std::chrono::milliseconds(10));
541 if (i == 1000) // Will come back in 10 seconds
545 fprintf(stderr, "Got SYNACK, sending ACK and starting tun listen\n");
547 build_tcp_header(buf, 0, 0, 0, src, dest.sin_addr.s_addr);
548 ssize_t res = sendto(fdr, buf, 20, 0, (struct sockaddr*)&dest, sizeof(dest));
551 fprintf(stderr, "Failed to send initial ACK with err %d (%s)\n", err, strerror(err));
556 if (pause_tun_read_reinit_tcp) {
557 pause_tun_read_reinit_tcp = false;
559 for (int i = 0; i < TUN_IF_COUNT; i++) {
560 std::thread t3(&tun_to_tcp);
561 std::thread t4(&tun_to_tcp_queue_process);
570 int main(int argc, char* argv[]) {
571 assert(argc > 1 && "Need tun name");
572 assert(argc > 2 && "Need tun remote host");
573 assert(argc > 3 && "Need tun local host");
574 assert(argc > 4 && "Need server port");
575 assert(argc > 5 && "Need shared secret");
576 assert(argc > 6 && "Need mode (client or server)");
577 assert(argc > 7 && "Need src host");
578 if (std::string(argv[6]) == std::string("client"))
579 assert(argc > 8 && "Need dest host");
581 assert(std::string(argv[6]) == std::string("client") || std::string(argv[6]) == std::string("server"));
582 are_server = (std::string(argv[6]) == std::string("server"));
585 // Parse args into variables
588 char tun_name[IFNAMSIZ];
590 memset(tun_name, 0, sizeof(tun_name));
591 strcpy(tun_name, argv[1]);
593 tun_dest = inet_addr(argv[2]);
594 tun_src = inet_addr(argv[3]);
597 local_port = atoi(argv[4]);
600 // Get local port in do_init() so that we pick a new one on reload
601 remote_port = atoi(argv[4]);
604 tcp_init_magic = atoll(argv[5]);
606 src = inet_addr(argv[7]);
608 memset(&dest, 0, sizeof(dest));
610 dest.sin_family = AF_INET;
611 dest.sin_addr.s_addr = inet_addr(argv[8]);
615 // Create tun and bind to sockets...
618 if (tun_alloc(tun_name, argv[3], argv[2], TUN_IF_COUNT, fd) != 0) {
619 fprintf(stderr, "Failed to alloc tun if\n");
623 fdr = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
625 fprintf(stderr, "Failed to get raw socket\n");
634 std::this_thread::sleep_for(std::chrono::seconds(15));
635 if (!are_server && last_ack_recv < std::chrono::steady_clock::now() - std::chrono::seconds(15)) {