Updating HEAD branch #4; Merging CABAL -> HEAD.
[oweals/tinc.git] / src / net_packet.c
1 /*
2     net_packet.c -- Handles in- and outgoing VPN packets
3     Copyright (C) 1998-2002 Ivo Timmermans <itimmermans@bigfoot.com>,
4                   2000-2002 Guus Sliepen <guus@sliepen.warande.net>
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
17     along with this program; if not, write to the Free Software
18     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
19
20     $Id: net_packet.c,v 1.2 2002/04/09 15:26:00 zarq Exp $
21 */
22
23 #include "config.h"
24
25 #include <errno.h>
26 #include <fcntl.h>
27 #include <netdb.h>
28 #include <netinet/in.h>
29 #ifdef HAVE_LINUX
30  #include <netinet/ip.h>
31  #include <netinet/tcp.h>
32 #endif
33 #include <stdio.h>
34 #include <stdlib.h>
35 #include <string.h>
36 #include <signal.h>
37 #include <sys/time.h>
38 #include <sys/types.h>
39 #include <syslog.h>
40 #include <unistd.h>
41 #include <sys/ioctl.h>
42 /* SunOS really wants sys/socket.h BEFORE net/if.h,
43    and FreeBSD wants these lines below the rest. */
44 #include <arpa/inet.h>
45 #include <sys/socket.h>
46 #include <net/if.h>
47
48 #include <openssl/rand.h>
49 #include <openssl/evp.h>
50 #include <openssl/pem.h>
51 #include <openssl/hmac.h>
52
53 #ifndef HAVE_RAND_PSEUDO_BYTES
54 #define RAND_pseudo_bytes RAND_bytes
55 #endif
56
57 #include <zlib.h>
58
59 #include <utils.h>
60 #include <xalloc.h>
61 #include <avl_tree.h>
62 #include <list.h>
63
64 #include "conf.h"
65 #include "connection.h"
66 #include "meta.h"
67 #include "net.h"
68 #include "netutl.h"
69 #include "process.h"
70 #include "protocol.h"
71 #include "subnet.h"
72 #include "graph.h"
73 #include "process.h"
74 #include "route.h"
75 #include "device.h"
76 #include "event.h"
77
78 #include "system.h"
79
80 int keylifetime = 0;
81 int keyexpires = 0;
82
83 #define MAX_SEQNO 1073741824
84
85 /* VPN packet I/O */
86
87 void receive_udppacket(node_t *n, vpn_packet_t *inpkt)
88 {
89   vpn_packet_t pkt1, pkt2;
90   vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
91   int nextpkt = 0;
92   vpn_packet_t *outpkt = pkt[0];
93   int outlen, outpad;
94   long int complen = MTU + 12;
95   EVP_CIPHER_CTX ctx;
96   char hmac[EVP_MAX_MD_SIZE];
97 cp
98   /* Check the message authentication code */
99
100   if(myself->digest && myself->maclength)
101     {
102       inpkt->len -= myself->maclength;
103       HMAC(myself->digest, myself->key, myself->keylength, (char *)&inpkt->seqno, inpkt->len, hmac, NULL);
104       if(memcmp(hmac, (char *)&inpkt->seqno + inpkt->len, myself->maclength))
105         {
106           if(debug_lvl >= DEBUG_TRAFFIC)
107             syslog(LOG_DEBUG, _("Got unauthenticated packet from %s (%s)"), n->name, n->hostname);
108           return;
109         }
110     }
111
112   /* Decrypt the packet */
113
114   if(myself->cipher)
115   {
116     outpkt = pkt[nextpkt++];
117
118     EVP_DecryptInit(&ctx, myself->cipher, myself->key, myself->key + myself->cipher->key_len);
119     EVP_DecryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
120     EVP_DecryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
121
122     outpkt->len = outlen + outpad;
123     inpkt = outpkt;
124   }
125
126   /* Check the sequence number */
127
128   inpkt->len -= sizeof(inpkt->seqno);
129   inpkt->seqno = ntohl(inpkt->seqno);
130
131   if(inpkt->seqno <= n->received_seqno)
132   {
133     if(debug_lvl >= DEBUG_TRAFFIC)
134       syslog(LOG_DEBUG, _("Got late or replayed packet from %s (%s), seqno %d"), n->name, n->hostname, inpkt->seqno);
135     return;
136   }
137   
138   n->received_seqno = inpkt->seqno;
139
140   if(n->received_seqno > MAX_SEQNO)
141     keyexpires = 0;
142
143   /* Decompress the packet */
144   
145   if(myself->compression)
146   {
147     outpkt = pkt[nextpkt++];
148
149     if(uncompress(outpkt->data, &complen, inpkt->data, inpkt->len) != Z_OK)
150     {
151       syslog(LOG_ERR, _("Error while uncompressing packet from %s (%s)"), n->name, n->hostname);
152       return;
153     }
154     
155     outpkt->len = complen;
156     inpkt = outpkt;
157   }
158
159   receive_packet(n, inpkt);
160 cp
161 }
162
163 void receive_tcppacket(connection_t *c, char *buffer, int len)
164 {
165   vpn_packet_t outpkt;
166 cp
167   outpkt.len = len;
168   memcpy(outpkt.data, buffer, len);
169
170   receive_packet(c->node, &outpkt);
171 cp
172 }
173
174 void receive_packet(node_t *n, vpn_packet_t *packet)
175 {
176 cp
177   if(debug_lvl >= DEBUG_TRAFFIC)
178     syslog(LOG_DEBUG, _("Received packet of %d bytes from %s (%s)"), packet->len, n->name, n->hostname);
179
180   route_incoming(n, packet);
181 cp
182 }
183
184 void send_udppacket(node_t *n, vpn_packet_t *inpkt)
185 {
186   vpn_packet_t pkt1, pkt2;
187   vpn_packet_t *pkt[] = {&pkt1, &pkt2, &pkt1, &pkt2};
188   int nextpkt = 0;
189   vpn_packet_t *outpkt;
190   int origlen;
191   int outlen, outpad;
192   long int complen = MTU + 12;
193   EVP_CIPHER_CTX ctx;
194   vpn_packet_t *copy;
195   static int priority = 0;
196   int origpriority;
197   int sock;
198 cp
199   /* Make sure we have a valid key */
200
201   if(!n->status.validkey)
202     {
203       if(debug_lvl >= DEBUG_TRAFFIC)
204         syslog(LOG_INFO, _("No valid key known yet for %s (%s), queueing packet"),
205                n->name, n->hostname);
206
207       /* Since packet is on the stack of handle_tap_input(),
208          we have to make a copy of it first. */
209
210       copy = xmalloc(sizeof(vpn_packet_t));
211       memcpy(copy, inpkt, sizeof(vpn_packet_t));
212
213       list_insert_tail(n->queue, copy);
214
215       if(n->queue->count > MAXQUEUELENGTH)
216         list_delete_head(n->queue);
217
218       if(!n->status.waitingforkey)
219         send_req_key(n->nexthop->connection, myself, n);
220
221       n->status.waitingforkey = 1;
222
223       return;
224     }
225
226   origlen = inpkt->len;
227   origpriority = inpkt->priority;
228
229   /* Compress the packet */
230
231   if(n->compression)
232   {
233     outpkt = pkt[nextpkt++];
234
235     if(compress2(outpkt->data, &complen, inpkt->data, inpkt->len, n->compression) != Z_OK)
236     {
237       syslog(LOG_ERR, _("Error while compressing packet to %s (%s)"), n->name, n->hostname);
238       return;
239     }
240     
241     outpkt->len = complen;
242     inpkt = outpkt;
243   }
244
245   /* Add sequence number */
246
247   inpkt->seqno = htonl(++(n->sent_seqno));
248   inpkt->len += sizeof(inpkt->seqno);
249
250   /* Encrypt the packet */
251
252   if(n->cipher)
253   {
254     outpkt = pkt[nextpkt++];
255
256     EVP_EncryptInit(&ctx, n->cipher, n->key, n->key + n->cipher->key_len);
257     EVP_EncryptUpdate(&ctx, (char *)&outpkt->seqno, &outlen, (char *)&inpkt->seqno, inpkt->len);
258     EVP_EncryptFinal(&ctx, (char *)&outpkt->seqno + outlen, &outpad);
259
260     outpkt->len = outlen + outpad;
261     inpkt = outpkt;
262   }
263
264   /* Add the message authentication code */
265
266   if(n->digest && n->maclength)
267     {
268       HMAC(n->digest, n->key, n->keylength, (char *)&inpkt->seqno, inpkt->len, (char *)&inpkt->seqno + inpkt->len, &outlen);
269       inpkt->len += n->maclength;
270     }
271
272   /* Determine which socket we have to use */
273
274   for(sock = 0; sock < listen_sockets; sock++)
275     if(n->address.sa.sa_family == listen_socket[sock].sa.sa.sa_family)
276       break;
277
278   if(sock >= listen_sockets)
279     sock = 0;  /* If none is available, just use the first and hope for the best. */
280   
281   /* Send the packet */
282
283 #if defined(SOL_IP) && defined(IP_TOS)
284   if(priorityinheritance && origpriority != priority && listen_socket[sock].sa.sa.sa_family == AF_INET)
285     {
286       priority = origpriority;
287       if(debug_lvl >= DEBUG_TRAFFIC)
288         syslog(LOG_DEBUG, _("Setting outgoing packet priority to %d"), priority);
289       if(setsockopt(sock, SOL_IP, IP_TOS, &priority, sizeof(priority))) /* SO_PRIORITY doesn't seem to work */
290         syslog(LOG_ERR, _("System call `%s' failed: %s"), "setsockopt", strerror(errno));
291     }
292 #endif
293
294   if((sendto(listen_socket[sock].udp, (char *)&inpkt->seqno, inpkt->len, 0, &(n->address.sa), SALEN(n->address.sa))) < 0)
295     {
296       syslog(LOG_ERR, _("Error sending packet to %s (%s): %s"),
297              n->name, n->hostname, strerror(errno));
298       return;
299     }
300   
301   inpkt->len = origlen;
302 cp
303 }
304
305 /*
306   send a packet to the given vpn ip.
307 */
308 void send_packet(node_t *n, vpn_packet_t *packet)
309 {
310   node_t *via;
311 cp
312   if(debug_lvl >= DEBUG_TRAFFIC)
313     syslog(LOG_ERR, _("Sending packet of %d bytes to %s (%s)"),
314            packet->len, n->name, n->hostname);
315
316   if(n == myself)
317     {
318       if(debug_lvl >= DEBUG_TRAFFIC)
319         {
320           syslog(LOG_NOTICE, _("Packet is looping back to us!"));
321         }
322
323       return;
324     }
325  
326   if(!n->status.reachable)
327     {
328       if(debug_lvl >= DEBUG_TRAFFIC)
329         syslog(LOG_INFO, _("Node %s (%s) is not reachable"),
330                n->name, n->hostname);
331       return;
332     }
333
334   via = (n->via == myself)?n->nexthop:n->via;
335
336   if(via != n && debug_lvl >= DEBUG_TRAFFIC)
337     syslog(LOG_ERR, _("Sending packet to %s via %s (%s)"),
338            n->name, via->name, n->via->hostname);
339
340   if((myself->options | via->options) & OPTION_TCPONLY)
341     {
342       if(send_tcppacket(via->connection, packet))
343         terminate_connection(via->connection, 1);
344     }
345   else
346     send_udppacket(via, packet);
347 }
348
349 /* Broadcast a packet using the minimum spanning tree */
350
351 void broadcast_packet(node_t *from, vpn_packet_t *packet)
352 {
353   avl_node_t *node;
354   connection_t *c;
355 cp
356   if(debug_lvl >= DEBUG_TRAFFIC)
357     syslog(LOG_INFO, _("Broadcasting packet of %d bytes from %s (%s)"),
358            packet->len, from->name, from->hostname);
359
360   for(node = connection_tree->head; node; node = node->next)
361     {
362       c = (connection_t *)node->data;
363       if(c->status.active && c->status.mst && c != from->nexthop->connection)
364         send_packet(c->node, packet);
365     }
366 cp
367 }
368
369 void flush_queue(node_t *n)
370 {
371   list_node_t *node, *next;
372 cp
373   if(debug_lvl >= DEBUG_TRAFFIC)
374     syslog(LOG_INFO, _("Flushing queue for %s (%s)"), n->name, n->hostname);
375
376   for(node = n->queue->head; node; node = next)
377     {
378       next = node->next;
379       send_udppacket(n, (vpn_packet_t *)node->data);
380       list_delete_node(n->queue, node);
381     }
382 cp
383 }
384
385 void handle_incoming_vpn_data(int sock)
386 {
387   vpn_packet_t pkt;
388   int x, l = sizeof(x);
389   char *hostname;
390   sockaddr_t from;
391   socklen_t fromlen = sizeof(from);
392   node_t *n;
393 cp
394   if(getsockopt(sock, SOL_SOCKET, SO_ERROR, &x, &l) < 0)
395     {
396       syslog(LOG_ERR, _("This is a bug: %s:%d: %d:%s"),
397              __FILE__, __LINE__, sock, strerror(errno));
398       cp_trace();
399       exit(1);
400     }
401   if(x)
402     {
403       syslog(LOG_ERR, _("Incoming data socket error: %s"), strerror(x));
404       return;
405     }
406
407   if((pkt.len = recvfrom(sock, (char *)&pkt.seqno, MAXSIZE, 0, &from.sa, &fromlen)) <= 0)
408     {
409       syslog(LOG_ERR, _("Receiving packet failed: %s"), strerror(errno));
410       return;
411     }
412
413   sockaddrunmap(&from);  /* Some braindead IPv6 implementations do stupid things. */
414
415   n = lookup_node_udp(&from);
416
417   if(!n)
418     {
419       hostname = sockaddr2hostname(&from);
420       syslog(LOG_WARNING, _("Received UDP packet from unknown source %s"), hostname);
421       free(hostname);
422       return;
423     }
424
425   if(n->connection)
426     n->connection->last_ping_time = now;
427
428   receive_udppacket(n, &pkt);
429 cp
430 }
431