ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/protocol.C
Revision: 1.17
Committed: Wed Mar 26 01:58:46 2003 UTC (21 years, 2 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.16: +256 -249 lines
Log Message:
*** empty log message ***

File Contents

# Content
1 /*
2 protocol.C -- handle the protocol, encryption, handshaking etc.
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 #include <list>
22
23 #include <cstdlib>
24 #include <cstring>
25 #include <cstdio>
26
27 #include <sys/types.h>
28 #include <sys/socket.h>
29 #include <sys/poll.h>
30 #include <sys/wait.h>
31 #include <netinet/in.h>
32 #include <arpa/inet.h>
33 #include <errno.h>
34 #include <time.h>
35 #include <unistd.h>
36
37 #include <openssl/rand.h>
38 #include <openssl/hmac.h>
39 #include <openssl/evp.h>
40 #include <openssl/rsa.h>
41 #include <openssl/err.h>
42
43 extern "C" {
44 # include "lzf/lzf.h"
45 }
46
47 #include "gettext.h"
48 #include "pidfile.h"
49
50 #include "conf.h"
51 #include "slog.h"
52 #include "device.h"
53 #include "protocol.h"
54
55 #if !HAVE_RAND_PSEUDO_BYTES
56 # define RAND_pseudo_bytes RAND_bytes
57 #endif
58
59 static time_t next_timecheck;
60
61 #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
62
63 struct crypto_ctx
64 {
65 EVP_CIPHER_CTX cctx;
66 HMAC_CTX hctx;
67
68 crypto_ctx (const rsachallenge &challenge, int enc);
69 ~crypto_ctx ();
70 };
71
72 crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
73 {
74 EVP_CIPHER_CTX_init (&cctx);
75 EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
76 HMAC_CTX_init (&hctx);
77 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
78 }
79
80 crypto_ctx::~crypto_ctx ()
81 {
82 EVP_CIPHER_CTX_cleanup (&cctx);
83 HMAC_CTX_cleanup (&hctx);
84 }
85
86 static void
87 rsa_hash (const rsachallenge &chg, rsaresponse &h)
88 {
89 EVP_MD_CTX ctx;
90
91 EVP_MD_CTX_init (&ctx);
92 EVP_DigestInit (&ctx, RSA_HASH);
93 EVP_DigestUpdate(&ctx, &chg, sizeof chg);
94 EVP_DigestFinal (&ctx, (unsigned char *)&h, 0);
95 EVP_MD_CTX_cleanup (&ctx);
96 }
97
98 struct rsa_entry {
99 tstamp expire;
100 rsaid id;
101 rsachallenge chg;
102 };
103
104 struct rsa_cache : list<rsa_entry>
105 {
106 void cleaner_cb (tstamp &ts); time_watcher cleaner;
107
108 bool find (const rsaid &id, rsachallenge &chg)
109 {
110 for (iterator i = begin (); i != end (); ++i)
111 {
112 if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW)
113 {
114 memcpy (&chg, &i->chg, sizeof chg);
115
116 erase (i);
117 return true;
118 }
119 }
120
121 if (cleaner.at < NOW)
122 cleaner.start (NOW + RSA_TTL);
123
124 return false;
125 }
126
127 void gen (rsaid &id, rsachallenge &chg)
128 {
129 rsa_entry e;
130
131 RAND_bytes ((unsigned char *)&id, sizeof id);
132 RAND_bytes ((unsigned char *)&chg, sizeof chg);
133
134 e.expire = NOW + RSA_TTL;
135 e.id = id;
136 memcpy (&e.chg, &chg, sizeof chg);
137
138 push_back (e);
139
140 if (cleaner.at < NOW)
141 cleaner.start (NOW + RSA_TTL);
142 }
143
144 rsa_cache ()
145 : cleaner (this, &rsa_cache::cleaner_cb)
146 { }
147
148 } rsa_cache;
149
150 void rsa_cache::cleaner_cb (tstamp &ts)
151 {
152 if (empty ())
153 ts = TSTAMP_CANCEL;
154 else
155 {
156 ts = NOW + RSA_TTL;
157
158 for (iterator i = begin (); i != end (); )
159 if (i->expire <= NOW)
160 i = erase (i);
161 else
162 ++i;
163 }
164 }
165
166 typedef callback<const char *, int> run_script_cb;
167
168 // run a shell script (or actually an external program).
169 static void
170 run_script (const run_script_cb &cb, bool wait)
171 {
172 int pid;
173
174 if ((pid = fork ()) == 0)
175 {
176 char *filename;
177 asprintf (&filename, "%s/%s", confbase, cb(0));
178 execl (filename, filename, (char *) 0);
179 exit (255);
180 }
181 else if (pid > 0)
182 {
183 if (wait)
184 {
185 waitpid (pid, 0, 0);
186 /* TODO: check status */
187 }
188 }
189 }
190
191 //////////////////////////////////////////////////////////////////////////////
192
193 void pkt_queue::put (tap_packet *p)
194 {
195 if (queue[i])
196 {
197 delete queue[i];
198 j = (j + 1) % QUEUEDEPTH;
199 }
200
201 queue[i] = p;
202
203 i = (i + 1) % QUEUEDEPTH;
204 }
205
206 tap_packet *pkt_queue::get ()
207 {
208 tap_packet *p = queue[j];
209
210 if (p)
211 {
212 queue[j] = 0;
213 j = (j + 1) % QUEUEDEPTH;
214 }
215
216 return p;
217 }
218
219 pkt_queue::pkt_queue ()
220 {
221 memset (queue, 0, sizeof (queue));
222 i = 0;
223 j = 0;
224 }
225
226 pkt_queue::~pkt_queue ()
227 {
228 for (i = QUEUEDEPTH; --i > 0; )
229 delete queue[i];
230 }
231
232 struct net_rateinfo {
233 u32 host;
234 double pcnt, diff;
235 tstamp last;
236 };
237
238 // only do action once every x seconds per host whole allowing bursts.
239 // this implementation ("splay list" ;) is inefficient,
240 // but low on resources.
241 struct net_rate_limiter : private list<net_rateinfo>
242 {
243 static const double ALPHA = 1. - 1. / 90.; // allow bursts
244 static const double CUTOFF = 20.; // one event every CUTOFF seconds
245 static const double EXPIRE = CUTOFF * 30.; // expire entries after this time
246
247 bool can (u32 host);
248 bool can (SOCKADDR *sa) { return can((u32)sa->sin_addr.s_addr); }
249 bool can (sockinfo &si) { return can((u32)si.host); }
250 };
251
252 net_rate_limiter auth_rate_limiter, reset_rate_limiter;
253
254 bool net_rate_limiter::can (u32 host)
255 {
256 iterator i;
257
258 for (i = begin (); i != end (); )
259 if (i->host == host)
260 break;
261 else if (i->last < NOW - EXPIRE)
262 i = erase (i);
263 else
264 i++;
265
266 if (i == end ())
267 {
268 net_rateinfo ri;
269
270 ri.host = host;
271 ri.pcnt = 1.;
272 ri.diff = CUTOFF * (1. / (1. - ALPHA));
273 ri.last = NOW;
274
275 push_front (ri);
276
277 return true;
278 }
279 else
280 {
281 net_rateinfo ri (*i);
282 erase (i);
283
284 ri.pcnt = ri.pcnt * ALPHA;
285 ri.diff = ri.diff * ALPHA + (NOW - ri.last);
286
287 ri.last = NOW;
288
289 bool send = ri.diff / ri.pcnt > CUTOFF;
290
291 if (send)
292 ri.pcnt++;
293
294 //printf ("RATE %d %f,%f = %f > %f\n", !!send, ri.pcnt, ri.diff, ri.diff / ri.pcnt, CUTOFF);
295
296 push_front (ri);
297
298 return send;
299 }
300 }
301
302 /////////////////////////////////////////////////////////////////////////////
303
304 static void next_wakeup (time_t next)
305 {
306 if (next_timecheck > next)
307 next_timecheck = next;
308 }
309
310 static unsigned char hmac_digest[EVP_MAX_MD_SIZE];
311
312 struct hmac_packet:net_packet
313 {
314 u8 hmac[HMACLENGTH]; // each and every packet has a hmac field, but that is not (yet) checked everywhere
315
316 void hmac_set (crypto_ctx * ctx);
317 bool hmac_chk (crypto_ctx * ctx);
318
319 private:
320 void hmac_gen (crypto_ctx * ctx)
321 {
322 unsigned int xlen;
323 HMAC_CTX *hctx = &ctx->hctx;
324
325 HMAC_Init_ex (hctx, 0, 0, 0, 0);
326 HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet),
327 len - sizeof (hmac_packet));
328 HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen);
329 }
330 };
331
332 void
333 hmac_packet::hmac_set (crypto_ctx * ctx)
334 {
335 hmac_gen (ctx);
336
337 memcpy (hmac, hmac_digest, HMACLENGTH);
338 }
339
340 bool
341 hmac_packet::hmac_chk (crypto_ctx * ctx)
342 {
343 hmac_gen (ctx);
344
345 return !memcmp (hmac, hmac_digest, HMACLENGTH);
346 }
347
348 struct vpn_packet : hmac_packet
349 {
350 enum ptype
351 {
352 PT_RESET = 0,
353 PT_DATA_UNCOMPRESSED,
354 PT_DATA_COMPRESSED,
355 PT_PING, PT_PONG, // wasting namespace space? ;)
356 PT_AUTH_REQ, // authentification request
357 PT_AUTH_RES, // authentification response
358 PT_CONNECT_REQ, // want other host to contact me
359 PT_CONNECT_INFO, // request connection to some node
360 PT_MAX
361 };
362
363 u8 type;
364 u8 srcdst, src1, dst1;
365
366 void set_hdr (ptype type, unsigned int dst);
367
368 unsigned int src ()
369 {
370 return src1 | ((srcdst >> 4) << 8);
371 }
372
373 unsigned int dst ()
374 {
375 return dst1 | ((srcdst & 0xf) << 8);
376 }
377
378 ptype typ ()
379 {
380 return (ptype) type;
381 }
382 };
383
384 void vpn_packet::set_hdr (ptype type, unsigned int dst)
385 {
386 this->type = type;
387
388 int src = THISNODE->id;
389
390 src1 = src;
391 srcdst = ((src >> 8) << 4) | (dst >> 8);
392 dst1 = dst;
393 }
394
395 #define MAXVPNDATA (MAX_MTU - 6 - 6)
396 #define DATAHDR (sizeof (u32) + RAND_SIZE)
397
398 struct vpndata_packet:vpn_packet
399 {
400 u8 data[MAXVPNDATA + DATAHDR]; // seqno
401
402 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
403 tap_packet *unpack (connection *conn, u32 &seqno);
404 private:
405
406 const u32 data_hdr_size () const
407 {
408 return sizeof (vpndata_packet) - sizeof (net_packet) - MAXVPNDATA - DATAHDR;
409 }
410 };
411
412 void
413 vpndata_packet::setup (connection *conn, int dst, u8 *d, u32 l, u32 seqno)
414 {
415 EVP_CIPHER_CTX *cctx = &conn->octx->cctx;
416 int outl = 0, outl2;
417 ptype type = PT_DATA_UNCOMPRESSED;
418
419 #if ENABLE_COMPRESSION
420 u8 cdata[MAX_MTU];
421 u32 cl;
422
423 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
424 if (cl)
425 {
426 type = PT_DATA_COMPRESSED;
427 d = cdata;
428 l = cl + 2;
429
430 d[0] = cl >> 8;
431 d[1] = cl;
432 }
433 #endif
434
435 EVP_EncryptInit_ex (cctx, 0, 0, 0, 0);
436
437 struct {
438 #if RAND_SIZE
439 u8 rnd[RAND_SIZE];
440 #endif
441 u32 seqno;
442 } datahdr;
443
444 datahdr.seqno = ntohl (seqno);
445 #if RAND_SIZE
446 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
447 #endif
448
449 EVP_EncryptUpdate (cctx,
450 (unsigned char *) data + outl, &outl2,
451 (unsigned char *) &datahdr, DATAHDR);
452 outl += outl2;
453
454 EVP_EncryptUpdate (cctx,
455 (unsigned char *) data + outl, &outl2,
456 (unsigned char *) d, l);
457 outl += outl2;
458
459 EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2);
460 outl += outl2;
461
462 len = outl + data_hdr_size ();
463
464 set_hdr (type, dst);
465
466 hmac_set (conn->octx);
467 }
468
469 tap_packet *
470 vpndata_packet::unpack (connection *conn, u32 &seqno)
471 {
472 EVP_CIPHER_CTX *cctx = &conn->ictx->cctx;
473 int outl = 0, outl2;
474 tap_packet *p = new tap_packet;
475 u8 *d;
476 u32 l = len - data_hdr_size ();
477
478 EVP_DecryptInit_ex (cctx, 0, 0, 0, 0);
479
480 #if ENABLE_COMPRESSION
481 u8 cdata[MAX_MTU];
482
483 if (type == PT_DATA_COMPRESSED)
484 d = cdata;
485 else
486 #endif
487 d = &(*p)[6 + 6 - DATAHDR];
488
489 /* this overwrites part of the src mac, but we fix that later */
490 EVP_DecryptUpdate (cctx,
491 d, &outl2,
492 (unsigned char *)&data, len - data_hdr_size ());
493 outl += outl2;
494
495 EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2);
496 outl += outl2;
497
498 seqno = ntohl (*(u32 *)(d + RAND_SIZE));
499
500 id2mac (dst () ? dst() : THISNODE->id, p->dst);
501 id2mac (src (), p->src);
502
503 #if ENABLE_COMPRESSION
504 if (type == PT_DATA_COMPRESSED)
505 {
506 u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
507 p->len = lzf_decompress (d + DATAHDR + 2, cl, &(*p)[6 + 6], MAX_MTU) + 6 + 6;
508 }
509 else
510 p->len = outl + (6 + 6 - DATAHDR);
511 #endif
512
513 return p;
514 }
515
516 struct ping_packet : vpn_packet
517 {
518 void setup (int dst, ptype type)
519 {
520 set_hdr (type, dst);
521 len = sizeof (*this) - sizeof (net_packet);
522 }
523 };
524
525 struct config_packet : vpn_packet
526 {
527 // actually, hmaclen cannot be checked because the hmac
528 // field comes before this data, so peers with other
529 // hmacs simply will not work.
530 u8 prot_major, prot_minor, randsize, hmaclen;
531 u8 flags, challengelen, pad2, pad3;
532 u32 cipher_nid, digest_nid, hmac_nid;
533
534 const u8 curflags () const
535 {
536 return 0x80
537 | (ENABLE_COMPRESSION ? 0x01 : 0x00);
538 }
539
540 void setup (ptype type, int dst)
541 {
542 prot_major = PROTOCOL_MAJOR;
543 prot_minor = PROTOCOL_MINOR;
544 randsize = RAND_SIZE;
545 hmaclen = HMACLENGTH;
546 flags = curflags ();
547 challengelen = sizeof (rsachallenge);
548
549 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
550 digest_nid = htonl (EVP_MD_type (RSA_HASH));
551 hmac_nid = htonl (EVP_MD_type (DIGEST));
552
553 len = sizeof (*this) - sizeof (net_packet);
554 set_hdr (type, dst);
555 }
556
557 bool chk_config ()
558 {
559 return prot_major == PROTOCOL_MAJOR
560 && randsize == RAND_SIZE
561 && hmaclen == HMACLENGTH
562 && flags == curflags ()
563 && challengelen == sizeof (rsachallenge)
564 && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
565 && digest_nid == htonl (EVP_MD_type (RSA_HASH))
566 && hmac_nid == htonl (EVP_MD_type (DIGEST));
567 }
568 };
569
570 struct auth_req_packet : config_packet
571 {
572 char magic[8];
573 u8 initiate; // false if this is just an automatic reply
574 u8 pad1, pad2, pad3;
575 rsaid id;
576 rsaencrdata encr;
577
578 auth_req_packet (int dst, bool initiate_)
579 {
580 config_packet::setup (PT_AUTH_REQ, dst);
581 initiate = !!initiate_;
582 strncpy (magic, MAGIC, 8);
583 len = sizeof (*this) - sizeof (net_packet);
584 }
585 };
586
587 struct auth_res_packet : config_packet
588 {
589 rsaid id;
590 rsaresponse response;
591
592 auth_res_packet (int dst)
593 {
594 config_packet::setup (PT_AUTH_RES, dst);
595 len = sizeof (*this) - sizeof (net_packet);
596 }
597 };
598
599 struct connect_req_packet : vpn_packet
600 {
601 u8 id;
602 u8 pad1, pad2, pad3;
603
604 connect_req_packet (int dst, int id_)
605 {
606 id = id_;
607 set_hdr (PT_CONNECT_REQ, dst);
608 len = sizeof (*this) - sizeof (net_packet);
609 }
610 };
611
612 struct connect_info_packet : vpn_packet
613 {
614 u8 id;
615 u8 pad1, pad2, pad3;
616 sockinfo si;
617
618 connect_info_packet (int dst, int id_, sockinfo &si_)
619 {
620 id = id_;
621 si = si_;
622 set_hdr (PT_CONNECT_INFO, dst);
623 len = sizeof (*this) - sizeof (net_packet);
624 }
625 };
626
627 /////////////////////////////////////////////////////////////////////////////
628
629 void
630 fill_sa (SOCKADDR *sa, conf_node *conf)
631 {
632 sa->sin_family = AF_INET;
633 sa->sin_port = htons (conf->port);
634 sa->sin_addr.s_addr = 0;
635
636 if (conf->hostname)
637 {
638 struct hostent *he = gethostbyname (conf->hostname);
639
640 if (he
641 && he->h_addrtype == AF_INET && he->h_length == 4 && he->h_addr_list[0])
642 {
643 //sa->sin_family = he->h_addrtype;
644 memcpy (&sa->sin_addr, he->h_addr_list[0], 4);
645 }
646 else
647 slog (L_NOTICE, _("unable to resolve host '%s'"), conf->hostname);
648 }
649 }
650
651 void
652 connection::reset_dstaddr ()
653 {
654 fill_sa (&sa, conf);
655 }
656
657 void
658 connection::send_ping (SOCKADDR *dsa, u8 pong)
659 {
660 ping_packet *pkt = new ping_packet;
661
662 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
663 vpn->send_vpn_packet (pkt, dsa, IPTOS_LOWDELAY);
664
665 delete pkt;
666 }
667
668 void
669 connection::send_reset (SOCKADDR *dsa)
670 {
671 if (reset_rate_limiter.can (dsa) && connectmode != conf_node::C_DISABLED)
672 {
673 config_packet *pkt = new config_packet;
674
675 pkt->setup (vpn_packet::PT_RESET, conf->id);
676 vpn->send_vpn_packet (pkt, dsa, IPTOS_MINCOST);
677
678 delete pkt;
679 }
680 }
681
682 void
683 connection::send_auth_request (SOCKADDR *sa, bool initiate)
684 {
685 if (auth_rate_limiter.can (sa))
686 {
687 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate);
688
689 rsachallenge chg;
690
691 rsa_cache.gen (pkt->id, chg);
692
693 if (0 > RSA_public_encrypt (sizeof chg,
694 (unsigned char *)&chg, (unsigned char *)&pkt->encr,
695 conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
696 fatal ("RSA_public_encrypt error");
697
698 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)sockinfo (sa));
699
700 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
701
702 delete pkt;
703 }
704 }
705
706 void
707 connection::send_auth_response (SOCKADDR *sa, const rsaid &id, const rsachallenge &chg)
708 {
709 if (auth_rate_limiter.can (sa))
710 {
711 auth_res_packet *pkt = new auth_res_packet (conf->id);
712
713 pkt->id = id;
714 rsa_hash (chg, pkt->response);
715
716 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)sockinfo (sa));
717
718 vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly
719
720 delete pkt;
721 }
722 }
723
724 void
725 connection::establish_connection_cb (tstamp &ts)
726 {
727 if (ictx || conf == THISNODE || connectmode == conf_node::C_NEVER)
728 ts = TSTAMP_CANCEL;
729 else if (ts <= 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 ts = NOW + retry_int;
737
738 if (conf->hostname)
739 {
740 reset_dstaddr ();
741 if (sa.sin_addr.s_addr)
742 if (retry_cnt < 4)
743 send_auth_request (&sa, true);
744 else if (auth_rate_limiter.can (&sa))
745 send_ping (&sa, 0);
746 }
747 else
748 vpn->connect_request (conf->id);
749 }
750 }
751
752 void
753 connection::reset_connection ()
754 {
755 if (ictx && octx)
756 {
757 slog (L_INFO, _("connection to %d (%s) lost"), conf->id, conf->nodename);
758
759 if (::conf.script_node_down)
760 run_script (run_script_cb (this, &connection::script_node_down), false);
761 }
762
763 delete ictx; ictx = 0;
764 delete octx; octx = 0;
765
766 sa.sin_port = 0;
767 sa.sin_addr.s_addr = 0;
768
769 last_activity = 0;
770
771 rekey.reset ();
772 keepalive.reset ();
773 establish_connection.reset ();
774 }
775
776 void
777 connection::shutdown ()
778 {
779 if (ictx && octx)
780 send_reset (&sa);
781
782 reset_connection ();
783 }
784
785 void
786 connection::rekey_cb (tstamp &ts)
787 {
788 ts = TSTAMP_CANCEL;
789
790 reset_connection ();
791 establish_connection ();
792 }
793
794 void
795 connection::send_data_packet (tap_packet * pkt, bool broadcast)
796 {
797 vpndata_packet *p = new vpndata_packet;
798 int tos = 0;
799
800 if (conf->inherit_tos
801 && (*pkt)[12] == 0x08 && (*pkt)[13] == 0x00 // IP
802 && ((*pkt)[14] & 0xf0) == 0x40) // IPv4
803 tos = (*pkt)[15] & IPTOS_TOS_MASK;
804
805 p->setup (this, broadcast ? 0 : conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
806 vpn->send_vpn_packet (p, &sa, tos);
807
808 delete p;
809
810 if (oseqno > MAX_SEQNO)
811 rekey ();
812 }
813
814 void
815 connection::inject_data_packet (tap_packet *pkt, bool broadcast)
816 {
817 if (ictx && octx)
818 send_data_packet (pkt, broadcast);
819 else
820 {
821 if (!broadcast)//DDDD
822 queue.put (new tap_packet (*pkt));
823
824 establish_connection ();
825 }
826 }
827
828 void
829 connection::recv_vpn_packet (vpn_packet *pkt, SOCKADDR *ssa)
830 {
831 last_activity = NOW;
832
833 slog (L_NOISE, "<<%d received packet type %d from %d to %d",
834 conf->id, pkt->typ (), pkt->src (), pkt->dst ());
835
836 switch (pkt->typ ())
837 {
838 case vpn_packet::PT_PING:
839 // we send pings instead of auth packets after some retries,
840 // so reset the retry counter and establish a conenction
841 // when we receive a pong.
842 if (!ictx && !octx)
843 {
844 retry_cnt = 0;
845 establish_connection.at = 0;
846 establish_connection ();
847 }
848 else
849 send_ping (ssa, 1); // pong
850
851 break;
852
853 case vpn_packet::PT_PONG:
854 break;
855
856 case vpn_packet::PT_RESET:
857 {
858 reset_connection ();
859
860 config_packet *p = (config_packet *) pkt;
861
862 if (!p->chk_config ())
863 {
864 slog (L_WARN, _("protocol mismatch, disabling node '%s'"), conf->nodename);
865 connectmode = conf_node::C_DISABLED;
866 }
867 else if (connectmode == conf_node::C_ALWAYS)
868 establish_connection ();
869 }
870 break;
871
872 case vpn_packet::PT_AUTH_REQ:
873 {
874 auth_req_packet *p = (auth_req_packet *) pkt;
875
876 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
877
878 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
879 {
880 if (p->prot_minor != PROTOCOL_MINOR)
881 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."),
882 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
883
884 if (p->initiate)
885 send_auth_request (ssa, false);
886
887 rsachallenge k;
888
889 if (0 > RSA_private_decrypt (sizeof (p->encr),
890 (unsigned char *)&p->encr, (unsigned char *)&k,
891 ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
892 slog (L_ERR, _("challenge from %s (%s) illegal or corrupted"),
893 conf->nodename, (const char *)sockinfo (ssa));
894 else
895 {
896 retry_cnt = 0;
897 establish_connection.set (NOW + 8); //? ;)
898 keepalive.reset ();
899 rekey.reset ();
900
901 delete ictx;
902 ictx = 0;
903
904 delete octx;
905
906 octx = new crypto_ctx (k, 1);
907 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
908
909 send_auth_response (ssa, p->id, k);
910
911 break;
912 }
913 }
914
915
916 }
917
918 send_reset (ssa);
919 break;
920
921 case vpn_packet::PT_AUTH_RES:
922 {
923 auth_res_packet *p = (auth_res_packet *) pkt;
924
925 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
926
927 if (p->chk_config ())
928 {
929 if (p->prot_minor != PROTOCOL_MINOR)
930 slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."),
931 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
932
933 rsachallenge chg;
934
935 if (!rsa_cache.find (p->id, chg))
936 slog (L_ERR, _("unrequested auth response from %s (%s)"),
937 conf->nodename, (const char *)sockinfo (ssa));
938 else
939 {
940 rsaresponse h;
941
942 rsa_hash (chg, h);
943
944 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
945 {
946 delete ictx;
947
948 ictx = new crypto_ctx (chg, 0);
949 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
950
951 sa = *ssa;
952
953 rekey.set (NOW + ::conf.rekey);
954 keepalive.set (NOW + ::conf.keepalive);
955
956 // send queued packets
957 while (tap_packet *p = queue.get ())
958 {
959 send_data_packet (p);
960 delete p;
961 }
962
963 connectmode = conf->connectmode;
964
965 slog (L_INFO, _("connection to %d (%s %s) established"),
966 conf->id, conf->nodename, (const char *)sockinfo (ssa));
967
968 if (::conf.script_node_up)
969 run_script (run_script_cb (this, &connection::script_node_up), false);
970
971 break;
972 }
973 else
974 slog (L_ERR, _("sent and received challenge do not match with (%s %s))"),
975 conf->nodename, (const char *)sockinfo (ssa));
976 }
977 }
978 }
979
980 send_reset (ssa);
981 break;
982
983 case vpn_packet::PT_DATA_COMPRESSED:
984 #if !ENABLE_COMPRESSION
985 send_reset (ssa);
986 break;
987 #endif
988
989 case vpn_packet::PT_DATA_UNCOMPRESSED:
990
991 if (ictx && octx)
992 {
993 vpndata_packet *p = (vpndata_packet *)pkt;
994
995 if (*ssa == sa)
996 {
997 if (!p->hmac_chk (ictx))
998 slog (L_ERR, _("hmac authentication error, received invalid packet\n"
999 "could be an attack, or just corruption or an synchronization error"));
1000 else
1001 {
1002 u32 seqno;
1003 tap_packet *d = p->unpack (this, seqno);
1004
1005 if (iseqno.recv_ok (seqno))
1006 {
1007 vpn->tap->send (d);
1008
1009 if (p->dst () == 0) // re-broadcast
1010 for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i)
1011 {
1012 connection *c = *i;
1013
1014 if (c->conf != THISNODE && c->conf != conf)
1015 c->inject_data_packet (d);
1016 }
1017
1018 delete d;
1019
1020 break;
1021 }
1022 }
1023 }
1024 else
1025 slog (L_ERR, _("received data packet from unknown source %s"), (const char *)sockinfo (ssa));//D
1026 }
1027
1028 send_reset (ssa);
1029 break;
1030
1031 case vpn_packet::PT_CONNECT_REQ:
1032 if (ictx && octx && *ssa == sa && pkt->hmac_chk (ictx))
1033 {
1034 connect_req_packet *p = (connect_req_packet *) pkt;
1035
1036 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1037
1038 connection *c = vpn->conns[p->id - 1];
1039
1040 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]\n",
1041 conf->id, p->id, c->ictx && c->octx);
1042
1043 if (c->ictx && c->octx)
1044 {
1045 // send connect_info packets to both sides, in case one is
1046 // behind a nat firewall (or both ;)
1047 {
1048 sockinfo si(sa);
1049
1050 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n",
1051 c->conf->id, conf->id, (const char *)si);
1052
1053 connect_info_packet *r = new connect_info_packet (c->conf->id, conf->id, si);
1054
1055 r->hmac_set (c->octx);
1056 vpn->send_vpn_packet (r, &c->sa);
1057
1058 delete r;
1059 }
1060
1061 {
1062 sockinfo si(c->sa);
1063
1064 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n",
1065 conf->id, c->conf->id, (const char *)si);
1066
1067 connect_info_packet *r = new connect_info_packet (conf->id, c->conf->id, si);
1068
1069 r->hmac_set (octx);
1070 vpn->send_vpn_packet (r, &sa);
1071
1072 delete r;
1073 }
1074 }
1075 }
1076
1077 break;
1078
1079 case vpn_packet::PT_CONNECT_INFO:
1080 if (ictx && octx && *ssa == sa && pkt->hmac_chk (ictx))
1081 {
1082 connect_info_packet *p = (connect_info_packet *) pkt;
1083
1084 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1085
1086 connection *c = vpn->conns[p->id - 1];
1087
1088 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
1089 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
1090
1091 c->send_auth_request (p->si.sa (), true);
1092 }
1093
1094 break;
1095
1096 default:
1097 send_reset (ssa);
1098 break;
1099
1100 }
1101 }
1102
1103 void connection::keepalive_cb (tstamp &ts)
1104 {
1105 if (NOW >= last_activity + ::conf.keepalive + 30)
1106 {
1107 reset_connection ();
1108 establish_connection ();
1109 }
1110 else if (NOW < last_activity + ::conf.keepalive)
1111 ts = last_activity + ::conf.keepalive;
1112 else if (conf->connectmode != conf_node::C_ONDEMAND
1113 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1114 {
1115 send_ping (&sa);
1116 ts = NOW + 5;
1117 }
1118 else
1119 reset_connection ();
1120
1121 }
1122
1123 void connection::connect_request (int id)
1124 {
1125 connect_req_packet *p = new connect_req_packet (conf->id, id);
1126
1127 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", id, conf->id);
1128 p->hmac_set (octx);
1129 vpn->send_vpn_packet (p, &sa);
1130
1131 delete p;
1132 }
1133
1134 void connection::script_node ()
1135 {
1136 vpn->script_if_up (0);
1137
1138 char *env;
1139 asprintf (&env, "DESTID=%d", conf->id);
1140 putenv (env);
1141 asprintf (&env, "DESTNODE=%s", conf->nodename);
1142 putenv (env);
1143 asprintf (&env, "DESTIP=%s", inet_ntoa (sa.sin_addr));
1144 putenv (env);
1145 asprintf (&env, "DESTPORT=%d", ntohs (sa.sin_port));
1146 putenv (env);
1147 }
1148
1149 const char *connection::script_node_up (int)
1150 {
1151 script_node ();
1152
1153 putenv ("STATE=up");
1154
1155 return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1156 }
1157
1158 const char *connection::script_node_down (int)
1159 {
1160 script_node ();
1161
1162 putenv ("STATE=down");
1163
1164 return ::conf.script_node_up ? ::conf.script_node_down : "node-down";
1165 }
1166
1167 connection::connection(struct vpn *vpn_)
1168 : vpn(vpn_)
1169 , rekey (this, &connection::rekey_cb)
1170 , keepalive (this, &connection::keepalive_cb)
1171 , establish_connection (this, &connection::establish_connection_cb)
1172 {
1173 octx = ictx = 0;
1174 retry_cnt = 0;
1175
1176 connectmode = conf_node::C_ALWAYS; // initial setting
1177 reset_connection ();
1178 }
1179
1180 connection::~connection ()
1181 {
1182 shutdown ();
1183 }
1184
1185 /////////////////////////////////////////////////////////////////////////////
1186
1187 const char *vpn::script_if_up (int)
1188 {
1189 // the tunnel device mtu should be the physical mtu - overhead
1190 // the tricky part is rounding to the cipher key blocksize
1191 int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - MAX_OVERHEAD;
1192 mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion
1193 mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round
1194 mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again
1195
1196 char *env;
1197 asprintf (&env, "CONFBASE=%s", confbase);
1198 putenv (env);
1199 asprintf (&env, "NODENAME=%s", THISNODE->nodename);
1200 putenv (env);
1201 asprintf (&env, "NODEID=%d", THISNODE->id);
1202 putenv (env);
1203 asprintf (&env, "IFNAME=%s", tap->interface ());
1204 putenv (env);
1205 asprintf (&env, "MTU=%d", mtu);
1206 putenv (env);
1207 asprintf (&env, "MAC=%02x:%02x:%02x:%02x:%02x:%02x",
1208 0xfe, 0xfd, 0x80, 0x00, THISNODE->id >> 8,
1209 THISNODE->id & 0xff);
1210 putenv (env);
1211
1212 return ::conf.script_if_up ? ::conf.script_if_up : "if-up";
1213 }
1214
1215 int
1216 vpn::setup (void)
1217 {
1218 struct sockaddr_in sa;
1219
1220 socket_fd = socket (PF_INET, SOCK_DGRAM, IPPROTO_UDP);
1221 if (socket_fd < 0)
1222 return -1;
1223
1224 fill_sa (&sa, THISNODE);
1225
1226 if (bind (socket_fd, (sockaddr *)&sa, sizeof (sa)))
1227 {
1228 slog (L_ERR, _("can't bind to %s: %s"), (const char *)sockinfo(sa), strerror (errno));
1229 exit (1);
1230 }
1231
1232 #ifdef IP_MTU_DISCOVER
1233 // this I really consider a linux bug. I am neither connected
1234 // nor do I fragment myself. Linux still sets DF and doesn't
1235 // fragment for me sometimes.
1236 {
1237 int oval = IP_PMTUDISC_DONT;
1238 setsockopt (socket_fd, SOL_IP, IP_MTU_DISCOVER, &oval, sizeof oval);
1239 }
1240 #endif
1241 {
1242 int oval = 1;
1243 setsockopt (socket_fd, SOL_SOCKET, SO_REUSEADDR, &oval, sizeof oval);
1244 }
1245
1246 udp_ev_watcher.start (socket_fd, POLLIN);
1247
1248 tap = new tap_device ();
1249 if (!tap) //D this, of course, never catches
1250 {
1251 slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname);
1252 exit (1);
1253 }
1254
1255 run_script (run_script_cb (this, &vpn::script_if_up), true);
1256
1257 vpn_ev_watcher.start (tap->fd, POLLIN);
1258
1259 reconnect_all ();
1260
1261 return 0;
1262 }
1263
1264 void
1265 vpn::send_vpn_packet (vpn_packet *pkt, SOCKADDR *sa, int tos)
1266 {
1267 setsockopt (socket_fd, SOL_IP, IP_TOS, &tos, sizeof tos);
1268 sendto (socket_fd, &((*pkt)[0]), pkt->len, 0, (sockaddr *)sa, sizeof (*sa));
1269 }
1270
1271 void
1272 vpn::shutdown_all ()
1273 {
1274 for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c)
1275 (*c)->shutdown ();
1276 }
1277
1278 void
1279 vpn::reconnect_all ()
1280 {
1281 for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c)
1282 delete *c;
1283
1284 conns.clear ();
1285
1286 for (configuration::node_vector::iterator i = conf.nodes.begin ();
1287 i != conf.nodes.end (); ++i)
1288 {
1289 connection *conn = new connection (this);
1290
1291 conn->conf = *i;
1292 conns.push_back (conn);
1293
1294 conn->establish_connection ();
1295 }
1296 }
1297
1298 connection *vpn::find_router ()
1299 {
1300 u32 prio = 0;
1301 connection *router = 0;
1302
1303 for (conns_vector::iterator i = conns.begin (); i != conns.end (); ++i)
1304 {
1305 connection *c = *i;
1306
1307 if (c->conf->routerprio > prio
1308 && c->connectmode == conf_node::C_ALWAYS
1309 && c->conf != THISNODE
1310 && c->ictx && c->octx)
1311 {
1312 prio = c->conf->routerprio;
1313 router = c;
1314 }
1315 }
1316
1317 return router;
1318 }
1319
1320 void vpn::connect_request (int id)
1321 {
1322 connection *c = find_router ();
1323
1324 if (c)
1325 c->connect_request (id);
1326 //else // does not work, because all others must connect to the same router
1327 // // no router found, aggressively connect to all routers
1328 // for (conns_vector::iterator i = conns.begin (); i != conns.end (); ++i)
1329 // if ((*i)->conf->routerprio)
1330 // (*i)->establish_connection ();
1331 }
1332
1333 void
1334 vpn::udp_ev (short revents)
1335 {
1336 if (revents & (POLLIN | POLLERR))
1337 {
1338 vpn_packet *pkt = new vpn_packet;
1339 struct sockaddr_in sa;
1340 socklen_t sa_len = sizeof (sa);
1341 int len;
1342
1343 len = recvfrom (socket_fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len);
1344
1345 if (len > 0)
1346 {
1347 pkt->len = len;
1348
1349 unsigned int src = pkt->src ();
1350 unsigned int dst = pkt->dst ();
1351
1352 slog (L_NOISE, _("<<?/%s received possible vpn packet type %d from %d to %d, length %d"),
1353 (const char *)sockinfo (sa), pkt->typ (), pkt->src (), pkt->dst (), pkt->len);
1354
1355 if (dst > conns.size () || pkt->typ () >= vpn_packet::PT_MAX)
1356 slog (L_WARN, _("<<? received CORRUPTED packet type %d from %d to %d"),
1357 pkt->typ (), pkt->src (), pkt->dst ());
1358 else if (dst == 0 && !THISNODE->routerprio)
1359 slog (L_WARN, _("<<%d received broadcast, but we are no router"), dst);
1360 else if (dst != 0 && dst != THISNODE->id)
1361 slog (L_WARN,
1362 _("received frame for node %d ('%s') from %s, but this is node %d ('%s')"),
1363 dst, conns[dst - 1]->conf->nodename,
1364 (const char *)sockinfo (sa),
1365 THISNODE->id, THISNODE->nodename);
1366 else if (src == 0 || src > conns.size ())
1367 slog (L_WARN, _("received frame from unknown node %d (%s)"), src, (const char *)sockinfo (sa));
1368 else
1369 conns[src - 1]->recv_vpn_packet (pkt, &sa);
1370 }
1371 else
1372 {
1373 // probably ECONNRESET or somesuch
1374 slog (L_DEBUG, _("%s: %s"), (const char *)sockinfo(sa), strerror (errno));
1375 }
1376
1377 delete pkt;
1378 }
1379 else if (revents & POLLHUP)
1380 {
1381 // this cannot ;) happen on udp sockets
1382 slog (L_ERR, _("FATAL: POLLHUP on socket fd, terminating."));
1383 exit (1);
1384 }
1385 else
1386 {
1387 slog (L_ERR,
1388 _("FATAL: unknown revents %08x in socket, terminating\n"),
1389 revents);
1390 exit (1);
1391 }
1392 }
1393
1394 void
1395 vpn::vpn_ev (short revents)
1396 {
1397 if (revents & POLLIN)
1398 {
1399 /* process data */
1400 tap_packet *pkt;
1401
1402 pkt = tap->recv ();
1403
1404 int dst = mac2id (pkt->dst);
1405 int src = mac2id (pkt->src);
1406
1407 if (src != THISNODE->id)
1408 {
1409 slog (L_ERR, _("FATAL: tap packet not originating on current node received, terminating."));
1410 exit (1);
1411 }
1412
1413 if (dst == THISNODE->id)
1414 {
1415 slog (L_ERR, _("FATAL: tap packet destined for current node received, terminating."));
1416 exit (1);
1417 }
1418
1419 if (dst > conns.size ())
1420 slog (L_ERR, _("tap packet for unknown node %d received, ignoring."), dst);
1421 else
1422 {
1423 if (dst)
1424 {
1425 // unicast
1426 if (dst != THISNODE->id)
1427 conns[dst - 1]->inject_data_packet (pkt);
1428 }
1429 else
1430 {
1431 // broadcast, first check router, then self, then english
1432 connection *router = find_router ();
1433
1434 if (router)
1435 router->inject_data_packet (pkt, true);
1436 else
1437 for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c)
1438 if ((*c)->conf != THISNODE)
1439 (*c)->inject_data_packet (pkt);
1440 }
1441 }
1442
1443 delete pkt;
1444 }
1445 else if (revents & (POLLHUP | POLLERR))
1446 {
1447 slog (L_ERR, _("FATAL: POLLHUP or POLLERR on network device fd, terminating."));
1448 exit (1);
1449 }
1450 else
1451 abort ();
1452 }
1453
1454 void
1455 vpn::event_cb (tstamp &ts)
1456 {
1457 if (events)
1458 {
1459 if (events & EVENT_SHUTDOWN)
1460 {
1461 shutdown_all ();
1462
1463 remove_pid (pidfilename);
1464
1465 slog (L_INFO, _("vped terminating"));
1466
1467 exit (0);
1468 }
1469
1470 if (events & EVENT_RECONNECT)
1471 reconnect_all ();
1472
1473 events = 0;
1474 }
1475
1476 ts = TSTAMP_CANCEL;
1477 }
1478
1479 vpn::vpn (void)
1480 : udp_ev_watcher (this, &vpn::udp_ev)
1481 , vpn_ev_watcher (this, &vpn::vpn_ev)
1482 , event (this, &vpn::event_cb)
1483 {
1484 }
1485
1486 vpn::~vpn ()
1487 {
1488 }
1489