ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.24
Committed: Wed Oct 22 01:05:23 2003 UTC (20 years, 7 months ago) by pcg
Content type: text/plain
Branch: MAIN
CVS Tags: poll-based-iom
Changes since 1.23: +2 -9 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 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 || conf == THISNODE
726 || connectmode == conf_node::C_NEVER
727 || connectmode == conf_node::C_DISABLED)
728 w.at = TSTAMP_CANCEL;
729 else if (w.at <= NOW)
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.at = 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.reset ();
778 keepalive.reset ();
779 establish_connection.reset ();
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 w.at = TSTAMP_CANCEL;
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 (new vpn_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 an 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 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 (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.at = 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.at = 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.at = 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