Stricter checks against routing loops.
[tinc] / src / route.c
1 /*
2     route.c -- routing
3     Copyright (C) 2000-2005 Ivo Timmermans,
4                   2000-2010 Guus Sliepen <guus@tinc-vpn.org>
5
6     This program is free software; you can redistribute it and/or modify
7     it under the terms of the GNU General Public License as published by
8     the Free Software Foundation; either version 2 of the License, or
9     (at your option) any later version.
10
11     This program is distributed in the hope that it will be useful,
12     but WITHOUT ANY WARRANTY; without even the implied warranty of
13     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14     GNU General Public License for more details.
15
16     You should have received a copy of the GNU General Public License along
17     with this program; if not, write to the Free Software Foundation, Inc.,
18     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 */
20
21 #include "system.h"
22
23 #include "avl_tree.h"
24 #include "connection.h"
25 #include "ethernet.h"
26 #include "ipv4.h"
27 #include "ipv6.h"
28 #include "logger.h"
29 #include "net.h"
30 #include "protocol.h"
31 #include "route.h"
32 #include "subnet.h"
33 #include "utils.h"
34
35 rmode_t routing_mode = RMODE_ROUTER;
36 fmode_t forwarding_mode = FMODE_INTERNAL;
37 bool decrement_ttl = true;
38 bool directonly = false;
39 bool priorityinheritance = false;
40 int macexpire = 600;
41 bool overwrite_mac = false;
42 bool broadcast = true;
43 mac_t mymac = {{0xFE, 0xFD, 0, 0, 0, 0}};
44
45 /* Sizes of various headers */
46
47 static const size_t ether_size = sizeof(struct ether_header);
48 static const size_t arp_size = sizeof(struct ether_arp);
49 static const size_t ip_size = sizeof(struct ip);
50 static const size_t icmp_size = sizeof(struct icmp) - sizeof(struct ip);
51 static const size_t ip6_size = sizeof(struct ip6_hdr);
52 static const size_t icmp6_size = sizeof(struct icmp6_hdr);
53 static const size_t ns_size = sizeof(struct nd_neighbor_solicit);
54 static const size_t opt_size = sizeof(struct nd_opt_hdr);
55
56 #ifndef MAX
57 #define MAX(a, b) ((a) > (b) ? (a) : (b))
58 #endif
59
60 /* RFC 1071 */
61
62 static uint16_t inet_checksum(void *data, int len, uint16_t prevsum) {
63         uint16_t *p = data;
64         uint32_t checksum = prevsum ^ 0xFFFF;
65
66         while(len >= 2) {
67                 checksum += *p++;
68                 len -= 2;
69         }
70         
71         if(len)
72                 checksum += *(uint8_t *)p;
73
74         while(checksum >> 16)
75                 checksum = (checksum & 0xFFFF) + (checksum >> 16);
76
77         return ~checksum;
78 }
79
80 static bool ratelimit(int frequency) {
81         static time_t lasttime = 0;
82         static int count = 0;
83         
84         if(lasttime == now) {
85                 if(count >= frequency)
86                         return true;
87         } else {
88                 lasttime = now;
89                 count = 0;
90         }
91
92         count++;
93         return false;
94 }
95
96 static bool checklength(node_t *source, vpn_packet_t *packet, length_t length) {
97         if(packet->len < length) {
98                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got too short packet from %s (%s)", source->name, source->hostname);
99                 return false;
100         } else
101                 return true;
102 }
103
104 static void clamp_mss(const node_t *source, const node_t *via, vpn_packet_t *packet) {
105         if(!source || !via || !(via->options & OPTION_CLAMP_MSS))
106                 return;
107
108         uint16_t mtu = source->mtu;
109         if(via != myself && via->mtu < mtu)
110                 mtu = via->mtu;
111
112         /* Find TCP header */
113         int start = 0;
114         uint16_t type = packet->data[12] << 8 | packet->data[13];
115
116         if(type == ETH_P_IP && packet->data[23] == 6)
117                 start = 14 + (packet->data[14] & 0xf) * 4;
118         else if(type == ETH_P_IPV6 && packet->data[20] == 6)
119                 start = 14 + 40;
120
121         if(!start || packet->len <= start + 20)
122                 return;
123
124         /* Use data offset field to calculate length of options field */
125         int len = ((packet->data[start + 12] >> 4) - 5) * 4;
126
127         if(packet->len < start + 20 + len)
128                 return;
129
130         /* Search for MSS option header */
131         for(int i = 0; i < len;) {
132                 if(packet->data[start + 20 + i] == 0)
133                         break;
134
135                 if(packet->data[start + 20 + i] == 1) {
136                         i++;
137                         continue;
138                 }
139
140                 if(i > len - 2 || i > len - packet->data[start + 21 + i])
141                         break;
142
143                 if(packet->data[start + 20 + i] != 2) {
144                         if(packet->data[start + 21 + i] < 2)
145                                 break;
146                         i += packet->data[start + 21 + i];
147                         continue;
148                 }
149
150                 if(packet->data[start + 21] != 4)
151                         break;
152
153                 /* Found it */
154                 uint16_t oldmss = packet->data[start + 22 + i] << 8 | packet->data[start + 23 + i];
155                 uint16_t newmss = mtu - start - 20;
156                 uint16_t csum = packet->data[start + 16] << 8 | packet->data[start + 17];
157
158                 if(oldmss <= newmss)
159                         break;
160                 
161                 ifdebug(TRAFFIC) logger(LOG_INFO, "Clamping MSS of packet from %s to %s to %d", source->name, via->name, newmss);
162
163                 /* Update the MSS value and the checksum */
164                 packet->data[start + 22 + i] = newmss >> 8;
165                 packet->data[start + 23 + i] = newmss & 0xff;
166                 csum ^= 0xffff;
167                 csum -= oldmss;
168                 csum += newmss;
169                 csum ^= 0xffff;
170                 packet->data[start + 16] = csum >> 8;
171                 packet->data[start + 17] = csum & 0xff;
172                 break;
173         }
174 }
175
176 static void swap_mac_addresses(vpn_packet_t *packet) {
177         mac_t tmp;
178         memcpy(&tmp, &packet->data[0], sizeof tmp);
179         memcpy(&packet->data[0], &packet->data[6], sizeof tmp);
180         memcpy(&packet->data[6], &tmp, sizeof tmp);
181 }
182         
183 static void learn_mac(mac_t *address) {
184         subnet_t *subnet;
185         avl_node_t *node;
186         connection_t *c;
187
188         subnet = lookup_subnet_mac(myself, address);
189
190         /* If we don't know this MAC address yet, store it */
191
192         if(!subnet) {
193                 ifdebug(TRAFFIC) logger(LOG_INFO, "Learned new MAC address %hx:%hx:%hx:%hx:%hx:%hx",
194                                    address->x[0], address->x[1], address->x[2], address->x[3],
195                                    address->x[4], address->x[5]);
196
197                 subnet = new_subnet();
198                 subnet->type = SUBNET_MAC;
199                 subnet->expires = now + macexpire;
200                 subnet->net.mac.address = *address;
201                 subnet->weight = 10;
202                 subnet_add(myself, subnet);
203                 subnet_update(myself, subnet, true);
204
205                 /* And tell all other tinc daemons it's our MAC */
206
207                 for(node = connection_tree->head; node; node = node->next) {
208                         c = node->data;
209                         if(c->status.active)
210                                 send_add_subnet(c, subnet);
211                 }
212         }
213
214         if(subnet->expires)
215                 subnet->expires = now + macexpire;
216 }
217
218 void age_subnets(void) {
219         subnet_t *s;
220         connection_t *c;
221         avl_node_t *node, *next, *node2;
222
223         for(node = myself->subnet_tree->head; node; node = next) {
224                 next = node->next;
225                 s = node->data;
226                 if(s->expires && s->expires <= now) {
227                         ifdebug(TRAFFIC) {
228                                 char netstr[MAXNETSTR];
229                                 if(net2str(netstr, sizeof netstr, s))
230                                         logger(LOG_INFO, "Subnet %s expired", netstr);
231                         }
232
233                         for(node2 = connection_tree->head; node2; node2 = node2->next) {
234                                 c = node2->data;
235                                 if(c->status.active)
236                                         send_del_subnet(c, s);
237                         }
238
239                         subnet_update(myself, s, false);
240                         subnet_del(myself, s);
241                 }
242         }
243 }
244
245 /* RFC 792 */
246
247 static void route_ipv4_unreachable(node_t *source, vpn_packet_t *packet, uint8_t type, uint8_t code) {
248         struct ip ip = {0};
249         struct icmp icmp = {0};
250         
251         struct in_addr ip_src;
252         struct in_addr ip_dst;
253         uint32_t oldlen;
254
255         if(ratelimit(3))
256                 return;
257         
258         /* Swap Ethernet source and destination addresses */
259
260         swap_mac_addresses(packet);
261
262         /* Copy headers from packet into properly aligned structs on the stack */
263
264         memcpy(&ip, packet->data + ether_size, ip_size);
265
266         /* Remember original source and destination */
267         
268         ip_src = ip.ip_src;
269         ip_dst = ip.ip_dst;
270
271         oldlen = packet->len - ether_size;
272
273         if(type == ICMP_DEST_UNREACH && code == ICMP_FRAG_NEEDED)
274                 icmp.icmp_nextmtu = htons(packet->len - ether_size);
275
276         if(oldlen >= IP_MSS - ip_size - icmp_size)
277                 oldlen = IP_MSS - ip_size - icmp_size;
278         
279         /* Copy first part of original contents to ICMP message */
280         
281         memmove(packet->data + ether_size + ip_size + icmp_size, packet->data + ether_size, oldlen);
282
283         /* Fill in IPv4 header */
284         
285         ip.ip_v = 4;
286         ip.ip_hl = ip_size / 4;
287         ip.ip_tos = 0;
288         ip.ip_len = htons(ip_size + icmp_size + oldlen);
289         ip.ip_id = 0;
290         ip.ip_off = 0;
291         ip.ip_ttl = 255;
292         ip.ip_p = IPPROTO_ICMP;
293         ip.ip_sum = 0;
294         ip.ip_src = ip_dst;
295         ip.ip_dst = ip_src;
296
297         ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
298         
299         /* Fill in ICMP header */
300         
301         icmp.icmp_type = type;
302         icmp.icmp_code = code;
303         icmp.icmp_cksum = 0;
304         
305         icmp.icmp_cksum = inet_checksum(&icmp, icmp_size, ~0);
306         icmp.icmp_cksum = inet_checksum(packet->data + ether_size + ip_size + icmp_size, oldlen, icmp.icmp_cksum);
307
308         /* Copy structs on stack back to packet */
309
310         memcpy(packet->data + ether_size, &ip, ip_size);
311         memcpy(packet->data + ether_size + ip_size, &icmp, icmp_size);
312         
313         packet->len = ether_size + ip_size + icmp_size + oldlen;
314
315         send_packet(source, packet);
316 }
317
318 /* RFC 791 */
319
320 static void fragment_ipv4_packet(node_t *dest, vpn_packet_t *packet) {
321         struct ip ip;
322         vpn_packet_t fragment;
323         int len, maxlen, todo;
324         uint8_t *offset;
325         uint16_t ip_off, origf;
326         
327         memcpy(&ip, packet->data + ether_size, ip_size);
328         fragment.priority = packet->priority;
329
330         if(ip.ip_hl != ip_size / 4)
331                 return;
332         
333         todo = ntohs(ip.ip_len) - ip_size;
334
335         if(ether_size + ip_size + todo != packet->len) {
336                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Length of packet (%d) doesn't match length in IPv4 header (%zd)", packet->len, ether_size + ip_size + todo);
337                 return;
338         }
339
340         ifdebug(TRAFFIC) logger(LOG_INFO, "Fragmenting packet of %d bytes to %s (%s)", packet->len, dest->name, dest->hostname);
341
342         offset = packet->data + ether_size + ip_size;
343         maxlen = (dest->mtu - ether_size - ip_size) & ~0x7;
344         ip_off = ntohs(ip.ip_off);
345         origf = ip_off & ~IP_OFFMASK;
346         ip_off &= IP_OFFMASK;
347         
348         while(todo) {
349                 len = todo > maxlen ? maxlen : todo;
350                 memcpy(fragment.data + ether_size + ip_size, offset, len);
351                 todo -= len;
352                 offset += len;
353
354                 ip.ip_len = htons(ip_size + len);
355                 ip.ip_off = htons(ip_off | origf | (todo ? IP_MF : 0));
356                 ip.ip_sum = 0;
357                 ip.ip_sum = inet_checksum(&ip, ip_size, ~0);
358                 memcpy(fragment.data, packet->data, ether_size);
359                 memcpy(fragment.data + ether_size, &ip, ip_size);
360                 fragment.len = ether_size + ip_size + len;
361
362                 send_packet(dest, &fragment);
363
364                 ip_off += len / 8;
365         }       
366 }
367
368 static void route_ipv4_unicast(node_t *source, vpn_packet_t *packet) {
369         subnet_t *subnet;
370         node_t *via;
371         ipv4_t dest;
372
373         memcpy(&dest, &packet->data[30], sizeof dest);
374         subnet = lookup_subnet_ipv4(&dest);
375
376         if(!subnet) {
377                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv4 destination address %d.%d.%d.%d",
378                                 source->name, source->hostname,
379                                 dest.x[0],
380                                 dest.x[1],
381                                 dest.x[2],
382                                 dest.x[3]);
383
384                 route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_UNKNOWN);
385                 return;
386         }
387         
388         if(subnet->owner == source) {
389                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
390                 return;
391         }
392
393         if(!subnet->owner->status.reachable)
394                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_UNREACH);
395
396         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
397                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_ANO);
398
399         if(priorityinheritance)
400                 packet->priority = packet->data[15];
401
402         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
403
404         if(via == source) {
405                 ifdebug(TRAFFIC) logger(LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
406                 return;
407         }
408         
409         if(directonly && subnet->owner != via)
410                 return route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_NET_ANO);
411
412         if(via && packet->len > MAX(via->mtu, 590) && via != myself) {
413                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
414                 if(packet->data[20] & 0x40) {
415                         packet->len = MAX(via->mtu, 590);
416                         route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
417                 } else {
418                         fragment_ipv4_packet(via, packet);
419                 }
420
421                 return;
422         }
423
424         clamp_mss(source, via, packet);
425  
426         send_packet(subnet->owner, packet);
427 }
428
429 static void route_ipv4(node_t *source, vpn_packet_t *packet) {
430         if(!checklength(source, packet, ether_size + ip_size))
431                 return;
432
433         if(broadcast && (((packet->data[30] & 0xf0) == 0xe0) || (
434                         packet->data[30] == 255 &&
435                         packet->data[31] == 255 &&
436                         packet->data[32] == 255 &&
437                         packet->data[33] == 255)))
438                 broadcast_packet(source, packet);
439         else
440                 route_ipv4_unicast(source, packet);
441 }
442
443 /* RFC 2463 */
444
445 static void route_ipv6_unreachable(node_t *source, vpn_packet_t *packet, uint8_t type, uint8_t code) {
446         struct ip6_hdr ip6;
447         struct icmp6_hdr icmp6 = {0};
448         uint16_t checksum;      
449
450         struct {
451                 struct in6_addr ip6_src;        /* source address */
452                 struct in6_addr ip6_dst;        /* destination address */
453                 uint32_t length;
454                 uint32_t next;
455         } pseudo;
456
457         if(ratelimit(3))
458                 return;
459         
460         /* Swap Ethernet source and destination addresses */
461
462         swap_mac_addresses(packet);
463
464         /* Copy headers from packet to structs on the stack */
465
466         memcpy(&ip6, packet->data + ether_size, ip6_size);
467
468         /* Remember original source and destination */
469         
470         pseudo.ip6_src = ip6.ip6_dst;
471         pseudo.ip6_dst = ip6.ip6_src;
472
473         pseudo.length = packet->len - ether_size;
474
475         if(type == ICMP6_PACKET_TOO_BIG)
476                 icmp6.icmp6_mtu = htonl(pseudo.length);
477         
478         if(pseudo.length >= IP_MSS - ip6_size - icmp6_size)
479                 pseudo.length = IP_MSS - ip6_size - icmp6_size;
480         
481         /* Copy first part of original contents to ICMP message */
482         
483         memmove(packet->data + ether_size + ip6_size + icmp6_size, packet->data + ether_size, pseudo.length);
484
485         /* Fill in IPv6 header */
486         
487         ip6.ip6_flow = htonl(0x60000000UL);
488         ip6.ip6_plen = htons(icmp6_size + pseudo.length);
489         ip6.ip6_nxt = IPPROTO_ICMPV6;
490         ip6.ip6_hlim = 255;
491         ip6.ip6_src = pseudo.ip6_src;
492         ip6.ip6_dst = pseudo.ip6_dst;
493
494         /* Fill in ICMP header */
495         
496         icmp6.icmp6_type = type;
497         icmp6.icmp6_code = code;
498         icmp6.icmp6_cksum = 0;
499
500         /* Create pseudo header */
501                 
502         pseudo.length = htonl(icmp6_size + pseudo.length);
503         pseudo.next = htonl(IPPROTO_ICMPV6);
504
505         /* Generate checksum */
506         
507         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
508         checksum = inet_checksum(&icmp6, icmp6_size, checksum);
509         checksum = inet_checksum(packet->data + ether_size + ip6_size + icmp6_size, ntohl(pseudo.length) - icmp6_size, checksum);
510
511         icmp6.icmp6_cksum = checksum;
512
513         /* Copy structs on stack back to packet */
514
515         memcpy(packet->data + ether_size, &ip6, ip6_size);
516         memcpy(packet->data + ether_size + ip6_size, &icmp6, icmp6_size);
517         
518         packet->len = ether_size + ip6_size + ntohl(pseudo.length);
519         
520         send_packet(source, packet);
521 }
522
523 static void route_ipv6_unicast(node_t *source, vpn_packet_t *packet) {
524         subnet_t *subnet;
525         node_t *via;
526         ipv6_t dest;
527
528         memcpy(&dest, &packet->data[38], sizeof dest);
529         subnet = lookup_subnet_ipv6(&dest);
530
531         if(!subnet) {
532                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown IPv6 destination address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
533                                 source->name, source->hostname,
534                                 ntohs(dest.x[0]),
535                                 ntohs(dest.x[1]),
536                                 ntohs(dest.x[2]),
537                                 ntohs(dest.x[3]),
538                                 ntohs(dest.x[4]),
539                                 ntohs(dest.x[5]),
540                                 ntohs(dest.x[6]),
541                                 ntohs(dest.x[7]));
542
543                 route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADDR);
544                 return;
545         }
546
547         if(subnet->owner == source) {
548                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
549                 return;
550         }
551
552         if(!subnet->owner->status.reachable)
553                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_NOROUTE);
554
555         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
556                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
557
558         via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
559         
560         if(via == source) {
561                 ifdebug(TRAFFIC) logger(LOG_ERR, "Routing loop for packet from %s (%s)!", source->name, source->hostname);
562                 return;
563         }
564         
565         if(directonly && subnet->owner != via)
566                 return route_ipv6_unreachable(source, packet, ICMP6_DST_UNREACH, ICMP6_DST_UNREACH_ADMIN);
567
568         if(via && packet->len > MAX(via->mtu, 1294) && via != myself) {
569                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
570                 packet->len = MAX(via->mtu, 1294);
571                 route_ipv6_unreachable(source, packet, ICMP6_PACKET_TOO_BIG, 0);
572                 return;
573         }
574
575         clamp_mss(source, via, packet);
576  
577         send_packet(subnet->owner, packet);
578 }
579
580 /* RFC 2461 */
581
582 static void route_neighborsol(node_t *source, vpn_packet_t *packet) {
583         struct ip6_hdr ip6;
584         struct nd_neighbor_solicit ns;
585         struct nd_opt_hdr opt;
586         subnet_t *subnet;
587         uint16_t checksum;
588         bool has_opt;
589
590         struct {
591                 struct in6_addr ip6_src;        /* source address */
592                 struct in6_addr ip6_dst;        /* destination address */
593                 uint32_t length;
594                 uint32_t next;
595         } pseudo;
596
597         if(!checklength(source, packet, ether_size + ip6_size + ns_size))
598                 return;
599         
600         has_opt = packet->len >= ether_size + ip6_size + ns_size + opt_size + ETH_ALEN;
601         
602         if(source != myself) {
603                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got neighbor solicitation request from %s (%s) while in router mode!", source->name, source->hostname);
604                 return;
605         }
606
607         /* Copy headers from packet to structs on the stack */
608
609         memcpy(&ip6, packet->data + ether_size, ip6_size);
610         memcpy(&ns, packet->data + ether_size + ip6_size, ns_size);
611         if(has_opt)
612                 memcpy(&opt, packet->data + ether_size + ip6_size + ns_size, opt_size);
613
614         /* First, snatch the source address from the neighbor solicitation packet */
615
616         if(overwrite_mac)
617                 memcpy(mymac.x, packet->data + ETH_ALEN, ETH_ALEN);
618
619         /* Check if this is a valid neighbor solicitation request */
620
621         if(ns.nd_ns_hdr.icmp6_type != ND_NEIGHBOR_SOLICIT ||
622            (has_opt && opt.nd_opt_type != ND_OPT_SOURCE_LINKADDR)) {
623                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: received unknown type neighbor solicitation request");
624                 return;
625         }
626
627         /* Create pseudo header */
628
629         pseudo.ip6_src = ip6.ip6_src;
630         pseudo.ip6_dst = ip6.ip6_dst;
631         if(has_opt)
632                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
633         else
634                 pseudo.length = htonl(ns_size);
635         pseudo.next = htonl(IPPROTO_ICMPV6);
636
637         /* Generate checksum */
638
639         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
640         checksum = inet_checksum(&ns, ns_size, checksum);
641         if(has_opt) {
642                 checksum = inet_checksum(&opt, opt_size, checksum);
643                 checksum = inet_checksum(packet->data + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
644         }
645
646         if(checksum) {
647                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: checksum error for neighbor solicitation request");
648                 return;
649         }
650
651         /* Check if the IPv6 address exists on the VPN */
652
653         subnet = lookup_subnet_ipv6((ipv6_t *) &ns.nd_ns_target);
654
655         if(!subnet) {
656                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: neighbor solicitation request for unknown address %hx:%hx:%hx:%hx:%hx:%hx:%hx:%hx",
657                                    ntohs(((uint16_t *) &ns.nd_ns_target)[0]),
658                                    ntohs(((uint16_t *) &ns.nd_ns_target)[1]),
659                                    ntohs(((uint16_t *) &ns.nd_ns_target)[2]),
660                                    ntohs(((uint16_t *) &ns.nd_ns_target)[3]),
661                                    ntohs(((uint16_t *) &ns.nd_ns_target)[4]),
662                                    ntohs(((uint16_t *) &ns.nd_ns_target)[5]),
663                                    ntohs(((uint16_t *) &ns.nd_ns_target)[6]),
664                                    ntohs(((uint16_t *) &ns.nd_ns_target)[7]));
665
666                 return;
667         }
668
669         /* Check if it is for our own subnet */
670
671         if(subnet->owner == myself)
672                 return;                                 /* silently ignore */
673
674         /* Create neighbor advertation reply */
675
676         memcpy(packet->data, packet->data + ETH_ALEN, ETH_ALEN);        /* copy destination address */
677         packet->data[ETH_ALEN * 2 - 1] ^= 0xFF; /* mangle source address so it looks like it's not from us */
678
679         ip6.ip6_dst = ip6.ip6_src;                      /* swap destination and source protocoll address */
680         ip6.ip6_src = ns.nd_ns_target;
681
682         if(has_opt)
683                 memcpy(packet->data + ether_size + ip6_size + ns_size + opt_size, packet->data + ETH_ALEN, ETH_ALEN);   /* add fake source hard addr */
684
685         ns.nd_ns_cksum = 0;
686         ns.nd_ns_type = ND_NEIGHBOR_ADVERT;
687         ns.nd_ns_reserved = htonl(0x40000000UL);        /* Set solicited flag */
688         opt.nd_opt_type = ND_OPT_TARGET_LINKADDR;
689
690         /* Create pseudo header */
691
692         pseudo.ip6_src = ip6.ip6_src;
693         pseudo.ip6_dst = ip6.ip6_dst;
694         if(has_opt)
695                 pseudo.length = htonl(ns_size + opt_size + ETH_ALEN);
696         else
697                 pseudo.length = htonl(ns_size);
698         pseudo.next = htonl(IPPROTO_ICMPV6);
699
700         /* Generate checksum */
701
702         checksum = inet_checksum(&pseudo, sizeof(pseudo), ~0);
703         checksum = inet_checksum(&ns, ns_size, checksum);
704         if(has_opt) {
705                 checksum = inet_checksum(&opt, opt_size, checksum);
706                 checksum = inet_checksum(packet->data + ether_size + ip6_size + ns_size + opt_size, ETH_ALEN, checksum);
707         }
708
709         ns.nd_ns_hdr.icmp6_cksum = checksum;
710
711         /* Copy structs on stack back to packet */
712
713         memcpy(packet->data + ether_size, &ip6, ip6_size);
714         memcpy(packet->data + ether_size + ip6_size, &ns, ns_size);
715         if(has_opt)
716                 memcpy(packet->data + ether_size + ip6_size + ns_size, &opt, opt_size);
717
718         send_packet(source, packet);
719 }
720
721 static void route_ipv6(node_t *source, vpn_packet_t *packet) {
722         if(!checklength(source, packet, ether_size + ip6_size))
723                 return;
724
725         if(packet->data[20] == IPPROTO_ICMPV6 && checklength(source, packet, ether_size + ip6_size + icmp6_size) && packet->data[54] == ND_NEIGHBOR_SOLICIT) {
726                 route_neighborsol(source, packet);
727                 return;
728         }
729
730         if(broadcast && packet->data[38] == 255)
731                 broadcast_packet(source, packet);
732         else
733                 route_ipv6_unicast(source, packet);
734 }
735
736 /* RFC 826 */
737
738 static void route_arp(node_t *source, vpn_packet_t *packet) {
739         struct ether_arp arp;
740         subnet_t *subnet;
741         struct in_addr addr;
742
743         if(!checklength(source, packet, ether_size + arp_size))
744                 return;
745
746         if(source != myself) {
747                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Got ARP request from %s (%s) while in router mode!", source->name, source->hostname);
748                 return;
749         }
750
751         /* First, snatch the source address from the ARP packet */
752
753         if(overwrite_mac)
754                 memcpy(mymac.x, packet->data + ETH_ALEN, ETH_ALEN);
755
756         /* Copy headers from packet to structs on the stack */
757
758         memcpy(&arp, packet->data + ether_size, arp_size);
759
760         /* Check if this is a valid ARP request */
761
762         if(ntohs(arp.arp_hrd) != ARPHRD_ETHER || ntohs(arp.arp_pro) != ETH_P_IP ||
763            arp.arp_hln != ETH_ALEN || arp.arp_pln != sizeof(addr) || ntohs(arp.arp_op) != ARPOP_REQUEST) {
764                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: received unknown type ARP request");
765                 return;
766         }
767
768         /* Check if the IPv4 address exists on the VPN */
769
770         subnet = lookup_subnet_ipv4((ipv4_t *) &arp.arp_tpa);
771
772         if(!subnet) {
773                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet: ARP request for unknown address %d.%d.%d.%d",
774                                    arp.arp_tpa[0], arp.arp_tpa[1], arp.arp_tpa[2],
775                                    arp.arp_tpa[3]);
776                 return;
777         }
778
779         /* Check if it is for our own subnet */
780
781         if(subnet->owner == myself)
782                 return;                                 /* silently ignore */
783
784         memcpy(packet->data, packet->data + ETH_ALEN, ETH_ALEN);        /* copy destination address */
785         packet->data[ETH_ALEN * 2 - 1] ^= 0xFF; /* mangle source address so it looks like it's not from us */
786
787         memcpy(&addr, arp.arp_tpa, sizeof(addr));       /* save protocol addr */
788         memcpy(arp.arp_tpa, arp.arp_spa, sizeof(addr)); /* swap destination and source protocol address */
789         memcpy(arp.arp_spa, &addr, sizeof(addr));       /* ... */
790
791         memcpy(arp.arp_tha, arp.arp_sha, ETH_ALEN);     /* set target hard/proto addr */
792         memcpy(arp.arp_sha, packet->data + ETH_ALEN, ETH_ALEN); /* add fake source hard addr */
793         arp.arp_op = htons(ARPOP_REPLY);
794
795         /* Copy structs on stack back to packet */
796
797         memcpy(packet->data + ether_size, &arp, arp_size);
798
799         send_packet(source, packet);
800 }
801
802 static void route_mac(node_t *source, vpn_packet_t *packet) {
803         subnet_t *subnet;
804         mac_t dest;
805
806         /* Learn source address */
807
808         if(source == myself) {
809                 mac_t src;
810                 memcpy(&src, &packet->data[6], sizeof src);
811                 learn_mac(&src);
812         }
813
814         /* Lookup destination address */
815
816         memcpy(&dest, &packet->data[0], sizeof dest);
817         subnet = lookup_subnet_mac(NULL, &dest);
818
819         if(!subnet) {
820                 if(broadcast)
821                         broadcast_packet(source, packet);
822                 return;
823         }
824
825         if(subnet->owner == source) {
826                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Packet looping back to %s (%s)!", source->name, source->hostname);
827                 return;
828         }
829
830         if(forwarding_mode == FMODE_OFF && source != myself && subnet->owner != myself)
831                 return;
832
833         // Handle packets larger than PMTU
834
835         node_t *via = (subnet->owner->via == myself) ? subnet->owner->nexthop : subnet->owner->via;
836
837         if(directonly && subnet->owner != via)
838                 return;
839         
840         if(via && packet->len > via->mtu && via != myself) {
841                 ifdebug(TRAFFIC) logger(LOG_INFO, "Packet for %s (%s) length %d larger than MTU %d", subnet->owner->name, subnet->owner->hostname, packet->len, via->mtu);
842                 uint16_t type = packet->data[12] << 8 | packet->data[13];
843                 if(type == ETH_P_IP && packet->len > 590) {
844                         if(packet->data[20] & 0x40) {
845                                 packet->len = via->mtu;
846                                 route_ipv4_unreachable(source, packet, ICMP_DEST_UNREACH, ICMP_FRAG_NEEDED);
847                         } else {
848                                 fragment_ipv4_packet(via, packet);
849                         }
850                         return;
851                 } else if(type == ETH_P_IPV6 && packet->len > 1294) {
852                         packet->len = via->mtu;
853                         route_ipv6_unreachable(source, packet, ICMP6_PACKET_TOO_BIG, 0);
854                         return;
855                 }
856         }
857
858         clamp_mss(source, via, packet);
859  
860         send_packet(subnet->owner, packet);
861 }
862
863 static bool do_decrement_ttl(node_t *source, vpn_packet_t *packet) {
864         uint16_t type = packet->data[12] << 8 | packet->data[13];
865
866         switch (type) {
867                 case ETH_P_IP:
868                         if(!checklength(source, packet, 14 + 32))
869                                 return false;
870
871                         if(packet->data[22] < 1) {
872                                 if(packet->data[25] != IPPROTO_ICMP || packet->data[46] != ICMP_TIME_EXCEEDED)
873                                         route_ipv4_unreachable(source, packet, ICMP_TIME_EXCEEDED, ICMP_EXC_TTL);
874                                 return false;
875                         }
876
877                         uint16_t old = packet->data[22] << 8 | packet->data[23];
878                         packet->data[22]--;
879                         uint16_t new = packet->data[22] << 8 | packet->data[23];
880
881                         uint32_t checksum = packet->data[24] << 8 | packet->data[25];
882                         checksum += old + (~new & 0xFFFF);
883                         while(checksum >> 16)
884                                 checksum = (checksum & 0xFFFF) + (checksum >> 16);
885                         packet->data[24] = checksum >> 8;
886                         packet->data[25] = checksum & 0xff;
887
888                         return true;
889
890                 case ETH_P_IPV6:
891                         if(!checklength(source, packet, 14 + 40))
892                                 return false;
893
894                         if(packet->data[21] < 1) {
895                                 if(packet->data[20] != IPPROTO_ICMPV6 || packet->data[54] != ICMP6_TIME_EXCEEDED)
896                                         route_ipv6_unreachable(source, packet, ICMP6_TIME_EXCEEDED, ICMP6_TIME_EXCEED_TRANSIT);
897                                 return false;
898                         }
899
900                         packet->data[21]--;
901
902                         return true;
903
904                 default:
905                         return true;
906         }
907 }
908
909 void route(node_t *source, vpn_packet_t *packet) {
910         if(forwarding_mode == FMODE_KERNEL && source != myself) {
911                 send_packet(myself, packet);
912                 return;
913         }
914
915         if(!checklength(source, packet, ether_size))
916                 return;
917
918         if(decrement_ttl && source != myself)
919                 if(!do_decrement_ttl(source, packet))
920                         return;
921
922         switch (routing_mode) {
923                 case RMODE_ROUTER:
924                         {
925                                 uint16_t type = packet->data[12] << 8 | packet->data[13];
926
927                                 switch (type) {
928                                         case ETH_P_ARP:
929                                                 route_arp(source, packet);
930                                                 break;
931
932                                         case ETH_P_IP:
933                                                 route_ipv4(source, packet);
934                                                 break;
935
936                                         case ETH_P_IPV6:
937                                                 route_ipv6(source, packet);
938                                                 break;
939
940                                         default:
941                                                 ifdebug(TRAFFIC) logger(LOG_WARNING, "Cannot route packet from %s (%s): unknown type %hx", source->name, source->hostname, type);
942                                                 break;
943                                 }
944                         }
945                         break;
946
947                 case RMODE_SWITCH:
948                         route_mac(source, packet);
949                         break;
950
951                 case RMODE_HUB:
952                         broadcast_packet(source, packet);
953                         break;
954         }
955 }