ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.28
Committed: Tue Jan 27 05:56:35 2004 UTC (20 years, 4 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.27: +3 -3 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 connection.C -- manage a single connection
3 Copyright (C) 2003-2004 Marc Lehmann <pcg@goof.com>
4
5 This program is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published by
7 the Free Software Foundation; either version 2 of the License, or
8 (at your option) any later version.
9
10 This program is distributed in the hope that it will be useful,
11 but WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 GNU General Public License for more details.
14
15 You should have received a copy of the GNU General Public License
16 along with this program; if not, write to the Free Software
17 Foundation, Inc. 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 */
19
20 #include "config.h"
21
22 extern "C" {
23 # include "lzf/lzf.h"
24 }
25
26 #include <cassert>
27
28 #include <list>
29
30 #include <openssl/rand.h>
31 #include <openssl/evp.h>
32 #include <openssl/rsa.h>
33 #include <openssl/err.h>
34
35 #include "gettext.h"
36
37 #include "conf.h"
38 #include "slog.h"
39 #include "device.h"
40 #include "vpn.h"
41 #include "connection.h"
42
43 #include "netcompat.h"
44
45 #if !HAVE_RAND_PSEUDO_BYTES
46 # define RAND_pseudo_bytes RAND_bytes
47 #endif
48
49 #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
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 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 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 EVP_DigestInit (&ctx, RSA_HASH);
81 EVP_DigestUpdate(&ctx, &chg, sizeof chg);
82 EVP_DigestUpdate(&ctx, &id, sizeof id);
83 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 static const double ALPHA = 1. - 1. / 600.; // allow bursts
206 static const double CUTOFF = 10.; // one event every CUTOFF seconds
207 static const double EXPIRE = CUTOFF * 30.; // expire entries after this time
208 static const double MAXDIF = CUTOFF * (1. / (1. - 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 - 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 = 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 * ALPHA;
247 ri.diff = ri.diff * ALPHA + (NOW - ri.last);
248
249 ri.last = NOW;
250
251 double dif = ri.diff / ri.pcnt;
252
253 bool send = dif > CUTOFF;
254
255 if (dif > MAXDIF)
256 {
257 ri.pcnt = 1.;
258 ri.diff = 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 u32 cl;
339
340 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
341 if (cl)
342 {
343 type = PT_DATA_COMPRESSED;
344 d = cdata;
345 l = cl + 2;
346
347 d[0] = cl >> 8;
348 d[1] = cl;
349 }
350 #endif
351
352 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0);
353
354 struct {
355 #if RAND_SIZE
356 u8 rnd[RAND_SIZE];
357 #endif
358 u32 seqno;
359 } datahdr;
360
361 datahdr.seqno = ntohl (seqno);
362 #if RAND_SIZE
363 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
364 #endif
365
366 EVP_EncryptUpdate (cctx,
367 (unsigned char *) data + outl, &outl2,
368 (unsigned char *) &datahdr, DATAHDR);
369 outl += outl2;
370
371 EVP_EncryptUpdate (cctx,
372 (unsigned char *) data + outl, &outl2,
373 (unsigned char *) d, l);
374 outl += outl2;
375
376 EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2);
377 outl += outl2;
378
379 len = outl + data_hdr_size ();
380
381 set_hdr (type, dst);
382
383 hmac_set (conn->octx);
384 }
385
386 tap_packet *
387 vpndata_packet::unpack (connection *conn, u32 &seqno)
388 {
389 EVP_CIPHER_CTX *cctx = &conn->ictx->cctx;
390 int outl = 0, outl2;
391 tap_packet *p = new tap_packet;
392 u8 *d;
393 u32 l = len - data_hdr_size ();
394
395 EVP_DecryptInit_ex (cctx, 0, 0, 0, 0);
396
397 #if ENABLE_COMPRESSION
398 u8 cdata[MAX_MTU];
399
400 if (type == PT_DATA_COMPRESSED)
401 d = cdata;
402 else
403 #endif
404 d = &(*p)[6 + 6 - DATAHDR];
405
406 /* this overwrites part of the src mac, but we fix that later */
407 EVP_DecryptUpdate (cctx,
408 d, &outl2,
409 (unsigned char *)&data, len - data_hdr_size ());
410 outl += outl2;
411
412 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2);
413 outl += outl2;
414
415 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
416
417 id2mac (dst () ? dst() : THISNODE->id, p->dst);
418 id2mac (src (), p->src);
419
420 #if ENABLE_COMPRESSION
421 if (type == PT_DATA_COMPRESSED)
422 {
423 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
424
425 p->len = lzf_decompress (d + DATAHDR + 2, cl < MAX_MTU ? cl : 0,
426 &(*p)[6 + 6], MAX_MTU)
427 + 6 + 6;
428 }
429 else
430 p->len = outl + (6 + 6 - DATAHDR);
431 #endif
432
433 return p;
434 }
435
436 struct ping_packet : vpn_packet
437 {
438 void setup (int dst, ptype type)
439 {
440 set_hdr (type, dst);
441 len = sizeof (*this) - sizeof (net_packet);
442 }
443 };
444
445 struct config_packet : vpn_packet
446 {
447 // actually, hmaclen cannot be checked because the hmac
448 // field comes before this data, so peers with other
449 // hmacs simply will not work.
450 u8 prot_major, prot_minor, randsize, hmaclen;
451 u8 flags, challengelen, pad2, pad3;
452 u32 cipher_nid, digest_nid, hmac_nid;
453
454 const u8 curflags () const
455 {
456 return 0x80
457 | (ENABLE_COMPRESSION ? 0x01 : 0x00);
458 }
459
460 void setup (ptype type, int dst);
461 bool chk_config () const;
462 };
463
464 void config_packet::setup (ptype type, int dst)
465 {
466 prot_major = PROTOCOL_MAJOR;
467 prot_minor = PROTOCOL_MINOR;
468 randsize = RAND_SIZE;
469 hmaclen = HMACLENGTH;
470 flags = curflags ();
471 challengelen = sizeof (rsachallenge);
472
473 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
474 digest_nid = htonl (EVP_MD_type (RSA_HASH));
475 hmac_nid = htonl (EVP_MD_type (DIGEST));
476
477 len = sizeof (*this) - sizeof (net_packet);
478 set_hdr (type, dst);
479 }
480
481 bool config_packet::chk_config () const
482 {
483 if (prot_major != PROTOCOL_MAJOR)
484 slog (L_WARN, _("major version mismatch (remote %d <=> local %d)"), prot_major, PROTOCOL_MAJOR);
485 else if (randsize != RAND_SIZE)
486 slog (L_WARN, _("rand size mismatch (remote %d <=> local %d)"), randsize, RAND_SIZE);
487 else if (hmaclen != HMACLENGTH)
488 slog (L_WARN, _("hmac length mismatch (remote %d <=> local %d)"), hmaclen, HMACLENGTH);
489 else if (flags != curflags ())
490 slog (L_WARN, _("flag mismatch (remote %x <=> local %x)"), flags, curflags ());
491 else if (challengelen != sizeof (rsachallenge))
492 slog (L_WARN, _("challenge length mismatch (remote %d <=> local %d)"), challengelen, sizeof (rsachallenge));
493 else if (cipher_nid != htonl (EVP_CIPHER_nid (CIPHER)))
494 slog (L_WARN, _("cipher mismatch (remote %x <=> local %x)"), ntohl (cipher_nid), EVP_CIPHER_nid (CIPHER));
495 else if (digest_nid != htonl (EVP_MD_type (RSA_HASH)))
496 slog (L_WARN, _("digest mismatch (remote %x <=> local %x)"), ntohl (digest_nid), EVP_MD_type (RSA_HASH));
497 else if (hmac_nid != htonl (EVP_MD_type (DIGEST)))
498 slog (L_WARN, _("hmac mismatch (remote %x <=> local %x)"), ntohl (hmac_nid), EVP_MD_type (DIGEST));
499 else
500 return true;
501
502 return false;
503 }
504
505 struct auth_req_packet : config_packet
506 {
507 char magic[8];
508 u8 initiate; // false if this is just an automatic reply
509 u8 protocols; // supported protocols (will be patched on forward)
510 u8 pad2, pad3;
511 rsaid id;
512 rsaencrdata encr;
513
514 auth_req_packet (int dst, bool initiate_, u8 protocols_)
515 {
516 config_packet::setup (PT_AUTH_REQ, dst);
517 strncpy (magic, MAGIC, 8);
518 initiate = !!initiate_;
519 protocols = protocols_;
520
521 len = sizeof (*this) - sizeof (net_packet);
522 }
523 };
524
525 struct auth_res_packet : config_packet
526 {
527 rsaid id;
528 u8 pad1, pad2, pad3;
529 u8 response_len; // encrypted length
530 rsaresponse response;
531
532 auth_res_packet (int dst)
533 {
534 config_packet::setup (PT_AUTH_RES, dst);
535
536 len = sizeof (*this) - sizeof (net_packet);
537 }
538 };
539
540 struct connect_req_packet : vpn_packet
541 {
542 u8 id, protocols;
543 u8 pad1, pad2;
544
545 connect_req_packet (int dst, int id_, u8 protocols_)
546 : id(id_)
547 , protocols(protocols_)
548 {
549 set_hdr (PT_CONNECT_REQ, dst);
550 len = sizeof (*this) - sizeof (net_packet);
551 }
552 };
553
554 struct connect_info_packet : vpn_packet
555 {
556 u8 id, protocols;
557 u8 pad1, pad2;
558 sockinfo si;
559
560 connect_info_packet (int dst, int id_, const sockinfo &si_, u8 protocols_)
561 : id(id_)
562 , protocols(protocols_)
563 , si(si_)
564 {
565 set_hdr (PT_CONNECT_INFO, dst);
566
567 len = sizeof (*this) - sizeof (net_packet);
568 }
569 };
570
571 /////////////////////////////////////////////////////////////////////////////
572
573 void
574 connection::connection_established ()
575 {
576 if (ictx && octx)
577 {
578 connectmode = conf->connectmode;
579
580 rekey.start (NOW + ::conf.rekey);
581 keepalive.start (NOW + ::conf.keepalive);
582
583 // send queued packets
584 if (ictx && octx)
585 {
586 while (tap_packet *p = (tap_packet *)data_queue.get ())
587 {
588 send_data_packet (p);
589 delete p;
590 }
591
592 while (vpn_packet *p = (vpn_packet *)vpn_queue.get ())
593 {
594 send_vpn_packet (p, si, IPTOS_RELIABILITY);
595 delete p;
596 }
597 }
598 }
599 else
600 {
601 retry_cnt = 0;
602 establish_connection.start (NOW + 5);
603 keepalive.stop ();
604 rekey.stop ();
605 }
606 }
607
608 void
609 connection::reset_si ()
610 {
611 protocol = best_protocol (THISNODE->protocols & conf->protocols);
612
613 // mask out protocols we cannot establish
614 if (!conf->udp_port) protocol &= ~PROT_UDPv4;
615 if (!conf->tcp_port) protocol &= ~PROT_TCPv4;
616
617 si.set (conf, protocol);
618 }
619
620 // ensure sockinfo is valid, forward if necessary
621 const sockinfo &
622 connection::forward_si (const sockinfo &si) const
623 {
624 if (!si.valid ())
625 {
626 connection *r = vpn->find_router ();
627
628 if (r)
629 {
630 slog (L_DEBUG, _("%s: no common protocol, trying indirectly through %s"),
631 conf->nodename, r->conf->nodename);
632 return r->si;
633 }
634 else
635 slog (L_DEBUG, _("%s: node unreachable, no common protocol"),
636 conf->nodename);
637 }
638
639 return si;
640 }
641
642 void
643 connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
644 {
645 if (!vpn->send_vpn_packet (pkt, si, tos))
646 reset_connection ();
647 }
648
649 void
650 connection::send_ping (const sockinfo &si, u8 pong)
651 {
652 ping_packet *pkt = new ping_packet;
653
654 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
655 send_vpn_packet (pkt, si, IPTOS_LOWDELAY);
656
657 delete pkt;
658 }
659
660 void
661 connection::send_reset (const sockinfo &si)
662 {
663 if (reset_rate_limiter.can (si) && connectmode != conf_node::C_DISABLED)
664 {
665 config_packet *pkt = new config_packet;
666
667 pkt->setup (vpn_packet::PT_RESET, conf->id);
668 send_vpn_packet (pkt, si, IPTOS_MINCOST);
669
670 delete pkt;
671 }
672 }
673
674 void
675 connection::send_auth_request (const sockinfo &si, bool initiate)
676 {
677 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols);
678
679 rsachallenge chg;
680 rsa_cache.gen (pkt->id, chg);
681 rsa_encrypt (conf->rsa_key, chg, pkt->encr);
682
683 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si);
684
685 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
686
687 delete pkt;
688 }
689
690 void
691 connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
692 {
693 auth_res_packet *pkt = new auth_res_packet (conf->id);
694
695 pkt->id = id;
696
697 rsa_hash (id, chg, pkt->response);
698
699 pkt->hmac_set (octx);
700
701 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
702
703 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
704
705 delete pkt;
706 }
707
708 void
709 connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
710 {
711 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n",
712 conf->id, rid, (const char *)rsi);
713
714 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
715
716 r->hmac_set (octx);
717 send_vpn_packet (r, si);
718
719 delete r;
720 }
721
722 void
723 connection::establish_connection_cb (time_watcher &w)
724 {
725 if (!ictx
726 && conf != THISNODE
727 && connectmode != conf_node::C_NEVER
728 && connectmode != conf_node::C_DISABLED
729 && NOW > w.at)
730 {
731 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6;
732
733 if (retry_int < 3600 * 8)
734 retry_cnt++;
735
736 w.start (NOW + retry_int);
737
738 reset_si ();
739
740 if (si.prot && !si.host)
741 vpn->send_connect_request (conf->id);
742 else
743 {
744 const sockinfo &dsi = forward_si (si);
745
746 if (dsi.valid () && auth_rate_limiter.can (dsi))
747 {
748 if (retry_cnt < 4)
749 send_auth_request (dsi, true);
750 else
751 send_ping (dsi, 0);
752 }
753 }
754 }
755 }
756
757 void
758 connection::reset_connection ()
759 {
760 if (ictx && octx)
761 {
762 slog (L_INFO, _("%s(%s): connection lost"),
763 conf->nodename, (const char *)si);
764
765 if (::conf.script_node_down)
766 run_script (run_script_cb (this, &connection::script_node_down), false);
767 }
768
769 delete ictx; ictx = 0;
770 delete octx; octx = 0;
771
772 si.host= 0;
773
774 last_activity = 0;
775 retry_cnt = 0;
776
777 rekey.stop ();
778 keepalive.stop ();
779 establish_connection.stop ();
780 }
781
782 void
783 connection::shutdown ()
784 {
785 if (ictx && octx)
786 send_reset (si);
787
788 reset_connection ();
789 }
790
791 void
792 connection::rekey_cb (time_watcher &w)
793 {
794 reset_connection ();
795 establish_connection ();
796 }
797
798 void
799 connection::send_data_packet (tap_packet *pkt)
800 {
801 vpndata_packet *p = new vpndata_packet;
802 int tos = 0;
803
804 // I am not hilarious about peeking into packets, but so be it.
805 if (conf->inherit_tos && pkt->is_ipv4 ())
806 tos = (*pkt)[15] & IPTOS_TOS_MASK;
807
808 p->setup (this, conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
809 send_vpn_packet (p, si, tos);
810
811 delete p;
812
813 if (oseqno > MAX_SEQNO)
814 rekey ();
815 }
816
817 void
818 connection::inject_data_packet (tap_packet *pkt, bool broadcast/*TODO DDD*/)
819 {
820 if (ictx && octx)
821 send_data_packet (pkt);
822 else
823 {
824 if (!broadcast)//DDDD
825 data_queue.put (new tap_packet (*pkt));
826
827 establish_connection ();
828 }
829 }
830
831 void connection::inject_vpn_packet (vpn_packet *pkt, int tos)
832 {
833 if (ictx && octx)
834 send_vpn_packet (pkt, si, tos);
835 else
836 {
837 vpn_queue.put ((vpn_packet *)new data_packet (*(data_packet *)pkt));
838
839 establish_connection ();
840 }
841 }
842
843 void
844 connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
845 {
846 last_activity = NOW;
847
848 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
849 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
850
851 switch (pkt->typ ())
852 {
853 case vpn_packet::PT_PING:
854 // we send pings instead of auth packets after some retries,
855 // so reset the retry counter and establish a connection
856 // when we receive a ping.
857 if (!ictx)
858 {
859 if (auth_rate_limiter.can (rsi))
860 send_auth_request (rsi, true);
861 }
862 else
863 send_ping (rsi, 1); // pong
864
865 break;
866
867 case vpn_packet::PT_PONG:
868 break;
869
870 case vpn_packet::PT_RESET:
871 {
872 reset_connection ();
873
874 config_packet *p = (config_packet *) pkt;
875
876 if (!p->chk_config ())
877 {
878 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
879 conf->nodename, (const char *)rsi);
880 connectmode = conf_node::C_DISABLED;
881 }
882 else if (connectmode == conf_node::C_ALWAYS)
883 establish_connection ();
884 }
885 break;
886
887 case vpn_packet::PT_AUTH_REQ:
888 if (auth_rate_limiter.can (rsi))
889 {
890 auth_req_packet *p = (auth_req_packet *) pkt;
891
892 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
893
894 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
895 {
896 if (p->prot_minor != PROTOCOL_MINOR)
897 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
898 conf->nodename, (const char *)rsi,
899 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
900
901 if (p->initiate)
902 send_auth_request (rsi, false);
903
904 rsachallenge k;
905
906 if (!rsa_decrypt (::conf.rsa_key, p->encr, k))
907 {
908 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"),
909 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0));
910 break;
911 }
912 else
913 {
914 delete octx;
915
916 octx = new crypto_ctx (k, 1);
917 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
918
919 conf->protocols = p->protocols;
920
921 send_auth_response (rsi, p->id, k);
922
923 connection_established ();
924
925 break;
926 }
927 }
928 else
929 slog (L_WARN, _("%s(%s): protocol mismatch"),
930 conf->nodename, (const char *)rsi);
931
932 send_reset (rsi);
933 }
934
935 break;
936
937 case vpn_packet::PT_AUTH_RES:
938 {
939 auth_res_packet *p = (auth_res_packet *) pkt;
940
941 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
942
943 if (p->chk_config ())
944 {
945 if (p->prot_minor != PROTOCOL_MINOR)
946 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
947 conf->nodename, (const char *)rsi,
948 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
949
950 rsachallenge chg;
951
952 if (!rsa_cache.find (p->id, chg))
953 {
954 slog (L_ERR, _("%s(%s): unrequested auth response ignored"),
955 conf->nodename, (const char *)rsi);
956 break;
957 }
958 else
959 {
960 crypto_ctx *cctx = new crypto_ctx (chg, 0);
961
962 if (!p->hmac_chk (cctx))
963 {
964 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
965 "could be an attack, or just corruption or a synchronization error"),
966 conf->nodename, (const char *)rsi);
967 break;
968 }
969 else
970 {
971 rsaresponse h;
972
973 rsa_hash (p->id, chg, h);
974
975 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
976 {
977 prot_minor = p->prot_minor;
978
979 delete ictx; ictx = cctx;
980
981 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
982
983 si = rsi;
984 protocol = rsi.prot;
985
986 connection_established ();
987
988 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
989 conf->nodename, (const char *)rsi,
990 p->prot_major, p->prot_minor);
991
992 if (::conf.script_node_up)
993 run_script (run_script_cb (this, &connection::script_node_up), false);
994
995 break;
996 }
997 else
998 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
999 conf->nodename, (const char *)rsi);
1000 }
1001
1002 delete cctx;
1003 }
1004 }
1005 }
1006
1007 send_reset (rsi);
1008 break;
1009
1010 case vpn_packet::PT_DATA_COMPRESSED:
1011 #if !ENABLE_COMPRESSION
1012 send_reset (rsi);
1013 break;
1014 #endif
1015
1016 case vpn_packet::PT_DATA_UNCOMPRESSED:
1017
1018 if (ictx && octx)
1019 {
1020 vpndata_packet *p = (vpndata_packet *)pkt;
1021
1022 if (!p->hmac_chk (ictx))
1023 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
1024 "could be an attack, or just corruption or a synchronization error"),
1025 conf->nodename, (const char *)rsi);
1026 else
1027 {
1028 u32 seqno;
1029 tap_packet *d = p->unpack (this, seqno);
1030
1031 if (iseqno.recv_ok (seqno))
1032 {
1033 vpn->tap->send (d);
1034
1035 if (si != rsi)
1036 {
1037 // fast re-sync on connection changes, useful especially for tcp/ip
1038 si = rsi;
1039
1040 slog (L_INFO, _("%s(%s): socket address changed to %s"),
1041 conf->nodename, (const char *)si, (const char *)rsi);
1042 }
1043
1044 delete d;
1045
1046 break;
1047 }
1048 }
1049 }
1050
1051 send_reset (rsi);
1052 break;
1053
1054 case vpn_packet::PT_CONNECT_REQ:
1055 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1056 {
1057 connect_req_packet *p = (connect_req_packet *) pkt;
1058
1059 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1060 connection *c = vpn->conns[p->id - 1];
1061 conf->protocols = p->protocols;
1062
1063 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]\n",
1064 conf->id, p->id, c->ictx && c->octx);
1065
1066 if (c->ictx && c->octx)
1067 {
1068 // send connect_info packets to both sides, in case one is
1069 // behind a nat firewall (or both ;)
1070 c->send_connect_info (conf->id, si, conf->protocols);
1071 send_connect_info (c->conf->id, c->si, c->conf->protocols);
1072 }
1073 else
1074 c->establish_connection ();
1075 }
1076
1077 break;
1078
1079 case vpn_packet::PT_CONNECT_INFO:
1080 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1081 {
1082 connect_info_packet *p = (connect_info_packet *) pkt;
1083
1084 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1085
1086 connection *c = vpn->conns[p->id - 1];
1087
1088 c->conf->protocols = p->protocols;
1089 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1090 p->si.upgrade_protocol (protocol, c->conf);
1091
1092 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
1093 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
1094
1095 const sockinfo &dsi = forward_si (p->si);
1096
1097 if (dsi.valid ())
1098 c->send_auth_request (dsi, true);
1099 }
1100
1101 break;
1102
1103 default:
1104 send_reset (rsi);
1105 break;
1106 }
1107 }
1108
1109 void connection::keepalive_cb (time_watcher &w)
1110 {
1111 if (NOW >= last_activity + ::conf.keepalive + 30)
1112 {
1113 reset_connection ();
1114 establish_connection ();
1115 }
1116 else if (NOW < last_activity + ::conf.keepalive)
1117 w.start (last_activity + ::conf.keepalive);
1118 else if (conf->connectmode != conf_node::C_ONDEMAND
1119 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1120 {
1121 send_ping (si);
1122 w.start (NOW + 5);
1123 }
1124 else if (NOW < last_activity + ::conf.keepalive + 10)
1125 // hold ondemand connections implicitly a few seconds longer
1126 // should delete octx, though, or something like that ;)
1127 w.start (last_activity + ::conf.keepalive + 10);
1128 else
1129 reset_connection ();
1130 }
1131
1132 void connection::send_connect_request (int id)
1133 {
1134 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols);
1135
1136 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id);
1137 p->hmac_set (octx);
1138 send_vpn_packet (p, si);
1139
1140 delete p;
1141 }
1142
1143 void connection::script_node ()
1144 {
1145 vpn->script_if_up ();
1146
1147 char *env;
1148 asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1149 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1150 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1151 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1152 }
1153
1154 const char *connection::script_node_up ()
1155 {
1156 script_node ();
1157
1158 putenv ("STATE=up");
1159
1160 return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1161 }
1162
1163 const char *connection::script_node_down ()
1164 {
1165 script_node ();
1166
1167 putenv ("STATE=down");
1168
1169 return ::conf.script_node_up ? ::conf.script_node_down : "node-down";
1170 }
1171
1172 connection::connection(struct vpn *vpn_)
1173 : vpn(vpn_)
1174 , rekey (this, &connection::rekey_cb)
1175 , keepalive (this, &connection::keepalive_cb)
1176 , establish_connection (this, &connection::establish_connection_cb)
1177 {
1178 octx = ictx = 0;
1179 retry_cnt = 0;
1180
1181 connectmode = conf_node::C_ALWAYS; // initial setting
1182 reset_connection ();
1183 }
1184
1185 connection::~connection ()
1186 {
1187 shutdown ();
1188 }
1189
1190 void connection_init ()
1191 {
1192 auth_rate_limiter.clear ();
1193 reset_rate_limiter.clear ();
1194 }
1195