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.9 by pcg, Fri Mar 21 23:17:01 2003 UTC vs.
Revision 1.20 by pcg, Wed Mar 26 17:59:12 2003 UTC

16 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA 16 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
17*/ 17*/
18 18
19#include "config.h" 19#include "config.h"
20 20
21#include <list>
22
21#include <cstdlib> 23#include <cstdlib>
22#include <cstring> 24#include <cstring>
23#include <cstdio> 25#include <cstdio>
24 26
25#include <sys/types.h> 27#include <sys/types.h>
56 58
57static time_t next_timecheck; 59static time_t next_timecheck;
58 60
59#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic 61#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
60 62
61static const rsachallenge & 63struct crypto_ctx
62challenge_bytes ()
63{
64 static rsachallenge challenge;
65 static double challenge_ttl; // time this challenge needs to be recreated
66
67 if (NOW > challenge_ttl)
68 { 64 {
69 RAND_bytes ((unsigned char *)&challenge, sizeof (challenge)); 65 EVP_CIPHER_CTX cctx;
70 challenge_ttl = NOW + CHALLENGE_TTL; 66 HMAC_CTX hctx;
71 }
72 67
73 return challenge; 68 crypto_ctx (const rsachallenge &challenge, int enc);
74} 69 ~crypto_ctx ();
70 };
75 71
76// run a script. yes, it's a template function. yes, c++ 72crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
77// is not a functional language. yes, this suxx. 73{
78template<class owner> 74 EVP_CIPHER_CTX_init (&cctx);
75 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
76 HMAC_CTX_init (&hctx);
77 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
78}
79
80crypto_ctx::~crypto_ctx ()
81{
82 EVP_CIPHER_CTX_cleanup (&cctx);
83 HMAC_CTX_cleanup (&hctx);
84}
85
79static void 86static void
80run_script (owner *obj, const char *(owner::*setup)(), bool wait) 87rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h)
88{
89 EVP_MD_CTX ctx;
90
91 EVP_MD_CTX_init (&ctx);
92 EVP_DigestInit (&ctx, RSA_HASH);
93 EVP_DigestUpdate(&ctx, &chg, sizeof chg);
94 EVP_DigestUpdate(&ctx, &id, sizeof id);
95 EVP_DigestFinal (&ctx, (unsigned char *)&h, 0);
96 EVP_MD_CTX_cleanup (&ctx);
97}
98
99struct rsa_entry {
100 tstamp expire;
101 rsaid id;
102 rsachallenge chg;
103};
104
105struct rsa_cache : list<rsa_entry>
106{
107 void cleaner_cb (tstamp &ts); time_watcher cleaner;
108
109 bool find (const rsaid &id, rsachallenge &chg)
110 {
111 for (iterator i = begin (); i != end (); ++i)
112 {
113 if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW)
114 {
115 memcpy (&chg, &i->chg, sizeof chg);
116
117 erase (i);
118 return true;
119 }
120 }
121
122 if (cleaner.at < NOW)
123 cleaner.start (NOW + RSA_TTL);
124
125 return false;
126 }
127
128 void gen (rsaid &id, rsachallenge &chg)
129 {
130 rsa_entry e;
131
132 RAND_bytes ((unsigned char *)&id, sizeof id);
133 RAND_bytes ((unsigned char *)&chg, sizeof chg);
134
135 e.expire = NOW + RSA_TTL;
136 e.id = id;
137 memcpy (&e.chg, &chg, sizeof chg);
138
139 push_back (e);
140
141 if (cleaner.at < NOW)
142 cleaner.start (NOW + RSA_TTL);
143 }
144
145 rsa_cache ()
146 : cleaner (this, &rsa_cache::cleaner_cb)
147 { }
148
149} rsa_cache;
150
151void rsa_cache::cleaner_cb (tstamp &ts)
152{
153 if (empty ())
154 ts = TSTAMP_CANCEL;
155 else
156 {
157 ts = NOW + RSA_TTL;
158
159 for (iterator i = begin (); i != end (); )
160 if (i->expire <= NOW)
161 i = erase (i);
162 else
163 ++i;
164 }
165}
166
167typedef callback<const char *, int> run_script_cb;
168
169// run a shell script (or actually an external program).
170static void
171run_script (const run_script_cb &cb, bool wait)
81{ 172{
82 int pid; 173 int pid;
83 174
84 if ((pid = fork ()) == 0) 175 if ((pid = fork ()) == 0)
85 { 176 {
86 char *filename; 177 char *filename;
87 asprintf (&filename, "%s/%s", confbase, (obj->*setup) ()); 178 asprintf (&filename, "%s/%s", confbase, cb(0));
88 execl (filename, filename, (char *) 0); 179 execl (filename, filename, (char *) 0);
89 exit (255); 180 exit (255);
90 } 181 }
91 else if (pid > 0) 182 else if (pid > 0)
92 { 183 {
96 /* TODO: check status */ 187 /* TODO: check status */
97 } 188 }
98 } 189 }
99} 190}
100 191
101// xor the socket address into the challenge to ensure different challenges
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
112struct crypto_ctx
113 {
114 EVP_CIPHER_CTX cctx;
115 HMAC_CTX hctx;
116
117 crypto_ctx (rsachallenge &challenge, int enc);
118 ~crypto_ctx ();
119 };
120
121crypto_ctx::crypto_ctx (rsachallenge &challenge, int enc)
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}
128
129crypto_ctx::~crypto_ctx ()
130{
131 EVP_CIPHER_CTX_cleanup (&cctx);
132 HMAC_CTX_cleanup (&hctx);
133}
134
135////////////////////////////////////////////////////////////////////////////// 192//////////////////////////////////////////////////////////////////////////////
136 193
137void pkt_queue::put (tap_packet *p) 194void pkt_queue::put (tap_packet *p)
138{ 195{
139 if (queue[i]) 196 if (queue[i])
171{ 228{
172 for (i = QUEUEDEPTH; --i > 0; ) 229 for (i = QUEUEDEPTH; --i > 0; )
173 delete queue[i]; 230 delete queue[i];
174} 231}
175 232
233struct net_rateinfo {
234 u32 host;
235 double pcnt, diff;
236 tstamp last;
237};
238
176// only do action once every x seconds per host. 239// only do action once every x seconds per host whole allowing bursts.
177// currently this is quite a slow implementation, 240// this implementation ("splay list" ;) is inefficient,
178// but suffices for normal operation. 241// but low on resources.
179struct u32_rate_limiter : private map<u32, tstamp> 242struct net_rate_limiter : private list<net_rateinfo>
180 { 243{
181 tstamp every; 244 static const double ALPHA = 1. - 1. / 90.; // allow bursts
245 static const double CUTOFF = 20.; // one event every CUTOFF seconds
246 static const double EXPIRE = CUTOFF * 30.; // expire entries after this time
182 247
183 bool can (u32 host); 248 bool can (u32 host);
184
185 u32_rate_limiter (tstamp every = 1)
186 {
187 this->every = every;
188 }
189 };
190
191struct net_rate_limiter : u32_rate_limiter
192 {
193 bool can (SOCKADDR *sa) { return u32_rate_limiter::can((u32)sa->sin_addr.s_addr); } 249 bool can (SOCKADDR *sa) { return can((u32)sa->sin_addr.s_addr); }
194 bool can (sockinfo &si) { return u32_rate_limiter::can((u32)si.host); } 250 bool can (sockinfo &si) { return can((u32)si.host); }
251};
195 252
196 net_rate_limiter (tstamp every) : u32_rate_limiter (every) {} 253net_rate_limiter auth_rate_limiter, reset_rate_limiter;
197 };
198 254
199bool u32_rate_limiter::can (u32 host) 255bool net_rate_limiter::can (u32 host)
200{ 256{
201 iterator i; 257 iterator i;
202 258
203 for (i = begin (); i != end (); ) 259 for (i = begin (); i != end (); )
204 if (i->second <= NOW) 260 if (i->host == host)
205 { 261 break;
262 else if (i->last < NOW - EXPIRE)
206 erase (i); 263 i = erase (i);
207 i = begin ();
208 }
209 else 264 else
210 ++i; 265 i++;
211 266
212 i = find (host);
213
214 if (i != end ()) 267 if (i == end ())
215 return false; 268 {
269 net_rateinfo ri;
216 270
217 insert (value_type (host, NOW + every)); 271 ri.host = host;
272 ri.pcnt = 1.;
273 ri.diff = CUTOFF * (1. / (1. - ALPHA));
274 ri.last = NOW;
218 275
276 push_front (ri);
277
219 return true; 278 return true;
279 }
280 else
281 {
282 net_rateinfo ri (*i);
283 erase (i);
284
285 ri.pcnt = ri.pcnt * ALPHA;
286 ri.diff = ri.diff * ALPHA + (NOW - ri.last);
287
288 ri.last = NOW;
289
290 bool send = ri.diff / ri.pcnt > CUTOFF;
291
292 if (send)
293 ri.pcnt++;
294
295 push_front (ri);
296
297 return send;
298 }
220} 299}
221 300
222///////////////////////////////////////////////////////////////////////////// 301/////////////////////////////////////////////////////////////////////////////
223 302
224static void next_wakeup (time_t next) 303static void next_wakeup (time_t next)
228} 307}
229 308
230static unsigned char hmac_digest[EVP_MAX_MD_SIZE]; 309static unsigned char hmac_digest[EVP_MAX_MD_SIZE];
231 310
232struct hmac_packet:net_packet 311struct hmac_packet:net_packet
312{
313 u8 hmac[HMACLENGTH]; // each and every packet has a hmac field, but that is not (yet) checked everywhere
314
315 void hmac_set (crypto_ctx * ctx);
316 bool hmac_chk (crypto_ctx * ctx);
317
318private:
319 void hmac_gen (crypto_ctx * ctx)
233 { 320 {
234 u8 hmac[HMACLENGTH]; // each and every packet has a hmac field, but that is not (yet) checked everywhere
235
236 void hmac_set (crypto_ctx * ctx);
237 bool hmac_chk (crypto_ctx * ctx);
238
239private:
240 void hmac_gen (crypto_ctx * ctx)
241 {
242 unsigned int xlen; 321 unsigned int xlen;
243 HMAC_CTX *hctx = &ctx->hctx; 322 HMAC_CTX *hctx = &ctx->hctx;
244 323
245 HMAC_Init_ex (hctx, 0, 0, 0, 0); 324 HMAC_Init_ex (hctx, 0, 0, 0, 0);
246 HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet), 325 HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet),
247 len - sizeof (hmac_packet)); 326 len - sizeof (hmac_packet));
248 HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen); 327 HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen);
249 }
250 }; 328 }
329};
251 330
252void 331void
253hmac_packet::hmac_set (crypto_ctx * ctx) 332hmac_packet::hmac_set (crypto_ctx * ctx)
254{ 333{
255 hmac_gen (ctx); 334 hmac_gen (ctx);
271 { 350 {
272 PT_RESET = 0, 351 PT_RESET = 0,
273 PT_DATA_UNCOMPRESSED, 352 PT_DATA_UNCOMPRESSED,
274 PT_DATA_COMPRESSED, 353 PT_DATA_COMPRESSED,
275 PT_PING, PT_PONG, // wasting namespace space? ;) 354 PT_PING, PT_PONG, // wasting namespace space? ;)
276 PT_AUTH, // authentification 355 PT_AUTH_REQ, // authentification request
356 PT_AUTH_RES, // authentification response
277 PT_CONNECT_REQ, // want other host to contact me 357 PT_CONNECT_REQ, // want other host to contact me
278 PT_CONNECT_INFO, // request connection to some node 358 PT_CONNECT_INFO, // request connection to some node
279 PT_REKEY, // rekeying (not yet implemented)
280 PT_MAX 359 PT_MAX
281 }; 360 };
282 361
283 u8 type; 362 u8 type;
284 u8 srcdst, src1, dst1; 363 u8 srcdst, src1, dst1;
352 } 431 }
353#endif 432#endif
354 433
355 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0); 434 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0);
356 435
436 struct {
357#if RAND_SIZE 437#if RAND_SIZE
358 struct {
359 u8 rnd[RAND_SIZE]; 438 u8 rnd[RAND_SIZE];
439#endif
360 u32 seqno; 440 u32 seqno;
361 } datahdr; 441 } datahdr;
362 442
363 datahdr.seqno = seqno; 443 datahdr.seqno = ntohl (seqno);
444#if RAND_SIZE
364 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE); 445 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
446#endif
365 447
366 EVP_EncryptUpdate (cctx, 448 EVP_EncryptUpdate (cctx,
367 (unsigned char *) data + outl, &outl2, 449 (unsigned char *) data + outl, &outl2,
368 (unsigned char *) &datahdr, DATAHDR); 450 (unsigned char *) &datahdr, DATAHDR);
369 outl += outl2; 451 outl += outl2;
370#else
371 EVP_EncryptUpdate (cctx,
372 (unsigned char *) data + outl, &outl2,
373 (unsigned char *) &seqno, DATAHDR);
374 outl += outl2;
375#endif
376 452
377 EVP_EncryptUpdate (cctx, 453 EVP_EncryptUpdate (cctx,
378 (unsigned char *) data + outl, &outl2, 454 (unsigned char *) data + outl, &outl2,
379 (unsigned char *) d, l); 455 (unsigned char *) d, l);
380 outl += outl2; 456 outl += outl2;
416 outl += outl2; 492 outl += outl2;
417 493
418 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2); 494 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2);
419 outl += outl2; 495 outl += outl2;
420 496
421 seqno = *(u32 *)(d + RAND_SIZE); 497 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
422 498
423 id2mac (dst () ? dst() : THISNODE->id, p->dst); 499 id2mac (dst () ? dst() : THISNODE->id, p->dst);
424 id2mac (src (), p->src); 500 id2mac (src (), p->src);
425 501
426#if ENABLE_COMPRESSION 502#if ENABLE_COMPRESSION
427 if (type == PT_DATA_COMPRESSED) 503 if (type == PT_DATA_COMPRESSED)
428 { 504 {
429 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1]; 505 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
506
430 p->len = lzf_decompress (d + DATAHDR + 2, cl, &(*p)[6 + 6], MAX_MTU) + 6 + 6; 507 p->len = lzf_decompress (d + DATAHDR + 2, cl < MAX_MTU ? cl : 0,
508 &(*p)[6 + 6], MAX_MTU)
509 + 6 + 6;
431 } 510 }
432 else 511 else
433 p->len = outl + (6 + 6 - DATAHDR); 512 p->len = outl + (6 + 6 - DATAHDR);
434#endif 513#endif
435 514
436 return p; 515 return p;
437} 516}
438 517
439struct ping_packet : vpn_packet 518struct ping_packet : vpn_packet
519{
520 void setup (int dst, ptype type)
440 { 521 {
441 void setup (int dst, ptype type)
442 {
443 set_hdr (type, dst); 522 set_hdr (type, dst);
444 len = sizeof (*this) - sizeof (net_packet); 523 len = sizeof (*this) - sizeof (net_packet);
445 }
446 }; 524 }
525};
447 526
448struct config_packet : vpn_packet 527struct config_packet : vpn_packet
528{
529 // actually, hmaclen cannot be checked because the hmac
530 // field comes before this data, so peers with other
531 // hmacs simply will not work.
532 u8 prot_major, prot_minor, randsize, hmaclen;
533 u8 flags, challengelen, pad2, pad3;
534 u32 cipher_nid, digest_nid, hmac_nid;
535
536 const u8 curflags () const
449 { 537 {
450 // actually, hmaclen cannot be checked because the hmac
451 // field comes before this data, so peers with other
452 // hmacs simply will not work.
453 u8 prot_major, prot_minor, randsize, hmaclen;
454 u8 flags, challengelen, pad2, pad3;
455 u32 cipher_nid;
456 u32 digest_nid;
457
458 const u8 curflags () const
459 {
460 return 0x80 538 return 0x80
461 | 0x02
462#if PROTOCOL_MAJOR != 2
463#error hi
464#endif
465 | (ENABLE_COMPRESSION ? 0x01 : 0x00); 539 | (ENABLE_COMPRESSION ? 0x01 : 0x00);
466 } 540 }
467 541
468 void setup (ptype type, int dst) 542 void setup (ptype type, int dst)
469 {
470 prot_major = PROTOCOL_MAJOR;
471 prot_minor = PROTOCOL_MINOR;
472 randsize = RAND_SIZE;
473 hmaclen = HMACLENGTH;
474 flags = curflags ();
475 challengelen = sizeof (rsachallenge);
476
477 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
478 digest_nid = htonl (EVP_MD_type (DIGEST));
479
480 len = sizeof (*this) - sizeof (net_packet);
481 set_hdr (type, dst);
482 }
483
484 bool chk_config ()
485 {
486 return prot_major == PROTOCOL_MAJOR
487 && randsize == RAND_SIZE
488 && hmaclen == HMACLENGTH
489 && flags == curflags ()
490 && challengelen == sizeof (rsachallenge)
491 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
492 && digest_nid == htonl (EVP_MD_type (DIGEST));
493 }
494 };
495
496struct auth_packet : config_packet
497 { 543 {
498 char magic[8]; 544 prot_major = PROTOCOL_MAJOR;
499 u8 subtype; 545 prot_minor = PROTOCOL_MINOR;
500 u8 pad1, pad2; 546 randsize = RAND_SIZE;
501 rsaencrdata challenge; 547 hmaclen = HMACLENGTH;
548 flags = curflags ();
549 challengelen = sizeof (rsachallenge);
502 550
503 auth_packet (int dst, auth_subtype stype) 551 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
504 { 552 digest_nid = htonl (EVP_MD_type (RSA_HASH));
505 config_packet::setup (PT_AUTH, dst); 553 hmac_nid = htonl (EVP_MD_type (DIGEST));
506 subtype = stype; 554
507 len = sizeof (*this) - sizeof (net_packet); 555 len = sizeof (*this) - sizeof (net_packet);
556 set_hdr (type, dst);
557 }
558
559 bool chk_config ()
560 {
561 return prot_major == PROTOCOL_MAJOR
562 && randsize == RAND_SIZE
563 && hmaclen == HMACLENGTH
564 && flags == curflags ()
565 && challengelen == sizeof (rsachallenge)
566 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
567 && digest_nid == htonl (EVP_MD_type (RSA_HASH))
568 && hmac_nid == htonl (EVP_MD_type (DIGEST));
569 }
570};
571
572struct auth_req_packet : config_packet
573{
574 char magic[8];
575 u8 initiate; // false if this is just an automatic reply
576 u8 pad1, pad2, pad3;
577 rsaid id;
578 rsaencrdata encr;
579
580 auth_req_packet (int dst, bool initiate_)
581 {
582 config_packet::setup (PT_AUTH_REQ, dst);
583 initiate = !!initiate_;
508 strncpy (magic, MAGIC, 8); 584 strncpy (magic, MAGIC, 8);
509 } 585 len = sizeof (*this) - sizeof (net_packet);
510 }; 586 }
587};
588
589struct auth_res_packet : config_packet
590{
591 rsaid id;
592 u8 pad1, pad2, pad3;
593 u8 response_len; // encrypted length
594 rsaresponse response;
595
596 auth_res_packet (int dst)
597 {
598 config_packet::setup (PT_AUTH_RES, dst);
599 len = sizeof (*this) - sizeof (net_packet);
600 }
601};
511 602
512struct connect_req_packet : vpn_packet 603struct connect_req_packet : vpn_packet
604{
605 u8 id;
606 u8 pad1, pad2, pad3;
607
608 connect_req_packet (int dst, int id_)
513 { 609 {
514 u8 id; 610 id = id_;
515 u8 pad1, pad2, pad3;
516
517 connect_req_packet (int dst, int id)
518 {
519 this->id = id;
520 set_hdr (PT_CONNECT_REQ, dst); 611 set_hdr (PT_CONNECT_REQ, dst);
521 len = sizeof (*this) - sizeof (net_packet); 612 len = sizeof (*this) - sizeof (net_packet);
522 }
523 }; 613 }
614};
524 615
525struct connect_info_packet : vpn_packet 616struct connect_info_packet : vpn_packet
617{
618 u8 id;
619 u8 pad1, pad2, pad3;
620 sockinfo si;
621
622 connect_info_packet (int dst, int id_, sockinfo &si_)
526 { 623 {
527 u8 id; 624 id = id_;
528 u8 pad1, pad2, pad3; 625 si = si_;
529 sockinfo si;
530
531 connect_info_packet (int dst, int id, sockinfo &si)
532 {
533 this->id = id;
534 this->si = si;
535 set_hdr (PT_CONNECT_INFO, dst); 626 set_hdr (PT_CONNECT_INFO, dst);
536 len = sizeof (*this) - sizeof (net_packet); 627 len = sizeof (*this) - sizeof (net_packet);
537 }
538 }; 628 }
629};
539 630
540///////////////////////////////////////////////////////////////////////////// 631/////////////////////////////////////////////////////////////////////////////
541 632
542void 633void
543fill_sa (SOCKADDR *sa, conf_node *conf) 634fill_sa (SOCKADDR *sa, conf_node *conf)
579} 670}
580 671
581void 672void
582connection::send_reset (SOCKADDR *dsa) 673connection::send_reset (SOCKADDR *dsa)
583{ 674{
584 static net_rate_limiter limiter(1); 675 if (reset_rate_limiter.can (dsa) && connectmode != conf_node::C_DISABLED)
585
586 if (limiter.can (dsa))
587 { 676 {
588 config_packet *pkt = new config_packet; 677 config_packet *pkt = new config_packet;
589 678
590 pkt->setup (vpn_packet::PT_RESET, conf->id); 679 pkt->setup (vpn_packet::PT_RESET, conf->id);
591 vpn->send_vpn_packet (pkt, dsa, IPTOS_MINCOST); 680 vpn->send_vpn_packet (pkt, dsa, IPTOS_MINCOST);
592 681
593 delete pkt; 682 delete pkt;
594 } 683 }
595} 684}
596 685
597static rsachallenge *
598gen_challenge (SOCKADDR *sa)
599{
600 static rsachallenge k;
601
602 memcpy (&k, &challenge_bytes (), sizeof (k));
603 RAND_bytes ((unsigned char *)&k[CHG_SEQNO], sizeof (u32));
604 xor_sa (k, sa);
605
606 return &k;
607}
608
609void 686void
610connection::send_auth (auth_subtype subtype, SOCKADDR *sa, rsachallenge *k) 687connection::send_auth_request (SOCKADDR *sa, bool initiate)
611{ 688{
612 static net_rate_limiter limiter(2); 689 if (!initiate || auth_rate_limiter.can (sa))
613
614 if (subtype != AUTH_INIT || limiter.can (sa))
615 { 690 {
616 auth_packet *pkt = new auth_packet (conf->id, subtype); 691 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate);
617 692
618 if (!k) 693 rsachallenge chg;
619 k = gen_challenge (sa);
620 694
695 rsa_cache.gen (pkt->id, chg);
696
621 if (0 > RSA_public_encrypt (sizeof (*k), 697 if (0 > RSA_public_encrypt (sizeof chg,
622 (unsigned char *)k, (unsigned char *)&pkt->challenge, 698 (unsigned char *)&chg, (unsigned char *)&pkt->encr,
623 conf->rsa_key, RSA_PKCS1_OAEP_PADDING)) 699 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
624 fatal ("RSA_public_encrypt error"); 700 fatal ("RSA_public_encrypt error");
625 701
626 slog (L_TRACE, ">>%d PT_AUTH(%d) [%s]", conf->id, subtype, (const char *)sockinfo (sa)); 702 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)sockinfo (sa));
627 703
628 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); 704 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
629 705
630 delete pkt; 706 delete pkt;
631 } 707 }
632} 708}
633 709
634void 710void
711connection::send_auth_response (SOCKADDR *sa, const rsaid &id, const rsachallenge &chg)
712{
713 auth_res_packet *pkt = new auth_res_packet (conf->id);
714
715 pkt->id = id;
716
717 rsa_hash (id, chg, pkt->response);
718
719 pkt->hmac_set (octx);
720
721 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)sockinfo (sa));
722
723 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
724
725 delete pkt;
726}
727
728void
635connection::establish_connection_cb (tstamp &ts) 729connection::establish_connection_cb (tstamp &ts)
636{ 730{
637 if (ictx || conf == THISNODE || connectmode == conf_node::C_NEVER) 731 if (ictx || conf == THISNODE
732 || connectmode == conf_node::C_NEVER
733 || connectmode == conf_node::C_DISABLED)
638 ts = TSTAMP_CANCEL; 734 ts = TSTAMP_CANCEL;
639 else if (ts <= NOW) 735 else if (ts <= NOW)
640 { 736 {
641 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.25; 737 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6;
642 738
643 if (retry_int < 3600 * 8) 739 if (retry_int < 3600 * 8)
644 retry_cnt++; 740 retry_cnt++;
645
646 if (connectmode == conf_node::C_ONDEMAND
647 && retry_int > ::conf.keepalive)
648 retry_int = ::conf.keepalive;
649 741
650 ts = NOW + retry_int; 742 ts = NOW + retry_int;
651 743
652 if (conf->hostname) 744 if (conf->hostname)
653 { 745 {
654 reset_dstaddr (); 746 reset_dstaddr ();
655 if (sa.sin_addr.s_addr) 747 if (sa.sin_addr.s_addr)
656 if (retry_cnt < 4) 748 if (retry_cnt < 4)
657 send_auth (AUTH_INIT, &sa); 749 send_auth_request (&sa, true);
658 else 750 else if (auth_rate_limiter.can (&sa))
659 send_ping (&sa, 0); 751 send_ping (&sa, 0);
660 } 752 }
661 else 753 else
662 vpn->connect_request (conf->id); 754 vpn->connect_request (conf->id);
663 } 755 }
666void 758void
667connection::reset_connection () 759connection::reset_connection ()
668{ 760{
669 if (ictx && octx) 761 if (ictx && octx)
670 { 762 {
671 slog (L_INFO, _("connection to %d (%s) lost"), conf->id, conf->nodename); 763 slog (L_INFO, _("%s(%s): connection lost"),
764 conf->nodename, (const char *)sockinfo (sa));
672 765
673 if (::conf.script_node_down) 766 if (::conf.script_node_down)
674 run_script (this, &connection::script_node_down, false); 767 run_script (run_script_cb (this, &connection::script_node_down), false);
675 } 768 }
676 769
677 delete ictx; 770 delete ictx; ictx = 0;
678 ictx = 0; 771 delete octx; octx = 0;
679
680 delete octx;
681 octx = 0;
682 772
683 sa.sin_port = 0; 773 sa.sin_port = 0;
684 sa.sin_addr.s_addr = 0; 774 sa.sin_addr.s_addr = 0;
685 775
686 last_activity = 0; 776 last_activity = 0;
751 conf->id, pkt->typ (), pkt->src (), pkt->dst ()); 841 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
752 842
753 switch (pkt->typ ()) 843 switch (pkt->typ ())
754 { 844 {
755 case vpn_packet::PT_PING: 845 case vpn_packet::PT_PING:
756 send_ping (ssa, 1); // pong
757 break;
758
759 case vpn_packet::PT_PONG:
760 // we send pings instead of auth packets after some retries, 846 // we send pings instead of auth packets after some retries,
761 // so reset the retry counter and establish a conenction 847 // so reset the retry counter and establish a conenction
762 // when we receive a pong. 848 // when we receive a pong.
763 if (!ictx && !octx) 849 if (!ictx && !octx)
764 { 850 {
765 retry_cnt = 0; 851 retry_cnt = 0;
766 establish_connection.at = 0; 852 establish_connection.at = 0;
767 establish_connection (); 853 establish_connection ();
768 } 854 }
855 else
856 send_ping (ssa, 1); // pong
769 857
858 break;
859
860 case vpn_packet::PT_PONG:
770 break; 861 break;
771 862
772 case vpn_packet::PT_RESET: 863 case vpn_packet::PT_RESET:
773 { 864 {
774 reset_connection (); 865 reset_connection ();
775 866
776 config_packet *p = (config_packet *) pkt; 867 config_packet *p = (config_packet *) pkt;
868
777 if (!p->chk_config ()) 869 if (!p->chk_config ())
778 { 870 {
779 slog (L_WARN, _("disabling node '%s' because of differing protocol"), conf->nodename); 871 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
872 conf->nodename, (const char *)sockinfo (ssa));
780 connectmode = conf_node::C_NEVER; 873 connectmode = conf_node::C_DISABLED;
781 } 874 }
782 else if (connectmode == conf_node::C_ALWAYS) 875 else if (connectmode == conf_node::C_ALWAYS)
783 establish_connection (); 876 establish_connection ();
784 } 877 }
785 break; 878 break;
786 879
787 case vpn_packet::PT_AUTH: 880 case vpn_packet::PT_AUTH_REQ:
881 if (auth_rate_limiter.can (ssa))
882 {
883 auth_req_packet *p = (auth_req_packet *) pkt;
884
885 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
886
887 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
888 {
889 if (p->prot_minor != PROTOCOL_MINOR)
890 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
891 conf->nodename, (const char *)sockinfo (ssa),
892 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
893
894 if (p->initiate)
895 send_auth_request (ssa, false);
896
897 rsachallenge k;
898
899 if (0 > RSA_private_decrypt (sizeof (p->encr),
900 (unsigned char *)&p->encr, (unsigned char *)&k,
901 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
902 slog (L_ERR, _("%s(%s): challenge illegal or corrupted"),
903 conf->nodename, (const char *)sockinfo (ssa));
904 else
905 {
906 retry_cnt = 0;
907 establish_connection.set (NOW + 8); //? ;)
908 keepalive.reset ();
909 rekey.reset ();
910
911 delete ictx;
912 ictx = 0;
913
914 delete octx;
915
916 octx = new crypto_ctx (k, 1);
917 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
918
919 send_auth_response (ssa, p->id, k);
920
921 break;
922 }
923 }
924
925 send_reset (ssa);
926 }
927
928 break;
929
930 case vpn_packet::PT_AUTH_RES:
788 { 931 {
789 auth_packet *p = (auth_packet *) pkt; 932 auth_res_packet *p = (auth_res_packet *) pkt;
790 933
791 slog (L_TRACE, "<<%d PT_AUTH(%d)", conf->id, p->subtype); 934 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
792 935
793 if (p->chk_config () 936 if (p->chk_config ())
794 && !strncmp (p->magic, MAGIC, 8))
795 { 937 {
796 if (p->prot_minor != PROTOCOL_MINOR) 938 if (p->prot_minor != PROTOCOL_MINOR)
797 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."), 939 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
940 conf->nodename, (const char *)sockinfo (ssa),
798 PROTOCOL_MINOR, conf->nodename, p->prot_minor); 941 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
799 942
800 if (p->subtype == AUTH_INIT)
801 send_auth (AUTH_INITREPLY, ssa);
802
803 rsachallenge k; 943 rsachallenge chg;
804 944
805 if (0 > RSA_private_decrypt (sizeof (rsaencrdata), 945 if (!rsa_cache.find (p->id, chg))
806 (unsigned char *)&p->challenge, (unsigned char *)&k, 946 slog (L_ERR, _("%s(%s): unrequested auth response"),
807 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) 947 conf->nodename, (const char *)sockinfo (ssa));
948 else
808 { 949 {
809 slog (L_ERR, _("challenge from %s (%s) illegal or corrupted"), 950 crypto_ctx *cctx = new crypto_ctx (chg, 0);
951
952 if (!p->hmac_chk (cctx))
953 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
954 "could be an attack, or just corruption or an synchronization error"),
810 conf->nodename, (const char *)sockinfo (ssa)); 955 conf->nodename, (const char *)sockinfo (ssa));
811 break; 956 else
812 }
813
814 retry_cnt = 0;
815 establish_connection.set (NOW + 8); //? ;)
816 keepalive.reset ();
817 rekey.reset ();
818
819 switch (p->subtype)
820 {
821 case AUTH_INIT:
822 case AUTH_INITREPLY:
823 delete ictx;
824 ictx = 0;
825
826 delete octx;
827
828 octx = new crypto_ctx (k, 1);
829 oseqno = *(u32 *)&k[CHG_SEQNO] & 0x7fffffff;
830
831 send_auth (AUTH_REPLY, ssa, &k);
832 break;
833
834 case AUTH_REPLY:
835
836 if (!memcmp ((u8 *)gen_challenge (ssa) + sizeof (u32), (u8 *)&k + sizeof (u32),
837 sizeof (rsachallenge) - sizeof (u32)))
838 { 957 {
839 delete ictx;
840
841 ictx = new crypto_ctx (k, 0);
842 iseqno.reset (*(u32 *)&k[CHG_SEQNO] & 0x7fffffff); // at least 2**31 sequence numbers are valid
843
844 sa = *ssa; 958 rsaresponse h;
845 959
846 rekey.set (NOW + ::conf.rekey); 960 rsa_hash (p->id, chg, h);
847 keepalive.set (NOW + ::conf.keepalive);
848 961
849 // send queued packets 962 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
850 while (tap_packet *p = queue.get ())
851 { 963 {
964 prot_minor = p->prot_minor;
965
966 delete ictx; ictx = cctx;
967
968 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
969
970 sa = *ssa;
971
972 rekey.set (NOW + ::conf.rekey);
973 keepalive.set (NOW + ::conf.keepalive);
974
975 // send queued packets
976 while (tap_packet *p = queue.get ())
977 {
852 send_data_packet (p); 978 send_data_packet (p);
853 delete p; 979 delete p;
980 }
981
982 connectmode = conf->connectmode;
983
984 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
985 conf->nodename, (const char *)sockinfo (ssa),
986 p->prot_major, p->prot_minor);
987
988 if (::conf.script_node_up)
989 run_script (run_script_cb (this, &connection::script_node_up), false);
990
991 break;
854 } 992 }
855 993 else
856 connectmode = conf->connectmode; 994 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
857
858 slog (L_INFO, _("connection to %d (%s %s) established"),
859 conf->id, conf->nodename, (const char *)sockinfo (ssa)); 995 conf->nodename, (const char *)sockinfo (ssa));
860
861 if (::conf.script_node_up)
862 run_script (this, &connection::script_node_up, false);
863 } 996 }
997
864 else 998 delete cctx;
865 slog (L_ERR, _("sent and received challenge do not match with (%s %s))"),
866 conf->nodename, (const char *)sockinfo (ssa));
867
868 break;
869 default:
870 slog (L_ERR, _("authentification illegal subtype error (%s %s)"),
871 conf->nodename, (const char *)sockinfo (ssa));
872 break;
873 } 999 }
874 } 1000 }
875 else
876 send_reset (ssa);
877
878 break;
879 } 1001 }
1002
1003 send_reset (ssa);
1004 break;
880 1005
881 case vpn_packet::PT_DATA_COMPRESSED: 1006 case vpn_packet::PT_DATA_COMPRESSED:
882#if !ENABLE_COMPRESSION 1007#if !ENABLE_COMPRESSION
883 send_reset (ssa); 1008 send_reset (ssa);
884 break; 1009 break;
885#endif 1010#endif
1011
886 case vpn_packet::PT_DATA_UNCOMPRESSED: 1012 case vpn_packet::PT_DATA_UNCOMPRESSED:
887 1013
888 if (ictx && octx) 1014 if (ictx && octx)
889 { 1015 {
890 vpndata_packet *p = (vpndata_packet *)pkt; 1016 vpndata_packet *p = (vpndata_packet *)pkt;
891 1017
892 if (*ssa == sa) 1018 if (*ssa == sa)
893 { 1019 {
894 if (!p->hmac_chk (ictx)) 1020 if (!p->hmac_chk (ictx))
895 slog (L_ERR, _("hmac authentication error, received invalid packet\n" 1021 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
896 "could be an attack, or just corruption or an synchronization error")); 1022 "could be an attack, or just corruption or an synchronization error"),
1023 conf->nodename, (const char *)sockinfo (ssa));
897 else 1024 else
898 { 1025 {
899 u32 seqno; 1026 u32 seqno;
900 tap_packet *d = p->unpack (this, seqno); 1027 tap_packet *d = p->unpack (this, seqno);
901 1028
983 connection *c = vpn->conns[p->id - 1]; 1110 connection *c = vpn->conns[p->id - 1];
984 1111
985 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)", 1112 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
986 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx); 1113 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
987 1114
988 c->send_auth (AUTH_INIT, p->si.sa ()); 1115 c->send_auth_request (p->si.sa (), true);
989 } 1116 }
1117
990 break; 1118 break;
991 1119
992 default: 1120 default:
993 send_reset (ssa); 1121 send_reset (ssa);
994 break; 1122 break;
1123
995 } 1124 }
996} 1125}
997 1126
998void connection::keepalive_cb (tstamp &ts) 1127void connection::keepalive_cb (tstamp &ts)
999{ 1128{
1026 delete p; 1155 delete p;
1027} 1156}
1028 1157
1029void connection::script_node () 1158void connection::script_node ()
1030{ 1159{
1031 vpn->script_if_up (); 1160 vpn->script_if_up (0);
1032 1161
1033 char *env; 1162 char *env;
1034 asprintf (&env, "DESTID=%d", conf->id); 1163 asprintf (&env, "DESTID=%d", conf->id);
1035 putenv (env); 1164 putenv (env);
1036 asprintf (&env, "DESTNODE=%s", conf->nodename); 1165 asprintf (&env, "DESTNODE=%s", conf->nodename);
1039 putenv (env); 1168 putenv (env);
1040 asprintf (&env, "DESTPORT=%d", ntohs (sa.sin_port)); 1169 asprintf (&env, "DESTPORT=%d", ntohs (sa.sin_port));
1041 putenv (env); 1170 putenv (env);
1042} 1171}
1043 1172
1044const char *connection::script_node_up () 1173const char *connection::script_node_up (int)
1045{ 1174{
1046 script_node (); 1175 script_node ();
1047 1176
1048 putenv ("STATE=up"); 1177 putenv ("STATE=up");
1049 1178
1050 return ::conf.script_node_up ? ::conf.script_node_up : "node-up"; 1179 return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1051} 1180}
1052 1181
1053const char *connection::script_node_down () 1182const char *connection::script_node_down (int)
1054{ 1183{
1055 script_node (); 1184 script_node ();
1056 1185
1057 putenv ("STATE=down"); 1186 putenv ("STATE=down");
1058 1187
1077 shutdown (); 1206 shutdown ();
1078} 1207}
1079 1208
1080///////////////////////////////////////////////////////////////////////////// 1209/////////////////////////////////////////////////////////////////////////////
1081 1210
1082const char *vpn::script_if_up () 1211const char *vpn::script_if_up (int)
1083{ 1212{
1084 // the tunnel device mtu should be the physical mtu - overhead 1213 // the tunnel device mtu should be the physical mtu - overhead
1085 // the tricky part is rounding to the cipher key blocksize 1214 // the tricky part is rounding to the cipher key blocksize
1086 int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - UDP_OVERHEAD; 1215 int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - MAX_OVERHEAD;
1087 mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion 1216 mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion
1088 mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round 1217 mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round
1089 mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again 1218 mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again
1090 1219
1091 char *env; 1220 char *env;
1145 { 1274 {
1146 slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname); 1275 slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname);
1147 exit (1); 1276 exit (1);
1148 } 1277 }
1149 1278
1150 run_script (this, &vpn::script_if_up, true); 1279 run_script (run_script_cb (this, &vpn::script_if_up), true);
1151 1280
1152 vpn_ev_watcher.start (tap->fd, POLLIN); 1281 vpn_ev_watcher.start (tap->fd, POLLIN);
1153 1282
1154 reconnect_all (); 1283 reconnect_all ();
1155 1284

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines