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