ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.57
Committed: Thu Jul 7 14:41:51 2005 UTC (18 years, 10 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.56: +23 -15 lines
Log Message:
*** empty log message ***

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