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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines