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

File Contents

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