]> git.meshlink.io Git - meshlink/blob - src/net_packet.c
Never automatically try to bind to ports >= 32768.
[meshlink] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 2014-2017 Guus Sliepen <guus@meshlink.io>
4
5     This program is free software; you can redistribute it and/or modify
6     it under the terms of the GNU General Public License as published by
7     the Free Software Foundation; either version 2 of the License, or
8     (at your option) any later version.
9
10     This program is distributed in the hope that it will be useful,
11     but WITHOUT ANY WARRANTY; without even the implied warranty of
12     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13     GNU General Public License for more details.
14
15     You should have received a copy of the GNU General Public License along
16     with this program; if not, write to the Free Software Foundation, Inc.,
17     51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19
20 #include "system.h"
21
22 #include "conf.h"
23 #include "connection.h"
24 #include "crypto.h"
25 #include "graph.h"
26 #include "logger.h"
27 #include "meshlink_internal.h"
28 #include "net.h"
29 #include "netutl.h"
30 #include "protocol.h"
31 #include "route.h"
32 #include "sptps.h"
33 #include "utils.h"
34 #include "xalloc.h"
35
36 int keylifetime = 0;
37
38 static void send_udppacket(meshlink_handle_t *mesh, node_t *, vpn_packet_t *);
39
40 #define MAX_SEQNO 1073741824
41 #define PROBE_OVERHEAD (SPTPS_DATAGRAM_OVERHEAD + 40)
42
43 /* mtuprobes == 1..30: initial discovery, send bursts with 1 second interval
44    mtuprobes ==    31: sleep pinginterval seconds
45    mtuprobes ==    32: send 1 burst, sleep pingtimeout second
46    mtuprobes ==    33: no response from other side, restart PMTU discovery process
47
48    Probes are sent in batches of at least three, with random sizes between the
49    lower and upper boundaries for the MTU thus far discovered.
50
51    After the initial discovery, a fourth packet is added to each batch with a
52    size larger than the currently known PMTU, to test if the PMTU has increased.
53
54    In case local discovery is enabled, another packet is added to each batch,
55    which will be broadcast to the local network.
56
57 */
58
59 static void send_mtu_probe_handler(event_loop_t *loop, void *data) {
60         meshlink_handle_t *mesh = loop->data;
61         node_t *n = data;
62         int timeout = 1;
63
64         n->mtuprobes++;
65
66         if(!n->status.reachable || !n->status.validkey) {
67                 logger(mesh, MESHLINK_INFO, "Trying to send MTU probe to unreachable or rekeying node %s", n->name);
68                 n->mtuprobes = 0;
69                 return;
70         }
71
72         if(n->mtuprobes > 32) {
73                 if(!n->minmtu) {
74                         n->mtuprobes = 31;
75                         timeout = mesh->dev_class_traits[n->devclass].pinginterval;
76                         goto end;
77                 }
78
79                 logger(mesh, MESHLINK_INFO, "%s did not respond to UDP ping, restarting PMTU discovery", n->name);
80                 n->status.udp_confirmed = false;
81                 n->mtuprobes = 1;
82                 n->minmtu = 0;
83                 n->maxmtu = MTU;
84
85                 update_node_pmtu(mesh, n);
86         }
87
88         if(n->mtuprobes >= 10 && n->mtuprobes < 32 && !n->minmtu) {
89                 logger(mesh, MESHLINK_INFO, "No response to MTU probes from %s", n->name);
90                 n->mtuprobes = 31;
91         }
92
93         if(n->mtuprobes == 30 || (n->mtuprobes < 30 && n->minmtu >= n->maxmtu)) {
94                 if(n->minmtu > n->maxmtu) {
95                         n->minmtu = n->maxmtu;
96                         update_node_pmtu(mesh, n);
97                 } else {
98                         n->maxmtu = n->minmtu;
99                 }
100
101                 n->mtu = n->minmtu;
102                 logger(mesh, MESHLINK_INFO, "Fixing MTU of %s to %d after %d probes", n->name, n->mtu, n->mtuprobes);
103                 n->mtuprobes = 31;
104         }
105
106         if(n->mtuprobes == 31) {
107                 if(!n->minmtu && n->status.want_udp && n->nexthop && n->nexthop->connection) {
108                         /* Send a dummy ANS_KEY to try to update the reflexive UDP address */
109                         send_request(mesh, n->nexthop->connection, NULL, "%d %s %s . -1 -1 -1 0", ANS_KEY, mesh->self->name, n->name);
110                         n->status.want_udp = false;
111                 }
112
113                 timeout = mesh->dev_class_traits[n->devclass].pinginterval;
114                 goto end;
115         } else if(n->mtuprobes == 32) {
116                 timeout = mesh->dev_class_traits[n->devclass].pingtimeout;
117         }
118
119         for(int i = 0; i < 5; i++) {
120                 int len;
121
122                 if(i == 0) {
123                         if(n->mtuprobes < 30 || n->maxmtu + 8 >= MTU) {
124                                 continue;
125                         }
126
127                         len = n->maxmtu + 8;
128                 } else if(n->maxmtu <= n->minmtu) {
129                         len = n->maxmtu;
130                 } else {
131                         len = n->minmtu + 1 + prng(mesh, n->maxmtu - n->minmtu);
132                 }
133
134                 if(len < 64) {
135                         len = 64;
136                 }
137
138                 vpn_packet_t packet;
139                 packet.probe = true;
140                 memset(packet.data, 0, 14);
141                 randomize(packet.data + 14, len - 14);
142                 packet.len = len;
143                 n->status.broadcast = i >= 4 && n->mtuprobes <= 10 && n->prevedge;
144
145                 logger(mesh, MESHLINK_DEBUG, "Sending MTU probe length %d to %s", len, n->name);
146
147                 n->out_meta += packet.len + PROBE_OVERHEAD;
148                 send_udppacket(mesh, n, &packet);
149         }
150
151         n->status.broadcast = false;
152
153 end:
154         timeout_set(&mesh->loop, &n->mtutimeout, &(struct timespec) {
155                 timeout, prng(mesh, TIMER_FUDGE)
156         });
157 }
158
159 void send_mtu_probe(meshlink_handle_t *mesh, node_t *n) {
160         timeout_add(&mesh->loop, &n->mtutimeout, send_mtu_probe_handler, n, &(struct timespec) {
161                 1, 0
162         });
163         send_mtu_probe_handler(&mesh->loop, n);
164 }
165
166 static void mtu_probe_h(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet, uint16_t len) {
167         n->in_meta += len + PROBE_OVERHEAD;
168
169         if(len < 64) {
170                 logger(mesh, MESHLINK_WARNING, "Got too short MTU probe length %d from %s", packet->len, n->name);
171                 return;
172         }
173
174         logger(mesh, MESHLINK_DEBUG, "Got MTU probe length %d from %s", packet->len, n->name);
175
176         if(!packet->data[0]) {
177                 /* It's a probe request, send back a reply */
178
179                 packet->data[0] = 1;
180
181                 /* Temporarily set udp_confirmed, so that the reply is sent
182                    back exactly the way it came in. */
183
184                 bool udp_confirmed = n->status.udp_confirmed;
185                 n->status.udp_confirmed = true;
186                 logger(mesh, MESHLINK_DEBUG, "Sending MTU probe reply %d to %s", packet->len, n->name);
187                 n->out_meta += packet->len + PROBE_OVERHEAD;
188                 send_udppacket(mesh, n, packet);
189                 n->status.udp_confirmed = udp_confirmed;
190         } else {
191                 /* It's a valid reply: now we know bidirectional communication
192                    is possible using the address and socket that the reply
193                    packet used. */
194
195                 if(!n->status.udp_confirmed) {
196                         char *address, *port;
197                         sockaddr2str(&n->address, &address, &port);
198
199                         if(n->nexthop && n->nexthop->connection) {
200                                 send_request(mesh, n->nexthop->connection, NULL, "%d %s %s . -1 -1 -1 0 %s %s", ANS_KEY, n->name, n->name, address, port);
201                         } else {
202                                 logger(mesh, MESHLINK_WARNING, "Cannot send reflexive address to %s via %s", n->name, n->nexthop ? n->nexthop->name : n->name);
203                         }
204
205                         free(address);
206                         free(port);
207                         n->status.udp_confirmed = true;
208                 }
209
210                 /* If we haven't established the PMTU yet, restart the discovery process. */
211
212                 if(n->mtuprobes > 30) {
213                         if(len == n->maxmtu + 8) {
214                                 logger(mesh, MESHLINK_INFO, "Increase in PMTU to %s detected, restarting PMTU discovery", n->name);
215                                 n->maxmtu = MTU;
216                                 n->mtuprobes = 10;
217                                 return;
218                         }
219
220                         if(n->minmtu) {
221                                 n->mtuprobes = 30;
222                         } else {
223                                 n->mtuprobes = 1;
224                         }
225                 }
226
227                 /* If applicable, raise the minimum supported MTU */
228
229                 if(len > n->maxmtu) {
230                         len = n->maxmtu;
231                 }
232
233                 if(n->minmtu < len) {
234                         n->minmtu = len;
235                         update_node_pmtu(mesh, n);
236                 }
237         }
238 }
239
240 /* VPN packet I/O */
241
242 static void receive_packet(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet) {
243         logger(mesh, MESHLINK_DEBUG, "Received packet of %d bytes from %s", packet->len, n->name);
244
245         if(n->status.blacklisted) {
246                 logger(mesh, MESHLINK_WARNING, "Dropping packet from blacklisted node %s", n->name);
247         } else {
248                 route(mesh, n, packet);
249         }
250 }
251
252 static bool try_mac(meshlink_handle_t *mesh, node_t *n, const vpn_packet_t *inpkt) {
253         (void)mesh;
254         return sptps_verify_datagram(&n->sptps, inpkt->data, inpkt->len);
255 }
256
257 static void receive_udppacket(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *inpkt) {
258         if(!n->status.reachable) {
259                 logger(mesh, MESHLINK_ERROR, "Got SPTPS data from unreachable node %s", n->name);
260                 return;
261         }
262
263         if(!n->sptps.state) {
264                 if(!n->status.waitingforkey) {
265                         logger(mesh, MESHLINK_DEBUG, "Got packet from %s but we haven't exchanged keys yet", n->name);
266                         send_req_key(mesh, n);
267                 } else {
268                         logger(mesh, MESHLINK_DEBUG, "Got packet from %s but he hasn't got our key yet", n->name);
269                 }
270
271                 return;
272         }
273
274         if(!sptps_receive_data(&n->sptps, inpkt->data, inpkt->len)) {
275                 logger(mesh, MESHLINK_ERROR, "Could not process SPTPS data from %s: %s", n->name, strerror(errno));
276         }
277 }
278
279 static void send_sptps_packet(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *origpkt) {
280         if(!n->status.reachable) {
281                 logger(mesh, MESHLINK_ERROR, "Trying to send SPTPS data to unreachable node %s", n->name);
282                 return;
283         }
284
285         if(!n->status.validkey) {
286                 if(n->connection && (n->connection->flags & PROTOCOL_TINY) & n->connection->status.active) {
287                         send_raw_packet(mesh, n->connection, origpkt);
288                         return;
289                 }
290
291                 logger(mesh, MESHLINK_INFO, "No valid key known yet for %s", n->name);
292
293                 if(!n->status.waitingforkey) {
294                         send_req_key(mesh, n);
295                 } else if(n->last_req_key + 10 < mesh->loop.now.tv_sec) {
296                         logger(mesh, MESHLINK_DEBUG, "No key from %s after 10 seconds, restarting SPTPS", n->name);
297                         sptps_stop(&n->sptps);
298                         n->status.waitingforkey = false;
299                         send_req_key(mesh, n);
300                 }
301
302                 return;
303         }
304
305         uint8_t type = 0;
306
307         // If it's a probe, send it immediately without trying to compress it.
308         if(origpkt->probe) {
309                 sptps_send_record(&n->sptps, PKT_PROBE, origpkt->data, origpkt->len);
310                 return;
311         }
312
313         sptps_send_record(&n->sptps, type, origpkt->data, origpkt->len);
314         return;
315 }
316
317 static void choose_udp_address(meshlink_handle_t *mesh, const node_t *n, const sockaddr_t **sa, int *sock, sockaddr_t *sa_buf) {
318         /* Latest guess */
319         *sa = &n->address;
320         *sock = n->sock;
321
322         /* If the UDP address is confirmed, use it. */
323         if(n->status.udp_confirmed) {
324                 return;
325         }
326
327         /* Send every third packet to n->address; that could be set
328            to the node's reflexive UDP address discovered during key
329            exchange. */
330
331         if(++mesh->udp_choice >= 3) {
332                 mesh->udp_choice = 0;
333                 return;
334         }
335
336         /* If we have learned an address via Catta, try this once every batch */
337         if(mesh->udp_choice == 1 && n->catta_address.sa.sa_family != AF_UNSPEC) {
338                 *sa = &n->catta_address;
339                 goto check_socket;
340         }
341
342         /* Else, if we have a canonical address, try this once every batch */
343         if(mesh->udp_choice == 1 && n->canonical_address) {
344                 char *host = xstrdup(n->canonical_address);
345                 char *port = strchr(host, ' ');
346
347                 if(port) {
348                         *port++ = 0;
349                         *sa_buf = str2sockaddr_random(mesh, host, port);
350                         *sa = sa_buf;
351
352                         if(sa_buf->sa.sa_family != AF_UNKNOWN) {
353                                 free(host);
354                                 goto check_socket;
355                         }
356                 }
357
358                 free(host);
359         }
360
361         /* Otherwise, address are found in edges to this node.
362            So we pick a random edge and a random socket. */
363
364         edge_t *candidate = NULL;
365
366         {
367                 int i = 0;
368                 int j = prng(mesh, n->edge_tree->count);
369
370                 for splay_each(edge_t, e, n->edge_tree) {
371                         if(i++ == j) {
372                                 candidate = e->reverse;
373                                 break;
374                         }
375                 }
376         }
377
378         if(candidate) {
379                 *sa = &candidate->address;
380                 *sock = prng(mesh, mesh->listen_sockets);
381         }
382
383 check_socket:
384
385         /* Make sure we have a suitable socket for the chosen address */
386         if(mesh->listen_socket[*sock].sa.sa.sa_family != (*sa)->sa.sa_family) {
387                 for(int i = 0; i < mesh->listen_sockets; i++) {
388                         if(mesh->listen_socket[i].sa.sa.sa_family == (*sa)->sa.sa_family) {
389                                 *sock = i;
390                                 break;
391                         }
392                 }
393         }
394 }
395
396 static void choose_broadcast_address(meshlink_handle_t *mesh, const node_t *n, const sockaddr_t **sa, int *sock) {
397         *sock = prng(mesh, mesh->listen_sockets);
398         sockaddr_t *broadcast_sa = &mesh->listen_socket[*sock].broadcast_sa;
399
400         if(broadcast_sa->sa.sa_family == AF_INET6) {
401                 broadcast_sa->in6.sin6_port = n->prevedge->address.in.sin_port;
402         } else {
403                 broadcast_sa->in.sin_port = n->prevedge->address.in.sin_port;
404         }
405
406         *sa = broadcast_sa;
407 }
408
409 static void send_udppacket(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *origpkt) {
410         if(!n->status.reachable) {
411                 logger(mesh, MESHLINK_INFO, "Trying to send UDP packet to unreachable node %s", n->name);
412                 return;
413         }
414
415         send_sptps_packet(mesh, n, origpkt);
416 }
417
418 bool send_sptps_data(void *handle, uint8_t type, const void *data, size_t len) {
419         assert(handle);
420         assert(data);
421         assert(len);
422
423         node_t *to = handle;
424         meshlink_handle_t *mesh = to->mesh;
425
426         if(!to->status.reachable) {
427                 logger(mesh, MESHLINK_ERROR, "Trying to send SPTPS data to unreachable node %s", to->name);
428                 return false;
429         }
430
431         /* Send it via TCP if it is a handshake packet, TCPOnly is in use, or this packet is larger than the MTU. */
432
433         if(type >= SPTPS_HANDSHAKE || (type != PKT_PROBE && (len - 21) > to->minmtu)) {
434                 char buf[len * 4 / 3 + 5];
435                 b64encode(data, buf, len);
436
437                 if(!to->nexthop || !to->nexthop->connection) {
438                         logger(mesh, MESHLINK_WARNING, "Unable to forward SPTPS packet to %s via %s", to->name, to->nexthop ? to->nexthop->name : to->name);
439                         return false;
440                 }
441
442                 /* If no valid key is known yet, send the packets using ANS_KEY requests,
443                    to ensure we get to learn the reflexive UDP address. */
444                 if(!to->status.validkey) {
445                         return send_request(mesh, to->nexthop->connection, NULL, "%d %s %s %s -1 -1 -1 %d", ANS_KEY, mesh->self->name, to->name, buf, 0);
446                 } else {
447                         return send_request(mesh, to->nexthop->connection, NULL, "%d %s %s %d %s", REQ_KEY, mesh->self->name, to->name, REQ_SPTPS, buf);
448                 }
449         }
450
451         /* Otherwise, send the packet via UDP */
452
453         sockaddr_t sa_buf;
454         const sockaddr_t *sa;
455         int sock;
456
457         if(to->status.broadcast) {
458                 choose_broadcast_address(mesh, to, &sa, &sock);
459         } else {
460                 choose_udp_address(mesh, to, &sa, &sock, &sa_buf);
461         }
462
463         if(sendto(mesh->listen_socket[sock].udp.fd, data, len, 0, &sa->sa, SALEN(sa->sa)) < 0 && !sockwouldblock(sockerrno)) {
464                 if(sockmsgsize(sockerrno)) {
465                         if(to->maxmtu >= len) {
466                                 to->maxmtu = len - 1;
467                         }
468
469                         if(to->mtu >= len) {
470                                 to->mtu = len - 1;
471                         }
472                 } else {
473                         logger(mesh, MESHLINK_WARNING, "Error sending UDP SPTPS packet to %s: %s", to->name, sockstrerror(sockerrno));
474                         return false;
475                 }
476         }
477
478         return true;
479 }
480
481 bool receive_sptps_record(void *handle, uint8_t type, const void *data, uint16_t len) {
482         assert(handle);
483         assert(!data || len);
484
485         node_t *from = handle;
486         meshlink_handle_t *mesh = from->mesh;
487
488         if(type == SPTPS_HANDSHAKE) {
489                 if(!from->status.validkey) {
490                         logger(mesh, MESHLINK_INFO, "SPTPS key exchange with %s successful", from->name);
491                         from->status.validkey = true;
492                         from->status.waitingforkey = false;
493
494                         if(from->utcp) {
495                                 utcp_reset_timers(from->utcp);
496                         }
497                 }
498
499                 return true;
500         }
501
502         if(len > MAXSIZE) {
503                 logger(mesh, MESHLINK_ERROR, "Packet from %s larger than maximum supported size (%d > %d)", from->name, len, MAXSIZE);
504                 return false;
505         }
506
507         vpn_packet_t inpkt;
508
509         if(type == PKT_PROBE) {
510                 inpkt.len = len;
511                 inpkt.probe = true;
512                 memcpy(inpkt.data, data, len);
513                 mtu_probe_h(mesh, from, &inpkt, len);
514                 return true;
515         } else {
516                 inpkt.probe = false;
517         }
518
519         if(type & ~(PKT_COMPRESSED)) {
520                 logger(mesh, MESHLINK_ERROR, "Unexpected SPTPS record type %d len %d from %s", type, len, from->name);
521                 return false;
522         }
523
524         if(type & PKT_COMPRESSED) {
525                 logger(mesh, MESHLINK_ERROR, "Error while decompressing packet from %s", from->name);
526                 return false;
527         }
528
529         memcpy(inpkt.data, data, len); // TODO: get rid of memcpy
530         inpkt.len = len;
531
532         receive_packet(mesh, from, &inpkt);
533         return true;
534 }
535
536 /*
537   send a packet to the given vpn ip.
538 */
539 void send_packet(meshlink_handle_t *mesh, node_t *n, vpn_packet_t *packet) {
540         if(n == mesh->self) {
541                 // TODO: send to application
542                 return;
543         }
544
545         logger(mesh, MESHLINK_DEBUG, "Sending packet of %d bytes to %s", packet->len, n->name);
546
547         if(!n->status.reachable) {
548                 logger(mesh, MESHLINK_WARNING, "Node %s is not reachable", n->name);
549                 return;
550         }
551
552         n->status.want_udp = true;
553
554         send_sptps_packet(mesh, n, packet);
555         return;
556 }
557
558 static node_t *try_harder(meshlink_handle_t *mesh, const sockaddr_t *from, const vpn_packet_t *pkt) {
559         node_t *n = NULL;
560         bool hard = false;
561
562         for splay_each(edge_t, e, mesh->edges) {
563                 if(!e->to->status.reachable || e->to == mesh->self) {
564                         continue;
565                 }
566
567                 if(sockaddrcmp_noport(from, &e->address)) {
568                         if(mesh->last_hard_try == mesh->loop.now.tv_sec) {
569                                 continue;
570                         }
571
572                         hard = true;
573                 }
574
575                 if(!try_mac(mesh, e->to, pkt)) {
576                         continue;
577                 }
578
579                 n = e->to;
580                 break;
581         }
582
583         if(hard) {
584                 mesh->last_hard_try = mesh->loop.now.tv_sec;
585         }
586
587         return n;
588 }
589
590 void handle_incoming_vpn_data(event_loop_t *loop, void *data, int flags) {
591         (void)flags;
592         meshlink_handle_t *mesh = loop->data;
593         listen_socket_t *ls = data;
594         vpn_packet_t pkt;
595         char *hostname;
596         sockaddr_t from;
597         socklen_t fromlen = sizeof(from);
598         node_t *n;
599         int len;
600
601         memset(&from, 0, sizeof(from));
602
603         len = recvfrom(ls->udp.fd, pkt.data, MAXSIZE, 0, &from.sa, &fromlen);
604
605         if(len <= 0 || len > MAXSIZE) {
606                 if(!sockwouldblock(sockerrno)) {
607                         logger(mesh, MESHLINK_ERROR, "Receiving packet failed: %s", sockstrerror(sockerrno));
608                 }
609
610                 return;
611         }
612
613         pkt.len = len;
614
615         sockaddrunmap(&from); /* Some braindead IPv6 implementations do stupid things. */
616
617         n = lookup_node_udp(mesh, &from);
618
619         if(!n) {
620                 n = try_harder(mesh, &from, &pkt);
621
622                 if(n) {
623                         update_node_udp(mesh, n, &from);
624                 } else if(mesh->log_level <= MESHLINK_WARNING) {
625                         hostname = sockaddr2hostname(&from);
626                         logger(mesh, MESHLINK_WARNING, "Received UDP packet from unknown source %s", hostname);
627                         free(hostname);
628                         return;
629                 } else {
630                         return;
631                 }
632         }
633
634         if(n->status.blacklisted) {
635                 logger(mesh, MESHLINK_WARNING, "Dropping packet from blacklisted node %s", n->name);
636                 return;
637         }
638
639         n->sock = ls - mesh->listen_socket;
640
641         receive_udppacket(mesh, n, &pkt);
642 }