ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
(Generate patch)

Comparing gvpe/src/connection.C (file contents):
Revision 1.1 by pcg, Wed Apr 2 03:06:22 2003 UTC vs.
Revision 1.64 by pcg, Tue Dec 4 15:01:12 2007 UTC

1/* 1/*
2 connection.C -- manage a single connection 2 connection.C -- manage a single connection
3 Copyright (C) 2003-2005 Marc Lehmann <gvpe@schmorp.de>
3 4
5 This file is part of GVPE.
6
4 This program is free software; you can redistribute it and/or modify 7 GVPE is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by 8 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2 of the License, or 9 the Free Software Foundation; either version 2 of the License, or
7 (at your option) any later version. 10 (at your option) any later version.
8 11
9 This program is distributed in the hope that it will be useful, 12 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of 13 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details. 15 GNU General Public License for more details.
13 16
14 You should have received a copy of the GNU General Public License 17 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software 18 along with gvpe; if not, write to the Free Software
16 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 19 Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
17*/ 20*/
18 21
19#include "config.h" 22#include "config.h"
20 23
21extern "C" {
22# include "lzf/lzf.h"
23}
24
25#include <list> 24#include <list>
26 25
27#include "gettext.h" 26#include <openssl/rand.h>
27#include <openssl/evp.h>
28#include <openssl/rsa.h>
29#include <openssl/err.h>
28 30
29#include "conf.h" 31#include "conf.h"
30#include "slog.h" 32#include "slog.h"
31#include "device.h" 33#include "device.h"
32#include "protocol.h" 34#include "vpn.h"
33#include "connection.h" 35#include "connection.h"
36
37#include "netcompat.h"
34 38
35#if !HAVE_RAND_PSEUDO_BYTES 39#if !HAVE_RAND_PSEUDO_BYTES
36# define RAND_pseudo_bytes RAND_bytes 40# define RAND_pseudo_bytes RAND_bytes
37#endif 41#endif
38 42
39#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic 43#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
40 44
45#define ULTRA_FAST 1
46#define HLOG 15
47#include "lzf/lzf.h"
48#include "lzf/lzf_c.c"
49#include "lzf/lzf_d.c"
50
41struct crypto_ctx 51struct crypto_ctx
42{ 52{
43 EVP_CIPHER_CTX cctx; 53 EVP_CIPHER_CTX cctx;
44 HMAC_CTX hctx; 54 HMAC_CTX hctx;
45 55
48}; 58};
49 59
50crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc) 60crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
51{ 61{
52 EVP_CIPHER_CTX_init (&cctx); 62 EVP_CIPHER_CTX_init (&cctx);
53 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc); 63 require (EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc));
54 HMAC_CTX_init (&hctx); 64 HMAC_CTX_init (&hctx);
55 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0); 65 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
56} 66}
57 67
58crypto_ctx::~crypto_ctx () 68crypto_ctx::~crypto_ctx ()
59{ 69{
60 EVP_CIPHER_CTX_cleanup (&cctx); 70 require (EVP_CIPHER_CTX_cleanup (&cctx));
61 HMAC_CTX_cleanup (&hctx); 71 HMAC_CTX_cleanup (&hctx);
62} 72}
63 73
64static void 74static void
65rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h) 75rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h)
66{ 76{
67 EVP_MD_CTX ctx; 77 EVP_MD_CTX ctx;
68 78
69 EVP_MD_CTX_init (&ctx); 79 EVP_MD_CTX_init (&ctx);
70 EVP_DigestInit (&ctx, RSA_HASH); 80 require (EVP_DigestInit (&ctx, RSA_HASH));
71 EVP_DigestUpdate(&ctx, &chg, sizeof chg); 81 require (EVP_DigestUpdate(&ctx, &chg, sizeof chg));
72 EVP_DigestUpdate(&ctx, &id, sizeof id); 82 require (EVP_DigestUpdate(&ctx, &id, sizeof id));
73 EVP_DigestFinal (&ctx, (unsigned char *)&h, 0); 83 require (EVP_DigestFinal (&ctx, (unsigned char *)&h, 0));
74 EVP_MD_CTX_cleanup (&ctx); 84 EVP_MD_CTX_cleanup (&ctx);
75} 85}
76 86
77struct rsa_entry { 87struct rsa_entry
88{
78 tstamp expire; 89 tstamp expire;
79 rsaid id; 90 rsaid id;
80 rsachallenge chg; 91 rsachallenge chg;
81}; 92};
82 93
83struct rsa_cache : list<rsa_entry> 94struct rsa_cache : list<rsa_entry>
84{ 95{
85 void cleaner_cb (tstamp &ts); time_watcher cleaner; 96 void cleaner_cb (ev::timer &w, int revents); ev::timer cleaner;
86 97
87 bool find (const rsaid &id, rsachallenge &chg) 98 bool find (const rsaid &id, rsachallenge &chg)
88 { 99 {
89 for (iterator i = begin (); i != end (); ++i) 100 for (iterator i = begin (); i != end (); ++i)
90 { 101 {
91 if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW) 102 if (!memcmp (&id, &i->id, sizeof id) && i->expire > ev_now ())
92 { 103 {
93 memcpy (&chg, &i->chg, sizeof chg); 104 memcpy (&chg, &i->chg, sizeof chg);
94 105
95 erase (i); 106 erase (i);
96 return true; 107 return true;
97 } 108 }
98 } 109 }
99 110
100 if (cleaner.at < NOW) 111 if (!cleaner.is_active ())
101 cleaner.start (NOW + RSA_TTL); 112 cleaner.again ();
102 113
103 return false; 114 return false;
104 } 115 }
105 116
106 void gen (rsaid &id, rsachallenge &chg) 117 void gen (rsaid &id, rsachallenge &chg)
107 { 118 {
108 rsa_entry e; 119 rsa_entry e;
109 120
110 RAND_bytes ((unsigned char *)&id, sizeof id); 121 RAND_bytes ((unsigned char *)&id, sizeof id);
111 RAND_bytes ((unsigned char *)&chg, sizeof chg); 122 RAND_bytes ((unsigned char *)&chg, sizeof chg);
112 123
113 e.expire = NOW + RSA_TTL; 124 e.expire = ev_now () + RSA_TTL;
114 e.id = id; 125 e.id = id;
115 memcpy (&e.chg, &chg, sizeof chg); 126 memcpy (&e.chg, &chg, sizeof chg);
116 127
117 push_back (e); 128 push_back (e);
118 129
119 if (cleaner.at < NOW) 130 if (!cleaner.is_active ())
120 cleaner.start (NOW + RSA_TTL); 131 cleaner.again ();
121 } 132 }
122 133
123 rsa_cache () 134 rsa_cache ()
124 : cleaner (this, &rsa_cache::cleaner_cb) 135 : cleaner (this, &rsa_cache::cleaner_cb)
125 { } 136 {
137 cleaner.set (RSA_TTL, RSA_TTL);
138 }
126 139
127} rsa_cache; 140} rsa_cache;
128 141
129void rsa_cache::cleaner_cb (tstamp &ts) 142void rsa_cache::cleaner_cb (ev::timer &w, int revents)
130{ 143{
131 if (empty ()) 144 if (empty ())
132 ts = TSTAMP_CANCEL; 145 w.stop ();
133 else 146 else
134 { 147 {
135 ts = NOW + RSA_TTL;
136
137 for (iterator i = begin (); i != end (); ) 148 for (iterator i = begin (); i != end (); )
138 if (i->expire <= NOW) 149 if (i->expire <= ev_now ())
139 i = erase (i); 150 i = erase (i);
140 else 151 else
141 ++i; 152 ++i;
142 } 153 }
143} 154}
144 155
145////////////////////////////////////////////////////////////////////////////// 156//////////////////////////////////////////////////////////////////////////////
146 157
147void pkt_queue::put (tap_packet *p) 158void pkt_queue::put (net_packet *p)
148{ 159{
149 if (queue[i]) 160 if (queue[i])
150 { 161 {
151 delete queue[i]; 162 delete queue[i];
152 j = (j + 1) % QUEUEDEPTH; 163 j = (j + 1) % QUEUEDEPTH;
155 queue[i] = p; 166 queue[i] = p;
156 167
157 i = (i + 1) % QUEUEDEPTH; 168 i = (i + 1) % QUEUEDEPTH;
158} 169}
159 170
160tap_packet *pkt_queue::get () 171net_packet *pkt_queue::get ()
161{ 172{
162 tap_packet *p = queue[j]; 173 net_packet *p = queue[j];
163 174
164 if (p) 175 if (p)
165 { 176 {
166 queue[j] = 0; 177 queue[j] = 0;
167 j = (j + 1) % QUEUEDEPTH; 178 j = (j + 1) % QUEUEDEPTH;
181{ 192{
182 for (i = QUEUEDEPTH; --i > 0; ) 193 for (i = QUEUEDEPTH; --i > 0; )
183 delete queue[i]; 194 delete queue[i];
184} 195}
185 196
186struct net_rateinfo { 197struct net_rateinfo
198{
187 u32 host; 199 u32 host;
188 double pcnt, diff; 200 double pcnt, diff;
189 tstamp last; 201 tstamp last;
190}; 202};
191 203
192// only do action once every x seconds per host whole allowing bursts. 204// only do action once every x seconds per host whole allowing bursts.
193// this implementation ("splay list" ;) is inefficient, 205// this implementation ("splay list" ;) is inefficient,
194// but low on resources. 206// but low on resources.
195struct net_rate_limiter : list<net_rateinfo> 207struct net_rate_limiter : list<net_rateinfo>
196{ 208{
197 static const double ALPHA = 1. - 1. / 90.; // allow bursts 209# define NRL_ALPHA (1. - 1. / 600.) // allow bursts
198 static const double CUTOFF = 20.; // one event every CUTOFF seconds 210# define NRL_CUTOFF 10. // one event every CUTOFF seconds
199 static const double EXPIRE = CUTOFF * 30.; // expire entries after this time 211# define NRL_EXPIRE (NRL_CUTOFF * 30.) // expire entries after this time
212# define NRL_MAXDIF (NRL_CUTOFF * (1. / (1. - NRL_ALPHA))) // maximum diff /count value
200 213
201 bool can (const sockinfo &si) { return can((u32)si.host); } 214 bool can (const sockinfo &si) { return can((u32)si.host); }
202 bool can (u32 host); 215 bool can (u32 host);
203}; 216};
204 217
205net_rate_limiter auth_rate_limiter, reset_rate_limiter; 218net_rate_limiter auth_rate_limiter, reset_rate_limiter;
206 219
209 iterator i; 222 iterator i;
210 223
211 for (i = begin (); i != end (); ) 224 for (i = begin (); i != end (); )
212 if (i->host == host) 225 if (i->host == host)
213 break; 226 break;
214 else if (i->last < NOW - EXPIRE) 227 else if (i->last < ev_now () - NRL_EXPIRE)
215 i = erase (i); 228 i = erase (i);
216 else 229 else
217 i++; 230 i++;
218 231
219 if (i == end ()) 232 if (i == end ())
220 { 233 {
221 net_rateinfo ri; 234 net_rateinfo ri;
222 235
223 ri.host = host; 236 ri.host = host;
224 ri.pcnt = 1.; 237 ri.pcnt = 1.;
225 ri.diff = CUTOFF * (1. / (1. - ALPHA)); 238 ri.diff = NRL_MAXDIF;
226 ri.last = NOW; 239 ri.last = ev_now ();
227 240
228 push_front (ri); 241 push_front (ri);
229 242
230 return true; 243 return true;
231 } 244 }
232 else 245 else
233 { 246 {
234 net_rateinfo ri (*i); 247 net_rateinfo ri (*i);
235 erase (i); 248 erase (i);
236 249
237 ri.pcnt = ri.pcnt * ALPHA; 250 ri.pcnt = ri.pcnt * NRL_ALPHA;
238 ri.diff = ri.diff * ALPHA + (NOW - ri.last); 251 ri.diff = ri.diff * NRL_ALPHA + (ev_now () - ri.last);
239 252
240 ri.last = NOW; 253 ri.last = ev_now ();
241 254
255 double dif = ri.diff / ri.pcnt;
256
242 bool send = ri.diff / ri.pcnt > CUTOFF; 257 bool send = dif > NRL_CUTOFF;
243 258
259 if (dif > NRL_MAXDIF)
260 {
261 ri.pcnt = 1.;
262 ri.diff = NRL_MAXDIF;
263 }
244 if (send) 264 else if (send)
245 ri.pcnt++; 265 ri.pcnt++;
246 266
247 push_front (ri); 267 push_front (ri);
248 268
249 return send; 269 return send;
280 hmac_gen (ctx); 300 hmac_gen (ctx);
281 301
282 return !memcmp (hmac, hmac_digest, HMACLENGTH); 302 return !memcmp (hmac, hmac_digest, HMACLENGTH);
283} 303}
284 304
285void vpn_packet::set_hdr (ptype type, unsigned int dst) 305void vpn_packet::set_hdr (ptype type_, unsigned int dst)
286{ 306{
287 this->type = type; 307 type = type_;
288 308
289 int src = THISNODE->id; 309 int src = THISNODE->id;
290 310
291 src1 = src; 311 src1 = src;
292 srcdst = ((src >> 8) << 4) | (dst >> 8); 312 srcdst = ((src >> 8) << 4) | (dst >> 8);
294} 314}
295 315
296#define MAXVPNDATA (MAX_MTU - 6 - 6) 316#define MAXVPNDATA (MAX_MTU - 6 - 6)
297#define DATAHDR (sizeof (u32) + RAND_SIZE) 317#define DATAHDR (sizeof (u32) + RAND_SIZE)
298 318
299struct vpndata_packet:vpn_packet 319struct vpndata_packet : vpn_packet
300 { 320 {
301 u8 data[MAXVPNDATA + DATAHDR]; // seqno 321 u8 data[MAXVPNDATA + DATAHDR]; // seqno
302 322
303 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno); 323 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
304 tap_packet *unpack (connection *conn, u32 &seqno); 324 tap_packet *unpack (connection *conn, u32 &seqno);
317 int outl = 0, outl2; 337 int outl = 0, outl2;
318 ptype type = PT_DATA_UNCOMPRESSED; 338 ptype type = PT_DATA_UNCOMPRESSED;
319 339
320#if ENABLE_COMPRESSION 340#if ENABLE_COMPRESSION
321 u8 cdata[MAX_MTU]; 341 u8 cdata[MAX_MTU];
322 u32 cl;
323 342
343 if (conn->features & ENABLE_COMPRESSION)
344 {
324 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7); 345 u32 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
346
325 if (cl) 347 if (cl)
326 { 348 {
327 type = PT_DATA_COMPRESSED; 349 type = PT_DATA_COMPRESSED;
328 d = cdata; 350 d = cdata;
329 l = cl + 2; 351 l = cl + 2;
330 352
331 d[0] = cl >> 8; 353 d[0] = cl >> 8;
332 d[1] = cl; 354 d[1] = cl;
355 }
333 } 356 }
334#endif 357#endif
335 358
336 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0); 359 require (EVP_EncryptInit_ex (cctx, 0, 0, 0, 0));
337 360
338 struct { 361 struct {
339#if RAND_SIZE 362#if RAND_SIZE
340 u8 rnd[RAND_SIZE]; 363 u8 rnd[RAND_SIZE];
341#endif 364#endif
345 datahdr.seqno = ntohl (seqno); 368 datahdr.seqno = ntohl (seqno);
346#if RAND_SIZE 369#if RAND_SIZE
347 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE); 370 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
348#endif 371#endif
349 372
350 EVP_EncryptUpdate (cctx, 373 require (EVP_EncryptUpdate (cctx,
351 (unsigned char *) data + outl, &outl2, 374 (unsigned char *) data + outl, &outl2,
352 (unsigned char *) &datahdr, DATAHDR); 375 (unsigned char *) &datahdr, DATAHDR));
353 outl += outl2; 376 outl += outl2;
354 377
355 EVP_EncryptUpdate (cctx, 378 require (EVP_EncryptUpdate (cctx,
356 (unsigned char *) data + outl, &outl2, 379 (unsigned char *) data + outl, &outl2,
357 (unsigned char *) d, l); 380 (unsigned char *) d, l));
358 outl += outl2; 381 outl += outl2;
359 382
360 EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2); 383 require (EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2));
361 outl += outl2; 384 outl += outl2;
362 385
363 len = outl + data_hdr_size (); 386 len = outl + data_hdr_size ();
364 387
365 set_hdr (type, dst); 388 set_hdr (type, dst);
374 int outl = 0, outl2; 397 int outl = 0, outl2;
375 tap_packet *p = new tap_packet; 398 tap_packet *p = new tap_packet;
376 u8 *d; 399 u8 *d;
377 u32 l = len - data_hdr_size (); 400 u32 l = len - data_hdr_size ();
378 401
379 EVP_DecryptInit_ex (cctx, 0, 0, 0, 0); 402 require (EVP_DecryptInit_ex (cctx, 0, 0, 0, 0));
380 403
381#if ENABLE_COMPRESSION 404#if ENABLE_COMPRESSION
382 u8 cdata[MAX_MTU]; 405 u8 cdata[MAX_MTU];
383 406
384 if (type == PT_DATA_COMPRESSED) 407 if (type == PT_DATA_COMPRESSED)
386 else 409 else
387#endif 410#endif
388 d = &(*p)[6 + 6 - DATAHDR]; 411 d = &(*p)[6 + 6 - DATAHDR];
389 412
390 /* this overwrites part of the src mac, but we fix that later */ 413 /* this overwrites part of the src mac, but we fix that later */
391 EVP_DecryptUpdate (cctx, 414 require (EVP_DecryptUpdate (cctx,
392 d, &outl2, 415 d, &outl2,
393 (unsigned char *)&data, len - data_hdr_size ()); 416 (unsigned char *)&data, len - data_hdr_size ()));
394 outl += outl2; 417 outl += outl2;
395 418
396 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2); 419 require (EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2));
397 outl += outl2; 420 outl += outl2;
398 421
399 seqno = ntohl (*(u32 *)(d + RAND_SIZE)); 422 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
400 423
401 id2mac (dst () ? dst() : THISNODE->id, p->dst); 424 id2mac (dst () ? dst() : THISNODE->id, p->dst);
430{ 453{
431 // actually, hmaclen cannot be checked because the hmac 454 // actually, hmaclen cannot be checked because the hmac
432 // field comes before this data, so peers with other 455 // field comes before this data, so peers with other
433 // hmacs simply will not work. 456 // hmacs simply will not work.
434 u8 prot_major, prot_minor, randsize, hmaclen; 457 u8 prot_major, prot_minor, randsize, hmaclen;
435 u8 flags, challengelen, pad2, pad3; 458 u8 flags, challengelen, features, pad3;
436 u32 cipher_nid, digest_nid, hmac_nid; 459 u32 cipher_nid, digest_nid, hmac_nid;
437
438 const u8 curflags () const
439 {
440 return 0x80
441 | (ENABLE_COMPRESSION ? 0x01 : 0x00);
442 }
443 460
444 void setup (ptype type, int dst); 461 void setup (ptype type, int dst);
445 bool chk_config () const; 462 bool chk_config () const;
463
464 static u8 get_features ()
465 {
466 u8 f = 0;
467#if ENABLE_COMPRESSION
468 f |= FEATURE_COMPRESSION;
469#endif
470#if ENABLE_ROHC
471 f |= FEATURE_ROHC;
472#endif
473#if ENABLE_BRIDGING
474 f |= FEATURE_BRIDGING;
475#endif
476 return f;
477 }
446}; 478};
447 479
448void config_packet::setup (ptype type, int dst) 480void config_packet::setup (ptype type, int dst)
449{ 481{
450 prot_major = PROTOCOL_MAJOR; 482 prot_major = PROTOCOL_MAJOR;
451 prot_minor = PROTOCOL_MINOR; 483 prot_minor = PROTOCOL_MINOR;
452 randsize = RAND_SIZE; 484 randsize = RAND_SIZE;
453 hmaclen = HMACLENGTH; 485 hmaclen = HMACLENGTH;
454 flags = curflags (); 486 flags = 0;
455 challengelen = sizeof (rsachallenge); 487 challengelen = sizeof (rsachallenge);
488 features = get_features ();
456 489
457 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER)); 490 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
458 digest_nid = htonl (EVP_MD_type (RSA_HASH)); 491 digest_nid = htonl (EVP_MD_type (RSA_HASH));
459 hmac_nid = htonl (EVP_MD_type (DIGEST)); 492 hmac_nid = htonl (EVP_MD_type (DIGEST));
460 493
462 set_hdr (type, dst); 495 set_hdr (type, dst);
463} 496}
464 497
465bool config_packet::chk_config () const 498bool config_packet::chk_config () const
466{ 499{
467 return prot_major == PROTOCOL_MAJOR 500 if (prot_major != PROTOCOL_MAJOR)
468 && randsize == RAND_SIZE 501 slog (L_WARN, _("major version mismatch (remote %d <=> local %d)"), prot_major, PROTOCOL_MAJOR);
469 && hmaclen == HMACLENGTH 502 else if (randsize != RAND_SIZE)
470 && flags == curflags () 503 slog (L_WARN, _("rand size mismatch (remote %d <=> local %d)"), randsize, RAND_SIZE);
504 else if (hmaclen != HMACLENGTH)
505 slog (L_WARN, _("hmac length mismatch (remote %d <=> local %d)"), hmaclen, HMACLENGTH);
471 && challengelen == sizeof (rsachallenge) 506 else if (challengelen != sizeof (rsachallenge))
507 slog (L_WARN, _("challenge length mismatch (remote %d <=> local %d)"), challengelen, sizeof (rsachallenge));
472 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER)) 508 else if (cipher_nid != htonl (EVP_CIPHER_nid (CIPHER)))
509 slog (L_WARN, _("cipher mismatch (remote %x <=> local %x)"), ntohl (cipher_nid), EVP_CIPHER_nid (CIPHER));
473 && digest_nid == htonl (EVP_MD_type (RSA_HASH)) 510 else if (digest_nid != htonl (EVP_MD_type (RSA_HASH)))
511 slog (L_WARN, _("digest mismatch (remote %x <=> local %x)"), ntohl (digest_nid), EVP_MD_type (RSA_HASH));
474 && hmac_nid == htonl (EVP_MD_type (DIGEST)); 512 else if (hmac_nid != htonl (EVP_MD_type (DIGEST)))
513 slog (L_WARN, _("hmac mismatch (remote %x <=> local %x)"), ntohl (hmac_nid), EVP_MD_type (DIGEST));
514 else
515 return true;
516
517 return false;
475} 518}
476 519
477struct auth_req_packet : config_packet 520struct auth_req_packet : config_packet
478{ 521{
479 char magic[8]; 522 char magic[8];
480 u8 initiate; // false if this is just an automatic reply 523 u8 initiate; // false if this is just an automatic reply
481 u8 protocols; // supported protocols (will get patches on forward) 524 u8 protocols; // supported protocols (will be patched on forward)
482 u8 pad2, pad3; 525 u8 pad2, pad3;
483 rsaid id; 526 rsaid id;
484 rsaencrdata encr; 527 rsaencrdata encr;
485 528
486 auth_req_packet (int dst, bool initiate_, u8 protocols_) 529 auth_req_packet (int dst, bool initiate_, u8 protocols_)
541}; 584};
542 585
543///////////////////////////////////////////////////////////////////////////// 586/////////////////////////////////////////////////////////////////////////////
544 587
545void 588void
589connection::connection_established ()
590{
591 slog (L_TRACE, _("%s: possible connection establish (ictx %d, octx %d)"), conf->nodename, !!ictx, !!octx);
592
593 if (ictx && octx)
594 {
595 connectmode = conf->connectmode;
596
597 // make sure rekeying timeouts are slightly asymmetric
598 ev::tstamp rekey_interval = ::conf.rekey + (conf->id > THISNODE->id ? 10 : 0);
599 rekey.start (rekey_interval, rekey_interval);
600 keepalive.start (::conf.keepalive);
601
602 // send queued packets
603 if (ictx && octx)
604 {
605 while (tap_packet *p = (tap_packet *)data_queue.get ())
606 {
607 send_data_packet (p);
608 delete p;
609 }
610
611 while (vpn_packet *p = (vpn_packet *)vpn_queue.get ())
612 {
613 send_vpn_packet (p, si, IPTOS_RELIABILITY);
614 delete p;
615 }
616 }
617 }
618 else
619 {
620 retry_cnt = 0;
621 establish_connection.start (5);
622 keepalive.stop ();
623 rekey.stop ();
624 }
625}
626
627void
546connection::reset_dstaddr () 628connection::reset_si ()
547{ 629{
630 protocol = best_protocol (THISNODE->protocols & conf->protocols);
631
632 // mask out protocols we cannot establish
633 if (!conf->udp_port) protocol &= ~PROT_UDPv4;
634 if (!conf->tcp_port) protocol &= ~PROT_TCPv4;
635 if (!conf->dns_port) protocol &= ~PROT_DNSv4;
636
637 if (protocol
638 && (!conf->can_direct (THISNODE)
639 || !THISNODE->can_direct (conf)))
640 {
641 slog (L_DEBUG, _("%s: direct connection denied"), conf->nodename);
642 protocol = 0;
643 }
644
548 si.set (conf); 645 si.set (conf, protocol);
646}
647
648// ensure sockinfo is valid, forward if necessary
649const sockinfo &
650connection::forward_si (const sockinfo &si) const
651{
652 if (!si.valid ())
653 {
654 connection *r = vpn->find_router ();
655
656 if (r)
657 {
658 slog (L_DEBUG, _("%s: no common protocol, trying indirectly through %s (%s)"),
659 conf->nodename, r->conf->nodename, (const char *)r->si);
660 return r->si;
661 }
662 else
663 slog (L_DEBUG, _("%s: node unreachable, no common protocol"),
664 conf->nodename);
665 }
666
667 return si;
668}
669
670void
671connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
672{
673 if (!vpn->send_vpn_packet (pkt, si, tos))
674 reset_connection ();
549} 675}
550 676
551void 677void
552connection::send_ping (const sockinfo &si, u8 pong) 678connection::send_ping (const sockinfo &si, u8 pong)
553{ 679{
576void 702void
577connection::send_auth_request (const sockinfo &si, bool initiate) 703connection::send_auth_request (const sockinfo &si, bool initiate)
578{ 704{
579 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols); 705 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols);
580 706
581 protocol = best_protocol (THISNODE->protocols & conf->protocols);
582
583 rsachallenge chg; 707 rsachallenge chg;
584
585 rsa_cache.gen (pkt->id, chg); 708 rsa_cache.gen (pkt->id, chg);
586 709 rsa_encrypt (conf->rsa_key, chg, pkt->encr);
587 if (0 > RSA_public_encrypt (sizeof chg,
588 (unsigned char *)&chg, (unsigned char *)&pkt->encr,
589 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
590 fatal ("RSA_public_encrypt error");
591 710
592 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si); 711 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si);
593 712
713 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
714
715 delete pkt;
716}
717
718void
719connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
720{
721 auth_res_packet *pkt = new auth_res_packet (conf->id);
722
723 pkt->id = id;
724
725 rsa_hash (id, chg, pkt->response);
726
727 pkt->hmac_set (octx);
728
729 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
730
594 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly 731 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
595 732
596 delete pkt; 733 delete pkt;
597} 734}
598 735
599void 736void
600connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
601{
602 auth_res_packet *pkt = new auth_res_packet (conf->id);
603
604 pkt->id = id;
605
606 rsa_hash (id, chg, pkt->response);
607
608 pkt->hmac_set (octx);
609
610 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
611
612 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
613
614 delete pkt;
615}
616
617void
618connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols) 737connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
619{ 738{
620 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n", 739 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)",
621 conf->id, rid, (const char *)rsi); 740 conf->id, rid, (const char *)rsi);
622 741
623 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols); 742 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
624 743
625 r->hmac_set (octx); 744 r->hmac_set (octx);
627 746
628 delete r; 747 delete r;
629} 748}
630 749
631void 750void
632connection::establish_connection_cb (tstamp &ts) 751connection::establish_connection_cb (ev::timer &w, int revents)
633{ 752{
634 if (ictx || conf == THISNODE 753 if (!ictx
754 && conf != THISNODE
635 || connectmode == conf_node::C_NEVER 755 && connectmode != conf_node::C_NEVER
636 || connectmode == conf_node::C_DISABLED) 756 && connectmode != conf_node::C_DISABLED
637 ts = TSTAMP_CANCEL; 757 && !w.is_active ())
638 else if (ts <= NOW)
639 { 758 {
640 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6; 759 ev::tstamp retry_int = ev::tstamp (retry_cnt & 3
760 ? (retry_cnt & 3) + 1
761 : 1 << (retry_cnt >> 2));
641 762
642 if (retry_int < 3600 * 8) 763 reset_si ();
643 retry_cnt++;
644 764
645 ts = NOW + retry_int; 765 bool slow = si.prot & PROT_SLOW;
646 766
647 if (conf->hostname) 767 if (si.prot && !si.host)
648 { 768 {
649 reset_dstaddr (); 769 slog (L_TRACE, _("%s: connection request (indirect)"), conf->nodename);
650 if (si.host && auth_rate_limiter.can (si)) 770 /*TODO*/ /* start the timer so we don't recurse endlessly */
651 { 771 w.start (1);
652 if (retry_cnt < 4) 772 vpn->send_connect_request (conf->id);
653 send_auth_request (si, true);
654 else
655 send_ping (si, 0);
656 }
657 } 773 }
658 else 774 else
659 vpn->connect_request (conf->id); 775 {
776 slog (L_TRACE, _("%s: connection request (direct)"), conf->nodename, !!ictx, !!octx);
777
778 const sockinfo &dsi = forward_si (si);
779
780 slow = slow || (dsi.prot & PROT_SLOW);
781
782 if (dsi.valid () && auth_rate_limiter.can (dsi))
783 {
784 if (retry_cnt < 4)
785 send_auth_request (dsi, true);
786 else
787 send_ping (dsi, 0);
788 }
789 }
790
791 retry_int *= slow ? 8. : 0.7;
792
793 if (retry_int < conf->max_retry)
794 retry_cnt++;
795 else
796 retry_int = conf->max_retry;
797
798 w.start (retry_int);
660 } 799 }
661} 800}
662 801
663void 802void
664connection::reset_connection () 803connection::reset_connection ()
667 { 806 {
668 slog (L_INFO, _("%s(%s): connection lost"), 807 slog (L_INFO, _("%s(%s): connection lost"),
669 conf->nodename, (const char *)si); 808 conf->nodename, (const char *)si);
670 809
671 if (::conf.script_node_down) 810 if (::conf.script_node_down)
672 run_script (run_script_cb (this, &connection::script_node_down), false); 811 {
812 run_script_cb cb;
813 callback_set (cb, this, connection, script_node_down);
814 if (!run_script (cb, false))
815 slog (L_WARN, _("node-down command execution failed, continuing."));
816 }
673 } 817 }
674 818
675 delete ictx; ictx = 0; 819 delete ictx; ictx = 0;
676 delete octx; octx = 0; 820 delete octx; octx = 0;
821#if ENABLE_DNS
822 dnsv4_reset_connection ();
823#endif
677 824
678 si.host= 0; 825 si.host = 0;
679 826
680 last_activity = 0; 827 last_activity = 0;
681 retry_cnt = 0; 828 retry_cnt = 0;
682 829
683 rekey.reset (); 830 rekey.stop ();
684 keepalive.reset (); 831 keepalive.stop ();
685 establish_connection.reset (); 832 establish_connection.stop ();
686} 833}
687 834
688void 835void
689connection::shutdown () 836connection::shutdown ()
690{ 837{
693 840
694 reset_connection (); 841 reset_connection ();
695} 842}
696 843
697void 844void
698connection::rekey_cb (tstamp &ts) 845connection::rekey_cb (ev::timer &w, int revents)
699{ 846{
700 ts = TSTAMP_CANCEL;
701
702 reset_connection (); 847 reset_connection ();
703 establish_connection (); 848 establish_connection ();
704} 849}
705 850
706void 851void
707connection::send_data_packet (tap_packet *pkt, bool broadcast) 852connection::send_data_packet (tap_packet *pkt)
708{ 853{
709 vpndata_packet *p = new vpndata_packet; 854 vpndata_packet *p = new vpndata_packet;
710 int tos = 0; 855 int tos = 0;
711 856
712 if (conf->inherit_tos 857 // I am not hilarious about peeking into packets, but so be it.
713 && (*pkt)[12] == 0x08 && (*pkt)[13] == 0x00 // IP 858 if (conf->inherit_tos && pkt->is_ipv4 ())
714 && ((*pkt)[14] & 0xf0) == 0x40) // IPv4
715 tos = (*pkt)[15] & IPTOS_TOS_MASK; 859 tos = (*pkt)[15] & IPTOS_TOS_MASK;
716 860
717 p->setup (this, broadcast ? 0 : conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs 861 p->setup (this, conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
718 send_vpn_packet (p, si, tos); 862 send_vpn_packet (p, si, tos);
719 863
720 delete p; 864 delete p;
721 865
722 if (oseqno > MAX_SEQNO) 866 if (oseqno > MAX_SEQNO)
723 rekey (); 867 rekey ();
724} 868}
725 869
726void 870void
727connection::inject_data_packet (tap_packet *pkt, bool broadcast) 871connection::inject_data_packet (tap_packet *pkt, bool broadcast/*TODO DDD*/)
728{ 872{
729 if (ictx && octx) 873 if (ictx && octx)
730 send_data_packet (pkt, broadcast); 874 send_data_packet (pkt);
731 else 875 else
732 { 876 {
733 if (!broadcast)//DDDD 877 if (!broadcast)
734 queue.put (new tap_packet (*pkt)); 878 data_queue.put (new tap_packet (*pkt));
735 879
736 establish_connection (); 880 establish_connection ();
737 } 881 }
738} 882}
739 883
884void connection::inject_vpn_packet (vpn_packet *pkt, int tos)
885{
886 if (ictx && octx)
887 send_vpn_packet (pkt, si, tos);
888 else
889 {
890 vpn_queue.put ((vpn_packet *)new data_packet (*(data_packet *)pkt));
891
892 establish_connection ();
893 }
894}
895
740void 896void
741connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi) 897connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
742{ 898{
743 last_activity = NOW; 899 last_activity = ev_now ();
744 900
745 slog (L_NOISE, "<<%d received packet type %d from %d to %d", 901 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
746 conf->id, pkt->typ (), pkt->src (), pkt->dst ()); 902 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
747 903
904 if (connectmode == conf_node::C_DISABLED)
905 return;
906
748 switch (pkt->typ ()) 907 switch (pkt->typ ())
749 { 908 {
750 case vpn_packet::PT_PING: 909 case vpn_packet::PT_PING:
751 // we send pings instead of auth packets after some retries, 910 // we send pings instead of auth packets after some retries,
752 // so reset the retry counter and establish a connection 911 // so reset the retry counter and establish a connection
753 // when we receive a ping. 912 // when we receive a ping.
754 if (!ictx) 913 if (!ictx)
914 {
915 if (auth_rate_limiter.can (rsi))
916 send_auth_request (rsi, true);
917 }
918 else
919 send_ping (rsi, 1); // pong
920
921 break;
922
923 case vpn_packet::PT_PONG:
924 break;
925
926 case vpn_packet::PT_RESET:
755 { 927 {
756 if (auth_rate_limiter.can (rsi)) 928 reset_connection ();
757 send_auth_request (rsi, true); 929
930 config_packet *p = (config_packet *) pkt;
931
932 if (!p->chk_config ())
933 {
934 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
935 conf->nodename, (const char *)rsi);
936 connectmode = conf_node::C_DISABLED;
937 }
938 else if (connectmode == conf_node::C_ALWAYS)
939 establish_connection ();
758 } 940 }
759 else
760 send_ping (rsi, 1); // pong
761
762 break; 941 break;
763 942
764 case vpn_packet::PT_PONG:
765 break;
766
767 case vpn_packet::PT_RESET: 943 case vpn_packet::PT_AUTH_REQ:
768 { 944 if (auth_rate_limiter.can (rsi))
769 reset_connection ();
770
771 config_packet *p = (config_packet *) pkt;
772
773 if (!p->chk_config ())
774 { 945 {
946 auth_req_packet *p = (auth_req_packet *) pkt;
947
948 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
949
950 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
951 {
952 if (p->prot_minor != PROTOCOL_MINOR)
953 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
954 conf->nodename, (const char *)rsi,
955 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
956
957 if (p->initiate)
958 send_auth_request (rsi, false);
959
960 rsachallenge k;
961
962 if (!rsa_decrypt (::conf.rsa_key, p->encr, k))
963 {
964 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"),
965 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0));
966 break;
967 }
968 else
969 {
970 delete octx;
971
972 octx = new crypto_ctx (k, 1);
973 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
974
975 conf->protocols = p->protocols;
976 features = p->features & config_packet::get_features ();
977
978 send_auth_response (rsi, p->id, k);
979
980 connection_established ();
981
982 break;
983 }
984 }
985 else
775 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"), 986 slog (L_WARN, _("%s(%s): protocol mismatch"),
776 conf->nodename, (const char *)rsi); 987 conf->nodename, (const char *)rsi);
777 connectmode = conf_node::C_DISABLED; 988
989 send_reset (rsi);
778 } 990 }
779 else if (connectmode == conf_node::C_ALWAYS) 991
780 establish_connection ();
781 }
782 break; 992 break;
783 993
784 case vpn_packet::PT_AUTH_REQ: 994 case vpn_packet::PT_AUTH_RES:
785 if (auth_rate_limiter.can (rsi))
786 { 995 {
787 auth_req_packet *p = (auth_req_packet *) pkt; 996 auth_res_packet *p = (auth_res_packet *) pkt;
788 997
789 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate); 998 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
790 999
791 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8)) 1000 if (p->chk_config ())
792 { 1001 {
793 if (p->prot_minor != PROTOCOL_MINOR) 1002 if (p->prot_minor != PROTOCOL_MINOR)
794 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."), 1003 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
795 conf->nodename, (const char *)rsi, 1004 conf->nodename, (const char *)rsi,
796 PROTOCOL_MINOR, conf->nodename, p->prot_minor); 1005 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
797 1006
798 if (p->initiate)
799 send_auth_request (rsi, false);
800
801 rsachallenge k; 1007 rsachallenge chg;
802 1008
803 if (0 > RSA_private_decrypt (sizeof (p->encr), 1009 if (!rsa_cache.find (p->id, chg))
804 (unsigned char *)&p->encr, (unsigned char *)&k, 1010 {
805 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) 1011 slog (L_ERR, _("%s(%s): unrequested auth response ignored"),
806 slog (L_ERR, _("%s(%s): challenge illegal or corrupted"),
807 conf->nodename, (const char *)rsi); 1012 conf->nodename, (const char *)rsi);
1013 break;
1014 }
808 else 1015 else
809 { 1016 {
810 retry_cnt = 0; 1017 crypto_ctx *cctx = new crypto_ctx (chg, 0);
811 establish_connection.set (NOW + 8); //? ;) 1018
812 keepalive.reset (); 1019 if (!p->hmac_chk (cctx))
1020 {
1021 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
1022 "could be an attack, or just corruption or a synchronization error"),
1023 conf->nodename, (const char *)rsi);
1024 break;
1025 }
813 rekey.reset (); 1026 else
1027 {
1028 rsaresponse h;
814 1029
1030 rsa_hash (p->id, chg, h);
1031
1032 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
1033 {
1034 prot_minor = p->prot_minor;
1035
1036 delete ictx; ictx = cctx;
1037
1038 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
1039
1040 si = rsi;
1041 protocol = rsi.prot;
1042
1043 connection_established ();
1044
1045 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
1046 conf->nodename, (const char *)rsi,
1047 p->prot_major, p->prot_minor);
1048
1049 if (::conf.script_node_up)
1050 {
1051 run_script_cb cb;
1052 callback_set (cb, this, connection, script_node_up);
1053 if (!run_script (cb, false))
1054 slog (L_WARN, _("node-up command execution failed, continuing."));
1055 }
1056
1057 break;
1058 }
1059 else
1060 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
1061 conf->nodename, (const char *)rsi);
1062 }
1063
815 delete ictx; 1064 delete cctx;
816 ictx = 0;
817
818 delete octx;
819
820 octx = new crypto_ctx (k, 1);
821 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
822
823 conf->protocols = p->protocols;
824 send_auth_response (rsi, p->id, k);
825
826 break;
827 } 1065 }
828 } 1066 }
829
830 send_reset (rsi);
831 } 1067 }
832 1068
1069 send_reset (rsi);
833 break; 1070 break;
834 1071
835 case vpn_packet::PT_AUTH_RES: 1072 case vpn_packet::PT_DATA_COMPRESSED:
836 { 1073#if !ENABLE_COMPRESSION
837 auth_res_packet *p = (auth_res_packet *) pkt; 1074 send_reset (rsi);
1075 break;
1076#endif
838 1077
839 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id); 1078 case vpn_packet::PT_DATA_UNCOMPRESSED:
840 1079
841 if (p->chk_config ()) 1080 if (ictx && octx)
842 { 1081 {
843 if (p->prot_minor != PROTOCOL_MINOR) 1082 vpndata_packet *p = (vpndata_packet *)pkt;
844 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
845 conf->nodename, (const char *)rsi,
846 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
847 1083
848 rsachallenge chg; 1084 if (!p->hmac_chk (ictx))
849 1085 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
850 if (!rsa_cache.find (p->id, chg)) 1086 "could be an attack, or just corruption or a synchronization error"),
851 slog (L_ERR, _("%s(%s): unrequested auth response"),
852 conf->nodename, (const char *)rsi); 1087 conf->nodename, (const char *)rsi);
853 else 1088 else
854 { 1089 {
855 crypto_ctx *cctx = new crypto_ctx (chg, 0);
856
857 if (!p->hmac_chk (cctx))
858 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
859 "could be an attack, or just corruption or an synchronization error"),
860 conf->nodename, (const char *)rsi);
861 else 1090 u32 seqno;
1091 tap_packet *d = p->unpack (this, seqno);
1092
1093 if (iseqno.recv_ok (seqno))
862 { 1094 {
863 rsaresponse h; 1095 vpn->tap->send (d);
864 1096
865 rsa_hash (p->id, chg, h); 1097 if (si != rsi)
866
867 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
868 { 1098 {
869 prot_minor = p->prot_minor; 1099 // fast re-sync on source address changes, useful especially for tcp/ip
870
871 delete ictx; ictx = cctx;
872
873 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
874
875 si = rsi; 1100 si = rsi;
876 1101
877 rekey.set (NOW + ::conf.rekey); 1102 slog (L_INFO, _("%s(%s): socket address changed to %s"),
878 keepalive.set (NOW + ::conf.keepalive);
879
880 // send queued packets
881 while (tap_packet *p = queue.get ())
882 {
883 send_data_packet (p);
884 delete p;
885 }
886
887 connectmode = conf->connectmode;
888
889 slog (L_INFO, _("%s(%s): %s connection established, protocol version %d.%d"),
890 conf->nodename, (const char *)rsi, 1103 conf->nodename, (const char *)si, (const char *)rsi);
891 strprotocol (protocol),
892 p->prot_major, p->prot_minor);
893
894 if (::conf.script_node_up)
895 run_script (run_script_cb (this, &connection::script_node_up), false);
896
897 break;
898 } 1104 }
899 else
900 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
901 conf->nodename, (const char *)rsi);
902 } 1105 }
903 1106
904 delete cctx; 1107 delete d;
1108 break;
905 } 1109 }
906 } 1110 }
907 }
908 1111
909 send_reset (rsi); 1112 send_reset (rsi);
910 break; 1113 break;
911 1114
912 case vpn_packet::PT_DATA_COMPRESSED:
913#if !ENABLE_COMPRESSION
914 send_reset (rsi);
915 break;
916#endif
917
918 case vpn_packet::PT_DATA_UNCOMPRESSED:
919
920 if (ictx && octx)
921 {
922 vpndata_packet *p = (vpndata_packet *)pkt;
923
924 if (rsi == si)
925 {
926 if (!p->hmac_chk (ictx))
927 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
928 "could be an attack, or just corruption or an synchronization error"),
929 conf->nodename, (const char *)rsi);
930 else
931 {
932 u32 seqno;
933 tap_packet *d = p->unpack (this, seqno);
934
935 if (iseqno.recv_ok (seqno))
936 {
937 vpn->tap->send (d);
938
939 if (p->dst () == 0) // re-broadcast
940 for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i)
941 {
942 connection *c = *i;
943
944 if (c->conf != THISNODE && c->conf != conf)
945 c->inject_data_packet (d);
946 }
947
948 delete d;
949
950 break;
951 }
952 }
953 }
954 else
955 slog (L_ERR, _("received data packet from unknown source %s"), (const char *)rsi);
956 }
957
958 send_reset (rsi);
959 break;
960
961 case vpn_packet::PT_CONNECT_REQ: 1115 case vpn_packet::PT_CONNECT_REQ:
962 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx)) 1116 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
963 { 1117 {
964 connect_req_packet *p = (connect_req_packet *) pkt; 1118 connect_req_packet *p = (connect_req_packet *) pkt;
965 1119
966 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything 1120 if (p->id > 0 && p->id <= vpn->conns.size ())
967 conf->protocols = p->protocols; 1121 {
968 connection *c = vpn->conns[p->id - 1]; 1122 connection *c = vpn->conns[p->id - 1];
1123 conf->protocols = p->protocols;
969 1124
970 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]\n", 1125 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]",
971 conf->id, p->id, c->ictx && c->octx); 1126 conf->id, p->id, c->ictx && c->octx);
972 1127
973 if (c->ictx && c->octx) 1128 if (c->ictx && c->octx)
974 { 1129 {
975 // send connect_info packets to both sides, in case one is 1130 // send connect_info packets to both sides, in case one is
976 // behind a nat firewall (or both ;) 1131 // behind a nat firewall (or both ;)
977 c->send_connect_info (conf->id, si, conf->protocols); 1132 c->send_connect_info (conf->id, si, conf->protocols);
978 send_connect_info (c->conf->id, c->si, c->conf->protocols); 1133 send_connect_info (c->conf->id, c->si, c->conf->protocols);
1134 }
1135 else
1136 c->establish_connection ();
979 } 1137 }
1138 else
1139 slog (L_WARN,
1140 _("received authenticated connection request from unknown node #%d, config file mismatch?"),
1141 p->id);
980 } 1142 }
981 1143
982 break; 1144 break;
983 1145
984 case vpn_packet::PT_CONNECT_INFO: 1146 case vpn_packet::PT_CONNECT_INFO:
985 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx)) 1147 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
986 { 1148 {
987 connect_info_packet *p = (connect_info_packet *) pkt; 1149 connect_info_packet *p = (connect_info_packet *)pkt;
988 1150
989 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything 1151 if (p->id > 0 && p->id <= vpn->conns.size ())
990 conf->protocols = p->protocols; 1152 {
991 connection *c = vpn->conns[p->id - 1]; 1153 connection *c = vpn->conns[p->id - 1];
992 1154
1155 c->conf->protocols = p->protocols;
1156 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1157 p->si.upgrade_protocol (protocol, c->conf);
1158
993 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)", 1159 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
994 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx); 1160 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
995 1161
1162 const sockinfo &dsi = forward_si (p->si);
1163
1164 if (dsi.valid ())
996 c->send_auth_request (p->si, true); 1165 c->send_auth_request (dsi, true);
1166 }
1167 else
1168 slog (L_WARN,
1169 _("received authenticated connection request from unknown node #%d, config file mismatch?"),
1170 p->id);
997 } 1171 }
998 1172
999 break; 1173 break;
1000 1174
1001 default: 1175 default:
1002 send_reset (rsi); 1176 send_reset (rsi);
1003 break; 1177 break;
1004
1005 } 1178 }
1006} 1179}
1007 1180
1008void connection::keepalive_cb (tstamp &ts) 1181void connection::keepalive_cb (ev::timer &w, int revents)
1009{ 1182{
1010 if (NOW >= last_activity + ::conf.keepalive + 30) 1183 if (ev_now () >= last_activity + ::conf.keepalive + 30)
1011 { 1184 {
1012 reset_connection (); 1185 reset_connection ();
1013 establish_connection (); 1186 establish_connection ();
1014 } 1187 }
1015 else if (NOW < last_activity + ::conf.keepalive) 1188 else if (ev_now () < last_activity + ::conf.keepalive)
1016 ts = last_activity + ::conf.keepalive; 1189 w.start (last_activity + ::conf.keepalive - ev::now ());
1017 else if (conf->connectmode != conf_node::C_ONDEMAND 1190 else if (conf->connectmode != conf_node::C_ONDEMAND
1018 || THISNODE->connectmode != conf_node::C_ONDEMAND) 1191 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1019 { 1192 {
1020 send_ping (si); 1193 send_ping (si);
1021 ts = NOW + 5; 1194 w.start (5);
1022 } 1195 }
1196 else if (ev_now () < last_activity + ::conf.keepalive + 10)
1197 // hold ondemand connections implicitly a few seconds longer
1198 // should delete octx, though, or something like that ;)
1199 w.start (last_activity + ::conf.keepalive + 10 - ev::now ());
1023 else 1200 else
1024 reset_connection (); 1201 reset_connection ();
1025} 1202}
1026 1203
1027void connection::connect_request (int id) 1204void connection::send_connect_request (int id)
1028{ 1205{
1029 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols); 1206 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols);
1030 1207
1031 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id); 1208 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id);
1032 p->hmac_set (octx); 1209 p->hmac_set (octx);
1033 send_vpn_packet (p, si); 1210 send_vpn_packet (p, si);
1034 1211
1035 delete p; 1212 delete p;
1036} 1213}
1037 1214
1215void connection::script_init_env (const char *ext)
1216{
1217 char *env;
1218 asprintf (&env, "IFUPDATA%s=%s", ext, conf->if_up_data); putenv (env);
1219 asprintf (&env, "NODENAME%s=%s", ext, conf->nodename); putenv (env);
1220 asprintf (&env, "MAC%s=%02x:%02x:%02x:%02x:%02x:%02x", ext,
1221 0xfe, 0xfd, 0x80, 0x00, conf->id >> 8,
1222 conf->id & 0xff); putenv (env);
1223}
1224
1038void connection::script_node () 1225void connection::script_init_connect_env ()
1039{ 1226{
1040 vpn->script_if_up (0); 1227 vpn->script_init_env ();
1041 1228
1042 char *env; 1229 char *env;
1043 asprintf (&env, "DESTID=%d", conf->id); putenv (env); 1230 asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1044 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env); 1231 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1045 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env); 1232 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1046 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env); 1233 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1047} 1234}
1048 1235
1049const char *connection::script_node_up (int) 1236const char *connection::script_node_up ()
1050{ 1237{
1051 script_node (); 1238 script_init_connect_env ();
1052 1239
1053 putenv ("STATE=up"); 1240 putenv ((char *)"STATE=up");
1054 1241
1242 char *filename;
1243 asprintf (&filename,
1244 "%s/%s",
1245 confbase,
1055 return ::conf.script_node_up ? ::conf.script_node_up : "node-up"; 1246 ::conf.script_node_up ? ::conf.script_node_up : "node-up");
1056}
1057 1247
1248 return filename;
1249}
1250
1058const char *connection::script_node_down (int) 1251const char *connection::script_node_down ()
1059{ 1252{
1060 script_node (); 1253 script_init_connect_env ();
1061 1254
1062 putenv ("STATE=down"); 1255 putenv ((char *)"STATE=down");
1063 1256
1064 return ::conf.script_node_up ? ::conf.script_node_down : "node-down"; 1257 char *filename;
1065} 1258 asprintf (&filename,
1259 "%s/%s",
1260 confbase,
1261 ::conf.script_node_down ? ::conf.script_node_down : "node-down");
1066 1262
1067// send a vpn packet out to other hosts 1263 return filename;
1068void
1069connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
1070{
1071 if (protocol & PROT_IPv4)
1072 vpn->send_ipv4_packet (pkt, si, tos);
1073 else
1074 vpn->send_udpv4_packet (pkt, si, tos);
1075} 1264}
1076 1265
1077connection::connection(struct vpn *vpn_) 1266connection::connection (struct vpn *vpn, conf_node *conf)
1078: vpn(vpn_) 1267: vpn(vpn), conf(conf)
1079, rekey (this, &connection::rekey_cb) 1268, rekey (this, &connection::rekey_cb)
1080, keepalive (this, &connection::keepalive_cb) 1269, keepalive (this, &connection::keepalive_cb)
1081, establish_connection (this, &connection::establish_connection_cb) 1270, establish_connection (this, &connection::establish_connection_cb)
1271#if ENABLE_DNS
1272, dns (0)
1273#endif
1082{ 1274{
1083 octx = ictx = 0; 1275 octx = ictx = 0;
1084 retry_cnt = 0; 1276 retry_cnt = 0;
1085 1277
1278 if (!conf->protocols) // make sure some protocol is enabled
1279 conf->protocols = PROT_UDPv4;
1280
1086 connectmode = conf_node::C_ALWAYS; // initial setting 1281 connectmode = conf_node::C_ALWAYS; // initial setting
1087 reset_connection (); 1282 reset_connection ();
1088} 1283}
1089 1284
1090connection::~connection () 1285connection::~connection ()

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines