--- gvpe/src/protocol.C 2003/03/09 12:48:22 1.7 +++ gvpe/src/protocol.C 2003/03/26 14:39:52 1.19 @@ -18,6 +18,8 @@ #include "config.h" +#include + #include #include #include @@ -58,33 +60,122 @@ #define MAGIC "vped\xbd\xc6\xdb\x82" // 8 bytes of magic -static const rsachallenge & -challenge_bytes () +struct crypto_ctx + { + EVP_CIPHER_CTX cctx; + HMAC_CTX hctx; + + crypto_ctx (const rsachallenge &challenge, int enc); + ~crypto_ctx (); + }; + +crypto_ctx::crypto_ctx (const rsachallenge &challenge, int enc) +{ + EVP_CIPHER_CTX_init (&cctx); + EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc); + HMAC_CTX_init (&hctx); + HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0); +} + +crypto_ctx::~crypto_ctx () +{ + EVP_CIPHER_CTX_cleanup (&cctx); + HMAC_CTX_cleanup (&hctx); +} + +static void +rsa_hash (const rsaid &id, const rsachallenge &chg, rsaresponse &h) { - static rsachallenge challenge; - static time_t challenge_ttl; // time this challenge needs to be recreated + EVP_MD_CTX ctx; - if (now > challenge_ttl) + EVP_MD_CTX_init (&ctx); + EVP_DigestInit (&ctx, RSA_HASH); + EVP_DigestUpdate(&ctx, &chg, sizeof chg); + EVP_DigestUpdate(&ctx, &id, sizeof id); + EVP_DigestFinal (&ctx, (unsigned char *)&h, 0); + EVP_MD_CTX_cleanup (&ctx); +} + +struct rsa_entry { + tstamp expire; + rsaid id; + rsachallenge chg; +}; + +struct rsa_cache : list +{ + void cleaner_cb (tstamp &ts); time_watcher cleaner; + + bool find (const rsaid &id, rsachallenge &chg) + { + for (iterator i = begin (); i != end (); ++i) + { + if (!memcmp (&id, &i->id, sizeof id) && i->expire > NOW) + { + memcpy (&chg, &i->chg, sizeof chg); + + erase (i); + return true; + } + } + + if (cleaner.at < NOW) + cleaner.start (NOW + RSA_TTL); + + return false; + } + + void gen (rsaid &id, rsachallenge &chg) { - RAND_bytes ((unsigned char *)&challenge, sizeof (challenge)); - challenge_ttl = now + CHALLENGE_TTL; + rsa_entry e; + + RAND_bytes ((unsigned char *)&id, sizeof id); + RAND_bytes ((unsigned char *)&chg, sizeof chg); + + e.expire = NOW + RSA_TTL; + e.id = id; + memcpy (&e.chg, &chg, sizeof chg); + + push_back (e); + + if (cleaner.at < NOW) + cleaner.start (NOW + RSA_TTL); } - return challenge; + rsa_cache () + : cleaner (this, &rsa_cache::cleaner_cb) + { } + +} rsa_cache; + +void rsa_cache::cleaner_cb (tstamp &ts) +{ + if (empty ()) + ts = TSTAMP_CANCEL; + else + { + ts = NOW + RSA_TTL; + + for (iterator i = begin (); i != end (); ) + if (i->expire <= NOW) + i = erase (i); + else + ++i; + } } -// run a script. yes, it's a template function. yes, c++ -// is not a functional language. yes, this suxx. -template +typedef callback run_script_cb; + +// run a shell script (or actually an external program). static void -run_script (owner *obj, const char *(owner::*setup)(), bool wait) +run_script (const run_script_cb &cb, bool wait) { int pid; if ((pid = fork ()) == 0) { char *filename; - asprintf (&filename, "%s/%s", confbase, (obj->*setup) ()); + asprintf (&filename, "%s/%s", confbase, cb(0)); execl (filename, filename, (char *) 0); exit (255); } @@ -98,38 +189,113 @@ } } -// xor the socket address into the challenge to ensure different challenges -// per host. we could rely on the OAEP padding, but this doesn't hurt. -void -xor_sa (rsachallenge &k, SOCKADDR *sa) +////////////////////////////////////////////////////////////////////////////// + +void pkt_queue::put (tap_packet *p) { - ((u32 *) k)[(CHG_CIPHER_KEY + 0) / 4] ^= sa->sin_addr.s_addr; - ((u16 *) k)[(CHG_CIPHER_KEY + 4) / 2] ^= sa->sin_port; - ((u32 *) k)[(CHG_HMAC_KEY + 0) / 4] ^= sa->sin_addr.s_addr; - ((u16 *) k)[(CHG_HMAC_KEY + 4) / 2] ^= sa->sin_port; + if (queue[i]) + { + delete queue[i]; + j = (j + 1) % QUEUEDEPTH; + } + + queue[i] = p; + + i = (i + 1) % QUEUEDEPTH; } -struct crypto_ctx - { - EVP_CIPHER_CTX cctx; - HMAC_CTX hctx; +tap_packet *pkt_queue::get () +{ + tap_packet *p = queue[j]; - crypto_ctx (rsachallenge &challenge, int enc); - ~crypto_ctx (); - }; + if (p) + { + queue[j] = 0; + j = (j + 1) % QUEUEDEPTH; + } -crypto_ctx::crypto_ctx (rsachallenge &challenge, int enc) + return p; +} + +pkt_queue::pkt_queue () { - EVP_CIPHER_CTX_init (&cctx); - EVP_CipherInit_ex (&cctx, CIPHER, 0, &challenge[CHG_CIPHER_KEY], 0, enc); - HMAC_CTX_init (&hctx); - HMAC_Init_ex (&hctx, &challenge[CHG_HMAC_KEY], HMAC_KEYLEN, DIGEST, 0); + memset (queue, 0, sizeof (queue)); + i = 0; + j = 0; } -crypto_ctx::~crypto_ctx () +pkt_queue::~pkt_queue () { - EVP_CIPHER_CTX_cleanup (&cctx); - HMAC_CTX_cleanup (&hctx); + for (i = QUEUEDEPTH; --i > 0; ) + delete queue[i]; +} + +struct net_rateinfo { + u32 host; + double pcnt, diff; + tstamp last; +}; + +// only do action once every x seconds per host whole allowing bursts. +// this implementation ("splay list" ;) is inefficient, +// but low on resources. +struct net_rate_limiter : private list +{ + static const double ALPHA = 1. - 1. / 90.; // allow bursts + static const double CUTOFF = 20.; // one event every CUTOFF seconds + static const double EXPIRE = CUTOFF * 30.; // expire entries after this time + + bool can (u32 host); + bool can (SOCKADDR *sa) { return can((u32)sa->sin_addr.s_addr); } + bool can (sockinfo &si) { return can((u32)si.host); } +}; + +net_rate_limiter auth_rate_limiter, reset_rate_limiter; + +bool net_rate_limiter::can (u32 host) +{ + iterator i; + + for (i = begin (); i != end (); ) + if (i->host == host) + break; + else if (i->last < NOW - EXPIRE) + i = erase (i); + else + i++; + + if (i == end ()) + { + net_rateinfo ri; + + ri.host = host; + ri.pcnt = 1.; + ri.diff = CUTOFF * (1. / (1. - ALPHA)); + ri.last = NOW; + + push_front (ri); + + return true; + } + else + { + net_rateinfo ri (*i); + erase (i); + + ri.pcnt = ri.pcnt * ALPHA; + ri.diff = ri.diff * ALPHA + (NOW - ri.last); + + ri.last = NOW; + + bool send = ri.diff / ri.pcnt > CUTOFF; + + if (send) + ri.pcnt++; + + push_front (ri); + + return send; + } } ///////////////////////////////////////////////////////////////////////////// @@ -143,24 +309,24 @@ static unsigned char hmac_digest[EVP_MAX_MD_SIZE]; struct hmac_packet:net_packet - { - u8 hmac[HMACLENGTH]; // each and every packet has a hmac field, but that is not (yet) checked everywhere +{ + u8 hmac[HMACLENGTH]; // each and every packet has a hmac field, but that is not (yet) checked everywhere - void hmac_set (crypto_ctx * ctx); - bool hmac_chk (crypto_ctx * ctx); + void hmac_set (crypto_ctx * ctx); + bool hmac_chk (crypto_ctx * ctx); private: - void hmac_gen (crypto_ctx * ctx) - { - unsigned int xlen; - HMAC_CTX *hctx = &ctx->hctx; + void hmac_gen (crypto_ctx * ctx) + { + unsigned int xlen; + HMAC_CTX *hctx = &ctx->hctx; - HMAC_Init_ex (hctx, 0, 0, 0, 0); - HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet), - len - sizeof (hmac_packet)); - HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen); - } - }; + HMAC_Init_ex (hctx, 0, 0, 0, 0); + HMAC_Update (hctx, ((unsigned char *) this) + sizeof (hmac_packet), + len - sizeof (hmac_packet)); + HMAC_Final (hctx, (unsigned char *) &hmac_digest, &xlen); + } +}; void hmac_packet::hmac_set (crypto_ctx * ctx) @@ -186,10 +352,10 @@ PT_DATA_UNCOMPRESSED, PT_DATA_COMPRESSED, PT_PING, PT_PONG, // wasting namespace space? ;) - PT_AUTH, // authentification + PT_AUTH_REQ, // authentification request + PT_AUTH_RES, // authentification response PT_CONNECT_REQ, // want other host to contact me PT_CONNECT_INFO, // request connection to some node - PT_REKEY, // rekeying (not yet implemented) PT_MAX }; @@ -202,10 +368,12 @@ { return src1 | ((srcdst >> 4) << 8); } + unsigned int dst () { return dst1 | ((srcdst & 0xf) << 8); } + ptype typ () { return (ptype) type; @@ -254,7 +422,6 @@ cl = lzf_compress (d, l, cdata + 2, (l - 2) & ~7); if (cl) { - //printf ("compressed packet, %d => %d\n", l, cl);//D type = PT_DATA_COMPRESSED; d = cdata; l = cl + 2; @@ -266,25 +433,22 @@ EVP_EncryptInit_ex (cctx, 0, 0, 0, 0); -#if RAND_SIZE struct { +#if RAND_SIZE u8 rnd[RAND_SIZE]; +#endif u32 seqno; } datahdr; - datahdr.seqno = seqno; + datahdr.seqno = ntohl (seqno); +#if RAND_SIZE RAND_pseudo_bytes ((unsigned char *) datahdr.rnd, RAND_SIZE); +#endif EVP_EncryptUpdate (cctx, (unsigned char *) data + outl, &outl2, (unsigned char *) &datahdr, DATAHDR); outl += outl2; -#else - EVP_EncryptUpdate (cctx, - (unsigned char *) data + outl, &outl2, - (unsigned char *) &seqno, DATAHDR); - outl += outl2; -#endif EVP_EncryptUpdate (cctx, (unsigned char *) data + outl, &outl2, @@ -330,7 +494,7 @@ EVP_DecryptFinal_ex (cctx, (unsigned char *)d + outl, &outl2); outl += outl2; - seqno = *(u32 *)(d + RAND_SIZE); + seqno = ntohl (*(u32 *)(d + RAND_SIZE)); id2mac (dst () ? dst() : THISNODE->id, p->dst); id2mac (src (), p->src); @@ -339,8 +503,10 @@ if (type == PT_DATA_COMPRESSED) { u32 cl = (d[DATAHDR] << 8) | d[DATAHDR + 1]; - p->len = lzf_decompress (d + DATAHDR + 2, cl, &(*p)[6 + 6], MAX_MTU) + 6 + 6; - //printf ("decompressxed %d(%d) => %d\n", cl, len - data_hdr_size (), p->len);//D + + p->len = lzf_decompress (d + DATAHDR + 2, cl < MAX_MTU ? cl : 0, + &(*p)[6 + 6], MAX_MTU) + + 6 + 6; } else p->len = outl + (6 + 6 - DATAHDR); @@ -350,102 +516,117 @@ } struct ping_packet : vpn_packet +{ + void setup (int dst, ptype type) { - void setup (int dst, ptype type) - { - set_hdr (type, dst); - len = sizeof (*this) - sizeof (net_packet); - } - }; + set_hdr (type, dst); + len = sizeof (*this) - sizeof (net_packet); + } +}; struct config_packet : vpn_packet +{ + // actually, hmaclen cannot be checked because the hmac + // field comes before this data, so peers with other + // hmacs simply will not work. + u8 prot_major, prot_minor, randsize, hmaclen; + u8 flags, challengelen, pad2, pad3; + u32 cipher_nid, digest_nid, hmac_nid; + + const u8 curflags () const { - // actually, hmaclen cannot be checked because the hmac - // field comes before this data, so peers with other - // hmacs simply will not work. - u8 prot_major, prot_minor, randsize, hmaclen; - u8 flags, challengelen, pad2, pad3; - u32 cipher_nid; - u32 digest_nid; + return 0x80 + | (ENABLE_COMPRESSION ? 0x01 : 0x00); + } - const u8 curflags () const - { - return 0x80 - | (ENABLE_COMPRESSION ? 0x01 : 0x00) - | (ENABLE_TRUST ? 0x02 : 0x00); - } + void setup (ptype type, int dst) + { + prot_major = PROTOCOL_MAJOR; + prot_minor = PROTOCOL_MINOR; + randsize = RAND_SIZE; + hmaclen = HMACLENGTH; + flags = curflags (); + challengelen = sizeof (rsachallenge); + + cipher_nid = htonl (EVP_CIPHER_nid (CIPHER)); + digest_nid = htonl (EVP_MD_type (RSA_HASH)); + hmac_nid = htonl (EVP_MD_type (DIGEST)); - void setup (ptype type, int dst) - { - prot_major = PROTOCOL_MAJOR; - prot_minor = PROTOCOL_MINOR; - randsize = RAND_SIZE; - hmaclen = HMACLENGTH; - flags = curflags (); - challengelen = sizeof (rsachallenge); + len = sizeof (*this) - sizeof (net_packet); + set_hdr (type, dst); + } - cipher_nid = htonl (EVP_CIPHER_nid (CIPHER)); - digest_nid = htonl (EVP_MD_type (DIGEST)); + bool chk_config () + { + return prot_major == PROTOCOL_MAJOR + && randsize == RAND_SIZE + && hmaclen == HMACLENGTH + && flags == curflags () + && challengelen == sizeof (rsachallenge) + && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER)) + && digest_nid == htonl (EVP_MD_type (RSA_HASH)) + && hmac_nid == htonl (EVP_MD_type (DIGEST)); + } +}; + +struct auth_req_packet : config_packet +{ + char magic[8]; + u8 initiate; // false if this is just an automatic reply + u8 pad1, pad2, pad3; + rsaid id; + rsaencrdata encr; - len = sizeof (*this) - sizeof (net_packet); - set_hdr (type, dst); - } + auth_req_packet (int dst, bool initiate_) + { + config_packet::setup (PT_AUTH_REQ, dst); + initiate = !!initiate_; + strncpy (magic, MAGIC, 8); + len = sizeof (*this) - sizeof (net_packet); + } +}; - bool chk_config () - { - return prot_major == PROTOCOL_MAJOR - && randsize == RAND_SIZE - && hmaclen == HMACLENGTH - && flags == curflags () - && challengelen == sizeof (rsachallenge) - && cipher_nid == htonl (EVP_CIPHER_nid (CIPHER)) - && digest_nid == htonl (EVP_MD_type (DIGEST)); - } - }; +struct auth_res_packet : config_packet +{ + rsaid id; + u8 pad1, pad2, pad3; + u8 response_len; // encrypted length + rsaresponse response; -struct auth_packet : config_packet + auth_res_packet (int dst) { - char magic[8]; - u8 subtype; - u8 pad1, pad2; - rsaencrdata challenge; - - auth_packet (int dst, auth_subtype stype) - { - config_packet::setup (PT_AUTH, dst); - subtype = stype; - len = sizeof (*this) - sizeof (net_packet); - strncpy (magic, MAGIC, 8); - } - }; + config_packet::setup (PT_AUTH_RES, dst); + len = sizeof (*this) - sizeof (net_packet); + } +}; struct connect_req_packet : vpn_packet - { - u8 id; - u8 pad1, pad2, pad3; +{ + u8 id; + u8 pad1, pad2, pad3; - connect_req_packet (int dst, int id) - { - this->id = id; - set_hdr (PT_CONNECT_REQ, dst); - len = sizeof (*this) - sizeof (net_packet); - } - }; + connect_req_packet (int dst, int id_) + { + id = id_; + set_hdr (PT_CONNECT_REQ, dst); + len = sizeof (*this) - sizeof (net_packet); + } +}; struct connect_info_packet : vpn_packet +{ + u8 id; + u8 pad1, pad2, pad3; + sockinfo si; + + connect_info_packet (int dst, int id_, sockinfo &si_) { - u8 id; - u8 pad1, pad2, pad3; - sockinfo si; - - connect_info_packet (int dst, int id, sockinfo &si) - { - this->id = id; - this->si = si; - set_hdr (PT_CONNECT_INFO, dst); - len = sizeof (*this) - sizeof (net_packet); - } - }; + id = id_; + si = si_; + set_hdr (PT_CONNECT_INFO, dst); + len = sizeof (*this) - sizeof (net_packet); + } +}; ///////////////////////////////////////////////////////////////////////////// @@ -491,9 +672,7 @@ void connection::send_reset (SOCKADDR *dsa) { - static net_rate_limiter limiter(1); - - if (limiter.can (dsa)) + if (reset_rate_limiter.can (dsa) && connectmode != conf_node::C_DISABLED) { config_packet *pkt = new config_packet; @@ -504,91 +683,75 @@ } } -static rsachallenge * -gen_challenge (SOCKADDR *sa) -{ - static rsachallenge k; - - memcpy (&k, &challenge_bytes (), sizeof (k)); - RAND_bytes ((unsigned char *)&k[CHG_SEQNO], sizeof (u32)); - xor_sa (k, sa); - - return &k; -} - void -connection::send_auth (auth_subtype subtype, SOCKADDR *sa, rsachallenge *k) +connection::send_auth_request (SOCKADDR *sa, bool initiate) { - static net_rate_limiter limiter(2); - - if (subtype != AUTH_INIT || limiter.can (sa)) + if (!initiate || auth_rate_limiter.can (sa)) { - auth_packet *pkt = new auth_packet (conf->id, subtype); + auth_req_packet *pkt = new auth_req_packet (conf->id, initiate); - //printf ("send auth_packet subtype %d\n", subtype);//D + rsachallenge chg; - if (!k) - k = gen_challenge (sa); + rsa_cache.gen (pkt->id, chg); -#if ENABLE_TRUST - if (0 > RSA_public_encrypt (sizeof (*k), - (unsigned char *)k, (unsigned char *)&pkt->challenge, + if (0 > RSA_public_encrypt (sizeof chg, + (unsigned char *)&chg, (unsigned char *)&pkt->encr, conf->rsa_key, RSA_PKCS1_OAEP_PADDING)) fatal ("RSA_public_encrypt error"); -#else -# error untrusted mode not yet implemented: programemr does not know how to - rsaencrdata enc; - - if (0 > RSA_private_encrypt (sizeof (*k), - (unsigned char *)k, (unsigned char *)&enc, - ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) - fatal ("RSA_private_encrypt error"); - - if (0 > RSA_public_encrypt (sizeof (enc), - (unsigned char *)enc, (unsigned char *)&pkt->challenge, - conf->rsa_key, RSA_NO_PADDING)) - fatal ("RSA_public_encrypt error"); -#endif - slog (L_TRACE, ">>%d PT_AUTH(%d) [%s]", conf->id, subtype, (const char *)sockinfo (sa)); + slog (L_TRACE, ">>%d PT_AUTH_REQ [%s]", conf->id, (const char *)sockinfo (sa)); - vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); + vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly delete pkt; } } void -connection::establish_connection () +connection::send_auth_response (SOCKADDR *sa, const rsaid &id, const rsachallenge &chg) { - if (!ictx && conf != THISNODE && connectmode != conf_node::C_NEVER) - { - if (now >= next_retry) - { - int retry_int = retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2); + auth_res_packet *pkt = new auth_res_packet (conf->id); - if (retry_cnt < (17 << 2) | 3) - retry_cnt++; + pkt->id = id; - if (connectmode == conf_node::C_ONDEMAND - && retry_int > ::conf.keepalive) - retry_int = ::conf.keepalive; + rsa_hash (id, chg, pkt->response); - next_retry = now + retry_int; - next_wakeup (next_retry); + pkt->hmac_set (octx); - if (conf->hostname) - { - reset_dstaddr (); - if (sa.sin_addr.s_addr) - if (retry_cnt < 4) - send_auth (AUTH_INIT, &sa); - else - send_ping (&sa, 0); - } - else - vpn->connect_request (conf->id); + slog (L_TRACE, ">>%d PT_AUTH_RES [%s]", conf->id, (const char *)sockinfo (sa)); + + vpn->send_vpn_packet (pkt, sa, IPTOS_RELIABILITY); // rsa is very very costly + + delete pkt; +} + +void +connection::establish_connection_cb (tstamp &ts) +{ + if (ictx || conf == THISNODE + || connectmode == conf_node::C_NEVER + || connectmode == conf_node::C_DISABLED) + ts = TSTAMP_CANCEL; + else if (ts <= NOW) + { + double retry_int = double (retry_cnt & 3 ? (retry_cnt & 3) : 1 << (retry_cnt >> 2)) * 0.6; + + if (retry_int < 3600 * 8) + retry_cnt++; + + ts = NOW + retry_int; + + if (conf->hostname) + { + reset_dstaddr (); + if (sa.sin_addr.s_addr) + if (retry_cnt < 4) + send_auth_request (&sa, true); + else if (auth_rate_limiter.can (&sa)) + send_ping (&sa, 0); } + else + vpn->connect_request (conf->id); } } @@ -597,24 +760,24 @@ { if (ictx && octx) { - slog (L_INFO, _("connection to %d (%s) lost"), conf->id, conf->nodename); + slog (L_INFO, _("%s(%s): connection lost"), + conf->nodename, (const char *)sockinfo (sa)); if (::conf.script_node_down) - run_script (this, &connection::script_node_down, false); + run_script (run_script_cb (this, &connection::script_node_down), false); } - delete ictx; - ictx = 0; - - delete octx; - octx = 0; + delete ictx; ictx = 0; + delete octx; octx = 0; sa.sin_port = 0; sa.sin_addr.s_addr = 0; - next_retry = 0; - next_rekey = 0; last_activity = 0; + + rekey.reset (); + keepalive.reset (); + establish_connection.reset (); } void @@ -627,8 +790,10 @@ } void -connection::rekey () +connection::rekey_cb (tstamp &ts) { + ts = TSTAMP_CANCEL; + reset_connection (); establish_connection (); } @@ -670,7 +835,7 @@ void connection::recv_vpn_packet (vpn_packet *pkt, SOCKADDR *ssa) { - last_activity = now; + last_activity = NOW; slog (L_NOISE, "<<%d received packet type %d from %d to %d", conf->id, pkt->typ (), pkt->src (), pkt->dst ()); @@ -678,148 +843,172 @@ switch (pkt->typ ()) { case vpn_packet::PT_PING: - send_ping (ssa, 1); // pong - break; - - case vpn_packet::PT_PONG: // we send pings instead of auth packets after some retries, // so reset the retry counter and establish a conenction // when we receive a pong. if (!ictx && !octx) { retry_cnt = 0; - next_retry = 0; + establish_connection.at = 0; establish_connection (); } + else + send_ping (ssa, 1); // pong break; + case vpn_packet::PT_PONG: + break; + case vpn_packet::PT_RESET: { reset_connection (); config_packet *p = (config_packet *) pkt; - if (p->chk_config ()) - if (connectmode == conf_node::C_ALWAYS) - establish_connection (); - //D slog the protocol mismatch? + if (!p->chk_config ()) + { + slog (L_WARN, _("%s(%s): protocol mismatch, disabling node"), + conf->nodename, (const char *)sockinfo (ssa)); + connectmode = conf_node::C_DISABLED; + } + else if (connectmode == conf_node::C_ALWAYS) + establish_connection (); } break; - case vpn_packet::PT_AUTH: + case vpn_packet::PT_AUTH_REQ: + if (auth_rate_limiter.can (ssa)) + { + auth_req_packet *p = (auth_req_packet *) pkt; + + slog (L_TRACE, "<<%d PT_AUTH_REQ(%d)", conf->id, p->initiate); + + if (p->chk_config () && !strncmp (p->magic, MAGIC, 8)) + { + if (p->prot_minor != PROTOCOL_MINOR) + slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."), + conf->nodename, (const char *)sockinfo (ssa), + PROTOCOL_MINOR, conf->nodename, p->prot_minor); + + if (p->initiate) + send_auth_request (ssa, false); + + rsachallenge k; + + if (0 > RSA_private_decrypt (sizeof (p->encr), + (unsigned char *)&p->encr, (unsigned char *)&k, + ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) + slog (L_ERR, _("%s(%s): challenge illegal or corrupted"), + conf->nodename, (const char *)sockinfo (ssa)); + else + { + retry_cnt = 0; + establish_connection.set (NOW + 8); //? ;) + keepalive.reset (); + rekey.reset (); + + delete ictx; + ictx = 0; + + delete octx; + + octx = new crypto_ctx (k, 1); + oseqno = ntohl (*(u32 *)&k[CHG_SEQNO]) & 0x7fffffff; + + send_auth_response (ssa, p->id, k); + + break; + } + } + + send_reset (ssa); + } + + break; + + case vpn_packet::PT_AUTH_RES: { - auth_packet *p = (auth_packet *) pkt; + auth_res_packet *p = (auth_res_packet *) pkt; - slog (L_TRACE, "<<%d PT_AUTH(%d)", conf->id, p->subtype); + slog (L_TRACE, "<<%d PT_AUTH_RES", conf->id); - if (p->chk_config () - && !strncmp (p->magic, MAGIC, 8)) + if (p->chk_config ()) { if (p->prot_minor != PROTOCOL_MINOR) - slog (L_INFO, _("protocol minor version mismatch: ours is %d, %s's is %d."), + slog (L_INFO, _("%s(%s): protocol minor version mismatch: ours is %d, %s's is %d."), + conf->nodename, (const char *)sockinfo (ssa), PROTOCOL_MINOR, conf->nodename, p->prot_minor); - if (p->subtype == AUTH_INIT) - send_auth (AUTH_INITREPLY, ssa); - - rsachallenge k; - -#if ENABLE_TRUST - if (0 > RSA_private_decrypt (sizeof (rsaencrdata), - (unsigned char *)&p->challenge, (unsigned char *)&k, - ::conf.rsa_key, RSA_PKCS1_OAEP_PADDING)) - // continued below -#else - rsaencrdata j; - - if (0 > RSA_private_decrypt (sizeof (rsaencrdata), - (unsigned char *)&p->challenge, (unsigned char *)&j, - ::conf.rsa_key, RSA_NO_PADDING)) - fatal ("RSA_private_decrypt error"); - - if (0 > RSA_public_decrypt (sizeof (k), - (unsigned char *)&j, (unsigned char *)&k, - conf->rsa_key, RSA_PKCS1_OAEP_PADDING)) - // continued below -#endif - { - slog (L_ERR, _("challenge from %s (%s) illegal or corrupted"), - conf->nodename, (const char *)sockinfo (ssa)); - break; - } - - retry_cnt = 0; - next_retry = now + 8; + rsachallenge chg; - switch (p->subtype) + if (!rsa_cache.find (p->id, chg)) + slog (L_ERR, _("%s(%s): unrequested auth response"), + conf->nodename, (const char *)sockinfo (ssa)); + else { - case AUTH_INIT: - case AUTH_INITREPLY: - delete ictx; - ictx = 0; + crypto_ctx *cctx = new crypto_ctx (chg, 0); - delete octx; + if (!p->hmac_chk (cctx)) + slog (L_ERR, _("%s(%s): hmac authentication error on auth response, received invalid packet\n" + "could be an attack, or just corruption or an synchronization error"), + conf->nodename, (const char *)sockinfo (ssa)); + else + { + rsaresponse h; - octx = new crypto_ctx (k, 1); - oseqno = *(u32 *)&k[CHG_SEQNO] & 0x7fffffff; + rsa_hash (p->id, chg, h); - send_auth (AUTH_REPLY, ssa, &k); - break; + if (!memcmp ((u8 *)&h, (u8 *)p->response, sizeof h)) + { + prot_minor = p->prot_minor; - case AUTH_REPLY: + delete ictx; ictx = cctx; - if (!memcmp ((u8 *)gen_challenge (ssa) + sizeof (u32), (u8 *)&k + sizeof (u32), - sizeof (rsachallenge) - sizeof (u32))) - { - delete ictx; + iseqno.reset (ntohl (*(u32 *)&chg[CHG_SEQNO]) & 0x7fffffff); // at least 2**31 sequence numbers are valid - ictx = new crypto_ctx (k, 0); - iseqno = *(u32 *)&k[CHG_SEQNO] & 0x7fffffff; // at least 2**31 sequence numbers are valid - ismask = 0xffffffff; // initially, all lower sequence numbers are invalid + sa = *ssa; - sa = *ssa; + rekey.set (NOW + ::conf.rekey); + keepalive.set (NOW + ::conf.keepalive); - next_rekey = now + ::conf.rekey; - next_wakeup (next_rekey); + // send queued packets + while (tap_packet *p = queue.get ()) + { + send_data_packet (p); + delete p; + } - // send queued packets - while (tap_packet *p = queue.get ()) - { - send_data_packet (p); - delete p; - } + connectmode = conf->connectmode; - connectmode = conf->connectmode; + slog (L_INFO, _("%s(%s): connection established, protocol version %d:%d"), + conf->nodename, (const char *)sockinfo (ssa), + p->prot_major, p->prot_minor); - slog (L_INFO, _("connection to %d (%s %s) established"), - conf->id, conf->nodename, (const char *)sockinfo (ssa)); + if (::conf.script_node_up) + run_script (run_script_cb (this, &connection::script_node_up), false); - if (::conf.script_node_up) - run_script (this, &connection::script_node_up, false); + break; + } + else + slog (L_ERR, _("%s(%s): sent and received challenge do not match"), + conf->nodename, (const char *)sockinfo (ssa)); } - else - slog (L_ERR, _("sent and received challenge do not match with (%s %s))"), - conf->nodename, (const char *)sockinfo (ssa)); - break; - default: - slog (L_ERR, _("authentification illegal subtype error (%s %s)"), - conf->nodename, (const char *)sockinfo (ssa)); - break; + delete cctx; } } - else - send_reset (ssa); - - break; } + send_reset (ssa); + break; + case vpn_packet::PT_DATA_COMPRESSED: #if !ENABLE_COMPRESSION send_reset (ssa); break; #endif + case vpn_packet::PT_DATA_UNCOMPRESSED: if (ictx && octx) @@ -829,52 +1018,30 @@ if (*ssa == sa) { if (!p->hmac_chk (ictx)) - slog (L_ERR, _("hmac authentication error, received invalid packet\n" - "could be an attack, or just corruption or an synchronization error")); + slog (L_ERR, _("%s(%s): hmac authentication error, received invalid packet\n" + "could be an attack, or just corruption or an synchronization error"), + conf->nodename, (const char *)sockinfo (ssa)); else { u32 seqno; tap_packet *d = p->unpack (this, seqno); - if (seqno <= iseqno - 32) - slog (L_ERR, _("received duplicate or outdated packet (received %08lx, expected %08lx)\n" - "possible replay attack, or just massive packet reordering"), seqno, iseqno + 1);//D - else if (seqno > iseqno + 32) - slog (L_ERR, _("received duplicate or out-of-sync packet (received %08lx, expected %08lx)\n" - "possible replay attack, or just massive packet loss"), seqno, iseqno + 1);//D - else + if (iseqno.recv_ok (seqno)) { - if (seqno > iseqno) - { - ismask <<= seqno - iseqno; - iseqno = seqno; - } - - u32 mask = 1 << (iseqno - seqno); - - //printf ("received seqno %08lx, iseqno %08lx, mask %08lx is %08lx\n", seqno, iseqno, mask, ismask); - if (ismask & mask) - slog (L_ERR, _("received duplicate packet (received %08lx, expected %08lx)\n" - "possible replay attack, or just packet duplication"), seqno, iseqno + 1);//D - else - { - ismask |= mask; - - vpn->tap->send (d); - - if (p->dst () == 0) // re-broadcast - for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i) - { - connection *c = *i; - - if (c->conf != THISNODE && c->conf != conf) - c->inject_data_packet (d); - } + vpn->tap->send (d); + + if (p->dst () == 0) // re-broadcast + for (vpn::conns_vector::iterator i = vpn->conns.begin (); i != vpn->conns.end (); ++i) + { + connection *c = *i; + + if (c->conf != THISNODE && c->conf != conf) + c->inject_data_packet (d); + } - delete d; + delete d; - break; - } + break; } } } @@ -945,41 +1112,36 @@ slog (L_TRACE, "<<%d PT_CONNECT_INFO(%d,%s) (%d)", conf->id, p->id, (const char *)p->si, !c->ictx && !c->octx); - c->send_auth (AUTH_INIT, p->si.sa ()); + c->send_auth_request (p->si.sa (), true); } + break; default: send_reset (ssa); break; + } } -void connection::timer () +void connection::keepalive_cb (tstamp &ts) { - if (conf != THISNODE) + if (NOW >= last_activity + ::conf.keepalive + 30) { - if (now >= next_retry && connectmode == conf_node::C_ALWAYS) - establish_connection (); - - if (ictx && octx) - { - if (now >= next_rekey) - rekey (); - else if (now >= last_activity + ::conf.keepalive + 30) - { - reset_connection (); - establish_connection (); - } - else if (now >= last_activity + ::conf.keepalive) - if (conf->connectmode != conf_node::C_ONDEMAND - || THISNODE->connectmode != conf_node::C_ONDEMAND) - send_ping (&sa); - else - reset_connection (); - - } + reset_connection (); + establish_connection (); } + else if (NOW < last_activity + ::conf.keepalive) + ts = last_activity + ::conf.keepalive; + else if (conf->connectmode != conf_node::C_ONDEMAND + || THISNODE->connectmode != conf_node::C_ONDEMAND) + { + send_ping (&sa); + ts = NOW + 5; + } + else + reset_connection (); + } void connection::connect_request (int id) @@ -995,7 +1157,7 @@ void connection::script_node () { - vpn->script_if_up (); + vpn->script_if_up (0); char *env; asprintf (&env, "DESTID=%d", conf->id); @@ -1008,7 +1170,7 @@ putenv (env); } -const char *connection::script_node_up () +const char *connection::script_node_up (int) { script_node (); @@ -1017,7 +1179,7 @@ return ::conf.script_node_up ? ::conf.script_node_up : "node-up"; } -const char *connection::script_node_down () +const char *connection::script_node_down (int) { script_node (); @@ -1026,16 +1188,31 @@ return ::conf.script_node_up ? ::conf.script_node_down : "node-down"; } -///////////////////////////////////////////////////////////////////////////// +connection::connection(struct vpn *vpn_) +: vpn(vpn_) +, rekey (this, &connection::rekey_cb) +, keepalive (this, &connection::keepalive_cb) +, establish_connection (this, &connection::establish_connection_cb) +{ + octx = ictx = 0; + retry_cnt = 0; -vpn::vpn (void) -{} + connectmode = conf_node::C_ALWAYS; // initial setting + reset_connection (); +} + +connection::~connection () +{ + shutdown (); +} + +///////////////////////////////////////////////////////////////////////////// -const char *vpn::script_if_up () +const char *vpn::script_if_up (int) { // the tunnel device mtu should be the physical mtu - overhead // the tricky part is rounding to the cipher key blocksize - int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - UDP_OVERHEAD; + int mtu = conf.mtu - ETH_OVERHEAD - VPE_OVERHEAD - MAX_OVERHEAD; mtu += ETH_OVERHEAD - 6 - 6; // now we have the data portion mtu -= mtu % EVP_CIPHER_block_size (CIPHER); // round mtu -= ETH_OVERHEAD - 6 - 6; // and get interface mtu again @@ -1090,14 +1267,20 @@ setsockopt (socket_fd, SOL_SOCKET, SO_REUSEADDR, &oval, sizeof oval); } + udp_ev_watcher.start (socket_fd, POLLIN); + tap = new tap_device (); if (!tap) //D this, of course, never catches { slog (L_ERR, _("cannot create network interface '%s'"), conf.ifname); exit (1); } + + run_script (run_script_cb (this, &vpn::script_if_up), true); + + vpn_ev_watcher.start (tap->fd, POLLIN); - run_script (this, &vpn::script_if_up, true); + reconnect_all (); return 0; } @@ -1172,181 +1355,159 @@ } void -vpn::main_loop () +vpn::udp_ev (short revents) { - struct pollfd pollfd[2]; - - pollfd[0].fd = tap->fd; - pollfd[0].events = POLLIN; - pollfd[1].fd = socket_fd; - pollfd[1].events = POLLIN; - - events = 0; - now = time (0); - next_timecheck = now + 1; - - reconnect_all (); - - for (;;) + if (revents & (POLLIN | POLLERR)) { - int npoll = poll (pollfd, 2, (next_timecheck - now) * 1000); - - now = time (0); + vpn_packet *pkt = new vpn_packet; + struct sockaddr_in sa; + socklen_t sa_len = sizeof (sa); + int len; - if (npoll > 0) - { - if (pollfd[1].revents) - { - if (pollfd[1].revents & (POLLIN | POLLERR)) - { - vpn_packet *pkt = new vpn_packet; - struct sockaddr_in sa; - socklen_t sa_len = sizeof (sa); - int len; - - len = recvfrom (socket_fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len); + len = recvfrom (socket_fd, &((*pkt)[0]), MAXSIZE, 0, (sockaddr *)&sa, &sa_len); - if (len > 0) - { - pkt->len = len; + if (len > 0) + { + pkt->len = len; - unsigned int src = pkt->src (); - unsigned int dst = pkt->dst (); + unsigned int src = pkt->src (); + unsigned int dst = pkt->dst (); - slog (L_NOISE, _("<typ (), pkt->src (), pkt->dst (), pkt->len); + slog (L_NOISE, _("<typ (), pkt->src (), pkt->dst (), pkt->len); - if (dst > conns.size () || pkt->typ () >= vpn_packet::PT_MAX) - slog (L_WARN, _("<typ (), pkt->src (), pkt->dst ()); - else if (dst == 0 && !THISNODE->routerprio) - slog (L_WARN, _("<<%d received broadcast, but we are no router"), dst); - else if (dst != 0 && dst != THISNODE->id) - slog (L_WARN, - _("received frame for node %d ('%s') from %s, but this is node %d ('%s')"), - dst, conns[dst - 1]->conf->nodename, - (const char *)sockinfo (sa), - THISNODE->id, THISNODE->nodename); - else if (src == 0 || src > conns.size ()) - slog (L_WARN, _("received frame from unknown node %d (%s)"), src, (const char *)sockinfo (sa)); - else - conns[src - 1]->recv_vpn_packet (pkt, &sa); - } - else - { - // probably ECONNRESET or somesuch - slog (L_DEBUG, _("%s: %s"), (const char *)sockinfo(sa), strerror (errno)); - } + if (dst > conns.size () || pkt->typ () >= vpn_packet::PT_MAX) + slog (L_WARN, _("<typ (), pkt->src (), pkt->dst ()); + else if (dst == 0 && !THISNODE->routerprio) + slog (L_WARN, _("<<%d received broadcast, but we are no router"), dst); + else if (dst != 0 && dst != THISNODE->id) + slog (L_WARN, + _("received frame for node %d ('%s') from %s, but this is node %d ('%s')"), + dst, conns[dst - 1]->conf->nodename, + (const char *)sockinfo (sa), + THISNODE->id, THISNODE->nodename); + else if (src == 0 || src > conns.size ()) + slog (L_WARN, _("received frame from unknown node %d (%s)"), src, (const char *)sockinfo (sa)); + else + conns[src - 1]->recv_vpn_packet (pkt, &sa); + } + else + { + // probably ECONNRESET or somesuch + slog (L_DEBUG, _("%s: %s"), (const char *)sockinfo(sa), strerror (errno)); + } - delete pkt; - } - else if (pollfd[1].revents & POLLHUP) - { - // this cannot ;) happen on udp sockets - slog (L_ERR, _("FATAL: POLLHUP on socket fd, terminating.")); - exit (1); - } - else - { - slog (L_ERR, - _("FATAL: unknown revents %08x in socket, terminating\n"), - pollfd[1].revents); - exit (1); - } - } + delete pkt; + } + else if (revents & POLLHUP) + { + // this cannot ;) happen on udp sockets + slog (L_ERR, _("FATAL: POLLHUP on socket fd, terminating.")); + exit (1); + } + else + { + slog (L_ERR, + _("FATAL: unknown revents %08x in socket, terminating\n"), + revents); + exit (1); + } +} - // I use else here to give vpn_packets absolute priority - else if (pollfd[0].revents) - { - if (pollfd[0].revents & POLLIN) - { - /* process data */ - tap_packet *pkt; +void +vpn::vpn_ev (short revents) +{ + if (revents & POLLIN) + { + /* process data */ + tap_packet *pkt; - pkt = tap->recv (); + pkt = tap->recv (); - int dst = mac2id (pkt->dst); - int src = mac2id (pkt->src); + int dst = mac2id (pkt->dst); + int src = mac2id (pkt->src); - if (src != THISNODE->id) - { - slog (L_ERR, _("FATAL: tap packet not originating on current node received, terminating.")); - exit (1); - } + if (src != THISNODE->id) + { + slog (L_ERR, _("FATAL: tap packet not originating on current node received, terminating.")); + exit (1); + } - if (dst == THISNODE->id) - { - slog (L_ERR, _("FATAL: tap packet destined for current node received, terminating.")); - exit (1); - } + if (dst == THISNODE->id) + { + slog (L_ERR, _("FATAL: tap packet destined for current node received, terminating.")); + exit (1); + } - if (dst > conns.size ()) - slog (L_ERR, _("tap packet for unknown node %d received, ignoring."), dst); - else - { - if (dst) - { - // unicast - if (dst != THISNODE->id) - conns[dst - 1]->inject_data_packet (pkt); - } - else - { - // broadcast, first check router, then self, then english - connection *router = find_router (); - - if (router) - router->inject_data_packet (pkt, true); - else - for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c) - if ((*c)->conf != THISNODE) - (*c)->inject_data_packet (pkt); - } - } + if (dst > conns.size ()) + slog (L_ERR, _("tap packet for unknown node %d received, ignoring."), dst); + else + { + if (dst) + { + // unicast + if (dst != THISNODE->id) + conns[dst - 1]->inject_data_packet (pkt); + } + else + { + // broadcast, first check router, then self, then english + connection *router = find_router (); - delete pkt; - } - else if (pollfd[0].revents & (POLLHUP | POLLERR)) - { - slog (L_ERR, _("FATAL: POLLHUP or POLLERR on network device fd, terminating.")); - exit (1); - } + if (router) + router->inject_data_packet (pkt, true); else - abort (); + for (conns_vector::iterator c = conns.begin (); c != conns.end (); ++c) + if ((*c)->conf != THISNODE) + (*c)->inject_data_packet (pkt); } } - if (events) - { - if (events & EVENT_SHUTDOWN) - { - shutdown_all (); - - remove_pid (pidfilename); + delete pkt; + } + else if (revents & (POLLHUP | POLLERR)) + { + slog (L_ERR, _("FATAL: POLLHUP or POLLERR on network device fd, terminating.")); + exit (1); + } + else + abort (); +} - slog (L_INFO, _("vped terminating")); +void +vpn::event_cb (tstamp &ts) +{ + if (events) + { + if (events & EVENT_SHUTDOWN) + { + shutdown_all (); - exit (0); - } + remove_pid (pidfilename); - if (events & EVENT_RECONNECT) - reconnect_all (); + slog (L_INFO, _("vped terminating")); - events = 0; + exit (0); } - // very very very dumb and crude and inefficient timer handling, or maybe not? - if (now >= next_timecheck) - { - next_timecheck = now + TIMER_GRANULARITY; + if (events & EVENT_RECONNECT) + reconnect_all (); - for (conns_vector::iterator c = conns.begin (); - c != conns.end (); ++c) - (*c)->timer (); - } + events = 0; } + + ts = TSTAMP_CANCEL; +} + +vpn::vpn (void) +: udp_ev_watcher (this, &vpn::udp_ev) +, vpn_ev_watcher (this, &vpn::vpn_ev) +, event (this, &vpn::event_cb) +{ } vpn::~vpn () -{} +{ +}