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