ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.16
Committed: Mon Sep 1 15:52:03 2003 UTC (20 years, 8 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.15: +2 -2 lines
Log Message:
*** empty log message ***

File Contents

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