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