ViewVC Help
View File | Revision Log | Show Annotations | Download File
/cvs/gvpe/src/protocol.C
Revision: 1.6
Committed: Sun Mar 9 12:40:18 2003 UTC (21 years, 2 months ago) by pcg
Content type: text/plain
Branch: MAIN
Changes since 1.5: +13 -5 lines
Log Message:
*** empty log message ***

File Contents

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