proxy.c 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <stdarg.h>
  4. #include <memory.h>
  5. #include <assert.h>
  6. #include <errno.h>
  7. #include <poll.h>
  8. #include <unistd.h>
  9. #include <sys/types.h>
  10. #include <arpa/inet.h>
  11. #include <netinet/in.h>
  12. #include <linux/ip.h>
  13. #include <linux/icmp.h>
  14. #define CMD_DEFINE
  15. #include "proxy.h"
  16. struct ip_net {
  17. in_addr_t ip;
  18. in_addr_t mask;
  19. };
  20. struct route_entry {
  21. struct ip_net dst;
  22. struct sockaddr_in next_hop;
  23. };
  24. typedef struct icmp_pkt {
  25. struct iphdr iph;
  26. struct icmphdr icmph;
  27. /* dest unreachable must include IP hdr 8 bytes of upper layer proto
  28. * of the original packet. */
  29. char data[sizeof(struct iphdr) + MAX_IPOPTLEN + 8];
  30. } __attribute__ ((aligned (4))) icmp_pkt;
  31. /* we calc hdr checksums using 32bit uints that can alias other types */
  32. typedef uint32_t __attribute__((__may_alias__)) aliasing_uint32_t;
  33. struct route_entry *routes;
  34. size_t routes_alloc;
  35. size_t routes_cnt;
  36. in_addr_t tun_addr;
  37. int log_enabled;
  38. int exit_flag;
  39. static inline in_addr_t netmask(int prefix_len) {
  40. return htonl(~((uint32_t)0) << (32 - prefix_len));
  41. }
  42. static inline int contains(struct ip_net net, in_addr_t ip) {
  43. return net.ip == (ip & net.mask);
  44. }
  45. static void log_error(const char *fmt, ...) {
  46. va_list ap;
  47. if( log_enabled ) {
  48. va_start(ap, fmt);
  49. vfprintf(stderr, fmt, ap);
  50. va_end(ap);
  51. }
  52. }
  53. /* fast version -- only works with mults of 4 bytes */
  54. uint16_t cksum(aliasing_uint32_t *buf, int len) {
  55. uint32_t sum = 0;
  56. uint16_t t1, t2;
  57. for( ; len > 0; len-- ) {
  58. uint32_t s = *buf++;
  59. sum += s;
  60. if( sum < s )
  61. sum++;
  62. }
  63. /* Fold down to 16 bits */
  64. t1 = sum;
  65. t2 = sum >> 16;
  66. t1 += t2;
  67. if( t1 < t2 )
  68. t1++;
  69. return ~t1;
  70. }
  71. static void send_net_unreachable(int tun, char *offender) {
  72. icmp_pkt pkt;
  73. int off_iph_len;
  74. struct iphdr *off_iph = (struct iphdr *)offender;
  75. size_t pktlen, nsent;
  76. off_iph_len = off_iph->ihl * 4;
  77. if( off_iph_len >= sizeof(struct iphdr) + MAX_IPOPTLEN ) {
  78. log_error("not sending net unreachable: mulformed ip pkt: iph=%d\n", (int)off_iph_len);
  79. return; /* ip pkt mulformed */
  80. }
  81. if( off_iph->protocol == IPPROTO_ICMP ) {
  82. /* To avoid infinite loops, RFC 792 instructs not to send ICMPs
  83. * about ICMPs */
  84. return;
  85. }
  86. /* Lower 3 bits (in network order) of frag_off is actually flags */
  87. if( (off_iph->frag_off & htons(0x1FFF)) != 0 ) {
  88. /* ICMP messages are only sent for first fragemnt */
  89. return;
  90. }
  91. pktlen = sizeof(struct iphdr) + sizeof(struct icmphdr) + off_iph_len + 8;
  92. memset(&pkt, 0, sizeof(pkt));
  93. /* Fill in the IP header */
  94. pkt.iph.ihl = sizeof(struct iphdr) / 4;
  95. pkt.iph.version = IPVERSION;
  96. pkt.iph.tot_len = htons(pktlen);
  97. pkt.iph.ttl = 8;
  98. pkt.iph.protocol = IPPROTO_ICMP;
  99. pkt.iph.saddr = tun_addr;
  100. pkt.iph.daddr = off_iph->saddr;
  101. pkt.iph.check = cksum((aliasing_uint32_t*) &pkt.iph, sizeof(struct iphdr) / sizeof(aliasing_uint32_t));
  102. /* Fill in the ICMP header */
  103. pkt.icmph.type = ICMP_DEST_UNREACH;
  104. pkt.icmph.code = ICMP_NET_UNREACH;
  105. /* Copy the offenders IP hdr + first 8 bytes of IP payload */
  106. memcpy(pkt.data, offender, off_iph_len + 8);
  107. /* Compute the checksum over the ICMP header and data */
  108. pkt.icmph.checksum = cksum((aliasing_uint32_t*) &pkt.icmph,
  109. (sizeof(struct icmphdr) + off_iph_len + 8) / sizeof(aliasing_uint32_t));
  110. /* Kick it back */
  111. nsent = write(tun, &pkt, pktlen);
  112. if( nsent < 0 ) {
  113. log_error("failed to send ICMP net unreachable: %s\n", strerror(errno));
  114. } else if( nsent != pktlen ) {
  115. log_error("failed to send ICMP net unreachable: only %d out of %d byte sent\n", (int)nsent, (int)pktlen);
  116. }
  117. }
  118. static int set_route(struct ip_net dst, struct sockaddr_in *next_hop) {
  119. size_t i;
  120. for( i = 0; i < routes_cnt; i++ ) {
  121. if( dst.ip == routes[i].dst.ip && dst.mask == routes[i].dst.mask ) {
  122. routes[i].next_hop = *next_hop;
  123. return 0;
  124. }
  125. }
  126. if( routes_alloc == routes_cnt ) {
  127. int new_alloc = (routes_alloc ? 2*routes_alloc : 8);
  128. struct route_entry *new_routes = (struct route_entry *) realloc(routes, new_alloc*sizeof(struct route_entry));
  129. if( !new_routes )
  130. return ENOMEM;
  131. routes = new_routes;
  132. routes_alloc = new_alloc;
  133. }
  134. routes[routes_cnt].dst = dst;
  135. routes[routes_cnt].next_hop = *next_hop;
  136. routes_cnt++;
  137. return 0;
  138. }
  139. static int del_route(struct ip_net dst) {
  140. size_t i;
  141. for( i = 0; i < routes_cnt; i++ ) {
  142. if( dst.ip == routes[i].dst.ip && dst.mask == routes[i].dst.mask ) {
  143. routes[i] = routes[routes_cnt-1];
  144. routes_cnt--;
  145. return 0;
  146. }
  147. }
  148. return ENOENT;
  149. }
  150. static struct sockaddr_in *find_route(in_addr_t dst) {
  151. size_t i;
  152. for( i = 0; i < routes_cnt; i++ ) {
  153. if( contains(routes[i].dst, dst) ) {
  154. // packets for same dest tend to come in bursts. swap to front make it faster for subsequent ones
  155. if( i != 0 ) {
  156. struct route_entry tmp = routes[i];
  157. routes[i] = routes[0];
  158. routes[0] = tmp;
  159. }
  160. return &routes[0].next_hop;
  161. }
  162. }
  163. return NULL;
  164. }
  165. static char *inaddr_str(in_addr_t a, char *buf, size_t len) {
  166. struct in_addr addr;
  167. addr.s_addr = a;
  168. strncpy(buf, inet_ntoa(addr), len);
  169. buf[len-1] = '\0';
  170. return buf;
  171. }
  172. static ssize_t tun_recv_packet(int tun, char *buf, size_t buflen) {
  173. ssize_t nread = read(tun, buf, buflen);
  174. if( nread < sizeof(struct iphdr) ) {
  175. if( nread < 0 ) {
  176. log_error("TUN recv failed: %s\n", strerror(errno));
  177. } else {
  178. log_error("TUN recv packet too small: %d bytes\n", (int)nread);
  179. }
  180. return -1;
  181. }
  182. return nread;
  183. }
  184. static ssize_t sock_recv_packet(int sock, char *buf, size_t buflen) {
  185. ssize_t nread = recv(sock, buf, buflen, 0);
  186. if( nread < sizeof(struct iphdr) ) {
  187. if( nread < 0 ) {
  188. log_error("UDP recv failed: %s\n", strerror(errno));
  189. } else {
  190. log_error("UDP recv packet too small: %d bytes\n", (int)nread);
  191. }
  192. return -1;
  193. }
  194. return nread;
  195. }
  196. static void sock_send_packet(int sock, char *pkt, size_t pktlen, struct sockaddr_in *dst) {
  197. ssize_t nsent = sendto(sock, pkt, pktlen, 0, (struct sockaddr *)dst, sizeof(struct sockaddr_in));
  198. if( nsent != pktlen ) {
  199. if( nsent < 0 ) {
  200. log_error("UDP send to %s:%hu failed: %s\n",
  201. inet_ntoa(dst->sin_addr), ntohs(dst->sin_port), strerror(errno));
  202. } else {
  203. log_error("Was only able to send %d out of %d bytes to %s:%hu\n",
  204. (int)nsent, (int)pktlen, inet_ntoa(dst->sin_addr), ntohs(dst->sin_port));
  205. }
  206. }
  207. }
  208. static void tun_send_packet(int tun, char *pkt, size_t pktlen) {
  209. ssize_t nsent = write(tun, pkt, pktlen);
  210. if( nsent != pktlen ) {
  211. if( nsent < 0 ) {
  212. log_error("TUN send failed: %s\n", strerror(errno));
  213. } else {
  214. log_error("Was only able to send %d out of %d bytes to TUN\n", (int)nsent, (int)pktlen);
  215. }
  216. }
  217. }
  218. inline static int decrement_ttl(struct iphdr *iph) {
  219. if( --(iph->ttl) == 0 ) {
  220. char saddr[32], daddr[32];
  221. log_error("Discarding IP fragment %s -> %s due to zero TTL\n",
  222. inaddr_str(iph->saddr, saddr, sizeof(saddr)),
  223. inaddr_str(iph->daddr, daddr, sizeof(daddr)));
  224. return 0;
  225. }
  226. /* patch up IP checksum (see RFC 1624) */
  227. if( iph->check >= htons(0xFFFFu - 0x100) ) {
  228. iph->check += htons(0x100) + 1;
  229. } else {
  230. iph->check += htons(0x100);
  231. }
  232. return 1;
  233. }
  234. static void tun_to_udp(int tun, int sock, char *buf, size_t buflen) {
  235. struct iphdr *iph;
  236. struct sockaddr_in *next_hop;
  237. ssize_t pktlen = tun_recv_packet(tun, buf, buflen);
  238. if( pktlen < 0 )
  239. return;
  240. iph = (struct iphdr *)buf;
  241. next_hop = find_route((in_addr_t) iph->daddr);
  242. if( !next_hop ) {
  243. send_net_unreachable(tun, buf);
  244. return;
  245. }
  246. if( !decrement_ttl(iph) ) {
  247. /* TTL went to 0, discard.
  248. * TODO: send back ICMP Time Exceeded
  249. */
  250. return;
  251. }
  252. sock_send_packet(sock, buf, pktlen, next_hop);
  253. }
  254. static void udp_to_tun(int sock, int tun, char *buf, size_t buflen) {
  255. struct iphdr *iph;
  256. ssize_t pktlen = sock_recv_packet(sock, buf, buflen);
  257. if( pktlen < 0 ) {
  258. return;
  259. }
  260. iph = (struct iphdr *)buf;
  261. if( !decrement_ttl(iph) ) {
  262. /* TTL went to 0, discard.
  263. * TODO: send back ICMP Time Exceeded
  264. */
  265. return;
  266. }
  267. tun_send_packet(tun, buf, pktlen);
  268. }
  269. static void process_cmd(int ctl) {
  270. struct command cmd;
  271. struct ip_net ipn;
  272. struct sockaddr_in sa = {
  273. .sin_family = AF_INET
  274. };
  275. ssize_t nrecv = recv(ctl, (char *) &cmd, sizeof(cmd), 0);
  276. if( nrecv < 0 ) {
  277. log_error("CTL recv failed: %s\n", strerror(errno));
  278. return;
  279. }
  280. if( cmd.cmd == CMD_SET_ROUTE ) {
  281. ipn.mask = netmask(cmd.dest_net_len);
  282. ipn.ip = cmd.dest_net & ipn.mask;
  283. sa.sin_addr.s_addr = cmd.next_hop_ip;
  284. sa.sin_port = htons(cmd.next_hop_port);
  285. set_route(ipn, &sa);
  286. } else if( cmd.cmd == CMD_DEL_ROUTE ) {
  287. ipn.mask = netmask(cmd.dest_net_len);
  288. ipn.ip = cmd.dest_net & ipn.mask;
  289. del_route(ipn);
  290. } else if( cmd.cmd == CMD_STOP ) {
  291. exit_flag = 1;
  292. }
  293. }
  294. void run_proxy(int tun, int sock, int ctl, in_addr_t tun_ip, size_t tun_mtu, int log_errors) {
  295. char *buf;
  296. struct pollfd fds[3] = {
  297. {
  298. .fd = tun,
  299. .events = POLLIN
  300. },
  301. {
  302. .fd = sock,
  303. .events = POLLIN
  304. },
  305. {
  306. .fd = ctl,
  307. .events = POLLIN
  308. },
  309. };
  310. exit_flag = 0;
  311. tun_addr = tun_ip;
  312. log_enabled = log_errors;
  313. buf = (char *) malloc(tun_mtu);
  314. if( !buf ) {
  315. log_error("Failed to allocate %d byte buffer\n", tun_mtu);
  316. exit(1);
  317. }
  318. while( !exit_flag ) {
  319. int nfds = poll(fds, 3, -1);
  320. if( nfds < 0 ) {
  321. if( errno == EINTR )
  322. continue;
  323. log_error("Poll failed: %s\n", strerror(errno));
  324. exit(1);
  325. }
  326. if( fds[0].revents & POLLIN )
  327. tun_to_udp(tun, sock, buf, tun_mtu);
  328. if( fds[1].revents & POLLIN )
  329. udp_to_tun(sock, tun, buf, tun_mtu);
  330. if( fds[2].revents & POLLIN ) {
  331. process_cmd(ctl);
  332. }
  333. }
  334. free(buf);
  335. }