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