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 static int tun_alloc(char *dev, int queues, int *fds)
41 memset(&ifr, 0, sizeof(ifr));
43 /* Flags: IFF_TUN - TUN device (no Ethernet headers)
44 * IFF_TAP - TAP device
46 * IFF_NO_PI - Do not provide packet information
48 ifr.ifr_flags = IFF_TUN | IFF_NO_PI | IFF_MULTI_QUEUE;
49 strncpy(ifr.ifr_name, dev, IFNAMSIZ);
51 for (i = 0; i < queues; i++) {
52 if((fd = open("/dev/net/tun", O_RDWR)) < 0)
54 err = ioctl(fd, TUNSETIFF, (void *) &ifr);
63 for (--i; i >= 0; i--)
68 static int check_ip_header(const unsigned char* buf, ssize_t buf_len, uint8_t expected_type) {
74 if ((buf[0] & 0xf0) != (4 << 4)) {
79 uint8_t num_words = buf[0] & 0xf;
80 int header_size = num_words * 4;
81 if (header_size < 20) {
82 fprintf(stderr, "Invalid IPv4 IHL size (%d)\n", header_size);
86 if ((((uint16_t)buf[2]) << 8 | buf[3]) != buf_len) {
87 //fprintf(stderr, "Packet len %u != %ld\n", ((uint16_t)buf[2]) << 8 | buf[3], buf_len);
91 if (buf[9] != expected_type) {
92 fprintf(stderr, "Packet type %u, not %u\n", buf[9], expected_type);
99 void print_packet(const unsigned char* buf, ssize_t buf_len) {
100 for (ssize_t i = 0; i < buf_len; ) {
101 for (int j = 0; i < buf_len && j < 20; i++, j++)
102 fprintf(stderr, "%02x", buf[i]);
103 fprintf(stderr, "\n");
107 static uint32_t data_checksum(const unsigned char* buf, size_t len) {
113 sum += (*buf++) << 8;
114 if (sum & 0x80000000)
115 sum = (sum & 0xFFFF) + (sum >> 16);
125 static uint16_t finalize_data_checksum(uint32_t sum) {
127 sum = (sum & 0xFFFF) + (sum >> 16);
129 return (uint16_t)(~sum);
132 static uint16_t tcp_checksum(const unsigned char* buff, size_t len, in_addr_t src_addr, in_addr_t dest_addr)
134 uint16_t *ip_src = (uint16_t*)&src_addr, *ip_dst = (uint16_t*)&dest_addr;
135 uint32_t sum = data_checksum(buff, len);
141 sum += htons(IPPROTO_TCP);
144 return finalize_data_checksum(sum);
147 static std::atomic<uint32_t> highest_recvd_seq(0), cur_seq(0);
148 static std::atomic<uint16_t> local_port(0);
149 static uint16_t remote_port;
150 static bool are_server;
152 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) {
153 buf[0 ] = local_port >> 8; // src port
154 buf[1 ] = local_port; // src port
155 buf[2 ] = remote_port >> 8; // dst port
156 buf[3 ] = remote_port; // dst port
158 uint32_t seq = cur_seq.fetch_add((syn || synack) ? 1 : len, std::memory_order_acq_rel);
159 buf[4 ] = seq >> (8 * 3); // SEQ
160 buf[5 ] = seq >> (8 * 2); // SEQ
161 buf[6 ] = seq >> (8 * 1); // SEQ
162 buf[7 ] = seq >> (8 * 0); // SEQ
164 uint32_t their_seq = highest_recvd_seq.load(std::memory_order_relaxed);
165 buf[8 ] = their_seq >> (8 * 3); // ACK
166 buf[9 ] = their_seq >> (8 * 2); // ACK
167 buf[10] = their_seq >> (8 * 1); // ACK
168 buf[11] = their_seq >> (8 * 0); // ACK
170 bool longpkt = syn || synack;
171 buf[12] = (longpkt ? 6 : 5) << 4; // data offset
173 buf[13] = 1 << 1; // SYN
175 buf[13] = (1 << 1) | (1 << 4); // SYN + ACK
177 buf[13] = 1 << 4; // ACK
179 buf[13] = 3 << 3; // PSH + ACK
180 buf[14] = 0xff; // Window Size
181 buf[15] = 0xff; // Window Size
183 buf[16] = 0x00; // Checksum
184 buf[17] = 0x00; // Checksum
185 buf[18] = 0x00; // URG Pointer
186 buf[19] = 0x00; // URG Pointer
189 buf[20] = 0x01; // NOP
190 buf[21] = 0x03; // Window Scale
191 buf[22] = 0x03; // Window Scale Option Length
192 buf[23] = 0x0e; // 1GB Window Size (0xffff << 0x0e)
195 uint16_t checksum = tcp_checksum(buf, len + 20 + (longpkt ? 4 : 0), src_addr, dest_addr);
196 buf[16] = checksum; // Checksum
197 buf[17] = checksum >> 8; // Checksum
200 static void build_ip_header(unsigned char* buf, uint32_t len, uint8_t proto, const in_addr_t& src_addr, const in_addr_t& dest_addr) {
201 buf[0 ] = (4 << 4) | 5; // IPv4 + IHL of 5 (20 bytes)
202 buf[1 ] = 0; // DSCP 0 + ECN 0
203 buf[2 ] = (len + 20) >> 8; // Length
204 buf[3 ] = (len + 20); // Length
205 memset(buf + 4, 0, 4); // Identification and Fragment 0s
206 buf[6 ] = 1 << 6; // DF bit
207 buf[8 ] = 255; // TTL
208 buf[9 ] = proto; // Protocol Number
209 buf[10] = 0; // Checksum
210 buf[11] = 0; // Checksum
212 memcpy(buf + 12, &src_addr, 4);
213 memcpy(buf + 16, &dest_addr, 4);
215 uint16_t checksum = finalize_data_checksum(data_checksum(buf, 20));
217 buf[11] = checksum >> 8;
221 const signed char p_util_hexdigit[256] =
222 { -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
223 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
224 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
225 0,1,2,3,4,5,6,7,8,9,-1,-1,-1,-1,-1,-1,
226 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
227 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
228 -1,0xa,0xb,0xc,0xd,0xe,0xf,-1,-1,-1,-1,-1,-1,-1,-1,-1,
229 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
230 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
231 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
232 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
233 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
234 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
235 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
236 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,
237 -1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1, };
239 uint32_t hex_to_num(const unsigned char* buf) {
240 const unsigned char* pbegin = buf;
241 while (p_util_hexdigit[*buf] != -1)
245 unsigned char* p1 = (unsigned char*)&res;
246 unsigned char* pend = p1 + 4;
247 while (buf >= pbegin && p1 < pend) {
248 *p1 = p_util_hexdigit[*buf--];
250 *p1 |= ((unsigned char)p_util_hexdigit[*buf--] << 4);
258 #define TUN_IF_COUNT 4
260 static int fd[TUN_IF_COUNT];
261 static struct sockaddr_in dest;
262 static in_addr_t src, tun_src, tun_dest, ipip_src, ipip_dest;
263 static uint64_t tcp_init_magic;
265 #define PENDING_MESSAGES_BUFF_SIZE (0x3000)
266 #define PACKET_READ_SIZE 1500
267 #define THREAD_POLL_SLEEP_MICS 50
268 struct MessageQueue {
269 std::tuple<sockaddr_in, std::array<unsigned char, PACKET_READ_SIZE>, ssize_t> messagesPendingRingBuff[PENDING_MESSAGES_BUFF_SIZE];
270 std::atomic<uint16_t> nextPendingMessage, nextUndefinedMessage;
271 MessageQueue() : nextPendingMessage(0), nextUndefinedMessage(0) {}
272 MessageQueue(MessageQueue&& q) =delete;
273 MessageQueue(MessageQueue& q) =delete;
276 static MessageQueue tcp_to_tun_queue;
277 static std::chrono::steady_clock::time_point last_ack_recv;
279 static void tcp_to_tun() {
280 unsigned char buf[1500];
281 struct sockaddr_in pkt_src;
282 memset(&pkt_src, 0, sizeof(pkt_src));
285 socklen_t hostsz = sizeof(pkt_src);
286 ssize_t nread = recvfrom(fdr, buf, sizeof(buf), 0, (struct sockaddr*)&pkt_src, &hostsz);
288 fprintf (stderr, "Failed to read tcp raw sock\n");
292 if (tcp_to_tun_queue.nextPendingMessage == (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
295 auto& new_msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextUndefinedMessage];
296 std::get<0>(new_msg) = pkt_src;
297 memcpy(std::get<1>(new_msg).data(), buf, nread);
298 std::get<2>(new_msg) = nread;
300 tcp_to_tun_queue.nextUndefinedMessage = (tcp_to_tun_queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
304 static void tcp_to_tun_queue_process() {
306 while (tcp_to_tun_queue.nextUndefinedMessage == tcp_to_tun_queue.nextPendingMessage) {
307 std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
310 auto& msg = tcp_to_tun_queue.messagesPendingRingBuff[tcp_to_tun_queue.nextPendingMessage];
312 const sockaddr_in& pkt_src = std::get<0>(msg);
313 unsigned char* buf = std::get<1>(msg).data();
314 ssize_t nread = std::get<2>(msg);
316 int header_size = check_ip_header(buf, nread, 0x06); // Only support TCP
320 if (nread - header_size < 20) {
321 fprintf(stderr, "Short TCP packet\n");
325 unsigned char* tcp_buf = buf + header_size;
327 if (((tcp_buf[2] << 8) | tcp_buf[3]) != local_port) continue;
329 bool syn = tcp_buf[13] & (1 << 1);
330 bool ack = tcp_buf[13] & (1 << 4);
332 if (are_server && syn && !ack) {
333 // We're a server and just got a client
334 if (tcp_buf[4 ] != uint8_t(tcp_init_magic >> (7 * 8)) ||
335 tcp_buf[5 ] != uint8_t(tcp_init_magic >> (6 * 8)) ||
336 tcp_buf[6 ] != uint8_t(tcp_init_magic >> (5 * 8)) ||
337 tcp_buf[7 ] != uint8_t(tcp_init_magic >> (4 * 8)) ||
338 tcp_buf[8 ] != uint8_t(tcp_init_magic >> (3 * 8)) ||
339 tcp_buf[9 ] != uint8_t(tcp_init_magic >> (2 * 8)) ||
340 tcp_buf[10] != uint8_t(tcp_init_magic >> (1 * 8)) ||
341 tcp_buf[11] != uint8_t(tcp_init_magic >> (0 * 8)))
344 fprintf(stderr, "Got SYN, sending SYNACK\n");
345 remote_port = (tcp_buf[0] << 8) | tcp_buf[1];
349 if (((tcp_buf[0] << 8) | tcp_buf[1]) != remote_port) continue;
350 if (pkt_src.sin_addr.s_addr != dest.sin_addr.s_addr) continue;
352 uint8_t num_words = (tcp_buf[12] & 0xf0) >> 4;
353 int tcp_header_size = num_words * 4;
354 if (tcp_header_size < 20) {
355 fprintf(stderr, "Invalid TCP header size (%d)\n", tcp_header_size);
359 highest_recvd_seq = ((((uint32_t)tcp_buf[4]) << (8 * 3)) |
360 (((uint32_t)tcp_buf[5]) << (8 * 2)) |
361 (((uint32_t)tcp_buf[6]) << (8 * 1)) |
362 (((uint32_t)tcp_buf[7]) << (8 * 0))) +
363 (syn ? 1 : nread - header_size - tcp_header_size);
366 last_ack_recv = std::chrono::steady_clock::now();
368 if (are_server && syn && !ack) {
369 build_tcp_header(tcp_buf, 0, 0, 1, src, dest.sin_addr.s_addr);
371 ssize_t res = sendto(fdr, tcp_buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
374 fprintf(stderr, "Failed to send SYNACK with err %d (%s)\n", err, strerror(err));
377 tcp_buf += tcp_header_size - 20;
379 // Replace TCP with IPv4 header
380 //build_ip_header(tcp_buf, nread - tcp_header_size - header_size, 0x01, ipip_dest, ipip_src); // ICMP
381 build_ip_header(tcp_buf, nread - tcp_header_size - header_size, 0x11, ipip_dest, ipip_src); // UDP
383 build_ip_header(tcp_buf - 20, nread - tcp_header_size - header_size + 20, 0x04, tun_dest, tun_src);
385 write(fd[0], tcp_buf - 20, nread - tcp_header_size - header_size + 40);
387 } while ((tcp_to_tun_queue.nextPendingMessage = (tcp_to_tun_queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
390 static std::atomic_int tun_if_thread(0), tun_if_process_thread(0);
391 static std::atomic_bool pause_tun_read_reinit_tcp(false);
392 static MessageQueue tun_to_tcp_queue[TUN_IF_COUNT];
394 static void tun_to_tcp() {
395 unsigned char buf[PACKET_READ_SIZE];
397 int thread = tun_if_thread.fetch_add(1);
398 MessageQueue& queue = tun_to_tcp_queue[thread];
401 ssize_t nread = read(fd[thread], buf, sizeof(buf));
402 if (pause_tun_read_reinit_tcp)
406 fprintf (stderr, "Failed to read tun if\n");
410 if (queue.nextPendingMessage == (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE)
413 auto& new_msg = queue.messagesPendingRingBuff[queue.nextUndefinedMessage];
414 memcpy(std::get<1>(new_msg).data(), buf, nread);
415 std::get<2>(new_msg) = nread;
417 queue.nextUndefinedMessage = (queue.nextUndefinedMessage + 1) % PENDING_MESSAGES_BUFF_SIZE;
421 static void tun_to_tcp_queue_process() {
422 int thread = tun_if_process_thread.fetch_add(1);
423 MessageQueue& queue = tun_to_tcp_queue[thread];
426 while (queue.nextUndefinedMessage == queue.nextPendingMessage) {
427 std::this_thread::sleep_for(std::chrono::microseconds(THREAD_POLL_SLEEP_MICS));
429 if (pause_tun_read_reinit_tcp)
432 auto& msg = queue.messagesPendingRingBuff[queue.nextPendingMessage];
434 unsigned char* buf = std::get<1>(msg).data();
435 ssize_t nread = std::get<2>(msg);
437 int header_size = check_ip_header(buf, nread, 0x04); // Only support IPIP
441 int internal_header_size = check_ip_header(buf + header_size, nread - header_size, 0x11); // Only support UDP
442 //int internal_header_size = check_ip_header(buf + header_size, nread - header_size, 0x01); // Only support ICMP
443 if (internal_header_size < 0)
446 if (internal_header_size + header_size + 8 > nread) {
447 fprintf(stderr, "Short UDP-in-IPIP packet\n");
451 size_t tcp_start_offset = header_size + internal_header_size - 20;
452 build_tcp_header(buf + tcp_start_offset, nread - tcp_start_offset - 20, 0, 0, src, dest.sin_addr.s_addr);
454 ssize_t res = sendto(fdr, buf + tcp_start_offset, nread - tcp_start_offset, 0, (struct sockaddr*)&dest, sizeof(dest));
457 fprintf(stderr, "Failed to send with err %d (%s)\n", err, strerror(err));
460 } while ((queue.nextPendingMessage = (queue.nextPendingMessage + 1) % PENDING_MESSAGES_BUFF_SIZE) || true);
465 // Send SYN and SYN/ACK
469 if (local_port) // Doing a re-init
470 pause_tun_read_reinit_tcp = true;
472 uint16_t local_port_tmp = 0;
473 while (local_port_tmp < 1024)
474 assert(getrandom(&local_port_tmp, sizeof(local_port_tmp), 0) == sizeof(local_port_tmp));
476 local_port = local_port_tmp;
479 uint32_t starting_ack = 0, starting_seq = 0;
480 memcpy(&starting_ack, &tcp_init_magic, 4);
481 memcpy(&starting_seq, ((const unsigned char*)&tcp_init_magic) + 4, 4);
482 highest_recvd_seq = starting_ack;
483 cur_seq = starting_seq;
485 if (!pause_tun_read_reinit_tcp) { // Not doing a re-init
486 std::thread t(&tcp_to_tun);
487 std::thread t2(&tcp_to_tun_queue_process);
492 unsigned char buf[1500];
494 build_tcp_header(buf, 0, 1, 0, src, dest.sin_addr.s_addr);
495 ssize_t res = sendto(fdr, buf, 20 + 4, 0, (struct sockaddr*)&dest, sizeof(dest));
498 fprintf(stderr, "Failed to send initial SYN with err %d (%s)\n", err, strerror(err));
504 for (i = 0; i < 1000 && highest_recvd_seq == starting_ack; i++)
505 std::this_thread::sleep_for(std::chrono::milliseconds(10));
506 if (i == 1000) // Will come back in 10 seconds
510 fprintf(stderr, "Got SYNACK, sending ACK and starting tun listen\n");
512 build_tcp_header(buf, 0, 0, 0, src, dest.sin_addr.s_addr);
513 ssize_t res = sendto(fdr, buf, 20, 0, (struct sockaddr*)&dest, sizeof(dest));
516 fprintf(stderr, "Failed to send initial ACK with err %d (%s)\n", err, strerror(err));
521 if (pause_tun_read_reinit_tcp) {
522 pause_tun_read_reinit_tcp = false;
524 for (int i = 0; i < TUN_IF_COUNT; i++) {
525 std::thread t3(&tun_to_tcp);
526 std::thread t4(&tun_to_tcp_queue_process);
535 int main(int argc, char* argv[]) {
536 assert(argc > 1 && "Need tun name");
537 assert(argc > 2 && "Need tun remote host");
538 assert(argc > 3 && "Need tun local host");
539 assert(argc > 4 && "Need ipip remote host");
540 assert(argc > 5 && "Need ipip local host");
541 assert(argc > 6 && "Need server port");
542 assert(argc > 7 && "Need shared secret");
543 assert(argc > 8 && "Need mode (client or server)");
544 assert(argc > 9 && "Need src host");
545 if (std::string(argv[8]) == std::string("client"))
546 assert(argc > 10 && "Need dest host");
548 assert(std::string(argv[8]) == std::string("client") || std::string(argv[8]) == std::string("server"));
549 are_server = (std::string(argv[8]) == std::string("server"));
552 // Parse args into variables
555 char tun_name[IFNAMSIZ];
557 memset(tun_name, 0, sizeof(tun_name));
558 strcpy(tun_name, argv[1]);
560 tun_dest = inet_addr(argv[2]);
561 tun_src = inet_addr(argv[3]);
563 ipip_dest = inet_addr(argv[4]);
564 ipip_src = inet_addr(argv[5]);
567 local_port = atoi(argv[6]);
570 // Get local port in do_init() so that we pick a new one on reload
571 remote_port = atoi(argv[6]);
574 tcp_init_magic = atoll(argv[7]);
576 src = inet_addr(argv[9]);
578 memset(&dest, 0, sizeof(dest));
580 dest.sin_family = AF_INET;
581 dest.sin_addr.s_addr = inet_addr(argv[10]);
585 // Create tun and bind to sockets...
588 if (tun_alloc(tun_name, TUN_IF_COUNT, fd) != 0) {
589 fprintf(stderr, "Failed to alloc tun if\n");
593 fdr = socket(AF_INET, SOCK_RAW, IPPROTO_TCP);
595 fprintf(stderr, "Failed to get raw socket\n");
604 std::this_thread::sleep_for(std::chrono::seconds(15));
605 if (!are_server && last_ack_recv < std::chrono::steady_clock::now() - std::chrono::seconds(15)) {