ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.70
Committed: Thu Aug 7 19:07:02 2008 UTC (15 years, 9 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.69: +49 -8 lines
Log Message:
*** empty log message ***

File Contents

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