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