ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
(Generate patch)

Comparing gvpe/src/connection.C (file contents):
Revision 1.69 by pcg, Thu Aug 7 17:54:26 2008 UTC vs.
Revision 1.112 by root, Fri Sep 12 10:40:43 2014 UTC

1/* 1/*
2 connection.C -- manage a single connection 2 connection.C -- manage a single connection
3 Copyright (C) 2003-2008 Marc Lehmann <gvpe@schmorp.de> 3 Copyright (C) 2003-2008,2010,2011,2013 Marc Lehmann <gvpe@schmorp.de>
4 4
5 This file is part of GVPE. 5 This file is part of GVPE.
6 6
7 GVPE is free software; you can redistribute it and/or modify it 7 GVPE is free software; you can redistribute it and/or modify it
8 under the terms of the GNU General Public License as published by the 8 under the terms of the GNU General Public License as published by the
30*/ 30*/
31 31
32#include "config.h" 32#include "config.h"
33 33
34#include <list> 34#include <list>
35#include <queue>
36#include <utility>
35 37
38#include <openssl/opensslv.h>
36#include <openssl/rand.h> 39#include <openssl/rand.h>
37#include <openssl/evp.h> 40#include <openssl/evp.h>
38#include <openssl/rsa.h> 41#include <openssl/rsa.h>
39#include <openssl/err.h> 42#include <openssl/err.h>
43
44// openssl 0.9.8 compatibility
45#if OPENSSL_VERSION_NUMBER < 0x10100000
46 #define require101(exp) exp
47#else
48 #define require101(exp) require (exp)
49#endif
40 50
41#include "conf.h" 51#include "conf.h"
42#include "slog.h" 52#include "slog.h"
43#include "device.h" 53#include "device.h"
44#include "vpn.h" 54#include "vpn.h"
45#include "connection.h" 55#include "connection.h"
56#include "hkdf.h"
46 57
47#include "netcompat.h" 58#include "netcompat.h"
48 59
49#if !HAVE_RAND_PSEUDO_BYTES
50# define RAND_pseudo_bytes RAND_bytes
51#endif
52
53#define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic 60#define MAGIC "gvpe\xbd\xc6\xdb\x82" // 8 bytes of magic
54 61
55#define ULTRA_FAST 1 62#define ULTRA_FAST 1
56#define HLOG 15 63#define HLOG 15
57#include "lzf/lzf.h" 64#include "lzf/lzf.h"
58#include "lzf/lzf_c.c" 65#include "lzf/lzf_c.c"
59#include "lzf/lzf_d.c" 66#include "lzf/lzf_d.c"
60 67
68//////////////////////////////////////////////////////////////////////////////
69
70static std::queue< std::pair<run_script_cb *, const char *> > rs_queue;
71static ev::child rs_child_ev;
72
73namespace
74{
75 void // c++ requires external linkage here, apparently :(
76 rs_child_cb (ev::child &w, int revents)
77 {
78 w.stop ();
79
80 if (rs_queue.empty ())
81 return;
82
83 pid_t pid = run_script (*rs_queue.front ().first, false);
84 if (pid)
85 {
86 w.set (pid);
87 w.start ();
88 }
89 else
90 slog (L_WARN, rs_queue.front ().second);
91
92 delete rs_queue.front ().first;
93 rs_queue.pop ();
94 }
95};
96
97// despite the fancy name, this is quite a hack
98static void
99run_script_queued (run_script_cb *cb, const char *warnmsg)
100{
101 rs_queue.push (std::make_pair (cb, warnmsg));
102
103 if (!rs_child_ev.is_active ())
104 {
105 rs_child_ev.set<rs_child_cb> ();
106 rs_child_ev ();
107 }
108}
109
110//////////////////////////////////////////////////////////////////////////////
111
61struct crypto_ctx 112struct crypto_ctx
62{ 113{
63 EVP_CIPHER_CTX cctx; 114 EVP_CIPHER_CTX cctx;
64 HMAC_CTX hctx; 115 HMAC_CTX hctx;
65 116
66 crypto_ctx (const rsachallenge &challenge, int enc); 117 crypto_ctx (const auth_data &auth1, const auth_data &auth2, const ecdh_key &a, const ecdh_key &b, int enc);
67 ~crypto_ctx (); 118 ~crypto_ctx ();
68}; 119};
69 120
70crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc) 121crypto_ctx::crypto_ctx (const auth_data &auth1, const auth_data &auth2, const ecdh_key &a, const ecdh_key &b, int enc)
71{ 122{
123 ecdh_key s;
124
125 curve25519_combine (a, b, s);
126
127 {
128 u8 mac_key[MAC_KEYSIZE];
129 static const unsigned char mac_info[] = "gvpe mac key";
130
131 hkdf kdf (auth2.rsa.hkdf_salt, sizeof (auth2.rsa.hkdf_salt), HKDF_XTR_HASH ());
132 kdf.extract (auth1.rsa.mac_key, sizeof (auth1.rsa.mac_key));
133 kdf.extract (s, sizeof (s));
134 kdf.extract_done (HKDF_PRF_HASH ());
135 kdf.expand (mac_key, sizeof (mac_key), mac_info, sizeof (mac_info));
136
137 HMAC_CTX_init (&hctx);
138 require101 (HMAC_Init_ex (&hctx, mac_key, MAC_KEYSIZE, MAC_DIGEST (), 0));
139 }
140
141 {
142 u8 cipher_key[CIPHER_KEYSIZE];
143 static const unsigned char cipher_info[] = "gvpe cipher key";
144
145 hkdf kdf (auth2.rsa.hkdf_salt, sizeof (auth2.rsa.hkdf_salt), HKDF_XTR_HASH ());
146 kdf.extract (auth1.rsa.cipher_key, sizeof (auth1.rsa.cipher_key));
147 kdf.extract (s, sizeof (s));
148 kdf.extract_done (HKDF_PRF_HASH ());
149 kdf.expand (cipher_key, sizeof (cipher_key), cipher_info, sizeof (cipher_info));
150
72 EVP_CIPHER_CTX_init (&cctx); 151 EVP_CIPHER_CTX_init (&cctx);
73 require (EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc)); 152 require (EVP_CipherInit_ex (&cctx, CIPHER (), 0, cipher_key, 0, enc));
74 HMAC_CTX_init (&hctx); 153 }
75 HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
76} 154}
77 155
78crypto_ctx::~crypto_ctx () 156crypto_ctx::~crypto_ctx ()
79{ 157{
80 require (EVP_CIPHER_CTX_cleanup (&cctx)); 158 require (EVP_CIPHER_CTX_cleanup (&cctx));
81 HMAC_CTX_cleanup (&hctx); 159 HMAC_CTX_cleanup (&hctx);
82} 160}
83 161
162static inline void
163auth_encrypt (RSA *key, const auth_data &auth, auth_encr &encr)
164{
165 if (RSA_public_encrypt (sizeof (auth.rsa),
166 (unsigned char *)&auth.rsa, (unsigned char *)&encr.rsa,
167 key, RSA_PKCS1_OAEP_PADDING) < 0)
168 fatal ("RSA_public_encrypt error");
169
170 memcpy (&encr.ecdh, &auth.ecdh, sizeof (encr.ecdh));
171}
172
173static inline bool
174auth_decrypt (RSA *key, const auth_encr &encr, auth_data &auth)
175{
176 u8 rsa_decrypt[RSA_KEYLEN];
177
178 if (RSA_private_decrypt (sizeof (encr.rsa),
179 (const unsigned char *)&encr.rsa, (unsigned char *)rsa_decrypt,
180 key, RSA_PKCS1_OAEP_PADDING) != sizeof (auth.rsa))
181 return 0;
182
183 memcpy (&auth.rsa, rsa_decrypt, sizeof (auth.rsa));
184 memcpy (&auth.ecdh, &encr.ecdh, sizeof (auth.ecdh));
185
186 return 1;
187}
188
84static void 189static void
85rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h) 190auth_hash (const auth_data &auth, const ecdh_key &b, auth_mac &mac)
86{ 191{
87 EVP_MD_CTX ctx; 192 hkdf kdf (b, sizeof b, AUTH_DIGEST ()); // use response ecdh b as salt
88 193 kdf.extract (&auth.rsa, sizeof (auth.rsa));
89 EVP_MD_CTX_init (&ctx); 194 kdf.extract_done ();
90 require (EVP_DigestInit (&ctx, RSA_HASH)); 195 kdf.expand (mac, sizeof mac, auth.ecdh, sizeof (auth.ecdh)); // use challenge ecdh b as info
91 require (EVP_DigestUpdate(&ctx, &chg, sizeof chg));
92 require (EVP_DigestUpdate(&ctx, &id, sizeof id));
93 require (EVP_DigestFinal (&ctx, (unsigned char *)&h, 0));
94 EVP_MD_CTX_cleanup (&ctx);
95} 196}
96 197
97struct rsa_entry 198void
199connection::generate_auth_data ()
98{ 200{
99 tstamp expire; 201 if (auth_expire < ev_now ())
100 rsaid id;
101 rsachallenge chg;
102};
103
104struct rsa_cache : list<rsa_entry>
105{
106 inline void cleaner_cb (ev::timer &w, int revents); ev::timer cleaner;
107
108 bool find (const rsaid &id, rsachallenge &chg)
109 {
110 for (iterator i = begin (); i != end (); ++i)
111 { 202 {
112 if (!memcmp (&id, &i->id, sizeof id) && i->expire > ev_now ()) 203 // request data
113 { 204 rand_fill (snd_auth.rsa);
114 memcpy (&chg, &i->chg, sizeof chg); 205 curve25519_generate (snd_ecdh_a, snd_auth.ecdh);
115 206
116 erase (i); 207 // eventual response data
117 return true; 208 curve25519_generate (rcv_ecdh_a, rcv_ecdh_b);
118 }
119 } 209 }
120 210
121 if (!cleaner.is_active ()) 211 // every use prolongs the expiry
122 cleaner.again ();
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 = ev_now () + RSA_TTL; 212 auth_expire = ev_now () + AUTH_TTL;
135 e.id = id;
136 memcpy (&e.chg, &chg, sizeof chg);
137
138 push_back (e);
139
140 if (!cleaner.is_active ())
141 cleaner.again ();
142 }
143
144 rsa_cache ()
145 {
146 cleaner.set<rsa_cache, &rsa_cache::cleaner_cb> (this);
147 cleaner.set (RSA_TTL, RSA_TTL);
148 }
149
150} rsa_cache;
151
152void rsa_cache::cleaner_cb (ev::timer &w, int revents)
153{
154 if (empty ())
155 w.stop ();
156 else
157 {
158 for (iterator i = begin (); i != end (); )
159 if (i->expire <= ev_now ())
160 i = erase (i);
161 else
162 ++i;
163 }
164} 213}
165 214
166////////////////////////////////////////////////////////////////////////////// 215//////////////////////////////////////////////////////////////////////////////
167 216
168pkt_queue::pkt_queue (double max_ttl, int max_queue) 217pkt_queue::pkt_queue (double max_ttl, int max_queue)
182 delete p; 231 delete p;
183 232
184 delete [] queue; 233 delete [] queue;
185} 234}
186 235
236void
187void pkt_queue::expire_cb (ev::timer &w, int revents) 237pkt_queue::expire_cb (ev::timer &w, int revents)
188{ 238{
189 ev_tstamp expire = ev_now () - max_ttl; 239 ev_tstamp expire = ev_now () - max_ttl;
190 240
191 for (;;) 241 for (;;)
192 { 242 {
203 253
204 delete get (); 254 delete get ();
205 } 255 }
206} 256}
207 257
258void
208void pkt_queue::put (net_packet *p) 259pkt_queue::put (net_packet *p)
209{ 260{
210 ev_tstamp now = ev_now (); 261 ev_tstamp now = ev_now ();
211 262
212 // start expiry timer 263 // start expiry timer
213 if (empty ()) 264 if (empty ())
222 queue[i].tstamp = now; 273 queue[i].tstamp = now;
223 274
224 i = ni; 275 i = ni;
225} 276}
226 277
227net_packet *pkt_queue::get () 278net_packet *
279pkt_queue::get ()
228{ 280{
229 if (empty ()) 281 if (empty ())
230 return 0; 282 return 0;
231 283
232 net_packet *p = queue[j].pkt; 284 net_packet *p = queue[j].pkt;
256 308
257 bool can (const sockinfo &si) { return can((u32)si.host); } 309 bool can (const sockinfo &si) { return can((u32)si.host); }
258 bool can (u32 host); 310 bool can (u32 host);
259}; 311};
260 312
261net_rate_limiter auth_rate_limiter, reset_rate_limiter; 313static net_rate_limiter auth_rate_limiter, reset_rate_limiter;
262 314
315bool
263bool net_rate_limiter::can (u32 host) 316net_rate_limiter::can (u32 host)
264{ 317{
265 iterator i; 318 iterator i;
266 319
267 for (i = begin (); i != end (); ) 320 for (i = begin (); i != end (); )
268 if (i->host == host) 321 if (i->host == host)
313 } 366 }
314} 367}
315 368
316///////////////////////////////////////////////////////////////////////////// 369/////////////////////////////////////////////////////////////////////////////
317 370
318unsigned char hmac_packet::hmac_digest[EVP_MAX_MD_SIZE]; 371void
319
320void hmac_packet::hmac_gen (crypto_ctx *ctx) 372hmac_packet::hmac_gen (crypto_ctx *ctx, u8 *hmac_digest)
321{ 373{
322 unsigned int xlen;
323
324 HMAC_CTX *hctx = &ctx->hctx; 374 HMAC_CTX *hctx = &ctx->hctx;
325 375
326 HMAC_Init_ex (hctx, 0, 0, 0, 0); 376 require101 (HMAC_Init_ex (hctx, 0, 0, 0, 0));
327 HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet), 377 require101 (HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet), len - sizeof (hmac_packet)));
328 len - sizeof (hmac_packet)); 378 require101 (HMAC_Final (hctx, hmac_digest, 0));
329 HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen);
330} 379}
331 380
332void 381void
333hmac_packet::hmac_set (crypto_ctx *ctx) 382hmac_packet::hmac_set (crypto_ctx *ctx)
334{ 383{
335 hmac_gen (ctx); 384 unsigned char hmac_digest[EVP_MAX_MD_SIZE];
336 385 hmac_gen (ctx, hmac_digest);
337 memcpy (hmac, hmac_digest, HMACLENGTH); 386 memcpy (hmac, hmac_digest, HMACLENGTH);
338} 387}
339 388
340bool 389bool
341hmac_packet::hmac_chk (crypto_ctx *ctx) 390hmac_packet::hmac_chk (crypto_ctx *ctx)
342{ 391{
343 hmac_gen (ctx); 392 unsigned char hmac_digest[EVP_MAX_MD_SIZE];
344 393 hmac_gen (ctx, hmac_digest);
345 return !memcmp (hmac, hmac_digest, HMACLENGTH); 394 return slow_memeq (hmac, hmac_digest, HMACLENGTH);
346} 395}
347 396
397void
348void vpn_packet::set_hdr (ptype type_, unsigned int dst) 398vpn_packet::set_hdr (ptype type_, unsigned int dst)
349{ 399{
350 type = type_; 400 type = type_;
351 401
352 int src = THISNODE->id; 402 int src = THISNODE->id;
353 403
358 408
359#define MAXVPNDATA (MAX_MTU - 6 - 6) 409#define MAXVPNDATA (MAX_MTU - 6 - 6)
360#define DATAHDR (sizeof (u32) + RAND_SIZE) 410#define DATAHDR (sizeof (u32) + RAND_SIZE)
361 411
362struct vpndata_packet : vpn_packet 412struct vpndata_packet : vpn_packet
413{
414 u8 data[MAXVPNDATA + DATAHDR]; // seqno
415
416 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
417 tap_packet *unpack (connection *conn, u32 &seqno);
418
419private:
420 const u32 data_hdr_size () const
363 { 421 {
364 u8 data[MAXVPNDATA + DATAHDR]; // seqno
365
366 void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
367 tap_packet *unpack (connection *conn, u32 &seqno);
368private:
369
370 const u32 data_hdr_size () const
371 {
372 return sizeof (vpndata_packet) - sizeof (net_packet) - MAXVPNDATA - DATAHDR; 422 return sizeof (vpndata_packet) - sizeof (net_packet) - MAXVPNDATA - DATAHDR;
373 }
374 }; 423 }
424};
375 425
376void 426void
377vpndata_packet::setup (connection *conn, int dst, u8 *d, u32 l, u32 seqno) 427vpndata_packet::setup (connection *conn, int dst, u8 *d, u32 l, u32 seqno)
378{ 428{
379 EVP_CIPHER_CTX *cctx = &conn->octx->cctx; 429 EVP_CIPHER_CTX *cctx = &conn->octx->cctx;
381 ptype type = PT_DATA_UNCOMPRESSED; 431 ptype type = PT_DATA_UNCOMPRESSED;
382 432
383#if ENABLE_COMPRESSION 433#if ENABLE_COMPRESSION
384 u8 cdata[MAX_MTU]; 434 u8 cdata[MAX_MTU];
385 435
386 if (conn->features & ENABLE_COMPRESSION) 436 if (conn->features & FEATURE_COMPRESSION)
387 { 437 {
388 u32 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7); 438 u32 cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
389 439
390 if (cl) 440 if (cl)
391 { 441 {
397 d[1] = cl; 447 d[1] = cl;
398 } 448 }
399 } 449 }
400#endif 450#endif
401 451
402 require (EVP_EncryptInit_ex (cctx, 0, 0, 0, 0)); 452 require (EVP_CipherInit_ex (cctx, 0, 0, 0, 0, 1));
403 453
404 struct { 454 struct {
405#if RAND_SIZE 455#if RAND_SIZE
406 u8 rnd[RAND_SIZE]; 456 u8 rnd[RAND_SIZE];
407#endif 457#endif
408 u32 seqno; 458 u32 seqno;
409 } datahdr; 459 } datahdr;
410 460
411 datahdr.seqno = ntohl (seqno); 461 datahdr.seqno = ntohl (seqno);
412#if RAND_SIZE 462#if RAND_SIZE
413 RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE); 463 // NB: a constant (per session) random prefix
464 // is likely enough, but we don't take any chances.
465 conn->oiv.get (datahdr.rnd, RAND_SIZE);
414#endif 466#endif
415 467
416 require (EVP_EncryptUpdate (cctx, 468 require (EVP_EncryptUpdate (cctx,
417 (unsigned char *) data + outl, &outl2, 469 (unsigned char *) data + outl, &outl2,
418 (unsigned char *) &datahdr, DATAHDR)); 470 (unsigned char *) &datahdr, DATAHDR));
440 int outl = 0, outl2; 492 int outl = 0, outl2;
441 tap_packet *p = new tap_packet; 493 tap_packet *p = new tap_packet;
442 u8 *d; 494 u8 *d;
443 u32 l = len - data_hdr_size (); 495 u32 l = len - data_hdr_size ();
444 496
445 require (EVP_DecryptInit_ex (cctx, 0, 0, 0, 0)); 497 require (EVP_CipherInit_ex (cctx, 0, 0, 0, 0, 0));
446 498
447#if ENABLE_COMPRESSION 499#if ENABLE_COMPRESSION
448 u8 cdata[MAX_MTU]; 500 u8 cdata[MAX_MTU];
449 501
450 if (type == PT_DATA_COMPRESSED) 502 if (type == PT_DATA_COMPRESSED)
451 d = cdata; 503 d = cdata;
452 else 504 else
453#endif 505#endif
454 d = &(*p)[6 + 6 - DATAHDR]; 506 d = &(*p)[6 + 6] - DATAHDR;
455 507
456 /* this overwrites part of the src mac, but we fix that later */ 508 // we play do evil games with the struct layout atm.
509 // pending better solutions, we at least do some verification.
510 // this is fine, as we left ISO territory long ago.
511 require (DATAHDR <= 16);
512 require ((u8 *)(&p->len + 1) == &(*p)[0]);
513
514 // this can overwrite the len/dst/src fields
457 require (EVP_DecryptUpdate (cctx, 515 require (EVP_DecryptUpdate (cctx,
458 d, &outl2, 516 d, &outl2,
459 (unsigned char *)&data, len - data_hdr_size ())); 517 (unsigned char *)&data, len - data_hdr_size ()));
460 outl += outl2; 518 outl += outl2;
461 519
492 } 550 }
493}; 551};
494 552
495struct config_packet : vpn_packet 553struct config_packet : vpn_packet
496{ 554{
497 // actually, hmaclen cannot be checked because the hmac 555 u8 serial[SERIAL_SIZE];
498 // field comes before this data, so peers with other
499 // hmacs simply will not work.
500 u8 prot_major, prot_minor, randsize, hmaclen; 556 u8 prot_major, prot_minor, randsize;
501 u8 flags, challengelen, features, pad3; 557 u8 flags, features, pad6, pad7, pad8;
502 u32 cipher_nid, digest_nid, hmac_nid; 558 u32 cipher_nid, mac_nid, auth_nid;
503 559
504 void setup (ptype type, int dst); 560 void setup (ptype type, int dst);
505 bool chk_config () const; 561 bool chk_config (const conf_node *conf, const sockinfo &rsi) const;
506 562
507 static u8 get_features () 563 static u8 get_features ()
508 { 564 {
509 u8 f = 0; 565 u8 f = 0;
510#if ENABLE_COMPRESSION 566#if ENABLE_COMPRESSION
518#endif 574#endif
519 return f; 575 return f;
520 } 576 }
521}; 577};
522 578
579void
523void config_packet::setup (ptype type, int dst) 580config_packet::setup (ptype type, int dst)
524{ 581{
525 prot_major = PROTOCOL_MAJOR; 582 prot_major = PROTOCOL_MAJOR;
526 prot_minor = PROTOCOL_MINOR; 583 prot_minor = PROTOCOL_MINOR;
527 randsize = RAND_SIZE; 584 randsize = RAND_SIZE;
528 hmaclen = HMACLENGTH;
529 flags = 0; 585 flags = 0;
530 challengelen = sizeof (rsachallenge);
531 features = get_features (); 586 features = get_features ();
532 587
588 strncpy ((char *)serial, conf.serial, sizeof (serial));
589
533 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER)); 590 cipher_nid = htonl (EVP_CIPHER_nid (CIPHER ()));
534 digest_nid = htonl (EVP_MD_type (RSA_HASH));
535 hmac_nid = htonl (EVP_MD_type (DIGEST)); 591 mac_nid = htonl (EVP_MD_type (MAC_DIGEST ()));
592 auth_nid = htonl (EVP_MD_type (AUTH_DIGEST ()));
536 593
537 len = sizeof (*this) - sizeof (net_packet); 594 len = sizeof (*this) - sizeof (net_packet);
538 set_hdr (type, dst); 595 set_hdr (type, dst);
539} 596}
540 597
541bool config_packet::chk_config () const 598bool
599config_packet::chk_config (const conf_node *conf, const sockinfo &rsi) const
542{ 600{
543 if (prot_major != PROTOCOL_MAJOR) 601 if (prot_major != PROTOCOL_MAJOR)
544 slog (L_WARN, _("major version mismatch (remote %d <=> local %d)"), prot_major, PROTOCOL_MAJOR); 602 slog (L_WARN, _("%s(%s): major version mismatch (remote %d <=> local %d)"),
603 conf->nodename, (const char *)rsi, prot_major, PROTOCOL_MAJOR);
545 else if (randsize != RAND_SIZE) 604 else if (randsize != RAND_SIZE)
546 slog (L_WARN, _("rand size mismatch (remote %d <=> local %d)"), randsize, RAND_SIZE); 605 slog (L_WARN, _("%s(%s): rand size mismatch (remote %d <=> local %d)"),
547 else if (hmaclen != HMACLENGTH) 606 conf->nodename, (const char *)rsi, randsize, RAND_SIZE);
548 slog (L_WARN, _("hmac length mismatch (remote %d <=> local %d)"), hmaclen, HMACLENGTH);
549 else if (challengelen != sizeof (rsachallenge))
550 slog (L_WARN, _("challenge length mismatch (remote %d <=> local %d)"), challengelen, sizeof (rsachallenge));
551 else if (cipher_nid != htonl (EVP_CIPHER_nid (CIPHER))) 607 else if (cipher_nid != htonl (EVP_CIPHER_nid (CIPHER ())))
552 slog (L_WARN, _("cipher mismatch (remote %x <=> local %x)"), ntohl (cipher_nid), EVP_CIPHER_nid (CIPHER)); 608 slog (L_WARN, _("%s(%s): cipher algo mismatch (remote %x <=> local %x)"),
553 else if (digest_nid != htonl (EVP_MD_type (RSA_HASH))) 609 conf->nodename, (const char *)rsi, ntohl (cipher_nid), EVP_CIPHER_nid (CIPHER ()));
554 slog (L_WARN, _("digest mismatch (remote %x <=> local %x)"), ntohl (digest_nid), EVP_MD_type (RSA_HASH));
555 else if (hmac_nid != htonl (EVP_MD_type (DIGEST))) 610 else if (mac_nid != htonl (EVP_MD_type (MAC_DIGEST ())))
556 slog (L_WARN, _("hmac mismatch (remote %x <=> local %x)"), ntohl (hmac_nid), EVP_MD_type (DIGEST)); 611 slog (L_WARN, _("%s(%s): mac algo mismatch (remote %x <=> local %x)"),
612 conf->nodename, (const char *)rsi, ntohl (mac_nid), EVP_MD_type (MAC_DIGEST ()));
613 else if (auth_nid != htonl (EVP_MD_type (AUTH_DIGEST ())))
614 slog (L_WARN, _("%s(%s): auth algo mismatch (remote %x <=> local %x)"),
615 conf->nodename, (const char *)rsi, ntohl (auth_nid), EVP_MD_type (AUTH_DIGEST ()));
557 else 616 else
617 {
618 int cmp = memcmp (serial, ::conf.serial, sizeof (serial));
619
620 if (cmp > 0)
621 slog (L_WARN, _("%s(%s): remote serial newer than local serial - outdated config?"),
622 conf->nodename, (const char *)rsi);
623 else if (cmp == 0)
558 return true; 624 return true;
625 }
559 626
560 return false; 627 return false;
561} 628}
562 629
563struct auth_req_packet : config_packet 630struct auth_req_packet : config_packet // UNPROTECTED
564{ 631{
565 char magic[8]; 632 char magic[8];
566 u8 initiate; // false if this is just an automatic reply 633 u8 initiate; // false if this is just an automatic reply
567 u8 protocols; // supported protocols (will be patched on forward) 634 u8 protocols; // supported protocols (will be patched on forward)
568 u8 pad2, pad3; 635 u8 pad2, pad3;
569 rsaid id; 636 auth_encr encr;
570 rsaencrdata encr;
571 637
572 auth_req_packet (int dst, bool initiate_, u8 protocols_) 638 auth_req_packet (int dst, bool initiate_, u8 protocols_)
573 { 639 {
574 config_packet::setup (PT_AUTH_REQ, dst); 640 config_packet::setup (PT_AUTH_REQ, dst);
575 strncpy (magic, MAGIC, 8); 641 memcpy (magic, MAGIC, 8);
576 initiate = !!initiate_; 642 initiate = !!initiate_;
577 protocols = protocols_; 643 protocols = protocols_;
578 644
579 len = sizeof (*this) - sizeof (net_packet); 645 len = sizeof (*this) - sizeof (net_packet);
580 } 646 }
581}; 647};
582 648
583struct auth_res_packet : config_packet 649struct auth_res_packet : vpn_packet // UNPROTECTED
584{ 650{
585 rsaid id;
586 u8 pad1, pad2, pad3;
587 u8 response_len; // encrypted length
588 rsaresponse response; 651 auth_response response;
589 652
590 auth_res_packet (int dst) 653 auth_res_packet (int dst)
591 { 654 {
592 config_packet::setup (PT_AUTH_RES, dst); 655 set_hdr (PT_AUTH_RES, dst);
593 656
594 len = sizeof (*this) - sizeof (net_packet); 657 len = sizeof (*this) - sizeof (net_packet);
595 } 658 }
596}; 659};
597 660
627}; 690};
628 691
629///////////////////////////////////////////////////////////////////////////// 692/////////////////////////////////////////////////////////////////////////////
630 693
631void 694void
632connection::connection_established () 695connection::connection_established (const sockinfo &rsi)
633{ 696{
634 slog (L_TRACE, _("%s: possible connection establish (ictx %d, octx %d)"), conf->nodename, !!ictx, !!octx); 697 if (!have_snd_auth || !have_rcv_auth)
698 return;
635 699
636 if (ictx && octx) 700 si = rsi;
701 protocol = rsi.prot;
702
703 slog (L_INFO, _("%s(%s): connection established (%s), protocol version %d.%d."),
704 conf->nodename, (const char *)rsi,
705 vpn->can_direct (THISNODE, conf) ? "direct" : "forwarded",
706 PROTOCOL_MAJOR, prot_minor);
707
708 if (::conf.script_node_up)
709 {
710 run_script_cb *cb = new run_script_cb;
711 cb->set<connection, &connection::script_node_up> (this);
712 run_script_queued (cb, _("node-up command execution failed, continuing."));
637 { 713 }
714
715 delete ictx; ictx = new crypto_ctx (rcv_auth, snd_auth, rcv_ecdh_a, rcv_auth.ecdh, 0);
716 iseqno.reset (ntohl (rcv_auth.rsa.seqno) & 0x7fffffff);
717
718 delete octx; octx = new crypto_ctx (snd_auth, rcv_auth, snd_ecdh_a, snd_ecdh_b , 1);
719 oseqno = ntohl (snd_auth.rsa.seqno) & 0x7fffffff;
720
721 oiv.reset ();
722
638 // make sure rekeying timeouts are slightly asymmetric 723 // make sure rekeying timeouts are slightly asymmetric
639 ev::tstamp rekey_interval = ::conf.rekey + (conf->id > THISNODE->id ? 10 : 0); 724 ev::tstamp rekey_interval = ::conf.rekey + (conf->id > THISNODE->id ? 10 : 0);
640 rekey.start (rekey_interval, rekey_interval); 725 rekey.start (rekey_interval, rekey_interval);
726
727 hmac_error = 0.;
728
641 keepalive.start (::conf.keepalive); 729 keepalive.start (::conf.keepalive);
642 730
643 // send queued packets 731 // send queued packets
644 if (ictx && octx)
645 {
646 while (tap_packet *p = (tap_packet *)data_queue.get ()) 732 while (tap_packet *p = (tap_packet *)data_queue.get ())
647 { 733 {
648 if (p->len) send_data_packet (p); 734 if (p->len) send_data_packet (p);
649 delete p; 735 delete p;
650 } 736 }
651 737
652 while (vpn_packet *p = (vpn_packet *)vpn_queue.get ()) 738 while (vpn_packet *p = (vpn_packet *)vpn_queue.get ())
653 { 739 {
654 if (p->len) send_vpn_packet (p, si, IPTOS_RELIABILITY); 740 if (p->len) send_vpn_packet (p, si, IPTOS_RELIABILITY);
655 delete p; 741 delete p;
656 }
657 }
658 } 742 }
743
744 vpn->connection_established (this);
745}
746
747void
748connection::reset_si ()
749{
750 if (vpn->can_direct (THISNODE, conf))
751 protocol = best_protocol (THISNODE->protocols & conf->connectable_protocols ());
659 else 752 else
660 { 753 {
661 retry_cnt = 0;
662 establish_connection.start (5);
663 keepalive.stop ();
664 rekey.stop ();
665 }
666}
667
668void
669connection::reset_si ()
670{
671 protocol = best_protocol (THISNODE->protocols & conf->protocols);
672
673 // mask out protocols we cannot establish
674 if (!conf->udp_port) protocol &= ~PROT_UDPv4;
675 if (!conf->tcp_port) protocol &= ~PROT_TCPv4;
676 if (!conf->dns_port) protocol &= ~PROT_DNSv4;
677
678 if (protocol
679 && (!conf->can_direct (THISNODE)
680 || !THISNODE->can_direct (conf)))
681 {
682 slog (L_DEBUG, _("%s: direct connection denied"), conf->nodename); 754 slog (L_TRACE, _("%s: direct connection denied by config."), conf->nodename);
683 protocol = 0; 755 protocol = 0;
684 } 756 }
685 757
686 si.set (conf, protocol); 758 si.set (conf, protocol);
687} 759}
690const sockinfo & 762const sockinfo &
691connection::forward_si (const sockinfo &si) const 763connection::forward_si (const sockinfo &si) const
692{ 764{
693 if (!si.valid ()) 765 if (!si.valid ())
694 { 766 {
695 connection *r = vpn->find_router (); 767 connection *r = vpn->find_router_for (this);
696 768
697 if (r) 769 if (r)
698 { 770 {
699 slog (L_DEBUG, _("%s: no common protocol, trying indirectly through %s (%s)"), 771 slog (L_DEBUG, _("%s: no common protocol, trying to route through %s."),
700 conf->nodename, r->conf->nodename, (const char *)r->si); 772 conf->nodename, r->conf->nodename);
701 return r->si; 773 return r->si;
702 } 774 }
703 else 775 else
704 slog (L_DEBUG, _("%s: node unreachable, no common protocol"), 776 slog (L_DEBUG, _("%s: node unreachable, no common protocol or no router available."),
705 conf->nodename); 777 conf->nodename);
706 } 778 }
707 779
708 return si; 780 return si;
709} 781}
710 782
711void 783void
712connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos) 784connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
713{ 785{
714 if (!vpn->send_vpn_packet (pkt, si, tos)) 786 if (!vpn->send_vpn_packet (pkt, si, tos))
715 reset_connection (); 787 reset_connection ("packet send error");
716} 788}
717 789
718void 790void
719connection::send_ping (const sockinfo &si, u8 pong) 791connection::send_ping (const sockinfo &si, u8 pong)
720{ 792{
721 ping_packet *pkt = new ping_packet; 793 ping_packet *pkt = new ping_packet;
722 794
723 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING); 795 pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
796
797 slog (L_TRACE, "%s << %s [%s]", conf->nodename, pong ? "PT_PONG" : "PT_PING", (const char *)si);
724 send_vpn_packet (pkt, si, IPTOS_LOWDELAY); 798 send_vpn_packet (pkt, si, IPTOS_LOWDELAY);
725 799
726 delete pkt; 800 delete pkt;
727} 801}
728 802
743void 817void
744connection::send_auth_request (const sockinfo &si, bool initiate) 818connection::send_auth_request (const sockinfo &si, bool initiate)
745{ 819{
746 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols); 820 auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols);
747 821
748 rsachallenge chg; 822 generate_auth_data ();
749 rsa_cache.gen (pkt->id, chg);
750 rsa_encrypt (conf->rsa_key, chg, pkt->encr); 823 auth_encrypt (conf->rsa_key, snd_auth, pkt->encr);
751 824
752 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si); 825 slog (L_TRACE, "%s << PT_AUTH_REQ [%s]", conf->nodename, (const char *)si);
753
754 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly 826 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
755 827
756 delete pkt; 828 delete pkt;
757} 829}
758 830
759void 831void
760connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg) 832connection::send_auth_response (const sockinfo &si)
761{ 833{
762 auth_res_packet *pkt = new auth_res_packet (conf->id); 834 auth_res_packet *pkt = new auth_res_packet (conf->id);
763 835
764 pkt->id = id; 836 memcpy (pkt->response.ecdh, rcv_ecdh_b, sizeof rcv_ecdh_b);
837 auth_hash (rcv_auth, rcv_ecdh_b, pkt->response.mac);
765 838
766 rsa_hash (id, chg, pkt->response);
767
768 pkt->hmac_set (octx);
769
770 slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si); 839 slog (L_TRACE, "%s << PT_AUTH_RES [%s]", conf->nodename, (const char *)si);
771
772 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly 840 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
773 841
774 delete pkt; 842 delete pkt;
775} 843}
776 844
777void 845void
778connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols) 846connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
779{ 847{
780 slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)", 848 slog (L_TRACE, "%s << PT_CONNECT_INFO(%s,%s,p%02x)", conf->nodename,
781 conf->id, rid, (const char *)rsi); 849 vpn->conns[rid - 1]->conf->nodename, (const char *)rsi,
850 conf->protocols);
782 851
783 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols); 852 connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
784 853
785 r->hmac_set (octx); 854 r->hmac_set (octx);
786 send_vpn_packet (r, si); 855 send_vpn_packet (r, si);
789} 858}
790 859
791inline void 860inline void
792connection::establish_connection_cb (ev::timer &w, int revents) 861connection::establish_connection_cb (ev::timer &w, int revents)
793{ 862{
794 if (!ictx 863 if (!(ictx && octx)
795 && conf != THISNODE 864 && conf != THISNODE
796 && connectmode != conf_node::C_NEVER 865 && connectmode != conf_node::C_NEVER
797 && connectmode != conf_node::C_DISABLED 866 && connectmode != conf_node::C_DISABLED
798 && !w.is_active ()) 867 && !w.is_active ())
799 { 868 {
800 // a bit hacky, if ondemand, and packets are no longer queued, then reset the connection 869 // a bit hacky, if ondemand, and packets are no longer queued, then reset the connection
801 // and stop trying. should probably be handled by a per-connection expire handler. 870 // and stop trying. should probably be handled by a per-connection expire handler.
802 if (connectmode == conf_node::C_ONDEMAND && vpn_queue.empty () && data_queue.empty ()) 871 if (connectmode == conf_node::C_ONDEMAND && vpn_queue.empty () && data_queue.empty ())
803 { 872 {
804 reset_connection (); 873 reset_connection ("no demand");
805 return; 874 return;
806 } 875 }
807 876
808 last_establish_attempt = ev_now (); 877 last_establish_attempt = ev_now ();
809 878
811 ? (retry_cnt & 3) + 1 880 ? (retry_cnt & 3) + 1
812 : 1 << (retry_cnt >> 2)); 881 : 1 << (retry_cnt >> 2));
813 882
814 reset_si (); 883 reset_si ();
815 884
816 bool slow = si.prot & PROT_SLOW; 885 bool slow = (si.prot & PROT_SLOW) || (conf->low_power || THISNODE->low_power);
817 886
818 if (si.prot && !si.host) 887 if (si.prot && !si.host && vpn->can_direct (THISNODE, conf))
819 { 888 {
820 slog (L_TRACE, _("%s: connection request (indirect)"), conf->nodename);
821 /*TODO*/ /* start the timer so we don't recurse endlessly */ 889 /*TODO*/ /* start the timer so we don't recurse endlessly */
822 w.start (1); 890 w.start (1);
823 vpn->send_connect_request (conf->id); 891 vpn->send_connect_request (this);
824 } 892 }
825 else 893 else
826 { 894 {
827 slog (L_TRACE, _("%s: connection request (direct)"), conf->nodename, !!ictx, !!octx); 895 if (si.valid ())
896 slog (L_DEBUG, _("%s: sending direct connection request to %s."),
897 conf->nodename, (const char *)si);
828 898
829 const sockinfo &dsi = forward_si (si); 899 const sockinfo &dsi = forward_si (si);
830 900
831 slow = slow || (dsi.prot & PROT_SLOW); 901 slow = slow || (dsi.prot & PROT_SLOW);
832 902
833 if (dsi.valid () && auth_rate_limiter.can (dsi)) 903 if (dsi.valid () && auth_rate_limiter.can (dsi))
834 { 904 {
835 if (retry_cnt < 4) 905 // use ping after the first few retries
906 // TODO: on rekeys, the other node might not interpret ping correctly,
907 // TODO: as it will still have a valid connection
908 if (retry_cnt < 4 && (!conf->low_power || THISNODE->low_power))
836 send_auth_request (dsi, true); 909 send_auth_request (dsi, true);
837 else 910 else
838 send_ping (dsi, 0); 911 send_ping (dsi, 0);
839 } 912 }
840 } 913 }
841 914
842 retry_int *= slow ? 8. : 0.9; 915 retry_int *= slow ? 4. : 0.9;
843 916
844 if (retry_int < conf->max_retry) 917 if (retry_int < conf->max_retry)
845 retry_cnt++; 918 retry_cnt++;
846 else 919 else
847 retry_int = conf->max_retry; 920 retry_int = conf->max_retry;
849 w.start (retry_int); 922 w.start (retry_int);
850 } 923 }
851} 924}
852 925
853void 926void
854connection::reset_connection () 927connection::reset_connection (const char *reason)
855{ 928{
856 if (ictx && octx) 929 if (ictx && octx)
857 { 930 {
858 slog (L_INFO, _("%s(%s): connection lost"), 931 slog (L_INFO, _("%s(%s): connection lost (%s)"),
859 conf->nodename, (const char *)si); 932 conf->nodename, (const char *)si, reason);
860 933
861 if (::conf.script_node_down) 934 if (::conf.script_node_down)
862 { 935 {
863 run_script_cb cb; 936 run_script_cb *cb = new run_script_cb;
864 cb.set<connection, &connection::script_node_down> (this); 937 cb->set<connection, &connection::script_node_down> (this);
865 if (!run_script (cb, false))
866 slog (L_WARN, _("node-down command execution failed, continuing.")); 938 run_script_queued (cb, _("node-down command execution failed, continuing."));
867 } 939 }
868 } 940 }
869 941
870 delete ictx; ictx = 0; 942 delete ictx; ictx = 0;
871 delete octx; octx = 0; 943 delete octx; octx = 0;
872#if ENABLE_DNS
873 dnsv4_reset_connection ();
874#endif
875 944
876 si.host = 0; 945 si.host = 0;
877 946
947 have_snd_auth = false;
948 have_rcv_auth = false;
949 auth_expire = 0.;
950
878 last_activity = 0; 951 last_activity = 0.;
952 //last_si_change = 0.;
879 retry_cnt = 0; 953 retry_cnt = 0;
880 954
881 rekey.stop (); 955 rekey.stop ();
882 keepalive.stop (); 956 keepalive.stop ();
883 establish_connection.stop (); 957 establish_connection.stop ();
887connection::shutdown () 961connection::shutdown ()
888{ 962{
889 if (ictx && octx) 963 if (ictx && octx)
890 send_reset (si); 964 send_reset (si);
891 965
892 reset_connection (); 966 reset_connection ("shutdown");
893} 967}
894 968
969// poor-man's rekeying
895inline void 970inline void
896connection::rekey_cb (ev::timer &w, int revents) 971connection::rekey_cb (ev::timer &w, int revents)
897{ 972{
898 reset_connection (); 973 reset_connection ("rekeying");
899 establish_connection (); 974 establish_connection ();
900} 975}
901 976
902void 977void
903connection::send_data_packet (tap_packet *pkt) 978connection::send_data_packet (tap_packet *pkt)
920 995
921void 996void
922connection::post_inject_queue () 997connection::post_inject_queue ()
923{ 998{
924 // force a connection every now and when when packets are sent (max 1/s) 999 // force a connection every now and when when packets are sent (max 1/s)
925 if (ev_now () - last_establish_attempt >= 0.95) // arbitrary 1000 if (ev_now () - last_establish_attempt >= (conf->low_power || THISNODE->low_power ? 2.95 : 0.95)) // arbitrary
926 establish_connection.stop (); 1001 establish_connection.stop ();
927 1002
928 establish_connection (); 1003 establish_connection ();
929} 1004}
930 1005
938 data_queue.put (new tap_packet (*pkt)); 1013 data_queue.put (new tap_packet (*pkt));
939 post_inject_queue (); 1014 post_inject_queue ();
940 } 1015 }
941} 1016}
942 1017
1018void
943void connection::inject_vpn_packet (vpn_packet *pkt, int tos) 1019connection::inject_vpn_packet (vpn_packet *pkt, int tos)
944{ 1020{
945 if (ictx && octx) 1021 if (ictx && octx)
946 send_vpn_packet (pkt, si, tos); 1022 send_vpn_packet (pkt, si, tos);
947 else 1023 else
948 { 1024 {
954void 1030void
955connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi) 1031connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
956{ 1032{
957 last_activity = ev_now (); 1033 last_activity = ev_now ();
958 1034
959 slog (L_NOISE, "<<%d received packet type %d from %d to %d", 1035 slog (L_NOISE, "%s >> received packet type %d from %d to %d.",
960 conf->id, pkt->typ (), pkt->src (), pkt->dst ()); 1036 conf->nodename, pkt->typ (), pkt->src (), pkt->dst ());
961 1037
962 if (connectmode == conf_node::C_DISABLED) 1038 if (connectmode == conf_node::C_DISABLED)
963 return; 1039 return;
964 1040
965 switch (pkt->typ ()) 1041 switch (pkt->typ ())
966 { 1042 {
967 case vpn_packet::PT_PING: 1043 case vpn_packet::PT_PING:
1044 slog (L_TRACE, "%s >> PT_PING", conf->nodename);
1045
968 // we send pings instead of auth packets after some retries, 1046 // we send pings instead of auth packets after some retries,
969 // so reset the retry counter and establish a connection 1047 // so reset the retry counter and establish a connection
970 // when we receive a ping. 1048 // when we receive a ping.
971 if (!ictx) 1049 if (!ictx)
972 { 1050 {
973 if (auth_rate_limiter.can (rsi)) 1051 if (auth_rate_limiter.can (rsi))
974 send_auth_request (rsi, true); 1052 send_auth_request (rsi, true);
975 } 1053 }
976 else 1054 else
1055 // we would love to change the socket address here, but ping's aren't
1056 // authenticated, so we best ignore it.
977 send_ping (rsi, 1); // pong 1057 send_ping (rsi, 1); // pong
978 1058
979 break; 1059 break;
980 1060
981 case vpn_packet::PT_PONG: 1061 case vpn_packet::PT_PONG:
1062 slog (L_TRACE, "%s >> PT_PONG", conf->nodename);
1063
1064 // a PONG might mean that the other side doesn't really know
1065 // about our desire for communication.
1066 establish_connection ();
982 break; 1067 break;
983 1068
984 case vpn_packet::PT_RESET: 1069 case vpn_packet::PT_RESET:
1070 slog (L_TRACE, "%s >> PT_RESET", conf->nodename);
1071
1072 if (ictx && octx)
985 { 1073 {
986 reset_connection (); 1074 reset_connection ("remote reset");
987 1075
988 config_packet *p = (config_packet *) pkt; 1076 config_packet *p = (config_packet *) pkt;
989 1077
990 if (!p->chk_config ()) 1078 if (p->chk_config (conf, rsi) && connectmode == conf_node::C_ALWAYS)
991 {
992 slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
993 conf->nodename, (const char *)rsi);
994 connectmode = conf_node::C_DISABLED;
995 }
996 else if (connectmode == conf_node::C_ALWAYS)
997 establish_connection (); 1079 establish_connection ();
998 } 1080 }
1081
999 break; 1082 break;
1000 1083
1001 case vpn_packet::PT_AUTH_REQ: 1084 case vpn_packet::PT_AUTH_REQ:
1002 if (auth_rate_limiter.can (rsi)) 1085 if (auth_rate_limiter.can (rsi))
1003 { 1086 {
1004 auth_req_packet *p = (auth_req_packet *) pkt; 1087 auth_req_packet *p = (auth_req_packet *)pkt;
1005 1088
1006 slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate); 1089 slog (L_TRACE, "%s >> PT_AUTH_REQ(%s,p%02x,f%02x)",
1090 conf->nodename, p->initiate ? "initiate" : "reply",
1091 p->protocols, p->features);
1007 1092
1008 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8)) 1093 if (memcmp (p->magic, MAGIC, 8))
1094 {
1095 slog (L_WARN, _("%s(%s): protocol magic mismatch - stray packet?"),
1096 conf->nodename, (const char *)rsi);
1097 }
1098 else if (p->chk_config (conf, rsi))
1009 { 1099 {
1010 if (p->prot_minor != PROTOCOL_MINOR) 1100 if (p->prot_minor != PROTOCOL_MINOR)
1011 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."), 1101 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
1012 conf->nodename, (const char *)rsi, 1102 conf->nodename, (const char *)rsi,
1013 PROTOCOL_MINOR, conf->nodename, p->prot_minor); 1103 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
1014 1104
1015 if (p->initiate) 1105 if (p->initiate)
1106 {
1016 send_auth_request (rsi, false); 1107 send_auth_request (rsi, false);
1017 1108
1018 rsachallenge k; 1109 if (ictx && octx)
1110 reset_connection ("reconnect");
1111 }
1019 1112
1113 auth_data auth;
1114
1020 if (!rsa_decrypt (::conf.rsa_key, p->encr, k)) 1115 if (!auth_decrypt (::conf.rsa_key, p->encr, auth))
1021 { 1116 {
1022 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"), 1117 slog (L_ERR, _("%s(%s): challenge illegal or corrupted (%s). mismatched key or config file?"),
1023 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0)); 1118 conf->nodename, (const char *)rsi, ERR_error_string (ERR_get_error (), 0));
1024 break;
1025 } 1119 }
1026 else 1120 else
1027 { 1121 {
1028 delete octx; 1122 bool chg = !have_rcv_auth || !slow_memeq (&rcv_auth, &auth, sizeof auth);
1029 1123
1030 octx = new crypto_ctx (k, 1); 1124 rcv_auth = auth;
1031 oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff; 1125 have_rcv_auth = true;
1032 1126
1127 send_auth_response (rsi);
1128
1129 if (chg)
1130 {
1033 conf->protocols = p->protocols; 1131 conf->protocols = p->protocols;
1034 features = p->features & config_packet::get_features (); 1132 features = p->features & config_packet::get_features ();
1035 1133
1036 send_auth_response (rsi, p->id, k);
1037
1038 connection_established (); 1134 connection_established (rsi);
1039
1040 break; 1135 }
1041 } 1136 }
1137
1138 break;
1042 } 1139 }
1043 else
1044 slog (L_WARN, _("%s(%s): protocol mismatch"),
1045 conf->nodename, (const char *)rsi);
1046 1140
1047 send_reset (rsi); 1141 send_reset (rsi);
1048 } 1142 }
1049 1143
1050 break; 1144 break;
1051 1145
1052 case vpn_packet::PT_AUTH_RES: 1146 case vpn_packet::PT_AUTH_RES:
1053 { 1147 {
1054 auth_res_packet *p = (auth_res_packet *) pkt; 1148 auth_res_packet *p = (auth_res_packet *)pkt;
1055 1149
1056 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id); 1150 slog (L_TRACE, "%s >> PT_AUTH_RES", conf->nodename);
1057 1151
1058 if (p->chk_config ()) 1152 auth_mac local_mac;
1153 auth_hash (snd_auth, p->response.ecdh, local_mac);
1154
1155 if (!slow_memeq (&p->response.mac, local_mac, sizeof local_mac))
1059 { 1156 {
1060 if (p->prot_minor != PROTOCOL_MINOR)
1061 slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
1062 conf->nodename, (const char *)rsi,
1063 PROTOCOL_MINOR, conf->nodename, p->prot_minor);
1064
1065 rsachallenge chg;
1066
1067 if (!rsa_cache.find (p->id, chg))
1068 {
1069 slog (L_ERR, _("%s(%s): unrequested auth response ignored"), 1157 slog (L_ERR, _("%s(%s): unrequested or outdated auth response, ignoring."),
1070 conf->nodename, (const char *)rsi); 1158 conf->nodename, (const char *)rsi);
1071 break;
1072 } 1159 }
1073 else 1160 else if (!have_snd_auth)
1074 { 1161 {
1075 crypto_ctx *cctx = new crypto_ctx (chg, 0); 1162 memcpy (snd_ecdh_b, p->response.ecdh, sizeof snd_ecdh_b);
1076 1163
1077 if (!p->hmac_chk (cctx)) 1164 have_snd_auth = true;
1078 {
1079 slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
1080 "could be an attack, or just corruption or a synchronization error"),
1081 conf->nodename, (const char *)rsi);
1082 break;
1083 }
1084 else
1085 {
1086 rsaresponse h;
1087
1088 rsa_hash (p->id, chg, h);
1089
1090 if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
1091 {
1092 prot_minor = p->prot_minor;
1093
1094 delete ictx; ictx = cctx;
1095
1096 iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
1097
1098 si = rsi;
1099 protocol = rsi.prot;
1100
1101 connection_established (); 1165 connection_established (rsi);
1102
1103 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
1104 conf->nodename, (const char *)rsi,
1105 p->prot_major, p->prot_minor);
1106
1107 if (::conf.script_node_up)
1108 {
1109 run_script_cb cb;
1110 cb.set<connection, &connection::script_node_up> (this);
1111 if (!run_script (cb, false))
1112 slog (L_WARN, _("node-up command execution failed, continuing."));
1113 }
1114
1115 break;
1116 }
1117 else
1118 slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
1119 conf->nodename, (const char *)rsi);
1120 }
1121
1122 delete cctx;
1123 }
1124 } 1166 }
1125 } 1167 }
1126
1127 send_reset (rsi);
1128 break; 1168 break;
1129 1169
1130 case vpn_packet::PT_DATA_COMPRESSED: 1170 case vpn_packet::PT_DATA_COMPRESSED:
1131#if !ENABLE_COMPRESSION 1171#if !ENABLE_COMPRESSION
1132 send_reset (rsi); 1172 send_reset (rsi);
1138 if (ictx && octx) 1178 if (ictx && octx)
1139 { 1179 {
1140 vpndata_packet *p = (vpndata_packet *)pkt; 1180 vpndata_packet *p = (vpndata_packet *)pkt;
1141 1181
1142 if (!p->hmac_chk (ictx)) 1182 if (!p->hmac_chk (ictx))
1183 {
1184 // rekeying often creates temporary hmac auth floods
1185 // we assume they don't take longer than a few seconds normally,
1186 // and suppress messages and resets during that time.
1187 //TODO: should be done per source address
1188 if (!hmac_error)
1189 {
1190 hmac_error = ev_now () + 3;
1191 break;
1192 }
1193 else if (hmac_error >= ev_now ())
1194 break; // silently suppress
1195 else
1196 {
1143 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n" 1197 slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
1144 "could be an attack, or just corruption or a synchronization error"), 1198 "could be an attack, or just corruption or a synchronization error."),
1145 conf->nodename, (const char *)rsi); 1199 conf->nodename, (const char *)rsi);
1200 // reset
1201 }
1202 }
1146 else 1203 else
1147 { 1204 {
1148 u32 seqno; 1205 u32 seqno;
1149 tap_packet *d = p->unpack (this, seqno); 1206 tap_packet *d = p->unpack (this, seqno);
1207 int seqclass = iseqno.seqno_classify (seqno);
1150 1208
1151 if (iseqno.recv_ok (seqno)) 1209 hmac_error = 0;
1210
1211 if (seqclass == 0) // ok
1152 { 1212 {
1153 vpn->tap->send (d); 1213 vpn->tap->send (d);
1154 1214
1155 if (si != rsi) 1215 if (si != rsi)
1156 { 1216 {
1157 // fast re-sync on source address changes, useful especially for tcp/ip 1217 // fast re-sync on source address changes, useful especially for tcp/ip
1218 //if (last_si_change < ev_now () + 5.)
1158 si = rsi; 1219 // {
1159
1160 slog (L_INFO, _("%s(%s): socket address changed to %s"), 1220 slog (L_INFO, _("%s(%s): changing socket address to %s."),
1161 conf->nodename, (const char *)si, (const char *)rsi); 1221 conf->nodename, (const char *)si, (const char *)rsi);
1222
1223 si = rsi;
1224
1225 if (::conf.script_node_change)
1226 {
1227 run_script_cb *cb = new run_script_cb;
1228 cb->set<connection, &connection::script_node_change> (this);
1229 run_script_queued (cb, _("node-change command execution failed, continuing."));
1230 }
1231
1232 // }
1233 //else
1234 // slog (L_INFO, _("%s(%s): accepted packet from %s, not (yet) redirecting traffic."),
1235 // conf->nodename, (const char *)si, (const char *)rsi);
1162 } 1236 }
1237 }
1238 else if (seqclass == 1) // far history
1239 slog (L_ERR, _("received very old packet (received %08lx, expected %08lx). "
1240 "possible replay attack, or just packet duplication/delay, ignoring."), seqno, iseqno.seq + 1);
1241 else if (seqclass == 2) // in-window duplicate, happens often on wireless
1242 slog (L_DEBUG, _("received recent duplicated packet (received %08lx, expected %08lx). "
1243 "possible replay attack, or just packet duplication, ignoring."), seqno, iseqno.seq + 1);
1244 else if (seqclass == 3) // reset
1245 {
1246 slog (L_ERR, _("received out-of-sync (far future) packet (received %08lx, expected %08lx). "
1247 "probably just massive packet loss, sending reset."), seqno, iseqno.seq + 1);
1248 send_reset (rsi);
1163 } 1249 }
1164 1250
1165 delete d; 1251 delete d;
1166 break; 1252 break;
1167 } 1253 }
1171 break; 1257 break;
1172 1258
1173 case vpn_packet::PT_CONNECT_REQ: 1259 case vpn_packet::PT_CONNECT_REQ:
1174 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx)) 1260 if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1175 { 1261 {
1176 connect_req_packet *p = (connect_req_packet *) pkt; 1262 connect_req_packet *p = (connect_req_packet *)pkt;
1177 1263
1178 if (p->id > 0 && p->id <= vpn->conns.size ()) 1264 if (p->id > 0 && p->id <= vpn->conns.size ())
1179 { 1265 {
1180 connection *c = vpn->conns[p->id - 1]; 1266 connection *c = vpn->conns[p->id - 1];
1181 conf->protocols = p->protocols; 1267 conf->protocols = p->protocols;
1182 1268
1183 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]", 1269 slog (L_TRACE, "%s >> PT_CONNECT_REQ(%s,p%02x) [%d]",
1270 conf->nodename, vpn->conns[p->id - 1]->conf->nodename,
1271 p->protocols,
1184 conf->id, p->id, c->ictx && c->octx); 1272 c->ictx && c->octx);
1185 1273
1186 if (c->ictx && c->octx) 1274 if (c->ictx && c->octx)
1187 { 1275 {
1188 // send connect_info packets to both sides, in case one is 1276 // send connect_info packets to both sides, in case one is
1189 // behind a nat firewall (or both ;) 1277 // behind a nat firewall (or both ;)
1212 1300
1213 c->conf->protocols = p->protocols; 1301 c->conf->protocols = p->protocols;
1214 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf)); 1302 protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1215 p->si.upgrade_protocol (protocol, c->conf); 1303 p->si.upgrade_protocol (protocol, c->conf);
1216 1304
1217 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)", 1305 slog (L_TRACE, "%s >> PT_CONNECT_INFO(%s,%s,protocols=%02x,protocol=%02x,upgradable=%02x) [%d]",
1218 conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx); 1306 conf->nodename,
1307 vpn->conns[p->id - 1]->conf->nodename,
1308 (const char *)p->si,
1309 p->protocols,
1310 protocol,
1311 p->si.supported_protocols (c->conf),
1312 !c->ictx && !c->octx);
1219 1313
1220 const sockinfo &dsi = forward_si (p->si); 1314 const sockinfo &dsi = forward_si (p->si);
1221 1315
1222 if (dsi.valid ()) 1316 if (dsi.valid ())
1223 c->send_auth_request (dsi, true); 1317 c->send_auth_request (dsi, true);
1318 else
1319 slog (L_INFO, "connect info for %s received (%s), but still unable to contact.",
1320 vpn->conns[p->id - 1]->conf->nodename,
1321 (const char *)p->si);
1224 } 1322 }
1225 else 1323 else
1226 slog (L_WARN, 1324 slog (L_WARN,
1227 _("received authenticated connection request from unknown node #%d, config file mismatch?"), 1325 _("received authenticated connection request from unknown node #%d, config file mismatch?"),
1228 p->id); 1326 p->id);
1237} 1335}
1238 1336
1239inline void 1337inline void
1240connection::keepalive_cb (ev::timer &w, int revents) 1338connection::keepalive_cb (ev::timer &w, int revents)
1241{ 1339{
1242 if (ev_now () >= last_activity + ::conf.keepalive + 30) 1340 ev_tstamp when = last_activity + ::conf.keepalive - ev::now ();
1341
1342 if (when >= 0)
1343 w.start (when);
1344 else if (when < -15)
1243 { 1345 {
1244 reset_connection (); 1346 reset_connection ("keepalive overdue");
1245 establish_connection (); 1347 establish_connection ();
1246 } 1348 }
1247 else if (ev_now () < last_activity + ::conf.keepalive)
1248 w.start (last_activity + ::conf.keepalive - ev::now ());
1249 else if (conf->connectmode != conf_node::C_ONDEMAND 1349 else if (conf->connectmode != conf_node::C_ONDEMAND
1250 || THISNODE->connectmode != conf_node::C_ONDEMAND) 1350 || THISNODE->connectmode != conf_node::C_ONDEMAND)
1251 { 1351 {
1352 w.start (3);
1252 send_ping (si); 1353 send_ping (si);
1253 w.start (5);
1254 } 1354 }
1255 else if (ev_now () < last_activity + ::conf.keepalive + 10) 1355 else if (when >= -10)
1256 // hold ondemand connections implicitly a few seconds longer 1356 // hold ondemand connections implicitly a few seconds longer
1257 // should delete octx, though, or something like that ;) 1357 // should delete octx, though, or something like that ;)
1258 w.start (last_activity + ::conf.keepalive + 10 - ev::now ()); 1358 w.start (when + 10);
1259 else 1359 else
1260 reset_connection (); 1360 reset_connection ("keepalive timeout");
1261} 1361}
1262 1362
1363void
1263void connection::send_connect_request (int id) 1364connection::send_connect_request (int id)
1264{ 1365{
1265 connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols); 1366 connect_req_packet *p = new connect_req_packet (conf->id, id, THISNODE->protocols);
1266 1367
1267 slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id); 1368 slog (L_TRACE, "%s << PT_CONNECT_REQ(%s,p%02x)",
1369 conf->nodename, vpn->conns[id - 1]->conf->nodename,
1370 THISNODE->protocols);
1268 p->hmac_set (octx); 1371 p->hmac_set (octx);
1269 send_vpn_packet (p, si); 1372 send_vpn_packet (p, si);
1270 1373
1271 delete p; 1374 delete p;
1272} 1375}
1273 1376
1377void
1274void connection::script_init_env (const char *ext) 1378connection::script_init_env (const char *ext)
1275{ 1379{
1276 char *env; 1380 char *env;
1277 asprintf (&env, "IFUPDATA%s=%s", ext, conf->if_up_data); putenv (env); 1381 asprintf (&env, "IFUPDATA%s=%s", ext, conf->if_up_data); putenv (env);
1278 asprintf (&env, "NODENAME%s=%s", ext, conf->nodename); putenv (env); 1382 asprintf (&env, "NODENAME%s=%s", ext, conf->nodename); putenv (env);
1279 asprintf (&env, "MAC%s=%02x:%02x:%02x:%02x:%02x:%02x", ext, 1383 asprintf (&env, "MAC%s=%02x:%02x:%02x:%02x:%02x:%02x", ext,
1280 0xfe, 0xfd, 0x80, 0x00, conf->id >> 8, 1384 0xfe, 0xfd, 0x80, 0x00, conf->id >> 8,
1281 conf->id & 0xff); putenv (env); 1385 conf->id & 0xff); putenv (env);
1282} 1386}
1283 1387
1388void
1284void connection::script_init_connect_env () 1389connection::script_init_connect_env ()
1285{ 1390{
1286 vpn->script_init_env (); 1391 vpn->script_init_env ();
1287 1392
1288 char *env; 1393 char *env;
1289 asprintf (&env, "DESTID=%d", conf->id); putenv (env); 1394 asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1395 asprintf (&env, "DESTSI=%s", (const char *)si); putenv (env);
1290 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env); 1396 asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1291 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env); 1397 asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1292 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env); 1398 asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1293} 1399}
1294 1400
1295inline const char * 1401inline const char *
1296connection::script_node_up () 1402connection::script_node_up ()
1297{ 1403{
1307 1413
1308 return filename; 1414 return filename;
1309} 1415}
1310 1416
1311inline const char * 1417inline const char *
1418connection::script_node_change ()
1419{
1420 script_init_connect_env ();
1421
1422 putenv ((char *)"STATE=change");
1423
1424 char *filename;
1425 asprintf (&filename,
1426 "%s/%s",
1427 confbase,
1428 ::conf.script_node_change ? ::conf.script_node_change : "node-change");
1429
1430 return filename;
1431}
1432
1433inline const char *
1312connection::script_node_down () 1434connection::script_node_down ()
1313{ 1435{
1314 script_init_connect_env (); 1436 script_init_connect_env ();
1315 1437
1316 putenv ((char *)"STATE=down"); 1438 putenv ((char *)"STATE=down");
1327connection::connection (struct vpn *vpn, conf_node *conf) 1449connection::connection (struct vpn *vpn, conf_node *conf)
1328: vpn(vpn), conf(conf), 1450: vpn(vpn), conf(conf),
1329#if ENABLE_DNS 1451#if ENABLE_DNS
1330 dns (0), 1452 dns (0),
1331#endif 1453#endif
1332 data_queue(conf->max_ttl, conf->max_queue), 1454 data_queue(conf->max_ttl, conf->max_queue + 1),
1333 vpn_queue(conf->max_ttl, conf->max_queue) 1455 vpn_queue(conf->max_ttl, conf->max_queue + 1)
1334{ 1456{
1335 rekey .set<connection, &connection::rekey_cb > (this); 1457 rekey .set<connection, &connection::rekey_cb > (this);
1336 keepalive .set<connection, &connection::keepalive_cb > (this); 1458 keepalive .set<connection, &connection::keepalive_cb > (this);
1337 establish_connection.set<connection, &connection::establish_connection_cb> (this); 1459 establish_connection.set<connection, &connection::establish_connection_cb> (this);
1338 1460
1339 last_establish_attempt = 0.; 1461 last_establish_attempt = 0.;
1340 octx = ictx = 0; 1462 octx = ictx = 0;
1341 1463
1342 if (!conf->protocols) // make sure some protocol is enabled
1343 conf->protocols = PROT_UDPv4;
1344
1345 connectmode = conf->connectmode; 1464 connectmode = conf->connectmode;
1346 1465
1347 // queue a dummy packet to force an initial connection attempt 1466 // queue a dummy packet to force an initial connection attempt
1348 if (connectmode != conf_node::C_ALWAYS && connectmode != conf_node::C_DISABLED) 1467 if (connectmode != conf_node::C_ALWAYS && connectmode != conf_node::C_DISABLED)
1349 vpn_queue.put (new net_packet); 1468 vpn_queue.put (new net_packet);
1350 1469
1351 reset_connection (); 1470 reset_connection ("startup");
1352} 1471}
1353 1472
1354connection::~connection () 1473connection::~connection ()
1355{ 1474{
1356 shutdown (); 1475 shutdown ();
1357} 1476}
1358 1477
1478void
1359void connection_init () 1479connection_init ()
1360{ 1480{
1361 auth_rate_limiter.clear (); 1481 auth_rate_limiter.clear ();
1362 reset_rate_limiter.clear (); 1482 reset_rate_limiter.clear ();
1363} 1483}
1364 1484

Diff Legend

Removed lines
+ Added lines
< Changed lines
> Changed lines