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