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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines