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

Comparing gvpe/src/protocol.C (file contents):
Revision 1.5 by pcg, Sat Mar 8 10:48:41 2003 UTC vs.
Revision 1.17 by pcg, Wed Mar 26 01:58:46 2003 UTC

16 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17*/ 17*/
18 18
19#include "config.h" 19#include "config.h"
20 20
21#include <list>
22
21#include <cstdlib> 23#include <cstdlib>
22#include <cstring> 24#include <cstring>
23#include <cstdio> 25#include <cstdio>
24 26
25#include <sys/types.h> 27#include <sys/types.h>
56 58
57static time_t next_timecheck; 59static time_t next_timecheck;
58 60
59#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic 61#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
60 62
61static const rsachallenge & 63struct crypto_ctx
62challenge_bytes ()
63{
64 static rsachallenge challenge;
65 static time_t challenge_ttl; // time this challenge needs to be recreated
66
67 if (now > challenge_ttl)
68 { 64 {
69 RAND_bytes ((unsigned char *)&challenge, sizeof (challenge)); 65 EVP_CIPHER_CTX cctx;
70 challenge_ttl = now + CHALLENGE_TTL; 66 HMAC_CTX hctx;
71 }
72 67
73 return challenge; 68 crypto_ctx (const rsachallenge &challenge, int enc);
74} 69 ~crypto_ctx ();
70 };
75 71
76// run a script. yes, it's a template function. yes, c++ 72crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
77// is not a functional language. yes, this suxx. 73{
78template<class owner> 74 EVP_CIPHER_CTX_init (&cctx);
75 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
76 HMAC_CTX_init (&hctx);
77 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
78}
79
80crypto_ctx::~crypto_ctx ()
81{
82 EVP_CIPHER_CTX_cleanup (&cctx);
83 HMAC_CTX_cleanup (&hctx);
84}
85
79static void 86static void
80run_script (owner *obj, const char *(owner::*setup)(), bool wait) 87rsa_hash (const rsachallenge &chg, rsaresponse &h)
88{
89 EVP_MD_CTX ctx;
90
91 EVP_MD_CTX_init (&ctx);
92 EVP_DigestInit (&ctx, RSA_HASH);
93 EVP_DigestUpdate(&ctx, &chg, sizeof chg);
94 EVP_DigestFinal (&ctx, (unsigned char *)&h, 0);
95 EVP_MD_CTX_cleanup (&ctx);
96}
97
98struct rsa_entry {
99 tstamp expire;
100 rsaid id;
101 rsachallenge chg;
102};
103
104struct rsa_cache : list<rsa_entry>
105{
106 void cleaner_cb (tstamp &ts); time_watcher cleaner;
107
108 bool find (const rsaid &id, rsachallenge &chg)
109 {
110 for (iterator i = begin (); i != end (); ++i)
111 {
112 if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW)
113 {
114 memcpy (&chg, &i->chg, sizeof chg);
115
116 erase (i);
117 return true;
118 }
119 }
120
121 if (cleaner.at < NOW)
122 cleaner.start (NOW + RSA_TTL);
123
124 return false;
125 }
126
127 void gen (rsaid &id, rsachallenge &chg)
128 {
129 rsa_entry e;
130
131 RAND_bytes ((unsigned char *)&id, sizeof id);
132 RAND_bytes ((unsigned char *)&chg, sizeof chg);
133
134 e.expire = NOW + RSA_TTL;
135 e.id = id;
136 memcpy (&e.chg, &chg, sizeof chg);
137
138 push_back (e);
139
140 if (cleaner.at < NOW)
141 cleaner.start (NOW + RSA_TTL);
142 }
143
144 rsa_cache ()
145 : cleaner (this, &rsa_cache::cleaner_cb)
146 { }
147
148} rsa_cache;
149
150void rsa_cache::cleaner_cb (tstamp &ts)
151{
152 if (empty ())
153 ts = TSTAMP_CANCEL;
154 else
155 {
156 ts = NOW + RSA_TTL;
157
158 for (iterator i = begin (); i != end (); )
159 if (i->expire <= NOW)
160 i = erase (i);
161 else
162 ++i;
163 }
164}
165
166typedef callback<const char *, int> run_script_cb;
167
168// run a shell script (or actually an external program).
169static void
170run_script (const run_script_cb &cb, bool wait)
81{ 171{
82 int pid; 172 int pid;
83 173
84 if ((pid = fork ()) == 0) 174 if ((pid = fork ()) == 0)
85 { 175 {
86 char *filename; 176 char *filename;
87 asprintf (&filename, "%s/%s", confbase, (obj->*setup) ()); 177 asprintf (&filename, "%s/%s", confbase, cb(0));
88 execl (filename, filename, (char *) 0); 178 execl (filename, filename, (char *) 0);
89 exit (255); 179 exit (255);
90 } 180 }
91 else if (pid > 0) 181 else if (pid > 0)
92 { 182 {
96 /* TODO: check status */ 186 /* TODO: check status */
97 } 187 }
98 } 188 }
99} 189}
100 190
101// xor the socket address into the challenge to ensure different challenges 191//////////////////////////////////////////////////////////////////////////////
102// per host. we could rely on the OAEP padding, but this doesn't hurt.
103void
104xor_sa (rsachallenge &k, SOCKADDR *sa)
105{
106 ((u32 *) k)[(CHG_CIPHER_KEY + 0) / 4] ^= sa->sin_addr.s_addr;
107 ((u16 *) k)[(CHG_CIPHER_KEY + 4) / 2] ^= sa->sin_port;
108 ((u32 *) k)[(CHG_HMAC_KEY + 0) / 4] ^= sa->sin_addr.s_addr;
109 ((u16 *) k)[(CHG_HMAC_KEY + 4) / 2] ^= sa->sin_port;
110}
111 192
112struct crypto_ctx 193void pkt_queue::put (tap_packet *p)
194{
195 if (queue[i])
113 { 196 {
114 EVP_CIPHER_CTX cctx; 197 delete queue[i];
115 HMAC_CTX hctx; 198 j = (j + 1) % QUEUEDEPTH;
199 }
116 200
117 crypto_ctx (rsachallenge &challenge, int enc); 201 queue[i] = p;
118 ~crypto_ctx ();
119 };
120 202
121crypto_ctx::crypto_ctx (rsachallenge &challenge, int enc) 203 i = (i + 1) % QUEUEDEPTH;
122{
123 EVP_CIPHER_CTX_init (&cctx);
124 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
125 HMAC_CTX_init (&hctx);
126 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
127} 204}
128 205
129crypto_ctx::~crypto_ctx () 206tap_packet *pkt_queue::get ()
130{ 207{
131 EVP_CIPHER_CTX_cleanup (&cctx); 208 tap_packet *p = queue[j];
132 HMAC_CTX_cleanup (&hctx); 209
210 if (p)
211 {
212 queue[j] = 0;
213 j = (j + 1) % QUEUEDEPTH;
214 }
215
216 return p;
217}
218
219pkt_queue::pkt_queue ()
220{
221 memset (queue, 0, sizeof (queue));
222 i = 0;
223 j = 0;
224}
225
226pkt_queue::~pkt_queue ()
227{
228 for (i = QUEUEDEPTH; --i > 0; )
229 delete queue[i];
230}
231
232struct net_rateinfo {
233 u32 host;
234 double pcnt, diff;
235 tstamp last;
236};
237
238// only do action once every x seconds per host whole allowing bursts.
239// this implementation ("splay list" ;) is inefficient,
240// but low on resources.
241struct net_rate_limiter : private list<net_rateinfo>
242{
243 static const double ALPHA = 1. - 1. / 90.; // allow bursts
244 static const double CUTOFF = 20.; // one event every CUTOFF seconds
245 static const double EXPIRE = CUTOFF * 30.; // expire entries after this time
246
247 bool can (u32 host);
248 bool can (SOCKADDR *sa) { return can((u32)sa->sin_addr.s_addr); }
249 bool can (sockinfo &si) { return can((u32)si.host); }
250};
251
252net_rate_limiter auth_rate_limiter, reset_rate_limiter;
253
254bool net_rate_limiter::can (u32 host)
255{
256 iterator i;
257
258 for (i = begin (); i != end (); )
259 if (i->host == host)
260 break;
261 else if (i->last < NOW - EXPIRE)
262 i = erase (i);
263 else
264 i++;
265
266 if (i == end ())
267 {
268 net_rateinfo ri;
269
270 ri.host = host;
271 ri.pcnt = 1.;
272 ri.diff = CUTOFF * (1. / (1. - ALPHA));
273 ri.last = NOW;
274
275 push_front (ri);
276
277 return true;
278 }
279 else
280 {
281 net_rateinfo ri (*i);
282 erase (i);
283
284 ri.pcnt = ri.pcnt * ALPHA;
285 ri.diff = ri.diff * ALPHA + (NOW - ri.last);
286
287 ri.last = NOW;
288
289 bool send = ri.diff / ri.pcnt > CUTOFF;
290
291 if (send)
292 ri.pcnt++;
293
294 //printf ("RATE %d %f,%f = %f > %f\n", !!send, ri.pcnt, ri.diff, ri.diff / ri.pcnt, CUTOFF);
295
296 push_front (ri);
297
298 return send;
299 }
133} 300}
134 301
135///////////////////////////////////////////////////////////////////////////// 302/////////////////////////////////////////////////////////////////////////////
136 303
137static void next_wakeup (time_t next) 304static void next_wakeup (time_t next)
184 { 351 {
185 PT_RESET = 0, 352 PT_RESET = 0,
186 PT_DATA_UNCOMPRESSED, 353 PT_DATA_UNCOMPRESSED,
187 PT_DATA_COMPRESSED, 354 PT_DATA_COMPRESSED,
188 PT_PING, PT_PONG, // wasting namespace space? ;) 355 PT_PING, PT_PONG, // wasting namespace space? ;)
189 PT_AUTH, // authentification 356 PT_AUTH_REQ, // authentification request
357 PT_AUTH_RES, // authentification response
190 PT_CONNECT_REQ, // want other host to contact me 358 PT_CONNECT_REQ, // want other host to contact me
191 PT_CONNECT_INFO, // request connection to some node 359 PT_CONNECT_INFO, // request connection to some node
192 PT_REKEY, // rekeying (not yet implemented)
193 PT_MAX 360 PT_MAX
194 }; 361 };
195 362
196 u8 type; 363 u8 type;
197 u8 srcdst, src1, dst1; 364 u8 srcdst, src1, dst1;
200 367
201 unsigned int src () 368 unsigned int src ()
202 { 369 {
203 return src1 | ((srcdst >> 4) << 8); 370 return src1 | ((srcdst >> 4) << 8);
204 } 371 }
372
205 unsigned int dst () 373 unsigned int dst ()
206 { 374 {
207 return dst1 | ((srcdst & 0xf) << 8); 375 return dst1 | ((srcdst & 0xf) << 8);
208 } 376 }
377
209 ptype typ () 378 ptype typ ()
210 { 379 {
211 return (ptype) type; 380 return (ptype) type;
212 } 381 }
213 }; 382 };
252 u32 cl; 421 u32 cl;
253 422
254 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7); 423 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
255 if (cl) 424 if (cl)
256 { 425 {
257 //printf ("compressed packet, %d => %d\n", l, cl);//D
258 type = PT_DATA_COMPRESSED; 426 type = PT_DATA_COMPRESSED;
259 d = cdata; 427 d = cdata;
260 l = cl + 2; 428 l = cl + 2;
261 429
262 d[0] = cl >> 8; 430 d[0] = cl >> 8;
264 } 432 }
265#endif 433#endif
266 434
267 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0); 435 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0);
268 436
437 struct {
269#if RAND_SIZE 438#if RAND_SIZE
270 struct {
271 u8 rnd[RAND_SIZE]; 439 u8 rnd[RAND_SIZE];
440#endif
272 u32 seqno; 441 u32 seqno;
273 } datahdr; 442 } datahdr;
274 443
275 datahdr.seqno = seqno; 444 datahdr.seqno = ntohl (seqno);
445#if RAND_SIZE
276 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE); 446 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
447#endif
277 448
278 EVP_EncryptUpdate (cctx, 449 EVP_EncryptUpdate (cctx,
279 (unsigned char *) data + outl, &outl2, 450 (unsigned char *) data + outl, &outl2,
280 (unsigned char *) &datahdr, DATAHDR); 451 (unsigned char *) &datahdr, DATAHDR);
281 outl += outl2; 452 outl += outl2;
282#else
283 EVP_EncryptUpdate (cctx,
284 (unsigned char *) data + outl, &outl2,
285 (unsigned char *) &seqno, DATAHDR);
286 outl += outl2;
287#endif
288 453
289 EVP_EncryptUpdate (cctx, 454 EVP_EncryptUpdate (cctx,
290 (unsigned char *) data + outl, &outl2, 455 (unsigned char *) data + outl, &outl2,
291 (unsigned char *) d, l); 456 (unsigned char *) d, l);
292 outl += outl2; 457 outl += outl2;
328 outl += outl2; 493 outl += outl2;
329 494
330 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2); 495 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2);
331 outl += outl2; 496 outl += outl2;
332 497
333 seqno = *(u32 *)(d + RAND_SIZE); 498 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
334 499
335 id2mac (dst () ? dst() : THISNODE->id, p->dst); 500 id2mac (dst () ? dst() : THISNODE->id, p->dst);
336 id2mac (src (), p->src); 501 id2mac (src (), p->src);
337 502
338#if ENABLE_COMPRESSION 503#if ENABLE_COMPRESSION
339 if (type == PT_DATA_COMPRESSED) 504 if (type == PT_DATA_COMPRESSED)
340 { 505 {
341 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1]; 506 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
342 p->len = lzf_decompress (d + DATAHDR + 2, cl, &(*p)[6 + 6], MAX_MTU) + 6 + 6; 507 p->len = lzf_decompress (d + DATAHDR + 2, cl, &(*p)[6 + 6], MAX_MTU) + 6 + 6;
343 //printf ("decompressxed %d(%d) => %d\n", cl, len - data_hdr_size (), p->len);//D
344 } 508 }
345 else 509 else
346 p->len = outl + (6 + 6 - DATAHDR); 510 p->len = outl + (6 + 6 - DATAHDR);
347#endif 511#endif
348 512
349 return p; 513 return p;
350} 514}
351 515
352struct ping_packet : vpn_packet 516struct ping_packet : vpn_packet
517{
518 void setup (int dst, ptype type)
353 { 519 {
354 void setup (int dst, ptype type)
355 {
356 set_hdr (type, dst); 520 set_hdr (type, dst);
357 len = sizeof (*this) - sizeof (net_packet); 521 len = sizeof (*this) - sizeof (net_packet);
358 }
359 }; 522 }
523};
360 524
361struct config_packet : vpn_packet 525struct config_packet : vpn_packet
526{
527 // actually, hmaclen cannot be checked because the hmac
528 // field comes before this data, so peers with other
529 // hmacs simply will not work.
530 u8 prot_major, prot_minor, randsize, hmaclen;
531 u8 flags, challengelen, pad2, pad3;
532 u32 cipher_nid, digest_nid, hmac_nid;
533
534 const u8 curflags () const
362 { 535 {
363 // actually, hmaclen cannot be checked because the hmac
364 // field comes before this data, so peers with other
365 // hmacs simply will not work.
366 u8 prot_major, prot_minor, randsize, hmaclen;
367 u8 flags, challengelen, pad2, pad3;
368 u32 cipher_nid;
369 u32 digest_nid;
370
371 const u8 curflags () const
372 {
373 return 0x80 536 return 0x80
374 | (ENABLE_COMPRESSION ? 0x01 : 0x00) 537 | (ENABLE_COMPRESSION ? 0x01 : 0x00);
375 | (ENABLE_TRUST ? 0x02 : 0x00);
376 } 538 }
377 539
378 void setup (ptype type, int dst) 540 void setup (ptype type, int dst)
379 {
380 prot_major = PROTOCOL_MAJOR;
381 prot_minor = PROTOCOL_MINOR;
382 randsize = RAND_SIZE;
383 hmaclen = HMACLENGTH;
384 flags = curflags ();
385 challengelen = sizeof (rsachallenge);
386
387 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
388 digest_nid = htonl (EVP_MD_type (DIGEST));
389
390 len = sizeof (*this) - sizeof (net_packet);
391 set_hdr (type, dst);
392 }
393
394 bool chk_config ()
395 {
396 return prot_major == PROTOCOL_MAJOR
397 && randsize == RAND_SIZE
398 && hmaclen == HMACLENGTH
399 && flags == curflags ()
400 && challengelen == sizeof (rsachallenge)
401 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
402 && digest_nid == htonl (EVP_MD_type (DIGEST));
403 }
404 };
405
406struct auth_packet : config_packet
407 { 541 {
408 char magic[8]; 542 prot_major = PROTOCOL_MAJOR;
409 u8 subtype; 543 prot_minor = PROTOCOL_MINOR;
410 u8 pad1, pad2; 544 randsize = RAND_SIZE;
411 rsaencrdata challenge; 545 hmaclen = HMACLENGTH;
546 flags = curflags ();
547 challengelen = sizeof (rsachallenge);
412 548
413 auth_packet (int dst, auth_subtype stype) 549 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
414 { 550 digest_nid = htonl (EVP_MD_type (RSA_HASH));
415 config_packet::setup (PT_AUTH, dst); 551 hmac_nid = htonl (EVP_MD_type (DIGEST));
416 subtype = stype; 552
417 len = sizeof (*this) - sizeof (net_packet); 553 len = sizeof (*this) - sizeof (net_packet);
554 set_hdr (type, dst);
555 }
556
557 bool chk_config ()
558 {
559 return prot_major == PROTOCOL_MAJOR
560 && randsize == RAND_SIZE
561 && hmaclen == HMACLENGTH
562 && flags == curflags ()
563 && challengelen == sizeof (rsachallenge)
564 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
565 && digest_nid == htonl (EVP_MD_type (RSA_HASH))
566 && hmac_nid == htonl (EVP_MD_type (DIGEST));
567 }
568};
569
570struct auth_req_packet : config_packet
571{
572 char magic[8];
573 u8 initiate; // false if this is just an automatic reply
574 u8 pad1, pad2, pad3;
575 rsaid id;
576 rsaencrdata encr;
577
578 auth_req_packet (int dst, bool initiate_)
579 {
580 config_packet::setup (PT_AUTH_REQ, dst);
581 initiate = !!initiate_;
418 strncpy (magic, MAGIC, 8); 582 strncpy (magic, MAGIC, 8);
419 } 583 len = sizeof (*this) - sizeof (net_packet);
420 }; 584 }
585};
586
587struct auth_res_packet : config_packet
588{
589 rsaid id;
590 rsaresponse response;
591
592 auth_res_packet (int dst)
593 {
594 config_packet::setup (PT_AUTH_RES, dst);
595 len = sizeof (*this) - sizeof (net_packet);
596 }
597};
421 598
422struct connect_req_packet : vpn_packet 599struct connect_req_packet : vpn_packet
600{
601 u8 id;
602 u8 pad1, pad2, pad3;
603
604 connect_req_packet (int dst, int id_)
423 { 605 {
424 u8 id; 606 id = id_;
425 u8 pad1, pad2, pad3;
426
427 connect_req_packet (int dst, int id)
428 {
429 this->id = id;
430 set_hdr (PT_CONNECT_REQ, dst); 607 set_hdr (PT_CONNECT_REQ, dst);
431 len = sizeof (*this) - sizeof (net_packet); 608 len = sizeof (*this) - sizeof (net_packet);
432 }
433 }; 609 }
610};
434 611
435struct connect_info_packet : vpn_packet 612struct connect_info_packet : vpn_packet
613{
614 u8 id;
615 u8 pad1, pad2, pad3;
616 sockinfo si;
617
618 connect_info_packet (int dst, int id_, sockinfo &si_)
436 { 619 {
437 u8 id; 620 id = id_;
438 u8 pad1, pad2, pad3; 621 si = si_;
439 sockinfo si;
440
441 connect_info_packet (int dst, int id, sockinfo &si)
442 {
443 this->id = id;
444 this->si = si;
445 set_hdr (PT_CONNECT_INFO, dst); 622 set_hdr (PT_CONNECT_INFO, dst);
446 len = sizeof (*this) - sizeof (net_packet); 623 len = sizeof (*this) - sizeof (net_packet);
447 }
448 }; 624 }
625};
449 626
450///////////////////////////////////////////////////////////////////////////// 627/////////////////////////////////////////////////////////////////////////////
451 628
452void 629void
453fill_sa (SOCKADDR *sa, conf_node *conf) 630fill_sa (SOCKADDR *sa, conf_node *conf)
481connection::send_ping (SOCKADDR *dsa, u8 pong) 658connection::send_ping (SOCKADDR *dsa, u8 pong)
482{ 659{
483 ping_packet *pkt = new ping_packet; 660 ping_packet *pkt = new ping_packet;
484 661
485 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING); 662 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
486 vpn->send_vpn_packet (pkt, dsa); 663 vpn->send_vpn_packet (pkt, dsa, IPTOS_LOWDELAY);
487 664
488 delete pkt; 665 delete pkt;
489} 666}
490 667
491void 668void
492connection::send_reset (SOCKADDR *dsa) 669connection::send_reset (SOCKADDR *dsa)
493{ 670{
494 static net_rate_limiter limiter(1); 671 if (reset_rate_limiter.can (dsa) && connectmode != conf_node::C_DISABLED)
495
496 if (limiter.can (dsa))
497 { 672 {
498 config_packet *pkt = new config_packet; 673 config_packet *pkt = new config_packet;
499 674
500 pkt->setup (vpn_packet::PT_RESET, conf->id); 675 pkt->setup (vpn_packet::PT_RESET, conf->id);
501 vpn->send_vpn_packet (pkt, dsa); 676 vpn->send_vpn_packet (pkt, dsa, IPTOS_MINCOST);
502 677
503 delete pkt; 678 delete pkt;
504 } 679 }
505} 680}
506 681
507static rsachallenge *
508gen_challenge (SOCKADDR *sa)
509{
510 static rsachallenge k;
511
512 memcpy (&k, &challenge_bytes (), sizeof (k));
513 RAND_bytes ((unsigned char *)&k[CHG_SEQNO], sizeof (u32));
514 xor_sa (k, sa);
515
516 return &k;
517}
518
519void 682void
520connection::send_auth (auth_subtype subtype, SOCKADDR *sa, rsachallenge *k) 683connection::send_auth_request (SOCKADDR *sa, bool initiate)
521{ 684{
522 static net_rate_limiter limiter(2); 685 if (auth_rate_limiter.can (sa))
523
524 if (subtype != AUTH_INIT || limiter.can (sa))
525 { 686 {
526 auth_packet *pkt = new auth_packet (conf->id, subtype); 687 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate);
527 688
528 //printf ("send auth_packet subtype %d\n", subtype);//D 689 rsachallenge chg;
529 690
530 if (!k) 691 rsa_cache.gen (pkt->id, chg);
531 k = gen_challenge (sa);
532 692
533#if ENABLE_TRUST
534 if (0 > RSA_public_encrypt (sizeof (*k), 693 if (0 > RSA_public_encrypt (sizeof chg,
535 (unsigned char *)k, (unsigned char *)&pkt->challenge, 694 (unsigned char *)&chg, (unsigned char *)&pkt->encr,
536 conf->rsa_key, RSA_PKCS1_OAEP_PADDING)) 695 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
537 fatal ("RSA_public_encrypt error"); 696 fatal ("RSA_public_encrypt error");
538#else
539# error untrusted mode not yet implemented: programemr does not know how to
540 rsaencrdata enc;
541 697
542 if (0 > RSA_private_encrypt (sizeof (*k),
543 (unsigned char *)k, (unsigned char *)&enc,
544 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
545 fatal ("RSA_private_encrypt error");
546
547 if (0 > RSA_public_encrypt (sizeof (enc),
548 (unsigned char *)enc, (unsigned char *)&pkt->challenge,
549 conf->rsa_key, RSA_NO_PADDING))
550 fatal ("RSA_public_encrypt error");
551#endif
552
553 slog (L_TRACE, ">>%d PT_AUTH(%d) [%s]", conf->id, subtype, (const char *)sockinfo (sa)); 698 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)sockinfo (sa));
554 699
555 vpn->send_vpn_packet (pkt, sa); 700 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
556 701
557 delete pkt; 702 delete pkt;
558 } 703 }
559} 704}
560 705
561void 706void
707connection::send_auth_response (SOCKADDR *sa, const rsaid &id, const rsachallenge &chg)
708{
709 if (auth_rate_limiter.can (sa))
710 {
711 auth_res_packet *pkt = new auth_res_packet (conf->id);
712
713 pkt->id = id;
714 rsa_hash (chg, pkt->response);
715
716 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)sockinfo (sa));
717
718 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
719
720 delete pkt;
721 }
722}
723
724void
562connection::establish_connection () 725connection::establish_connection_cb (tstamp &ts)
563{ 726{
564 if (!ictx && conf != THISNODE && connectmode != conf_node::C_NEVER) 727 if (ictx || conf == THISNODE || connectmode == conf_node::C_NEVER)
728 ts = TSTAMP_CANCEL;
729 else if (ts <= NOW)
565 { 730 {
566 if (now >= next_retry) 731 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6;
732
733 if (retry_int < 3600 * 8)
734 retry_cnt++;
735
736 ts = NOW + retry_int;
737
738 if (conf->hostname)
567 { 739 {
568 int retry_int = retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2);
569
570 if (retry_cnt < (17 << 2) | 3)
571 retry_cnt++;
572
573 if (connectmode == conf_node::C_ONDEMAND
574 && retry_int > ::conf.keepalive)
575 retry_int = ::conf.keepalive;
576
577 next_retry = now + retry_int;
578 next_wakeup (next_retry);
579
580 if (conf->hostname)
581 {
582 reset_dstaddr (); 740 reset_dstaddr ();
583 if (sa.sin_addr.s_addr) 741 if (sa.sin_addr.s_addr)
584 if (retry_cnt < 4) 742 if (retry_cnt < 4)
585 send_auth (AUTH_INIT, &sa); 743 send_auth_request (&sa, true);
586 else 744 else if (auth_rate_limiter.can (&sa))
587 send_ping (&sa, 0); 745 send_ping (&sa, 0);
588 }
589 else
590 vpn->connect_request (conf->id);
591 } 746 }
747 else
748 vpn->connect_request (conf->id);
592 } 749 }
593} 750}
594 751
595void 752void
596connection::reset_connection () 753connection::reset_connection ()
598 if (ictx && octx) 755 if (ictx && octx)
599 { 756 {
600 slog (L_INFO, _("connection to %d (%s) lost"), conf->id, conf->nodename); 757 slog (L_INFO, _("connection to %d (%s) lost"), conf->id, conf->nodename);
601 758
602 if (::conf.script_node_down) 759 if (::conf.script_node_down)
603 run_script (this, &connection::script_node_down, false); 760 run_script (run_script_cb (this, &connection::script_node_down), false);
604 } 761 }
605 762
606 delete ictx; 763 delete ictx; ictx = 0;
607 ictx = 0; 764 delete octx; octx = 0;
608
609 delete octx;
610 octx = 0;
611 765
612 sa.sin_port = 0; 766 sa.sin_port = 0;
613 sa.sin_addr.s_addr = 0; 767 sa.sin_addr.s_addr = 0;
614 768
615 next_retry = 0;
616 next_rekey = 0;
617 last_activity = 0; 769 last_activity = 0;
770
771 rekey.reset ();
772 keepalive.reset ();
773 establish_connection.reset ();
618} 774}
619 775
620void 776void
621connection::shutdown () 777connection::shutdown ()
622{ 778{
625 781
626 reset_connection (); 782 reset_connection ();
627} 783}
628 784
629void 785void
630connection::rekey () 786connection::rekey_cb (tstamp &ts)
631{ 787{
788 ts = TSTAMP_CANCEL;
789
632 reset_connection (); 790 reset_connection ();
633 establish_connection (); 791 establish_connection ();
634} 792}
635 793
636void 794void
637connection::send_data_packet (tap_packet * pkt, bool broadcast) 795connection::send_data_packet (tap_packet * pkt, bool broadcast)
638{ 796{
639 vpndata_packet *p = new vpndata_packet; 797 vpndata_packet *p = new vpndata_packet;
798 int tos = 0;
799
800 if (conf->inherit_tos
801 && (*pkt)[12] == 0x08 && (*pkt)[13] == 0x00 // IP
802 && ((*pkt)[14] & 0xf0) == 0x40) // IPv4
803 tos = (*pkt)[15] & IPTOS_TOS_MASK;
640 804
641 p->setup (this, broadcast ? 0 : conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs 805 p->setup (this, broadcast ? 0 : conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
642 vpn->send_vpn_packet (p, &sa); 806 vpn->send_vpn_packet (p, &sa, tos);
643 807
644 delete p; 808 delete p;
645 809
646 if (oseqno > MAX_SEQNO) 810 if (oseqno > MAX_SEQNO)
647 rekey (); 811 rekey ();
662} 826}
663 827
664void 828void
665connection::recv_vpn_packet (vpn_packet *pkt, SOCKADDR *ssa) 829connection::recv_vpn_packet (vpn_packet *pkt, SOCKADDR *ssa)
666{ 830{
667 last_activity = now; 831 last_activity = NOW;
668 832
669 slog (L_NOISE, "<<%d received packet type %d from %d to %d", 833 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
670 conf->id, pkt->typ (), pkt->src (), pkt->dst ()); 834 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
671 835
672 switch (pkt->typ ()) 836 switch (pkt->typ ())
673 { 837 {
674 case vpn_packet::PT_PING: 838 case vpn_packet::PT_PING:
675 send_ping (ssa, 1); // pong
676 break;
677
678 case vpn_packet::PT_PONG:
679 // we send pings instead of auth packets after some retries, 839 // we send pings instead of auth packets after some retries,
680 // so reset the retry counter and establish a conenction 840 // so reset the retry counter and establish a conenction
681 // when we receive a pong. 841 // when we receive a pong.
682 if (!ictx && !octx) 842 if (!ictx && !octx)
683 { 843 {
684 retry_cnt = 0; 844 retry_cnt = 0;
685 next_retry = 0; 845 establish_connection.at = 0;
686 establish_connection (); 846 establish_connection ();
687 } 847 }
848 else
849 send_ping (ssa, 1); // pong
688 850
851 break;
852
853 case vpn_packet::PT_PONG:
689 break; 854 break;
690 855
691 case vpn_packet::PT_RESET: 856 case vpn_packet::PT_RESET:
692 { 857 {
693 reset_connection (); 858 reset_connection ();
694 859
695 config_packet *p = (config_packet *) pkt; 860 config_packet *p = (config_packet *) pkt;
861
696 if (p->chk_config ()) 862 if (!p->chk_config ())
863 {
864 slog (L_WARN, _("protocol mismatch, disabling node '%s'"), conf->nodename);
865 connectmode = conf_node::C_DISABLED;
866 }
697 if (connectmode == conf_node::C_ALWAYS) 867 else if (connectmode == conf_node::C_ALWAYS)
698 establish_connection (); 868 establish_connection ();
699
700 //D slog the protocol mismatch?
701 } 869 }
702 break; 870 break;
703 871
704 case vpn_packet::PT_AUTH: 872 case vpn_packet::PT_AUTH_REQ:
705 { 873 {
706 auth_packet *p = (auth_packet *) pkt; 874 auth_req_packet *p = (auth_req_packet *) pkt;
707 875
708 slog (L_TRACE, "<<%d PT_AUTH(%d)", conf->id, p->subtype); 876 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
709 877
710 if (p->chk_config ()
711 && !strncmp (p->magic, MAGIC, 8)) 878 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
712 { 879 {
713 if (p->prot_minor != PROTOCOL_MINOR) 880 if (p->prot_minor != PROTOCOL_MINOR)
714 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."), 881 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."),
715 PROTOCOL_MINOR, conf->nodename, p->prot_minor); 882 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
716 883
717 if (p->subtype == AUTH_INIT) 884 if (p->initiate)
718 send_auth (AUTH_INITREPLY, ssa); 885 send_auth_request (ssa, false);
719 886
720 rsachallenge k; 887 rsachallenge k;
721 888
722#if ENABLE_TRUST
723 if (0 > RSA_private_decrypt (sizeof (rsaencrdata), 889 if (0 > RSA_private_decrypt (sizeof (p->encr),
724 (unsigned char *)&p->challenge, (unsigned char *)&k, 890 (unsigned char *)&p->encr, (unsigned char *)&k,
725 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) 891 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
726 // continued below 892 slog (L_ERR, _("challenge from %s (%s) illegal or corrupted"),
727#else 893 conf->nodename, (const char *)sockinfo (ssa));
728 rsaencrdata j;
729 894 else
730 if (0 > RSA_private_decrypt (sizeof (rsaencrdata),
731 (unsigned char *)&p->challenge, (unsigned char *)&j,
732 ::conf.rsa_key, RSA_NO_PADDING))
733 fatal ("RSA_private_decrypt error");
734
735 if (0 > RSA_public_decrypt (sizeof (k),
736 (unsigned char *)&j, (unsigned char *)&k,
737 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
738 // continued below
739#endif
740 { 895 {
741 slog (L_ERR, _("challenge from %s (%s) illegal or corrupted"), 896 retry_cnt = 0;
742 conf->nodename, (const char *)sockinfo (ssa)); 897 establish_connection.set (NOW + 8); //? ;)
898 keepalive.reset ();
899 rekey.reset ();
900
901 delete ictx;
902 ictx = 0;
903
904 delete octx;
905
906 octx = new crypto_ctx (k, 1);
907 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
908
909 send_auth_response (ssa, p->id, k);
910
743 break; 911 break;
744 } 912 }
913 }
745 914
746 retry_cnt = 0;
747 next_retry = now + 8;
748 915
749 switch (p->subtype) 916 }
917
918 send_reset (ssa);
919 break;
920
921 case vpn_packet::PT_AUTH_RES:
922 {
923 auth_res_packet *p = (auth_res_packet *) pkt;
924
925 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
926
927 if (p->chk_config ())
928 {
929 if (p->prot_minor != PROTOCOL_MINOR)
930 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."),
931 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
932
933 rsachallenge chg;
934
935 if (!rsa_cache.find (p->id, chg))
936 slog (L_ERR, _("unrequested auth response from %s (%s)"),
937 conf->nodename, (const char *)sockinfo (ssa));
938 else
750 { 939 {
751 case AUTH_INIT: 940 rsaresponse h;
752 case AUTH_INITREPLY:
753 delete ictx;
754 ictx = 0;
755 941
756 delete octx; 942 rsa_hash (chg, h);
757 943
758 octx = new crypto_ctx (k, 1); 944 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
759 oseqno = *(u32 *)&k[CHG_SEQNO] & 0x7fffffff;
760
761 send_auth (AUTH_REPLY, ssa, &k);
762 break;
763
764 case AUTH_REPLY:
765
766 if (!memcmp ((u8 *)gen_challenge (ssa) + sizeof (u32), (u8 *)&k + sizeof (u32),
767 sizeof (rsachallenge) - sizeof (u32)))
768 { 945 {
769 delete ictx; 946 delete ictx;
770 947
771 ictx = new crypto_ctx (k, 0); 948 ictx = new crypto_ctx (chg, 0);
772 iseqno = *(u32 *)&k[CHG_SEQNO] & 0x7fffffff; // at least 2**31 sequence numbers are valid 949 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
773 ismask = 0xffffffff; // initially, all lower sequence numbers are invalid
774 950
775 sa = *ssa; 951 sa = *ssa;
776 952
777 next_rekey = now + ::conf.rekey; 953 rekey.set (NOW + ::conf.rekey);
778 next_wakeup (next_rekey); 954 keepalive.set (NOW + ::conf.keepalive);
779 955
780 // send queued packets 956 // send queued packets
781 while (tap_packet *p = queue.get ()) 957 while (tap_packet *p = queue.get ())
782 { 958 {
783 send_data_packet (p); 959 send_data_packet (p);
788 964
789 slog (L_INFO, _("connection to %d (%s %s) established"), 965 slog (L_INFO, _("connection to %d (%s %s) established"),
790 conf->id, conf->nodename, (const char *)sockinfo (ssa)); 966 conf->id, conf->nodename, (const char *)sockinfo (ssa));
791 967
792 if (::conf.script_node_up) 968 if (::conf.script_node_up)
793 run_script (this, &connection::script_node_up, false); 969 run_script (run_script_cb (this, &connection::script_node_up), false);
970
971 break;
794 } 972 }
795 else 973 else
796 slog (L_ERR, _("sent and received challenge do not match with (%s %s))"), 974 slog (L_ERR, _("sent and received challenge do not match with (%s %s))"),
797 conf->nodename, (const char *)sockinfo (ssa)); 975 conf->nodename, (const char *)sockinfo (ssa));
798
799 break;
800 default:
801 slog (L_ERR, _("authentification illegal subtype error (%s %s)"),
802 conf->nodename, (const char *)sockinfo (ssa));
803 break;
804 } 976 }
805 } 977 }
806 else
807 send_reset (ssa);
808
809 break;
810 } 978 }
979
980 send_reset (ssa);
981 break;
811 982
812 case vpn_packet::PT_DATA_COMPRESSED: 983 case vpn_packet::PT_DATA_COMPRESSED:
813#if !ENABLE_COMPRESSION 984#if !ENABLE_COMPRESSION
814 send_reset (ssa); 985 send_reset (ssa);
815 break; 986 break;
816#endif 987#endif
988
817 case vpn_packet::PT_DATA_UNCOMPRESSED: 989 case vpn_packet::PT_DATA_UNCOMPRESSED:
818 990
819 if (ictx && octx) 991 if (ictx && octx)
820 { 992 {
821 vpndata_packet *p = (vpndata_packet *)pkt; 993 vpndata_packet *p = (vpndata_packet *)pkt;
828 else 1000 else
829 { 1001 {
830 u32 seqno; 1002 u32 seqno;
831 tap_packet *d = p->unpack (this, seqno); 1003 tap_packet *d = p->unpack (this, seqno);
832 1004
833 if (seqno <= iseqno - 32) 1005 if (iseqno.recv_ok (seqno))
834 slog (L_ERR, _("received duplicate or outdated packet (received %08lx, expected %08lx)\n"
835 "possible replay attack, or just massive packet reordering"), seqno, iseqno + 1);//D
836 else if (seqno > iseqno + 32)
837 slog (L_ERR, _("received duplicate or out-of-sync packet (received %08lx, expected %08lx)\n"
838 "possible replay attack, or just massive packet loss"), seqno, iseqno + 1);//D
839 else
840 { 1006 {
841 if (seqno > iseqno)
842 {
843 ismask <<= seqno - iseqno;
844 iseqno = seqno;
845 }
846
847 u32 mask = 1 << (iseqno - seqno);
848
849 //printf ("received seqno %08lx, iseqno %08lx, mask %08lx is %08lx\n", seqno, iseqno, mask, ismask);
850 if (ismask & mask)
851 slog (L_ERR, _("received duplicate packet (received %08lx, expected %08lx)\n"
852 "possible replay attack, or just packet duplication"), seqno, iseqno + 1);//D
853 else
854 {
855 ismask |= mask;
856
857 vpn->tap->send (d); 1007 vpn->tap->send (d);
858 1008
859 if (p->dst () == 0) // re-broadcast 1009 if (p->dst () == 0) // re-broadcast
860 for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i) 1010 for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i)
861 { 1011 {
862 connection *c = *i; 1012 connection *c = *i;
863 1013
864 if (c->conf != THISNODE && c->conf != conf) 1014 if (c->conf != THISNODE && c->conf != conf)
865 c->inject_data_packet (d); 1015 c->inject_data_packet (d);
866 }
867
868 delete d;
869
870 break;
871 } 1016 }
1017
1018 delete d;
1019
1020 break;
872 } 1021 }
873 } 1022 }
874 } 1023 }
875 else 1024 else
876 slog (L_ERR, _("received data packet from unknown source %s"), (const char *)sockinfo (ssa));//D 1025 slog (L_ERR, _("received data packet from unknown source %s"), (const char *)sockinfo (ssa));//D
937 connection *c = vpn->conns[p->id - 1]; 1086 connection *c = vpn->conns[p->id - 1];
938 1087
939 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)", 1088 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
940 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx); 1089 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
941 1090
942 c->send_auth (AUTH_INIT, p->si.sa ()); 1091 c->send_auth_request (p->si.sa (), true);
943 } 1092 }
1093
944 break; 1094 break;
945 1095
946 default: 1096 default:
947 send_reset (ssa); 1097 send_reset (ssa);
948 break; 1098 break;
949 }
950}
951 1099
952void connection::timer ()
953{
954 if (conf != THISNODE)
955 { 1100 }
956 if (now >= next_retry && connectmode == conf_node::C_ALWAYS) 1101}
1102
1103void connection::keepalive_cb (tstamp &ts)
1104{
1105 if (NOW >= last_activity + ::conf.keepalive + 30)
1106 {
1107 reset_connection ();
957 establish_connection (); 1108 establish_connection ();
958 1109 }
959 if (ictx && octx)
960 {
961 if (now >= next_rekey)
962 rekey ();
963 else if (now >= last_activity + ::conf.keepalive + 30)
964 {
965 reset_connection ();
966 establish_connection ();
967 }
968 else if (now >= last_activity + ::conf.keepalive) 1110 else if (NOW < last_activity + ::conf.keepalive)
1111 ts = last_activity + ::conf.keepalive;
969 if (conf->connectmode != conf_node::C_ONDEMAND 1112 else if (conf->connectmode != conf_node::C_ONDEMAND
970 || THISNODE->connectmode != conf_node::C_ONDEMAND) 1113 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1114 {
971 send_ping (&sa); 1115 send_ping (&sa);
972 else 1116 ts = NOW + 5;
1117 }
1118 else
973 reset_connection (); 1119 reset_connection ();
974 1120
975 }
976 }
977} 1121}
978 1122
979void connection::connect_request (int id) 1123void connection::connect_request (int id)
980{ 1124{
981 connect_req_packet *p = new connect_req_packet (conf->id, id); 1125 connect_req_packet *p = new connect_req_packet (conf->id, id);
987 delete p; 1131 delete p;
988} 1132}
989 1133
990void connection::script_node () 1134void connection::script_node ()
991{ 1135{
992 vpn->script_if_up (); 1136 vpn->script_if_up (0);
993 1137
994 char *env; 1138 char *env;
995 asprintf (&env, "DESTID=%d", conf->id); 1139 asprintf (&env, "DESTID=%d", conf->id);
996 putenv (env); 1140 putenv (env);
997 asprintf (&env, "DESTNODE=%s", conf->nodename); 1141 asprintf (&env, "DESTNODE=%s", conf->nodename);
1000 putenv (env); 1144 putenv (env);
1001 asprintf (&env, "DESTPORT=%d", ntohs (sa.sin_port)); 1145 asprintf (&env, "DESTPORT=%d", ntohs (sa.sin_port));
1002 putenv (env); 1146 putenv (env);
1003} 1147}
1004 1148
1005const char *connection::script_node_up () 1149const char *connection::script_node_up (int)
1006{ 1150{
1007 script_node (); 1151 script_node ();
1008 1152
1009 putenv ("STATE=up"); 1153 putenv ("STATE=up");
1010 1154
1011 return ::conf.script_node_up ? ::conf.script_node_up : "node-up"; 1155 return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1012} 1156}
1013 1157
1014const char *connection::script_node_down () 1158const char *connection::script_node_down (int)
1015{ 1159{
1016 script_node (); 1160 script_node ();
1017 1161
1018 putenv ("STATE=down"); 1162 putenv ("STATE=down");
1019 1163
1020 return ::conf.script_node_up ? ::conf.script_node_down : "node-down"; 1164 return ::conf.script_node_up ? ::conf.script_node_down : "node-down";
1021} 1165}
1022 1166
1167connection::connection(struct vpn *vpn_)
1168: vpn(vpn_)
1169, rekey (this, &connection::rekey_cb)
1170, keepalive (this, &connection::keepalive_cb)
1171, establish_connection (this, &connection::establish_connection_cb)
1172{
1173 octx = ictx = 0;
1174 retry_cnt = 0;
1175
1176 connectmode = conf_node::C_ALWAYS; // initial setting
1177 reset_connection ();
1178}
1179
1180connection::~connection ()
1181{
1182 shutdown ();
1183}
1184
1023///////////////////////////////////////////////////////////////////////////// 1185/////////////////////////////////////////////////////////////////////////////
1024 1186
1025vpn::vpn (void)
1026{}
1027
1028const char *vpn::script_if_up () 1187const char *vpn::script_if_up (int)
1029{ 1188{
1030 // the tunnel device mtu should be the physical mtu - overhead 1189 // the tunnel device mtu should be the physical mtu - overhead
1031 // the tricky part is rounding to the cipher key blocksize 1190 // the tricky part is rounding to the cipher key blocksize
1032 int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - UDP_OVERHEAD; 1191 int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - MAX_OVERHEAD;
1033 mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion 1192 mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion
1034 mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round 1193 mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round
1035 mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again 1194 mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again
1036 1195
1037 char *env; 1196 char *env;
1082 { 1241 {
1083 int oval = 1; 1242 int oval = 1;
1084 setsockopt (socket_fd, SOL_SOCKET, SO_REUSEADDR, &oval, sizeof oval); 1243 setsockopt (socket_fd, SOL_SOCKET, SO_REUSEADDR, &oval, sizeof oval);
1085 } 1244 }
1086 1245
1246 udp_ev_watcher.start (socket_fd, POLLIN);
1247
1087 tap = new tap_device (); 1248 tap = new tap_device ();
1088 if (!tap) //D this, of course, never catches 1249 if (!tap) //D this, of course, never catches
1089 { 1250 {
1090 slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname); 1251 slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname);
1091 exit (1); 1252 exit (1);
1092 } 1253 }
1093 1254
1094 run_script (this, &vpn::script_if_up, true); 1255 run_script (run_script_cb (this, &vpn::script_if_up), true);
1256
1257 vpn_ev_watcher.start (tap->fd, POLLIN);
1258
1259 reconnect_all ();
1095 1260
1096 return 0; 1261 return 0;
1097} 1262}
1098 1263
1099void 1264void
1100vpn::send_vpn_packet (vpn_packet *pkt, SOCKADDR *sa) 1265vpn::send_vpn_packet (vpn_packet *pkt, SOCKADDR *sa, int tos)
1101{ 1266{
1267 setsockopt (socket_fd, SOL_IP, IP_TOS, &tos, sizeof tos);
1102 sendto (socket_fd, &((*pkt)[0]), pkt->len, 0, (sockaddr *)sa, sizeof (*sa)); 1268 sendto (socket_fd, &((*pkt)[0]), pkt->len, 0, (sockaddr *)sa, sizeof (*sa));
1103} 1269}
1104 1270
1105void 1271void
1106vpn::shutdown_all () 1272vpn::shutdown_all ()
1163 // if ((*i)->conf->routerprio) 1329 // if ((*i)->conf->routerprio)
1164 // (*i)->establish_connection (); 1330 // (*i)->establish_connection ();
1165} 1331}
1166 1332
1167void 1333void
1168vpn::main_loop () 1334vpn::udp_ev (short revents)
1169{ 1335{
1170 struct pollfd pollfd[2]; 1336 if (revents & (POLLIN | POLLERR))
1171
1172 pollfd[0].fd = tap->fd;
1173 pollfd[0].events = POLLIN;
1174 pollfd[1].fd = socket_fd;
1175 pollfd[1].events = POLLIN;
1176
1177 events = 0;
1178 now = time (0);
1179 next_timecheck = now + 1;
1180
1181 reconnect_all ();
1182
1183 for (;;)
1184 { 1337 {
1185 int npoll = poll (pollfd, 2, (next_timecheck - now) * 1000); 1338 vpn_packet *pkt = new vpn_packet;
1186 1339 struct sockaddr_in sa;
1187 now = time (0); 1340 socklen_t sa_len = sizeof (sa);
1341 int len;
1188 1342
1343 len = recvfrom (socket_fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len);
1344
1189 if (npoll > 0) 1345 if (len > 0)
1190 { 1346 {
1191 if (pollfd[1].revents) 1347 pkt->len = len;
1348
1349 unsigned int src = pkt->src ();
1350 unsigned int dst = pkt->dst ();
1351
1352 slog (L_NOISE, _("<<?/%s received possible vpn packet type %d from %d to %d, length %d"),
1353 (const char *)sockinfo (sa), pkt->typ (), pkt->src (), pkt->dst (), pkt->len);
1354
1355 if (dst > conns.size () || pkt->typ () >= vpn_packet::PT_MAX)
1356 slog (L_WARN, _("<<? received CORRUPTED packet type %d from %d to %d"),
1357 pkt->typ (), pkt->src (), pkt->dst ());
1358 else if (dst == 0 && !THISNODE->routerprio)
1359 slog (L_WARN, _("<<%d received broadcast, but we are no router"), dst);
1360 else if (dst != 0 && dst != THISNODE->id)
1361 slog (L_WARN,
1362 _("received frame for node %d ('%s') from %s, but this is node %d ('%s')"),
1363 dst, conns[dst - 1]->conf->nodename,
1364 (const char *)sockinfo (sa),
1365 THISNODE->id, THISNODE->nodename);
1366 else if (src == 0 || src > conns.size ())
1367 slog (L_WARN, _("received frame from unknown node %d (%s)"), src, (const char *)sockinfo (sa));
1368 else
1369 conns[src - 1]->recv_vpn_packet (pkt, &sa);
1370 }
1371 else
1372 {
1373 // probably ECONNRESET or somesuch
1374 slog (L_DEBUG, _("%s: %s"), (const char *)sockinfo(sa), strerror (errno));
1375 }
1376
1377 delete pkt;
1378 }
1379 else if (revents & POLLHUP)
1380 {
1381 // this cannot ;) happen on udp sockets
1382 slog (L_ERR, _("FATAL: POLLHUP on socket fd, terminating."));
1383 exit (1);
1384 }
1385 else
1386 {
1387 slog (L_ERR,
1388 _("FATAL: unknown revents %08x in socket, terminating\n"),
1389 revents);
1390 exit (1);
1391 }
1392}
1393
1394void
1395vpn::vpn_ev (short revents)
1396{
1397 if (revents & POLLIN)
1398 {
1399 /* process data */
1400 tap_packet *pkt;
1401
1402 pkt = tap->recv ();
1403
1404 int dst = mac2id (pkt->dst);
1405 int src = mac2id (pkt->src);
1406
1407 if (src != THISNODE->id)
1408 {
1409 slog (L_ERR, _("FATAL: tap packet not originating on current node received, terminating."));
1410 exit (1);
1411 }
1412
1413 if (dst == THISNODE->id)
1414 {
1415 slog (L_ERR, _("FATAL: tap packet destined for current node received, terminating."));
1416 exit (1);
1417 }
1418
1419 if (dst > conns.size ())
1420 slog (L_ERR, _("tap packet for unknown node %d received, ignoring."), dst);
1421 else
1422 {
1423 if (dst)
1192 { 1424 {
1193 if (pollfd[1].revents & (POLLIN | POLLERR)) 1425 // unicast
1194 {
1195 vpn_packet *pkt = new vpn_packet;
1196 struct sockaddr_in sa;
1197 socklen_t sa_len = sizeof (sa);
1198 int len;
1199
1200 len = recvfrom (socket_fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len);
1201
1202 if (len > 0)
1203 {
1204 pkt->len = len;
1205
1206 unsigned int src = pkt->src ();
1207 unsigned int dst = pkt->dst ();
1208
1209 slog (L_NOISE, _("<<?/%s received possible vpn packet type %d from %d to %d, length %d"),
1210 (const char *)sockinfo (sa), pkt->typ (), pkt->src (), pkt->dst (), pkt->len);
1211
1212 if (dst > conns.size () || pkt->typ () >= vpn_packet::PT_MAX)
1213 slog (L_WARN, _("<<? received CORRUPTED packet type %d from %d to %d"),
1214 pkt->typ (), pkt->src (), pkt->dst ());
1215 else if (dst == 0 && !THISNODE->routerprio)
1216 slog (L_WARN, _("<<%d received broadcast, but we are no router"), dst);
1217 else if (dst != 0 && dst != THISNODE->id) 1426 if (dst != THISNODE->id)
1218 slog (L_WARN,
1219 _("received frame for node %d ('%s') from %s, but this is node %d ('%s')"),
1220 dst, conns[dst - 1]->conf->nodename,
1221 (const char *)sockinfo (sa),
1222 THISNODE->id, THISNODE->nodename);
1223 else if (src == 0 || src > conns.size ())
1224 slog (L_WARN, _("received frame from unknown node %d (%s)"), src, (const char *)sockinfo (sa));
1225 else
1226 conns[src - 1]->recv_vpn_packet (pkt, &sa); 1427 conns[dst - 1]->inject_data_packet (pkt);
1227 }
1228 else
1229 {
1230 // probably ECONNRESET or somesuch
1231 slog (L_DEBUG, _("%s: %s"), (const char *)sockinfo(sa), strerror (errno));
1232 }
1233
1234 delete pkt;
1235 } 1428 }
1236 else if (pollfd[1].revents & POLLHUP) 1429 else
1237 { 1430 {
1238 // this cannot ;) happen on udp sockets 1431 // broadcast, first check router, then self, then english
1239 slog (L_ERR, _("FATAL: POLLHUP on socket fd, terminating.")); 1432 connection *router = find_router ();
1240 exit (1); 1433
1241 } 1434 if (router)
1435 router->inject_data_packet (pkt, true);
1242 else 1436 else
1243 {
1244 slog (L_ERR,
1245 _("FATAL: unknown revents %08x in socket, terminating\n"),
1246 pollfd[1].revents);
1247 exit (1);
1248 }
1249 }
1250
1251 // I use else here to give vpn_packets absolute priority
1252 else if (pollfd[0].revents)
1253 {
1254 if (pollfd[0].revents & POLLIN)
1255 {
1256 /* process data */
1257 tap_packet *pkt;
1258
1259 pkt = tap->recv ();
1260
1261 int dst = mac2id (pkt->dst);
1262 int src = mac2id (pkt->src);
1263
1264 if (src != THISNODE->id)
1265 {
1266 slog (L_ERR, _("FATAL: tap packet not originating on current node received, terminating."));
1267 exit (1);
1268 }
1269
1270 if (dst == THISNODE->id)
1271 {
1272 slog (L_ERR, _("FATAL: tap packet destined for current node received, terminating."));
1273 exit (1);
1274 }
1275
1276 if (dst > conns.size ())
1277 slog (L_ERR, _("tap packet for unknown node %d received, ignoring."), dst);
1278 else
1279 {
1280 if (dst)
1281 {
1282 // unicast
1283 if (dst != THISNODE->id)
1284 conns[dst - 1]->inject_data_packet (pkt);
1285 }
1286 else
1287 {
1288 // broadcast, first check router, then self, then english
1289 connection *router = find_router ();
1290
1291 if (router)
1292 router->inject_data_packet (pkt, true);
1293 else
1294 for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c) 1437 for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c)
1295 if ((*c)->conf != THISNODE) 1438 if ((*c)->conf != THISNODE)
1296 (*c)->inject_data_packet (pkt); 1439 (*c)->inject_data_packet (pkt);
1297 }
1298 }
1299
1300 delete pkt;
1301 }
1302 else if (pollfd[0].revents & (POLLHUP | POLLERR))
1303 {
1304 slog (L_ERR, _("FATAL: POLLHUP or POLLERR on network device fd, terminating."));
1305 exit (1);
1306 }
1307 else
1308 abort ();
1309 } 1440 }
1310 } 1441 }
1311 1442
1443 delete pkt;
1444 }
1445 else if (revents & (POLLHUP | POLLERR))
1446 {
1447 slog (L_ERR, _("FATAL: POLLHUP or POLLERR on network device fd, terminating."));
1448 exit (1);
1449 }
1450 else
1451 abort ();
1452}
1453
1454void
1455vpn::event_cb (tstamp &ts)
1456{
1312 if (events) 1457 if (events)
1458 {
1459 if (events & EVENT_SHUTDOWN)
1313 { 1460 {
1314 if (events & EVENT_SHUTDOWN)
1315 {
1316 shutdown_all (); 1461 shutdown_all ();
1317 1462
1318 remove_pid (pidfilename); 1463 remove_pid (pidfilename);
1319 1464
1320 slog (L_INFO, _("vped terminating")); 1465 slog (L_INFO, _("vped terminating"));
1321 1466
1322 exit (0); 1467 exit (0);
1323 }
1324
1325 if (events & EVENT_RECONNECT)
1326 reconnect_all ();
1327
1328 events = 0;
1329 } 1468 }
1330 1469
1331 // very very very dumb and crude and inefficient timer handling, or maybe not? 1470 if (events & EVENT_RECONNECT)
1332 if (now >= next_timecheck) 1471 reconnect_all ();
1333 {
1334 next_timecheck = now + TIMER_GRANULARITY;
1335 1472
1336 for (conns_vector::iterator c = conns.begin (); 1473 events = 0;
1337 c != conns.end (); ++c)
1338 (*c)->timer ();
1339 }
1340 } 1474 }
1475
1476 ts = TSTAMP_CANCEL;
1477}
1478
1479vpn::vpn (void)
1480: udp_ev_watcher (this, &vpn::udp_ev)
1481, vpn_ev_watcher (this, &vpn::vpn_ev)
1482, event (this, &vpn::event_cb)
1483{
1341} 1484}
1342 1485
1343vpn::~vpn () 1486vpn::~vpn ()
1344{} 1487{
1488}
1345 1489

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines