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