ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.65
Committed: Tue Dec 4 17:17:20 2007 UTC (16 years, 5 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.64: +7 -6 lines
Log Message:
switch to new callback system

File Contents

# Content
1 /*
2 connection.C -- manage a single connection
3 Copyright (C) 2003-2005 Marc Lehmann <gvpe@schmorp.de>
4
5 This file is part of GVPE.
6
7 GVPE is free software; you can redistribute it and/or modify
8 it under the terms of the GNU General Public License as published by
9 the Free Software Foundation; either version 2 of the License, or
10 (at your option) any later version.
11
12 This program is distributed in the hope that it will be useful,
13 but WITHOUT ANY WARRANTY; without even the implied warranty of
14 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 GNU General Public License for more details.
16
17 You should have received a copy of the GNU General Public License
18 along with gvpe; if not, write to the Free Software
19 Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
20 */
21
22 #include "config.h"
23
24 #include <list>
25
26 #include <openssl/rand.h>
27 #include <openssl/evp.h>
28 #include <openssl/rsa.h>
29 #include <openssl/err.h>
30
31 #include "conf.h"
32 #include "slog.h"
33 #include "device.h"
34 #include "vpn.h"
35 #include "connection.h"
36
37 #include "netcompat.h"
38
39 #if !HAVE_RAND_PSEUDO_BYTES
40 # define RAND_pseudo_bytes RAND_bytes
41 #endif
42
43 #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
44
45 #define ULTRA_FAST 1
46 #define HLOG 15
47 #include "lzf/lzf.h"
48 #include "lzf/lzf_c.c"
49 #include "lzf/lzf_d.c"
50
51 struct crypto_ctx
52 {
53 EVP_CIPHER_CTX cctx;
54 HMAC_CTX hctx;
55
56 crypto_ctx (const rsachallenge &challenge, int enc);
57 ~crypto_ctx ();
58 };
59
60 crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
61 {
62 EVP_CIPHER_CTX_init (&cctx);
63 require (EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc));
64 HMAC_CTX_init (&hctx);
65 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
66 }
67
68 crypto_ctx::~crypto_ctx ()
69 {
70 require (EVP_CIPHER_CTX_cleanup (&cctx));
71 HMAC_CTX_cleanup (&hctx);
72 }
73
74 static void
75 rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h)
76 {
77 EVP_MD_CTX ctx;
78
79 EVP_MD_CTX_init (&ctx);
80 require (EVP_DigestInit (&ctx, RSA_HASH));
81 require (EVP_DigestUpdate(&ctx, &chg, sizeof chg));
82 require (EVP_DigestUpdate(&ctx, &id, sizeof id));
83 require (EVP_DigestFinal (&ctx, (unsigned char *)&h, 0));
84 EVP_MD_CTX_cleanup (&ctx);
85 }
86
87 struct rsa_entry
88 {
89 tstamp expire;
90 rsaid id;
91 rsachallenge chg;
92 };
93
94 struct rsa_cache : list<rsa_entry>
95 {
96 void cleaner_cb (ev::timer &w, int revents); ev::timer cleaner;
97
98 bool find (const rsaid &id, rsachallenge &chg)
99 {
100 for (iterator i = begin (); i != end (); ++i)
101 {
102 if (!memcmp (&id, &i->id, sizeof id) && i->expire > ev_now ())
103 {
104 memcpy (&chg, &i->chg, sizeof chg);
105
106 erase (i);
107 return true;
108 }
109 }
110
111 if (!cleaner.is_active ())
112 cleaner.again ();
113
114 return false;
115 }
116
117 void gen (rsaid &id, rsachallenge &chg)
118 {
119 rsa_entry e;
120
121 RAND_bytes ((unsigned char *)&id, sizeof id);
122 RAND_bytes ((unsigned char *)&chg, sizeof chg);
123
124 e.expire = ev_now () + RSA_TTL;
125 e.id = id;
126 memcpy (&e.chg, &chg, sizeof chg);
127
128 push_back (e);
129
130 if (!cleaner.is_active ())
131 cleaner.again ();
132 }
133
134 rsa_cache ()
135 {
136 cleaner.set<rsa_cache, &rsa_cache::cleaner_cb> (this);
137 cleaner.set (RSA_TTL, RSA_TTL);
138 }
139
140 } rsa_cache;
141
142 void rsa_cache::cleaner_cb (ev::timer &w, int revents)
143 {
144 if (empty ())
145 w.stop ();
146 else
147 {
148 for (iterator i = begin (); i != end (); )
149 if (i->expire <= ev_now ())
150 i = erase (i);
151 else
152 ++i;
153 }
154 }
155
156 //////////////////////////////////////////////////////////////////////////////
157
158 void pkt_queue::put (net_packet *p)
159 {
160 if (queue[i])
161 {
162 delete queue[i];
163 j = (j + 1) % QUEUEDEPTH;
164 }
165
166 queue[i] = p;
167
168 i = (i + 1) % QUEUEDEPTH;
169 }
170
171 net_packet *pkt_queue::get ()
172 {
173 net_packet *p = queue[j];
174
175 if (p)
176 {
177 queue[j] = 0;
178 j = (j + 1) % QUEUEDEPTH;
179 }
180
181 return p;
182 }
183
184 pkt_queue::pkt_queue ()
185 {
186 memset (queue, 0, sizeof (queue));
187 i = 0;
188 j = 0;
189 }
190
191 pkt_queue::~pkt_queue ()
192 {
193 for (i = QUEUEDEPTH; --i > 0; )
194 delete queue[i];
195 }
196
197 struct net_rateinfo
198 {
199 u32 host;
200 double pcnt, diff;
201 tstamp last;
202 };
203
204 // only do action once every x seconds per host whole allowing bursts.
205 // this implementation ("splay list" ;) is inefficient,
206 // but low on resources.
207 struct net_rate_limiter : list<net_rateinfo>
208 {
209 # define NRL_ALPHA (1. - 1. / 600.) // allow bursts
210 # define NRL_CUTOFF 10. // one event every CUTOFF seconds
211 # define NRL_EXPIRE (NRL_CUTOFF * 30.) // expire entries after this time
212 # define NRL_MAXDIF (NRL_CUTOFF * (1. / (1. - NRL_ALPHA))) // maximum diff /count value
213
214 bool can (const sockinfo &si) { return can((u32)si.host); }
215 bool can (u32 host);
216 };
217
218 net_rate_limiter auth_rate_limiter, reset_rate_limiter;
219
220 bool net_rate_limiter::can (u32 host)
221 {
222 iterator i;
223
224 for (i = begin (); i != end (); )
225 if (i->host == host)
226 break;
227 else if (i->last < ev_now () - NRL_EXPIRE)
228 i = erase (i);
229 else
230 i++;
231
232 if (i == end ())
233 {
234 net_rateinfo ri;
235
236 ri.host = host;
237 ri.pcnt = 1.;
238 ri.diff = NRL_MAXDIF;
239 ri.last = ev_now ();
240
241 push_front (ri);
242
243 return true;
244 }
245 else
246 {
247 net_rateinfo ri (*i);
248 erase (i);
249
250 ri.pcnt = ri.pcnt * NRL_ALPHA;
251 ri.diff = ri.diff * NRL_ALPHA + (ev_now () - ri.last);
252
253 ri.last = ev_now ();
254
255 double dif = ri.diff / ri.pcnt;
256
257 bool send = dif > NRL_CUTOFF;
258
259 if (dif > NRL_MAXDIF)
260 {
261 ri.pcnt = 1.;
262 ri.diff = NRL_MAXDIF;
263 }
264 else if (send)
265 ri.pcnt++;
266
267 push_front (ri);
268
269 return send;
270 }
271 }
272
273 /////////////////////////////////////////////////////////////////////////////
274
275 unsigned char hmac_packet::hmac_digest[EVP_MAX_MD_SIZE];
276
277 void hmac_packet::hmac_gen (crypto_ctx *ctx)
278 {
279 unsigned int xlen;
280
281 HMAC_CTX *hctx = &ctx->hctx;
282
283 HMAC_Init_ex (hctx, 0, 0, 0, 0);
284 HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet),
285 len - sizeof (hmac_packet));
286 HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen);
287 }
288
289 void
290 hmac_packet::hmac_set (crypto_ctx *ctx)
291 {
292 hmac_gen (ctx);
293
294 memcpy (hmac, hmac_digest, HMACLENGTH);
295 }
296
297 bool
298 hmac_packet::hmac_chk (crypto_ctx *ctx)
299 {
300 hmac_gen (ctx);
301
302 return !memcmp (hmac, hmac_digest, HMACLENGTH);
303 }
304
305 void vpn_packet::set_hdr (ptype type_, unsigned int dst)
306 {
307 type = type_;
308
309 int src = THISNODE->id;
310
311 src1 = src;
312 srcdst = ((src >> 8) << 4) | (dst >> 8);
313 dst1 = dst;
314 }
315
316 #define MAXVPNDATA (MAX_MTU - 6 - 6)
317 #define DATAHDR (sizeof (u32) + RAND_SIZE)
318
319 struct vpndata_packet : vpn_packet
320 {
321 u8 data[MAXVPNDATA + DATAHDR]; // seqno
322
323 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
324 tap_packet *unpack (connection *conn, u32 &seqno);
325 private:
326
327 const u32 data_hdr_size () const
328 {
329 return sizeof (vpndata_packet) - sizeof (net_packet) - MAXVPNDATA - DATAHDR;
330 }
331 };
332
333 void
334 vpndata_packet::setup (connection *conn, int dst, u8 *d, u32 l, u32 seqno)
335 {
336 EVP_CIPHER_CTX *cctx = &conn->octx->cctx;
337 int outl = 0, outl2;
338 ptype type = PT_DATA_UNCOMPRESSED;
339
340 #if ENABLE_COMPRESSION
341 u8 cdata[MAX_MTU];
342
343 if (conn->features & ENABLE_COMPRESSION)
344 {
345 u32 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
346
347 if (cl)
348 {
349 type = PT_DATA_COMPRESSED;
350 d = cdata;
351 l = cl + 2;
352
353 d[0] = cl >> 8;
354 d[1] = cl;
355 }
356 }
357 #endif
358
359 require (EVP_EncryptInit_ex (cctx, 0, 0, 0, 0));
360
361 struct {
362 #if RAND_SIZE
363 u8 rnd[RAND_SIZE];
364 #endif
365 u32 seqno;
366 } datahdr;
367
368 datahdr.seqno = ntohl (seqno);
369 #if RAND_SIZE
370 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
371 #endif
372
373 require (EVP_EncryptUpdate (cctx,
374 (unsigned char *) data + outl, &outl2,
375 (unsigned char *) &datahdr, DATAHDR));
376 outl += outl2;
377
378 require (EVP_EncryptUpdate (cctx,
379 (unsigned char *) data + outl, &outl2,
380 (unsigned char *) d, l));
381 outl += outl2;
382
383 require (EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2));
384 outl += outl2;
385
386 len = outl + data_hdr_size ();
387
388 set_hdr (type, dst);
389
390 hmac_set (conn->octx);
391 }
392
393 tap_packet *
394 vpndata_packet::unpack (connection *conn, u32 &seqno)
395 {
396 EVP_CIPHER_CTX *cctx = &conn->ictx->cctx;
397 int outl = 0, outl2;
398 tap_packet *p = new tap_packet;
399 u8 *d;
400 u32 l = len - data_hdr_size ();
401
402 require (EVP_DecryptInit_ex (cctx, 0, 0, 0, 0));
403
404 #if ENABLE_COMPRESSION
405 u8 cdata[MAX_MTU];
406
407 if (type == PT_DATA_COMPRESSED)
408 d = cdata;
409 else
410 #endif
411 d = &(*p)[6 + 6 - DATAHDR];
412
413 /* this overwrites part of the src mac, but we fix that later */
414 require (EVP_DecryptUpdate (cctx,
415 d, &outl2,
416 (unsigned char *)&data, len - data_hdr_size ()));
417 outl += outl2;
418
419 require (EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2));
420 outl += outl2;
421
422 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
423
424 id2mac (dst () ? dst() : THISNODE->id, p->dst);
425 id2mac (src (), p->src);
426
427 #if ENABLE_COMPRESSION
428 if (type == PT_DATA_COMPRESSED)
429 {
430 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
431
432 p->len = lzf_decompress (d + DATAHDR + 2, cl < MAX_MTU ? cl : 0,
433 &(*p)[6 + 6], MAX_MTU)
434 + 6 + 6;
435 }
436 else
437 p->len = outl + (6 + 6 - DATAHDR);
438 #endif
439
440 return p;
441 }
442
443 struct ping_packet : vpn_packet
444 {
445 void setup (int dst, ptype type)
446 {
447 set_hdr (type, dst);
448 len = sizeof (*this) - sizeof (net_packet);
449 }
450 };
451
452 struct config_packet : vpn_packet
453 {
454 // actually, hmaclen cannot be checked because the hmac
455 // field comes before this data, so peers with other
456 // hmacs simply will not work.
457 u8 prot_major, prot_minor, randsize, hmaclen;
458 u8 flags, challengelen, features, pad3;
459 u32 cipher_nid, digest_nid, hmac_nid;
460
461 void setup (ptype type, int dst);
462 bool chk_config () const;
463
464 static u8 get_features ()
465 {
466 u8 f = 0;
467 #if ENABLE_COMPRESSION
468 f |= FEATURE_COMPRESSION;
469 #endif
470 #if ENABLE_ROHC
471 f |= FEATURE_ROHC;
472 #endif
473 #if ENABLE_BRIDGING
474 f |= FEATURE_BRIDGING;
475 #endif
476 return f;
477 }
478 };
479
480 void config_packet::setup (ptype type, int dst)
481 {
482 prot_major = PROTOCOL_MAJOR;
483 prot_minor = PROTOCOL_MINOR;
484 randsize = RAND_SIZE;
485 hmaclen = HMACLENGTH;
486 flags = 0;
487 challengelen = sizeof (rsachallenge);
488 features = get_features ();
489
490 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
491 digest_nid = htonl (EVP_MD_type (RSA_HASH));
492 hmac_nid = htonl (EVP_MD_type (DIGEST));
493
494 len = sizeof (*this) - sizeof (net_packet);
495 set_hdr (type, dst);
496 }
497
498 bool config_packet::chk_config () const
499 {
500 if (prot_major != PROTOCOL_MAJOR)
501 slog (L_WARN, _("major version mismatch (remote %d <=> local %d)"), prot_major, PROTOCOL_MAJOR);
502 else if (randsize != RAND_SIZE)
503 slog (L_WARN, _("rand size mismatch (remote %d <=> local %d)"), randsize, RAND_SIZE);
504 else if (hmaclen != HMACLENGTH)
505 slog (L_WARN, _("hmac length mismatch (remote %d <=> local %d)"), hmaclen, HMACLENGTH);
506 else if (challengelen != sizeof (rsachallenge))
507 slog (L_WARN, _("challenge length mismatch (remote %d <=> local %d)"), challengelen, sizeof (rsachallenge));
508 else if (cipher_nid != htonl (EVP_CIPHER_nid (CIPHER)))
509 slog (L_WARN, _("cipher mismatch (remote %x <=> local %x)"), ntohl (cipher_nid), EVP_CIPHER_nid (CIPHER));
510 else if (digest_nid != htonl (EVP_MD_type (RSA_HASH)))
511 slog (L_WARN, _("digest mismatch (remote %x <=> local %x)"), ntohl (digest_nid), EVP_MD_type (RSA_HASH));
512 else if (hmac_nid != htonl (EVP_MD_type (DIGEST)))
513 slog (L_WARN, _("hmac mismatch (remote %x <=> local %x)"), ntohl (hmac_nid), EVP_MD_type (DIGEST));
514 else
515 return true;
516
517 return false;
518 }
519
520 struct auth_req_packet : config_packet
521 {
522 char magic[8];
523 u8 initiate; // false if this is just an automatic reply
524 u8 protocols; // supported protocols (will be patched on forward)
525 u8 pad2, pad3;
526 rsaid id;
527 rsaencrdata encr;
528
529 auth_req_packet (int dst, bool initiate_, u8 protocols_)
530 {
531 config_packet::setup (PT_AUTH_REQ, dst);
532 strncpy (magic, MAGIC, 8);
533 initiate = !!initiate_;
534 protocols = protocols_;
535
536 len = sizeof (*this) - sizeof (net_packet);
537 }
538 };
539
540 struct auth_res_packet : config_packet
541 {
542 rsaid id;
543 u8 pad1, pad2, pad3;
544 u8 response_len; // encrypted length
545 rsaresponse response;
546
547 auth_res_packet (int dst)
548 {
549 config_packet::setup (PT_AUTH_RES, dst);
550
551 len = sizeof (*this) - sizeof (net_packet);
552 }
553 };
554
555 struct connect_req_packet : vpn_packet
556 {
557 u8 id, protocols;
558 u8 pad1, pad2;
559
560 connect_req_packet (int dst, int id_, u8 protocols_)
561 : id(id_)
562 , protocols(protocols_)
563 {
564 set_hdr (PT_CONNECT_REQ, dst);
565 len = sizeof (*this) - sizeof (net_packet);
566 }
567 };
568
569 struct connect_info_packet : vpn_packet
570 {
571 u8 id, protocols;
572 u8 pad1, pad2;
573 sockinfo si;
574
575 connect_info_packet (int dst, int id_, const sockinfo &si_, u8 protocols_)
576 : id(id_)
577 , protocols(protocols_)
578 , si(si_)
579 {
580 set_hdr (PT_CONNECT_INFO, dst);
581
582 len = sizeof (*this) - sizeof (net_packet);
583 }
584 };
585
586 /////////////////////////////////////////////////////////////////////////////
587
588 void
589 connection::connection_established ()
590 {
591 slog (L_TRACE, _("%s: possible connection establish (ictx %d, octx %d)"), conf->nodename, !!ictx, !!octx);
592
593 if (ictx && octx)
594 {
595 connectmode = conf->connectmode;
596
597 // make sure rekeying timeouts are slightly asymmetric
598 ev::tstamp rekey_interval = ::conf.rekey + (conf->id > THISNODE->id ? 10 : 0);
599 rekey.start (rekey_interval, rekey_interval);
600 keepalive.start (::conf.keepalive);
601
602 // send queued packets
603 if (ictx && octx)
604 {
605 while (tap_packet *p = (tap_packet *)data_queue.get ())
606 {
607 send_data_packet (p);
608 delete p;
609 }
610
611 while (vpn_packet *p = (vpn_packet *)vpn_queue.get ())
612 {
613 send_vpn_packet (p, si, IPTOS_RELIABILITY);
614 delete p;
615 }
616 }
617 }
618 else
619 {
620 retry_cnt = 0;
621 establish_connection.start (5);
622 keepalive.stop ();
623 rekey.stop ();
624 }
625 }
626
627 void
628 connection::reset_si ()
629 {
630 protocol = best_protocol (THISNODE->protocols & conf->protocols);
631
632 // mask out protocols we cannot establish
633 if (!conf->udp_port) protocol &= ~PROT_UDPv4;
634 if (!conf->tcp_port) protocol &= ~PROT_TCPv4;
635 if (!conf->dns_port) protocol &= ~PROT_DNSv4;
636
637 if (protocol
638 && (!conf->can_direct (THISNODE)
639 || !THISNODE->can_direct (conf)))
640 {
641 slog (L_DEBUG, _("%s: direct connection denied"), conf->nodename);
642 protocol = 0;
643 }
644
645 si.set (conf, protocol);
646 }
647
648 // ensure sockinfo is valid, forward if necessary
649 const sockinfo &
650 connection::forward_si (const sockinfo &si) const
651 {
652 if (!si.valid ())
653 {
654 connection *r = vpn->find_router ();
655
656 if (r)
657 {
658 slog (L_DEBUG, _("%s: no common protocol, trying indirectly through %s (%s)"),
659 conf->nodename, r->conf->nodename, (const char *)r->si);
660 return r->si;
661 }
662 else
663 slog (L_DEBUG, _("%s: node unreachable, no common protocol"),
664 conf->nodename);
665 }
666
667 return si;
668 }
669
670 void
671 connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
672 {
673 if (!vpn->send_vpn_packet (pkt, si, tos))
674 reset_connection ();
675 }
676
677 void
678 connection::send_ping (const sockinfo &si, u8 pong)
679 {
680 ping_packet *pkt = new ping_packet;
681
682 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
683 send_vpn_packet (pkt, si, IPTOS_LOWDELAY);
684
685 delete pkt;
686 }
687
688 void
689 connection::send_reset (const sockinfo &si)
690 {
691 if (reset_rate_limiter.can (si) && connectmode != conf_node::C_DISABLED)
692 {
693 config_packet *pkt = new config_packet;
694
695 pkt->setup (vpn_packet::PT_RESET, conf->id);
696 send_vpn_packet (pkt, si, IPTOS_MINCOST);
697
698 delete pkt;
699 }
700 }
701
702 void
703 connection::send_auth_request (const sockinfo &si, bool initiate)
704 {
705 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols);
706
707 rsachallenge chg;
708 rsa_cache.gen (pkt->id, chg);
709 rsa_encrypt (conf->rsa_key, chg, pkt->encr);
710
711 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si);
712
713 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
714
715 delete pkt;
716 }
717
718 void
719 connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
720 {
721 auth_res_packet *pkt = new auth_res_packet (conf->id);
722
723 pkt->id = id;
724
725 rsa_hash (id, chg, pkt->response);
726
727 pkt->hmac_set (octx);
728
729 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
730
731 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
732
733 delete pkt;
734 }
735
736 void
737 connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
738 {
739 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)",
740 conf->id, rid, (const char *)rsi);
741
742 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
743
744 r->hmac_set (octx);
745 send_vpn_packet (r, si);
746
747 delete r;
748 }
749
750 void
751 connection::establish_connection_cb (ev::timer &w, int revents)
752 {
753 if (!ictx
754 && conf != THISNODE
755 && connectmode != conf_node::C_NEVER
756 && connectmode != conf_node::C_DISABLED
757 && !w.is_active ())
758 {
759 ev::tstamp retry_int = ev::tstamp (retry_cnt & 3
760 ? (retry_cnt & 3) + 1
761 : 1 << (retry_cnt >> 2));
762
763 reset_si ();
764
765 bool slow = si.prot & PROT_SLOW;
766
767 if (si.prot && !si.host)
768 {
769 slog (L_TRACE, _("%s: connection request (indirect)"), conf->nodename);
770 /*TODO*/ /* start the timer so we don't recurse endlessly */
771 w.start (1);
772 vpn->send_connect_request (conf->id);
773 }
774 else
775 {
776 slog (L_TRACE, _("%s: connection request (direct)"), conf->nodename, !!ictx, !!octx);
777
778 const sockinfo &dsi = forward_si (si);
779
780 slow = slow || (dsi.prot & PROT_SLOW);
781
782 if (dsi.valid () && auth_rate_limiter.can (dsi))
783 {
784 if (retry_cnt < 4)
785 send_auth_request (dsi, true);
786 else
787 send_ping (dsi, 0);
788 }
789 }
790
791 retry_int *= slow ? 8. : 0.7;
792
793 if (retry_int < conf->max_retry)
794 retry_cnt++;
795 else
796 retry_int = conf->max_retry;
797
798 w.start (retry_int);
799 }
800 }
801
802 void
803 connection::reset_connection ()
804 {
805 if (ictx && octx)
806 {
807 slog (L_INFO, _("%s(%s): connection lost"),
808 conf->nodename, (const char *)si);
809
810 if (::conf.script_node_down)
811 {
812 run_script_cb cb;
813 cb.set<connection, &connection::script_node_down> (this);
814 if (!run_script (cb, false))
815 slog (L_WARN, _("node-down command execution failed, continuing."));
816 }
817 }
818
819 delete ictx; ictx = 0;
820 delete octx; octx = 0;
821 #if ENABLE_DNS
822 dnsv4_reset_connection ();
823 #endif
824
825 si.host = 0;
826
827 last_activity = 0;
828 retry_cnt = 0;
829
830 rekey.stop ();
831 keepalive.stop ();
832 establish_connection.stop ();
833 }
834
835 void
836 connection::shutdown ()
837 {
838 if (ictx && octx)
839 send_reset (si);
840
841 reset_connection ();
842 }
843
844 void
845 connection::rekey_cb (ev::timer &w, int revents)
846 {
847 reset_connection ();
848 establish_connection ();
849 }
850
851 void
852 connection::send_data_packet (tap_packet *pkt)
853 {
854 vpndata_packet *p = new vpndata_packet;
855 int tos = 0;
856
857 // I am not hilarious about peeking into packets, but so be it.
858 if (conf->inherit_tos && pkt->is_ipv4 ())
859 tos = (*pkt)[15] & IPTOS_TOS_MASK;
860
861 p->setup (this, conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
862 send_vpn_packet (p, si, tos);
863
864 delete p;
865
866 if (oseqno > MAX_SEQNO)
867 rekey ();
868 }
869
870 void
871 connection::inject_data_packet (tap_packet *pkt, bool broadcast/*TODO DDD*/)
872 {
873 if (ictx && octx)
874 send_data_packet (pkt);
875 else
876 {
877 if (!broadcast)
878 data_queue.put (new tap_packet (*pkt));
879
880 establish_connection ();
881 }
882 }
883
884 void connection::inject_vpn_packet (vpn_packet *pkt, int tos)
885 {
886 if (ictx && octx)
887 send_vpn_packet (pkt, si, tos);
888 else
889 {
890 vpn_queue.put ((vpn_packet *)new data_packet (*(data_packet *)pkt));
891
892 establish_connection ();
893 }
894 }
895
896 void
897 connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
898 {
899 last_activity = ev_now ();
900
901 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
902 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
903
904 if (connectmode == conf_node::C_DISABLED)
905 return;
906
907 switch (pkt->typ ())
908 {
909 case vpn_packet::PT_PING:
910 // we send pings instead of auth packets after some retries,
911 // so reset the retry counter and establish a connection
912 // when we receive a ping.
913 if (!ictx)
914 {
915 if (auth_rate_limiter.can (rsi))
916 send_auth_request (rsi, true);
917 }
918 else
919 send_ping (rsi, 1); // pong
920
921 break;
922
923 case vpn_packet::PT_PONG:
924 break;
925
926 case vpn_packet::PT_RESET:
927 {
928 reset_connection ();
929
930 config_packet *p = (config_packet *) pkt;
931
932 if (!p->chk_config ())
933 {
934 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
935 conf->nodename, (const char *)rsi);
936 connectmode = conf_node::C_DISABLED;
937 }
938 else if (connectmode == conf_node::C_ALWAYS)
939 establish_connection ();
940 }
941 break;
942
943 case vpn_packet::PT_AUTH_REQ:
944 if (auth_rate_limiter.can (rsi))
945 {
946 auth_req_packet *p = (auth_req_packet *) pkt;
947
948 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
949
950 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
951 {
952 if (p->prot_minor != PROTOCOL_MINOR)
953 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
954 conf->nodename, (const char *)rsi,
955 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
956
957 if (p->initiate)
958 send_auth_request (rsi, false);
959
960 rsachallenge k;
961
962 if (!rsa_decrypt (::conf.rsa_key, p->encr, k))
963 {
964 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"),
965 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0));
966 break;
967 }
968 else
969 {
970 delete octx;
971
972 octx = new crypto_ctx (k, 1);
973 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
974
975 conf->protocols = p->protocols;
976 features = p->features & config_packet::get_features ();
977
978 send_auth_response (rsi, p->id, k);
979
980 connection_established ();
981
982 break;
983 }
984 }
985 else
986 slog (L_WARN, _("%s(%s): protocol mismatch"),
987 conf->nodename, (const char *)rsi);
988
989 send_reset (rsi);
990 }
991
992 break;
993
994 case vpn_packet::PT_AUTH_RES:
995 {
996 auth_res_packet *p = (auth_res_packet *) pkt;
997
998 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
999
1000 if (p->chk_config ())
1001 {
1002 if (p->prot_minor != PROTOCOL_MINOR)
1003 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
1004 conf->nodename, (const char *)rsi,
1005 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
1006
1007 rsachallenge chg;
1008
1009 if (!rsa_cache.find (p->id, chg))
1010 {
1011 slog (L_ERR, _("%s(%s): unrequested auth response ignored"),
1012 conf->nodename, (const char *)rsi);
1013 break;
1014 }
1015 else
1016 {
1017 crypto_ctx *cctx = new crypto_ctx (chg, 0);
1018
1019 if (!p->hmac_chk (cctx))
1020 {
1021 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
1022 "could be an attack, or just corruption or a synchronization error"),
1023 conf->nodename, (const char *)rsi);
1024 break;
1025 }
1026 else
1027 {
1028 rsaresponse h;
1029
1030 rsa_hash (p->id, chg, h);
1031
1032 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
1033 {
1034 prot_minor = p->prot_minor;
1035
1036 delete ictx; ictx = cctx;
1037
1038 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
1039
1040 si = rsi;
1041 protocol = rsi.prot;
1042
1043 connection_established ();
1044
1045 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
1046 conf->nodename, (const char *)rsi,
1047 p->prot_major, p->prot_minor);
1048
1049 if (::conf.script_node_up)
1050 {
1051 run_script_cb cb;
1052 cb.set<connection, &connection::script_node_up> (this);
1053 if (!run_script (cb, false))
1054 slog (L_WARN, _("node-up command execution failed, continuing."));
1055 }
1056
1057 break;
1058 }
1059 else
1060 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
1061 conf->nodename, (const char *)rsi);
1062 }
1063
1064 delete cctx;
1065 }
1066 }
1067 }
1068
1069 send_reset (rsi);
1070 break;
1071
1072 case vpn_packet::PT_DATA_COMPRESSED:
1073 #if !ENABLE_COMPRESSION
1074 send_reset (rsi);
1075 break;
1076 #endif
1077
1078 case vpn_packet::PT_DATA_UNCOMPRESSED:
1079
1080 if (ictx && octx)
1081 {
1082 vpndata_packet *p = (vpndata_packet *)pkt;
1083
1084 if (!p->hmac_chk (ictx))
1085 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
1086 "could be an attack, or just corruption or a synchronization error"),
1087 conf->nodename, (const char *)rsi);
1088 else
1089 {
1090 u32 seqno;
1091 tap_packet *d = p->unpack (this, seqno);
1092
1093 if (iseqno.recv_ok (seqno))
1094 {
1095 vpn->tap->send (d);
1096
1097 if (si != rsi)
1098 {
1099 // fast re-sync on source address changes, useful especially for tcp/ip
1100 si = rsi;
1101
1102 slog (L_INFO, _("%s(%s): socket address changed to %s"),
1103 conf->nodename, (const char *)si, (const char *)rsi);
1104 }
1105 }
1106
1107 delete d;
1108 break;
1109 }
1110 }
1111
1112 send_reset (rsi);
1113 break;
1114
1115 case vpn_packet::PT_CONNECT_REQ:
1116 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1117 {
1118 connect_req_packet *p = (connect_req_packet *) pkt;
1119
1120 if (p->id > 0 && p->id <= vpn->conns.size ())
1121 {
1122 connection *c = vpn->conns[p->id - 1];
1123 conf->protocols = p->protocols;
1124
1125 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]",
1126 conf->id, p->id, c->ictx && c->octx);
1127
1128 if (c->ictx && c->octx)
1129 {
1130 // send connect_info packets to both sides, in case one is
1131 // behind a nat firewall (or both ;)
1132 c->send_connect_info (conf->id, si, conf->protocols);
1133 send_connect_info (c->conf->id, c->si, c->conf->protocols);
1134 }
1135 else
1136 c->establish_connection ();
1137 }
1138 else
1139 slog (L_WARN,
1140 _("received authenticated connection request from unknown node #%d, config file mismatch?"),
1141 p->id);
1142 }
1143
1144 break;
1145
1146 case vpn_packet::PT_CONNECT_INFO:
1147 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1148 {
1149 connect_info_packet *p = (connect_info_packet *)pkt;
1150
1151 if (p->id > 0 && p->id <= vpn->conns.size ())
1152 {
1153 connection *c = vpn->conns[p->id - 1];
1154
1155 c->conf->protocols = p->protocols;
1156 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1157 p->si.upgrade_protocol (protocol, c->conf);
1158
1159 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
1160 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
1161
1162 const sockinfo &dsi = forward_si (p->si);
1163
1164 if (dsi.valid ())
1165 c->send_auth_request (dsi, true);
1166 }
1167 else
1168 slog (L_WARN,
1169 _("received authenticated connection request from unknown node #%d, config file mismatch?"),
1170 p->id);
1171 }
1172
1173 break;
1174
1175 default:
1176 send_reset (rsi);
1177 break;
1178 }
1179 }
1180
1181 void connection::keepalive_cb (ev::timer &w, int revents)
1182 {
1183 if (ev_now () >= last_activity + ::conf.keepalive + 30)
1184 {
1185 reset_connection ();
1186 establish_connection ();
1187 }
1188 else if (ev_now () < last_activity + ::conf.keepalive)
1189 w.start (last_activity + ::conf.keepalive - ev::now ());
1190 else if (conf->connectmode != conf_node::C_ONDEMAND
1191 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1192 {
1193 send_ping (si);
1194 w.start (5);
1195 }
1196 else if (ev_now () < last_activity + ::conf.keepalive + 10)
1197 // hold ondemand connections implicitly a few seconds longer
1198 // should delete octx, though, or something like that ;)
1199 w.start (last_activity + ::conf.keepalive + 10 - ev::now ());
1200 else
1201 reset_connection ();
1202 }
1203
1204 void connection::send_connect_request (int id)
1205 {
1206 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols);
1207
1208 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id);
1209 p->hmac_set (octx);
1210 send_vpn_packet (p, si);
1211
1212 delete p;
1213 }
1214
1215 void connection::script_init_env (const char *ext)
1216 {
1217 char *env;
1218 asprintf (&env, "IFUPDATA%s=%s", ext, conf->if_up_data); putenv (env);
1219 asprintf (&env, "NODENAME%s=%s", ext, conf->nodename); putenv (env);
1220 asprintf (&env, "MAC%s=%02x:%02x:%02x:%02x:%02x:%02x", ext,
1221 0xfe, 0xfd, 0x80, 0x00, conf->id >> 8,
1222 conf->id & 0xff); putenv (env);
1223 }
1224
1225 void connection::script_init_connect_env ()
1226 {
1227 vpn->script_init_env ();
1228
1229 char *env;
1230 asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1231 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1232 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1233 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1234 }
1235
1236 const char *connection::script_node_up ()
1237 {
1238 script_init_connect_env ();
1239
1240 putenv ((char *)"STATE=up");
1241
1242 char *filename;
1243 asprintf (&filename,
1244 "%s/%s",
1245 confbase,
1246 ::conf.script_node_up ? ::conf.script_node_up : "node-up");
1247
1248 return filename;
1249 }
1250
1251 const char *connection::script_node_down ()
1252 {
1253 script_init_connect_env ();
1254
1255 putenv ((char *)"STATE=down");
1256
1257 char *filename;
1258 asprintf (&filename,
1259 "%s/%s",
1260 confbase,
1261 ::conf.script_node_down ? ::conf.script_node_down : "node-down");
1262
1263 return filename;
1264 }
1265
1266 connection::connection (struct vpn *vpn, conf_node *conf)
1267 : vpn(vpn), conf(conf)
1268 #if ENABLE_DNS
1269 , dns (0)
1270 #endif
1271 {
1272 rekey .set<connection, &connection::rekey_cb > (this);
1273 keepalive .set<connection, &connection::keepalive_cb > (this);
1274 establish_connection.set<connection, &connection::establish_connection_cb> (this);
1275
1276 octx = ictx = 0;
1277 retry_cnt = 0;
1278
1279 if (!conf->protocols) // make sure some protocol is enabled
1280 conf->protocols = PROT_UDPv4;
1281
1282 connectmode = conf_node::C_ALWAYS; // initial setting
1283 reset_connection ();
1284 }
1285
1286 connection::~connection ()
1287 {
1288 shutdown ();
1289 }
1290
1291 void connection_init ()
1292 {
1293 auth_rate_limiter.clear ();
1294 reset_rate_limiter.clear ();
1295 }
1296