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