ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/connection.C
Revision: 1.11
Committed: Sun Apr 13 00:35:46 2003 UTC (21 years, 1 month ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.10: +2 -0 lines
Log Message:
*** empty log message ***

File Contents

# User Rev Content
1 pcg 1.1 /*
2     connection.C -- manage a single connection
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     extern "C" {
22     # include "lzf/lzf.h"
23     }
24    
25     #include <list>
26    
27 pcg 1.2 #include <openssl/rand.h>
28     #include <openssl/evp.h>
29     #include <openssl/rsa.h>
30     #include <openssl/err.h>
31    
32 pcg 1.1 #include "gettext.h"
33    
34     #include "conf.h"
35     #include "slog.h"
36     #include "device.h"
37 pcg 1.2 #include "vpn.h"
38 pcg 1.1 #include "connection.h"
39    
40     #if !HAVE_RAND_PSEUDO_BYTES
41     # define RAND_pseudo_bytes RAND_bytes
42     #endif
43    
44     #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic
45    
46     struct crypto_ctx
47     {
48     EVP_CIPHER_CTX cctx;
49     HMAC_CTX hctx;
50    
51     crypto_ctx (const rsachallenge &challenge, int enc);
52     ~crypto_ctx ();
53     };
54    
55     crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc)
56     {
57     EVP_CIPHER_CTX_init (&cctx);
58     EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc);
59     HMAC_CTX_init (&hctx);
60     HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0);
61     }
62    
63     crypto_ctx::~crypto_ctx ()
64     {
65     EVP_CIPHER_CTX_cleanup (&cctx);
66     HMAC_CTX_cleanup (&hctx);
67     }
68    
69     static void
70     rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h)
71     {
72     EVP_MD_CTX ctx;
73    
74     EVP_MD_CTX_init (&ctx);
75     EVP_DigestInit (&ctx, RSA_HASH);
76     EVP_DigestUpdate(&ctx, &chg, sizeof chg);
77     EVP_DigestUpdate(&ctx, &id, sizeof id);
78     EVP_DigestFinal (&ctx, (unsigned char *)&h, 0);
79     EVP_MD_CTX_cleanup (&ctx);
80     }
81    
82     struct rsa_entry {
83     tstamp expire;
84     rsaid id;
85     rsachallenge chg;
86     };
87    
88     struct rsa_cache : list<rsa_entry>
89     {
90 pcg 1.4 void cleaner_cb (time_watcher &w); time_watcher cleaner;
91 pcg 1.1
92     bool find (const rsaid &id, rsachallenge &chg)
93     {
94     for (iterator i = begin (); i != end (); ++i)
95     {
96     if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW)
97     {
98     memcpy (&chg, &i->chg, sizeof chg);
99    
100     erase (i);
101     return true;
102     }
103     }
104    
105     if (cleaner.at < NOW)
106     cleaner.start (NOW + RSA_TTL);
107    
108     return false;
109     }
110    
111     void gen (rsaid &id, rsachallenge &chg)
112     {
113     rsa_entry e;
114    
115     RAND_bytes ((unsigned char *)&id, sizeof id);
116     RAND_bytes ((unsigned char *)&chg, sizeof chg);
117    
118     e.expire = NOW + RSA_TTL;
119     e.id = id;
120     memcpy (&e.chg, &chg, sizeof chg);
121    
122     push_back (e);
123    
124     if (cleaner.at < NOW)
125     cleaner.start (NOW + RSA_TTL);
126     }
127    
128     rsa_cache ()
129     : cleaner (this, &rsa_cache::cleaner_cb)
130     { }
131    
132     } rsa_cache;
133    
134 pcg 1.4 void rsa_cache::cleaner_cb (time_watcher &w)
135 pcg 1.1 {
136     if (empty ())
137 pcg 1.4 w.at = TSTAMP_CANCEL;
138 pcg 1.1 else
139     {
140 pcg 1.4 w.at = NOW + RSA_TTL;
141 pcg 1.1
142     for (iterator i = begin (); i != end (); )
143     if (i->expire <= NOW)
144     i = erase (i);
145     else
146     ++i;
147     }
148     }
149    
150     //////////////////////////////////////////////////////////////////////////////
151    
152     void pkt_queue::put (tap_packet *p)
153     {
154     if (queue[i])
155     {
156     delete queue[i];
157     j = (j + 1) % QUEUEDEPTH;
158     }
159    
160     queue[i] = p;
161    
162     i = (i + 1) % QUEUEDEPTH;
163     }
164    
165     tap_packet *pkt_queue::get ()
166     {
167     tap_packet *p = queue[j];
168    
169     if (p)
170     {
171     queue[j] = 0;
172     j = (j + 1) % QUEUEDEPTH;
173     }
174    
175     return p;
176     }
177    
178     pkt_queue::pkt_queue ()
179     {
180     memset (queue, 0, sizeof (queue));
181     i = 0;
182     j = 0;
183     }
184    
185     pkt_queue::~pkt_queue ()
186     {
187     for (i = QUEUEDEPTH; --i > 0; )
188     delete queue[i];
189     }
190    
191     struct net_rateinfo {
192     u32 host;
193     double pcnt, diff;
194     tstamp last;
195     };
196    
197     // only do action once every x seconds per host whole allowing bursts.
198     // this implementation ("splay list" ;) is inefficient,
199     // but low on resources.
200     struct net_rate_limiter : list<net_rateinfo>
201     {
202 pcg 1.9 static const double ALPHA = 1. - 1. / 180.; // allow bursts
203     static const double CUTOFF = 10.; // one event every CUTOFF seconds
204     static const double EXPIRE = CUTOFF * 30.; // expire entries after this time
205 pcg 1.10 static const double MAXDIF = CUTOFF * (1. / (1. - ALPHA)); // maximum diff /count value
206 pcg 1.1
207     bool can (const sockinfo &si) { return can((u32)si.host); }
208     bool can (u32 host);
209     };
210    
211     net_rate_limiter auth_rate_limiter, reset_rate_limiter;
212    
213     bool net_rate_limiter::can (u32 host)
214     {
215     iterator i;
216    
217     for (i = begin (); i != end (); )
218     if (i->host == host)
219     break;
220     else if (i->last < NOW - EXPIRE)
221     i = erase (i);
222     else
223     i++;
224    
225     if (i == end ())
226     {
227     net_rateinfo ri;
228    
229     ri.host = host;
230     ri.pcnt = 1.;
231 pcg 1.10 ri.diff = MAXDIF;
232 pcg 1.1 ri.last = NOW;
233    
234     push_front (ri);
235    
236     return true;
237     }
238     else
239     {
240     net_rateinfo ri (*i);
241     erase (i);
242    
243     ri.pcnt = ri.pcnt * ALPHA;
244     ri.diff = ri.diff * ALPHA + (NOW - ri.last);
245    
246     ri.last = NOW;
247    
248 pcg 1.10 double dif = ri.diff / ri.pcnt;
249 pcg 1.1
250 pcg 1.10 bool send = dif > CUTOFF;
251    
252     if (dif > MAXDIF)
253     {
254     ri.pcnt = 1.;
255     ri.diff = MAXDIF;
256     }
257     else if (send)
258 pcg 1.1 ri.pcnt++;
259    
260     push_front (ri);
261    
262     return send;
263     }
264     }
265    
266     /////////////////////////////////////////////////////////////////////////////
267    
268     unsigned char hmac_packet::hmac_digest[EVP_MAX_MD_SIZE];
269    
270     void hmac_packet::hmac_gen (crypto_ctx *ctx)
271     {
272     unsigned int xlen;
273    
274     HMAC_CTX *hctx = &ctx->hctx;
275    
276     HMAC_Init_ex (hctx, 0, 0, 0, 0);
277     HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet),
278     len - sizeof (hmac_packet));
279     HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen);
280     }
281    
282     void
283     hmac_packet::hmac_set (crypto_ctx *ctx)
284     {
285     hmac_gen (ctx);
286    
287     memcpy (hmac, hmac_digest, HMACLENGTH);
288     }
289    
290     bool
291     hmac_packet::hmac_chk (crypto_ctx *ctx)
292     {
293     hmac_gen (ctx);
294    
295     return !memcmp (hmac, hmac_digest, HMACLENGTH);
296     }
297    
298 pcg 1.6 void vpn_packet::set_hdr (ptype type_, unsigned int dst)
299 pcg 1.1 {
300 pcg 1.6 type = type_;
301 pcg 1.1
302     int src = THISNODE->id;
303    
304     src1 = src;
305     srcdst = ((src >> 8) << 4) | (dst >> 8);
306     dst1 = dst;
307     }
308    
309     #define MAXVPNDATA (MAX_MTU - 6 - 6)
310     #define DATAHDR (sizeof (u32) + RAND_SIZE)
311    
312     struct vpndata_packet:vpn_packet
313     {
314     u8 data[MAXVPNDATA + DATAHDR]; // seqno
315    
316     void setup (connection *conn, int dst, u8 *d, u32 len, u32 seqno);
317     tap_packet *unpack (connection *conn, u32 &seqno);
318     private:
319    
320     const u32 data_hdr_size () const
321     {
322     return sizeof (vpndata_packet) - sizeof (net_packet) - MAXVPNDATA - DATAHDR;
323     }
324     };
325    
326     void
327     vpndata_packet::setup (connection *conn, int dst, u8 *d, u32 l, u32 seqno)
328     {
329     EVP_CIPHER_CTX *cctx = &conn->octx->cctx;
330     int outl = 0, outl2;
331     ptype type = PT_DATA_UNCOMPRESSED;
332    
333     #if ENABLE_COMPRESSION
334     u8 cdata[MAX_MTU];
335     u32 cl;
336    
337     cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7);
338     if (cl)
339     {
340     type = PT_DATA_COMPRESSED;
341     d = cdata;
342     l = cl + 2;
343    
344     d[0] = cl >> 8;
345     d[1] = cl;
346     }
347     #endif
348    
349     EVP_EncryptInit_ex (cctx, 0, 0, 0, 0);
350    
351     struct {
352     #if RAND_SIZE
353     u8 rnd[RAND_SIZE];
354     #endif
355     u32 seqno;
356     } datahdr;
357    
358     datahdr.seqno = ntohl (seqno);
359     #if RAND_SIZE
360     RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE);
361     #endif
362    
363     EVP_EncryptUpdate (cctx,
364     (unsigned char *) data + outl, &outl2,
365     (unsigned char *) &datahdr, DATAHDR);
366     outl += outl2;
367    
368     EVP_EncryptUpdate (cctx,
369     (unsigned char *) data + outl, &outl2,
370     (unsigned char *) d, l);
371     outl += outl2;
372    
373     EVP_EncryptFinal_ex (cctx, (unsigned char *) data + outl, &outl2);
374     outl += outl2;
375    
376     len = outl + data_hdr_size ();
377    
378     set_hdr (type, dst);
379    
380     hmac_set (conn->octx);
381     }
382    
383     tap_packet *
384     vpndata_packet::unpack (connection *conn, u32 &seqno)
385     {
386     EVP_CIPHER_CTX *cctx = &conn->ictx->cctx;
387     int outl = 0, outl2;
388     tap_packet *p = new tap_packet;
389     u8 *d;
390     u32 l = len - data_hdr_size ();
391    
392     EVP_DecryptInit_ex (cctx, 0, 0, 0, 0);
393    
394     #if ENABLE_COMPRESSION
395     u8 cdata[MAX_MTU];
396    
397     if (type == PT_DATA_COMPRESSED)
398     d = cdata;
399     else
400     #endif
401     d = &(*p)[6 + 6 - DATAHDR];
402    
403     /* this overwrites part of the src mac, but we fix that later */
404     EVP_DecryptUpdate (cctx,
405     d, &outl2,
406     (unsigned char *)&data, len - data_hdr_size ());
407     outl += outl2;
408    
409     EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2);
410     outl += outl2;
411    
412     seqno = ntohl (*(u32 *)(d + RAND_SIZE));
413    
414     id2mac (dst () ? dst() : THISNODE->id, p->dst);
415     id2mac (src (), p->src);
416    
417     #if ENABLE_COMPRESSION
418     if (type == PT_DATA_COMPRESSED)
419     {
420     u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1];
421    
422     p->len = lzf_decompress (d + DATAHDR + 2, cl < MAX_MTU ? cl : 0,
423     &(*p)[6 + 6], MAX_MTU)
424     + 6 + 6;
425     }
426     else
427     p->len = outl + (6 + 6 - DATAHDR);
428     #endif
429    
430     return p;
431     }
432    
433     struct ping_packet : vpn_packet
434     {
435     void setup (int dst, ptype type)
436     {
437     set_hdr (type, dst);
438     len = sizeof (*this) - sizeof (net_packet);
439     }
440     };
441    
442     struct config_packet : vpn_packet
443     {
444     // actually, hmaclen cannot be checked because the hmac
445     // field comes before this data, so peers with other
446     // hmacs simply will not work.
447     u8 prot_major, prot_minor, randsize, hmaclen;
448     u8 flags, challengelen, pad2, pad3;
449     u32 cipher_nid, digest_nid, hmac_nid;
450    
451     const u8 curflags () const
452     {
453     return 0x80
454     | (ENABLE_COMPRESSION ? 0x01 : 0x00);
455     }
456    
457     void setup (ptype type, int dst);
458     bool chk_config () const;
459     };
460    
461     void config_packet::setup (ptype type, int dst)
462     {
463     prot_major = PROTOCOL_MAJOR;
464     prot_minor = PROTOCOL_MINOR;
465     randsize = RAND_SIZE;
466     hmaclen = HMACLENGTH;
467     flags = curflags ();
468     challengelen = sizeof (rsachallenge);
469    
470     cipher_nid = htonl (EVP_CIPHER_nid (CIPHER));
471     digest_nid = htonl (EVP_MD_type (RSA_HASH));
472     hmac_nid = htonl (EVP_MD_type (DIGEST));
473    
474     len = sizeof (*this) - sizeof (net_packet);
475     set_hdr (type, dst);
476     }
477    
478     bool config_packet::chk_config () const
479     {
480     return prot_major == PROTOCOL_MAJOR
481     && randsize == RAND_SIZE
482     && hmaclen == HMACLENGTH
483     && flags == curflags ()
484     && challengelen == sizeof (rsachallenge)
485     && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER))
486     && digest_nid == htonl (EVP_MD_type (RSA_HASH))
487     && hmac_nid == htonl (EVP_MD_type (DIGEST));
488     }
489    
490     struct auth_req_packet : config_packet
491     {
492     char magic[8];
493     u8 initiate; // false if this is just an automatic reply
494     u8 protocols; // supported protocols (will get patches on forward)
495     u8 pad2, pad3;
496     rsaid id;
497     rsaencrdata encr;
498    
499     auth_req_packet (int dst, bool initiate_, u8 protocols_)
500     {
501     config_packet::setup (PT_AUTH_REQ, dst);
502     strncpy (magic, MAGIC, 8);
503     initiate = !!initiate_;
504     protocols = protocols_;
505    
506     len = sizeof (*this) - sizeof (net_packet);
507     }
508     };
509    
510     struct auth_res_packet : config_packet
511     {
512     rsaid id;
513     u8 pad1, pad2, pad3;
514     u8 response_len; // encrypted length
515     rsaresponse response;
516    
517     auth_res_packet (int dst)
518     {
519     config_packet::setup (PT_AUTH_RES, dst);
520    
521     len = sizeof (*this) - sizeof (net_packet);
522     }
523     };
524    
525     struct connect_req_packet : vpn_packet
526     {
527     u8 id, protocols;
528     u8 pad1, pad2;
529    
530     connect_req_packet (int dst, int id_, u8 protocols_)
531     : id(id_)
532     , protocols(protocols_)
533     {
534     set_hdr (PT_CONNECT_REQ, dst);
535     len = sizeof (*this) - sizeof (net_packet);
536     }
537     };
538    
539     struct connect_info_packet : vpn_packet
540     {
541     u8 id, protocols;
542     u8 pad1, pad2;
543     sockinfo si;
544    
545     connect_info_packet (int dst, int id_, const sockinfo &si_, u8 protocols_)
546     : id(id_)
547     , protocols(protocols_)
548     , si(si_)
549     {
550     set_hdr (PT_CONNECT_INFO, dst);
551    
552     len = sizeof (*this) - sizeof (net_packet);
553     }
554     };
555    
556     /////////////////////////////////////////////////////////////////////////////
557    
558     void
559 pcg 1.10 connection::connection_established ()
560     {
561     if (ictx && octx)
562     {
563     connectmode = conf->connectmode;
564    
565     rekey.start (NOW + ::conf.rekey);
566     keepalive.start (NOW + ::conf.keepalive);
567    
568     // send queued packets
569     if (ictx && octx)
570     while (tap_packet *p = queue.get ())
571     {
572     send_data_packet (p);
573     delete p;
574     }
575     }
576     else
577     {
578     retry_cnt = 0;
579     establish_connection.start (NOW + 5);
580     keepalive.reset ();
581     rekey.reset ();
582     }
583     }
584    
585     void
586 pcg 1.8 connection::reset_si ()
587 pcg 1.1 {
588 pcg 1.6 protocol = best_protocol (THISNODE->protocols & conf->protocols);
589    
590     // mask out protocols we cannot establish
591     if (!conf->udp_port) protocol &= ~PROT_UDPv4;
592     if (!conf->tcp_port) protocol &= ~PROT_TCPv4;
593    
594     si.set (conf, protocol);
595 pcg 1.1 }
596    
597 pcg 1.8 // ensure sockinfo is valid, forward if necessary
598     const sockinfo &
599     connection::forward_si (const sockinfo &si) const
600     {
601     if (!si.valid ())
602     {
603     connection *r = vpn->find_router ();
604    
605     if (r)
606     {
607     slog (L_DEBUG, _("%s: no common protocol, trying indirectly through %s"),
608     conf->nodename, r->conf->nodename);
609     return r->si;
610     }
611     else
612     slog (L_DEBUG, _("%s: node unreachable, no common protocol"),
613     conf->nodename);
614     }
615    
616     return si;
617     }
618    
619 pcg 1.1 void
620 pcg 1.10 connection::send_vpn_packet (vpn_packet *pkt, const sockinfo &si, int tos)
621     {
622     if (!vpn->send_vpn_packet (pkt, si, tos))
623     reset_connection ();
624     }
625    
626     void
627 pcg 1.1 connection::send_ping (const sockinfo &si, u8 pong)
628     {
629     ping_packet *pkt = new ping_packet;
630    
631     pkt->setup (conf->id, pong ? ping_packet::PT_PONG : ping_packet::PT_PING);
632 pcg 1.10 send_vpn_packet (pkt, si, IPTOS_LOWDELAY);
633 pcg 1.1
634     delete pkt;
635     }
636    
637     void
638     connection::send_reset (const sockinfo &si)
639     {
640     if (reset_rate_limiter.can (si) && connectmode != conf_node::C_DISABLED)
641     {
642     config_packet *pkt = new config_packet;
643    
644     pkt->setup (vpn_packet::PT_RESET, conf->id);
645 pcg 1.10 send_vpn_packet (pkt, si, IPTOS_MINCOST);
646 pcg 1.1
647     delete pkt;
648     }
649     }
650    
651     void
652     connection::send_auth_request (const sockinfo &si, bool initiate)
653     {
654     auth_req_packet *pkt = new auth_req_packet (conf->id, initiate, THISNODE->protocols);
655    
656 pcg 1.6 rsachallenge chg;
657 pcg 1.1
658 pcg 1.6 rsa_cache.gen (pkt->id, chg);
659 pcg 1.2
660 pcg 1.6 if (0 > RSA_public_encrypt (sizeof chg,
661     (unsigned char *)&chg, (unsigned char *)&pkt->encr,
662     conf->rsa_key, RSA_PKCS1_OAEP_PADDING))
663     fatal ("RSA_public_encrypt error");
664 pcg 1.1
665 pcg 1.6 slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)si);
666 pcg 1.1
667 pcg 1.10 send_vpn_packet (pkt, si, IPTOS_RELIABILITY | IPTOS_LOWDELAY); // rsa is very very costly
668 pcg 1.1
669 pcg 1.6 delete pkt;
670 pcg 1.1 }
671    
672     void
673     connection::send_auth_response (const sockinfo &si, const rsaid &id, const rsachallenge &chg)
674     {
675     auth_res_packet *pkt = new auth_res_packet (conf->id);
676    
677     pkt->id = id;
678    
679     rsa_hash (id, chg, pkt->response);
680    
681     pkt->hmac_set (octx);
682    
683     slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)si);
684    
685 pcg 1.10 send_vpn_packet (pkt, si, IPTOS_RELIABILITY); // rsa is very very costly
686 pcg 1.1
687     delete pkt;
688     }
689    
690     void
691     connection::send_connect_info (int rid, const sockinfo &rsi, u8 rprotocols)
692     {
693     slog (L_TRACE, ">>%d PT_CONNECT_INFO(%d,%s)\n",
694     conf->id, rid, (const char *)rsi);
695    
696     connect_info_packet *r = new connect_info_packet (conf->id, rid, rsi, rprotocols);
697    
698     r->hmac_set (octx);
699 pcg 1.10 send_vpn_packet (r, si);
700 pcg 1.1
701     delete r;
702     }
703    
704     void
705 pcg 1.4 connection::establish_connection_cb (time_watcher &w)
706 pcg 1.1 {
707     if (ictx || conf == THISNODE
708     || connectmode == conf_node::C_NEVER
709     || connectmode == conf_node::C_DISABLED)
710 pcg 1.4 w.at = TSTAMP_CANCEL;
711     else if (w.at <= NOW)
712 pcg 1.1 {
713     double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6;
714    
715     if (retry_int < 3600 * 8)
716     retry_cnt++;
717    
718 pcg 1.4 w.at = NOW + retry_int;
719 pcg 1.1
720 pcg 1.8 reset_si ();
721    
722     if (si.prot && !si.host)
723 pcg 1.10 vpn->send_connect_request (conf->id);
724 pcg 1.8 else
725 pcg 1.1 {
726 pcg 1.8 const sockinfo &dsi = forward_si (si);
727 pcg 1.6
728 pcg 1.8 if (dsi.valid () && auth_rate_limiter.can (dsi))
729     {
730     if (retry_cnt < 4)
731     send_auth_request (dsi, true);
732     else
733     send_ping (dsi, 0);
734     }
735 pcg 1.1 }
736     }
737     }
738    
739     void
740     connection::reset_connection ()
741     {
742     if (ictx && octx)
743     {
744     slog (L_INFO, _("%s(%s): connection lost"),
745     conf->nodename, (const char *)si);
746    
747     if (::conf.script_node_down)
748     run_script (run_script_cb (this, &connection::script_node_down), false);
749     }
750    
751     delete ictx; ictx = 0;
752     delete octx; octx = 0;
753    
754     si.host= 0;
755    
756     last_activity = 0;
757     retry_cnt = 0;
758    
759     rekey.reset ();
760     keepalive.reset ();
761     establish_connection.reset ();
762     }
763    
764     void
765     connection::shutdown ()
766     {
767     if (ictx && octx)
768     send_reset (si);
769    
770     reset_connection ();
771     }
772    
773     void
774 pcg 1.4 connection::rekey_cb (time_watcher &w)
775 pcg 1.1 {
776 pcg 1.4 w.at = TSTAMP_CANCEL;
777 pcg 1.1
778     reset_connection ();
779     establish_connection ();
780     }
781    
782     void
783     connection::send_data_packet (tap_packet *pkt, bool broadcast)
784     {
785     vpndata_packet *p = new vpndata_packet;
786     int tos = 0;
787    
788     if (conf->inherit_tos
789     && (*pkt)[12] == 0x08 && (*pkt)[13] == 0x00 // IP
790     && ((*pkt)[14] & 0xf0) == 0x40) // IPv4
791     tos = (*pkt)[15] & IPTOS_TOS_MASK;
792    
793     p->setup (this, broadcast ? 0 : conf->id, &((*pkt)[6 + 6]), pkt->len - 6 - 6, ++oseqno); // skip 2 macs
794 pcg 1.10 send_vpn_packet (p, si, tos);
795 pcg 1.1
796     delete p;
797    
798     if (oseqno > MAX_SEQNO)
799     rekey ();
800     }
801    
802     void
803     connection::inject_data_packet (tap_packet *pkt, bool broadcast)
804     {
805     if (ictx && octx)
806     send_data_packet (pkt, broadcast);
807     else
808     {
809     if (!broadcast)//DDDD
810     queue.put (new tap_packet (*pkt));
811    
812     establish_connection ();
813     }
814     }
815    
816 pcg 1.8 void connection::inject_vpn_packet (vpn_packet *pkt, int tos)
817     {
818     if (ictx && octx)
819 pcg 1.10 send_vpn_packet (pkt, si, tos);
820 pcg 1.8 else
821     establish_connection ();
822     }
823    
824 pcg 1.1 void
825     connection::recv_vpn_packet (vpn_packet *pkt, const sockinfo &rsi)
826     {
827     last_activity = NOW;
828    
829     slog (L_NOISE, "<<%d received packet type %d from %d to %d",
830     conf->id, pkt->typ (), pkt->src (), pkt->dst ());
831    
832     switch (pkt->typ ())
833     {
834 pcg 1.3 case vpn_packet::PT_PING:
835     // we send pings instead of auth packets after some retries,
836     // so reset the retry counter and establish a connection
837     // when we receive a ping.
838     if (!ictx)
839     {
840     if (auth_rate_limiter.can (rsi))
841     send_auth_request (rsi, true);
842     }
843     else
844     send_ping (rsi, 1); // pong
845    
846     break;
847    
848     case vpn_packet::PT_PONG:
849     break;
850    
851     case vpn_packet::PT_RESET:
852 pcg 1.1 {
853 pcg 1.3 reset_connection ();
854    
855     config_packet *p = (config_packet *) pkt;
856    
857     if (!p->chk_config ())
858     {
859     slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"),
860     conf->nodename, (const char *)rsi);
861     connectmode = conf_node::C_DISABLED;
862     }
863     else if (connectmode == conf_node::C_ALWAYS)
864     establish_connection ();
865 pcg 1.1 }
866 pcg 1.3 break;
867    
868     case vpn_packet::PT_AUTH_REQ:
869     if (auth_rate_limiter.can (rsi))
870     {
871     auth_req_packet *p = (auth_req_packet *) pkt;
872    
873     slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate);
874 pcg 1.1
875 pcg 1.3 if (p->chk_config () && !strncmp (p->magic, MAGIC, 8))
876     {
877     if (p->prot_minor != PROTOCOL_MINOR)
878     slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
879     conf->nodename, (const char *)rsi,
880     PROTOCOL_MINOR, conf->nodename, p->prot_minor);
881    
882     if (p->initiate)
883     send_auth_request (rsi, false);
884    
885     rsachallenge k;
886    
887     if (0 > RSA_private_decrypt (sizeof (p->encr),
888     (unsigned char *)&p->encr, (unsigned char *)&k,
889     ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING))
890     slog (L_ERR, _("%s(%s): challenge illegal or corrupted"),
891     conf->nodename, (const char *)rsi);
892     else
893     {
894     delete octx;
895 pcg 1.1
896 pcg 1.3 octx = new crypto_ctx (k, 1);
897     oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff;
898 pcg 1.1
899 pcg 1.3 conf->protocols = p->protocols;
900 pcg 1.10
901 pcg 1.3 send_auth_response (rsi, p->id, k);
902    
903 pcg 1.10 connection_established ();
904    
905 pcg 1.3 break;
906     }
907     }
908    
909     send_reset (rsi);
910 pcg 1.1 }
911    
912 pcg 1.3 break;
913    
914     case vpn_packet::PT_AUTH_RES:
915 pcg 1.1 {
916 pcg 1.3 auth_res_packet *p = (auth_res_packet *) pkt;
917 pcg 1.1
918 pcg 1.3 slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id);
919 pcg 1.1
920 pcg 1.3 if (p->chk_config ())
921 pcg 1.1 {
922     if (p->prot_minor != PROTOCOL_MINOR)
923     slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."),
924     conf->nodename, (const char *)rsi,
925     PROTOCOL_MINOR, conf->nodename, p->prot_minor);
926    
927 pcg 1.3 rsachallenge chg;
928 pcg 1.1
929 pcg 1.3 if (!rsa_cache.find (p->id, chg))
930     slog (L_ERR, _("%s(%s): unrequested auth response"),
931 pcg 1.1 conf->nodename, (const char *)rsi);
932     else
933     {
934 pcg 1.3 crypto_ctx *cctx = new crypto_ctx (chg, 0);
935    
936     if (!p->hmac_chk (cctx))
937     slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n"
938     "could be an attack, or just corruption or an synchronization error"),
939     conf->nodename, (const char *)rsi);
940     else
941     {
942     rsaresponse h;
943    
944     rsa_hash (p->id, chg, h);
945    
946     if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h))
947     {
948     prot_minor = p->prot_minor;
949    
950     delete ictx; ictx = cctx;
951    
952     iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid
953    
954     si = rsi;
955 pcg 1.7 protocol = rsi.prot;
956 pcg 1.3
957 pcg 1.10 connection_established ();
958 pcg 1.1
959 pcg 1.7 slog (L_INFO, _("%s(%s): connection established, protocol version %d.%d"),
960 pcg 1.3 conf->nodename, (const char *)rsi,
961     p->prot_major, p->prot_minor);
962 pcg 1.1
963 pcg 1.3 if (::conf.script_node_up)
964     run_script (run_script_cb (this, &connection::script_node_up), false);
965 pcg 1.1
966 pcg 1.3 break;
967     }
968     else
969     slog (L_ERR, _("%s(%s): sent and received challenge do not match"),
970     conf->nodename, (const char *)rsi);
971     }
972 pcg 1.1
973 pcg 1.3 delete cctx;
974 pcg 1.1 }
975     }
976     }
977    
978 pcg 1.3 send_reset (rsi);
979     break;
980 pcg 1.1
981 pcg 1.3 case vpn_packet::PT_DATA_COMPRESSED:
982     #if !ENABLE_COMPRESSION
983     send_reset (rsi);
984     break;
985     #endif
986 pcg 1.1
987 pcg 1.3 case vpn_packet::PT_DATA_UNCOMPRESSED:
988 pcg 1.1
989 pcg 1.3 if (ictx && octx)
990 pcg 1.1 {
991 pcg 1.3 vpndata_packet *p = (vpndata_packet *)pkt;
992 pcg 1.1
993 pcg 1.10 if (!p->hmac_chk (ictx))
994     slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n"
995     "could be an attack, or just corruption or an synchronization error"),
996     conf->nodename, (const char *)rsi);
997     else
998 pcg 1.1 {
999 pcg 1.10 u32 seqno;
1000     tap_packet *d = p->unpack (this, seqno);
1001    
1002     if (iseqno.recv_ok (seqno))
1003 pcg 1.1 {
1004 pcg 1.10 vpn->tap->send (d);
1005    
1006     if (p->dst () == 0) // re-broadcast
1007     for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i)
1008     {
1009     connection *c = *i;
1010    
1011     if (c->conf != THISNODE && c->conf != conf)
1012     c->inject_data_packet (d);
1013     }
1014 pcg 1.1
1015 pcg 1.10 if (si != rsi)
1016 pcg 1.1 {
1017 pcg 1.10 // fast re-sync on conneciton changes, useful especially for tcp/ip
1018     si = rsi;
1019 pcg 1.1
1020 pcg 1.10 slog (L_INFO, _("%s(%s): socket address changed to %s"),
1021     conf->nodename, (const char *)si, (const char *)rsi);
1022     }
1023 pcg 1.3
1024 pcg 1.10 delete d;
1025 pcg 1.1
1026 pcg 1.10 break;
1027 pcg 1.1 }
1028     }
1029     }
1030    
1031 pcg 1.3 send_reset (rsi);
1032     break;
1033 pcg 1.1
1034 pcg 1.3 case vpn_packet::PT_CONNECT_REQ:
1035     if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1036     {
1037     connect_req_packet *p = (connect_req_packet *) pkt;
1038 pcg 1.1
1039 pcg 1.3 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1040 pcg 1.7 connection *c = vpn->conns[p->id - 1];
1041 pcg 1.3 conf->protocols = p->protocols;
1042 pcg 1.1
1043 pcg 1.3 slog (L_TRACE, "<<%d PT_CONNECT_REQ(%d) [%d]\n",
1044     conf->id, p->id, c->ictx && c->octx);
1045 pcg 1.1
1046 pcg 1.3 if (c->ictx && c->octx)
1047     {
1048     // send connect_info packets to both sides, in case one is
1049     // behind a nat firewall (or both ;)
1050     c->send_connect_info (conf->id, si, conf->protocols);
1051     send_connect_info (c->conf->id, c->si, c->conf->protocols);
1052     }
1053 pcg 1.11 else
1054     c->establish_connection ();
1055 pcg 1.3 }
1056 pcg 1.1
1057 pcg 1.3 break;
1058 pcg 1.1
1059 pcg 1.3 case vpn_packet::PT_CONNECT_INFO:
1060     if (ictx && octx && rsi == si && pkt->hmac_chk (ictx))
1061     {
1062     connect_info_packet *p = (connect_info_packet *) pkt;
1063 pcg 1.1
1064 pcg 1.3 assert (p->id > 0 && p->id <= vpn->conns.size ()); // hmac-auth does not mean we accept anything
1065 pcg 1.7
1066 pcg 1.3 connection *c = vpn->conns[p->id - 1];
1067 pcg 1.1
1068 pcg 1.7 c->conf->protocols = p->protocols;
1069     protocol = best_protocol (c->conf->protocols & THISNODE->protocols & p->si.supported_protocols (c->conf));
1070     p->si.upgrade_protocol (protocol, c->conf);
1071    
1072 pcg 1.3 slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)",
1073     conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx);
1074 pcg 1.1
1075 pcg 1.8 const sockinfo &dsi = forward_si (p->si);
1076    
1077     if (dsi.valid ())
1078     c->send_auth_request (dsi, true);
1079 pcg 1.3 }
1080 pcg 1.1
1081 pcg 1.3 break;
1082 pcg 1.1
1083 pcg 1.3 default:
1084     send_reset (rsi);
1085     break;
1086 pcg 1.1 }
1087     }
1088    
1089 pcg 1.4 void connection::keepalive_cb (time_watcher &w)
1090 pcg 1.1 {
1091     if (NOW >= last_activity + ::conf.keepalive + 30)
1092     {
1093     reset_connection ();
1094     establish_connection ();
1095     }
1096     else if (NOW < last_activity + ::conf.keepalive)
1097 pcg 1.4 w.at = last_activity + ::conf.keepalive;
1098 pcg 1.1 else if (conf->connectmode != conf_node::C_ONDEMAND
1099     || THISNODE->connectmode != conf_node::C_ONDEMAND)
1100     {
1101     send_ping (si);
1102 pcg 1.4 w.at = NOW + 5;
1103 pcg 1.1 }
1104     else
1105     reset_connection ();
1106     }
1107    
1108 pcg 1.10 void connection::send_connect_request (int id)
1109 pcg 1.1 {
1110     connect_req_packet *p = new connect_req_packet (conf->id, id, conf->protocols);
1111    
1112     slog (L_TRACE, ">>%d PT_CONNECT_REQ(%d)", conf->id, id);
1113     p->hmac_set (octx);
1114 pcg 1.10 send_vpn_packet (p, si);
1115 pcg 1.1
1116     delete p;
1117     }
1118    
1119     void connection::script_node ()
1120     {
1121 pcg 1.3 vpn->script_if_up ();
1122 pcg 1.1
1123     char *env;
1124     asprintf (&env, "DESTID=%d", conf->id); putenv (env);
1125     asprintf (&env, "DESTNODE=%s", conf->nodename); putenv (env);
1126     asprintf (&env, "DESTIP=%s", si.ntoa ()); putenv (env);
1127     asprintf (&env, "DESTPORT=%d", ntohs (si.port)); putenv (env);
1128     }
1129    
1130 pcg 1.3 const char *connection::script_node_up ()
1131 pcg 1.1 {
1132     script_node ();
1133    
1134     putenv ("STATE=up");
1135    
1136     return ::conf.script_node_up ? ::conf.script_node_up : "node-up";
1137     }
1138    
1139 pcg 1.3 const char *connection::script_node_down ()
1140 pcg 1.1 {
1141     script_node ();
1142    
1143     putenv ("STATE=down");
1144    
1145     return ::conf.script_node_up ? ::conf.script_node_down : "node-down";
1146     }
1147    
1148     connection::connection(struct vpn *vpn_)
1149     : vpn(vpn_)
1150     , rekey (this, &connection::rekey_cb)
1151     , keepalive (this, &connection::keepalive_cb)
1152     , establish_connection (this, &connection::establish_connection_cb)
1153     {
1154     octx = ictx = 0;
1155     retry_cnt = 0;
1156    
1157     connectmode = conf_node::C_ALWAYS; // initial setting
1158     reset_connection ();
1159     }
1160    
1161     connection::~connection ()
1162     {
1163     shutdown ();
1164     }
1165    
1166     void connection_init ()
1167     {
1168     auth_rate_limiter.clear ();
1169     reset_rate_limiter.clear ();
1170     }
1171