ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.23
Committed: Wed Oct 22 00:42:53 2003 UTC (20 years, 7 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.22: +13 -10 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 connection.C -- manage a single connection
3 Copyright (C) 2003 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 <list>
27
28 #include <openssl/rand.h>
29 #include <openssl/evp.h>
30 #include <openssl/rsa.h>
31 #include <openssl/err.h>
32
33 #include "gettext.h"
34
35 #include "conf.h"
36 #include "slog.h"
37 #include "device.h"
38 #include "vpn.h"
39 #include "connection.h"
40
41 #include "netcompat.h"
42
43 #if !HAVE_RAND_PSEUDO_BYTES
44 # define RAND_pseudo_bytes RAND_bytes
45 #endif
46
47 #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
48
49 struct crypto_ctx
50 {
51 EVP_CIPHER_CTX cctx;
52 HMAC_CTX hctx;
53
54 crypto_ctx (const rsachallenge &challenge, int enc);
55 ~crypto_ctx ();
56 };
57
58 crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
59 {
60 EVP_CIPHER_CTX_init (&cctx);
61 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
62 HMAC_CTX_init (&hctx);
63 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
64 }
65
66 crypto_ctx::~crypto_ctx ()
67 {
68 EVP_CIPHER_CTX_cleanup (&cctx);
69 HMAC_CTX_cleanup (&hctx);
70 }
71
72 static void
73 rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h)
74 {
75 EVP_MD_CTX ctx;
76
77 EVP_MD_CTX_init (&ctx);
78 EVP_DigestInit (&ctx, RSA_HASH);
79 EVP_DigestUpdate(&ctx, &chg, sizeof chg);
80 EVP_DigestUpdate(&ctx, &id, sizeof id);
81 EVP_DigestFinal (&ctx, (unsigned char *)&h, 0);
82 EVP_MD_CTX_cleanup (&ctx);
83 }
84
85 struct rsa_entry {
86 tstamp expire;
87 rsaid id;
88 rsachallenge chg;
89 };
90
91 struct rsa_cache : list<rsa_entry>
92 {
93 void cleaner_cb (time_watcher &w); time_watcher cleaner;
94
95 bool find (const rsaid &id, rsachallenge &chg)
96 {
97 for (iterator i = begin (); i != end (); ++i)
98 {
99 if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW)
100 {
101 memcpy (&chg, &i->chg, sizeof chg);
102
103 erase (i);
104 return true;
105 }
106 }
107
108 if (cleaner.at < NOW)
109 cleaner.start (NOW + RSA_TTL);
110
111 return false;
112 }
113
114 void gen (rsaid &id, rsachallenge &chg)
115 {
116 rsa_entry e;
117
118 RAND_bytes ((unsigned char *)&id, sizeof id);
119 RAND_bytes ((unsigned char *)&chg, sizeof chg);
120
121 e.expire = NOW + RSA_TTL;
122 e.id = id;
123 memcpy (&e.chg, &chg, sizeof chg);
124
125 push_back (e);
126
127 if (cleaner.at < NOW)
128 cleaner.start (NOW + RSA_TTL);
129 }
130
131 rsa_cache ()
132 : cleaner (this, &rsa_cache::cleaner_cb)
133 { }
134
135 } rsa_cache;
136
137 void rsa_cache::cleaner_cb (time_watcher &w)
138 {
139 if (empty ())
140 w.at = TSTAMP_CANCEL;
141 else
142 {
143 w.at = 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 get patches 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.reset ();
604 rekey.reset ();
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
681 rsa_cache.gen (pkt->id, chg);
682
683 if (0 > RSA_public_encrypt (sizeof chg,
684 (unsigned char *)&chg, (unsigned char *)&pkt->encr,
685 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
686 fatal ("RSA_public_encrypt error");
687
688 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si);
689
690 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
691
692 delete pkt;
693 }
694
695 void
696 connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
697 {
698 auth_res_packet *pkt = new auth_res_packet (conf->id);
699
700 pkt->id = id;
701
702 rsa_hash (id, chg, pkt->response);
703
704 pkt->hmac_set (octx);
705
706 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
707
708 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
709
710 delete pkt;
711 }
712
713 void
714 connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
715 {
716 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n",
717 conf->id, rid, (const char *)rsi);
718
719 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
720
721 r->hmac_set (octx);
722 send_vpn_packet (r, si);
723
724 delete r;
725 }
726
727 void
728 connection::establish_connection_cb (time_watcher &w)
729 {
730 if (ictx || conf == THISNODE
731 || connectmode == conf_node::C_NEVER
732 || connectmode == conf_node::C_DISABLED)
733 w.at = TSTAMP_CANCEL;
734 else if (w.at <= NOW)
735 {
736 double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6;
737
738 if (retry_int < 3600 * 8)
739 retry_cnt++;
740
741 w.at = NOW + retry_int;
742
743 reset_si ();
744
745 if (si.prot && !si.host)
746 vpn->send_connect_request (conf->id);
747 else
748 {
749 const sockinfo &dsi = forward_si (si);
750
751 if (dsi.valid () && auth_rate_limiter.can (dsi))
752 {
753 if (retry_cnt < 4)
754 send_auth_request (dsi, true);
755 else
756 send_ping (dsi, 0);
757 }
758 }
759 }
760 }
761
762 void
763 connection::reset_connection ()
764 {
765 if (ictx && octx)
766 {
767 slog (L_INFO, _("%s(%s): connection lost"),
768 conf->nodename, (const char *)si);
769
770 if (::conf.script_node_down)
771 run_script (run_script_cb (this, &connection::script_node_down), false);
772 }
773
774 delete ictx; ictx = 0;
775 delete octx; octx = 0;
776
777 si.host= 0;
778
779 last_activity = 0;
780 retry_cnt = 0;
781
782 rekey.reset ();
783 keepalive.reset ();
784 establish_connection.reset ();
785 }
786
787 void
788 connection::shutdown ()
789 {
790 if (ictx && octx)
791 send_reset (si);
792
793 reset_connection ();
794 }
795
796 void
797 connection::rekey_cb (time_watcher &w)
798 {
799 w.at = TSTAMP_CANCEL;
800
801 reset_connection ();
802 establish_connection ();
803 }
804
805 void
806 connection::send_data_packet (tap_packet *pkt)
807 {
808 vpndata_packet *p = new vpndata_packet;
809 int tos = 0;
810
811 // I am not hilarious about peeking into packets, but so be it.
812 if (conf->inherit_tos && pkt->is_ipv4 ())
813 tos = (*pkt)[15] & IPTOS_TOS_MASK;
814
815 p->setup (this, conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
816 send_vpn_packet (p, si, tos);
817
818 delete p;
819
820 if (oseqno > MAX_SEQNO)
821 rekey ();
822 }
823
824 void
825 connection::inject_data_packet (tap_packet *pkt, bool broadcast/*TODO DDD*/)
826 {
827 if (ictx && octx)
828 send_data_packet (pkt);
829 else
830 {
831 if (!broadcast)//DDDD
832 data_queue.put (new tap_packet (*pkt));
833
834 establish_connection ();
835 }
836 }
837
838 void connection::inject_vpn_packet (vpn_packet *pkt, int tos)
839 {
840 if (ictx && octx)
841 send_vpn_packet (pkt, si, tos);
842 else
843 {
844 vpn_queue.put (new vpn_packet (*pkt));
845
846 establish_connection ();
847 }
848 }
849
850 void
851 connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
852 {
853 last_activity = NOW;
854
855 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
856 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
857
858 switch (pkt->typ ())
859 {
860 case vpn_packet::PT_PING:
861 // we send pings instead of auth packets after some retries,
862 // so reset the retry counter and establish a connection
863 // when we receive a ping.
864 if (!ictx)
865 {
866 if (auth_rate_limiter.can (rsi))
867 send_auth_request (rsi, true);
868 }
869 else
870 send_ping (rsi, 1); // pong
871
872 break;
873
874 case vpn_packet::PT_PONG:
875 break;
876
877 case vpn_packet::PT_RESET:
878 {
879 reset_connection ();
880
881 config_packet *p = (config_packet *) pkt;
882
883 if (!p->chk_config ())
884 {
885 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
886 conf->nodename, (const char *)rsi);
887 connectmode = conf_node::C_DISABLED;
888 }
889 else if (connectmode == conf_node::C_ALWAYS)
890 establish_connection ();
891 }
892 break;
893
894 case vpn_packet::PT_AUTH_REQ:
895 if (auth_rate_limiter.can (rsi))
896 {
897 auth_req_packet *p = (auth_req_packet *) pkt;
898
899 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
900
901 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
902 {
903 if (p->prot_minor != PROTOCOL_MINOR)
904 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
905 conf->nodename, (const char *)rsi,
906 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
907
908 if (p->initiate)
909 send_auth_request (rsi, false);
910
911 rsachallenge k;
912
913 if (0 > RSA_private_decrypt (sizeof (p->encr),
914 (unsigned char *)&p->encr, (unsigned char *)&k,
915 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
916 {
917 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"),
918 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0));
919 break;
920 }
921 else
922 {
923 delete octx;
924
925 octx = new crypto_ctx (k, 1);
926 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
927
928 conf->protocols = p->protocols;
929
930 send_auth_response (rsi, p->id, k);
931
932 connection_established ();
933
934 break;
935 }
936 }
937 else
938 slog (L_WARN, _("%s(%s): protocol mismatch"),
939 conf->nodename, (const char *)rsi);
940
941 send_reset (rsi);
942 }
943
944 break;
945
946 case vpn_packet::PT_AUTH_RES:
947 {
948 auth_res_packet *p = (auth_res_packet *) pkt;
949
950 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
951
952 if (p->chk_config ())
953 {
954 if (p->prot_minor != PROTOCOL_MINOR)
955 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
956 conf->nodename, (const char *)rsi,
957 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
958
959 rsachallenge chg;
960
961 if (!rsa_cache.find (p->id, chg))
962 {
963 slog (L_ERR, _("%s(%s): unrequested auth response ignored"),
964 conf->nodename, (const char *)rsi);
965 break;
966 }
967 else
968 {
969 crypto_ctx *cctx = new crypto_ctx (chg, 0);
970
971 if (!p->hmac_chk (cctx))
972 {
973 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
974 "could be an attack, or just corruption or an synchronization error"),
975 conf->nodename, (const char *)rsi);
976 break;
977 }
978 else
979 {
980 rsaresponse h;
981
982 rsa_hash (p->id, chg, h);
983
984 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
985 {
986 prot_minor = p->prot_minor;
987
988 delete ictx; ictx = cctx;
989
990 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
991
992 si = rsi;
993 protocol = rsi.prot;
994
995 connection_established ();
996
997 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
998 conf->nodename, (const char *)rsi,
999 p->prot_major, p->prot_minor);
1000
1001 if (::conf.script_node_up)
1002 run_script (run_script_cb (this, &connection::script_node_up), false);
1003
1004 break;
1005 }
1006 else
1007 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
1008 conf->nodename, (const char *)rsi);
1009 }
1010
1011 delete cctx;
1012 }
1013 }
1014 }
1015
1016 send_reset (rsi);
1017 break;
1018
1019 case vpn_packet::PT_DATA_COMPRESSED:
1020 #if !ENABLE_COMPRESSION
1021 send_reset (rsi);
1022 break;
1023 #endif
1024
1025 case vpn_packet::PT_DATA_UNCOMPRESSED:
1026
1027 if (ictx && octx)
1028 {
1029 vpndata_packet *p = (vpndata_packet *)pkt;
1030
1031 if (!p->hmac_chk (ictx))
1032 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
1033 "could be an attack, or just corruption or an synchronization error"),
1034 conf->nodename, (const char *)rsi);
1035 else
1036 {
1037 u32 seqno;
1038 tap_packet *d = p->unpack (this, seqno);
1039
1040 if (iseqno.recv_ok (seqno))
1041 {
1042 vpn->tap->send (d);
1043
1044 if (si != rsi)
1045 {
1046 // fast re-sync on connection changes, useful especially for tcp/ip
1047 si = rsi;
1048
1049 slog (L_INFO, _("%s(%s): socket address changed to %s"),
1050 conf->nodename, (const char *)si, (const char *)rsi);
1051 }
1052
1053 delete d;
1054
1055 break;
1056 }
1057 }
1058 }
1059
1060 send_reset (rsi);
1061 break;
1062
1063 case vpn_packet::PT_CONNECT_REQ:
1064 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1065 {
1066 connect_req_packet *p = (connect_req_packet *) pkt;
1067
1068 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1069 connection *c = vpn->conns[p->id - 1];
1070 conf->protocols = p->protocols;
1071
1072 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]\n",
1073 conf->id, p->id, c->ictx && c->octx);
1074
1075 if (c->ictx && c->octx)
1076 {
1077 // send connect_info packets to both sides, in case one is
1078 // behind a nat firewall (or both ;)
1079 c->send_connect_info (conf->id, si, conf->protocols);
1080 send_connect_info (c->conf->id, c->si, c->conf->protocols);
1081 }
1082 else
1083 c->establish_connection ();
1084 }
1085
1086 break;
1087
1088 case vpn_packet::PT_CONNECT_INFO:
1089 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1090 {
1091 connect_info_packet *p = (connect_info_packet *) pkt;
1092
1093 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1094
1095 connection *c = vpn->conns[p->id - 1];
1096
1097 c->conf->protocols = p->protocols;
1098 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1099 p->si.upgrade_protocol (protocol, c->conf);
1100
1101 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
1102 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
1103
1104 const sockinfo &dsi = forward_si (p->si);
1105
1106 if (dsi.valid ())
1107 c->send_auth_request (dsi, true);
1108 }
1109
1110 break;
1111
1112 default:
1113 send_reset (rsi);
1114 break;
1115 }
1116 }
1117
1118 void connection::keepalive_cb (time_watcher &w)
1119 {
1120 if (NOW >= last_activity + ::conf.keepalive + 30)
1121 {
1122 reset_connection ();
1123 establish_connection ();
1124 }
1125 else if (NOW < last_activity + ::conf.keepalive)
1126 w.at = last_activity + ::conf.keepalive;
1127 else if (conf->connectmode != conf_node::C_ONDEMAND
1128 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1129 {
1130 send_ping (si);
1131 w.at = NOW + 5;
1132 }
1133 else if (NOW < last_activity + ::conf.keepalive + 10)
1134 // hold ondemand connections implicitly a few seconds longer
1135 // should delete octx, though, or something like that ;)
1136 w.at = last_activity + ::conf.keepalive + 10;
1137 else
1138 reset_connection ();
1139 }
1140
1141 void connection::send_connect_request (int id)
1142 {
1143 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols);
1144
1145 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id);
1146 p->hmac_set (octx);
1147 send_vpn_packet (p, si);
1148
1149 delete p;
1150 }
1151
1152 void connection::script_node ()
1153 {
1154 vpn->script_if_up ();
1155
1156 char *env;
1157 asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1158 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1159 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1160 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1161 }
1162
1163 const char *connection::script_node_up ()
1164 {
1165 script_node ();
1166
1167 putenv ("STATE=up");
1168
1169 return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1170 }
1171
1172 const char *connection::script_node_down ()
1173 {
1174 script_node ();
1175
1176 putenv ("STATE=down");
1177
1178 return ::conf.script_node_up ? ::conf.script_node_down : "node-down";
1179 }
1180
1181 connection::connection(struct vpn *vpn_)
1182 : vpn(vpn_)
1183 , rekey (this, &connection::rekey_cb)
1184 , keepalive (this, &connection::keepalive_cb)
1185 , establish_connection (this, &connection::establish_connection_cb)
1186 {
1187 octx = ictx = 0;
1188 retry_cnt = 0;
1189
1190 connectmode = conf_node::C_ALWAYS; // initial setting
1191 reset_connection ();
1192 }
1193
1194 connection::~connection ()
1195 {
1196 shutdown ();
1197 }
1198
1199 void connection_init ()
1200 {
1201 auth_rate_limiter.clear ();
1202 reset_rate_limiter.clear ();
1203 }
1204