anytun-0.3.8/0000775000175000017500000000000013604635455013017 5ustar equinoxequinoxanytun-0.3.8/version0000664000175000017500000000000613604635444014421 0ustar equinoxequinox0.3.8 anytun-0.3.8/usr/0000775000175000017500000000000013604635433013624 5ustar equinoxequinoxanytun-0.3.8/usr/lib/0000775000175000017500000000000013604635433014372 5ustar equinoxequinoxanytun-0.3.8/usr/lib/systemd/0000775000175000017500000000000013604635433016062 5ustar equinoxequinoxanytun-0.3.8/usr/lib/systemd/system/0000775000175000017500000000000013604635433017406 5ustar equinoxequinoxanytun-0.3.8/usr/lib/systemd/system/anytun-controld@.service0000664000175000017500000000070213604635433024227 0ustar equinoxequinox[Unit] Description=secure anycast tunneling config daemon for %i PartOf=anytun.service After=anytun@%i.service Documentation=man:anytun-controld(8) [Service] Type=simple PIDFile=/run/anytun-controld/%i.pid Environment="NAME=%i" "DAEMONOPTS=-D -L stdout:3 --username anytun" ExecStart=/usr/local/lib/anytun-launcher configd Restart=on-failure PrivateTmp=yes PrivateDevices=yes ProtectSystem=full ProtectHome=yes [Install] WantedBy=multi-user.target anytun-0.3.8/usr/lib/systemd/system/anytun.service0000664000175000017500000000031713604635433022307 0ustar equinoxequinox[Unit] Description=Anytun Service After=network.target [Service] Type=oneshot RemainAfterExit=yes ExecStart=/bin/true ExecReload=/bin/true WorkingDirectory=/etc/anytun [Install] WantedBy=multi-user.target anytun-0.3.8/usr/lib/systemd/system/anytun@.service0000664000175000017500000000070213604635433022405 0ustar equinoxequinox[Unit] Description=secure anycast tunneling daemon for %i PartOf=anytun.service Requires=anytun-controld@%i.service Documentation=man:anytun(8) [Service] Type=simple PIDFile=/run/anytun/%i.pid Environment="NAME=%i" "DAEMONOPTS=-D --username anytun" ExecStart=/usr/local/lib/anytun-launcher vpn Restart=on-failure PrivateTmp=yes ProtectSystem=full ProtectHome=yes DeviceAllow=/dev/net/tun rw DevicePolicy=closed [Install] WantedBy=multi-user.target anytun-0.3.8/usr/lib/systemd/system-generator/0000775000175000017500000000000013604635433021372 5ustar equinoxequinoxanytun-0.3.8/usr/lib/systemd/system-generator/anytun-generator0000775000175000017500000000107713604635433024627 0ustar equinoxequinox#!/bin/sh # This systemd generator creates dependency symlinks that make all anytun # tunnels listed in /etc/anytun/autostart be started/stopped/reloaded # when anytun.service is started/stopped/reloaded. set -eu GENDIR="$1" WANTDIR="$1/anytun.service.wants" SERVICEFILE="/lib/systemd/system/anytun@.service" AUTOSTART="all" CONFIG_DIR=/usr/local/etc/anytun mkdir -p "$WANTDIR" if [ -f $CONFIG_DIR/autostart ] ; then for NAME in `sed 's/#.*//' < $CONFIG_DIR/autostart | grep -e '\w'`; do ln -s "$SERVICEFILE" "$WANTDIR/anytun@$NAME.service" done fi exit 0 anytun-0.3.8/usr/lib/tmpfiles.d/0000775000175000017500000000000013604635433016437 5ustar equinoxequinoxanytun-0.3.8/usr/lib/tmpfiles.d/anytun.conf0000664000175000017500000000011713604635433020623 0ustar equinoxequinoxd /run/anytun-controld 0700 anytun anytun - d /run/anytun 0700 anytun anytun - anytun-0.3.8/usr/lib/anytun-launcher0000775000175000017500000000347613604635433017447 0ustar equinoxequinox#!/bin/sh NAME="${NAME:-$2}" DAEMON=/usr/local/sbin/anytun ANYTUNCONFIG=/usr/local/bin/anytun-config CONTROLDAEMON=/usr/local/bin/anytun-controld CONFIG_DIR=/usr/local/etc/anytun VARRUN_DIR=/run/anytun VARCONTROL_DIR=/run/anytun-controld test -x $DAEMON || exit 0 test -z $NAME && exit 1 start_vpn () { if [ -f $CONFIG_DIR/$NAME/config ] ; then POSTUP='' test -f $CONFIG_DIR/$NAME/post-up.sh && POSTUP="-x $CONFIG_DIR/$NAME/post-up.sh" CHROOTDIR=`grep '^chroot' < $CONFIG_DIR/$NAME/config | sed 's/chroot\s*//'` if [ -n "$CHROOTDIR" ] ; then test -d $CHROOTDIR || mkdir -p $CHROOTDIR fi test -d $VARRUN_DIR || mkdir -p $VARRUN_DIR DAEMONARG=`sed 's/#.*//' < $CONFIG_DIR/$NAME/config | grep -e '\w' | sed 's/^/--/' | tr '\n' ' '` exec $DAEMON --write-pid $VARRUN_DIR/$NAME.pid $POSTUP $DAEMONOPTS $DAEMONARG else echo "no config found" >&2 return 1 fi } start_configd () { if [ -d $CONFIG_DIR/$NAME/conf.d ] ; then test -d $VARCONTROL_DIR || mkdir -p $VARCONTROL_DIR chmod 700 $VARCONTROL_DIR rm -f $VARCONTROL_DIR/$NAME 2>/dev/null KDPRF=`sed 's/#.*//' < $CONFIG_DIR/$NAME/config | grep -e 'kd-prf' | sed 's/^/ --/' | xargs echo` for CLIENTNAME in `ls $CONFIG_DIR/$NAME/conf.d`; do echo -n " ($CLIENTNAME)" DAEMONARG=`sed 's/#.*//' < $CONFIG_DIR/$NAME/conf.d/$CLIENTNAME | grep -e '\w' | sed 's/^/ --/' | xargs echo` $ANYTUNCONFIG $DAEMONARG $CIPHER $AUTHALGO $KDPRF >> $VARCONTROL_DIR/$NAME done CONTROLHOST=`sed 's/#.*//' < $CONFIG_DIR/$NAME/config | grep -e 'control-host' | sed 's/^/ --/' | xargs echo` exec $CONTROLDAEMON -f $VARCONTROL_DIR/$NAME $DAEMONOPTS $CONTROLHOST \ --write-pid $VARCONTROL_DIR/$NAME.pid fi } case $1 in vpn) start_vpn ;; configd) start_configd ;; *) exit 2 ;; esac anytun-0.3.8/ChangeLog0000664000175000017500000000564513604635433014577 0ustar equinoxequinox2020.01.06 -- version 0.3.8 * fix build for Boost 1.71 2018.06.08 -- version 0.3.7 * fix build for new versions of GCC and Boost * add support for OpenSSL 1.1 2016.07.08 -- Version 0.3.6 * fixed build for GCC-6 and C++0x * fixed some libgcrypt warnings @ anytun-showtables and anytun-config * added systemd unit files and gernator 2014.08.26 -- Version 0.3.5 * added an exception to the license which allows linking with OpenSSL * added support for clang * added libnettle as additional crypto library option * fixed mutli-threading support for libgcrypt 1.6.0 and newer 2011.12.30 -- Version 0.3.4 * Service Release: several build fixes for newer versions of libboost and gcc * formatting cleanups 2010.2.16 -- Version 0.3.3 * Security fix: packet length check errors * fixed dropping of priveleges on FreeBSD * added sysExec for Windows * added multi socket support which allows simultanous usage of IPv4 and IPv6 even on operating systems without V4_MAPPED address support * added workaround for signalhandling on Debian GNU/kFreebsd * added -v|--version option * added prebuilt manpage to release tarball (less build deps) 2009.12.02 -- Version 0.3.2 * added 64bit build target to windows build system * added install target to build system * cleaned up manpages * moved to new svn location 2009.10.28 -- Version 0.3.1 svn852 * switched to GPLv3 or higher * Changed Windows TAP driver version to support 64-bit windows * fixed some memory errors * improved logging * improved post up script execution * builds on FreeBSD now 2009.5.1 -- Version 0.3 svn834 * updated to new protocol specification (extended label and crypto role) Due to this changes this version is incompatible to version 0.2 and prior * the auth tag length can now be configured * added extended logging support (syslog, file stdout and stderr) * changed -n|--ifconfig parameter to new behavior tun and tap devices now use the same syntax * added seperate resolver thread * fixed packet length errors * dropping privileges is now possible wihtout chroot * full ipv6 support - ipv6 multiple connection routing - syncronisation over ipv6 - 4in6,6in6 tunnels * replaced several dependencies with boost libs * ported basic functionality to Windows * dropped OpenBSD Port due to multi threading issues * code cleanup 2008.6.20 -- Version 0.2.1svn556 * finished own tun/tap devices and removed openvpn source code currently there are tun/tap devices for Linux, FreeBSD, OpenBSD and NetBSD * several fixes for building on OpenBSD * added manpages for all binaries * switched to GPLv3 2008.4.12 -- Version 0.2svn490 * updated to Internet Draft Revision 02 Mind that the this version is incompatible to version 0.1 However this is only the case if you use encryption. There shouldn't be any Problem with NULL cipher * several fixes for tunneling IPv6 2008.3.18 -- Version 0.1svn441 * Initial release. * IPv4 tunnel over UDP, with AES-CTR cipher and SHA1 HMAC signature. anytun-0.3.8/AUTHORS0000664000175000017500000000021113604635433014055 0ustar equinoxequinoxMarkus Grüneis Othmar Gsenger Erwin Nindl Christian Pointner anytun-0.3.8/src/0000775000175000017500000000000013604635433013602 5ustar equinoxequinoxanytun-0.3.8/src/keyDerivationFactory.h0000664000175000017500000000500713604635433020122 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_keyDerivationFactory_h_INCLUDED #define ANYTUN_keyDerivationFactory_h_INCLUDED #include #include "datatypes.h" #include "keyDerivation.h" class KeyDerivationFactory { public: static KeyDerivation* create(std::string const& type); private: KeyDerivationFactory(); KeyDerivationFactory(const KeyDerivationFactory& src); void operator=(const KeyDerivationFactory& src); ~KeyDerivationFactory(); }; #endif anytun-0.3.8/src/cipher.cpp0000664000175000017500000001705113604635433015564 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include "endian.h" #include "cipher.h" #if defined(USE_NETTLE) #include #endif #include "log.h" #include "anytunError.h" void Cipher::encrypt(KeyDerivation& kd, PlainPacket& in, EncryptedPacket& out, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { uint32_t len = cipher(kd, in, in.getLength(), out.getPayload(), out.getPayloadLength(), seq_nr, sender_id, mux); out.setSenderId(sender_id); out.setSeqNr(seq_nr); out.setMux(mux); out.setPayloadLength(len); } void Cipher::decrypt(KeyDerivation& kd, EncryptedPacket& in, PlainPacket& out) { uint32_t len = decipher(kd, in.getPayload() , in.getPayloadLength(), out, out.getLength(), in.getSeqNr(), in.getSenderId(), in.getMux()); out.setLength(len); } //******* NullCipher ******* uint32_t NullCipher::cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { std::memcpy(out, in, (ilen < olen) ? ilen : olen); return (ilen < olen) ? ilen : olen; } uint32_t NullCipher::decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { std::memcpy(out, in, (ilen < olen) ? ilen : olen); return (ilen < olen) ? ilen : olen; } #ifndef NO_CRYPT //****** AesIcmCipher ****** AesIcmCipher::AesIcmCipher(kd_dir_t d) : Cipher(d), key_(uint32_t(DEFAULT_KEY_LENGTH/8)), salt_(uint32_t(SALT_LENGTH)) { init(); } AesIcmCipher::AesIcmCipher(kd_dir_t d, uint16_t key_length) : Cipher(d), key_(uint32_t(key_length/8)), salt_(uint32_t(SALT_LENGTH)) { init(key_length); } void AesIcmCipher::init(uint16_t key_length) { #if defined(USE_SSL_CRYPTO) // nothing here #elif defined(USE_NETTLE) // nothing here #else // USE_GCRYPT is the default handle_ = NULL; int algo; switch(key_length) { case 128: algo = GCRY_CIPHER_AES128; break; case 192: algo = GCRY_CIPHER_AES192; break; case 256: algo = GCRY_CIPHER_AES256; break; default: { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher::AesIcmCipher: cipher key length of " << key_length << " Bits is not supported"; return; } } gcry_error_t err = gcry_cipher_open(&handle_, algo, GCRY_CIPHER_MODE_CTR, 0); if(err) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher::AesIcmCipher: Failed to open cipher" << AnytunGpgError(err); } #endif } AesIcmCipher::~AesIcmCipher() { #if defined(USE_SSL_CRYPTO) // nothing here #elif defined(USE_NETTLE) // nothing here #else // USE_GCRYPT is the default if(handle_) { gcry_cipher_close(handle_); } #endif } uint32_t AesIcmCipher::cipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { calc(kd, in, ilen, out, olen, seq_nr, sender_id, mux); return (ilen < olen) ? ilen : olen; } uint32_t AesIcmCipher::decipher(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { calc(kd, in, ilen, out, olen, seq_nr, sender_id, mux); return (ilen < olen) ? ilen : olen; } void AesIcmCipher::calcCtr(KeyDerivation& kd, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { kd.generate(dir_, LABEL_SALT, seq_nr, salt_); std::memcpy(ctr_.salt_.buf_, salt_.getBuf(), SALT_LENGTH); ctr_.salt_.zero_ = 0; ctr_.params_.mux_ ^= MUX_T_HTON(mux); ctr_.params_.sender_id_ ^= SENDER_ID_T_HTON(sender_id); ctr_.params_.seq_nr_ ^= SEQ_NR_T_HTON(seq_nr); return; } void AesIcmCipher::calc(KeyDerivation& kd, uint8_t* in, uint32_t ilen, uint8_t* out, uint32_t olen, seq_nr_t seq_nr, sender_id_t sender_id, mux_t mux) { #if defined(USE_GCRYPT) if(!handle_) { return; } #endif kd.generate(dir_, LABEL_ENC, seq_nr, key_); #if defined(USE_SSL_CRYPTO) int ret = AES_set_encrypt_key(key_.getBuf(), key_.getLength()*8, &aes_key_); if(ret) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher ssl key (code: " << ret << ")"; return; } #elif defined(USE_NETTLE) aes_set_encrypt_key(&ctx_, key_.getLength(), key_.getBuf()); #else // USE_GCRYPT is the default gcry_error_t err = gcry_cipher_setkey(handle_, key_.getBuf(), key_.getLength()); if(err) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher key: " << AnytunGpgError(err); return; } #endif calcCtr(kd, seq_nr, sender_id, mux); #if defined(USE_SSL_CRYPTO) if(CTR_LENGTH != AES_BLOCK_SIZE) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: size doesn't fit"; return; } unsigned int num = 0; std::memset(ecount_buf_, 0, AES_BLOCK_SIZE); CRYPTO_ctr128_encrypt(in, out, (ilen < olen) ? ilen : olen, &aes_key_, ctr_.buf_, ecount_buf_, &num, (block128_f)AES_encrypt); #elif defined(USE_NETTLE) if(CTR_LENGTH != AES_BLOCK_SIZE) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: size doesn't fit"; return; } ctr_crypt(&ctx_, (nettle_crypt_func *)(aes_encrypt), AES_BLOCK_SIZE, ctr_.buf_, (ilen < olen) ? ilen : olen, out, in); #else // USE_GCRYPT is the default err = gcry_cipher_setctr(handle_, ctr_.buf_, CTR_LENGTH); if(err) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to set cipher CTR: " << AnytunGpgError(err); return; } err = gcry_cipher_encrypt(handle_, out, olen, in, ilen); if(err) { cLog.msg(Log::PRIO_ERROR) << "AesIcmCipher: Failed to de/encrypt packet: " << AnytunGpgError(err); return; } #endif } #endif anytun-0.3.8/src/syncConnectionCommand.h0000664000175000017500000000554213604635433020254 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_syncConnectionCommands_h_INCLUDED #define ANYTUN_syncConnectionCommands_h_INCLUDED #include #include #include "connectionList.h" #include "threadUtils.hpp" class SyncConnectionCommand { public: SyncConnectionCommand(ConnectionList& cl); SyncConnectionCommand(ConnectionList& cl ,uint16_t mux); uint16_t getMux() const; private: SyncConnectionCommand(const SyncConnectionCommand&); ConnectionList& cl_; uint16_t mux_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(cl_.getMutex()); ar& mux_; ConnectionParam& conn = cl_.getOrNewConnectionUnlocked(mux_); ar& conn; } }; #endif anytun-0.3.8/src/seqWindow.h0000664000175000017500000000641213604635433015736 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_seqWindow_h_INCLUDED #define ANYTUN_seqWindow_h_INCLUDED #include #include #include #include #include "threadUtils.hpp" #include "datatypes.h" class SeqWindow; class SeqWindowElement { public: SeqWindowElement(); ~SeqWindowElement(); void init(window_size_t w, seq_nr_t m); seq_nr_t max_; window_size_t pos_; uint8_t* window_; }; class SeqWindow { public: typedef std::map SenderMap; SeqWindow(window_size_t w); ~SeqWindow(); bool checkAndAdd(sender_id_t sender, seq_nr_t seq_nr); void clear(sender_id_t sender); void clear(); private: window_size_t window_size_; Mutex mutex_; SenderMap sender_; SeqWindow(const SeqWindow& s); void operator=(const SeqWindow& s); friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(mutex_); //unsigned int serial = (unsigned int) window_size_; //window_size_t serial = (window_size_t) window_size_; ar& window_size_; //TODO: Do not sync complete Sender Map! // ar & sender_; } }; #endif anytun-0.3.8/src/buffer.cpp0000664000175000017500000001555613604635433015573 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include #include #include "datatypes.h" #include "buffer.h" Buffer::Buffer(bool allow_realloc) : buf_(0), length_(0), real_length_(0), allow_realloc_(allow_realloc) { } Buffer::Buffer(uint32_t length, bool allow_realloc) : length_(length), real_length_(length_ + Buffer::OVER_SIZE_), allow_realloc_(allow_realloc) { buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } std::memset(buf_, 0, real_length_); } Buffer::Buffer(uint8_t* data, uint32_t length, bool allow_realloc) : length_(length), real_length_(length + Buffer::OVER_SIZE_), allow_realloc_(allow_realloc) { if(!data) { length_ = 0; real_length_ = 0; return; } buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } std::memcpy(buf_, data, length_); } Buffer::Buffer(std::string hex_data, bool allow_realloc) : length_(static_cast(hex_data.size())/2), real_length_(length_ + Buffer::OVER_SIZE_), allow_realloc_(allow_realloc) { buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } for(uint32_t i=0; i> std::hex >> tmp)) { tmp = 0; } buf_[i] = static_cast(tmp); } } Buffer::~Buffer() { if(buf_) { delete[] buf_; } } Buffer::Buffer(const Buffer& src) : length_(src.length_), real_length_(src.real_length_), allow_realloc_(src.allow_realloc_) { buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } std::memcpy(buf_, src.buf_, length_); } void Buffer::operator=(const Buffer& src) { if(buf_) { delete[] buf_; } length_ = src.length_; real_length_ = src.real_length_; allow_realloc_ = src.allow_realloc_; buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; throw std::bad_alloc(); } std::memcpy(buf_, src.buf_, length_); } bool Buffer::operator==(const Buffer& cmp) const { if(length_ != cmp.length_) { return false; } if(!std::memcmp(buf_, cmp.buf_, length_)) { return true; } return false; } Buffer Buffer::operator^(const Buffer& xor_by) const { uint32_t res_length = (xor_by.length_ > length_) ? xor_by.length_ : length_; uint32_t min_length = (xor_by.length_ < length_) ? xor_by.length_ : length_; Buffer res(res_length); for(uint32_t index = 0; index < min_length; index++) { res[index] = buf_[index] ^ xor_by[index]; } return res; } uint32_t Buffer::getLength() const { return length_; } void Buffer::setLength(uint32_t new_length) { if(new_length == length_) { return; } if(new_length > real_length_) { if(!allow_realloc_) { throw std::out_of_range("buffer::setLength() - reallocation not allowed for this Buffer"); } uint8_t* old_buf = buf_; uint32_t old_length = length_; length_ = new_length; real_length_ = length_ + Buffer::OVER_SIZE_; buf_ = new uint8_t[real_length_]; if(!buf_) { length_ = 0; real_length_ = 0; if(old_buf) { delete[] old_buf; } throw std::bad_alloc(); } std::memcpy(buf_, old_buf, old_length); if(old_buf) { delete[] old_buf; } old_buf = &buf_[old_length]; std::memset(old_buf, 0, real_length_ - old_length); } else { length_ = new_length; } reinit(); } uint8_t* Buffer::getBuf() { return buf_; } uint8_t& Buffer::operator[](uint32_t index) { if(index >= length_) { throw std::out_of_range("buffer::operator[]"); } return buf_[index]; } uint8_t Buffer::operator[](uint32_t index) const { if(index >= length_) { throw std::out_of_range("buffer::operator[] const"); } return buf_[index]; } Buffer::operator uint8_t*() { return buf_; } std::string Buffer::getHexDump() const { std::stringstream ss; ss << "Length=" << length_ << std::endl << std::hex << std::uppercase; for(uint32_t index = 0; index < length_; index++) { ss << std::setw(2) << std::setfill('0') << uint32_t(buf_[index]) << " "; if(!((index+1) % 16)) { ss << std::endl; continue; } if(!((index+1) % 8)) { ss << " "; } } return ss.str(); } std::string Buffer::getHexDumpOneLine() const { std::stringstream ss; ss << length_ << " Bytes,'" << std::hex << std::uppercase; for(uint32_t index = 0; index < length_; index++) { ss << std::setw(2) << std::setfill('0') << uint32_t(buf_[index]); } ss << "'"; return ss.str(); } bool Buffer::isReallocAllowed() const { return allow_realloc_; } anytun-0.3.8/src/tunDevice.h0000664000175000017500000000743513604635433015712 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_tunDevice_h_INCLUDED #define ANYTUN_tunDevice_h_INCLUDED #include "buffer.h" #include "deviceConfig.hpp" #include "threadUtils.hpp" #if !defined(_MSC_VER) && !defined(MINGW) #include "sysExec.h" #else #include #endif class TunDevice { public: TunDevice(std::string dev,std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix); ~TunDevice(); int read(uint8_t* buf, uint32_t len); int write(uint8_t* buf, uint32_t len); const char* getActualName() const { return actual_name_.c_str(); } const char* getActualNode() const { return actual_node_.c_str(); } device_type_t getType() const { return conf_.type_; } void waitUntilReady(); const char* getTypeString() const { #if !defined(_MSC_VER) && !defined(MINGW) if(fd_ < 0) #else if(handle_ == INVALID_HANDLE_VALUE) #endif return ""; switch(conf_.type_) { case TYPE_UNDEF: return "undef"; break; case TYPE_TUN: return "tun"; break; case TYPE_TAP: return "tap"; break; } return ""; } private: void operator=(const TunDevice& src); TunDevice(const TunDevice& src); void init_post(); void do_ifconfig(); int fix_return(int ret, size_t pi_length) const; #if !defined(_MSC_VER) && !defined(MINGW) int fd_; #else bool getAdapter(std::string const& dev_name); DWORD performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, LPVOID outBuffer, DWORD outBufferSize); HANDLE handle_; OVERLAPPED roverlapped_, woverlapped_; #endif DeviceConfig conf_; #if !defined(_MSC_VER) && !defined(MINGW) SysExec* sys_exec_; #endif bool with_pi_; std::string actual_name_; std::string actual_node_; }; #endif anytun-0.3.8/src/packetSource.cpp0000664000175000017500000001343313604635433016742 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include "datatypes.h" #include "packetSource.h" #include "log.h" #include "resolver.h" #include "options.h" #include "signalController.h" #include "anytunError.h" void PacketSource::waitUntilReady() { ready_sem_.down(); } UDPPacketSource::UDPPacketSource(std::string localaddr, std::string port) { gResolver.resolveUdp(localaddr, port, boost::bind(&UDPPacketSource::onResolve, this, _1), boost::bind(&UDPPacketSource::onError, this, _1), gOpt.getResolvAddrType()); } UDPPacketSource::~UDPPacketSource() { std::list::iterator it = sockets_.begin(); for(; it != sockets_.end(); ++it) { /// this might be a needed by the receiver thread, TODO cleanup // delete[](it->buf_); // delete(it->sem_); // delete(it->sock_); } } void UDPPacketSource::onResolve(PacketSourceResolverIt it) { while(it != PacketSourceResolverIt()) { PacketSourceEndpoint e = *it; cLog.msg(Log::PRIO_NOTICE) << "opening socket: " << e; SocketsElement sock; sock.buf_ = NULL; sock.len_ = 0; sock.sem_ = NULL; sock.sock_ = new proto::socket(io_service_); if(!sock.sock_) { AnytunError::throwErr() << "memory error"; } sock.sock_->open(e.protocol()); #if !defined(_MSC_VER) && !defined(MINGW) if(e.protocol() == proto::v6()) { sock.sock_->set_option(boost::asio::ip::v6_only(true)); } #endif sock.sock_->bind(e); sockets_.push_back(sock); it++; } // prepare multi-socket recv if(sockets_.size() > 1) { std::list::iterator it = sockets_.begin(); for(; it != sockets_.end(); ++it) { it->len_ = MAX_PACKET_LENGTH; it->buf_ = new uint8_t[it->len_]; if(!it->buf_) { AnytunError::throwErr() << "memory error"; } it->sem_ = new Semaphore(); if(!it->sem_) { delete[](it->buf_); AnytunError::throwErr() << "memory error"; } boost::thread(boost::bind(&UDPPacketSource::recv_thread, this, it)); it->sem_->up(); } } ready_sem_.up(); } void UDPPacketSource::onError(const std::runtime_error& e) { gSignalController.inject(SIGERROR, e.what()); } void UDPPacketSource::recv_thread(std::list::iterator it) { cLog.msg(Log::PRIO_INFO) << "started receiver thread for " << it->sock_->local_endpoint(); ThreadResult result; result.it_ = it; for(;;) { it->sem_->down(); result.len_ = static_cast(it->sock_->receive_from(boost::asio::buffer(it->buf_, it->len_), result.remote_)); { Lock lock(thread_result_mutex_); thread_result_queue_.push(result); } thread_result_sem_.up(); } } uint32_t UDPPacketSource::recv(uint8_t* buf, uint32_t len, PacketSourceEndpoint& remote) { if(sockets_.size() == 1) { return static_cast(sockets_.front().sock_->receive_from(boost::asio::buffer(buf, len), remote)); } thread_result_sem_.down(); ThreadResult result; { Lock lock(thread_result_mutex_); result = thread_result_queue_.front(); thread_result_queue_.pop(); } remote = result.remote_; std::memcpy(buf, result.it_->buf_, (len < result.len_) ? len : result.len_); len = (len < result.len_) ? len : result.len_; result.it_->sem_->up(); return len; } void UDPPacketSource::send(uint8_t* buf, uint32_t len, PacketSourceEndpoint remote) { std::list::iterator it = sockets_.begin(); for(; it != sockets_.end(); ++it) { if(it->sock_->local_endpoint().protocol() == remote.protocol()) { it->sock_->send_to(boost::asio::buffer(buf, len), remote); return; } } cLog.msg(Log::PRIO_WARNING) << "no suitable socket found for remote endpoint protocol: " << remote; } anytun-0.3.8/src/authAlgo.cpp0000664000175000017500000001566213604635433016064 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "authAlgo.h" #include "log.h" #include "anytunError.h" #include "buffer.h" #include "encryptedPacket.h" #include #include //****** NullAuthAlgo ****** void NullAuthAlgo::generate(KeyDerivation& kd, EncryptedPacket& packet) { } bool NullAuthAlgo::checkTag(KeyDerivation& kd, EncryptedPacket& packet) { return true; } #ifndef NO_CRYPT //****** Sha1AuthAlgo ****** Sha1AuthAlgo::Sha1AuthAlgo(kd_dir_t d) : AuthAlgo(d), key_(DIGEST_LENGTH) { #if defined(USE_SSL_CRYPTO) ctx_ = NULL; #elif defined(USE_NETTLE) // nothing here #else // USE_GCRYPT is the default handle_ = 0; #endif } bool Sha1AuthAlgo::Init() { #if defined(USE_SSL_CRYPTO) # if OPENSSL_VERSION_NUMBER >= 0x10100000L if ((ctx_ = HMAC_CTX_new()) == NULL) { return false; } # else if ((ctx_ = (HMAC_CTX*)calloc(1, sizeof(HMAC_CTX))) == NULL) { return false; } HMAC_CTX_init(ctx_); # endif HMAC_Init_ex(ctx_, NULL, 0, EVP_sha1(), NULL); #elif defined(USE_NETTLE) // nothing here #else // USE_GCRYPT is the default gcry_error_t err = gcry_md_open(&handle_, GCRY_MD_SHA1, GCRY_MD_FLAG_HMAC); if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::Sha1AuthAlgo: Failed to open message digest algo"; return false; } #endif return true; } Sha1AuthAlgo::~Sha1AuthAlgo() { #if defined(USE_SSL_CRYPTO) if(ctx_) { # if OPENSSL_VERSION_NUMBER >= 0x10100000L HMAC_CTX_free(ctx_); # else HMAC_CTX_cleanup(ctx_); free(ctx_); # endif } #elif defined(USE_NETTLE) // nothing here #else // USE_GCRYPT is the default if(handle_) { gcry_md_close(handle_); } #endif } void Sha1AuthAlgo::generate(KeyDerivation& kd, EncryptedPacket& packet) { #if defined(USE_GCRYPT) if(!handle_) { return; } #endif packet.addAuthTag(); if(!packet.getAuthTagLength()) { return; } kd.generate(dir_, LABEL_AUTH, packet.getSeqNr(), key_); #if defined(USE_SSL_CRYPTO) HMAC_Init_ex(ctx_, key_.getBuf(), key_.getLength(), EVP_sha1(), NULL); uint8_t hmac[DIGEST_LENGTH]; HMAC_Update(ctx_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); HMAC_Final(ctx_, hmac, NULL); #elif defined(USE_NETTLE) hmac_sha1_set_key(&ctx_, key_.getLength(), key_.getBuf()); uint8_t hmac[DIGEST_LENGTH]; hmac_sha1_update(&ctx_, packet.getAuthenticatedPortionLength(), packet.getAuthenticatedPortion()); hmac_sha1_digest(&ctx_, DIGEST_LENGTH, hmac); #else // USE_GCRYPT is the default gcry_error_t err = gcry_md_setkey(handle_, key_.getBuf(), key_.getLength()); if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::setKey: Failed to set hmac key: " << AnytunGpgError(err); return; } gcry_md_reset(handle_); gcry_md_write(handle_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); gcry_md_final(handle_); uint8_t* hmac = gcry_md_read(handle_, 0); #endif uint8_t* tag = packet.getAuthTag(); uint32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; if(length > DIGEST_LENGTH) { std::memset(tag, 0, packet.getAuthTagLength()); } std::memcpy(&tag[packet.getAuthTagLength() - length], &hmac[DIGEST_LENGTH - length], length); } bool Sha1AuthAlgo::checkTag(KeyDerivation& kd, EncryptedPacket& packet) { #if defined(USE_GCRYPT) if(!handle_) { return false; } #endif packet.withAuthTag(true); if(!packet.getAuthTagLength()) { return true; } kd.generate(dir_, LABEL_AUTH, packet.getSeqNr(), key_); #if defined(USE_SSL_CRYPTO) HMAC_Init_ex(ctx_, key_.getBuf(), key_.getLength(), EVP_sha1(), NULL); uint8_t hmac[DIGEST_LENGTH]; HMAC_Update(ctx_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); HMAC_Final(ctx_, hmac, NULL); #elif defined(USE_NETTLE) hmac_sha1_set_key(&ctx_, key_.getLength(), key_.getBuf()); uint8_t hmac[DIGEST_LENGTH]; hmac_sha1_update(&ctx_, packet.getAuthenticatedPortionLength(), packet.getAuthenticatedPortion()); hmac_sha1_digest(&ctx_, DIGEST_LENGTH, hmac); #else // USE_GCRYPT is the default gcry_error_t err = gcry_md_setkey(handle_, key_.getBuf(), key_.getLength()); if(err) { cLog.msg(Log::PRIO_ERROR) << "Sha1AuthAlgo::setKey: Failed to set hmac key: " << AnytunGpgError(err); return false; } gcry_md_reset(handle_); gcry_md_write(handle_, packet.getAuthenticatedPortion(), packet.getAuthenticatedPortionLength()); gcry_md_final(handle_); uint8_t* hmac = gcry_md_read(handle_, 0); #endif uint8_t* tag = packet.getAuthTag(); uint32_t length = (packet.getAuthTagLength() < DIGEST_LENGTH) ? packet.getAuthTagLength() : DIGEST_LENGTH; if(length > DIGEST_LENGTH) for(uint32_t i=0; i < (packet.getAuthTagLength() - DIGEST_LENGTH); ++i) if(tag[i]) { return false; } int ret = std::memcmp(&tag[packet.getAuthTagLength() - length], &hmac[DIGEST_LENGTH - length], length); packet.removeAuthTag(); if(ret) { return false; } return true; } #endif anytun-0.3.8/src/log.h0000664000175000017500000000633513604635433014543 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_log_h_INCLUDED #define ANYTUN_log_h_INCLUDED #include #include #include "logTargets.h" #include "threadUtils.hpp" class Log; class LogStringBuilder { public: LogStringBuilder(LogStringBuilder const& src); LogStringBuilder(Log& l, int p); ~LogStringBuilder(); template std::ostream& operator<<(T const& value) { return stream << value; } private: Log& log; int prio; std::stringstream stream; }; class Log { public: static const int PRIO_ERROR = 1; static const int PRIO_WARNING = 2; static const int PRIO_NOTICE = 3; static const int PRIO_INFO = 4; static const int PRIO_DEBUG = 5; static std::string prioToString(int prio); static Log& instance(); void addTarget(std::string conf); void addTarget(LogTargetList::target_type_t type, int prio, std::string conf); LogStringBuilder msg(int prio=PRIO_INFO) { return LogStringBuilder(*this, prio); } private: Log() {}; ~Log() {}; Log(const Log& l); void operator=(const Log& l); void log(std::string msg, int prio); Mutex mutex; friend class LogStringBuilder; LogTargetList targets; }; extern Log& cLog; #endif anytun-0.3.8/src/connectionParam.h0000664000175000017500000000673313604635433017104 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_connectionParam_h_INCLUDED #define ANYTUN_connectionParam_h_INCLUDED #include "keyDerivation.h" #include "seqWindow.h" #include "threadUtils.hpp" #include "packetSource.h" #include "log.h" #include #include class ConnectionParam { public: ConnectionParam(const ConnectionParam& src); ConnectionParam(KeyDerivation& kd, SeqWindow& seq_window, seq_nr_t seq_nr_, PacketSourceEndpoint remote_end); KeyDerivation& kd_; SeqWindow& seq_window_; seq_nr_t seq_nr_; PacketSourceEndpoint remote_end_; private: //TODO: check if this is ok Mutex mutex_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(mutex_); std::string remote_host(remote_end_.address().to_string()); uint16_t remote_port = remote_end_.port(); ar& kd_; ar& seq_window_; ar& seq_nr_; ar& remote_host; ar& remote_port; PacketSourceEndpoint emptyEndpoint; UDPPacketSource::proto::endpoint endpoint(boost::asio::ip::address::from_string(remote_host), remote_port); //This is a workarround, against race condition in sync process //TODO: find a better solution if(endpoint != emptyEndpoint && remote_host != "::" && remote_host != "[::]" && remote_host != "0.0.0.0") { remote_end_ = endpoint; } } }; #endif anytun-0.3.8/src/buffer.h0000664000175000017500000000617013604635433015230 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_buffer_h_INCLUDED #define ANYTUN_buffer_h_INCLUDED #include "datatypes.h" #include class TunDevice; class UDPPacketSource; class Buffer { public: Buffer(bool allow_realloc = true); Buffer(uint32_t length, bool allow_realloc = true); Buffer(uint8_t* data, uint32_t length, bool allow_realloc = true); Buffer(std::string hex_data, bool allow_realloc = true); virtual ~Buffer(); Buffer(const Buffer& src); void operator=(const Buffer& src); bool operator==(const Buffer& cmp) const; Buffer operator^(const Buffer& xor_by) const; uint32_t getLength() const; virtual void setLength(uint32_t new_length); uint8_t* getBuf(); uint8_t& operator[](uint32_t index); uint8_t operator[](uint32_t index) const; std::string getHexDump() const; std::string getHexDumpOneLine() const; bool isReallocAllowed() const; operator uint8_t*(); protected: virtual void reinit() {}; uint8_t* buf_; uint32_t length_; uint32_t real_length_; bool allow_realloc_; static const uint32_t OVER_SIZE_ = 100; }; #endif anytun-0.3.8/src/anytun-config.cpp0000664000175000017500000001211213604635433017064 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include "datatypes.h" #include "log.h" #include "buffer.h" #include "keyDerivation.h" #include "keyDerivationFactory.h" #include "options.h" #include "connectionList.h" #include "routingTable.h" #include "networkAddress.h" #include "packetSource.h" #include "resolver.h" #include "cryptinit.hpp" #include "syncQueue.h" #include "syncCommand.h" void createConnection(const PacketSourceEndpoint& remote_end, ConnectionList& cl, uint16_t seqSize, SyncQueue& queue, mux_t mux, Semaphore& sem) { SeqWindow* seq = new SeqWindow(seqSize); seq_nr_t seq_nr_ = 0; KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf()); kd->init(gOpt.getKey(), gOpt.getSalt(), gOpt.getPassphrase()); kd->setRole(gOpt.getRole()); cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_end; ConnectionParam connparam((*kd), (*seq), seq_nr_, remote_end); cl.addConnection(connparam, mux); std::ostringstream sout; boost::archive::text_oarchive oa(sout); const SyncCommand scom(cl, mux); oa << scom; std::cout << std::setw(5) << std::setfill('0') << sout.str().size()<< ' ' << sout.str() << std::endl; NetworkList routes = gOpt.getRoutes(); NetworkList::const_iterator rit; for(rit = routes.begin(); rit != routes.end(); ++rit) { NetworkAddress addr(rit->net_addr.c_str()); NetworkPrefix prefix(addr, rit->prefix_length); gRoutingTable.addRoute(prefix, mux); std::ostringstream sout2; boost::archive::text_oarchive oa2(sout2); const SyncCommand scom2(prefix); oa2 << scom2; std::cout << std::setw(5) << std::setfill('0') << sout2.str().size()<< ' ' << sout2.str() << std::endl; } sem.up(); } void createConnectionResolver(PacketSourceResolverIt it, ConnectionList& cl, uint16_t seqSize, SyncQueue& queue, mux_t mux, Semaphore& sem) { createConnection(*it, cl, seqSize, queue, mux, sem); } void createConnectionError(const std::exception& e, Semaphore& sem, int& ret) { cLog.msg(Log::PRIO_ERROR) << "uncaught runtime error: " << e.what(); ret = -1; sem.up(); } int main(int argc, char* argv[]) { try { if(!gOpt.parse(argc, argv)) { exit(0); } StringList targets = gOpt.getLogTargets(); for(StringList::const_iterator it = targets.begin(); it != targets.end(); ++it) { cLog.addTarget(*it); } } catch(syntax_error& e) { std::cerr << e << std::endl; gOpt.printUsage(); exit(-1); } gOpt.parse_post(); // print warnings gResolver.init(); initCrypto(); ConnectionList cl; SyncQueue queue; Semaphore sem; int ret = 0; UDPPacketSource::proto::endpoint endpoint; // allow emtpy endpoint!!! gResolver.resolveUdp(gOpt.getRemoteAddr(), gOpt.getRemotePort(), boost::bind(createConnectionResolver, _1, boost::ref(cl), gOpt.getSeqWindowSize(), boost::ref(queue), gOpt.getMux(), boost::ref(sem)), boost::bind(createConnectionError, _1, boost::ref(sem), boost::ref(ret)), gOpt.getResolvAddrType()); sem.down(); return ret; } anytun-0.3.8/src/syncConnectionCommand.cpp0000664000175000017500000000455613604635433020613 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncConnectionCommand.h" SyncConnectionCommand::SyncConnectionCommand(ConnectionList& cl) :cl_(cl) { } SyncConnectionCommand::SyncConnectionCommand(ConnectionList& cl, uint16_t mux) :cl_(cl),mux_(mux) { } uint16_t SyncConnectionCommand::getMux() const { return mux_; } anytun-0.3.8/src/connectionList.cpp0000664000175000017500000001117713604635433017310 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "threadUtils.hpp" #include "datatypes.h" #include "keyDerivationFactory.h" #include "options.h" #include "packetSource.h" #include "connectionList.h" ConnectionList& gConnectionList = ConnectionList::instance(); ConnectionList& ConnectionList::instance() { static ConnectionList instance; return instance; } ConnectionList::ConnectionList() { } ConnectionList::~ConnectionList() { // TODO: comment this in as soon as threads @ main get cleaned up properly // Lock lock(mutex_); // ConnectionMap::iterator it; // for(it = connections_.begin(); it != connections_.end(); ++it) { // delete &it->second.kd_; // delete &it->second.seq_window_; // } } void ConnectionList::addConnection(ConnectionParam& conn, uint16_t mux) { Lock lock(mutex_); std::pair ret = connections_.insert(ConnectionMap::value_type(mux, conn)); if(!ret.second) { connections_.erase(ret.first); connections_.insert(ConnectionMap::value_type(mux, conn)); } } const ConnectionMap::iterator ConnectionList::getEnd() { Lock lock(mutex_); return connections_.end(); } ConnectionMap::iterator ConnectionList::getBeginUnlocked() { return connections_.begin(); } const ConnectionMap::iterator ConnectionList::getBegin() { Lock lock(mutex_); return connections_.begin(); } ConnectionMap::iterator ConnectionList::getEndUnlocked() { return connections_.end(); } const ConnectionMap::iterator ConnectionList::getConnection(uint16_t mux) { Lock lock(mutex_); ConnectionMap::iterator it = connections_.find(mux); return it; } ConnectionParam& ConnectionList::getOrNewConnectionUnlocked(uint16_t mux) { ConnectionMap::iterator it = connections_.find(mux); if(it!=connections_.end()) { return it->second; } uint8_t key[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p' }; uint8_t salt[] = { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n' }; SeqWindow* seq= new SeqWindow(0); seq_nr_t seq_nr_=0; KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf()); kd->init(Buffer(key, sizeof(key)), Buffer(salt, sizeof(salt))); ConnectionParam conn((*kd), (*seq), seq_nr_, PacketSourceEndpoint()); connections_.insert(ConnectionMap::value_type(mux, conn)); it = connections_.find(mux); return it->second; } void ConnectionList::clear() { Lock lock(mutex_); connections_.clear(); } bool ConnectionList::empty() { Lock lock(mutex_); return connections_.empty(); } Mutex& ConnectionList::getMutex() { return mutex_; } anytun-0.3.8/src/options.h0000664000175000017500000001535213604635433015454 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_options_h_INCLUDED #define ANYTUN_options_h_INCLUDED #include "datatypes.h" #include "buffer.h" #include "threadUtils.hpp" #include class syntax_error : public std::runtime_error { public: syntax_error(std::string t, int32_t p) : runtime_error(t), pos(p) {}; int32_t pos; }; std::ostream& operator<<(std::ostream& stream, syntax_error const& error); class OptionHost { public: OptionHost() : addr(""), port("") {}; OptionHost(std::string addrPort) { init(addrPort); }; OptionHost(std::string a, std::string p) : addr(a), port(p) {}; void init(std::string addrPort); std::string addr; std::string port; }; typedef std::list HostList; std::istream& operator>>(std::istream& stream, OptionHost& host); class OptionNetwork { public: OptionNetwork() : net_addr(""), prefix_length(0) {}; OptionNetwork(std::string network) { init(network); }; OptionNetwork(std::string n, uint16_t p) : net_addr(n), prefix_length(p) {}; void init(std::string network); std::string net_addr; uint16_t prefix_length; }; typedef std::list NetworkList; std::istream& operator>>(std::istream& stream, OptionNetwork& network); typedef std::list StringList; typedef enum { ROLE_LEFT, ROLE_RIGHT } role_t; std::ostream& operator<<(std::ostream& stream, role_t const& role); class Options { public: static Options& instance(); bool parse(int argc, char* argv[]); void parse_post(); void printVersion(); void printUsage(); void printOptions(); std::string getProgname(); Options& setProgname(std::string p); bool getDaemonize(); Options& setDaemonize(bool d); std::string getUsername(); Options& setUsername(std::string u); std::string getGroupname(); Options& setGroupname(std::string g); std::string getChrootDir(); Options& setChrootDir(std::string c); std::string getPidFile(); Options& setPidFile(std::string p); StringList getLogTargets(); bool getDebug(); Options& setDebug(bool d); std::string getFileName(); Options& setFileName(std::string f); std::string getBindToAddr(); Options& setBindToAddr(std::string b); std::string getBindToPort(); Options& setBindToPort(std::string b); ResolvAddrType getResolvAddrType(); Options& setResolvAddrType(ResolvAddrType r); std::string getLocalAddr(); Options& setLocalAddr(std::string l); std::string getLocalPort(); Options& setLocalPort(std::string l); std::string getRemoteAddr(); Options& setRemoteAddr(std::string r); std::string getRemotePort(); Options& setRemotePort(std::string r); std::string getLocalSyncAddr(); Options& setLocalSyncAddr(std::string l); std::string getLocalSyncPort(); Options& setLocalSyncPort(std::string l); HostList getRemoteSyncHosts(); std::string getDevName(); Options& setDevName(std::string d); std::string getDevType(); Options& setDevType(std::string d); OptionNetwork getIfconfigParam(); Options& setIfconfigParam(OptionNetwork i); std::string getPostUpScript(); Options& setPostUpScript(std::string p); NetworkList getRoutes(); sender_id_t getSenderId(); Options& setSenderId(sender_id_t s); mux_t getMux(); Options& setMux(mux_t m); window_size_t getSeqWindowSize(); Options& setSeqWindowSize(window_size_t s); std::string getCipher(); Options& setCipher(std::string c); std::string getAuthAlgo(); Options& setAuthAlgo(std::string a); uint32_t getAuthTagLength(); Options& setAuthTagLength(uint32_t a); std::string getKdPrf(); Options& setKdPrf(std::string k); role_t getRole(); Options& setRole(role_t r); std::string getPassphrase(); Options& setPassphrase(std::string p); Options& setKey(std::string k); Buffer getKey(); Options& setSalt(std::string s); Buffer getSalt(); private: Options(); ~Options(); Options(const Options& l); void operator=(const Options& l); ::SharedMutex mutex; bool cluster_opts; bool connection_opts; std::string progname_; bool daemonize_; std::string username_; std::string groupname_; std::string chroot_dir_; std::string pid_file_; StringList log_targets_; bool debug_; std::string file_name_; OptionHost bind_to_; ResolvAddrType resolv_addr_type_; OptionHost local_; OptionHost remote_; OptionHost local_sync_; HostList remote_sync_hosts_; std::string dev_name_; std::string dev_type_; OptionNetwork ifconfig_param_; std::string post_up_script_; NetworkList routes_; sender_id_t sender_id_; mux_t mux_; window_size_t seq_window_size_; std::string cipher_; std::string auth_algo_; uint32_t auth_tag_length_; std::string kd_prf_; role_t role_; std::string passphrase_; Buffer key_; Buffer salt_; }; extern Options& gOpt; #endif anytun-0.3.8/src/deviceConfig.hpp0000664000175000017500000000735113604635433016706 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_deviceConfig_hpp_INCLUDED #define ANYTUN_deviceConfig_hpp_INCLUDED #include "networkAddress.h" #include #include "anytunError.h" class TunDevice; enum device_type_t { TYPE_UNDEF, TYPE_TUN, TYPE_TAP }; class DeviceConfig { public: DeviceConfig(std::string dev_name ,std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix, uint16_t mtu) { mtu_ = mtu; type_ = TYPE_UNDEF; #if !defined(_MSC_VER) && !defined(MINGW) if(dev_type != "") { if(!dev_type.compare(0,3,"tun")) { type_ = TYPE_TUN; } else if(!dev_type.compare(0,3,"tap")) { type_ = TYPE_TAP; } } else if(dev_name != "") { if(!dev_name.compare(0,3,"tun")) { type_ = TYPE_TUN; } else if(!dev_name.compare(0,3,"tap")) { type_ = TYPE_TAP; } } #else if(dev_type == "") { AnytunError::throwErr() << "Device type must be specified on Windows"; } if(dev_type == "tun") { type_ = TYPE_TUN; } else if(dev_type == "tap") { type_ = TYPE_TAP; } if(type_ == TYPE_TUN && ifcfg_addr == "") { AnytunError::throwErr() << "Device type tun requires ifconfig parameter (--ifconfig)"; } #endif if(ifcfg_addr != "") { addr_.setNetworkAddress(ipv4, ifcfg_addr.c_str()); } prefix_ = ifcfg_prefix; uint32_t mask = 0; for(uint16_t i = 0; i < prefix_; ++i) { mask = mask >> 1; mask |= 0x80000000L; } netmask_.setNetworkAddress(boost::asio::ip::address_v4(mask)); } private: device_type_t type_; NetworkAddress addr_; NetworkAddress netmask_; uint16_t prefix_; uint16_t mtu_; friend class TunDevice; }; #endif anytun-0.3.8/src/signalController.cpp0000664000175000017500000000776013604635433017641 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include "signalController.h" #include "log.h" #include "anytunError.h" #include "threadUtils.hpp" SignalController& gSignalController = SignalController::instance(); SignalController& SignalController::instance() { static SignalController instance; return instance; } int SigErrorHandler(int /*sig*/, const std::string& msg) { AnytunError::throwErr() << msg; return 0; } //use system specific signal handler #if !defined(_MSC_VER) && !defined(MINGW) #include "signalHandler.hpp" #else #ifdef WIN_SERVICE #include "win32/signalServiceHandler.hpp" #else #include "win32/signalHandler.hpp" #endif #endif void SignalController::init(DaemonService& service) { registerSignalHandler(*this, service); handler[SIGERROR] = boost::bind(SigErrorHandler, _1, _2); } void SignalController::inject(int sig, const std::string& msg) { { Lock lock(sigQueueMutex); sigQueue.push(SigPair(sig, msg)); } sigQueueSem.up(); } int SignalController::run() { for(CallbackMap::iterator it = callbacks.begin(); it != callbacks.end(); ++it) if(it->first == CALLB_RUNNING) { it->second(); } int ret = 0; for(;;) { sigQueueSem.down(); SigPair sig; { Lock lock(sigQueueMutex); sig = sigQueue.front(); sigQueue.pop(); } HandlerMap::iterator it = handler.find(sig.first); if(it != handler.end()) { ret = it->second(sig.first, sig.second); if(ret) { break; } } else { it = handler.find(SIGUNKNOWN); if(it != handler.end()) { it->second(sig.first, sig.second); } else { cLog.msg(Log::PRIO_NOTICE) << "SIG " << sig.first << " caught with message '" << sig.second << "' - ignoring"; } } } for(CallbackMap::iterator it = callbacks.begin(); it != callbacks.end(); ++it) if(it->first == CALLB_STOPPING) { it->second(); } return ret; } anytun-0.3.8/src/networkAddress.cpp0000664000175000017500000001415413604635433017312 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "threadUtils.hpp" #include "datatypes.h" #include #include "networkAddress.h" #include "anytunError.h" NetworkAddress::NetworkAddress():ipv4_address_(),ipv6_address_() { network_address_type_=ipv4; } NetworkAddress::NetworkAddress(const NetworkAddress& ref) : mutex_(),ipv4_address_(ref.ipv4_address_),ipv6_address_(ref.ipv6_address_),ethernet_address_(ref.ethernet_address_),network_address_type_(ref.network_address_type_) { } NetworkAddress::NetworkAddress(const std::string& address) { boost::asio::ip::address addr = boost::asio::ip::address::from_string(address); if(addr.is_v4()) { network_address_type_=ipv4; ipv4_address_ = addr.to_v4(); } else { network_address_type_=ipv6; ipv6_address_ = addr.to_v6(); } } NetworkAddress::NetworkAddress(boost::asio::ip::address_v6 ipv6_address) { network_address_type_=ipv6; ipv6_address_ = ipv6_address; } NetworkAddress::NetworkAddress(boost::asio::ip::address_v4 ipv4_address) { network_address_type_=ipv4; ipv4_address_ = ipv4_address; } NetworkAddress::NetworkAddress(uint64_t ethernet_address) { network_address_type_=ethernet; ethernet_address_=ethernet_address; } NetworkAddress::~NetworkAddress() { } NetworkAddress::NetworkAddress(const network_address_type_t type, const std::string& address) { setNetworkAddress(type, address); } void NetworkAddress::setNetworkAddress(const network_address_type_t type, const std::string& address) { if(type==ipv4) { ipv4_address_=boost::asio::ip::address_v4::from_string(address); } else if(type==ipv6) { ipv6_address_=boost::asio::ip::address_v6::from_string(address); } else if(type==ethernet) { //TODO } else { //TODO } network_address_type_ = type; } void NetworkAddress::setNetworkAddress(boost::asio::ip::address_v4 addr) { network_address_type_=ipv4; ipv4_address_ = addr; } void NetworkAddress::setNetworkAddress(boost::asio::ip::address_v6 addr) { network_address_type_=ipv6; ipv6_address_ = addr; } void NetworkAddress::setNetworkAddress(uint64_t addr) { network_address_type_=ethernet; ethernet_address_=addr; } network_address_type_t NetworkAddress::getNetworkAddressType() const { return network_address_type_; } const boost::asio::ip::address_v4& NetworkAddress::getNetworkAddressV4() const { if(network_address_type_ != ipv4) { AnytunError::throwErr() << "wrong address type"; } return ipv4_address_; } const boost::asio::ip::address_v6& NetworkAddress::getNetworkAddressV6() const { if(network_address_type_ != ipv6) { AnytunError::throwErr() << "wrong address type"; } return ipv6_address_; } const uint64_t NetworkAddress::getNetworkAdrressEther() const { if(network_address_type_ != ethernet) { AnytunError::throwErr() << "wrong address type"; } return ethernet_address_; } std::string NetworkAddress::toString() const { if(network_address_type_==ipv4) { return ipv4_address_.to_string(); } else if(network_address_type_==ipv6) { return ipv6_address_.to_string(); } else if(network_address_type_==ethernet) { // TODO } return std::string(""); } ipv4_bytes_type NetworkAddress::to_bytes_v4() const { return ipv4_address_.to_bytes(); } ipv6_bytes_type NetworkAddress::to_bytes_v6() const { return ipv6_address_.to_bytes(); } ethernet_bytes_type NetworkAddress::to_bytes_ethernet() const { boost::array result; uint64_t ether=ethernet_address_; for(int i = 0; i < 6; i++) { result[i] = (unsigned char)(ether & 0xff); ether >>= 8; } return result; } bool NetworkAddress::operator<(const NetworkAddress& right) const { if(network_address_type_!=right.network_address_type_) { AnytunError::throwErr() << "NetworkAddress::operator<() address types don't match"; } if(network_address_type_==ipv4) { return (ipv4_address_ < right.ipv4_address_); } else if(network_address_type_==ipv6) { return (ipv6_address_ < right.ipv6_address_); } else if(network_address_type_==ethernet) { return (ethernet_address_ < right.ethernet_address_); } else { //TODO } return false; } anytun-0.3.8/src/authAlgoFactory.h0000664000175000017500000000503713604635433017054 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_authAlgoFactory_h_INCLUDED #define ANYTUN_authAlgoFactory_h_INCLUDED #include #include "datatypes.h" #include "authAlgo.h" class AuthAlgoFactory { public: static AuthAlgo* create(std::string const& type, kd_dir_t dir); static uint32_t getDigestLength(std::string const& type); private: AuthAlgoFactory(); AuthAlgoFactory(const AuthAlgoFactory& src); void operator=(const AuthAlgoFactory& src); ~AuthAlgoFactory(); }; #endif anytun-0.3.8/src/cryptinit.hpp0000664000175000017500000001010113604635433016331 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_cryptinit_hpp_INCLUDED #define ANYTUN_cryptinit_hpp_INCLUDED #ifndef NO_CRYPT #include "anytunError.h" #if defined(USE_GCRYPT) #include #if GCRYPT_VERSION_NUMBER < 0x010600 #if defined(BOOST_HAS_PTHREADS) // boost thread callbacks for libgcrypt GCRY_THREAD_OPTION_PTHREAD_IMPL; #else #error You can not use gcrypt without pthreads - please configure Boost to use pthreads! #endif // defined(BOOST_HAS_PTHREADS) #endif // GCRYPT_VERSION_NUMBER < 0x010600 #define MIN_GCRYPT_VERSION "1.2.0" bool initLibGCrypt() { #if GCRYPT_VERSION_NUMBER < 0x010600 #if defined(BOOST_HAS_PTHREADS) // make libgcrypt thread safe // this must be called before any other libgcrypt call gcry_control(GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread); #else #error You can not use gcrypt without pthreads - please configure Boost to use pthreads! #endif // defined(BOOST_HAS_PTHREADS) #endif // GCRYPT_VERSION_NUMBER < 0x010600 // this must be called right after the GCRYCTL_SET_THREAD_CBS command // no other function must be called till now if(!gcry_check_version(MIN_GCRYPT_VERSION)) { std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl; return false; } gcry_error_t err = gcry_control(GCRYCTL_DISABLE_SECMEM, 0); if(err) { std::cout << "initLibGCrypt: Failed to disable secure memory: " << AnytunGpgError(err) << std::endl; return false; } // Tell Libgcrypt that initialization has completed. err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED); if(err) { std::cout << "initLibGCrypt: Failed to finish initialization: " << AnytunGpgError(err) << std::endl; return false; } cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished"; return true; } #endif #endif bool initCrypto() { #ifndef NO_CRYPT #if defined(USE_SSL_CRYPTO) return true; #elif defined(USE_NETTLE) return true; #else // USE_GCRYPT is the default return initLibGCrypt(); #endif #else return true; #endif } #endif anytun-0.3.8/src/authAlgo.h0000664000175000017500000000740213604635433015522 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_authAlgo_h_INCLUDED #define ANYTUN_authAlgo_h_INCLUDED #include "datatypes.h" #include "buffer.h" #include "encryptedPacket.h" #ifndef NO_CRYPT #if defined(USE_SSL_CRYPTO) #include #elif defined(USE_NETTLE) #include #else // USE_GCRYPT is the default #include #endif #endif #include "keyDerivation.h" class AuthAlgo { public: AuthAlgo() : dir_(KD_INBOUND) {}; AuthAlgo(kd_dir_t d) : dir_(d) {}; virtual ~AuthAlgo() {}; /** * generate the mac * @param packet the packet to be authenticated */ virtual void generate(KeyDerivation& kd, EncryptedPacket& packet) = 0; /** * check the mac * @param packet the packet to be authenticated */ virtual bool checkTag(KeyDerivation& kd, EncryptedPacket& packet) = 0; protected: kd_dir_t dir_; }; //****** NullAuthAlgo ****** class NullAuthAlgo : public AuthAlgo { public: void generate(KeyDerivation& kd, EncryptedPacket& packet); bool checkTag(KeyDerivation& kd, EncryptedPacket& packet); static const uint32_t DIGEST_LENGTH = 0; }; #ifndef NO_CRYPT //****** Sha1AuthAlgo ****** //* HMAC SHA1 Auth Tag Generator Class class AuthAlgoFactory; class Sha1AuthAlgo : public AuthAlgo { friend class AuthAlgoFactory; public: ~Sha1AuthAlgo(); void generate(KeyDerivation& kd, EncryptedPacket& packet); bool checkTag(KeyDerivation& kd, EncryptedPacket& packet); static const uint32_t DIGEST_LENGTH = 20; private: Sha1AuthAlgo(kd_dir_t d); bool Init(); #if defined(USE_SSL_CRYPTO) HMAC_CTX *ctx_; #elif defined(USE_NETTLE) struct hmac_sha1_ctx ctx_; #else // USE_GCRYPT is the default gcry_md_hd_t handle_; #endif Buffer key_; }; #endif #endif anytun-0.3.8/src/syncBuffer.cpp0000664000175000017500000000414713604635433016422 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncBuffer.h" anytun-0.3.8/src/plainPacket.h0000664000175000017500000000724713604635433016220 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_plainPacket_h_INCLUDED #define ANYTUN_plainPacket_h_INCLUDED #include "datatypes.h" #include "buffer.h" #include "networkAddress.h" class Cipher; /** * plain SATP packet class
* includes payload_type and payload */ #define PAYLOAD_TYPE_TAP 0x6558 #define PAYLOAD_TYPE_TUN 0x0000 #define PAYLOAD_TYPE_TUN4 0x0800 #define PAYLOAD_TYPE_TUN6 0x86DD class PlainPacket : public Buffer { public: /** * Packet constructor * @param the length of the payload * @param allow reallocation of buffer */ PlainPacket(uint32_t payload_length, bool allow_realloc = false); /** * Packet destructor */ ~PlainPacket() {}; /** * Get the length of the header * @return the length of the header */ static uint32_t getHeaderLength(); /** * Get the payload type * @return the id of the payload type */ payload_type_t getPayloadType() const; /** * Set the payload type * @param payload_type payload type id */ void setPayloadType(payload_type_t payload_type); /** * Get the length of the payload * @return the length of the payload */ uint32_t getPayloadLength() const; /** * Set the length of the payload * @param length length of the payload */ void setPayloadLength(uint32_t payload_length); /** * Get the the payload * @return the Pointer to the payload */ uint8_t* getPayload(); // NetworkAddress getSrcAddr() const; NetworkAddress getDstAddr() const; private: PlainPacket(); PlainPacket(const PlainPacket& src); void reinit(); payload_type_t* payload_type_; uint8_t* payload_; }; #endif anytun-0.3.8/src/routingTreeNode.h0000664000175000017500000000503013604635433017066 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_routingTreeNode_h_INCLUDED #define ANYTUN_routingTreeNode_h_INCLUDED #include "threadUtils.hpp" #include "datatypes.h" #include "networkAddress.h" #include "networkPrefix.h" class RoutingTree; class RoutingTreeNode { public: RoutingTreeNode(); ~RoutingTreeNode(); void print(int) const; private: // Mutex mutex_; uint16_t mux_; bool valid_; boost::array nodes_; friend class RoutingTree; }; #endif anytun-0.3.8/src/endian.h0000664000175000017500000000524413604635433015216 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_endian_h_INCLUDED #define ANYTUN_endian_h_INCLUDED #ifndef _WIN32 #include #else #include #endif #define SEQ_NR_T_NTOH(a) ntohl(a) #define SEQ_NR_T_HTON(a) htonl(a) #define SENDER_ID_T_NTOH(a) ntohs(a) #define SENDER_ID_T_HTON(a) htons(a) #define PAYLOAD_TYPE_T_NTOH(a) ntohs(a) #define PAYLOAD_TYPE_T_HTON(a) htons(a) #define MUX_T_NTOH(a) ntohs(a) #define MUX_T_HTON(a) htons(a) #define SATP_PRF_LABEL_T_NTOH(a) ntohl(a) #define SATP_PRF_LABEL_T_HTON(a) htonl(a) //#define AUTH_TAG_T_NTOH(a) ntohl(a) //#define AUTH_TAG_T_HTON(a) htonl(a) #endif anytun-0.3.8/src/routingTreeNode.cpp0000664000175000017500000000524713604635433017433 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include "routingTreeNode.h" RoutingTreeNode::RoutingTreeNode():mux_(0),valid_(false) { for(int i=0; i<256; i++) { nodes_[i]=NULL; } } void RoutingTreeNode::print(int level) const { if(valid_) { std::cout << " -> " <print(level+1); } } } RoutingTreeNode::~RoutingTreeNode() { for(int i=0; i<256; i++) if(nodes_[i]) { delete nodes_[i]; } } anytun-0.3.8/src/win32/0000775000175000017500000000000013604635433014544 5ustar equinoxequinoxanytun-0.3.8/src/win32/tunDevice.cpp0000664000175000017500000002375213604635433017207 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include "../endian.h" #include "../tunDevice.h" #include "../threadUtils.hpp" #include "../log.h" #include "../anytunError.h" #include "registryKey.h" #include "common.h" #define MIN_TAP_VER_MAJOR 8 #define MIN_TAP_VER_MINOR 2 TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400) { if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP) { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; } handle_ = INVALID_HANDLE_VALUE; if(!getAdapter(dev_name)) { AnytunError::throwErr() << "can't find any suitable device"; } if(handle_ == INVALID_HANDLE_VALUE) { std::stringstream tapname; tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX; handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0); if(handle_ == INVALID_HANDLE_VALUE) { AnytunError::throwErr() << "Unable to open device: " << actual_node_ << " (" << actual_name_ << "): " << AnytunErrno(GetLastError()); } } DWORD err; u_long info[3]; info[0] = info[1] = info[2] = 0; err = performIoControl(TAP_IOCTL_GET_VERSION, info, sizeof(info), info, sizeof(info)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to get device version: " << AnytunErrno(err); } cLog.msg(Log::PRIO_NOTICE) << "Windows TAP Driver Version " << info[0] << "." << info[1] << " " << (info[2] ? "(DEBUG)" : ""); if(!(info[0] > MIN_TAP_VER_MAJOR || (info[0] == MIN_TAP_VER_MAJOR && info[1] >= MIN_TAP_VER_MINOR))) { CloseHandle(handle_); AnytunError::throwErr() << "need a higher Version of TAP Driver (at least " << MIN_TAP_VER_MAJOR << "." << MIN_TAP_VER_MINOR << ")"; } if(conf_.type_ == TYPE_TUN) { u_long ep[3]; ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong()); ep[1] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong()); ep[2] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong()); err = performIoControl(TAP_IOCTL_CONFIG_TUN, ep, sizeof(ep), ep, sizeof(ep)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to set device tun mode: " << AnytunErrno(err); } } if(ifcfg_addr != "") { do_ifconfig(); } int status = true; err = performIoControl(TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to set device media status: " << AnytunErrno(err); } roverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); woverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); } bool TunDevice::getAdapter(std::string const& dev_name) { RegistryKey akey; DWORD err = akey.open(HKEY_LOCAL_MACHINE, ADAPTER_KEY, KEY_ENUMERATE_SUB_KEYS); if(err != ERROR_SUCCESS) { AnytunError::throwErr() << "Unable to open registry key (HKLM\\" << ADAPTER_KEY << "): " << AnytunErrno(err); } bool found = false; for(int i=0; ; ++i) { RegistryKey ckey; DWORD err = akey.getSubKey(i, ckey, KEY_QUERY_VALUE); if(err == ERROR_NO_MORE_ITEMS) { break; } if(err != ERROR_SUCCESS) { continue; } try { if(ckey["ComponentId"] != TAP_COMPONENT_ID) { continue; } actual_node_ = ckey["NetCfgInstanceId"]; RegistryKey nkey; std::stringstream keyname; keyname << NETWORK_CONNECTIONS_KEY << "\\" << actual_node_ << "\\Connection"; err = nkey.open(HKEY_LOCAL_MACHINE, keyname.str().c_str(), KEY_QUERY_VALUE);; if(err != ERROR_SUCCESS) { continue; } actual_name_ = nkey["Name"]; } catch(AnytunErrno&) { continue; } if(dev_name != "") { if(dev_name == actual_name_) { found = true; break; } } else { std::stringstream tapname; tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX; handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0); if(handle_ == INVALID_HANDLE_VALUE) { continue; } found = true; break; } } if(!found) { actual_node_ = ""; actual_name_ = ""; } return found; } DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, LPVOID outBuffer, DWORD outBufferSize) { OVERLAPPED overlapped; overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL); overlapped.Offset = 0; overlapped.OffsetHigh = 0; DWORD len; if(!DeviceIoControl(handle_, controlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, &len, &overlapped)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { WaitForSingleObject(overlapped.hEvent, INFINITE); if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE)) { return GetLastError(); } } else { return GetLastError(); } } return ERROR_SUCCESS; } TunDevice::~TunDevice() { if(handle_ != INVALID_HANDLE_VALUE) { CloseHandle(handle_); } if(roverlapped_.hEvent != INVALID_HANDLE_VALUE) { CloseHandle(roverlapped_.hEvent); } if(woverlapped_.hEvent != INVALID_HANDLE_VALUE) { CloseHandle(woverlapped_.hEvent); } } int TunDevice::fix_return(int ret, size_t pi_length) const { // nothing to be done here return 0; } int TunDevice::read(uint8_t* buf, uint32_t len) { DWORD lenout; roverlapped_.Offset = 0; roverlapped_.OffsetHigh = 0; ResetEvent(roverlapped_.hEvent); if(!ReadFile(handle_, buf, len, &lenout, &roverlapped_)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { WaitForSingleObject(roverlapped_.hEvent, INFINITE); if(!GetOverlappedResult(handle_, &roverlapped_, &lenout, FALSE)) { cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError()); return -1; } } else { cLog.msg(Log::PRIO_ERROR) << "Error while reading from device: " << AnytunErrno(GetLastError()); return -1; } } return lenout; } int TunDevice::write(uint8_t* buf, uint32_t len) { DWORD lenout; woverlapped_.Offset = 0; woverlapped_.OffsetHigh = 0; ResetEvent(woverlapped_.hEvent); if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) { DWORD err = GetLastError(); if(err == ERROR_IO_PENDING) { WaitForSingleObject(woverlapped_.hEvent, INFINITE); if(!GetOverlappedResult(handle_, &woverlapped_, &lenout, FALSE)) { cLog.msg(Log::PRIO_ERROR) << "Error while trying to get overlapped result: " << AnytunErrno(GetLastError()); return -1; } } else { cLog.msg(Log::PRIO_ERROR) << "Error while writing to device: " << AnytunErrno(GetLastError()); return -1; } } return lenout; } void TunDevice::init_post() { // nothing to be done here } void TunDevice::do_ifconfig() { u_long ep[4]; ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong()); ep[1] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong()); ep[2] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong()); ep[3] = 365 * 24 * 3600; // lease time in seconds DWORD err = performIoControl(TAP_IOCTL_CONFIG_DHCP_MASQ, ep, sizeof(ep), ep, sizeof(ep)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to set device dhcp masq mode: " << AnytunErrno(err); } u_long mtu; err = performIoControl(TAP_IOCTL_GET_MTU, &mtu, sizeof(mtu), &mtu, sizeof(mtu)); if(err != ERROR_SUCCESS) { CloseHandle(handle_); AnytunError::throwErr() << "Unable to get device mtu: " << AnytunErrno(err); } conf_.mtu_ = static_cast(mtu); } void TunDevice::waitUntilReady() { // nothing to be done here } anytun-0.3.8/src/win32/winService.cpp0000664000175000017500000001465013604635433017374 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifdef WIN_SERVICE #include #include #include "winService.h" #include "../log.h" #include "../anytunError.h" #include "../threadUtils.hpp" void WinService::install() { SC_HANDLE schSCManager; SC_HANDLE schService; char szPath[MAX_PATH]; if(!GetModuleFileNameA(NULL, szPath, MAX_PATH)) { AnytunError::throwErr() << "Error on GetModuleFileName: " << AnytunErrno(GetLastError()); } schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); if(NULL == schSCManager) { AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); } schService = CreateServiceA(schSCManager, SVC_NAME, SVC_NAME, SERVICE_ALL_ACCESS, SERVICE_WIN32_OWN_PROCESS, SERVICE_DEMAND_START, SERVICE_ERROR_NORMAL, szPath, NULL, NULL, NULL, NULL, NULL); if(schService == NULL) { CloseServiceHandle(schSCManager); AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); } std::cout << "Service installed successfully" << std::endl; CloseServiceHandle(schService); CloseServiceHandle(schSCManager); } void WinService::uninstall() { SC_HANDLE schSCManager; SC_HANDLE schService; schSCManager = OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS); if(NULL == schSCManager) { AnytunError::throwErr() << "Error on OpenSCManager: " << AnytunErrno(GetLastError()); } schService = OpenServiceA(schSCManager, SVC_NAME, SERVICE_ALL_ACCESS); if(schService == NULL) { CloseServiceHandle(schSCManager); AnytunError::throwErr() << "Error on CreateService: " << AnytunErrno(GetLastError()); } if(!DeleteService(schService)) { CloseServiceHandle(schService); CloseServiceHandle(schSCManager); AnytunError::throwErr() << "Error on DeleteService: " << AnytunErrno(GetLastError()); } std::cout << "Service uninstalled successfully" << std::endl; CloseServiceHandle(schService); CloseServiceHandle(schSCManager); } void WinService::start() { SERVICE_TABLE_ENTRY DispatchTable[] = { {SVC_NAME, (LPSERVICE_MAIN_FUNCTION)WinService::main }, {NULL, NULL} }; if(!StartServiceCtrlDispatcherA(DispatchTable)) { AnytunError::throwErr() << "Error on StartServiceCtrlDispatcher: " << AnytunErrno(GetLastError()); } } int real_main(int argc, char* argv[], WinService& service); VOID WINAPI WinService::main(DWORD dwArgc, LPTSTR* lpszArgv) { WinService service; service.status_handle_ = RegisterServiceCtrlHandlerA(SVC_NAME, WinService::ctrlHandler); if(!service.status_handle_) { cLog.msg(Log::PRIO_ERROR) << "Error on RegisterServiceCtrlHandler: " << AnytunErrno(GetLastError()); return; } service.status_.dwServiceType = SERVICE_WIN32_OWN_PROCESS; service.status_.dwServiceSpecificExitCode = 0; service.reportStatus(SERVICE_START_PENDING, NO_ERROR); real_main(dwArgc, lpszArgv, service); service.reportStatus(SERVICE_STOPPED, NO_ERROR); } VOID WINAPI WinService::ctrlHandler(DWORD dwCtrl) { gSignalController.inject(dwCtrl); } int WinService::handleCtrlSignal(int sig, const std::string& msg) { switch(sig) { case SERVICE_CONTROL_STOP: { reportStatus(SERVICE_STOP_PENDING, NO_ERROR); cLog.msg(Log::PRIO_NOTICE) << "received service stop signal, exitting"; return 1; } case SERVICE_CONTROL_INTERROGATE: break; default: break; } reportStatus(status_.dwCurrentState, NO_ERROR); return 0; } void WinService::reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode) { static DWORD dwCheckPoint = 1; status_.dwCurrentState = dwCurrentState; status_.dwWin32ExitCode = dwWin32ExitCode; status_.dwWaitHint = 0; if((dwCurrentState == SERVICE_START_PENDING) || (dwCurrentState == SERVICE_STOP_PENDING)) { status_.dwControlsAccepted = 0; } else { status_.dwControlsAccepted = SERVICE_ACCEPT_STOP; } if((dwCurrentState == SERVICE_RUNNING) || (dwCurrentState == SERVICE_STOPPED)) { status_.dwCheckPoint = 0; } else { status_.dwCheckPoint = dwCheckPoint++; } SetServiceStatus(status_handle_, &status_); } void WinService::initPrivs(std::string const& username, std::string const& groupname) { // nothing here } void WinService::dropPrivs() { // nothing here } void WinService::chroot(std::string const& dir) { // nothing here } void WinService::daemonize() { // nothing here } bool WinService::isDaemonized() { return true; } #endif anytun-0.3.8/src/win32/common.h0000664000175000017500000000654313604635433016215 0ustar equinoxequinox/* * TAP-Win32 -- A kernel driver to provide virtual tap device functionality * on Windows. Originally derived from the CIPE-Win32 * project by Damion K. Wilson, with extensive modifications by * James Yonan. * * All source code which derives from the CIPE-Win32 project is * Copyright (C) Damion K. Wilson, 2003, and is released under the * GPL version 2 (see below). * * All other source code is Copyright (C) 2002-2005 OpenVPN Solutions LLC, * and is released under the GPL version 2 (see below). * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program (see the file COPYING included with this * distribution); if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #ifndef ANYTUN_win32_common_h_INCLUDED #define ANYTUN_win32_common_h_INCLUDED //=============================================== // This file is included both by OpenVPN and // the TAP-Win32 driver and contains definitions // common to both. //=============================================== //============= // TAP IOCTLs //============= #define TAP_CONTROL_CODE(request,method) \ CTL_CODE (FILE_DEVICE_UNKNOWN, request, method, FILE_ANY_ACCESS) // Present in 8.1 #define TAP_IOCTL_GET_MAC TAP_CONTROL_CODE (1, METHOD_BUFFERED) #define TAP_IOCTL_GET_VERSION TAP_CONTROL_CODE (2, METHOD_BUFFERED) #define TAP_IOCTL_GET_MTU TAP_CONTROL_CODE (3, METHOD_BUFFERED) #define TAP_IOCTL_GET_INFO TAP_CONTROL_CODE (4, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_POINT_TO_POINT TAP_CONTROL_CODE (5, METHOD_BUFFERED) #define TAP_IOCTL_SET_MEDIA_STATUS TAP_CONTROL_CODE (6, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_MASQ TAP_CONTROL_CODE (7, METHOD_BUFFERED) #define TAP_IOCTL_GET_LOG_LINE TAP_CONTROL_CODE (8, METHOD_BUFFERED) #define TAP_IOCTL_CONFIG_DHCP_SET_OPT TAP_CONTROL_CODE (9, METHOD_BUFFERED) // Added in 8.2 /* obsoletes TAP_IOCTL_CONFIG_POINT_TO_POINT */ #define TAP_IOCTL_CONFIG_TUN TAP_CONTROL_CODE (10, METHOD_BUFFERED) //================= // Registry keys //================= #define ADAPTER_KEY "SYSTEM\\CurrentControlSet\\Control\\Class\\{4D36E972-E325-11CE-BFC1-08002BE10318}" #define NETWORK_CONNECTIONS_KEY "SYSTEM\\CurrentControlSet\\Control\\Network\\{4D36E972-E325-11CE-BFC1-08002BE10318}" //====================== // Filesystem prefixes //====================== #define USERMODEDEVICEDIR "\\\\.\\Global\\" #define SYSDEVICEDIR "\\Device\\" #define USERDEVICEDIR "\\DosDevices\\Global\\" #define TAPSUFFIX ".tap" //========================================================= // TAP_COMPONENT_ID -- This string defines the TAP driver // type -- different component IDs can reside in the system // simultaneously. //========================================================= #define TAP_COMPONENT_ID "tap0901" #endif anytun-0.3.8/src/win32/sysExec.hpp0000664000175000017500000001367013604635433016707 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #pragma once #ifndef ANYTUN_sysexec_hpp_INCLUDED #define ANYTUN_sysexec_hpp_INCLUDED #include #include // todo remove #include SysExec::~SysExec() { if(!closed_) { CloseHandle(process_info_.hProcess); CloseHandle(process_info_.hThread); } } STARTUPINFOA getStartupInfo() { STARTUPINFOA startup_info; startup_info.cb = sizeof(STARTUPINFOA); GetStartupInfoA(&startup_info); //startup_info.dwFlags = STARTF_USESTDHANDLES; //startup_info.hStdInput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; //startup_info.hStdOutput = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; //startup_info.hStdError = CreateFile("NUL", GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, 0, 0, 0); // INVALID_HANDLE_VALUE; startup_info.dwFlags |= STARTF_USESHOWWINDOW; startup_info.wShowWindow = SW_HIDE; return startup_info; } char const* const BATCH_FILE_EXTS[] = { ".bat", ".cmd" }; int const BATCH_FILE_EXTS_COUNT = sizeof(BATCH_FILE_EXTS) / sizeof(BATCH_FILE_EXTS[0]); bool endsWith(std::string const& string, std::string const& suffix) { return string.find(suffix, string.size() - suffix.size()) != std::string::npos; } void SysExec::doExec(StringVector args, StringList env_param) { std::vector arguments; bool isBatchFile = false; for(int i = 0; i < BATCH_FILE_EXTS_COUNT; ++i) { if(endsWith(script_, BATCH_FILE_EXTS[i])) { isBatchFile = true; break; } } if(isBatchFile) { std::string const BATCH_INTERPRETER = "cmd /c \""; arguments.insert(arguments.end(), BATCH_INTERPRETER.begin(), BATCH_INTERPRETER.end()); } arguments.push_back('\"'); arguments.insert(arguments.end(), script_.begin(), script_.end()); arguments.push_back('\"'); arguments.push_back(' '); for(StringVector::const_iterator it = args.begin(); it != args.end(); ++it) { arguments.push_back('\"'); arguments.insert(arguments.end(), it->begin(), it->end()); arguments.push_back('\"'); arguments.push_back(' '); } if(isBatchFile) { arguments.push_back('\"'); } arguments.push_back(0); STARTUPINFOA startup_info = getStartupInfo(); std::map envDict; for(StringList::const_iterator it = env_param.begin(); it != env_param.begin(); ++it) { size_t delimiter_pos = it->find('='); envDict.insert(std::make_pair(it->substr(0, delimiter_pos), it->substr(delimiter_pos + 1))); } std::vector env; for(std::map::iterator it = envDict.begin(); it != envDict.end(); ++it) { env.insert(env.end(), it->first.begin(), it->first.end()); env.push_back(0); } env.push_back(0); if(!CreateProcessA(NULL, &arguments[0], NULL, NULL, false, 0, &env[0], NULL, &startup_info, &process_info_ )) { cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' CreateProcess() error: " << GetLastError(); return; } } int SysExec::waitForScript() { DWORD result = WaitForSingleObject(process_info_.hProcess, INFINITE); assert(WAIT_OBJECT_0 == result); // WAIT_FAILED, WAIT_TIMEOUT ... ??? bool success = GetExitCodeProcess(process_info_.hProcess, &return_code_) != 0; assert(true == success); // false -> HU? CloseHandle(process_info_.hProcess); CloseHandle(process_info_.hThread); closed_ = true; return static_cast(return_code_); } void SysExec::waitAndDestroy(SysExec*& s) { if(!s) { return; } s->waitForScript(); cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << s->return_code_; delete(s); s = NULL; } #endif // ANYTUN_sysexec_hpp_INCLUDED anytun-0.3.8/src/win32/signalHandler.hpp0000664000175000017500000000715513604635433020040 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_signalHandler_hpp_INCLUDED #define ANYTUN_signalHandler_hpp_INCLUDED #include int CtrlCHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "CTRL-C Event received, exitting"; return 1; } int CtrlBreakHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "CTRL-Break Event received, ignoring"; return 0; } int CtrlCloseHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "Close Event received, exitting"; return 1; } int CtrlLogoffHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "LogOff Event received, exitting"; return 1; } int CtrlShutdownHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "Shutdown Event received, exitting"; return 1; } bool handleSignal(DWORD ctrlType) { gSignalController.inject(ctrlType); return true; } void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/) { if(!SetConsoleCtrlHandler((PHANDLER_ROUTINE)handleSignal, true)) { AnytunError::throwErr() << "Error on SetConsoleCtrlhandler: " << AnytunErrno(GetLastError()); } ctrl.handler[CTRL_C_EVENT] = boost::bind(CtrlCHandler, _1, _2); ctrl.handler[CTRL_BREAK_EVENT] = boost::bind(CtrlBreakHandler, _1, _2); ctrl.handler[CTRL_CLOSE_EVENT] = boost::bind(CtrlCloseHandler, _1, _2); ctrl.handler[CTRL_LOGOFF_EVENT] = boost::bind(CtrlLogoffHandler, _1, _2); ctrl.handler[CTRL_SHUTDOWN_EVENT] = boost::bind(CtrlShutdownHandler, _1, _2); } #endif anytun-0.3.8/src/win32/make_version_h.bat0000664000175000017500000000137213604635433020230 0ustar equinoxequinox@echo off setlocal set /p VERSION=<..\version set OUTPUT_FILE=version.h echo /* > %OUTPUT_FILE% echo * anytun version info >> %OUTPUT_FILE% echo * >> %OUTPUT_FILE% echo * this file was created automatically >> %OUTPUT_FILE% echo * do not edit this file directly >> %OUTPUT_FILE% echo * use win32/make_version_h.bat instead >> %OUTPUT_FILE% echo */ >> %OUTPUT_FILE% echo. >> %OUTPUT_FILE% echo #ifndef ANYTUN_version_h_INCLUDED >> %OUTPUT_FILE% echo #define ANYTUN_version_h_INCLUDED >> %OUTPUT_FILE% echo. >> %OUTPUT_FILE% echo #define VERSION_STRING_0 " version %VERSION%" >> %OUTPUT_FILE% echo #define VERSION_STRING_1 "built on %COMPUTERNAME%, %DATE% %TIME%" >> %OUTPUT_FILE% echo. >> %OUTPUT_FILE% echo #endif >> %OUTPUT_FILE% anytun-0.3.8/src/win32/registryKey.h0000664000175000017500000000544413604635433017245 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_win32_registryKey_h_INCLUDED #define ANYTUN_win32_registryKey_h_INCLUDED #include #include class RegistryKey { public: #define NAME_LENGTH 256 #define STRING_VALUE_LENGTH 256 RegistryKey(); RegistryKey(HKEY hkey, std::string subKey, REGSAM samDesired); ~RegistryKey(); bool isOpen() const; std::string getName() const; DWORD open(HKEY hkey, std::string subKey, REGSAM samDesired); void close(); DWORD getSubKey(DWORD index, RegistryKey& subKey, REGSAM sam) const; DWORD getSubKey(std::string name, RegistryKey& subKey, REGSAM sam) const; std::string operator[](std::string const& name) const; private: HKEY key_; bool opened_; std::string name_; }; #endif anytun-0.3.8/src/win32/signalServiceHandler.hpp0000664000175000017500000000562113604635433021355 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_signalServiceHandler_hpp_INCLUDED #define ANYTUN_signalServiceHandler_hpp_INCLUDED #include "winService.h" void registerSignalHandler(SignalController& ctrl, WinService& service) { ctrl.handler[SERVICE_CONTROL_STOP] = boost::bind(&WinService::handleCtrlSignal, &service, _1, _2); ctrl.handler[SERVICE_CONTROL_INTERROGATE] = boost::bind(&WinService::handleCtrlSignal, &service, _1, _2); ctrl.handler[SIGUNKNOWN] = boost::bind(&WinService::handleCtrlSignal, &service, _1, _2); ctrl.callbacks.insert(SignalController::CallbackMap::value_type(CALLB_RUNNING, boost::bind(&WinService::reportStatus, &service, SERVICE_RUNNING, NO_ERROR))); ctrl.callbacks.insert(SignalController::CallbackMap::value_type(CALLB_STOPPING, boost::bind(&WinService::reportStatus, &service, SERVICE_STOP_PENDING, NO_ERROR))); } #endif anytun-0.3.8/src/win32/winService.h0000664000175000017500000000601113604635433017031 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_win32_winService_h_INCLUDED #define ANYTUN_win32_winService_h_INCLUDED #ifdef WIN_SERVICE #include "../threadUtils.hpp" #include "../signalController.h" class WinService { public: #define SVC_NAME "anytun" static void install(); static void uninstall(); static void start(); static VOID WINAPI main(DWORD dwArgc, LPTSTR* lpszArgv); static VOID WINAPI ctrlHandler(DWORD dwCtrl); void reportStatus(DWORD dwCurrentState, DWORD dwWin32ExitCode); int handleCtrlSignal(int sig, const std::string& msg); void initPrivs(std::string const& username, std::string const& groupname); void dropPrivs(); void chroot(std::string const& dir); void daemonize(); bool isDaemonized(); private: WinService() {}; ~WinService() {}; WinService(const WinService& w); void operator=(const WinService& w); SERVICE_STATUS status_; SERVICE_STATUS_HANDLE status_handle_; }; typedef WinService DaemonService; #endif #endif anytun-0.3.8/src/win32/registryKey.cpp0000664000175000017500000000766013604635433017602 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include "registryKey.h" #include "../anytunError.h" RegistryKey::RegistryKey() : opened_(false) { } RegistryKey::RegistryKey(HKEY hkey, std::string subKey, REGSAM samDesired) : opened_(false) { open(hkey, subKey, samDesired); } RegistryKey::~RegistryKey() { close(); } bool RegistryKey::isOpen() const { return opened_; } std::string RegistryKey::getName() const { return name_; } DWORD RegistryKey::open(HKEY hkey, std::string subKey, REGSAM samDesired) { if(opened_) { RegCloseKey(key_); } opened_ = false; name_ = ""; LONG err = RegOpenKeyExA(hkey, subKey.c_str(), 0, samDesired, &key_); if(err != ERROR_SUCCESS) { return err; } name_ = subKey; opened_ = true; return ERROR_SUCCESS; } void RegistryKey::close() { if(opened_) { RegCloseKey(key_); } opened_ = false; } std::string RegistryKey::operator[](std::string const& name) const { if(!opened_) { throw AnytunErrno(ERROR_INVALID_HANDLE); } char value[STRING_VALUE_LENGTH]; DWORD len = sizeof(value); LONG err = RegQueryValueExA(key_, name.c_str(), NULL, NULL, (LPBYTE)value, &len); if(err != ERROR_SUCCESS) { throw AnytunErrno(err); } if(value[len-1] != 0) { if(len < sizeof(value)) { value[len++] = 0; } else { throw AnytunErrno(ERROR_INSUFFICIENT_BUFFER); } } return std::string(value); } DWORD RegistryKey::getSubKey(DWORD index, RegistryKey& subKey, REGSAM sam) const { char subkeyname[NAME_LENGTH]; DWORD len = sizeof(subkeyname); DWORD err = RegEnumKeyExA(key_, index, subkeyname, &len, NULL, NULL, NULL, NULL); if(err != ERROR_SUCCESS) { return err; } return subKey.open(key_, subkeyname, sam); } DWORD RegistryKey::getSubKey(std::string name, RegistryKey& subKey, REGSAM sam) const { return subKey.open(key_, name.c_str(), sam); } anytun-0.3.8/src/linux/0000775000175000017500000000000013604635433014741 5ustar equinoxequinoxanytun-0.3.8/src/linux/tunDevice.cpp0000664000175000017500000001234213604635433017375 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include #include #include #include #include #include #define DEFAULT_DEVICE "/dev/net/tun" #include "tunDevice.h" #include "threadUtils.hpp" #include "log.h" #include "anytunError.h" #include "sysExec.h" TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400), sys_exec_(NULL) { struct ifreq ifr; memset(&ifr, 0, sizeof(ifr)); if(conf_.type_ == TYPE_TUN) { ifr.ifr_flags = IFF_TUN; with_pi_ = true; } else if(conf_.type_ == TYPE_TAP) { ifr.ifr_flags = IFF_TAP | IFF_NO_PI; with_pi_ = false; } else { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; } if(dev_name != "") { strncpy(ifr.ifr_name, dev_name.c_str(), IFNAMSIZ-1); } fd_ = ::open(DEFAULT_DEVICE, O_RDWR); if(fd_ < 0) { AnytunError::throwErr() << "can't open device file (" << DEFAULT_DEVICE << "): " << AnytunErrno(errno); } if(!ioctl(fd_, TUNSETIFF, &ifr)) { actual_name_ = ifr.ifr_name; } else if(!ioctl(fd_, (('T' << 8) | 202), &ifr)) { actual_name_ = ifr.ifr_name; } else { ::close(fd_); AnytunError::throwErr() << "tun/tap device ioctl failed: " << AnytunErrno(errno); } actual_node_ = DEFAULT_DEVICE; if(ifcfg_addr != "") { do_ifconfig(); } } TunDevice::~TunDevice() { if(fd_ > 0) { ::close(fd_); } } int TunDevice::fix_return(int ret, size_t pi_length) const { if(ret < 0) { return ret; } return (static_cast(ret) > pi_length ? (ret - pi_length) : 0); } int TunDevice::read(uint8_t* buf, uint32_t len) { if(fd_ < 0) { return -1; } if(with_pi_) { struct iovec iov[2]; struct tun_pi tpi; iov[0].iov_base = &tpi; iov[0].iov_len = sizeof(tpi); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::readv(fd_, iov, 2), sizeof(tpi))); } else { return(::read(fd_, buf, len)); } } int TunDevice::write(uint8_t* buf, uint32_t len) { if(fd_ < 0) { return -1; } if(!buf) { return 0; } if(with_pi_) { struct iovec iov[2]; struct tun_pi tpi; struct iphdr* hdr = reinterpret_cast(buf); tpi.flags = 0; if(hdr->version == 4) { tpi.proto = htons(ETH_P_IP); } else { tpi.proto = htons(ETH_P_IPV6); } iov[0].iov_base = &tpi; iov[0].iov_len = sizeof(tpi); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::writev(fd_, iov, 2), sizeof(tpi))); } else { return(::write(fd_, buf, len)); } } void TunDevice::init_post() { // nothing to be done here } void TunDevice::do_ifconfig() { std::ostringstream mtu_ss; mtu_ss << conf_.mtu_; StringVector args = boost::assign::list_of(actual_name_)(conf_.addr_.toString())("netmask")(conf_.netmask_.toString())("mtu")(mtu_ss.str()); sys_exec_ = new SysExec("/sbin/ifconfig", args); } void TunDevice::waitUntilReady() { if(sys_exec_) { SysExec::waitAndDestroy(sys_exec_); } } anytun-0.3.8/src/connectionList.h0000664000175000017500000000606413604635433016754 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_connectionList_h_INCLUDED #define ANYTUN_connectionList_h_INCLUDED #include #include #include "threadUtils.hpp" #include "datatypes.h" #include "connectionParam.h" #include "networkAddress.h" typedef std::map ConnectionMap; class ConnectionList { public: ConnectionList(); ~ConnectionList(); static ConnectionList& instance(); void addConnection(ConnectionParam& conn, uint16_t mux); const ConnectionMap::iterator getConnection(uint16_t mux); const ConnectionMap::iterator getEnd(); ConnectionMap::iterator getEndUnlocked(); ConnectionMap::iterator getBeginUnlocked(); const ConnectionMap::iterator getBegin(); ConnectionParam& getOrNewConnectionUnlocked(uint16_t mux); bool empty(); void clear(); Mutex& getMutex(); private: ConnectionList(const ConnectionList& s); void operator=(const ConnectionList& s); ConnectionMap connections_; Mutex mutex_; }; extern ConnectionList& gConnectionList; #endif anytun-0.3.8/src/syncServer.cpp0000664000175000017500000001221713604635433016454 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncServer.h" #include "resolver.h" #include "log.h" #include "anytunError.h" //using asio::ip::tcp; SyncServer::SyncServer(std::string localaddr, std::string port, ConnectCallback onConnect) : onConnect_(onConnect) { gResolver.resolveTcp(localaddr, port, boost::bind(&SyncServer::onResolve, this, _1), boost::bind(&SyncServer::onResolvError, this, _1)); } SyncServer::~SyncServer() { std::list::iterator it = acceptors_.begin(); for(; it != acceptors_.end(); ++it) { /// this might be a needed by a running thread, TODO cleanup // delete(it->acceptor_); } } void SyncServer::onResolve(SyncTcpConnection::proto::resolver::iterator it) { while(it != SyncTcpConnection::proto::resolver::iterator()) { SyncTcpConnection::proto::endpoint e = *it; AcceptorsElement acceptor; acceptor.acceptor_ = new SyncTcpConnection::proto::acceptor(io_service_); if(!acceptor.acceptor_) { AnytunError::throwErr() << "memory error"; } acceptor.acceptor_->open(e.protocol()); #if !defined(_MSC_VER) && !defined(MINGW) if(e.protocol() == boost::asio::ip::tcp::v6()) { acceptor.acceptor_->set_option(boost::asio::ip::v6_only(true)); } #endif acceptor.acceptor_->set_option(boost::asio::socket_base::reuse_address(true)); acceptor.acceptor_->bind(e); acceptor.acceptor_->listen(); acceptor.started_ = false; acceptors_.push_back(acceptor); cLog.msg(Log::PRIO_NOTICE) << "sync server listening on " << e; it++; } start_accept(); ready_sem_.up(); } void SyncServer::onResolvError(const std::runtime_error& e) { cLog.msg(Log::PRIO_ERROR) << "sync server bind/listen failed: " << e.what(); // TODO: stop daemon?? } void SyncServer::run() { ready_sem_.down(); io_service_.run(); } void SyncServer::send(std::string message) { Lock lock(mutex_); for(std::list::iterator it = conns_.begin() ; it != conns_.end(); ++it) { (*it)->Send(message); } } void SyncServer::start_accept() { Lock lock(mutex_); std::list::iterator it = acceptors_.begin(); for(; it != acceptors_.end(); ++it) { if(!it->started_) { #if BOOST_VERSION >= 107000 SyncTcpConnection::pointer new_connection = SyncTcpConnection::create(it->acceptor_->get_executor()); #else SyncTcpConnection::pointer new_connection = SyncTcpConnection::create(it->acceptor_->get_io_service()); #endif conns_.push_back(new_connection); it->acceptor_->async_accept(new_connection->socket(), boost::bind(&SyncServer::handle_accept, this, new_connection, boost::asio::placeholders::error, it)); it->started_ = true; } } } void SyncServer::handle_accept(SyncTcpConnection::pointer new_connection, const boost::system::error_code& error, std::list::iterator it) { if(!error) { cLog.msg(Log::PRIO_INFO) << "new sync client connected from " << new_connection->socket().remote_endpoint(); new_connection->onConnect = onConnect_; new_connection->start(); it->started_ = false; start_accept(); } } anytun-0.3.8/src/Makefile0000664000175000017500000003433213604635433015247 0ustar equinoxequinox## ## anytun ## ## The secure anycast tunneling protocol (satp) defines a protocol used ## for communication between any combination of unicast and anycast ## tunnel endpoints. It has less protocol overhead than IPSec in Tunnel ## mode and allows tunneling of every ETHER TYPE protocol (e.g. ## ethernet, ip, arp ...). satp directly includes cryptography and ## message authentication based on the methods used by SRTP. It is ## intended to deliver a generic, scaleable and secure solution for ## tunneling and relaying of packets of any protocol. ## ## ## Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, ## Christian Pointner ## ## This file is part of Anytun. ## ## Anytun is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## Anytun is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Anytun. If not, see . ## ## In addition, as a special exception, the copyright holders give ## permission to link the code of portions of this program with the ## OpenSSL library under certain conditions as described in each ## individual source file, and distribute linked combinations ## including the two. ## You must obey the GNU General Public License in all respects ## for all of the code used other than OpenSSL. If you modify ## file(s) with this exception, you may extend this exception to your ## version of the file(s), but you are not obligated to do so. If you ## do not wish to do so, delete this exception statement from your ## version. If you delete this exception statement from all source ## files in the program, then also delete it here. ## ifneq ($(MAKECMDGOALS),distclean) include include.mk endif ANYTUNOBJS := packetSource.o \ authAlgo.o \ authAlgoFactory.o \ cipher.o \ cipherFactory.o \ plainPacket.o \ encryptedPacket.o \ options.o \ signalController.o \ sysExec.o \ resolver.o \ buffer.o \ syncBuffer.o \ keyDerivation.o \ keyDerivationFactory.o \ connectionList.o \ connectionParam.o \ networkAddress.o \ networkPrefix.o \ routingTable.o \ routingTreeNode.o \ log.o \ logTargets.o \ anytunError.o \ seqWindow.o ifneq ($(TARGET),mingw) ANYTUNOBJS := $(ANYTUNOBJS) \ tunDevice.o \ daemonService.o else ANYTUNOBJS := $(ANYTUNOBJS) \ win32/tunDevice.o \ nullDaemon.o \ win32/winService.o \ win32/registryKey.o endif ANYSHOWOBJS := buffer.o \ syncBuffer.o \ keyDerivation.o \ keyDerivationFactory.o \ connectionList.o \ connectionParam.o \ networkAddress.o \ networkPrefix.o \ routingTable.o \ routingTreeNode.o \ log.o \ logTargets.o \ anytunError.o \ seqWindow.o \ nullOptions.o \ resolver.o SYNCOBJS := syncServer.o \ syncClient.o \ syncQueue.o \ syncCommand.o \ syncRouteCommand.o \ syncConnectionCommand.o \ syncTcpConnection.o ANYCTROBJS := signalController.o \ anyCtrOptions.o \ buffer.o \ log.o \ logTargets.o \ anytunError.o \ syncTcpConnection.o \ syncServer.o \ resolver.o ifneq ($(TARGET),mingw) ANYCTROBJS := $(ANYCTROBJS) \ daemonService.o else ANYCTROBJS := $(ANYCTROBJS) \ nullDaemon.o endif ANYCONFOBJS := log.o \ logTargets.o \ anytunError.o \ buffer.o \ keyDerivation.o \ keyDerivationFactory.o \ networkAddress.o \ networkPrefix.o \ connectionList.o \ connectionParam.o \ routingTreeNode.o \ anyConfOptions.o \ routingTable.o \ seqWindow.o \ syncQueue.o \ syncBuffer.o \ syncCommand.o \ syncServer.o \ syncTcpConnection.o \ syncRouteCommand.o \ syncConnectionCommand.o \ resolver.o ifneq ($(TARGET),mingw) EXE := else EXE := .exe endif EXECUTABLES := anytun$(EXE) anytun-config$(EXE) anytun-controld$(EXE) anytun-showtables$(EXE) anytun-nosync$(EXE) EXEOBJS := anytun.o anytun-config.o anytun-controld.o anytun-showtables.o ANYTUNSRCS := $(ANYTUNOBJS:%.o=%.cpp) ANYSHOWSRCS := $(ANYSHOWOBJS:%.o=%.cpp) SYNCSRCS := $(SYNCOBJS:%.o=%.cpp) ANYCTRSRCS := $(ANYCTROBJS:%.o=%.cpp) ANYCONFSRCS := $(ANYCONFOBJS:%.o=%.cpp) EXESRCS := $(EXEOBJS:%.o=%.cpp) .PHONY: distclean cleanall clean manpage install install-bin install-etc install-man uninstall remove purge remove-systemd install-systemd remove-bin remove-man remove-examples all: $(EXECUTABLES) #libAnysync.a %.d: %.cpp @set -e; rm -f $@; \ $(CXX) -MM $(CPPFLAGS) $< > $@.$$$$; \ sed 's,\($*\)\.o[ :]*,\1.o $@ : ,g' < $@.$$$$ > $@; \ rm -f $@.$$$$; echo '(re)building $@' ifneq ($(MAKECMDGOALS),distclean) -include $(ANYTUNSRCS:%.cpp=%.d) $(ANYSHOWSRCS:%.cpp=%.d) $(SYNCSRCS:%.cpp=%.d) $(ANYCTRSRCS:%.cpp=%.d) $(ANYCONFSRCS:%.cpp=%.d) $(EXESRCS:%.cpp=%.d) endif strip: $(EXECUTABLES) $(STRIP) -s $(EXECUTABLES) anytun$(EXE): $(ANYTUNOBJS) $(SYNCOBJS) anytun.o $(LD) $(ANYTUNOBJS) $(SYNCOBJS) anytun.o -o $@ $(LDFLAGS) anytun-static: $(ANYTUNOBJS) $(SYNCOBJS) anytun-noprivdrop.o $(LD) $(ANYTUNOBJS) $(SYNCOBJS) anytun-noprivdrop.o -o $@ -Bstatic -lstdc++ -static $(LDFLAGS) -lpthread $(STRIP) -s anytun-static anytun-nosync$(EXE): $(ANYTUNOBJS) anytun-nosync.o $(LD) $(ANYTUNOBJS) anytun-nosync.o -o $@ $(LDFLAGS) anytun-nosync.o: anytun.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DANYTUN_NOSYNC $< -c -o anytun-nosync.o anytun-showtables$(EXE): $(ANYSHOWOBJS) $(SYNCOBJS) anytun-showtables.o $(LD) $(ANYSHOWOBJS) $(SYNCOBJS) anytun-showtables.o -o $@ $(LDFLAGS) anytun-config$(EXE): $(ANYCONFOBJS) anytun-config.o $(LD) $(ANYCONFOBJS) anytun-config.o -o $@ $(LDFLAGS) anytun-controld$(EXE): $(ANYCTROBJS) anytun-controld.o $(LD) $(ANYCTROBJS) anytun-controld.o -o $@ $(LDFLAGS) options.o: options.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DANYTUN_OPTIONS $< -c -o $@ anyCtrOptions.o: options.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DANYCTR_OPTIONS $< -c -o $@ anyConfOptions.o: options.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) -DANYCONF_OPTIONS $< -c -o $@ nullOptions.o: options.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ %.o: %.cpp $(CXX) $(CPPFLAGS) $(CXXFLAGS) $< -c -o $@ libAnysync.a: $(OBJS) ar cru $@ $(OBJS) ranlib $@ anyrtpproxy: anytun $(MAKE) --directory=$(CURDIR)/anyrtpproxy distclean: cleanall find . -name *.o -exec rm -f {} \; rm -f config.sub config.guess rm -f daemonService.h rm -f daemonService.cpp rm -f signalHandler.hpp rm -f sysExec.hpp rm -f version.h rm -f tunDevice.cpp rm -f include.mk cleanall: clean $(MAKE) --directory="../doc" clean clean: rm -f *.o rm -f *.d rm -f *.d.* rm -f win32/*.o rm -f win32/*.d rm -f win32/*.d.* rm -f $(EXECUTABLES) rm -f *.exe rm -f anytun-nosync rm -f -r doc/html/* rm -f -r doc/latex/* rm -f libAnysync.a $(MAKE) --directory=$(CURDIR)/anyrtpproxy clean manpage: $(MAKE) --directory="../doc" manpage INSTALL_TARGETS := install-bin install-etc REMOVE_TARGETS := remove-bin remove-etc ifdef MANDIR INSTALL_TARGETS += install-man REMOVE_TARGETS += remove-man endif ifdef EXAMPLESDIR INSTALL_TARGETS += install-examples REMOVE_TARGETS += remove-examples endif ifdef SYSTEMDDIR INSTALL_TARGETS += install-systemd REMOVE_TARGETS := remove-systemd endif install: all $(INSTALL_TARGETS) install-bin: $(EXECUTABLES) $(INSTALL) -d $(DESTDIR)$(SBINDIR) $(INSTALL) -m 755 anytun $(DESTDIR)$(SBINDIR) $(INSTALL) -d $(DESTDIR)$(BINDIR) $(INSTALL) -m 755 anytun-config $(DESTDIR)$(BINDIR) $(INSTALL) -m 755 anytun-controld $(DESTDIR)$(BINDIR) $(INSTALL) -m 755 anytun-showtables $(DESTDIR)$(BINDIR) $(INSTALL) -d $(DESTDIR)$(LIBDIR) @ sed -e 's#/usr/local/sbin#$(SBINDIR)#' -e 's#/usr/local/bin#$(BINDIR)#' \ -e 's#/usr/local/etc#$(ETCDIR)#' ../usr/lib/anytun-launcher > ../usr/lib/anytun-launcher.bak $(INSTALL) -m 755 ../usr/lib/anytun-launcher.bak $(DESTDIR)$(LIBDIR)/anytun-launcher rm -f ../usr/lib/anytun-launcher.bak install-etc: $(INSTALL) -d $(DESTDIR)$(ETCDIR)/anytun @ echo "example configurations can be found at $(EXAMPLESDIR)/anytun" > $(DESTDIR)$(ETCDIR)/anytun/README $(INSTALL) -d $(DESTDIR)$(ETCDIR)/init.d @ sed -e 's#/usr/local/bin#$(BINDIR)#' -e 's#/usr/local/lib#$(LIBDIR)#' -e 's#/usr/local/etc#$(ETCDIR)#' ../etc/init.d/anytun > ../etc/init.d/anytun.bak $(INSTALL) -m 755 ../etc/init.d/anytun.bak $(DESTDIR)$(ETCDIR)/init.d/anytun rm -f ../etc/init.d/anytun.bak install-systemd: $(INSTALL) -d $(DESTDIR)$(SYSTEMDDIR) $(INSTALL) -m 644 ../usr/lib/systemd/system/anytun.service $(DESTDIR)$(SYSTEMDDIR)/anytun.service @ sed -e 's#/usr/local/lib#$(LIBDIR)#' ../usr/lib/systemd/system/anytun@.service > ../usr/lib/systemd/system/anytun@.service.bak @ sed -e 's#/usr/local/lib#$(LIBDIR)#' ../usr/lib/systemd/system/anytun-controld@.service > ../usr/lib/systemd/system/anytun-controld@.service.bak $(INSTALL) -m 644 ../usr/lib/systemd/system/anytun@.service.bak $(DESTDIR)$(SYSTEMDDIR)/anytun@.service $(INSTALL) -m 644 ../usr/lib/systemd/system/anytun-controld@.service.bak $(DESTDIR)$(SYSTEMDDIR)/anytun-controld@.service rm -f ../usr/lib/systemd/system/anytun@.service.bak rm -f ../usr/lib/systemd/system/anytun-controld@.service.bak $(INSTALL) -d $(DESTDIR)$(SYSTEMDGENERATORDIR) @ sed -e 's#/usr/local/etc#$(ETCDIR)#' ../usr/lib/systemd/system-generator/anytun-generator > ../usr/lib/systemd/system-generator/anytun-generator.bak $(INSTALL) -m 755 ../usr/lib/systemd/system-generator/anytun-generator.bak $(DESTDIR)$(SYSTEMDGENERATORDIR)/anytun-generator rm -f ../usr/lib/systemd/system-generator/anytun-generator.bak $(INSTALL) -d $(DESTDIR)$(TMPFILESDDIR) $(INSTALL) -m 644 ../usr/lib/tmpfiles.d/anytun.conf $(DESTDIR)$(TMPFILESDDIR)/anytun.conf install-examples: $(INSTALL) -d $(DESTDIR)$(EXAMPLESDIR)/anytun $(INSTALL) -m 644 ../etc/anytun/autostart $(DESTDIR)$(EXAMPLESDIR)/anytun/autostart @( cd '../etc/anytun/' ; \ for dir in `ls`; do \ if [ -d $$dir ]; then \ echo "install $$dir configuration" ; \ cd $$dir ; \ $(INSTALL) -d $(DESTDIR)$(EXAMPLESDIR)/anytun/$$dir ; \ $(INSTALL) -m 600 config $(DESTDIR)$(EXAMPLESDIR)/anytun/$$dir/config ; \ if [ -e 'post-up.sh' ]; then \ $(INSTALL) -m 755 post-up.sh $(DESTDIR)$(EXAMPLESDIR)/anytun/$$dir/post-up.sh ; \ fi ; \ if [ -d 'conf.d' ]; then \ $(INSTALL) -d $(DESTDIR)$(EXAMPLESDIR)/anytun/$$dir/conf.d ; \ cd conf.d ; \ for file in `ls`; do \ if [ -f $$file ]; then \ $(INSTALL) -m 600 $$file $(DESTDIR)$(EXAMPLESDIR)/anytun/$$dir/conf.d ; \ fi ; \ done ; \ cd .. ; \ fi ; \ cd .. ; \ fi ; \ done \ ) install-man: manpage $(INSTALL) -d $(DESTDIR)$(MANDIR)/man8/ $(INSTALL) -m 644 ../doc/anytun.8 $(DESTDIR)$(MANDIR)/man8/ $(INSTALL) -m 644 ../doc/anytun-config.8 $(DESTDIR)$(MANDIR)/man8/ $(INSTALL) -m 644 ../doc/anytun-controld.8 $(DESTDIR)$(MANDIR)/man8/ $(INSTALL) -m 644 ../doc/anytun-showtables.8 $(DESTDIR)$(MANDIR)/man8/ uninstall: remove remove: $(REMOVE_TARGETS) remove-bin: rm -f $(DESTDIR)$(SBINDIR)/anytun rm -f $(DESTDIR)$(BINDIR)/anytun-config rm -f $(DESTDIR)$(BINDIR)/anytun-controld rm -f $(DESTDIR)$(BINDIR)/anytun-showtables remove-etc: rm -f $(DESTDIR)$(ETCDIR)/init.d/anytun remove-systemd: rm -f $(DESTDIR)$(SYSTEMDDIR)/anytun.service rm -f $(DESTDIR)$(SYSTEMDDIR)/anytun@.service rm -f $(DESTDIR)$(SYSTEMDDIR)/anytun-controld@.service rm -f $(DESTDIR)$(SYSTEMDGENERATORDIR)/anytun-generator rm -f $(DESTDIR)$(TMPFILESDDIR)/anytun.conf remove-examples: rm -rf $(DESTDIR)$(EXAMPLESDIR)/anytun/ remove-man: rm -f $(DESTDIR)$(MANDIR)/man8/anytun.8 rm -f $(DESTDIR)$(MANDIR)/man8/anytun-config.8 rm -f $(DESTDIR)$(MANDIR)/man8/anytun-controld.8 rm -f $(DESTDIR)$(MANDIR)/man8/anytun-showtables.8 purge: remove rm -rf $(DESTDIR)$(ETCDIR)/anytun/ anytun-0.3.8/src/authAlgoFactory.cpp0000664000175000017500000000570413604635433017410 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include "authAlgoFactory.h" #include "authAlgo.h" #include "anytunError.h" AuthAlgo* AuthAlgoFactory::create(std::string const& type, kd_dir_t dir) { if(type == "null") { return new NullAuthAlgo(); } #ifndef NO_CRYPT else if(type == "sha1") { Sha1AuthAlgo* a = new Sha1AuthAlgo(dir); if(!a || !(a->Init())) { if(a) delete a; AnytunError::throwErr() << "failed to initialize SHA1 auth algo"; } return a; } #endif else { throw std::invalid_argument("auth algo not available"); } } uint32_t AuthAlgoFactory::getDigestLength(std::string const& type) { if(type == "null") { return NullAuthAlgo::DIGEST_LENGTH; } #ifndef NO_CRYPT else if(type == "sha1") { return Sha1AuthAlgo::DIGEST_LENGTH; } #endif else { throw std::invalid_argument("auth algo not available"); } } anytun-0.3.8/src/nullDaemon.cpp0000664000175000017500000000471413604635433016412 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "nullDaemon.h" void DaemonService::initPrivs(std::string const& username, std::string const& groupname) { // nothing here } void DaemonService::dropPrivs() { // nothing here } void DaemonService::chroot(std::string const& chrootdir) { // nothing here } void DaemonService::daemonize() { // nothing here } bool DaemonService::isDaemonized() { return false; } anytun-0.3.8/src/networkAddress.h0000664000175000017500000001136313604635433016756 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_networkAddress_h_INCLUDED #define ANYTUN_networkAddress_h_INCLUDED // TODO not required here #include #include #include "threadUtils.hpp" #include "datatypes.h" #include #include #include typedef boost::array ethernet_bytes_type; typedef boost::asio::ip::address_v4::bytes_type ipv4_bytes_type; typedef boost::asio::ip::address_v6::bytes_type ipv6_bytes_type; enum network_address_type_t { ipv4=0, ipv6=1, ethernet=2 }; class NetworkAddress { public: NetworkAddress(); NetworkAddress(const NetworkAddress&); NetworkAddress(const std::string&); NetworkAddress(boost::asio::ip::address_v6); NetworkAddress(boost::asio::ip::address_v4); NetworkAddress(uint64_t); NetworkAddress(const network_address_type_t type, const std::string& address); ~NetworkAddress(); void setNetworkAddress(const network_address_type_t type, const std::string& address); void setNetworkAddress(boost::asio::ip::address_v4); void setNetworkAddress(boost::asio::ip::address_v6); void setNetworkAddress(uint64_t); network_address_type_t getNetworkAddressType() const; std::string toString() const; bool operator<(const NetworkAddress& s) const; ipv4_bytes_type to_bytes_v4() const; ipv6_bytes_type to_bytes_v6() const; ethernet_bytes_type to_bytes_ethernet() const; const boost::asio::ip::address_v4& getNetworkAddressV4() const; const boost::asio::ip::address_v6& getNetworkAddressV6() const; const uint64_t getNetworkAdrressEther() const; protected: Mutex mutex_; boost::asio::ip::address_v4 ipv4_address_; boost::asio::ip::address_v6 ipv6_address_; uint64_t ethernet_address_; network_address_type_t network_address_type_; private: NetworkAddress operator=(const NetworkAddress& s); friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar& network_address_type_; if(network_address_type_==ipv4) { std::string ip(ipv4_address_.to_string()); ar& ip; ipv4_address_=boost::asio::ip::address_v4::from_string(ip); } if(network_address_type_==ipv6) { std::string ip(ipv6_address_.to_string()); ar& ip; ipv6_address_=boost::asio::ip::address_v6::from_string(ip); } if(network_address_type_==ethernet) { ar& ethernet_address_; } } }; // for(int i=0;i<4;i++) //#if defined(__GNUC__) && defined(__linux__) // ar & ipv6_address_.s6_addr32; //#elif defined(__GNUC__) && defined(__OpenBSD__) // ar & ipv6_address_.__u6_addr.__u6_addr32; //#else // #error Target not supported //#endif #endif anytun-0.3.8/src/signalController.h0000664000175000017500000000654413604635433017305 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_signalController_h_INCLUDED #define ANYTUN_signalController_h_INCLUDED #include #include #include #include "threadUtils.hpp" #ifdef WIN_SERVICE //#include "win32/winService.h" class WinService; typedef WinService DaemonService; #else class DaemonService; #endif #define SIGERROR -1 #define SIGUNKNOWN -2 typedef boost::function SignalHandler; typedef enum { CALLB_RUNNING, CALLB_STOPPING } CallbackType; typedef boost::function ServiceCallback; class SignalController { public: static SignalController& instance(); void init(DaemonService& service); int run(); void inject(int sig, const std::string& msg = ""); private: SignalController() {}; ~SignalController() {}; SignalController(const SignalController& s); void operator=(const SignalController& s); typedef std::pair SigPair; std::queue sigQueue; Mutex sigQueueMutex; Semaphore sigQueueSem; typedef std::map HandlerMap; HandlerMap handler; typedef std::map CallbackMap; CallbackMap callbacks; friend void registerSignalHandler(SignalController& ctrl, DaemonService& service); }; extern SignalController& gSignalController; #endif anytun-0.3.8/src/logTargets.h0000664000175000017500000001372513604635433016076 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_logTargets_h_INCLUDED #define ANYTUN_logTargets_h_INCLUDED #include #include #ifdef LOG_SYSLOG #include #endif #ifdef LOG_FILE #include #endif #include "datatypes.h" class LogTarget { public: LogTarget(); LogTarget(int prio); virtual ~LogTarget() {}; virtual void open() = 0; virtual void close() = 0; bool isOpen() { return opened; }; void enable() { enabled = true; }; void disable() { enabled = false; }; bool isEnabled() { return enabled; }; int getMaxPrio() { return max_prio; }; void setMaxPrio(int p) { max_prio = p; }; virtual void log(std::string msg, int prio) = 0; protected: bool opened; bool enabled; int max_prio; }; class LogTargetList { public: typedef enum { TARGET_UNKNOWN, TARGET_SYSLOG, TARGET_FILE, TARGET_STDOUT, TARGET_STDERR, TARGET_WINEVENTLOG } target_type_t; static target_type_t targetTypeFromString(std::string type); static std::string targetTypeToString(target_type_t type); ~LogTargetList(); LogTarget* add(std::string conf); LogTarget* add(target_type_t type, int prio, std::string conf); void clear(); void log(std::string msg, int prio); private: typedef std::multimap TargetsMap; TargetsMap targets; }; #ifdef LOG_SYSLOG class LogTargetSyslog : public LogTarget { public: static const int FAC_USER = LOG_USER; static const int FAC_MAIL = LOG_MAIL; static const int FAC_DAEMON = LOG_DAEMON; static const int FAC_AUTH = LOG_AUTH; static const int FAC_SYSLOG = LOG_SYSLOG; static const int FAC_LPR = LOG_LPR; static const int FAC_NEWS = LOG_NEWS; static const int FAC_UUCP = LOG_UUCP; static const int FAC_CRON = LOG_CRON; static const int FAC_AUTHPRIV = LOG_AUTHPRIV; static const int FAC_FTP = LOG_FTP; static const int FAC_LOCAL0 = LOG_LOCAL0; static const int FAC_LOCAL1 = LOG_LOCAL1; static const int FAC_LOCAL2 = LOG_LOCAL2; static const int FAC_LOCAL3 = LOG_LOCAL3; static const int FAC_LOCAL4 = LOG_LOCAL4; static const int FAC_LOCAL5 = LOG_LOCAL5; static const int FAC_LOCAL6 = LOG_LOCAL6; static const int FAC_LOCAL7 = LOG_LOCAL7; static int facilityFromString(std::string fac); static std::string facilityToString(int fac); LogTargetSyslog(int prio, std::string conf); ~LogTargetSyslog(); void open(); void close(); void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; LogTargetSyslog& setLogName(std::string l); std::string getLogName() const { return logname; } LogTargetSyslog& setFacility(int f); int getFacility() const { return facility; } private: std::string logname; int facility; }; #endif #ifdef LOG_FILE class LogTargetFile : public LogTarget { public: LogTargetFile(int prio, std::string conf); ~LogTargetFile(); void open(); void close(); void log(std::string msg, int prio); static bool duplicateAllowed() { return true; }; LogTargetFile& setLogFilename(std::string l); std::string getLogFilename() const { return logfilename; } private: std::string logfilename; std::ofstream logfile; }; #endif #ifdef LOG_STDOUT class LogTargetStdout : public LogTarget { public: LogTargetStdout(int prio, std::ostream& s); ~LogTargetStdout(); void open(); void close(); void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; private: std::ostream& stream; }; #endif #ifdef LOG_WINEVENTLOG class LogTargetWinEventlog : public LogTarget { public: static WORD prioToEventLogType(int prio); LogTargetWinEventlog(int prio, std::string conf); ~LogTargetWinEventlog(); void open(); void close(); void log(std::string msg, int prio); static bool duplicateAllowed() { return false; }; LogTargetWinEventlog& setLogName(std::string l); std::string getLogName() const { return logname; }; private: std::string logname; HANDLE h_event_source; }; #endif #endif anytun-0.3.8/src/syncRouteCommand.cpp0000664000175000017500000000446013604635433017604 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncRouteCommand.h" SyncRouteCommand::SyncRouteCommand() { } SyncRouteCommand::SyncRouteCommand(const NetworkPrefix& addr) :addr_(addr) { } NetworkPrefix SyncRouteCommand::getPrefix() const { return addr_; } anytun-0.3.8/src/keyDerivation.h0000664000175000017500000001465213604635433016600 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_keyDerivation_h_INCLUDED #define ANYTUN_keyDerivation_h_INCLUDED #include "datatypes.h" #include "buffer.h" #include "threadUtils.hpp" #include "syncBuffer.h" #include "options.h" #ifndef NO_CRYPT #if defined(USE_SSL_CRYPTO) #include #elif defined(USE_NETTLE) #include #else // USE_GCRYPT is the default #include #endif #endif #include #include #include #define LABEL_ENC 0 #define LABEL_AUTH 1 #define LABEL_SALT 2 #define LABEL_LEFT_ENC 0x356A192B #define LABEL_RIGHT_ENC 0xDA4B9237 #define LABEL_LEFT_SALT 0x77DE68DA #define LABEL_RIGHT_SALT 0x1B645389 #define LABEL_LEFT_AUTH 0xAC3478D6 #define LABEL_RIGHT_AUTH 0xC1DFD96E typedef enum { KD_INBOUND, KD_OUTBOUND } kd_dir_t; class KeyDerivation { public: KeyDerivation() : is_initialized_(false), role_(ROLE_LEFT), key_length_(0), master_salt_(0), master_key_(0) {}; KeyDerivation(uint16_t key_length) : is_initialized_(false), role_(ROLE_LEFT), key_length_(key_length), master_salt_(0), master_key_(0) {}; virtual ~KeyDerivation() {}; void setRole(const role_t role); virtual void init(Buffer key, Buffer salt, std::string passphrase = "") = 0; virtual bool generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key) = 0; virtual std::string printType() { return "GenericKeyDerivation"; }; satp_prf_label_t convertLabel(kd_dir_t dir, satp_prf_label_t label); protected: virtual void updateMasterKey() = 0; #ifndef NO_PASSPHRASE void calcMasterKey(std::string passphrase, uint16_t length); void calcMasterSalt(std::string passphrase, uint16_t length); #endif KeyDerivation(const KeyDerivation& src); friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { WritersLock lock(mutex_); ar& role_; ar& key_length_; ar& master_salt_; ar& master_key_; updateMasterKey(); } bool is_initialized_; role_t role_; uint16_t key_length_; SyncBuffer master_salt_; SyncBuffer master_key_; SharedMutex mutex_; }; #if BOOST_VERSION <= 103500 BOOST_IS_ABSTRACT(KeyDerivation); #else BOOST_SERIALIZATION_ASSUME_ABSTRACT(KeyDerivation); #endif //****** NullKeyDerivation ****** class NullKeyDerivation : public KeyDerivation { public: NullKeyDerivation() {}; ~NullKeyDerivation() {}; void init(Buffer key, Buffer salt, std::string passphrase = "") {}; bool generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key); std::string printType() { return "NullKeyDerivation"; }; private: void updateMasterKey() {}; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar& boost::serialization::base_object(*this); } }; #ifndef NO_CRYPT //****** AesIcmKeyDerivation ****** class AesIcmKeyDerivation : public KeyDerivation { public: AesIcmKeyDerivation(); AesIcmKeyDerivation(uint16_t key_length); ~AesIcmKeyDerivation(); static const uint16_t DEFAULT_KEY_LENGTH = 128; static const uint16_t CTR_LENGTH = 16; static const uint16_t SALT_LENGTH = 14; void init(Buffer key, Buffer salt, std::string passphrase = ""); bool generate(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr, Buffer& key); std::string printType(); private: void updateMasterKey(); bool calcCtr(kd_dir_t dir, satp_prf_label_t label, seq_nr_t seq_nr); friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar& boost::serialization::base_object(*this); } #if defined(USE_SSL_CRYPTO) AES_KEY aes_key_[2]; uint8_t ecount_buf_[2][AES_BLOCK_SIZE]; #elif defined(USE_NETTLE) struct aes_ctx ctx_[2]; #else // USE_GCRYPT is the default gcry_cipher_hd_t handle_[2]; #endif #ifdef _MSC_VER #pragma pack(push, 1) #endif union ATTR_PACKED key_derivation_aesctr_ctr_union { uint8_t buf_[CTR_LENGTH]; struct ATTR_PACKED { uint8_t buf_[SALT_LENGTH]; uint16_t zero_; } salt_; struct ATTR_PACKED { uint8_t fill_[SALT_LENGTH - sizeof(satp_prf_label_t) - sizeof(seq_nr_t)]; satp_prf_label_t label_; seq_nr_t seq_; uint16_t zero_; } params_; } ctr_[2]; #ifdef _MSC_VER #pragma pack(pop) #endif }; #endif #endif anytun-0.3.8/src/networkPrefix.h0000664000175000017500000000564413604635433016633 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_networkPrefix_h_INCLUDED #define ANYTUN_networkPrefix_h_INCLUDED #include "threadUtils.hpp" #include "datatypes.h" #include #include #include "networkAddress.h" class NetworkPrefix : public NetworkAddress { public: NetworkPrefix(); NetworkPrefix(const NetworkAddress&, uint8_t length); NetworkPrefix(const NetworkPrefix&); void setNetworkPrefixLength(uint8_t length); uint8_t getNetworkPrefixLength() const; bool operator<(const NetworkPrefix& s) const; private: void operator=(const NetworkPrefix& s); uint8_t length_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { ar& length_; ar& boost::serialization::base_object(*this); }; }; #endif anytun-0.3.8/src/anyrtpproxy/0000775000175000017500000000000013604635433016221 5ustar equinoxequinoxanytun-0.3.8/src/anyrtpproxy/commandHandler.cpp0000664000175000017500000002212613604635433021644 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include #include "commandHandler.h" #include "../buffer.h" #include "../log.h" #include "../syncQueue.h" #include "syncRtpCommand.h" #include "rtpSessionTable.h" #include "callIdQueue.h" #include "options.h" #define MAX_COMMAND_LENGTH 1000 CommandHandler::CommandHandler(SyncQueue& q, std::string lp,PortWindow& pw) : thread_(boost::bind(run,this)), queue_(q), running_(true), control_sock_(io_service_), local_address_(""), local_port_(lp),port_window_(pw) { proto::resolver resolver(io_service_); proto::resolver::query query(local_port_); proto::endpoint e = *resolver.resolve(query); control_sock_.open(e.protocol()); control_sock_.bind(e); } CommandHandler::CommandHandler(SyncQueue& q, string la, std::string lp, PortWindow& pw) : thread_(boost::bind(run,this)), queue_(q), running_(true), control_sock_(io_service_), local_address_(la), local_port_(lp),port_window_(pw) { proto::resolver resolver(io_service_); proto::resolver::query query(local_address_, local_port_); proto::endpoint e = *resolver.resolve(query); control_sock_.open(e.protocol()); control_sock_.bind(e); } void CommandHandler::run(void* s) { CommandHandler* self = reinterpret_cast(s); Buffer buf(uint32_t(MAX_COMMAND_LENGTH)); try { proto::endpoint remote_end; int len; for(;;) { buf.setLength(MAX_COMMAND_LENGTH); len = self->control_sock_.receive_from(boost::asio::buffer(buf.getBuf(), buf.getLength()), remote_end); buf.setLength(len); std::string ret = self->handle(std::string(reinterpret_cast(buf.getBuf()), buf.getLength())); // TODO: reinterpret is ugly cLog.msg(Log::PRIO_DEBUG) << "CommandHandler received Command from " << remote_end << ", ret='" << ret << "'"; self->control_sock_.send_to(boost::asio::buffer(ret.c_str(), ret.length()), remote_end); } } catch(std::exception& e) { self->running_ = false; } self->running_ = false; } bool CommandHandler::isRunning() { return running_; } std::string CommandHandler::handle(std::string command) { istringstream iss(command); ostringstream oss; std::string cookie; std::string cmd; iss >> cookie; oss << cookie << " "; if(iss.bad() || iss.eof()) { oss << RET_ERR_SYNTAX; return oss.str(); } iss >> cmd; std::vector params; while(!iss.bad() && !iss.eof()) { std::string tmp; iss >> tmp; params.push_back(tmp); } switch(std::toupper(cmd[0])) { case CMD_REQUEST: if(params.size() < 4) { oss << RET_ERR_SYNTAX; break; } oss << handleRequest(cmd.erase(0,1), params[0], params[1], params[2], params[3], (params.size() < 5) ? "" : params[4]); break; case CMD_RESPONSE: if(params.size() < 4) { oss << RET_ERR_SYNTAX; break; } oss << handleResponse(cmd.erase(0,1), params[0], params[1], params[2], params[3], (params.size() < 5) ? "" : params[4]); break; case CMD_DELETE: if(params.size() < 2) { oss << RET_ERR_SYNTAX; break; } oss << handleDelete(params[0], params[1], (params.size() < 3) ? "" : params[2]); break; case CMD_VERSION: if(cmd.length() > 1 && cmd[1] == 'F') { if(params.size() < 1) { oss << RET_ERR_SYNTAX; break; } oss << handleVersionF(params[0]); break; } oss << handleVersion(); break; case CMD_INFO: oss << handleInfo(); break; default: oss << RET_ERR_SYNTAX; break; } return oss.str(); } string CommandHandler::handleRequest(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag) { std::cout << "received request[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port << "','" << from_tag << "','" << to_tag << "')" << std::endl; try { RtpSession::proto::resolver resolver(io_service_); bool is_new; RtpSession& session = gRtpSessionTable.getOrNewSession(call_id, is_new); if(is_new) { uint16_t port1 = port_window_.newPort(); // TODO: get next available port uint16_t port2 = port_window_.newPort(); // TODO: get next available port if(!port1 || !port2) { if(port1) { port_window_.freePort(port1); } if(port2) { port_window_.freePort(port2); } throw std::runtime_error("no free port found"); } std::stringstream ps1, ps2; ps1 << port1; ps2 << port2; RtpSession::proto::endpoint e1, e2; if(gOpt.getLocalAddr() == "") { RtpSession::proto::resolver::query query1(ps1.str()); e1 = *resolver.resolve(query1); RtpSession::proto::resolver::query query2(ps2.str()); e2 = *resolver.resolve(query2); } else { RtpSession::proto::resolver::query query1(gOpt.getLocalAddr(),ps1.str()); e1 = *resolver.resolve(query1); RtpSession::proto::resolver::query query2(gOpt.getLocalAddr(),ps2.str()); e2 = *resolver.resolve(query2); } session.setLocalEnd1(e1); session.setLocalEnd2(e2); } RtpSession::proto::resolver::query query(addr,port); session.setRemoteEnd1(*resolver.resolve(query)); ostringstream oss; oss << session.getLocalEnd2().port(); return oss.str(); } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } string CommandHandler::handleResponse(string modifiers, string call_id, string addr, string port, string from_tag, string to_tag) { std::cout << "received response[" << modifiers << "] command ('" << call_id << "','" << addr << "','" << port << "','" << from_tag << "','" << to_tag << "')" << std::endl; try { RtpSession& session = gRtpSessionTable.getSession(call_id); RtpSession::proto::resolver resolver(io_service_); RtpSession::proto::resolver::query query(addr,port); session.setRemoteEnd2(*resolver.resolve(query)); session.isComplete(true); SyncRtpCommand sc(call_id); queue_.push(sc); ostringstream oss; oss << session.getLocalEnd1().port(); return oss.str(); } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } string CommandHandler::handleDelete(string call_id, string from_tag, string to_tag) { std::cout << "received delete command ('" << call_id << "','" << from_tag << "','" << to_tag << "')" << std::endl; try { RtpSession& session = gRtpSessionTable.getSession(call_id); session.isDead(true); SyncRtpCommand sc(call_id); queue_.push(sc); return RET_OK; } catch(std::exception& e) { return RET_ERR_UNKNOWN; // TODO: change to corret error value } } string CommandHandler::handleVersion() { std::cout << "received version command" << std::endl; return BASE_VERSION; } string CommandHandler::handleVersionF(string date_code) { std::cout << "received version[F] command ('" << date_code << "')" << std::endl; if(!date_code.compare(SUP_VERSION)) { return "1"; } return "0"; } string CommandHandler::handleInfo() { std::cout << "received info command, ignoring" << std::endl; return RET_OK; } anytun-0.3.8/src/anyrtpproxy/syncRtpCommand.h0000664000175000017500000000542013604635433021334 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _SYNCRTPCOMMAND_H #define _SYNCRTPCOMMAND_H #include #include #include "../threadUtils.hpp" #include "rtpSessionTable.h" class SyncRtpCommand { public: SyncRtpCommand(const std::string&); SyncRtpCommand(); std::string getCallId() const; private: SyncRtpCommand(const SyncRtpCommand&); std::string callid_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(gRtpSessionTable.getMutex()); ar& callid_; bool is_new; ar& gRtpSessionTable.getOrNewSessionUnlocked(callid_, is_new); }; }; #endif // _SYNCCOMMAND_H anytun-0.3.8/src/anyrtpproxy/connectionList.cpp0000664000175000017500000000607013604635433021723 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "connectionList.h" ConnectionList::ConnectionList() { } ConnectionList::~ConnectionList() { } void ConnectionList::addConnection(ConnectionParam& conn, uint16_t mux) { } const ConnectionMap::iterator ConnectionList::getEnd() { return connections_.end(); } ConnectionMap::iterator ConnectionList::getBeginUnlocked() { return connections_.begin(); } ConnectionMap::iterator ConnectionList::getEndUnlocked() { return connections_.end(); } const ConnectionMap::iterator ConnectionList::getConnection(uint16_t mux) { Lock lock(mutex_); ConnectionMap::iterator it = connections_.find(mux); return it; } ConnectionParam& ConnectionList::getOrNewConnectionUnlocked(uint16_t mux) { ConnectionMap::iterator it = connections_.find(mux); return it->second; } void ConnectionList::clear() { Lock lock(mutex_); connections_.clear(); } bool ConnectionList::empty() { Lock lock(mutex_); return connections_.empty(); } Mutex& ConnectionList::getMutex() { return mutex_; } anytun-0.3.8/src/anyrtpproxy/options.h0000664000175000017500000001035413604635433020070 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _OPTIONS_H_ #define _OPTIONS_H_ #include "../threadUtils.hpp" #include #include typedef struct OptionConnectTo { std::string host; std::string port; }; typedef std::list ConnectToList; class Host { public: Host(std::string addr, std::string port) : addr_(addr), port_(port) {} Host(std::string addr_port) { splitAndSetAddrPort(addr_port); } std::string toString() const { std::ostringstream oss; oss << addr_ << ":" << port_; return oss.str(); } std::string addr_; std::string port_; protected: void splitAndSetAddrPort(std::string addr_port); }; typedef std::list HostList; class Options { public: static Options& instance(); bool parse(int argc, char* argv[]); void printUsage(); void printOptions(); std::string getProgname(); bool getChroot(); bool getNat(); bool getNoNatOnce(); std::string getUsername(); std::string getChrootDir(); std::string getPidFile(); bool getDaemonize(); Host getControlInterface(); std::string getLocalAddr(); Options& setLocalAddr(std::string l); std::string getLocalSyncAddr(); Options& setLocalSyncAddr(std::string l); std::string getLocalSyncPort(); Options& setLocalSyncPort(std::string l); uint16_t getRtpStartPort(); Options& setRtpStartPort(uint16_t l); uint16_t getRtpEndPort(); Options& setRtpEndPort(uint16_t l); ConnectToList getConnectTo(); private: Options(); ~Options(); Options(const Options& l); void operator=(const Options& l); bool sanityCheck(); static Options* inst; static ::Mutex instMutex; class instanceCleaner { public: ~instanceCleaner() { if(Options::inst != 0) { delete Options::inst; } } }; friend class instanceCleaner; ::Mutex mutex; std::string progname_; bool chroot_; bool nat_; bool no_nat_once_; std::string username_; std::string chroot_dir_; std::string pid_file_; bool daemonize_; std::string local_sync_addr_; std::string local_sync_port_; std::string local_addr_; uint16_t rtp_start_port_; uint16_t rtp_end_port_; ConnectToList connect_to_; Host control_interface_; }; extern Options& gOpt; #endif anytun-0.3.8/src/anyrtpproxy/portWindow.cpp0000664000175000017500000000577513604635433021117 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "portWindow.h" PortWindow::PortWindow(uint16_t start, uint16_t end) : start_port_(start), end_port_(end) { } PortWindow::~PortWindow() { } PortWindow::PortSet::size_type PortWindow::getLength() { Lock lock(mutex_); return ports_.size(); } bool PortWindow::hasPort(uint16_t port) { Lock lock(mutex_); PortSet::const_iterator it=ports_.find(port); if(it == ports_.end()) { return false; } return true; } bool PortWindow::freePort(uint16_t port) { Lock lock(mutex_); PortSet::iterator it=ports_.find(port); if(it == ports_.end()) { return false; } ports_.erase(it); return true; } uint16_t PortWindow::newPort() { Lock lock(mutex_); uint16_t port= start_port_; while(port=end_port_) { return 0; } ports_.insert(port); return port; } void PortWindow::clear() { Lock lock(mutex_); ports_.clear(); } anytun-0.3.8/src/anyrtpproxy/callIdQueue.h0000664000175000017500000000545713604635433020602 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef __CALLID_QUEUE_H__ #define __CALLID_QUEUE_H__ #include #include #include "../threadUtils.hpp" class CallIdQueue { public: static CallIdQueue& instance(); std::string& front(); void push(std::string c); void pop(); private: CallIdQueue(); ~CallIdQueue(); void operator=(const CallIdQueue& src); CallIdQueue(const CallIdQueue& src); static CallIdQueue* inst; static ::Mutex instMutex; class instanceCleaner { public: ~instanceCleaner() { if(CallIdQueue::inst != 0) { delete CallIdQueue::inst; } } }; friend class instanceCleaner; ::Mutex mutex_; Semaphore sem_; std::queue callids_; }; extern CallIdQueue& gCallIdQueue; #endif anytun-0.3.8/src/anyrtpproxy/commandHandler.h0000664000175000017500000000722413604635433021313 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _COMMAND_HANDLER_H_ #define _COMMAND_HANDLER_H_ #include #include #include "../datatypes.h" #include "../PracticalSocket.h" #include "../syncQueue.h" #include "portWindow.h" class CommandHandler { public: typedef boost::asio::ip::udp proto; CommandHandler(SyncQueue& q, std::string lp, PortWindow&); CommandHandler(SyncQueue& q, std::string la, std::string lp, PortWindow&); bool isRunning(); #define CMD_REQUEST 'U' #define CMD_RESPONSE 'L' #define CMD_DELETE 'D' #define CMD_VERSION 'V' #define CMD_INFO 'I' #define RET_OK "0" #define RET_ERR_SYNTAX "E1" #define RET_ERR_UNKNOWN "E2" #define BASE_VERSION "20040107" #define SUP_VERSION "20050322" private: CommandHandler(const CommandHandler& c); void operator=(const CommandHandler& c); static void run(void* s); std::string handle(std::string command); std::string handleRequest(std::string modifiers, std::string call_id, std::string addr, std::string port, std::string from_tag, std::string to_tag); std::string handleResponse(std::string modifiers, std::string call_id, std::string addr, std::string port, std::string from_tag, std::string to_tag); std::string handleDelete(std::string call_id, std::string from_tag, std::string to_tag); std::string handleVersion(); std::string handleVersionF(std::string date_code); std::string handleInfo(); boost::thread thread_; SyncQueue& queue_; bool running_; boost::asio::io_service io_service_; proto::socket control_sock_; std::string local_address_; std::string local_port_; PortWindow& port_window_; }; #endif anytun-0.3.8/src/anyrtpproxy/connectionList.h0000664000175000017500000000562713604635433021377 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _CONNECTION_LIST_H #define _CONNECTION_LIST_H #include #include "../threadUtils.hpp" #include "../datatypes.h" #include "../connectionParam.h" #include "../networkAddress.h" typedef std::map ConnectionMap; class ConnectionList { public: ConnectionList(); ~ConnectionList(); void addConnection(ConnectionParam& conn, uint16_t mux); const ConnectionMap::iterator getConnection(uint16_t mux); const ConnectionMap::iterator getEnd(); ConnectionMap::iterator getEndUnlocked(); ConnectionMap::iterator getBeginUnlocked(); ConnectionParam& getOrNewConnectionUnlocked(uint16_t mux); bool empty(); void clear(); Mutex& getMutex(); private: ConnectionList(const ConnectionList& s); void operator=(const ConnectionList& s); ConnectionMap connections_; Mutex mutex_; }; #endif anytun-0.3.8/src/anyrtpproxy/Makefile0000664000175000017500000000566613604635433017676 0ustar equinoxequinox## ## anytun ## ## The secure anycast tunneling protocol (satp) defines a protocol used ## for communication between any combination of unicast and anycast ## tunnel endpoints. It has less protocol overhead than IPSec in Tunnel ## mode and allows tunneling of every ETHER TYPE protocol (e.g. ## ethernet, ip, arp ...). satp directly includes cryptography and ## message authentication based on the methods used by SRTP. It is ## intended to deliver a generic, scaleable and secure solution for ## tunneling and relaying of packets of any protocol. ## ## ## Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, ## Christian Pointner ## ## This file is part of Anytun. ## ## Anytun is free software: you can redistribute it and/or modify ## it under the terms of the GNU General Public License as published by ## the Free Software Foundation, either version 3 of the License, or ## any later version. ## ## Anytun is distributed in the hope that it will be useful, ## but WITHOUT ANY WARRANTY; without even the implied warranty of ## MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ## GNU General Public License for more details. ## ## You should have received a copy of the GNU General Public License ## along with Anytun. If not, see . ## ## In addition, as a special exception, the copyright holders give ## permission to link the code of portions of this program with the ## OpenSSL library under certain conditions as described in each ## individual source file, and distribute linked combinations ## including the two. ## You must obey the GNU General Public License in all respects ## for all of the code used other than OpenSSL. If you modify ## file(s) with this exception, you may extend this exception to your ## version of the file(s), but you are not obligated to do so. If you ## do not wish to do so, delete this exception statement from your ## version. If you delete this exception statement from all source ## files in the program, then also delete it here. ## CC = gcc CFLAGS = -g -Wall CXX = g++ CXXFLAGS = -g -Wall LD = g++ LDFLAGS = -g -Wall -O2 -lboost_thread -lboost_serialization -lboost_system OBJS = anyrtpproxy.o \ ../signalController.o \ ../log.o \ ../buffer.o \ rtpSessionTable.o \ rtpSession.o \ connectionList.o \ ../syncServer.o \ ../syncClient.o \ ../syncTcpConnection.o \ ../syncQueue.o \ syncRtpCommand.o \ commandHandler.o \ portWindow.o \ callIdQueue.o \ options.o SRCS = $(OBJS:%.o=%.cpp) EXECUTABLE = anyrtpproxy DEPENDFILE = .depend .PHONY: dep clean all: dep $(EXECUTABLE) dep: $(SRCS) $(CC) -MM $(SRCS) > $(DEPENDFILE) -include $(DEPENDFILE) anyrtpproxy: $(OBJS) $(LD) $(OBJS) -o $@ $(LDFLAGS) %.o: %.cpp $(CXX) $(CXXFLAGS) $< -c clean: rm -f *.o rm -f $(DEPENDFILE) rm -f $(EXECUTABLE) anytun-0.3.8/src/anyrtpproxy/syncRtpCommand.cpp0000664000175000017500000000444413604635433021674 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncRtpCommand.h" SyncRtpCommand::SyncRtpCommand() { } SyncRtpCommand::SyncRtpCommand(const std::string& addr) :callid_(addr) { } std::string SyncRtpCommand::getCallId() const { return callid_; } anytun-0.3.8/src/anyrtpproxy/portWindow.h0000664000175000017500000000515413604635433020553 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _PORT_WINDOW_H_ #define _PORT_WINDOW_H_ #include #include "../threadUtils.hpp" #include "../datatypes.h" class PortWindow { public: typedef std::set PortSet; PortWindow(uint16_t,uint16_t); ~PortWindow(); PortSet::size_type getLength(); bool hasPort(uint16_t); bool freePort(uint16_t); uint16_t newPort(); void clear(); private: uint16_t start_port_; uint16_t end_port_; ::Mutex mutex_; PortSet ports_; PortWindow(const PortWindow& s); void operator=(const PortWindow& s); }; #endif anytun-0.3.8/src/anyrtpproxy/anyrtpproxy.cpp0000664000175000017500000003021313604635433021343 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include "../datatypes.h" #include "../log.h" #include "../signalController.h" #include "../buffer.h" #include "connectionList.h" #include "rtpSessionTable.h" #include "syncRtpCommand.h" #include "../syncQueue.h" #include "../syncClient.h" #include "syncOnConnect.hpp" #include "../threadUtils.hpp" #include "commandHandler.h" #include "callIdQueue.h" #include "options.h" #include "portWindow.h" #include #include #define MAX_PACKET_SIZE 1500 void listener(RtpSession::proto::socket* sock1, RtpSession::proto::socket* sock2, std::string call_id, int dir, SyncQueue* queue, bool* running) { cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") started"; try { Buffer buf(uint32_t(MAX_PACKET_SIZE)); RtpSession::proto::endpoint remote_end; for(;;) { buf.setLength(MAX_PACKET_SIZE); uint32_t len=0; if(dir == 1) { len = 0; //sock1->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); } else if(dir == 2) { len = 0; //sock2->recvFromNonBlocking(buf.getBuf(), buf.getLength(), remote_end, 1000); } else { break; } RtpSession& session = gRtpSessionTable.getSession(call_id); if(session.isDead()) { cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") session is dead, exiting"; break; } if(!len) { continue; } buf.setLength(len); if((dir == 1 && remote_end != session.getRemoteEnd1()) || (dir == 2 && remote_end != session.getRemoteEnd2())) { if(gOpt.getNat() || (!gOpt.getNoNatOnce() && ((dir == 1 && !session.getSeen1()) || (dir == 2 && !session.getSeen2())))) { cLog.msg(Log::PRIO_NOTICE) << "listener(" << call_id << "/" << dir << ") setting remote host to " << remote_end; if(dir == 1) { session.setRemoteEnd1(remote_end); } if(dir == 2) { session.setRemoteEnd2(remote_end); } if(!gOpt.getNat()) { // with nat enabled sync is not needed SyncRtpCommand sc(call_id); queue->push(sc); } } else { continue; } } session.setSeen1(); session.setSeen2(); if(dir == 1) { sock2->send_to(boost::asio::buffer(buf.getBuf(), buf.getLength()), session.getRemoteEnd2()); } else if(dir == 2) { sock1->send_to(boost::asio::buffer(buf.getBuf(), buf.getLength()), session.getRemoteEnd1()); } else { break; } } } catch(std::exception& e) { cLog.msg(Log::PRIO_ERR) << "listener(" << call_id << "/" << dir << ") exiting because: " << e.what(); } *running = false; gCallIdQueue.push(call_id); } class ListenerData { public: ListenerData() : sock1_(ios1_), sock2_(ios2_) {} boost::asio::io_service ios1_; boost::asio::io_service ios2_; RtpSession::proto::socket sock1_; RtpSession::proto::socket sock2_; boost::thread* thread1_; boost::thread* thread2_; bool running1_; bool running2_; }; void listenerManager(void* p) { SyncQueue* queue_ = reinterpret_cast(p); std::map listenerMap; for(;;) { try { std::string call_id = gCallIdQueue.front(); // waits for semaphor and returns next call_id gCallIdQueue.pop(); RtpSession& session = gRtpSessionTable.getSession(call_id); if(!session.isComplete()) { continue; } std::map::iterator it; it = listenerMap.find(call_id); if(it == listenerMap.end()) { // listener Threads not existing yet ListenerData* ld = new ListenerData(); ld->sock1_.open(session.getLocalEnd1().protocol()); ld->sock1_.bind(session.getLocalEnd1()); ld->sock2_.open(session.getLocalEnd2().protocol()); ld->sock2_.bind(session.getLocalEnd2()); ld->thread1_ = new boost::thread(boost::bind(listener, &(ld->sock1_), &(ld->sock2_), call_id, 1, queue_, &(ld->running1_))); ld->thread2_ = new boost::thread(boost::bind(listener, &(ld->sock1_), &(ld->sock2_), call_id, 2, queue_, &(ld->running2_))); std::pair::iterator, bool> ret; ret = listenerMap.insert(std::map::value_type(call_id, ld)); continue; } if(!it->second->running1_ && !it->second->running2_) { cLog.msg(Log::PRIO_NOTICE) << "listenerManager both threads for '" << call_id << "' exited, cleaning up"; if(it->second->thread1_) { it->second->thread1_->join(); delete it->second->thread1_; } if(it->second->thread2_) { it->second->thread2_->join(); delete it->second->thread2_; } delete it->second; listenerMap.erase(it); gRtpSessionTable.delSession(call_id); continue; } // TODO: reinit if session changed } catch(std::exception& e) { cLog.msg(Log::PRIO_ERR) << "listenerManager restarting after exception: " << e.what(); usleep(500); // in case of an hard error don't block cpu (this is ugly) } } cLog.msg(Log::PRIO_ERR) << "listenerManager exiting because of unknown reason"; } void chrootAndDrop(string const& chrootdir, string const& username) { if(getuid() != 0) { std::cerr << "this program has to be run as root in order to run in a chroot" << std::endl; exit(-1); } struct passwd* pw = getpwnam(username.c_str()); if(pw) { if(chroot(chrootdir.c_str())) { std::cerr << "can't chroot to " << chrootdir << std::endl; exit(-1); } std::cout << "we are in chroot jail (" << chrootdir << ") now" << std::endl; chdir("/"); if(initgroups(pw->pw_name, pw->pw_gid) || setgid(pw->pw_gid) || setuid(pw->pw_uid)) { std::cerr << "can't drop to user " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; exit(-1); } std::cout << "dropped user to " << username << " " << pw->pw_uid << ":" << pw->pw_gid << std::endl; } else { std::cerr << "unknown user " << username << std::endl; exit(-1); } } void daemonize() { pid_t pid; pid = fork(); if(pid) { exit(0); } setsid(); pid = fork(); if(pid) { exit(0); } // std::cout << "running in background now..." << std::endl; int fd; // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors for(fd=0; fd<=2; fd++) { // close all file descriptors close(fd); } fd=open("/dev/null",O_RDWR); // stdin dup(fd); // stdout dup(fd); // stderr umask(027); } class ThreadParam { public: ThreadParam(SyncQueue& queue_,OptionConnectTo& connto_) : queue(queue_),connto(connto_) {}; SyncQueue& queue; OptionConnectTo& connto; }; void syncConnector(void* p) { ThreadParam* param = reinterpret_cast(p); SyncClient sc(param->connto.host, param->connto.port); sc.run(); } void syncListener(SyncQueue* queue) { try { boost::asio::io_service io_service; SyncTcpConnection::proto::resolver resolver(io_service); SyncTcpConnection::proto::endpoint e; if(gOpt.getLocalSyncAddr()!="") { SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncAddr(), gOpt.getLocalSyncPort()); e = *resolver.resolve(query); } else { SyncTcpConnection::proto::resolver::query query(gOpt.getLocalSyncPort()); e = *resolver.resolve(query); } SyncServer server(io_service,e); server.onConnect=boost::bind(syncOnConnect,_1); queue->setSyncServerPtr(&server); io_service.run(); } catch(std::exception& e) { std::string addr = gOpt.getLocalSyncAddr() == "" ? "*" : gOpt.getLocalSyncAddr(); cLog.msg(Log::PRIO_ERR) << "sync: cannot bind to " << addr << ":" << gOpt.getLocalSyncPort() << " (" << e.what() << ")" << std::endl; } } int main(int argc, char* argv[]) { // std::cout << "anyrtpproxy" << std::endl; if(!gOpt.parse(argc, argv)) { gOpt.printUsage(); exit(-1); } cLog.setLogName("anyrtpproxy"); cLog.msg(Log::PRIO_NOTICE) << "anyrtpproxy started..."; std::ofstream pidFile; if(gOpt.getPidFile() != "") { pidFile.open(gOpt.getPidFile().c_str()); if(!pidFile.is_open()) { std::cout << "can't open pid file" << std::endl; } } if(gOpt.getChroot()) { chrootAndDrop(gOpt.getChrootDir(), gOpt.getUsername()); } if(gOpt.getDaemonize()) { daemonize(); } if(pidFile.is_open()) { pid_t pid = getpid(); pidFile << pid; pidFile.close(); } SignalController sig; sig.init(); SyncQueue queue; boost::thread listenerManagerThread(boost::bind(listenerManager,&queue)); // #ifndef ANYTUN_NOSYNC // boost::thread * syncListenerThread; // if(gOpt.getLocalSyncPort() != "") // syncListenerThread = new boost::thread(boost::bind(syncListener,&queue)); // std::list connectThreads; // for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) { // ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it); // connectThreads.push_back(new boost::thread(boost::bind(syncConnector,point))); // } // #endif // pthread_t syncListenerThread; // ConnectToList connect_to = gOpt.getConnectTo(); // ThreadParam p( queue,*(new OptionConnectTo())); // if ( gOpt.getLocalSyncPort()) // pthread_create(&syncListenerThread, NULL, syncListener, &p); // std::list connectThreads; // for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it) // { // connectThreads.push_back(pthread_t()); // ThreadParam * point = new ThreadParam(queue,*it); // pthread_create(& connectThreads.back(), NULL, syncConnector, point); // } PortWindow port_window(gOpt.getRtpStartPort(),gOpt.getRtpEndPort()); CommandHandler cmd(queue, gOpt.getControlInterface().addr_, gOpt.getControlInterface().port_,port_window); int ret = sig.run(); return ret; } anytun-0.3.8/src/anyrtpproxy/options.cpp0000664000175000017500000003172213604635433020425 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include "options.h" Options* Options::inst = NULL; Mutex Options::instMutex; Options& gOpt = Options::instance(); Options& Options::instance() { Lock lock(instMutex); static instanceCleaner c; if(!inst) { inst = new Options(); } return *inst; } void Host::splitAndSetAddrPort(std::string addr_port) { if(addr_port.length() >= 2 && addr_port[0] == ':' && addr_port[1] != ':') { addr_ = ""; addr_port.erase(0,1); std::stringstream tmp_stream(addr_port); tmp_stream >> port_; return; } size_t pos = addr_port.find_first_of("["); if(pos != std::string::npos && pos != 0) { return; // an [ was found but not at the beginning } bool hasPort = false; if(pos != std::string::npos) { addr_port.erase(pos, 1); pos = addr_port.find_first_of("]"); if(pos == std::string::npos) { return; // no trailing ] although an leading [ was found } if(pos < addr_port.length()-2) { if(addr_port[pos+1] != ':') { return; // wrong port delimieter } addr_port[pos+1] = '/'; hasPort = true; } else if(pos != addr_port.length()-1) { return; // to few characters left } addr_port.erase(pos, 1); } if(hasPort) { std::stringstream tmp_stream(addr_port); getline(tmp_stream, addr_, '/'); if(!tmp_stream.good()) { return; } tmp_stream >> port_; } else { addr_ = addr_port; port_ = "2323"; // default sync port } } Options::Options() : control_interface_("0.0.0.0", "22222") { progname_ = "anyrtpproxy"; chroot_ = false; username_ = "nobody"; chroot_dir_ = "/var/run"; daemonize_ = true; pid_file_ = ""; local_addr_ = ""; local_sync_port_ = ""; rtp_start_port_ = 34000; rtp_end_port_ = 35000; no_nat_once_ = false; nat_ = false; } Options::~Options() { } #define PARSE_BOOL_PARAM(SHORT, LONG, VALUE) \ else if(str == SHORT || str == LONG) \ VALUE = true; #define PARSE_INVERSE_BOOL_PARAM(SHORT, LONG, VALUE) \ else if(str == SHORT || str == LONG) \ VALUE = false; #define PARSE_SCALAR_PARAM(SHORT, LONG, VALUE) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1 || argv[i+1][0] == '-') \ return false; \ std::stringstream tmp; \ tmp << argv[i+1]; \ tmp >> VALUE; \ argc--; \ i++; \ } #define PARSE_SCALAR_PARAM2(SHORT, LONG, VALUE1, VALUE2) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 2 || \ argv[i+1][0] == '-' || argv[i+2][0] == '-') \ return false; \ std::stringstream tmp; \ tmp << argv[i+1] << " " << argv[i+2]; \ tmp >> VALUE1; \ tmp >> VALUE2; \ argc-=2; \ i+=2; \ } #define PARSE_STRING_PARAM(SHORT, LONG, VALUE) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1 || argv[i+1][0] == '-') \ return false; \ VALUE = std::string(argv[i+1]); \ argc--; \ i++; \ } #define PARSE_HEXSTRING_PARAM_SEC(SHORT, LONG, VALUE) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1 || argv[i+1][0] == '-') \ return false; \ VALUE = Buffer(std::string(argv[i+1])); \ for(size_t j=0; j < strlen(argv[i+1]); ++j) \ argv[i+1][j] = '#'; \ argc--; \ i++; \ } #define PARSE_CSLIST_PARAM(SHORT, LONG, LIST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1 || argv[i+1][0] == '-') \ return false; \ std::stringstream tmp(argv[i+1]); \ /* LIST.clear(); */ \ while (tmp.good()) \ { \ std::string tmp_line; \ getline(tmp,tmp_line,','); \ LIST.push(tmp_line); \ } \ argc--; \ i++; \ } bool Options::parse(int argc, char* argv[]) { Lock lock(mutex); progname_ = argv[0]; std::queue host_port_queue; argc--; for(int i=1; argc > 0; ++i) { std::string str(argv[i]); argc--; if(str == "-h" || str == "--help") { return false; } PARSE_BOOL_PARAM("-t","--chroot", chroot_) PARSE_BOOL_PARAM("-n","--nat", nat_) PARSE_BOOL_PARAM("-o","--no-nat-once", no_nat_once_) PARSE_SCALAR_PARAM("-u","--user", username_) PARSE_SCALAR_PARAM("-c","--chroot-dir", chroot_dir_) PARSE_INVERSE_BOOL_PARAM("-d","--nodaemonize", daemonize_) PARSE_SCALAR_PARAM("-P","--write-pid", pid_file_) PARSE_SCALAR_PARAM("-i","--interface", local_addr_) PARSE_STRING_PARAM("-s","--control", control_interface_) PARSE_SCALAR_PARAM2("-p","--port-range", rtp_start_port_, rtp_end_port_) PARSE_CSLIST_PARAM("-M","--sync-hosts", host_port_queue) PARSE_SCALAR_PARAM("-S","--sync-port", local_sync_port_) PARSE_SCALAR_PARAM("-I","--sync-interface", local_sync_addr_) else { return false; } } while(!host_port_queue.empty()) { std::stringstream tmp_stream(host_port_queue.front()); OptionConnectTo oct; getline(tmp_stream,oct.host,':'); if(!tmp_stream.good()) { return false; } tmp_stream >> oct.port; host_port_queue.pop(); connect_to_.push_back(oct); } return sanityCheck(); } bool Options::sanityCheck() { if(control_interface_.port_ == "") { control_interface_.port_ = "22222"; } return true; } void Options::printUsage() { std::cout << "USAGE: anyrtpproxy" << std::endl; std::cout << " [-h|--help] prints this..." << std::endl; std::cout << " [-t|--chroot] chroot and drop priviledges" << std::endl; std::cout << " [-u|--username] in case of chroot run as this user" << std::endl; std::cout << " [-c|--chroot-dir] directory to make a chroot to" << std::endl; std::cout << " [-d|--nodaemonize] don't run in background" << std::endl; std::cout << " [-P|--write-pid] write pid to this file" << std::endl; std::cout << " [-i|--interface] local ip address to listen to for RTP packets" << std::endl; std::cout << " [-s|--control] [:] the address/port to listen on for control commands" << std::endl; std::cout << " [-p|--port-range] port range used to relay rtp connections" << std::endl; std::cout << " [-n|--nat] enable permantent automatic nat detection(use only with anytun)" << std::endl; std::cout << " [-o|--no-nat-once] disable automatic nat detection for new connections" << std::endl; std::cout << " [-I|--sync-interface] local unicast(sync) ip address to bind to" << std::endl; std::cout << " [-S|--sync-port] local unicast(sync) port to bind to" << std::endl; std::cout << " [-M|--sync-hosts] :[,:[...]]"<< std::endl; std::cout << " List of Remote Sync Hosts/Ports"<< std::endl; } void Options::printOptions() { Lock lock(mutex); std::cout << "Options:" << std::endl; std::cout << "chroot='" << chroot_ << "'" << std::endl; std::cout << "username='" << username_ << "'" << std::endl; std::cout << "chroot-dir='" << chroot_dir_ << "'" << std::endl; std::cout << "daemonize='" << daemonize_ << "'" << std::endl; std::cout << "pid_file='" << pid_file_ << "'" << std::endl; std::cout << "control-interface='" << control_interface_.toString() << "'" << std::endl; std::cout << "local_addr='" << local_addr_ << "'" << std::endl; std::cout << "rtp_start_port=" << rtp_start_port_ << std::endl; std::cout << "rtp_end_port=" << rtp_end_port_ << std::endl; std::cout << "local_sync_addr='" << local_sync_addr_ << "'" << std::endl; std::cout << "local_sync_port='" << local_sync_port_ << "'" << std::endl; } std::string Options::getProgname() { Lock lock(mutex); return progname_; } bool Options::getChroot() { Lock lock(mutex); return chroot_; } bool Options::getNat() { Lock lock(mutex); return nat_; } bool Options::getNoNatOnce() { Lock lock(mutex); return no_nat_once_; } std::string Options::getUsername() { Lock lock(mutex); return username_; } std::string Options::getChrootDir() { Lock lock(mutex); return chroot_dir_; } bool Options::getDaemonize() { Lock lock(mutex); return daemonize_; } std::string Options::getPidFile() { Lock lock(mutex); return pid_file_; } Host Options::getControlInterface() { Lock lock(mutex); return control_interface_; } std::string Options::getLocalAddr() { Lock lock(mutex); return local_addr_; } Options& Options::setLocalAddr(std::string l) { Lock lock(mutex); local_addr_ = l; return *this; } std::string Options::getLocalSyncAddr() { Lock lock(mutex); return local_sync_addr_; } Options& Options::setLocalSyncAddr(std::string l) { Lock lock(mutex); local_sync_addr_ = l; return *this; } std::string Options::getLocalSyncPort() { Lock lock(mutex); return local_sync_port_; } Options& Options::setLocalSyncPort(std::string l) { Lock lock(mutex); local_sync_port_ = l; return *this; } uint16_t Options::getRtpStartPort() { return rtp_start_port_; } Options& Options::setRtpStartPort(uint16_t l) { rtp_start_port_ = l; return *this; } uint16_t Options::getRtpEndPort() { return rtp_end_port_; } Options& Options::setRtpEndPort(uint16_t l) { rtp_end_port_ = l; return *this; } ConnectToList Options::getConnectTo() { Lock lock(mutex); return connect_to_; } anytun-0.3.8/src/anyrtpproxy/rtpSession.cpp0000664000175000017500000001001613604635433021074 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "rtpSession.h" #include "callIdQueue.h" RtpSession::RtpSession(const std::string& call_id) : in_sync_(false), call_id_(call_id) , dead_(false), complete_(false), seen1_(false), seen2_(false) { } void RtpSession::reinit() { gCallIdQueue.push(call_id_); } bool RtpSession::isDead() { Lock lock(mutex_); return (dead_ && in_sync_); } bool RtpSession::isDead(bool d) { Lock Lock(mutex_); return dead_ = d; } bool RtpSession::isComplete() { Lock lock(mutex_); return complete_; } bool RtpSession::isComplete(bool c) { Lock lock(mutex_); return complete_ = c; } bool RtpSession::getSeen1() { Lock lock(mutex_); return seen1_; } RtpSession& RtpSession::setSeen1() { Lock lock(mutex_); //in_sync_ = false; seen1_ = true; return *this; } bool RtpSession::getSeen2() { Lock lock(mutex_); return seen2_; } RtpSession& RtpSession::setSeen2() { Lock lock(mutex_); //in_sync_ = false; seen2_ = true; return *this; } RtpSession::proto::endpoint RtpSession::getLocalEnd1() { Lock lock(mutex_); return local_end1_; } RtpSession& RtpSession::setLocalEnd1(RtpSession::proto::endpoint e) { Lock lock(mutex_); in_sync_ = false; local_end1_ = e; return *this; } RtpSession::proto::endpoint RtpSession::getLocalEnd2() { Lock lock(mutex_); return local_end2_; } RtpSession& RtpSession::setLocalEnd2(RtpSession::proto::endpoint e) { Lock lock(mutex_); in_sync_ = false; local_end2_ = e; return *this; } RtpSession::proto::endpoint RtpSession::getRemoteEnd1() { Lock lock(mutex_); return remote_end1_; } RtpSession& RtpSession::setRemoteEnd1(RtpSession::proto::endpoint e) { Lock lock(mutex_); in_sync_ = false; remote_end1_ = e; return *this; } RtpSession::proto::endpoint RtpSession::getRemoteEnd2() { Lock lock(mutex_); return remote_end2_; } RtpSession& RtpSession::setRemoteEnd2(RtpSession::proto::endpoint e) { Lock lock(mutex_); in_sync_ = false; remote_end2_ = e; return *this; } anytun-0.3.8/src/anyrtpproxy/callIdQueue.cpp0000664000175000017500000000537213604635433021131 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "callIdQueue.h" CallIdQueue* CallIdQueue::inst = NULL; Mutex CallIdQueue::instMutex; CallIdQueue& gCallIdQueue = CallIdQueue::instance(); CallIdQueue& CallIdQueue::instance() { Lock lock(instMutex); static instanceCleaner c; if(!inst) { inst = new CallIdQueue(); } return *inst; } CallIdQueue::CallIdQueue() { } CallIdQueue::~CallIdQueue() { while(!callids_.empty()) { pop(); } } std::string& CallIdQueue::front() { sem_.down(); Lock lock(mutex_); return callids_.front(); } void CallIdQueue::push(std::string c) { Lock lock(mutex_); callids_.push(c); sem_.up(); } void CallIdQueue::pop() { Lock lock(mutex_); callids_.pop(); } anytun-0.3.8/src/anyrtpproxy/rtpSession.h0000664000175000017500000001115313604635433020544 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _RTPSESSION_H_ #define _RTPSESSION_H_ #include #include "../threadUtils.hpp" #include #include class RtpSession { public: typedef boost::asio::ip::udp proto; RtpSession(const std::string& call_id); bool isDead(); bool isDead(bool d); bool isComplete(); bool isComplete(bool c); proto::endpoint getLocalEnd1(); RtpSession& setLocalEnd1(proto::endpoint e); proto::endpoint getLocalEnd2(); RtpSession& setLocalEnd2(proto::endpoint e); proto::endpoint getRemoteEnd1(); RtpSession& setRemoteEnd1(proto::endpoint e); proto::endpoint getRemoteEnd2(); RtpSession& setRemoteEnd2(proto::endpoint e); RtpSession& setSeen1(); bool getSeen1(); RtpSession& setSeen2(); bool getSeen2(); private: RtpSession(const RtpSession& src); void reinit(); //TODO: check if this is ok friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(mutex_); // address of local_end1 and local_end2 are always equal std::string local_addr(local_end1_.address().to_string()); uint16_t local_port1 = local_end1_.port(); uint16_t local_port2 = local_end2_.port(); std::string remote_addr1(remote_end1_.address().to_string()); uint16_t remote_port1 = remote_end1_.port(); std::string remote_addr2(remote_end2_.address().to_string()); uint16_t remote_port2 = remote_end2_.port(); ar& dead_; ar& complete_; ar& local_addr; ar& local_port1; ar& local_port2; ar& remote_addr1; ar& remote_port1; ar& remote_addr2; ar& remote_port2; ar& seen1_; ar& seen2_; proto::endpoint local_end1(boost::asio::ip::address::from_string(local_addr), local_port1); local_end1_ = local_end1; proto::endpoint local_end2(boost::asio::ip::address::from_string(local_addr), local_port2); local_end2_ = local_end2; proto::endpoint remote_end1(boost::asio::ip::address::from_string(remote_addr1), remote_port1); remote_end1_ = remote_end1; proto::endpoint remote_end2(boost::asio::ip::address::from_string(remote_addr2), remote_port2); remote_end2_ = remote_end2; if(complete_ && !dead_) { reinit(); } in_sync_ = true; } bool in_sync_; ::Mutex mutex_; const std::string& call_id_; bool dead_; bool complete_; proto::endpoint local_end1_, local_end2_; proto::endpoint remote_end1_, remote_end2_; bool seen1_,seen2_; //has at least 1 packet been recieved? }; #endif anytun-0.3.8/src/anyrtpproxy/rtpSessionTable.cpp0000664000175000017500000000766613604635433022065 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "../threadUtils.hpp" #include "../datatypes.h" #include "rtpSessionTable.h" RtpSessionTable* RtpSessionTable::inst = NULL; Mutex RtpSessionTable::instMutex; RtpSessionTable& gRtpSessionTable = RtpSessionTable::instance(); RtpSessionTable& RtpSessionTable::instance() { Lock lock(instMutex); static instanceCleaner c; if(!inst) { inst = new RtpSessionTable(); } return *inst; } RtpSessionTable::RtpSessionTable() { } RtpSessionTable::~RtpSessionTable() { } void RtpSessionTable::delSession(const std::string& call_id) { Lock lock(mutex_); RtpSessionMap::iterator it = map_.find(call_id); if(it!=map_.end()) { delete it->second; } map_.erase(it); } RtpSession& RtpSessionTable::getOrNewSession(const std::string& call_id, bool& is_new) { Lock lock(mutex_); return getOrNewSessionUnlocked(call_id, is_new); } RtpSession& RtpSessionTable::getOrNewSessionUnlocked(const std::string& call_id, bool& is_new) { is_new = false; RtpSessionMap::iterator it = map_.find(call_id); if(it!=map_.end()) { return *(it->second); } is_new = true; std::pair ret = map_.insert(RtpSessionMap::value_type(call_id, NULL)); ret.first->second = new RtpSession(ret.first->first); return *(ret.first->second); } RtpSession& RtpSessionTable::getSession(const std::string& call_id) { RtpSessionMap::iterator it = map_.find(call_id); if(it!=map_.end()) { return *(it->second); } throw std::runtime_error("session not found"); } RtpSessionMap::iterator RtpSessionTable::getBeginUnlocked() { return map_.begin(); } RtpSessionMap::iterator RtpSessionTable::getEndUnlocked() { return map_.end(); } void RtpSessionTable::clear() { Lock lock(mutex_); map_.clear(); } bool RtpSessionTable::empty() { Lock lock(mutex_); return map_.empty(); } Mutex& RtpSessionTable::getMutex() { return mutex_; } anytun-0.3.8/src/anyrtpproxy/rtpSessionTable.h0000664000175000017500000000627213604635433021522 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef _RTPSESSIONTABLE_H #define _RTPSESSIONTABLE_H #include #include "../threadUtils.hpp" #include "../datatypes.h" #include "rtpSession.h" typedef std::map RtpSessionMap; class RtpSessionTable { public: static RtpSessionTable& instance(); RtpSessionTable(); ~RtpSessionTable(); void delSession(const std::string& call_id); bool empty(); void clear(); ::Mutex& getMutex(); RtpSessionMap::iterator getBeginUnlocked(); RtpSessionMap::iterator getEndUnlocked(); RtpSession& getOrNewSession(const std::string& call_id, bool& isnew); RtpSession& getOrNewSessionUnlocked(const std::string& call_id, bool& isnew); RtpSession& getSession(const std::string& call_id); private: static ::Mutex instMutex; static RtpSessionTable* inst; class instanceCleaner { public: ~instanceCleaner() { if(RtpSessionTable::inst != 0) { delete RtpSessionTable::inst; } } }; RtpSessionTable(const RtpSessionTable& s); void operator=(const RtpSessionTable& s); RtpSessionMap map_; ::Mutex mutex_; }; extern RtpSessionTable& gRtpSessionTable; #endif anytun-0.3.8/src/routingTable.h0000664000175000017500000000642313604635433016417 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_routingTable_h_INCLUDED #define ANYTUN_routingTable_h_INCLUDED #include #include #include "threadUtils.hpp" #include "datatypes.h" #include "networkAddress.h" #include "networkPrefix.h" #include "routingTreeNode.h" #include "boost/array.hpp" typedef std::map RoutingMap; class RoutingTable { public: static RoutingTable& instance(); RoutingTable(); ~RoutingTable(); void addRoute(const NetworkPrefix& ,uint16_t); void updateRouteTreeUnlocked(const NetworkPrefix& pref); void delRoute(const NetworkPrefix&); uint16_t getRoute(const NetworkAddress&); bool empty(network_address_type_t type); void clear(network_address_type_t type); Mutex& getMutex(); uint16_t* getOrNewRoutingTEUnlocked(const NetworkPrefix& addr); uint16_t getCountUnlocked(network_address_type_t type); RoutingMap::iterator getBeginUnlocked(network_address_type_t type); RoutingMap::iterator getEndUnlocked(network_address_type_t type); private: RoutingTable(const RoutingTable& s); void operator=(const RoutingTable& s); boost::array routes_; boost::array root_; Mutex mutex_; }; extern RoutingTable& gRoutingTable; #endif anytun-0.3.8/src/posix/0000775000175000017500000000000013604635433014744 5ustar equinoxequinoxanytun-0.3.8/src/posix/sysExec.hpp0000664000175000017500000001364513604635433017111 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #pragma once #ifndef ANYTUN_sysexec_hpp_INCLUDED #define ANYTUN_sysexec_hpp_INCLUDED #include #include #include #include #include #include #include #include #include SysExec::~SysExec() { if(!closed_) { close(pipefd_); } } template char** dupSysStringArray(T const& array) { char** new_array; new_array = static_cast(malloc((array.size() + 1)*sizeof(char*))); if(!new_array) { return NULL; } unsigned int i = 0; for(typename T::const_iterator it = array.begin(); it != array.end(); ++it) { new_array[i] = strdup(it->c_str()); if(!new_array) { while(i--) { free(new_array[i]); } free(new_array); return NULL; } ++i; } new_array[array.size()] = NULL; return new_array; } void freeSysStringArray(char** array) { if(!array) { return; } for(int i=0; array[i] ; ++i) { free(array[i]); } free(array); } void SysExec::doExec(StringVector args, StringList env) { int pipefd[2]; if(pipe(pipefd) == -1) { cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' pipe() error: " << AnytunErrno(errno); return; } pid_ = fork(); if(pid_ == -1) { cLog.msg(Log::PRIO_ERROR) << "executing script '" << script_ << "' fork() error: " << AnytunErrno(errno); return; } if(pid_) { close(pipefd[1]); pipefd_=pipefd[0]; // parent exits here, call waitForScript to cleanup up zombie return; } // child code, exec the script int fd; for(fd=getdtablesize(); fd>=0; --fd) // close all file descriptors if(fd != pipefd[1]) { close(fd); } fd = open("/dev/null",O_RDWR); // stdin if(fd == -1) { cLog.msg(Log::PRIO_WARNING) << "can't open stdin"; } else { if(dup(fd) == -1) { // stdout cLog.msg(Log::PRIO_WARNING) << "can't open stdout"; } if(dup(fd) == -1) { // stderr cLog.msg(Log::PRIO_WARNING) << "can't open stderr"; } } args.insert(args.begin(), script_); char** argv = dupSysStringArray(args); char** evp = dupSysStringArray(env); execve(script_.c_str(), argv, evp); // if execve returns, an error occurred, but logging doesn't work // because we closed all file descriptors, so just write errno to // pipe and call exit freeSysStringArray(argv); freeSysStringArray(evp); int err = errno; int ret = write(pipefd[1], (void*)(&err), sizeof(err)); if(ret != sizeof(errno)) { exit(-2); } exit(-1); } int SysExec::waitForScript() { int status = 0; waitpid(pid_, &status, 0); fd_set rfds; FD_ZERO(&rfds); FD_SET(pipefd_, &rfds); struct timeval tv = { 0 , 0 }; if(select(pipefd_+1, &rfds, NULL, NULL, &tv) == 1) { int err = 0; if(read(pipefd_, (void*)(&err), sizeof(err)) >= static_cast(sizeof(err))) { cLog.msg(Log::PRIO_ERROR) << "script '" << script_ << "' exec() error: " << AnytunErrno(err); close(pipefd_); return_code_ = -1; return return_code_; } } close(pipefd_); closed_ = true; return_code_ = status; return return_code_; } void SysExec::waitAndDestroy(SysExec*& s) { if(!s) { return; } s->waitForScript(); if(WIFEXITED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' returned " << WEXITSTATUS(s->return_code_); } else if(WIFSIGNALED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' terminated after signal " << WTERMSIG(s->return_code_); } else if(WIFSTOPPED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' stopped after signal " << WSTOPSIG(s->return_code_); } else if(WIFCONTINUED(s->return_code_)) { cLog.msg(Log::PRIO_NOTICE) << "script '" << s->script_ << "' continued after SIGCONT"; } delete(s); s = NULL; } #endif // ANYTUN_sysexec_hpp_INCLUDED anytun-0.3.8/src/posix/posixDaemon.h0000664000175000017500000000474713604635433017417 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_posixDaemon_h_INCLUDED #define ANYTUN_posixDaemon_h_INCLUDED #include class DaemonService { public: DaemonService(); void initPrivs(std::string const& username, std::string const& groupname); void dropPrivs(); void chroot(std::string const& dir); void daemonize(); bool isDaemonized(); private: struct passwd* pw_; struct group* gr_; bool daemonized_; }; #endif anytun-0.3.8/src/posix/signalHandler.hpp0000664000175000017500000001164713604635433020241 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_signalHandler_hpp_INCLUDED #define ANYTUN_signalHandler_hpp_INCLUDED #include #include #include int SigIntHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Int caught, exiting"; return 1; } int SigQuitHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Quit caught, exiting"; return 1; } int SigHupHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Hup caught"; return 0; } int SigTermHandler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Term caught, exiting"; return 1; } int SigUsr1Handler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Usr1 caught"; return 0; } int SigUsr2Handler(int /*sig*/, const std::string& /*msg*/) { cLog.msg(Log::PRIO_NOTICE) << "SIG-Usr2 caught"; return 0; } /// TODO: this outstandignly ugly please and i really can't stress the please fix it asap!!!!!!! extern std::ofstream pidFile; void handleSignal() { if(pidFile.is_open()) { pid_t pid = getpid(); pidFile << pid; pidFile.close(); } struct timespec timeout; sigset_t signal_set; int sigNum; for(;;) { sigemptyset(&signal_set); sigaddset(&signal_set, SIGINT); sigaddset(&signal_set, SIGQUIT); sigaddset(&signal_set, SIGHUP); sigaddset(&signal_set, SIGTERM); sigaddset(&signal_set, SIGUSR1); sigaddset(&signal_set, SIGUSR2); timeout.tv_sec = 1; timeout.tv_nsec = 0; sigNum = sigtimedwait(&signal_set, NULL, &timeout); if(sigNum == -1) { if(errno != EINTR && errno != EAGAIN) { cLog.msg(Log::PRIO_ERROR) << "sigwait failed with error: \"" << AnytunErrno(errno) << "\" SignalHandling will be disabled"; break; } } else { gSignalController.inject(sigNum); } } } void registerSignalHandler(SignalController& ctrl, DaemonService& /*service*/) { sigset_t signal_set; sigemptyset(&signal_set); sigaddset(&signal_set, SIGINT); sigaddset(&signal_set, SIGQUIT); sigaddset(&signal_set, SIGHUP); sigaddset(&signal_set, SIGTERM); sigaddset(&signal_set, SIGUSR1); sigaddset(&signal_set, SIGUSR2); #if defined(BOOST_HAS_PTHREADS) pthread_sigmask(SIG_BLOCK, &signal_set, NULL); #else #error The signalhandler works only with pthreads #endif boost::thread(boost::bind(handleSignal)); ctrl.handler[SIGINT] = boost::bind(SigIntHandler, _1, _2); ctrl.handler[SIGQUIT] = boost::bind(SigQuitHandler, _1, _2); ctrl.handler[SIGHUP] = boost::bind(SigHupHandler, _1, _2); ctrl.handler[SIGTERM] = boost::bind(SigTermHandler, _1, _2); ctrl.handler[SIGUSR1] = boost::bind(SigUsr1Handler, _1, _2); ctrl.handler[SIGUSR2] = boost::bind(SigUsr2Handler, _1, _2); cLog.msg(Log::PRIO_DEBUG) << "signal handlers are now registered"; } #endif anytun-0.3.8/src/posix/posixDaemon.cpp0000664000175000017500000001343413604635433017743 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include #include #include "daemonService.h" #include "log.h" #include "options.h" #include "anytunError.h" DaemonService::DaemonService() : pw_(NULL), gr_(NULL), daemonized_(false) { } void DaemonService::initPrivs(std::string const& username, std::string const& groupname) { if(username == "") { return; } pw_ = getpwnam(username.c_str()); if(!pw_) { AnytunError::throwErr() << "unknown user " << username; } if(groupname != "") { gr_ = getgrnam(groupname.c_str()); } else { gr_ = getgrgid(pw_->pw_gid); } if(!gr_) { AnytunError::throwErr() << "unknown group " << groupname; } } void DaemonService::dropPrivs() { if(!pw_ || !gr_) { return; } if(setgid(gr_->gr_gid)) { AnytunError::throwErr() << "setgid('" << gr_->gr_name << "') failed: " << AnytunErrno(errno); } gid_t gr_list[1]; gr_list[0] = gr_->gr_gid; if(setgroups(1, gr_list)) { AnytunError::throwErr() << "setgroups(['" << gr_->gr_name << "']) failed: " << AnytunErrno(errno); } if(setuid(pw_->pw_uid)) { AnytunError::throwErr() << "setuid('" << pw_->pw_name << "') failed: " << AnytunErrno(errno); } cLog.msg(Log::PRIO_NOTICE) << "dropped privileges to " << pw_->pw_name << ":" << gr_->gr_name; } void DaemonService::chroot(std::string const& chrootdir) { if(getuid() != 0) { AnytunError::throwErr() << "this program has to be run as root in order to run in a chroot"; } if(::chroot(chrootdir.c_str())) { AnytunError::throwErr() << "can't chroot to " << chrootdir; } cLog.msg(Log::PRIO_NOTICE) << "we are in chroot jail (" << chrootdir << ") now" << std::endl; if(chdir("/")) { AnytunError::throwErr() << "can't change to /"; } } /// TODO: this outstandignly ugly please and i really can't stress the please fix it asap!!!!!!! std::ofstream pidFile; // FIXXXME no global variable void DaemonService::daemonize() { // std::ofstream pidFile; if(gOpt.getPidFile() != "") { pidFile.open(gOpt.getPidFile().c_str()); if(!pidFile.is_open()) { AnytunError::throwErr() << "can't open pid file (" << gOpt.getPidFile() << "): " << AnytunErrno(errno); } } pid_t pid; pid = fork(); if(pid < 0) { AnytunError::throwErr() << "daemonizing failed at fork(): " << AnytunErrno(errno) << ", exitting"; } if(pid) { exit(0); } umask(0); if(setsid() < 0) { AnytunError::throwErr() << "daemonizing failed at setsid(): " << AnytunErrno(errno) << ", exitting"; } pid = fork(); if(pid < 0) { AnytunError::throwErr() << "daemonizing failed at fork(): " << AnytunErrno(errno) << ", exitting"; } if(pid) { exit(0); } if((chdir("/")) < 0) { AnytunError::throwErr() << "daemonizing failed at chdir(): " << AnytunErrno(errno) << ", exitting"; } // std::cout << "running in background now..." << std::endl; int fd; // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors for(fd=0; fd<=2; fd++) { // close all file descriptors close(fd); } fd = open("/dev/null",O_RDWR); // stdin if(fd == -1) { cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stdin"; } else { if(dup(fd) == -1) { // stdout cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stdout"; } if(dup(fd) == -1) { // stderr cLog.msg(Log::PRIO_WARNING) << "can't open /dev/null as stderr"; } } // FIXXXXME: write this pid to file (currently pid from posix/signhandler.hpp:77 is used) // // if(pidFile.is_open()) { // pid_t pid = getpid(); // pidFile << pid; // pidFile.close(); // } daemonized_ = true; } bool DaemonService::isDaemonized() { return daemonized_; } anytun-0.3.8/src/syncRouteCommand.h0000664000175000017500000000571313604635433017253 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_syncRouteCommands_h_INCLUDED #define ANYTUN_syncRouteCommands_h_INCLUDED #include #include #include "threadUtils.hpp" #include "networkPrefix.h" #include "routingTable.h" class SyncRouteCommand { public: SyncRouteCommand(const NetworkPrefix&); SyncRouteCommand(); NetworkPrefix getPrefix() const; private: SyncRouteCommand(const SyncRouteCommand&); uint16_t count_; NetworkPrefix addr_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { Lock lock(gRoutingTable.getMutex()); ar& addr_; // uint16_t & mux (gRoutingTable.getOrNewRoutingTEUnlocked(addr_)); // ar & mux; ar & (*(gRoutingTable.getOrNewRoutingTEUnlocked(addr_))); gRoutingTable.updateRouteTreeUnlocked(addr_); }; }; #endif anytun-0.3.8/src/sysExec.cpp0000664000175000017500000000575613604635433015746 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include "datatypes.h" #include "sysExec.h" #include "log.h" #include "anytunError.h" //use system specific sys exec #if !defined(_MSC_VER) && !defined(MINGW) #include "sysExec.hpp" #else #include "win32/sysExec.hpp" #endif SysExec::SysExec(std::string const& script) : script_(script),closed_(false),return_code_(0) { doExec(StringVector(), StringList()); } SysExec::SysExec(std::string const& script, StringVector args) : script_(script),closed_(false),return_code_(0) { doExec(args, StringList()); } SysExec::SysExec(std::string const& script, StringList env) : script_(script),closed_(false),return_code_(0) { doExec(StringVector(), env); } SysExec::SysExec(std::string const& script, StringVector args, StringList env) : script_(script),closed_(false),return_code_(0) { doExec(args, env); } int SysExec::getReturnCode() const { return return_code_; } anytun-0.3.8/src/anytunError.cpp0000664000175000017500000000520413604635433016637 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "anytunError.h" #include #include #ifndef NO_CRYPT #if defined(USE_GCRYPT) std::ostream& operator<<(std::ostream& stream, AnytunGpgError const& value) { char buf[STERROR_TEXT_MAX]; buf[0] = 0; gpg_strerror_r(value.err_, buf, STERROR_TEXT_MAX); return stream << buf; } #endif #endif std::ostream& operator<<(std::ostream& stream, AnytunErrno const& value) { boost::system::system_error err(boost::system::error_code(value.err_, boost::system::get_system_category())); return stream << err.what(); } anytun-0.3.8/src/syncClient.cpp0000664000175000017500000001173313604635433016426 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include "connectionList.h" #include "syncCommand.h" #include #include #include "log.h" #include "syncClient.h" #include "syncTcpConnection.h" #include "buffer.h" #include SyncClient::SyncClient(std::string hostname,std::string port) :hostname_(hostname),port_(port) { } void SyncClient::run() { bool connected(false); for(;;) { try { boost::asio::io_service io_service; SyncTcpConnection::proto::resolver resolver(io_service); SyncTcpConnection::proto::resolver::query query(hostname_, port_); SyncTcpConnection::proto::resolver::iterator endpoint_iterator = resolver.resolve(query); SyncTcpConnection::proto::resolver::iterator end; SyncTcpConnection::proto::socket socket(io_service); boost::system::error_code error = boost::asio::error::host_not_found; while(error && endpoint_iterator != end) { socket.close(); socket.connect(*endpoint_iterator++, error); } if(error) { throw boost::system::system_error(error); } if(!connected) { cLog.msg(Log::PRIO_NOTICE) << "sync: connected to " << hostname_ <<":"<< port_; } connected=true; readAndProcess(socket); //endless loop } catch(std::exception& e) { if(connected) { cLog.msg(Log::PRIO_NOTICE) << "sync: connection to " << hostname_ <<":"<< port_<< " lost ("<< e.what() << ") retrying every 10sec"; } connected=false; boost::this_thread::sleep(boost::posix_time::milliseconds(10000)); } } } void SyncClient::readAndProcess(SyncTcpConnection::proto::socket& socket) { ConnectionList& cl_(gConnectionList); size_t message_lenght ; for(;;) { std::stringstream message_lenght_stream; readExactly(socket,5,message_lenght_stream); message_lenght_stream >> message_lenght; std::stringstream void_stream; readExactly(socket,1,void_stream); //skip space std::stringstream sync_command_stream; readExactly(socket,message_lenght, sync_command_stream); //cLog.msg(Log::PRIO_NOTICE) << "recieved sync inforamtaion "<> scom; } } void SyncClient::readExactly(SyncTcpConnection::proto::socket& socket,size_t toread, std::iostream& result) { size_t hasread = 0; while(toread > hasread) { //TODO read bigger buffers boost::array buf; boost::system::error_code error; size_t len = socket.read_some(boost::asio::buffer(buf), error); if(error == boost::asio::error::eof) { break; // Connection closed cleanly by peer. } else if(error) { throw boost::system::system_error(error); // Some other error. } //for (size_t pos=0; pos * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_threadUtils_hpp_INCLUDED #define ANYTUN_threadUtils_hpp_INCLUDED #include #include #include #include #include "datatypes.h" typedef boost::mutex::scoped_lock Lock; typedef boost::mutex Mutex; typedef boost::shared_mutex SharedMutex; typedef boost::shared_lock ReadersLock; typedef boost::unique_lock WritersLock; class Semaphore { public: Semaphore(unsigned int initVal=0) :count_(initVal) {}; void up() { boost::mutex::scoped_lock lock(mutex_); count_++; lock.unlock(); cond_.notify_one(); } void down() { boost::mutex::scoped_lock lock(mutex_); while(count_ <= 0) { cond_.wait(lock); } count_--; } private: boost::mutex mutex_; boost::condition cond_; int16_t count_; }; #endif anytun-0.3.8/src/keyDerivationFactory.cpp0000664000175000017500000000533313604635433020457 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include "keyDerivationFactory.h" #include "keyDerivation.h" KeyDerivation* KeyDerivationFactory::create(std::string const& type) { if(type == "null") { return new NullKeyDerivation(); } #ifndef NO_CRYPT else if(type == "aes-ctr") { return new AesIcmKeyDerivation(); } else if(type == "aes-ctr-128") { return new AesIcmKeyDerivation(128); } else if(type == "aes-ctr-192") { return new AesIcmKeyDerivation(192); } else if(type == "aes-ctr-256") { return new AesIcmKeyDerivation(256); } #endif else { throw std::invalid_argument("key derivation prf not available"); } } anytun-0.3.8/src/syncClient.h0000664000175000017500000000503213604635433016066 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_syncClient_h_INCLUDED #define ANYTUN_syncClient_h_INCLUDED #include #include "syncTcpConnection.h" class SyncClient { public: SyncClient(std::string hostname,std::string port); void run(); private: void readAndProcess(SyncTcpConnection::proto::socket& socket); void readExactly(SyncTcpConnection::proto::socket& socket,size_t toread, std::iostream&); std::string hostname_; std::string port_; }; #endif // _SYNCSOCKET_H anytun-0.3.8/src/datatypes.h0000664000175000017500000000623513604635433015757 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_datatypes_h_INCLUDED #define ANYTUN_datatypes_h_INCLUDED #include #include #include #ifndef BOOST_NO_NOEXCEPT #define NOEXCEPT(x) noexcept(x) #else #define NOEXCEPT(x) #endif // should not be necessary on GCC, #ifdef + #include should do the job; still required on MS VC++9, though. using boost::int8_t; using boost::uint8_t; using boost::int16_t; using boost::uint16_t; using boost::int32_t; using boost::uint32_t; using boost::int64_t; using boost::uint64_t; typedef uint32_t window_size_t; typedef uint32_t seq_nr_t; #define SEQ_NR_MAX 0xFFFFFFFF typedef uint16_t sender_id_t; typedef uint16_t payload_type_t; typedef uint16_t mux_t; typedef uint32_t satp_prf_label_t; typedef enum { ANY, IPV4_ONLY, IPV6_ONLY } ResolvAddrType; #ifndef _MSC_VER #define ATTR_PACKED __attribute__((__packed__)) #else #define ATTR_PACKED #endif #if !defined(_MSC_VER) && !defined(MINGW) typedef int system_error_t; #else #include typedef DWORD system_error_t; #endif #define MAX_PACKET_LENGTH 1600 #endif anytun-0.3.8/src/bsd/0000775000175000017500000000000013604635433014352 5ustar equinoxequinoxanytun-0.3.8/src/bsd/tunDevice.cpp0000664000175000017500000001736713604635433017022 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "tunDevice.h" #include "threadUtils.hpp" #include "log.h" #include "anytunError.h" #include "sysExec.h" #define DEVICE_FILE_MAX 255 TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, uint16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400),sys_exec_(NULL) { std::string device_file = "/dev/"; bool dynamic = true; if(dev_name != "") { device_file.append(dev_name); dynamic = false; } #if defined(__GNUC__) && defined(__OpenBSD__) else if(conf_.type_ == TYPE_TUN || conf_.type_ == TYPE_TAP) { device_file.append("tun"); actual_name_ = "tun"; } #else else if(conf_.type_ == TYPE_TUN) { device_file.append("tun"); actual_name_ = "tun"; } else if(conf_.type_ == TYPE_TAP) { device_file.append("tap"); actual_name_ = "tap"; } #endif else { AnytunError::throwErr() << "unable to recognize type of device (tun or tap)"; } uint32_t dev_id=0; if(dynamic) { for(; dev_id <= DEVICE_FILE_MAX; ++dev_id) { std::ostringstream ds; ds << device_file; ds << dev_id; fd_ = ::open(ds.str().c_str(), O_RDWR); if(fd_ >= 0) { break; } } } else { fd_ = ::open(device_file.c_str(), O_RDWR); } if(fd_ < 0) { if(dynamic) { AnytunError::throwErr() << "can't open device file dynamically: no unused node left"; } else { AnytunError::throwErr() << "can't open device file (" << device_file << "): " << AnytunErrno(errno); } } if(dynamic) { std::stringstream s; s << actual_name_; s << dev_id; actual_name_ = s.str(); } else { actual_name_ = dev_name; } actual_node_ = device_file; init_post(); if(ifcfg_addr != "") { do_ifconfig(); } } TunDevice::~TunDevice() { if(fd_ > 0) { ::close(fd_); } } #if defined(__GNUC__) && defined(__OpenBSD__) void TunDevice::init_post() { with_pi_ = true; if(conf_.type_ == TYPE_TAP) { with_pi_ = false; } struct tuninfo ti; if(ioctl(fd_, TUNGIFINFO, &ti) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno); } ti.flags |= IFF_MULTICAST; if(conf_.type_ == TYPE_TUN) { ti.flags &= ~IFF_POINTOPOINT; } if(ioctl(fd_, TUNSIFINFO, &ti) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno); } } #elif defined(__GNUC__) && (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) void TunDevice::init_post() { with_pi_ = true; if(conf_.type_ == TYPE_TAP) { with_pi_ = false; } if(conf_.type_ == TYPE_TUN) { int arg = 0; if(ioctl(fd_, TUNSLMODE, &arg) < 0) { ::close(fd_); AnytunError::throwErr() << "can't disable link-layer mode for interface: " << AnytunErrno(errno); } arg = 1; if(ioctl(fd_, TUNSIFHEAD, &arg) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multi-af modefor interface: " << AnytunErrno(errno); } arg = IFF_BROADCAST; arg |= IFF_MULTICAST; if(ioctl(fd_, TUNSIFMODE, &arg) < 0) { ::close(fd_); AnytunError::throwErr() << "can't enable multicast for interface: " << AnytunErrno(errno); } } } #elif defined(__GNUC__) && defined(__NetBSD__) void TunDevice::init_post() { with_pi_ = false; int arg = IFF_POINTOPOINT|IFF_MULTICAST; ioctl(fd_, TUNSIFMODE, &arg); arg = 0; ioctl(fd_, TUNSLMODE, &arg); } #else #error This Device works just for OpenBSD, FreeBSD or NetBSD #endif int TunDevice::fix_return(int ret, size_t pi_length) const { if(ret < 0) { return ret; } return (static_cast(ret) > pi_length ? (ret - pi_length) : 0); } int TunDevice::read(uint8_t* buf, uint32_t len) { if(fd_ < 0) { return -1; } if(with_pi_) { struct iovec iov[2]; uint32_t type; iov[0].iov_base = &type; iov[0].iov_len = sizeof(type); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::readv(fd_, iov, 2), sizeof(type))); } else { return(::read(fd_, buf, len)); } } int TunDevice::write(uint8_t* buf, uint32_t len) { if(fd_ < 0) { return -1; } if(!buf) { return 0; } if(with_pi_) { struct iovec iov[2]; uint32_t type; struct ip* hdr = reinterpret_cast(buf); type = 0; if(hdr->ip_v == 4) { type = htonl(AF_INET); } else { type = htonl(AF_INET6); } iov[0].iov_base = &type; iov[0].iov_len = sizeof(type); iov[1].iov_base = buf; iov[1].iov_len = len; return(fix_return(::writev(fd_, iov, 2), sizeof(type))); } else { return(::write(fd_, buf, len)); } } void TunDevice::do_ifconfig() { std::ostringstream mtu_ss; mtu_ss << conf_.mtu_; StringVector args = boost::assign::list_of(actual_name_)(conf_.addr_.toString())("netmask")(conf_.netmask_.toString())("mtu")(mtu_ss.str()); if(conf_.type_ == TYPE_TUN) { args.push_back("up"); } else { #if defined(__GNUC__) && defined(__OpenBSD__) args.push_back("link0"); #elif defined(__GNUC__) && (defined(__FreeBSD__) || defined(__FreeBSD_kernel__)) args.push_back("up"); #elif defined(__GNUC__) && defined(__NetBSD__) // nothing to be done here #else #error This Device works just for OpenBSD, FreeBSD or NetBSD #endif } sys_exec_ = new SysExec("/sbin/ifconfig", args); } void TunDevice::waitUntilReady() { if(sys_exec_) { SysExec::waitAndDestroy(sys_exec_); } } anytun-0.3.8/src/syncBuffer.h0000664000175000017500000000565113604635433016070 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_syncBuffer_h_INCLUDED #define ANYTUN_syncBuffer_h_INCLUDED #include #include #include "buffer.h" #include #include "datatypes.h" #include "threadUtils.hpp" class SyncBuffer : public Buffer { public: SyncBuffer() : Buffer() {}; SyncBuffer(uint32_t length) : Buffer(length) {}; SyncBuffer(Buffer b): Buffer(b) {}; SyncBuffer(uint8_t* data, uint32_t length): Buffer(data,length) {}; SyncBuffer(const SyncBuffer& src) : Buffer(src) {}; private: //TODO check if this is ok // Mutex mutex_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { // Lock lock(mutex_); ar& length_; for(uint32_t i = 0; i < length_; i++) { ar & (*this)[i]; } } }; #endif anytun-0.3.8/src/anytun-showtables.cpp0000664000175000017500000001112013604635433017770 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "datatypes.h" #include "log.h" #include "buffer.h" #include "keyDerivation.h" #include "seqWindow.h" #include "connectionList.h" #include "routingTable.h" #include "networkAddress.h" #include "syncCommand.h" #include "cryptinit.hpp" #include #include #include #include #include void output() { ConnectionList& cl(gConnectionList); if(!cl.empty()) { ConnectionMap::iterator it = cl.getBeginUnlocked(); mux_t mux = it->first; ConnectionParam& conn(it->second); std::cout << "Client " << mux << ": " ; if(conn.remote_end_==PacketSourceEndpoint()) { std::cout<< "not registered"; } else { std::cout<< conn.remote_end_; } std::cout << std::endl; //std::cout << "Connection: Keyderivation-Type: " << conn.kd_.printType() << std::endl; cl.clear(); } else { network_address_type_t types[] = {ipv4,ipv6,ethernet}; for(int types_idx=0; types_idx<3; types_idx++) { network_address_type_t type = types[types_idx]; if(!gRoutingTable.empty(type)) { RoutingMap::iterator it = gRoutingTable.getBeginUnlocked(type); NetworkPrefix pref(it->first); std::cout << "Route: " << pref.toString() << "/" << (int)pref.getNetworkPrefixLength() << " -> "; mux_t mux = it->second; std::cout << mux << std::endl; gRoutingTable.clear(type); } } } } void readExactly(size_t toread, std::iostream& result) { size_t hasread = 0; while(toread > hasread && std::cin.good()) { char a[1]; std::cin.read(a,1); result.write(a,1); hasread++; } } void readAndProcessOne() { size_t message_lenght ; std::stringstream message_lenght_stream; readExactly(5,message_lenght_stream); message_lenght_stream >> message_lenght; std::stringstream void_stream; readExactly(1,void_stream); //skip space if(!message_lenght) { return; } std::stringstream sync_command_stream; readExactly(message_lenght, sync_command_stream); //std::cout << message_lenght << std::endl; //std::cout << sync_command_stream.str()<< std::endl; boost::archive::text_iarchive ia(sync_command_stream); SyncCommand scom(gConnectionList); ia >> scom; } int main(int argc, char* argv[]) { initCrypto(); int ret = 0; while(std::cin.good()) { try { readAndProcessOne(); } catch(std::exception& e) { std::cout << "uncaught exception, exiting: " << e.what() << std::endl; } output(); } return ret; } anytun-0.3.8/src/configure0000775000175000017500000003117313604635433015516 0ustar equinoxequinox#!/bin/sh # # anytun # # The secure anycast tunneling protocol (satp) defines a protocol used # for communication between any combination of unicast and anycast # tunnel endpoints. It has less protocol overhead than IPSec in Tunnel # mode and allows tunneling of every ETHER TYPE protocol (e.g. # ethernet, ip, arp ...). satp directly includes cryptography and # message authentication based on the methods used by SRTP. It is # intended to deliver a generic, scaleable and secure solution for # tunneling and relaying of packets of any protocol. # # # Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, # Christian Pointner # # This file is part of Anytun. # # Anytun is free software: you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # any later version. # # Anytun is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Anytun. If not, see . # # In addition, as a special exception, the copyright holders give # permission to link the code of portions of this program with the # OpenSSL library under certain conditions as described in each # individual source file, and distribute linked combinations # including the two. # You must obey the GNU General Public License in all respects # for all of the code used other than OpenSSL. If you modify # file(s) with this exception, you may extend this exception to your # version of the file(s), but you are not obligated to do so. If you # do not wish to do so, delete this exception statement from your # version. If you delete this exception statement from all source # files in the program, then also delete it here. # TARGET=`uname -s` EBUILD_COMPAT=0 CROSS_PREFIX='' USE_CLANG=0 CRYPTO_LIB='gcrypt' PASSPHRASE=1 ROUTING=1 PREFIX='/usr/local' BINDIR='' SBINDIR='' LIBDIR='' ETCDIR='' MANDIR='' INSTALLMANPAGE=1 EXAMPLESDIR='' INSTALLEXAMPLES=1 SYSTEMDDIR='' SYSTEMDGENERATORDIR='' TMPFILESDDIR='' INSTALLSYSTEMD=1 BOOST_PREFIX='' GCRYPT_PREFIX='' NETTLE_PREFIX='' OPENSSL_PREFIX='' print_usage() { echo "configure --help print this" echo " --target= build target i.e. Linux (default: autodetect)" echo " --prefix= the installation prefix (default: /usr/local)" echo " --bindir= the path to the bin directory (default: $PREFIX/bin)" echo " --sbindir= the path to the sbin directory (default: $PREFIX/sbin)" echo " --libdir= the path to the lib directory (default: $PREFIX/lib)" echo " --sysconfdir= the path to the system configuration directory (default: $PREFIX/etc" echo " --mandir= the path to the system man pages (default: $PREFIX/share/man)" echo " --no-manpage don't install manpages" echo " --examplesdir= the path to the examples files (default: $PREFIX/share/examples)" echo " --no-examples don't install example files" echo " --systemddir= the path to the systemd service unit directory (default: from pkg-config)" echo " --systemdgeneratordir= the path to the systemd generator directory (default: from pkg-config)" echo " --tmpfilesddir= the path to the systemd tmpfiles.d configuration file (default: from pkg-config)" echo " --no-systemd don't install systemd units" echo " --use-gcrypt use libgcrypt (this is the default)" echo " --use-nettle use libnettle instead of libgcrypt" echo " --use-ssl-crypto use openssl crypto library instead of libgcrypt" echo " --no-crypto disable crypto at all (only NULL cipher)" echo " --disable-passphrase disable master key and salt passphrase" echo " --enable-passphrase enable master key and salt passphrase" echo " --disable-routing disable built-in routing capability" echo " --enable-routing enable built-in routing capability" echo " --cross-prefix= add PREFIX to compiler calls" echo " --with-boost= don't use systemwide boost" echo " --with-gcrypt= don't use systemwide gcrypt" echo " --with-nettle= don't use systemwide nettle" echo " --with-openssl= don't use systemwide openssl" echo " --use-clang use clang/llvm as compiler/linker" } for arg do case $arg in --target=*) TARGET=${arg#--target=} ;; --use-clang) USE_CLANG=1 ;; --prefix=*) PREFIX=${arg#--prefix=} ;; --bindir=*) SBINDIR=${arg#--bindir=} ;; --sbindir=*) SBINDIR=${arg#--sbindir=} ;; --libdir=*) LIBDIR=${arg#--libdir=} ;; --sysconfdir=*) ETCDIR=${arg#--sysconfdir=} ;; --mandir=*) MANDIR=${arg#--mandir=} ;; --no-manpage) INSTALLMANPAGE=0 ;; --examplesdir=*) EXAMPLESDIR=${arg#--examplesdir=} ;; --no-examples) INSTALLEXAMPLES=0 ;; --systemddir=*) SYSTEMDDIR=${arg#--systemddir=} ;; --systemdgeneratordir=*) SYSTEMDGENERATORDIR=${arg#--systemdgeneratordir=} ;; --tmpfilesddir=*) TMPFILESDDIR=${arg#--tmpfilesddir=} ;; --no-systemd) INSTALLSYSTEMD=0 ;; --use-gcrypt) CRYPTO_LIB='gcrypt' ;; --use-nettle) CRYPTO_LIB='nettle' ;; --use-ssl-crypto) CRYPTO_LIB='ssl' ;; --no-crypto) CRYPTO_LIB='none' ;; --enable-passphrase) PASSPHRASE=1 ;; --disable-passphrase) PASSPHRASE=0 ;; --enable-routing) ROUTING=1 ;; --disable-routing) ROUTING=0 ;; --ebuild-compat) EBUILD_COMPAT=1 ;; --cross-prefix=*) CROSS_PREFIX=${arg#--cross-prefix=} ;; --with-boost=*) BOOST_PREFIX=${arg#--with-boost=} ;; --with-gcrypt=*) GCRYPT_PREFIX=${arg#--with-gcrypt=} ;; --with-nettle=*) NETTLE_PREFIX=${arg#--with-nettle=} ;; --with-openssl=*) OPENSSL_PREFIX=${arg#--with-openssl=} ;; --help) print_usage exit 0 ;; *) ERRORS="$ERRORS $arg" ;; esac done if [ -n "$ERRORS" ] && [ $EBUILD_COMPAT -ne 1 ]; then for error in $ERRORS; do echo "Unknown argument: $error" done print_usage exit 1 fi if [ $USE_CLANG -eq 0 ]; then if [ -z "$CXXFLAGS" ]; then CXXFLAGS='-g -Wall -O2'; fi if [ -z "$LDFLAGS" ]; then LDFLAGS='-g -Wall -O2'; fi COMPILER='g++' else if [ -z "$CXXFLAGS" ]; then CXXFLAGS='-g -O2'; fi if [ -z "$LDFLAGS" ]; then LDFLAGS='-g -O2'; fi COMPILER='clang++' fi rm -f include.mk rm -f version.h case $TARGET in Linux) rm -f tunDevice.cpp ln -sf linux/tunDevice.cpp rm -f signalHandler.hpp ln -sf posix/signalHandler.hpp rm -f sysExec.hpp ln -sf posix/sysExec.hpp rm -f daemonService.h daemonService.cpp ln -sf posix/posixDaemon.h daemonService.h ln -sf posix/posixDaemon.cpp daemonService.cpp echo "loading Linux specific TUN Device" LDFLAGS=$LDFLAGS' -lboost_thread -lboost_serialization -lboost_system -lboost_date_time -lpthread' LOG_TARGETS='-DLOG_SYSLOG -DLOG_FILE -DLOG_STDOUT' ;; OpenBSD|FreeBSD|NetBSD|GNU/kFreeBSD) rm -f tunDevice.cpp ln -sf bsd/tunDevice.cpp rm -f signalHandler.hpp ln -sf posix/signalHandler.hpp rm -f sysExec.hpp ln -sf posix/sysExec.hpp rm -f daemonService.h daemonService.cpp ln -sf posix/posixDaemon.h daemonService.h ln -sf posix/posixDaemon.cpp daemonService.cpp echo "loading BSD specific TUN Device" CPPFLAGS=$CPPFLAGS' -I/usr/local/include' LDFLAGS=$LDFLAGS' -L/usr/local/lib -lboost_thread -lboost_serialization -lboost_system -lboost_date_time -lpthread' LOG_TARGETS='-DLOG_SYSLOG -DLOG_FILE -DLOG_STDOUT' INSTALLSYSTEMD=0 ;; mingw) rm -f tunDevice.cpp rm -f signalHandler.hpp rm -f sysExec.hpp rm -f daemonService.h daemonService.cpp echo "loading Windows specific TUN Device" CPPFLAGS=$CPPFLAGS' -DMINGW -D_WIN32_WINNT=0x0501 -DWIN32_LEAN_AND_MEAN -DBOOST_WINDOWS -fno-strict-aliasing -DBOOST_THREAD_USE_LIB' LDFLAGS=$LDFLAGS' -lboost_thread_win32 -lboost_serialization -lboost_system -lboost_date_time -lwsock32 -lws2_32' LOG_TARGETS='-DWIN_EVENTLOG -DLOG_FILE -DLOG_STDOUT' INSTALLSYSTEMD=0 ;; *) echo "platform not supported" exit 1 ;; esac CPPFLAGS="$CPPFLAGS $LOG_TARGETS" if [ -n "$BOOST_PREFIX" ]; then CPPFLAGS="$CPPFLAGS -I\"$BOOST_PREFIX/include\"" LDFLAGS="$LDFLAGS -L\"$BOOST_PREFIX/lib\"" fi CRYPTO_LIB_NAME="" case $CRYPTO_LIB in gcrypt) CPPFLAGS=$CPPFLAGS' -DUSE_GCRYPT' LDFLAGS=$LDFLAGS' -lgcrypt -lgpg-error' if [ -n "$GCRYPT_PREFIX" ]; then CPPFLAGS="$CPPFLAGS -I\"$GCRYPT_PREFIX/include\"" LDFLAGS="$LDFLAGS -L\"$GCRYPT_PREFIX/lib\"" fi CRYPTO_LIB_NAME="libgcrypt" echo "using gcrypt library" ;; nettle) CPPFLAGS=$CPPFLAGS' -DUSE_NETTLE' LDFLAGS=$LDFLAGS' -lnettle' if [ -n "$NETTLE_PREFIX" ]; then CPPFLAGS="$CPPFLAGS -I\"$NETTLE_PREFIX/include\"" LDFLAGS="$LDFLAGS -L\"$NETTLE_PREFIX/lib\"" fi CRYPTO_LIB_NAME="Nettle" echo "using nettle library" ;; ssl) CPPFLAGS=$CPPFLAGS' -DUSE_SSL_CRYPTO' LDFLAGS=$LDFLAGS' -lcrypto' if [ -n "$OPENSSL_PREFIX" ]; then CPPFLAGS="$CPPFLAGS -I\"$OPENSSL_PREFIX/include\"" LDFLAGS="$LDFLAGS -L\"$OPENSSL_PREFIX/lib\"" fi CRYPTO_LIB_NAME="OpenSSL" echo "using openssl crypto library" ;; none) CPPFLAGS=$CPPFLAGS' -DNO_CRYPT' CRYPTO_LIB_NAME="none" echo "disabling crypto" ;; esac if [ $PASSPHRASE -eq 0 ]; then CPPFLAGS=$CPPFLAGS' -DNO_PASSPHRASE' echo "disabling master key and salt passphrase" fi if [ $ROUTING -eq 0 ]; then CPPFLAGS=$CPPFLAGS' -DNO_ROUTING' echo "disabling built-in routing capability" fi if [ -z "$BINDIR" ]; then BINDIR=$PREFIX/bin fi if [ -z "$SBINDIR" ]; then SBINDIR=$PREFIX/sbin fi if [ -z "$LIBDIR" ]; then LIBDIR=$PREFIX/lib fi if [ -z "$ETCDIR" ]; then ETCDIR=$PREFIX/etc fi if [ -z "$MANDIR" ]; then MANDIR=$PREFIX/share/man fi if [ -z "$EXAMPLESDIR" ]; then EXAMPLESDIR=$PREFIX/share/examples fi if [ $INSTALLSYSTEMD -eq 1 ]; then if [ -z "$SYSTEMDDIR" ]; then SYSTEMDDIR=`pkg-config systemd --variable=systemdsystemunitdir` fi if [ -z "$SYSTEMDGENERATORDIR" ]; then SYSTEMDGENERATORDIR=`pkg-config systemd --variable=systemdsystemgeneratordir` fi if [ -z "$TMPFILESDDIR" ]; then TMPFILESDDIR=`pkg-config systemd --variable=tmpfilesdir` fi fi cat > include.mk <> include.mk fi if [ $INSTALLMANPAGE -eq 1 ]; then echo "MANDIR := $MANDIR" >> include.mk echo "installing manpage" else echo "not installing manpage" fi if [ $INSTALLEXAMPLES -eq 1 ]; then echo "EXAMPLESDIR := $EXAMPLESDIR" >> include.mk echo "installing example files" else echo "not installing example files" fi if [ $INSTALLSYSTEMD -eq 1 ]; then echo "SYSTEMDDIR := $SYSTEMDDIR" >> include.mk echo "SYSTEMDGENERATORDIR := $SYSTEMDGENERATORDIR" >> include.mk echo "TMPFILESDDIR := $TMPFILESDDIR" >> include.mk echo "installing systemd units" else echo "not installing systemd units" fi VERSION=`cat ../version` if which git >/dev/null; then GIT_HASH=`git rev-parse HEAD 2> /dev/null` if [ -n "$GIT_HASH" ]; then VERSION="$VERSION (git $GIT_HASH)" fi fi cat > version.h < * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include "datatypes.h" #include "endian.h" #include "plainPacket.h" #include "anytunError.h" PlainPacket::PlainPacket(uint32_t payload_length, bool allow_realloc) : Buffer(payload_length + sizeof(payload_type_t), allow_realloc) { payload_type_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(payload_type_t); *payload_type_ = 0; } uint32_t PlainPacket::getHeaderLength() { return sizeof(payload_type_t); } payload_type_t PlainPacket::getPayloadType() const { if(payload_type_) { return PAYLOAD_TYPE_T_NTOH(*payload_type_); } return 0; } void PlainPacket::setPayloadType(payload_type_t payload_type) { if(!payload_type_) { return; } if(payload_type == PAYLOAD_TYPE_TUN) { if(!payload_) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN); return; } char* ip_version_ptr = reinterpret_cast(payload_); char ip_version = ip_version_ptr[0]; ip_version >>=4; if(ip_version == 4) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN4); } else if(ip_version == 6) { *payload_type_ = PAYLOAD_TYPE_T_HTON(PAYLOAD_TYPE_TUN6); } } else { *payload_type_ = PAYLOAD_TYPE_T_HTON(payload_type); } } uint32_t PlainPacket::getPayloadLength() const { if(!payload_) { return 0; } return (length_ > sizeof(payload_type_t)) ? (length_ - sizeof(payload_type_t)) : 0; } void PlainPacket::setPayloadLength(uint32_t payload_length) { Buffer::setLength(payload_length + sizeof(payload_type_t)); // depending on allow_realloc buf_ may point to another address // therefore in this case reinit() gets called by Buffer::setLength() } void PlainPacket::reinit() { payload_type_ = reinterpret_cast(buf_); payload_ = buf_ + sizeof(payload_type_t); if(length_ <= (sizeof(payload_type_t))) { payload_ = NULL; } if(length_ < (sizeof(payload_type_t))) { payload_type_ = NULL; AnytunError::throwErr() << "plain packet can't be initialized, buffer is too small"; } } uint8_t* PlainPacket::getPayload() { return payload_; } /* NetworkAddress PlainPacket::getSrcAddr() const { if(!payload_type_ || !payload_) return NetworkAddress(); payload_type_t type = PAYLOAD_TYPE_T_NTOH(*payload_type_); if(type == PAYLOAD_TYPE_TAP) // Ehternet { // TODO return NetworkAddress(); } else if(type == PAYLOAD_TYPE_TUN4) // IPv4 { if(length_ < (sizeof(payload_type_t)+sizeof(struct ip))) return NetworkAddress(); struct ip* hdr = reinterpret_cast(payload_); return NetworkAddress(hdr->ip_src); } else if(type == PAYLOAD_TYPE_TUN6) // IPv6 { if(length_ < (sizeof(payload_type_t)+sizeof(struct ip6_hdr))) return NetworkAddress(); struct ip6_hdr* hdr = reinterpret_cast(payload_); return NetworkAddress(hdr->ip6_src); } return NetworkAddress(); }*/ NetworkAddress PlainPacket::getDstAddr() const { if(!payload_type_ || !payload_) { return NetworkAddress(); } payload_type_t type = PAYLOAD_TYPE_T_NTOH(*payload_type_); if(type == PAYLOAD_TYPE_TAP) { // Ehternet // TODO return NetworkAddress(); } else if(type == PAYLOAD_TYPE_TUN4) { // IPv4 if(length_ < (sizeof(payload_type_t)+5*4)) { return NetworkAddress(); } char* hdr = reinterpret_cast(payload_); boost::asio::ip::address_v4::bytes_type ip_octets; for(int i=0; i<4; i++) { ip_octets[i]=hdr[4*4+i]; } return NetworkAddress(boost::asio::ip::address_v4(ip_octets)); } else if(type == PAYLOAD_TYPE_TUN6) { // IPv6 if(length_ < (sizeof(payload_type_t)+2*16+2*4)) { return NetworkAddress(); } char* hdr = reinterpret_cast(payload_); boost::asio::ip::address_v6::bytes_type ip_octets; for(int i=0; i<16; i++) { ip_octets[i]=hdr[2*4+16+i]; } return NetworkAddress(boost::asio::ip::address_v6(ip_octets)); } return NetworkAddress(); } anytun-0.3.8/src/syncCommand.cpp0000664000175000017500000000504213604635433016562 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "syncCommand.h" SyncCommand::SyncCommand(ConnectionList& cl) { scc_ = new SyncConnectionCommand(cl); src_ = new SyncRouteCommand(); } SyncCommand::SyncCommand(ConnectionList& cl, uint16_t mux) { scc_ = new SyncConnectionCommand(cl,mux); src_=NULL; } SyncCommand::SyncCommand(NetworkPrefix np) { scc_ = NULL; src_ = new SyncRouteCommand(np); } SyncCommand::~SyncCommand() { if(scc_) { delete scc_; } if(src_) { delete src_; } } anytun-0.3.8/src/syncCommand.h0000664000175000017500000000625113604635433016232 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #ifndef ANYTUN_syncCommand_h_INCLUDED #define ANYTUN_syncCommand_h_INCLUDED #include #include #include "connectionList.h" #include "threadUtils.hpp" #include "syncConnectionCommand.h" #include "syncRouteCommand.h" #include "networkPrefix.h" #include class SyncCommand { public: SyncCommand(ConnectionList& cl); SyncCommand(ConnectionList& cl ,uint16_t mux); SyncCommand(NetworkPrefix); ~SyncCommand(); private: SyncCommand(const SyncCommand&); SyncConnectionCommand* scc_; SyncRouteCommand* src_; friend class boost::serialization::access; template void serialize(Archive& ar, const unsigned int version) { std::string syncstr; if(scc_) { syncstr = "connection"; } if(src_) { syncstr = "route"; } ar& syncstr; // std::cout << "syncstr received " < * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include "cipherFactory.h" #include "cipher.h" Cipher* CipherFactory::create(std::string const& type, kd_dir_t dir) { if(type == "null") { return new NullCipher(); } #ifndef NO_CRYPT else if(type == "aes-ctr") { return new AesIcmCipher(dir); } else if(type == "aes-ctr-128") { return new AesIcmCipher(dir, 128); } else if(type == "aes-ctr-192") { return new AesIcmCipher(dir, 192); } else if(type == "aes-ctr-256") { return new AesIcmCipher(dir, 256); } #endif else { throw std::invalid_argument("cipher not available"); } } anytun-0.3.8/src/connectionParam.cpp0000664000175000017500000000474013604635433017433 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include "connectionParam.h" ConnectionParam::ConnectionParam(KeyDerivation& kd, SeqWindow& seq_window,seq_nr_t seq_nr, PacketSourceEndpoint remote_end) : kd_(kd),seq_window_(seq_window),seq_nr_(seq_nr), remote_end_(remote_end) { } ConnectionParam::ConnectionParam(const ConnectionParam& src) : kd_(src.kd_),seq_window_(src.seq_window_),seq_nr_(src.seq_nr_),remote_end_(src.remote_end_),mutex_() { } anytun-0.3.8/src/options.cpp0000664000175000017500000011074213604635433016006 0ustar equinoxequinox/* * anytun * * The secure anycast tunneling protocol (satp) defines a protocol used * for communication between any combination of unicast and anycast * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel * mode and allows tunneling of every ETHER TYPE protocol (e.g. * ethernet, ip, arp ...). satp directly includes cryptography and * message authentication based on the methods used by SRTP. It is * intended to deliver a generic, scaleable and secure solution for * tunneling and relaying of packets of any protocol. * * * Copyright (C) 2007-2014 Markus Grüneis, Othmar Gsenger, Erwin Nindl, * Christian Pointner * * This file is part of Anytun. * * Anytun is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * any later version. * * Anytun is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Anytun. If not, see . * * In addition, as a special exception, the copyright holders give * permission to link the code of portions of this program with the * OpenSSL library under certain conditions as described in each * individual source file, and distribute linked combinations * including the two. * You must obey the GNU General Public License in all respects * for all of the code used other than OpenSSL. If you modify * file(s) with this exception, you may extend this exception to your * version of the file(s), but you are not obligated to do so. If you * do not wish to do so, delete this exception statement from your * version. If you delete this exception statement from all source * files in the program, then also delete it here. */ #include #include #include #include #include #include "datatypes.h" #include "version.h" #include "options.h" #include "log.h" #include "authAlgoFactory.h" std::ostream& operator<<(std::ostream& stream, syntax_error const& error) { stream << "syntax error: " << error.what() << std::endl; if(error.pos >= 0) { stream << " "; for(int32_t i = 0; i < error.pos; ++i) { stream << " "; } return stream << "^"; } return stream; } std::ostream& operator<<(std::ostream& stream, role_t const& role) { switch(role) { case ROLE_LEFT: stream << "left"; break; case ROLE_RIGHT: stream << "right"; break; default: stream << "unknown"; break; } return stream; } void OptionHost::init(std::string addrPort) { std::string origAddrPort(addrPort); size_t pos = addrPort.find_first_of("["); if(pos != std::string::npos && pos != 0) { throw syntax_error(origAddrPort, pos); // an [ was found but not at the beginning; } bool hasPort = false; if(pos != std::string::npos) { addrPort.erase(pos, 1); pos = addrPort.find_first_of("]"); if(pos == std::string::npos) { throw syntax_error(origAddrPort, origAddrPort.length()); //no trailing ] although an leading [ was found } if(pos < addrPort.length()-2) { if(addrPort[pos+1] != ':') { throw syntax_error(origAddrPort, pos+2); // wrong port delimieter } addrPort[pos+1] = '/'; hasPort = true; } else if(pos != addrPort.length()-1) { throw syntax_error(origAddrPort, pos+2); // too few characters left } addrPort.erase(pos, 1); } else { pos = addrPort.find_first_of(":"); if(pos != std::string::npos && pos == addrPort.find_last_of(":")) { // an ':' has been found and it is the only one -> assuming port present hasPort = true; addrPort[pos] = '/'; } } if(hasPort) { std::stringstream tmp_stream(addrPort); getline(tmp_stream, addr, '/'); if(!tmp_stream.good()) { throw syntax_error(origAddrPort, addr.length()); } tmp_stream >> port; } else { addr = addrPort; port = "2323"; // default sync port } } std::istream& operator>>(std::istream& stream, OptionHost& host) { std::string tmp; stream >> tmp; host.init(tmp); return stream; } void OptionNetwork::init(std::string network) { std::stringstream tmp_stream(network); getline(tmp_stream, net_addr, '/'); if(!tmp_stream.good()) { throw syntax_error(network, net_addr.length()); } tmp_stream >> prefix_length; } std::istream& operator>>(std::istream& stream, OptionNetwork& network) { std::string tmp; stream >> tmp; network.init(tmp); return stream; } Options& gOpt = Options::instance(); Options& Options::instance() { static Options instance; return instance; } Options::Options() : key_(uint32_t(0)), salt_(uint32_t(0)) { #if defined(ANYCTR_OPTIONS) progname_ = "anytun-controld"; #elif defined(ANYCONF_OPTIONS) progname_ = "anytun-config"; #else progname_ = "anytun"; #endif cluster_opts = false; connection_opts = false; daemonize_ = true; username_ = ""; groupname_ = ""; chroot_dir_ = ""; pid_file_ = ""; debug_ = false; file_name_ = ""; bind_to_.addr = "127.0.0.1"; bind_to_.port = "2323"; resolv_addr_type_ = ANY; local_.addr = ""; local_.port = "4444"; remote_.addr = ""; remote_.port = "4444"; local_sync_.addr = ""; local_sync_.port = ""; dev_name_ = ""; dev_type_ = ""; post_up_script_ = ""; sender_id_ = 0; mux_ = 0; seq_window_size_ = 0; #if !defined(ANYCONF_OPTIONS) #ifndef NO_CRYPT cipher_ = "aes-ctr"; auth_algo_ = "sha1"; auth_tag_length_ = 10; kd_prf_ = "aes-ctr"; #else cipher_ = "null"; auth_algo_ = "null"; auth_tag_length_ = 0; kd_prf_ = "null"; #endif #else cipher_ = "null"; auth_algo_ = "null"; auth_tag_length_ = 0; kd_prf_ = "aes-ctr"; #endif role_ = ROLE_LEFT; } Options::~Options() { } #define NOTHING #define PARSE_BOOL_PARAM(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) { \ VALUE = true; \ DO_POST; \ } #define PARSE_INVERSE_BOOL_PARAM(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) { \ VALUE = false; \ DO_POST; \ } #define PARSE_SIGNED_INT_PARAM(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ std::stringstream tmp; \ tmp << argv[i+1]; \ tmp >> VALUE; \ argc--; \ i++; \ DO_POST; \ } #define PARSE_SCALAR_PARAM(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ std::stringstream tmp; \ tmp << argv[i+1]; \ tmp >> VALUE; \ argc--; \ i++; \ DO_POST; \ } #define PARSE_SCALAR_PARAM2(SHORT, LONG, VALUE1, VALUE2, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argc < 2) \ throw syntax_error(str.append(" ").append(argv[i+1]), str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ if(argv[i+2][0] == '-') { \ uint32_t pos = str.length() + 1 + strlen(argv[i+1]) + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]).append(" ").append(argv[i+2]), pos); \ } \ std::stringstream tmp; \ tmp << argv[i+1] << " " << argv[i+2]; \ tmp >> VALUE1; \ tmp >> VALUE2; \ argc-=2; \ i+=2; \ DO_POST; \ } #define PARSE_CSLIST_PARAM(SHORT, LONG, LIST, TYPE, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ std::stringstream tmp(argv[i+1]); \ while (tmp.good()) \ { \ std::string tmp_line; \ getline(tmp,tmp_line,','); \ LIST.push_back(TYPE(tmp_line)); \ } \ argc--; \ i++; \ DO_POST; \ } #define PARSE_HEXSTRING_PARAM_SEC(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ VALUE = Buffer(std::string(argv[i+1])); \ for(size_t j=0; j < strlen(argv[i+1]); ++j) \ argv[i+1][j] = '#'; \ argc--; \ i++; \ DO_POST; \ } #define PARSE_PHRASE_PARAM_SEC(SHORT, LONG, VALUE, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ VALUE = argv[i+1]; \ for(size_t j=0; j < strlen(argv[i+1]); ++j) \ argv[i+1][j] = '#'; \ argc--; \ i++; \ DO_POST; \ } #define PARSE_STRING_LIST(SHORT, LONG, LIST, DO_POST) \ else if(str == SHORT || str == LONG) \ { \ if(argc < 1) \ throw syntax_error(str, str.length()); \ if(argv[i+1][0] == '-') { \ uint32_t pos = str.length() + 1; \ throw syntax_error(str.append(" ").append(argv[i+1]), pos); \ } \ LIST.push_back(argv[i+1]); \ argc--; \ i++; \ DO_POST; \ } bool Options::parse(int argc, char* argv[]) { WritersLock lock(mutex); progname_ = argv[0]; argc--; bool ipv4_only = false, ipv6_only = false; std::string role = ""; for(int i=1; argc > 0; ++i) { std::string str(argv[i]); argc--; if(str == "-h" || str == "--help") { printUsage(); return false; } else if(str == "-v" || str == "--version") { printVersion(); return false; } #if defined(ANYTUN_OPTIONS) || defined(ANYCTR_OPTIONS) #if !defined(_MSC_VER) && !defined(MINGW) PARSE_INVERSE_BOOL_PARAM("-D","--nodaemonize", daemonize_, NOTHING) PARSE_SCALAR_PARAM("-u","--username", username_, NOTHING) PARSE_SCALAR_PARAM("-g","--groupname", groupname_, NOTHING) PARSE_SCALAR_PARAM("-C","--chroot", chroot_dir_, NOTHING) PARSE_SCALAR_PARAM("-P","--write-pid", pid_file_, NOTHING) #endif #endif PARSE_STRING_LIST("-L","--log", log_targets_, NOTHING) PARSE_BOOL_PARAM("-U","--debug", debug_, NOTHING) #if defined(ANYCTR_OPTIONS) PARSE_SCALAR_PARAM("-f","--file", file_name_, NOTHING) PARSE_SCALAR_PARAM("-X","--control-host", bind_to_, NOTHING) #endif #if defined(ANYTUN_OPTIONS) PARSE_SCALAR_PARAM("-i","--interface", local_.addr, NOTHING) PARSE_SCALAR_PARAM("-p","--port", local_.port, NOTHING) PARSE_SCALAR_PARAM("-s","--sender-id", sender_id_, NOTHING) #endif #if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS) PARSE_SCALAR_PARAM("-r","--remote-host", remote_.addr, connection_opts = true) PARSE_SCALAR_PARAM("-o","--remote-port", remote_.port, connection_opts = true) PARSE_BOOL_PARAM("-4","--ipv4-only", ipv4_only, connection_opts = true) PARSE_BOOL_PARAM("-6","--ipv6-only", ipv6_only, connection_opts = true) #endif #if defined(ANYTUN_OPTIONS) PARSE_SCALAR_PARAM("-I","--sync-interface", local_sync_.addr, cluster_opts = true) PARSE_SCALAR_PARAM("-S","--sync-port", local_sync_.port, cluster_opts = true) PARSE_CSLIST_PARAM("-M","--sync-hosts", remote_sync_hosts_, OptionHost, cluster_opts = true) PARSE_CSLIST_PARAM("-X","--control-host", remote_sync_hosts_, OptionHost, cluster_opts = true) PARSE_SCALAR_PARAM("-d","--dev", dev_name_, NOTHING) PARSE_SCALAR_PARAM("-t","--type", dev_type_, NOTHING) PARSE_SCALAR_PARAM("-n","--ifconfig", ifconfig_param_, NOTHING) PARSE_SCALAR_PARAM("-x","--post-up-script", post_up_script_, NOTHING) #endif #if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS) #ifndef NO_ROUTING PARSE_CSLIST_PARAM("-R","--route", routes_, OptionNetwork, connection_opts = true) #endif PARSE_SCALAR_PARAM("-m","--mux", mux_, connection_opts = true) PARSE_SCALAR_PARAM("-w","--window-size", seq_window_size_, connection_opts = true) #ifndef NO_CRYPT PARSE_SCALAR_PARAM("-k","--kd-prf", kd_prf_, connection_opts = true) PARSE_SCALAR_PARAM("-e","--role", role, connection_opts = true) #ifndef NO_PASSPHRASE PARSE_PHRASE_PARAM_SEC("-E","--passphrase", passphrase_, connection_opts = true) #endif PARSE_HEXSTRING_PARAM_SEC("-K","--key", key_, connection_opts = true) PARSE_HEXSTRING_PARAM_SEC("-A","--salt", salt_, connection_opts = true) #endif #endif #if defined(ANYTUN_OPTIONS) #ifndef NO_CRYPT PARSE_SCALAR_PARAM("-c","--cipher", cipher_, NOTHING) PARSE_SCALAR_PARAM("-a","--auth-algo", auth_algo_, NOTHING) PARSE_SCALAR_PARAM("-b","--auth-tag-length", auth_tag_length_, NOTHING) #endif #endif else { throw syntax_error(str, 0); } } if(ipv4_only && ipv6_only) { throw syntax_error("-4 and -6 are mutual exclusive", -1); } if(ipv4_only) { resolv_addr_type_ = IPV4_ONLY; } if(ipv6_only) { resolv_addr_type_ = IPV6_ONLY; } if(role != "") { if(role == "alice" || role == "server" || role == "left") { role_ = ROLE_LEFT; } else if(role == "bob" || role == "client" || role == "right") { role_ = ROLE_RIGHT; } else { throw syntax_error("unknown role name: " + role, -1); } } if(debug_) { log_targets_.push_back("stdout:5"); daemonize_ = false; } if(log_targets_.empty()) { #if !defined(_MSC_VER) && !defined(MINGW) #if !defined(ANYCONF_OPTIONS) log_targets_.push_back(std::string("syslog:3,").append(progname_).append(",daemon")); #else log_targets_.push_back("stderr:2"); #endif #else #ifdef WIN_SERVICE log_targets_.push_back(std::string("eventlog:3,").append(progname_)); #else log_targets_.push_back("stdout:3"); #endif #endif } return true; } void Options::parse_post() { #if defined(ANYTUN_OPTIONS) if(cluster_opts && connection_opts) { cLog.msg(Log::PRIO_WARNING) << "you have provided options for cluster support as well as connection oriented options, we strongly recommend to use anytun-config and anytun-controld when building a cluster"; } if(cipher_ == "null" && auth_algo_ == "null") { kd_prf_ = "null"; } if((cipher_ != "null" || auth_algo_ != "null") && kd_prf_ == "null") { cLog.msg(Log::PRIO_WARNING) << "using NULL key derivation with encryption and or authentication enabled!"; } uint32_t tag_len_max = AuthAlgoFactory::getDigestLength(auth_algo_); if(!tag_len_max) { auth_tag_length_ = 0; } else if(tag_len_max < auth_tag_length_) { cLog.msg(Log::PRIO_WARNING) << auth_algo_ << " auth algo can't generate tags of length " << auth_tag_length_ << ", using maximum tag length(" << tag_len_max << ")"; auth_tag_length_ = tag_len_max; } #endif if(dev_name_ == "" && dev_type_ == "") { dev_type_ = "tun"; } } void Options::printVersion() { #if defined(ANYCTR_OPTIONS) std::cout << "anytun-controld"; #elif defined(ANYCONF_OPTIONS) std::cout << "anytun-config"; #else std::cout << "anytun"; #endif std::cout << VERSION_STRING << std::endl; #if defined(__clang__) std::cout << "built using CLANG " << __clang_version__ << " with " << CRYPTO_LIB_NAME << " crypto library." << std::endl; #elif defined(__GNUC__) std::cout << "built using GCC " << __GNUC__ << '.' << __GNUC_MINOR__ << '.' << __GNUC_PATCHLEVEL__ << " with " << CRYPTO_LIB_NAME << " crypto library." << std::endl; #else std::cout << "built using an unknown compiler " << CRYPTO_LIB_NAME << " crypto library." << std::endl; #endif } void Options::printUsage() { std::cout << "USAGE:" << std::endl; #if defined(ANYCTR_OPTIONS) std::cout << "anytun-controld " << std::endl; #elif defined(ANYCONF_OPTIONS) std::cout << "anytun-config " << std::endl; #else std::cout << "anytun " << std::endl; #endif std::cout << " [-h|--help] prints this..." << std::endl; std::cout << " [-v|--version] print version info and exit" << std::endl; #if defined(ANYTUN_OPTIONS) || defined(ANYCTR_OPTIONS) #if !defined(_MSC_VER) && !defined(MINGW) std::cout << " [-D|--nodaemonize] don't run in background" << std::endl; std::cout << " [-u|--username] change to this user" << std::endl; std::cout << " [-g|--groupname] change to this group" << std::endl; std::cout << " [-C|--chroot] chroot to this directory" << std::endl; std::cout << " [-P|--write-pid] write pid to this file" << std::endl; #endif #endif std::cout << " [-L|--log] :[,[,..]]" << std::endl; std::cout << " add a log target, can be invoked several times" << std::endl; std::cout << " i.e.: stdout:5" << std::endl; std::cout << " [-U|--debug] don't daemonize and log to stdout with maximum log level" << std::endl; #if defined(ANYCTR_OPTIONS) std::cout << " [-f|--file] path to input file" << std::endl; std::cout << " [-X|--control-host] < [:] | : >" << std::endl; std::cout << " local tcp port and or ip address to bind to" << std::endl; #endif #if defined(ANYTUN_OPTIONS) std::cout << " [-i|--interface] local anycast ip address to bind to" << std::endl; std::cout << " [-p|--port] local anycast(data) port to bind to" << std::endl; std::cout << " [-s|--sender-id ] the sender id to use" << std::endl; #endif #if defined(ANYTUN_OPTIONS) || defined(ANYCONF_OPTIONS) std::cout << " [-r|--remote-host] remote host" << std::endl; std::cout << " [-o|--remote-port] remote port" << std::endl; std::cout << " [-4|--ipv4-only] always resolv IPv4 addresses" << std::endl; std::cout << " [-6|--ipv6-only] always resolv IPv6 addresses" << std::endl; #endif #if defined(ANYTUN_OPTIONS) std::cout << " [-I|--sync-interface] local unicast(sync) ip address to bind to" << std::endl; std::cout << " [-S|--sync-port] local unicast(sync) port to bind to" << std::endl; std::cout << " [-M|--sync-hosts] [:][,[:][...]]"<< std::endl; std::cout << " remote hosts to sync with" << std::endl; std::cout << " [-X|--control-host] [:]"<< std::endl; std::cout << " fetch the config from this host" << std::endl; std::cout << " [-d|--dev] device name" << std::endl; std::cout << " [-t|--type] device type" << std::endl; std::cout << " [-n|--ifconfig] / the local address for the tun/tap device and the used prefix length" << std::endl; std::cout << " [-x|--post-up-script]