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.18 by pcg, Wed Mar 26 02:15:38 2003 UTC

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

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines