Changed directory structure

This commit is contained in:
Friedrich Schöller committed 2013-05-02 03:06:43 +02:00
1 parent 34acb3f6d5
commit 455da8b0da
36 files changed
+48 -37

No files matched your search

+57
View File
@@ -0,0 +1,57 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "auth.h"
#include "sha1.h"
#include "utility.h"
#include <arpa/inet.h>
Auth::Auth(const char *passphrase)
{
this->passphrase = passphrase;
}
Auth::Response Auth::getResponse(const Challenge &challenge) const
{
SHA1 hasher;
Response response;
hasher << passphrase.c_str();
hasher.Input(&challenge[0], challenge.size());
hasher.Result((unsigned int *)response.data);
for (int i = 0; i < 5; i++)
response.data[i] = htonl(response.data[i]);
return response;
}
Auth::Challenge Auth::generateChallenge(int length) const
{
Challenge challenge;
challenge.resize(length);
for (int i = 0; i < length; i++)
challenge[i] = Utility::rand();
return challenge;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef AUTH_H
#define AUTH_H
#include <vector>
#include <string>
#include <string.h>
#include <stdint.h>
class Auth
{
public:
typedef std::vector<char> Challenge;
struct Response
{
uint32_t data[5];
bool operator==(const Response &other) const { return memcmp(this, &other, sizeof(Response)) == 0; }
};
Auth(const char *passphrase);
Challenge generateChallenge(int length) const;
Response getResponse(const Challenge &challenge) const;
protected:
std::string passphrase;
std::string challenge;
};
#endif
+243
View File
@@ -0,0 +1,243 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "client.h"
#include "server.h"
#include "exception.h"
#include "config.h"
#include "utility.h"
#include <string.h>
#include <arpa/inet.h>
#include <syslog.h>
using namespace std;
const Worker::TunnelHeader::Magic Client::magic("hanc");
Client::Client(int tunnelMtu, const char *deviceName, uint32_t serverIp,
int maxPolls, const char *passphrase, uid_t uid, gid_t gid,
bool changeEchoId, bool changeEchoSeq, uint32_t desiredIp)
: Worker(tunnelMtu, deviceName, false, uid, gid), auth(passphrase)
{
this->serverIp = serverIp;
this->clientIp = INADDR_NONE;
this->desiredIp = desiredIp;
this->maxPolls = maxPolls;
this->nextEchoId = Utility::rand();
this->changeEchoId = changeEchoId;
this->changeEchoSeq = changeEchoSeq;
this->nextEchoSequence = Utility::rand();
state = STATE_CLOSED;
}
Client::~Client()
{
}
void Client::sendConnectionRequest()
{
Server::ClientConnectData *connectData = (Server::ClientConnectData *)echoSendPayloadBuffer();
connectData->maxPolls = maxPolls;
connectData->desiredIp = desiredIp;
syslog(LOG_DEBUG, "sending connection request");
sendEchoToServer(TunnelHeader::TYPE_CONNECTION_REQUEST, sizeof(Server::ClientConnectData));
state = STATE_CONNECTION_REQUEST_SENT;
setTimeout(5000);
}
void Client::sendChallengeResponse(int dataLength)
{
if (dataLength != CHALLENGE_SIZE)
throw Exception("invalid challenge received");
state = STATE_CHALLENGE_RESPONSE_SENT;
syslog(LOG_DEBUG, "sending challenge response");
vector<char> challenge;
challenge.resize(dataLength);
memcpy(&challenge[0], echoReceivePayloadBuffer(), dataLength);
Auth::Response response = auth.getResponse(challenge);
memcpy(echoSendPayloadBuffer(), (char *)&response, sizeof(Auth::Response));
sendEchoToServer(TunnelHeader::TYPE_CHALLENGE_RESPONSE, sizeof(Auth::Response));
setTimeout(5000);
}
bool Client::handleEchoData(const TunnelHeader &header, int dataLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq)
{
if (realIp != serverIp || !reply)
return false;
if (header.magic != Server::magic)
return false;
switch (header.type)
{
case TunnelHeader::TYPE_RESET_CONNECTION:
syslog(LOG_DEBUG, "reset reveiced");
sendConnectionRequest();
return true;
case TunnelHeader::TYPE_SERVER_FULL:
if (state == STATE_CONNECTION_REQUEST_SENT)
{
throw Exception("server full");
}
break;
case TunnelHeader::TYPE_CHALLENGE:
if (state == STATE_CONNECTION_REQUEST_SENT)
{
syslog(LOG_DEBUG, "challenge received");
sendChallengeResponse(dataLength);
return true;
}
break;
case TunnelHeader::TYPE_CONNECTION_ACCEPT:
if (state == STATE_CHALLENGE_RESPONSE_SENT)
{
if (dataLength != sizeof(uint32_t))
{
throw Exception("invalid ip received");
return true;
}
syslog(LOG_INFO, "connection established");
uint32_t ip = ntohl(*(uint32_t *)echoReceivePayloadBuffer());
if (ip != clientIp)
{
if (privilegesDropped)
throw Exception("could not get the same ip address, so root privileges are required to change it");
clientIp = ip;
desiredIp = ip;
tun->setIp(ip, (ip & 0xffffff00) + 1, false);
}
state = STATE_ESTABLISHED;
dropPrivileges();
startPolling();
return true;
}
break;
case TunnelHeader::TYPE_CHALLENGE_ERROR:
if (state == STATE_CHALLENGE_RESPONSE_SENT)
{
throw Exception("password error");
}
break;
case TunnelHeader::TYPE_DATA:
if (state == STATE_ESTABLISHED)
{
handleDataFromServer(dataLength);
return true;
}
break;
}
syslog(LOG_DEBUG, "invalid packet type: %d, state: %d", header.type, state);
return true;
}
void Client::sendEchoToServer(int type, int dataLength)
{
if (maxPolls == 0 && state == STATE_ESTABLISHED)
setTimeout(KEEP_ALIVE_INTERVAL);
sendEcho(magic, type, dataLength, serverIp, false, nextEchoId, nextEchoSequence);
if (changeEchoId)
nextEchoId = nextEchoId + 38543; // some random prime
if (changeEchoSeq)
nextEchoSequence = nextEchoSequence + 38543; // some random prime
}
void Client::startPolling()
{
if (maxPolls == 0)
{
setTimeout(KEEP_ALIVE_INTERVAL);
}
else
{
for (int i = 0; i < maxPolls; i++)
sendEchoToServer(TunnelHeader::TYPE_POLL, 0);
setTimeout(POLL_INTERVAL);
}
}
void Client::handleDataFromServer(int dataLength)
{
if (dataLength == 0)
{
syslog(LOG_WARNING, "received empty data packet");
return;
}
sendToTun(dataLength);
if (maxPolls != 0)
sendEchoToServer(TunnelHeader::TYPE_POLL, 0);
}
void Client::handleTunData(int dataLength, uint32_t sourceIp, uint32_t destIp)
{
if (state != STATE_ESTABLISHED)
return;
sendEchoToServer(TunnelHeader::TYPE_DATA, dataLength);
}
void Client::handleTimeout()
{
switch (state)
{
case STATE_CONNECTION_REQUEST_SENT:
case STATE_CHALLENGE_RESPONSE_SENT:
sendConnectionRequest();
break;
case STATE_ESTABLISHED:
sendEchoToServer(TunnelHeader::TYPE_POLL, 0);
setTimeout(maxPolls == 0 ? KEEP_ALIVE_INTERVAL : POLL_INTERVAL);
break;
case STATE_CLOSED:
break;
}
}
void Client::run()
{
now = Time::now();
sendConnectionRequest();
Worker::run();
}
+77
View File
@@ -0,0 +1,77 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef CLIENT_H
#define CLIENT_H
#include "worker.h"
#include "auth.h"
#include <vector>
class Client : public Worker
{
public:
Client(int tunnelMtu, const char *deviceName, uint32_t serverIp,
int maxPolls, const char *passphrase, uid_t uid, gid_t gid,
bool changeEchoId, bool changeEchoSeq, uint32_t desiredIp);
virtual ~Client();
virtual void run();
static const Worker::TunnelHeader::Magic magic;
protected:
enum State
{
STATE_CLOSED,
STATE_CONNECTION_REQUEST_SENT,
STATE_CHALLENGE_RESPONSE_SENT,
STATE_ESTABLISHED
};
virtual bool handleEchoData(const TunnelHeader &header, int dataLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq);
virtual void handleTunData(int dataLength, uint32_t sourceIp, uint32_t destIp);
virtual void handleTimeout();
void handleDataFromServer(int length);
void startPolling();
void sendEchoToServer(int type, int dataLength);
void sendChallengeResponse(int dataLength);
void sendConnectionRequest();
Auth auth;
uint32_t serverIp;
uint32_t clientIp;
uint32_t desiredIp;
int maxPolls;
int pollTimeoutNr;
bool changeEchoId, changeEchoSeq;
uint16_t nextEchoId;
uint16_t nextEchoSequence;
State state;
};
#endif
+28
View File
@@ -0,0 +1,28 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#define MAX_BUFFERED_PACKETS 20
#define KEEP_ALIVE_INTERVAL (60 * 1000)
#define POLL_INTERVAL 2000
#define CHALLENGE_SIZE 20
//#define DEBUG_ONLY(a) a
#define DEBUG_ONLY(a)
+121
View File
@@ -0,0 +1,121 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "echo.h"
#include "exception.h"
#include <sys/socket.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>
#include <syslog.h>
#include <string.h>
typedef ip IpHeader;
Echo::Echo(int maxPayloadSize)
{
fd = socket(AF_INET, SOCK_RAW, IPPROTO_ICMP);
if (fd == -1)
throw Exception("creating icmp socket", true);
bufferSize = maxPayloadSize + headerSize();
sendBuffer = new char[bufferSize];
receiveBuffer = new char[bufferSize];
}
Echo::~Echo()
{
close(fd);
delete[] sendBuffer;
delete[] receiveBuffer;
}
int Echo::headerSize()
{
return sizeof(IpHeader) + sizeof(EchoHeader);
}
void Echo::send(int payloadLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq)
{
struct sockaddr_in target;
target.sin_family = AF_INET;
target.sin_addr.s_addr = htonl(realIp);
if (payloadLength + sizeof(IpHeader) + sizeof(EchoHeader) > bufferSize)
throw Exception("packet too big");
EchoHeader *header = (EchoHeader *)(sendBuffer + sizeof(IpHeader));
header->type = reply ? 0: 8;
header->code = 0;
header->id = htons(id);
header->seq = htons(seq);
header->chksum = 0;
header->chksum = icmpChecksum(sendBuffer + sizeof(IpHeader), payloadLength + sizeof(EchoHeader));
int result = sendto(fd, sendBuffer + sizeof(IpHeader), payloadLength + sizeof(EchoHeader), 0, (struct sockaddr *)&target, sizeof(struct sockaddr_in));
if (result == -1)
syslog(LOG_ERR, "error sending icmp packet: %s", strerror(errno));
}
int Echo::receive(uint32_t &realIp, bool &reply, uint16_t &id, uint16_t &seq)
{
struct sockaddr_in source;
int source_addr_len = sizeof(struct sockaddr_in);
int dataLength = recvfrom(fd, receiveBuffer, bufferSize, 0, (struct sockaddr *)&source, (socklen_t *)&source_addr_len);
if (dataLength == -1)
{
syslog(LOG_ERR, "error receiving icmp packet: %s", strerror(errno));
return -1;
}
if (dataLength < sizeof(IpHeader) + sizeof(EchoHeader))
return -1;
EchoHeader *header = (EchoHeader *)(receiveBuffer + sizeof(IpHeader));
if ((header->type != 0 && header->type != 8) || header->code != 0)
return -1;
realIp = ntohl(source.sin_addr.s_addr);
reply = header->type == 0;
id = ntohs(header->id);
seq = ntohs(header->seq);
return dataLength - sizeof(IpHeader) - sizeof(EchoHeader);
}
uint16_t Echo::icmpChecksum(const char *data, int length)
{
uint16_t *data16 = (uint16_t *)data;
uint32_t sum = 0;
for (sum = 0; length > 1; length -= 2)
sum += *data16++;
if (length == 1)
sum += *(unsigned char *)data16;
sum = (sum >> 16) + (sum & 0xffff);
sum += (sum >> 16);
return ~sum;
}
+58
View File
@@ -0,0 +1,58 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef ECHO_H
#define ECHO_H
#include <string>
#include <stdint.h>
class Echo
{
public:
Echo(int maxPayloadSize);
~Echo();
int getFd() { return fd; }
void send(int payloadLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq);
int receive(uint32_t &realIp, bool &reply, uint16_t &id, uint16_t &seq);
char *sendPayloadBuffer() { return sendBuffer + headerSize(); }
char *receivePayloadBuffer() { return receiveBuffer + headerSize(); }
static int headerSize();
protected:
struct EchoHeader
{
uint8_t type;
uint8_t code;
uint16_t chksum;
uint16_t id;
uint16_t seq;
}; // size = 8
uint16_t icmpChecksum(const char *data, int length);
int fd;
int bufferSize;
char *sendBuffer, *receiveBuffer;
};
#endif
+38
View File
@@ -0,0 +1,38 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "exception.h"
#include <errno.h>
#include <string.h>
using namespace std;
Exception::Exception(const char *msg)
{
this->msg = msg;
}
Exception::Exception(const char *msg, bool appendSystemError)
{
if (appendSystemError)
this->msg = string(msg) + ": " + strerror(errno);
else
this->msg = msg;
}
+31
View File
@@ -0,0 +1,31 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include <string>
class Exception
{
public:
Exception(const char *msg);
Exception(const char *msg, bool appendSystemError);
const char *errorMessage() const { return msg.c_str(); }
protected:
std::string msg;
};
+216
View File
@@ -0,0 +1,216 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "client.h"
#include "server.h"
#include "exception.h"
#include <stdio.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <pwd.h>
#include <netdb.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <syslog.h>
void usage()
{
printf(
"Hans - IP over ICMP version 0.4.1\n\n"
"RUN AS SERVER\n"
" hans -s network [-fvr] [-p password] [-u unprivileged_user] [-d tun_device] [-m reference_mtu] [-a ip]\n\n"
"RUN AS CLIENT\n"
" hans -c server [-fv] [-p password] [-u unprivileged_user] [-d tun_device] [-m reference_mtu] [-w polls]\n\n"
"ARGUMENTS\n"
" -s network Run as a server with the given network address for the virtual interface.\n"
" -c server Connect to a server.\n"
" -f Run in foreground.\n"
" -v Print debug information.\n"
" -r Respond to ordinary pings. Only in server mode.\n"
" -p password Use a password.\n"
" -u username Set the user under which the program should run.\n"
" -d device Use the given tun device.\n"
" -m mtu Use this mtu to calculate the tunnel mtu.\n"
" The generated echo packets will not be bigger than this value.\n"
" Has to be the same on client and server. Defaults to 1500.\n"
" -w polls Number of echo requests the client sends to the server for polling.\n"
" 0 disables polling. Defaults to 10.\n"
" -i Change the echo id for every echo request.\n"
" -q Change the echo sequence number for every echo request.\n"
" -a ip Try to get assigned the given tunnel ip address.\n"
);
}
int main(int argc, char *argv[])
{
const char *serverName;
const char *userName = NULL;
const char *password = "";
const char *device = NULL;
bool isServer = false;
bool isClient = false;
bool foreground = false;
int mtu = 1500;
int maxPolls = 10;
uint32_t network = INADDR_NONE;
uint32_t clientIp = INADDR_NONE;
bool answerPing = false;
uid_t uid = 0;
gid_t gid = 0;
bool changeEchoId = false;
bool changeEchoSeq = false;
bool verbose = false;
openlog(argv[0], LOG_PERROR, LOG_DAEMON);
int c;
while ((c = getopt(argc, argv, "fru:d:p:s:c:m:w:qiva:")) != -1)
{
switch(c) {
case 'f':
foreground = true;
break;
case 'u':
userName = optarg;
break;
case 'd':
device = optarg;
break;
case 'p':
password = strdup(optarg);
memset(optarg, 0, strlen(optarg));
break;
case 'c':
isClient = true;
serverName = optarg;
break;
case 's':
isServer = true;
network = ntohl(inet_addr(optarg));
if (network == INADDR_NONE)
printf("invalid network\n");
break;
case 'm':
mtu = atoi(optarg);
break;
case 'w':
maxPolls = atoi(optarg);
break;
case 'r':
answerPing = true;
break;
case 'q':
changeEchoSeq = true;
break;
case 'i':
changeEchoId = true;
break;
case 'v':
verbose = true;
break;
case 'a':
clientIp = ntohl(inet_addr(optarg));
break;
default:
usage();
return 1;
}
}
mtu -= Echo::headerSize() + Worker::headerSize();
if (mtu < 68)
{
// RFC 791: Every internet module must be able to forward a datagram of 68 octets without further fragmentation.
printf("mtu too small\n");
return 1;
}
if ((isClient == isServer) ||
(isServer && network == INADDR_NONE) ||
(maxPolls < 0 || maxPolls > 255) ||
(isServer && (changeEchoSeq || changeEchoId)))
{
usage();
return 1;
}
if (userName != NULL)
{
passwd *pw = getpwnam(userName);
if (pw != NULL)
{
uid = pw->pw_uid;
gid = pw->pw_gid;
}
else
{
syslog(LOG_ERR, "user not found");
return 1;
}
}
if (!verbose)
setlogmask(LOG_UPTO(LOG_INFO));
try
{
Worker *worker;
if (isServer)
{
worker = new Server(mtu, device, password, network, answerPing, uid, gid, 5000);
}
else
{
uint32_t serverIp = inet_addr(serverName);
if (serverIp == INADDR_NONE)
{
struct hostent* he = gethostbyname(serverName);
if (!he)
{
syslog(LOG_ERR, "gethostbyname: %s", hstrerror(h_errno));
return 1;
}
serverIp = *(uint32_t *)he->h_addr;
}
worker = new Client(mtu, device, ntohl(serverIp), maxPolls, password, uid, gid, changeEchoId, changeEchoSeq, clientIp);
}
if (!foreground)
{
syslog(LOG_INFO, "detaching from terminal");
daemon(0, 0);
}
worker->run();
}
catch (Exception e)
{
syslog(LOG_ERR, "%s", e.errorMessage());
return 1;
}
return 0;
}
+354
View File
@@ -0,0 +1,354 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "server.h"
#include "client.h"
#include "config.h"
#include "utility.h"
#include <string.h>
#include <arpa/inet.h>
#include <syslog.h>
using namespace std;
#define FIRST_ASSIGNED_IP_OFFSET 100
const Worker::TunnelHeader::Magic Server::magic("hans");
Server::Server(int tunnelMtu, const char *deviceName, const char *passphrase, uint32_t network, bool answerEcho, uid_t uid, gid_t gid, int pollTimeout)
: Worker(tunnelMtu, deviceName, answerEcho, uid, gid), auth(passphrase)
{
this->network = network & 0xffffff00;
this->pollTimeout = pollTimeout;
this->latestAssignedIpOffset = FIRST_ASSIGNED_IP_OFFSET - 1;
tun->setIp(this->network + 1, this->network + 2, true);
dropPrivileges();
}
Server::~Server()
{
}
void Server::handleUnknownClient(const TunnelHeader &header, int dataLength, uint32_t realIp, uint16_t echoId, uint16_t echoSeq)
{
ClientData client;
client.realIp = realIp;
client.maxPolls = 1;
pollReceived(&client, echoId, echoSeq);
if (header.type != TunnelHeader::TYPE_CONNECTION_REQUEST || dataLength != sizeof(ClientConnectData))
{
syslog(LOG_DEBUG, "invalid request %s", Utility::formatIp(realIp).c_str());
sendReset(&client);
return;
}
ClientConnectData *connectData = (ClientConnectData *)echoReceivePayloadBuffer();
client.maxPolls = connectData->maxPolls;
client.state = ClientData::STATE_NEW;
client.tunnelIp = reserveTunnelIp(connectData->desiredIp);
syslog(LOG_DEBUG, "new client: %s (%s)\n", Utility::formatIp(client.realIp).c_str(), Utility::formatIp(client.tunnelIp).c_str());
if (client.tunnelIp != 0)
{
client.challenge = auth.generateChallenge(CHALLENGE_SIZE);
sendChallenge(&client);
// add client to list
clientList.push_back(client);
clientRealIpMap[realIp] = clientList.size() - 1;
clientTunnelIpMap[client.tunnelIp] = clientList.size() - 1;
}
else
{
syslog(LOG_WARNING, "server full");
sendEchoToClient(&client, TunnelHeader::TYPE_SERVER_FULL, 0);
}
}
void Server::sendChallenge(ClientData *client)
{
syslog(LOG_DEBUG, "sending challenge to: %s\n", Utility::formatIp(client->realIp).c_str());
memcpy(echoSendPayloadBuffer(), &client->challenge[0], client->challenge.size());
sendEchoToClient(client, TunnelHeader::TYPE_CHALLENGE, client->challenge.size());
client->state = ClientData::STATE_CHALLENGE_SENT;
}
void Server::removeClient(ClientData *client)
{
syslog(LOG_DEBUG, "removing client: %s (%s)\n", Utility::formatIp(client->realIp).c_str(), Utility::formatIp(client->tunnelIp).c_str());
releaseTunnelIp(client->tunnelIp);
int nr = clientRealIpMap[client->realIp];
clientRealIpMap.erase(client->realIp);
clientTunnelIpMap.erase(client->tunnelIp);
clientList.erase(clientList.begin() + nr);
}
void Server::checkChallenge(ClientData *client, int length)
{
Auth::Response rightResponse = auth.getResponse(client->challenge);
if (length != sizeof(Auth::Response) || memcmp(&rightResponse, echoReceivePayloadBuffer(), length) != 0)
{
syslog(LOG_DEBUG, "wrong challenge response\n");
sendEchoToClient(client, TunnelHeader::TYPE_CHALLENGE_ERROR, 0);
removeClient(client);
return;
}
uint32_t *ip = (uint32_t *)echoSendPayloadBuffer();
*ip = htonl(client->tunnelIp);
sendEchoToClient(client, TunnelHeader::TYPE_CONNECTION_ACCEPT, sizeof(uint32_t));
client->state = ClientData::STATE_ESTABLISHED;
syslog(LOG_INFO, "connection established: %s", Utility::formatIp(client->realIp).c_str());
}
void Server::sendReset(ClientData *client)
{
syslog(LOG_DEBUG, "sending reset: %s", Utility::formatIp(client->realIp).c_str());
sendEchoToClient(client, TunnelHeader::TYPE_RESET_CONNECTION, 0);
}
bool Server::handleEchoData(const TunnelHeader &header, int dataLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq)
{
if (reply)
return false;
if (header.magic != Client::magic)
return false;
ClientData *client = getClientByRealIp(realIp);
if (client == NULL)
{
handleUnknownClient(header, dataLength, realIp, id, seq);
return true;
}
pollReceived(client, id, seq);
switch (header.type)
{
case TunnelHeader::TYPE_CONNECTION_REQUEST:
if (client->state == ClientData::STATE_CHALLENGE_SENT)
{
sendChallenge(client);
return true;
}
while (client->pollIds.size() > 1)
client->pollIds.pop();
syslog(LOG_DEBUG, "reconnecting %s", Utility::formatIp(realIp).c_str());
sendReset(client);
removeClient(client);
return true;
case TunnelHeader::TYPE_CHALLENGE_RESPONSE:
if (client->state == ClientData::STATE_CHALLENGE_SENT)
{
checkChallenge(client, dataLength);
return true;
}
break;
case TunnelHeader::TYPE_DATA:
if (client->state == ClientData::STATE_ESTABLISHED)
{
if (dataLength == 0)
{
syslog(LOG_WARNING, "received empty data packet");
return true;
}
sendToTun(dataLength);
return true;
}
break;
case TunnelHeader::TYPE_POLL:
return true;
}
syslog(LOG_DEBUG, "invalid packet from: %s, type: %d, state: %d", Utility::formatIp(realIp).c_str(), header.type, client->state);
return true;
}
Server::ClientData *Server::getClientByTunnelIp(uint32_t ip)
{
ClientIpMap::iterator clientMapIterator = clientTunnelIpMap.find(ip);
if (clientMapIterator == clientTunnelIpMap.end())
return NULL;
return &clientList[clientMapIterator->second];
}
Server::ClientData *Server::getClientByRealIp(uint32_t ip)
{
ClientIpMap::iterator clientMapIterator = clientRealIpMap.find(ip);
if (clientMapIterator == clientRealIpMap.end())
return NULL;
return &clientList[clientMapIterator->second];
}
void Server::handleTunData(int dataLength, uint32_t sourceIp, uint32_t destIp)
{
if (destIp == network + 255) // ignore broadcasts
return;
ClientData *client = getClientByTunnelIp(destIp);
if (client == NULL)
{
syslog(LOG_DEBUG, "unknown client: %s\n", Utility::formatIp(destIp).c_str());
return;
}
sendEchoToClient(client, TunnelHeader::TYPE_DATA, dataLength);
}
void Server::pollReceived(ClientData *client, uint16_t echoId, uint16_t echoSeq)
{
unsigned int maxSavedPolls = client->maxPolls != 0 ? client->maxPolls : 1;
client->pollIds.push(ClientData::EchoId(echoId, echoSeq));
if (client->pollIds.size() > maxSavedPolls)
client->pollIds.pop();
DEBUG_ONLY(printf("poll -> %d\n", client->pollIds.size()));
if (client->pendingPackets.size() > 0)
{
Packet &packet = client->pendingPackets.front();
memcpy(echoSendPayloadBuffer(), &packet.data[0], packet.data.size());
client->pendingPackets.pop();
DEBUG_ONLY(printf("pending packet: %d bytes\n", packet.data.size()));
sendEchoToClient(client, packet.type, packet.data.size());
}
client->lastActivity = now;
}
void Server::sendEchoToClient(ClientData *client, int type, int dataLength)
{
if (client->maxPolls == 0)
{
sendEcho(magic, type, dataLength, client->realIp, true, client->pollIds.front().id, client->pollIds.front().seq);
return;
}
if (client->pollIds.size() != 0)
{
ClientData::EchoId echoId = client->pollIds.front();
client->pollIds.pop();
DEBUG_ONLY(printf("sending -> %d\n", client->pollIds.size()));
sendEcho(magic, type, dataLength, client->realIp, true, echoId.id, echoId.seq);
return;
}
if (client->pendingPackets.size() == MAX_BUFFERED_PACKETS)
{
client->pendingPackets.pop();
syslog(LOG_WARNING, "packet dropped to %s", Utility::formatIp(client->tunnelIp).c_str());
}
DEBUG_ONLY(printf("packet queued: %d bytes\n", dataLength));
client->pendingPackets.push(Packet());
Packet &packet = client->pendingPackets.back();
packet.type = type;
packet.data.resize(dataLength);
memcpy(&packet.data[0], echoReceivePayloadBuffer(), dataLength);
}
void Server::releaseTunnelIp(uint32_t tunnelIp)
{
usedIps.erase(tunnelIp);
}
void Server::handleTimeout()
{
for (int i = 0; i < clientList.size(); i++)
{
ClientData *client = &clientList[i];
if (client->lastActivity + KEEP_ALIVE_INTERVAL * 2 < now)
{
syslog(LOG_DEBUG, "client timeout: %s\n", Utility::formatIp(client->realIp).c_str());
removeClient(client);
i--;
}
}
setTimeout(KEEP_ALIVE_INTERVAL);
}
uint32_t Server::reserveTunnelIp(uint32_t desiredIp)
{
if (desiredIp > network + 1 && desiredIp < network + 255 && !usedIps.count(desiredIp))
{
usedIps.insert(desiredIp);
return desiredIp;
}
bool ipAvailable = false;
for (int i = 0; i < 255 - FIRST_ASSIGNED_IP_OFFSET; i++)
{
latestAssignedIpOffset++;
if (latestAssignedIpOffset == 255)
latestAssignedIpOffset = FIRST_ASSIGNED_IP_OFFSET;
if (!usedIps.count(network + latestAssignedIpOffset))
{
ipAvailable = true;
break;
}
}
if (!ipAvailable)
return 0;
usedIps.insert(network + latestAssignedIpOffset);
return network + latestAssignedIpOffset;
}
void Server::run()
{
setTimeout(KEEP_ALIVE_INTERVAL);
Worker::run();
}
+126
View File
@@ -0,0 +1,126 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef SERVER_H
#define SERVER_H
#include "worker.h"
#include "auth.h"
#include <map>
#include <queue>
#include <vector>
#include <set>
class Server : public Worker
{
public:
Server(int tunnelMtu, const char *deviceName, const char *passphrase, uint32_t network, bool answerEcho, uid_t uid, gid_t gid, int pollTimeout);
virtual ~Server();
// change some time:
// struct __attribute__ ((__packed__)) ClientConnectData
struct ClientConnectData
{
uint8_t maxPolls;
uint32_t desiredIp;
};
static const Worker::TunnelHeader::Magic magic;
protected:
struct Packet
{
int type;
std::vector<char> data;
};
struct ClientData
{
enum State
{
STATE_NEW,
STATE_CHALLENGE_SENT,
STATE_ESTABLISHED
};
struct EchoId
{
EchoId(uint16_t id, uint16_t seq) { this->id = id; this->seq = seq; }
uint16_t id;
uint16_t seq;
};
uint32_t realIp;
uint32_t tunnelIp;
std::queue<Packet> pendingPackets;
int maxPolls;
std::queue<EchoId> pollIds;
Time lastActivity;
State state;
Auth::Challenge challenge;
};
typedef std::vector<ClientData> ClientList;
typedef std::map<uint32_t, int> ClientIpMap;
virtual bool handleEchoData(const TunnelHeader &header, int dataLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq);
virtual void handleTunData(int dataLength, uint32_t sourceIp, uint32_t destIp);
virtual void handleTimeout();
virtual void run();
void serveTun(ClientData *client);
void handleUnknownClient(const TunnelHeader &header, int dataLength, uint32_t realIp, uint16_t echoId, uint16_t echoSeq);
void removeClient(ClientData *client);
void sendChallenge(ClientData *client);
void checkChallenge(ClientData *client, int dataLength);
void sendReset(ClientData *client);
void sendEchoToClient(ClientData *client, int type, int dataLength);
void pollReceived(ClientData *client, uint16_t echoId, uint16_t echoSeq);
uint32_t reserveTunnelIp(uint32_t desiredIp);
void releaseTunnelIp(uint32_t tunnelIp);
ClientData *getClientByTunnelIp(uint32_t ip);
ClientData *getClientByRealIp(uint32_t ip);
Auth auth;
uint32_t network;
std::set<uint32_t> usedIps;
uint32_t latestAssignedIpOffset;
Time pollTimeout;
ClientList clientList;
ClientIpMap clientRealIpMap;
ClientIpMap clientTunnelIpMap;
};
#endif
+589
View File
@@ -0,0 +1,589 @@
/*
* sha1.cpp
*
* Copyright (C) 1998, 2009
* Paul E. Jones <paulej@packetizer.com>
* All Rights Reserved.
*
*****************************************************************************
* $Id: sha1.cpp 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This class implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* The Secure Hashing Standard, which uses the Secure Hashing
* Algorithm (SHA), produces a 160-bit message digest for a
* given data stream. In theory, it is highly improbable that
* two messages will produce the same message digest. Therefore,
* this algorithm can serve as a means of providing a "fingerprint"
* for a message.
*
* Portability Issues:
* SHA-1 is defined in terms of 32-bit "words". This code was
* written with the expectation that the processor has at least
* a 32-bit machine word size. If the machine word size is larger,
* the code should still function properly. One caveat to that
* is that the input functions taking characters and character arrays
* assume that only 8 bits of information are stored in each character.
*
* Caveats:
* SHA-1 is designed to work with messages less than 2^64 bits long.
* Although SHA-1 allows a message digest to be generated for
* messages of any number of bits less than 2^64, this implementation
* only works with messages with a length that is a multiple of 8
* bits.
*
*/
#include "sha1.h"
/*
* SHA1
*
* Description:
* This is the constructor for the sha1 class.
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
SHA1::SHA1()
{
Reset();
}
/*
* ~SHA1
*
* Description:
* This is the destructor for the sha1 class
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
SHA1::~SHA1()
{
// The destructor does nothing
}
/*
* Reset
*
* Description:
* This function will initialize the sha1 class member variables
* in preparation for computing a new message digest.
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::Reset()
{
Length_Low = 0;
Length_High = 0;
Message_Block_Index = 0;
H[0] = 0x67452301;
H[1] = 0xEFCDAB89;
H[2] = 0x98BADCFE;
H[3] = 0x10325476;
H[4] = 0xC3D2E1F0;
Computed = false;
Corrupted = false;
}
/*
* Result
*
* Description:
* This function will return the 160-bit message digest into the
* array provided.
*
* Parameters:
* message_digest_array: [out]
* This is an array of five unsigned integers which will be filled
* with the message digest that has been computed.
*
* Returns:
* True if successful, false if it failed.
*
* Comments:
*
*/
bool SHA1::Result(unsigned *message_digest_array)
{
int i; // Counter
if (Corrupted)
{
return false;
}
if (!Computed)
{
PadMessage();
Computed = true;
}
for(i = 0; i < 5; i++)
{
message_digest_array[i] = H[i];
}
return true;
}
/*
* Input
*
* Description:
* This function accepts an array of octets as the next portion of
* the message.
*
* Parameters:
* message_array: [in]
* An array of characters representing the next portion of the
* message.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::Input( const unsigned char *message_array,
unsigned length)
{
if (!length)
{
return;
}
if (Computed || Corrupted)
{
Corrupted = true;
return;
}
while(length-- && !Corrupted)
{
Message_Block[Message_Block_Index++] = (*message_array & 0xFF);
Length_Low += 8;
Length_Low &= 0xFFFFFFFF; // Force it to 32 bits
if (Length_Low == 0)
{
Length_High++;
Length_High &= 0xFFFFFFFF; // Force it to 32 bits
if (Length_High == 0)
{
Corrupted = true; // Message is too long
}
}
if (Message_Block_Index == 64)
{
ProcessMessageBlock();
}
message_array++;
}
}
/*
* Input
*
* Description:
* This function accepts an array of octets as the next portion of
* the message.
*
* Parameters:
* message_array: [in]
* An array of characters representing the next portion of the
* message.
* length: [in]
* The length of the message_array
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::Input( const char *message_array,
unsigned length)
{
Input((unsigned char *) message_array, length);
}
/*
* Input
*
* Description:
* This function accepts a single octets as the next message element.
*
* Parameters:
* message_element: [in]
* The next octet in the message.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::Input(unsigned char message_element)
{
Input(&message_element, 1);
}
/*
* Input
*
* Description:
* This function accepts a single octet as the next message element.
*
* Parameters:
* message_element: [in]
* The next octet in the message.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::Input(char message_element)
{
Input((unsigned char *) &message_element, 1);
}
/*
* operator<<
*
* Description:
* This operator makes it convenient to provide character strings to
* the SHA1 object for processing.
*
* Parameters:
* message_array: [in]
* The character array to take as input.
*
* Returns:
* A reference to the SHA1 object.
*
* Comments:
* Each character is assumed to hold 8 bits of information.
*
*/
SHA1& SHA1::operator<<(const char *message_array)
{
const char *p = message_array;
while(*p)
{
Input(*p);
p++;
}
return *this;
}
/*
* operator<<
*
* Description:
* This operator makes it convenient to provide character strings to
* the SHA1 object for processing.
*
* Parameters:
* message_array: [in]
* The character array to take as input.
*
* Returns:
* A reference to the SHA1 object.
*
* Comments:
* Each character is assumed to hold 8 bits of information.
*
*/
SHA1& SHA1::operator<<(const unsigned char *message_array)
{
const unsigned char *p = message_array;
while(*p)
{
Input(*p);
p++;
}
return *this;
}
/*
* operator<<
*
* Description:
* This function provides the next octet in the message.
*
* Parameters:
* message_element: [in]
* The next octet in the message
*
* Returns:
* A reference to the SHA1 object.
*
* Comments:
* The character is assumed to hold 8 bits of information.
*
*/
SHA1& SHA1::operator<<(const char message_element)
{
Input((unsigned char *) &message_element, 1);
return *this;
}
/*
* operator<<
*
* Description:
* This function provides the next octet in the message.
*
* Parameters:
* message_element: [in]
* The next octet in the message
*
* Returns:
* A reference to the SHA1 object.
*
* Comments:
* The character is assumed to hold 8 bits of information.
*
*/
SHA1& SHA1::operator<<(const unsigned char message_element)
{
Input(&message_element, 1);
return *this;
}
/*
* ProcessMessageBlock
*
* Description:
* This function will process the next 512 bits of the message
* stored in the Message_Block array.
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
* Many of the variable names in this function, especially the single
* character names, were used because those were the names used
* in the publication.
*
*/
void SHA1::ProcessMessageBlock()
{
const unsigned K[] = { // Constants defined for SHA-1
0x5A827999,
0x6ED9EBA1,
0x8F1BBCDC,
0xCA62C1D6
};
int t; // Loop counter
unsigned temp; // Temporary word value
unsigned W[80]; // Word sequence
unsigned A, B, C, D, E; // Word buffers
/*
* Initialize the first 16 words in the array W
*/
for(t = 0; t < 16; t++)
{
W[t] = ((unsigned) Message_Block[t * 4]) << 24;
W[t] |= ((unsigned) Message_Block[t * 4 + 1]) << 16;
W[t] |= ((unsigned) Message_Block[t * 4 + 2]) << 8;
W[t] |= ((unsigned) Message_Block[t * 4 + 3]);
}
for(t = 16; t < 80; t++)
{
W[t] = CircularShift(1,W[t-3] ^ W[t-8] ^ W[t-14] ^ W[t-16]);
}
A = H[0];
B = H[1];
C = H[2];
D = H[3];
E = H[4];
for(t = 0; t < 20; t++)
{
temp = CircularShift(5,A) + ((B & C) | ((~B) & D)) + E + W[t] + K[0];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = CircularShift(30,B);
B = A;
A = temp;
}
for(t = 20; t < 40; t++)
{
temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[1];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = CircularShift(30,B);
B = A;
A = temp;
}
for(t = 40; t < 60; t++)
{
temp = CircularShift(5,A) +
((B & C) | (B & D) | (C & D)) + E + W[t] + K[2];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = CircularShift(30,B);
B = A;
A = temp;
}
for(t = 60; t < 80; t++)
{
temp = CircularShift(5,A) + (B ^ C ^ D) + E + W[t] + K[3];
temp &= 0xFFFFFFFF;
E = D;
D = C;
C = CircularShift(30,B);
B = A;
A = temp;
}
H[0] = (H[0] + A) & 0xFFFFFFFF;
H[1] = (H[1] + B) & 0xFFFFFFFF;
H[2] = (H[2] + C) & 0xFFFFFFFF;
H[3] = (H[3] + D) & 0xFFFFFFFF;
H[4] = (H[4] + E) & 0xFFFFFFFF;
Message_Block_Index = 0;
}
/*
* PadMessage
*
* Description:
* According to the standard, the message must be padded to an even
* 512 bits. The first padding bit must be a '1'. The last 64 bits
* represent the length of the original message. All bits in between
* should be 0. This function will pad the message according to those
* rules by filling the message_block array accordingly. It will also
* call ProcessMessageBlock() appropriately. When it returns, it
* can be assumed that the message digest has been computed.
*
* Parameters:
* None.
*
* Returns:
* Nothing.
*
* Comments:
*
*/
void SHA1::PadMessage()
{
/*
* Check to see if the current message block is too small to hold
* the initial padding bits and length. If so, we will pad the
* block, process it, and then continue padding into a second block.
*/
if (Message_Block_Index > 55)
{
Message_Block[Message_Block_Index++] = 0x80;
while(Message_Block_Index < 64)
{
Message_Block[Message_Block_Index++] = 0;
}
ProcessMessageBlock();
while(Message_Block_Index < 56)
{
Message_Block[Message_Block_Index++] = 0;
}
}
else
{
Message_Block[Message_Block_Index++] = 0x80;
while(Message_Block_Index < 56)
{
Message_Block[Message_Block_Index++] = 0;
}
}
/*
* Store the message length as the last 8 octets
*/
Message_Block[56] = (Length_High >> 24) & 0xFF;
Message_Block[57] = (Length_High >> 16) & 0xFF;
Message_Block[58] = (Length_High >> 8) & 0xFF;
Message_Block[59] = (Length_High) & 0xFF;
Message_Block[60] = (Length_Low >> 24) & 0xFF;
Message_Block[61] = (Length_Low >> 16) & 0xFF;
Message_Block[62] = (Length_Low >> 8) & 0xFF;
Message_Block[63] = (Length_Low) & 0xFF;
ProcessMessageBlock();
}
/*
* CircularShift
*
* Description:
* This member function will perform a circular shifting operation.
*
* Parameters:
* bits: [in]
* The number of bits to shift (1-31)
* word: [in]
* The value to shift (assumes a 32-bit integer)
*
* Returns:
* The shifted value.
*
* Comments:
*
*/
unsigned SHA1::CircularShift(int bits, unsigned word)
{
return ((word << bits) & 0xFFFFFFFF) | ((word & 0xFFFFFFFF) >> (32-bits));
}
+89
View File
@@ -0,0 +1,89 @@
/*
* sha1.h
*
* Copyright (C) 1998, 2009
* Paul E. Jones <paulej@packetizer.com>
* All Rights Reserved.
*
*****************************************************************************
* $Id: sha1.h 12 2009-06-22 19:34:25Z paulej $
*****************************************************************************
*
* Description:
* This class implements the Secure Hashing Standard as defined
* in FIPS PUB 180-1 published April 17, 1995.
*
* Many of the variable names in this class, especially the single
* character names, were used because those were the names used
* in the publication.
*
* Please read the file sha1.cpp for more information.
*
*/
#ifndef _SHA1_H_
#define _SHA1_H_
class SHA1
{
public:
SHA1();
virtual ~SHA1();
/*
* Re-initialize the class
*/
void Reset();
/*
* Returns the message digest
*/
bool Result(unsigned *message_digest_array);
/*
* Provide input to SHA1
*/
void Input( const unsigned char *message_array,
unsigned length);
void Input( const char *message_array,
unsigned length);
void Input(unsigned char message_element);
void Input(char message_element);
SHA1& operator<<(const char *message_array);
SHA1& operator<<(const unsigned char *message_array);
SHA1& operator<<(const char message_element);
SHA1& operator<<(const unsigned char message_element);
private:
/*
* Process the next 512 bits of the message
*/
void ProcessMessageBlock();
/*
* Pads the current message block to 512 bits
*/
void PadMessage();
/*
* Performs a circular left shift operation
*/
inline unsigned CircularShift(int bits, unsigned word);
unsigned H[5]; // Message digest buffers
unsigned Length_Low; // Message length in bits
unsigned Length_High; // Message length in bits
unsigned char Message_Block[64]; // 512-bit message blocks
int Message_Block_Index; // Index into message block array
bool Computed; // Is the digest computed?
bool Corrupted; // Is the message digest corruped?
};
#endif
+14
View File
@@ -0,0 +1,14 @@
Copyright (C) 1998, 2009
Paul E. Jones <paulej@packetizer.com>
Freeware Public License (FPL)
This software is licensed as "freeware." Permission to distribute
this software in source and binary forms, including incorporation
into other products, is hereby granted without a fee. THIS SOFTWARE
IS PROVIDED 'AS IS' AND WITHOUT ANY EXPRESSED OR IMPLIED WARRANTIES,
INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
AND FITNESS FOR A PARTICULAR PURPOSE. THE AUTHOR SHALL NOT BE HELD
LIABLE FOR ANY DAMAGES RESULTING FROM THE USE OF THIS SOFTWARE, EITHER
DIRECTLY OR INDIRECTLY, INCLUDING, BUT NOT LIMITED TO, LOSS OF DATA
OR DATA BEING RENDERED INACCURATE.
+85
View File
@@ -0,0 +1,85 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "time.h"
const Time Time::ZERO = Time(0);
Time::Time(int ms)
{
tv.tv_sec = ms / 1000;
tv.tv_usec = (ms % 1000) * 1000;
}
Time Time::operator-(const Time &other) const
{
Time result;
result.tv.tv_sec = tv.tv_sec - other.tv.tv_sec;
result.tv.tv_usec = tv.tv_usec - other.tv.tv_usec;
if (result.tv.tv_usec < 0)
{
result.tv.tv_usec += 1000000;
result.tv.tv_sec -= 1;
}
return result;
}
Time Time::operator+(const Time &other) const
{
Time result;
result.tv.tv_sec = tv.tv_sec + other.tv.tv_sec;
result.tv.tv_usec = tv.tv_usec + other.tv.tv_usec;
if (result.tv.tv_usec >= 1000000)
{
result.tv.tv_usec -= 1000000;
result.tv.tv_sec += 1;
}
return result;
}
bool Time::operator==(const Time &other) const
{
return tv.tv_sec != other.tv.tv_sec ? false : tv.tv_usec == other.tv.tv_usec;
}
bool Time::operator!=(const Time &other) const
{
return tv.tv_sec != other.tv.tv_sec ? true : tv.tv_usec != other.tv.tv_usec;
}
bool Time::operator<(const Time &other) const
{
return tv.tv_sec != other.tv.tv_sec ? tv.tv_sec < other.tv.tv_sec : tv.tv_usec < other.tv.tv_usec;
}
bool Time::operator>(const Time &other) const
{
return tv.tv_sec != other.tv.tv_sec ? tv.tv_sec > other.tv.tv_sec : tv.tv_usec > other.tv.tv_usec;
}
Time Time::now()
{
Time result;
gettimeofday(&result.tv, 0);
return result;
}
+48
View File
@@ -0,0 +1,48 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TIME_H
#define TIME_H
#include <sys/time.h>
class Time
{
public:
Time() { tv.tv_sec = 0; tv.tv_usec = 0; };
Time(int ms);
timeval &getTimeval() { return tv; }
Time operator+(const Time &other) const;
Time operator-(const Time &other) const;
bool operator!=(const Time &other) const;
bool operator==(const Time &other) const;
bool operator<(const Time &other) const;
bool operator>(const Time &other) const;
static Time now();
static const Time ZERO;
protected:
timeval tv;
};
#endif
+113
View File
@@ -0,0 +1,113 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "tun.h"
#include "exception.h"
#include "utility.h"
#include <arpa/inet.h>
#include <netinet/in_systm.h>
#include <netinet/in.h>
#include <netinet/ip.h>
#include <syslog.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <stdio.h>
typedef ip IpHeader;
using namespace std;
Tun::Tun(const char *device, int mtu)
{
this->mtu = mtu;
if (device != NULL)
{
strncpy(this->device, device, VTUN_DEV_LEN);
this->device[VTUN_DEV_LEN] = 0;
}
else
this->device[0] = 0;
fd = tun_open(this->device);
if (fd == -1)
throw Exception("could not create tunnel device");
char cmdline[512];
snprintf(cmdline, sizeof(cmdline), "/sbin/ifconfig %s mtu %u", this->device, mtu);
if (system(cmdline) != 0)
syslog(LOG_ERR, "could not set tun device mtu");
}
Tun::~Tun()
{
tun_close(fd, device);
}
void Tun::setIp(uint32_t ip, uint32_t destIp, bool includeSubnet)
{
char cmdline[512];
string ips = Utility::formatIp(ip);
string destIps = Utility::formatIp(destIp);
#ifdef LINUX
snprintf(cmdline, sizeof(cmdline), "/sbin/ifconfig %s %s netmask 255.255.255.0", device, ips.c_str());
#else
snprintf(cmdline, sizeof(cmdline), "/sbin/ifconfig %s %s %s netmask 255.255.255.255", device, ips.c_str(), destIps.c_str());
#endif
if (system(cmdline) != 0)
syslog(LOG_ERR, "could not set tun device ip address");
#ifndef LINUX
if (includeSubnet)
{
snprintf(cmdline, sizeof(cmdline), "/sbin/route add %s/24 %s", destIps.c_str(), destIps.c_str());
if (system(cmdline) != 0)
syslog(LOG_ERR, "could not add route");
}
#endif
}
void Tun::write(const char *buffer, int length)
{
if (tun_write(fd, (char *)buffer, length) == -1)
syslog(LOG_ERR, "error writing %d bytes to tun: %s", length, strerror(errno));
}
int Tun::read(char *buffer)
{
int length = tun_read(fd, buffer, mtu);
if (length == -1)
syslog(LOG_ERR, "error reading from tun: %s", strerror(errno));
return length;
}
int Tun::read(char *buffer, uint32_t &sourceIp, uint32_t &destIp)
{
int length = read(buffer);
IpHeader *header = (IpHeader *)buffer;
sourceIp = ntohl(header->ip_src.s_addr);
destIp = ntohl(header->ip_dst.s_addr);
return length;
}
+49
View File
@@ -0,0 +1,49 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef TUN_H
#define TUN_H
#include "tun_dev.h"
#include <string>
#include <stdint.h>
class Tun
{
public:
Tun(const char *device, int mtu);
~Tun();
int getFd() { return fd; }
int read(char *buffer);
int read(char *buffer, uint32_t &sourceIp, uint32_t &destIp);
void write(const char *buffer, int length);
void setIp(uint32_t ip, uint32_t destIp, bool includeSubnet);
protected:
char device[VTUN_DEV_LEN];
int mtu;
int fd;
};
#endif
+27
View File
@@ -0,0 +1,27 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
#define VTUN_DEV_LEN 20
extern "C"
{
int tun_open(char *dev);
int tun_close(int fd, char *dev);
int tun_write(int fd, char *buf, int len);
int tun_read(int fd, char *buf, int len);
}
+44
View File
@@ -0,0 +1,44 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
#include "tunemu.h"
#include <syslog.h>
int tun_open(char *dev)
{
int fd = tunemu_open(dev);
if (fd < 0)
syslog(LOG_ERR, tunemu_error);
return fd;
}
int tun_close(int fd, char *dev)
{
return tunemu_close(fd);
}
int tun_write(int fd, char *buf, int len)
{
return tunemu_write(fd, buf, len);
}
int tun_read(int fd, char *buf, int len)
{
return tunemu_read(fd, buf, len);
}
+83
View File
@@ -0,0 +1,83 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
/*
* tun_dev.c,v 1.2.2.1.2.1 2006/11/16 04:04:23 mtbishop Exp
*/
/* #include "config.h" */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sys/ioctl.h>
#include <net/if_tun.h>
/* #include "vtun.h"
#include "lib.h" */
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
int tun_open(char *dev)
{
char tunname[14];
int i, fd = -1;
if( *dev ){
sprintf(tunname, "/dev/%s", dev);
fd = open(tunname, O_RDWR);
} else {
for(i=0; i < 255; i++){
sprintf(tunname, "/dev/tun%d", i);
/* Open device */
if( (fd=open(tunname, O_RDWR)) > 0 ){
sprintf(dev, "tun%d", i);
break;
}
}
}
if( fd > -1 ){
i=0;
/* Disable extended modes */
ioctl(fd, TUNSLMODE, &i);
ioctl(fd, TUNSIFHEAD, &i);
}
return fd;
}
int tun_close(int fd, char *dev)
{
return close(fd);
}
/* Read/write frames from/to TUN device */
int tun_write(int fd, char *buf, int len)
{
return write(fd, buf, len);
}
int tun_read(int fd, char *buf, int len)
{
return read(fd, buf, len);
}
+74
View File
@@ -0,0 +1,74 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
/*
* tun_dev.c,v 1.2.2.1.2.1 2006/11/16 04:04:40 mtbishop Exp
*/
/* #include "config.h" */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
/* #include "vtun.h"
#include "lib.h" */
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
int tun_open(char *dev)
{
char tunname[14];
int i, fd;
if( *dev ) {
sprintf(tunname, "/dev/%s", dev);
return open(tunname, O_RDWR);
}
for(i=0; i < 255; i++){
sprintf(tunname, "/dev/tun%d", i);
/* Open device */
if( (fd=open(tunname, O_RDWR)) > 0 ){
sprintf(dev, "tun%d", i);
return fd;
}
}
return -1;
}
int tun_close(int fd, char *dev)
{
return close(fd);
}
/* Read/write frames from TUN device */
int tun_write(int fd, char *buf, int len)
{
return write(fd, buf, len);
}
int tun_read(int fd, char *buf, int len)
{
return read(fd, buf, len);
}
+132
View File
@@ -0,0 +1,132 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
/*
* $Id: tun_dev.c,v 1.4 2006/12/11 10:45:35 mtbishop Exp $
*/
/* #include "config.h" */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <errno.h>
#include <sys/ioctl.h>
#include <sys/socket.h>
#include <linux/if.h>
/* #include "vtun.h"
#include "lib.h" */
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
static int tun_open_common0(char *dev, int istun)
{
char tunname[14];
int i, fd, err;
if( *dev ) {
sprintf(tunname, "/dev/%s", dev);
return open(tunname, O_RDWR);
}
sprintf(tunname, "/dev/%s", istun ? "tun" : "tap");
err = 0;
for(i=0; i < 255; i++){
sprintf(tunname + 8, "%d", i);
/* Open device */
if( (fd=open(tunname, O_RDWR)) > 0 ) {
strcpy(dev, tunname + 5);
return fd;
}
else if (errno != ENOENT)
err = errno;
else if (i) /* don't try all 256 devices */
break;
}
if (err)
errno = err;
return -1;
}
#ifdef HAVE_LINUX_IF_TUN_H /* New driver support */
#include <linux/if_tun.h>
#ifndef OTUNSETNOCSUM
/* pre 2.4.6 compatibility */
#define OTUNSETNOCSUM (('T'<< 8) | 200)
#define OTUNSETDEBUG (('T'<< 8) | 201)
#define OTUNSETIFF (('T'<< 8) | 202)
#define OTUNSETPERSIST (('T'<< 8) | 203)
#define OTUNSETOWNER (('T'<< 8) | 204)
#endif
static int tun_open_common(char *dev, int istun)
{
struct ifreq ifr;
int fd;
if ((fd = open("/dev/net/tun", O_RDWR)) < 0)
return tun_open_common0(dev, istun);
memset(&ifr, 0, sizeof(ifr));
ifr.ifr_flags = (istun ? IFF_TUN : IFF_TAP) | IFF_NO_PI;
if (*dev)
strncpy(ifr.ifr_name, dev, IFNAMSIZ);
if (ioctl(fd, TUNSETIFF, (void *) &ifr) < 0) {
if (errno == EBADFD) {
/* Try old ioctl */
if (ioctl(fd, OTUNSETIFF, (void *) &ifr) < 0)
goto failed;
} else
goto failed;
}
strcpy(dev, ifr.ifr_name);
return fd;
failed:
close(fd);
return -1;
}
#else
# define tun_open_common(dev, type) tun_open_common0(dev, type)
#endif /* New driver support */
int tun_open(char *dev) { return tun_open_common(dev, 1); }
int tap_open(char *dev) { return tun_open_common(dev, 0); }
int tun_close(int fd, char *dev) { return close(fd); }
int tap_close(int fd, char *dev) { return close(fd); }
/* Read/write frames from TUN device */
int tun_write(int fd, char *buf, int len) { return write(fd, buf, len); }
int tap_write(int fd, char *buf, int len) { return write(fd, buf, len); }
int tun_read(int fd, char *buf, int len) { return read(fd, buf, len); }
int tap_read(int fd, char *buf, int len) { return read(fd, buf, len); }
+100
View File
@@ -0,0 +1,100 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
/*
* tun_dev.c,v 1.3.2.1.2.1 2006/11/16 04:04:52 mtbishop Exp
*/
/* #include "config.h" */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/uio.h>
#include <sys/socket.h>
#include <sys/ioctl.h>
#include <net/if_tun.h>
/* #include "vtun.h"
#include "lib.h" */
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
int tun_open(char *dev)
{
char tunname[14];
int i, fd = -1;
if( *dev ){
sprintf(tunname, "/dev/%s", dev);
fd = open(tunname, O_RDWR);
} else {
for(i=0; i < 255; i++){
sprintf(tunname, "/dev/tun%d", i);
/* Open device */
if( (fd=open(tunname, O_RDWR)) > 0 ){
sprintf(dev, "tun%d", i);
break;
}
}
}
return fd;
}
int tun_close(int fd, char *dev)
{
return close(fd);
}
/* Read/write frames from TUN device */
int tun_write(int fd, char *buf, int len)
{
u_int32_t type = htonl(AF_INET);
struct iovec iv[2];
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = buf;
iv[1].iov_len = len;
return writev(fd, iv, 2);
}
int tun_read(int fd, char *buf, int len)
{
struct iovec iv[2];
u_int32_t type;
register int rlen;
iv[0].iov_base = &type;
iv[0].iov_len = sizeof(type);
iv[1].iov_base = buf;
iv[1].iov_len = len;
if( (rlen = readv(fd, iv, 2)) > 0 )
return rlen - sizeof(type);
else
return rlen;
}
+177
View File
@@ -0,0 +1,177 @@
/*
VTun - Virtual Tunnel over TCP/IP network.
Copyright (C) 1998-2000 Maxim Krasnyansky <max_mk@yahoo.com>
VTun has been derived from VPPP package by Maxim Krasnyansky.
This program 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 2 of the License, or
(at your option) any later version.
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.
*/
/*
* tun_dev.c,v 1.2.2.2.2.1 2006/11/16 04:05:18 mtbishop Exp
*/
/* #include "config.h" */
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <sys/time.h>
#include <sys/wait.h>
#include <syslog.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <sys/sockio.h>
#include <sys/ioctl.h>
#include <errno.h>
#include <signal.h>
#include <stropts.h>
#include <net/if.h>
#include <net/if_tun.h>
#ifdef HAVE_NETINET_IN_H
#include <netinet/in.h>
#endif
#ifdef HAVE_NETINET_IN_SYSTM_H
#include <netinet/in_systm.h>
#endif
#ifdef HAVE_NETINET_IP_H
#include <netinet/ip.h>
#endif
#ifdef HAVE_NETINET_TCP_H
#include <netinet/tcp.h>
#endif
/* #include "vtun.h"
#include "lib.h" */
static int ip_fd = -1;
/*
* Allocate TUN device, returns opened fd.
* Stores dev name in the first arg(must be large enough).
*/
int tun_open(char *dev)
{
int tun_fd, if_fd, muxid, ppa = -1;
struct ifreq ifr;
char *ptr;
if( *dev ){
ptr = dev;
while( *ptr && !isdigit((int)*ptr) ) ptr++;
ppa = atoi(ptr);
}
if( (ip_fd = open("/dev/udp", O_RDWR, 0)) < 0){
syslog(LOG_ERR, "Can't open /dev/ip");
return -1;
}
if( (tun_fd = open("/dev/tun", O_RDWR, 0)) < 0){
syslog(LOG_ERR, "Can't open /dev/tun");
return -1;
}
/* Assign a new PPA and get its unit number. */
if( (ppa = ioctl(tun_fd, TUNNEWPPA, ppa)) < 0){
syslog(LOG_ERR, "Can't assign new interface");
return -1;
}
if( (if_fd = open("/dev/tun", O_RDWR, 0)) < 0){
syslog(LOG_ERR, "Can't open /dev/tun (2)");
return -1;
}
if(ioctl(if_fd, I_PUSH, "ip") < 0){
syslog(LOG_ERR, "Can't push IP module");
return -1;
}
/* Assign ppa according to the unit number returned by tun device */
if(ioctl(if_fd, IF_UNITSEL, (char *)&ppa) < 0){
syslog(LOG_ERR, "Can't set PPA %d", ppa);
return -1;
}
if( (muxid = ioctl(ip_fd, I_PLINK, if_fd)) < 0){
syslog(LOG_ERR, "Can't link TUN device to IP");
return -1;
}
close(if_fd);
sprintf(dev, "tun%d", ppa);
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, dev);
ifr.ifr_ip_muxid = muxid;
if( ioctl(ip_fd, SIOCSIFMUXID, &ifr) < 0 ){
ioctl(ip_fd, I_PUNLINK, muxid);
syslog(LOG_ERR, "Can't set multiplexor id");
return -1;
}
return tun_fd;
}
/*
* Close TUN device.
*/
int tun_close(int fd, char *dev)
{
struct ifreq ifr;
memset(&ifr, 0, sizeof(ifr));
strcpy(ifr.ifr_name, dev);
if( ioctl(ip_fd, SIOCGIFFLAGS, &ifr) < 0 ){
syslog(LOG_ERR, "Can't get iface flags");
return 0;
}
if( ioctl(ip_fd, SIOCGIFMUXID, &ifr) < 0 ){
syslog(LOG_ERR, "Can't get multiplexor id");
return 0;
}
if( ioctl(ip_fd, I_PUNLINK, ifr.ifr_ip_muxid) < 0 ){
syslog(LOG_ERR, "Can't unlink interface");
return 0;
}
close(ip_fd); close(fd);
return 0;
}
int tun_write(int fd, char *buf, int len)
{
struct strbuf sbuf;
sbuf.len = len;
sbuf.buf = buf;
return putmsg(fd, NULL, &sbuf, 0) >=0 ? sbuf.len : -1;
}
int tun_read(int fd, char *buf, int len)
{
struct strbuf sbuf;
int f = 0;
sbuf.maxlen = len;
sbuf.buf = buf;
return getmsg(fd, NULL, &sbuf, &f) >=0 ? sbuf.len : -1;
}
+395
View File
@@ -0,0 +1,395 @@
/*
* tunemu - Tun device emulation for Darwin
*
* Copyright (c) 2009-2010 Friedrich Schöller <hans@schoeller.se>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#include "tunemu.h"
#include <sys/socket.h>
#include <unistd.h>
#include <sys/ioctl.h>
#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <util.h>
#include <pcap.h>
#include <stdarg.h>
#include <errno.h>
#include <stdint.h>
#include <stdint.h>
#include <ctype.h>
#include <fcntl.h>
#define PPPPROTO_CTL 1
#define PPP_IP 0x21
#define PPP_IPV6 0x57
#define SC_LOOP_TRAFFIC 0x00000200
#define PPPIOCNEWUNIT _IOWR('t', 62, int)
#define PPPIOCSFLAGS _IOW('t', 89, int)
#define PPPIOCSNPMODE _IOW('t', 75, struct npioctl)
#define PPPIOCATTCHAN _IOW('t', 56, int)
#define PPPIOCGCHAN _IOR('t', 55, int)
#define PPPIOCCONNECT _IOW('t', 58, int)
#define PPPIOCGUNIT _IOR('t', 86, int)
struct sockaddr_ppp
{
u_int8_t ppp_len;
u_int8_t ppp_family;
u_int16_t ppp_proto;
u_int32_t ppp_cookie;
};
enum NPmode
{
NPMODE_PASS,
NPMODE_DROP,
NPMODE_ERROR,
NPMODE_QUEUE
};
struct npioctl
{
int protocol;
enum NPmode mode;
};
#define PPP_KEXT_PATH "/System/Library/Extensions/PPP.kext"
#define ERROR_BUFFER_SIZE 1024
char tunemu_error[ERROR_BUFFER_SIZE];
static int pcap_use_count = 0;
static pcap_t *pcap = NULL;
static int data_buffer_length = 0;
static char *data_buffer = NULL;
static void tun_error(char *format, ...)
{
va_list vl;
va_start(vl, format);
vsnprintf(tunemu_error, ERROR_BUFFER_SIZE, format, vl);
va_end(vl);
}
static void tun_noerror(void)
{
*tunemu_error = 0;
}
static void closeall(void)
{
int fd = getdtablesize();
while (fd--)
close(fd);
open("/dev/null", O_RDWR, 0);
dup(0);
dup(0);
}
static int ppp_load_kext(void)
{
int pid = fork();
if (pid < 0)
{
tun_error("fork for ppp kext: %s", strerror(errno));
return -1;
}
if (pid == 0)
{
closeall();
execle("/sbin/kextload", "kextload", PPP_KEXT_PATH, NULL, NULL);
exit(1);
}
int status;
while (waitpid(pid, &status, 0) < 0)
{
if (errno == EINTR)
continue;
tun_error("waitpid for ppp kext: %s", strerror(errno));
return -1;
}
if (WEXITSTATUS(status) != 0)
{
tun_error("could not load ppp kext \"%s\"", PPP_KEXT_PATH);
return -1;
}
tun_noerror();
return 0;
}
static int ppp_new_instance(void)
{
// create ppp socket
int ppp_sockfd = socket(PF_PPP, SOCK_RAW, PPPPROTO_CTL);
if (ppp_sockfd < 0)
{
if (ppp_load_kext() < 0)
return -1;
ppp_sockfd = socket(PF_PPP, SOCK_RAW, PPPPROTO_CTL);
if (ppp_sockfd < 0)
{
tun_error("creating ppp socket: %s", strerror(errno));
return -1;
}
}
// connect to ppp procotol
struct sockaddr_ppp pppaddr;
pppaddr.ppp_len = sizeof(struct sockaddr_ppp);
pppaddr.ppp_family = AF_PPP;
pppaddr.ppp_proto = PPPPROTO_CTL;
pppaddr.ppp_cookie = 0;
if (connect(ppp_sockfd, (struct sockaddr *)&pppaddr, sizeof(struct sockaddr_ppp)) < 0)
{
tun_error("connecting ppp socket: %s", strerror(errno));
close(ppp_sockfd);
return -1;
}
tun_noerror();
return ppp_sockfd;
}
static int ppp_new_unit(int *unit_number)
{
int fd = ppp_new_instance();
if (fd < 0)
return -1;
// create ppp unit
if (ioctl(fd, PPPIOCNEWUNIT, unit_number) < 0)
{
tun_error("creating ppp unit: %s", strerror(errno));
close(fd);
return -1;
}
tun_noerror();
return fd;
}
static int ppp_setup_unit(int unit_fd)
{
// send traffic to program
int flags = SC_LOOP_TRAFFIC;
if (ioctl(unit_fd, PPPIOCSFLAGS, &flags) < 0)
{
tun_error("setting ppp loopback mode: %s", strerror(errno));
return -1;
}
// allow packets
struct npioctl npi;
npi.protocol = PPP_IP;
npi.mode = NPMODE_PASS;
if (ioctl(unit_fd, PPPIOCSNPMODE, &npi) < 0)
{
tun_error("starting ppp unit: %s", strerror(errno));
return -1;
}
tun_noerror();
return 0;
}
static int open_pcap(void)
{
if (pcap != NULL)
{
pcap_use_count++;
return 0;
}
char errbuf[PCAP_ERRBUF_SIZE];
pcap = pcap_open_live("lo0", BUFSIZ, 0, 1, errbuf);
pcap_use_count = 1;
if (pcap == NULL)
{
tun_error("opening pcap: %s", errbuf);
return -1;
}
tun_noerror();
return 0;
}
static void close_pcap(void)
{
if (pcap == NULL)
return;
pcap_use_count--;
if (pcap_use_count == 0)
{
pcap_close(pcap);
pcap = NULL;
}
}
static void allocate_data_buffer(int size)
{
if (data_buffer_length < size)
{
free(data_buffer);
data_buffer_length = size;
data_buffer = malloc(data_buffer_length);
}
}
static void make_device_name(tunemu_device device, int unit_number)
{
snprintf(device, sizeof(tunemu_device), "ppp%d", unit_number);
}
static int check_device_name(tunemu_device device)
{
if (strlen(device) < 4)
return -1;
int unit_number = atoi(device + 3);
if (unit_number < 0 || unit_number > 999)
return -1;
tunemu_device compare;
make_device_name(compare, unit_number);
if (strcmp(device, compare) != 0)
return -1;
return 0;
}
int tunemu_open(tunemu_device device)
{
int ppp_unit_number = -1;
if (device[0] != 0)
{
if (check_device_name(device) < 0)
{
tun_error("invalid device name \"%s\"", device);
return -1;
}
ppp_unit_number = atoi(device + 3);
}
int ppp_unit_fd = ppp_new_unit(&ppp_unit_number);
if (ppp_unit_fd < 0)
return -1;
if (ppp_setup_unit(ppp_unit_fd) < 0)
{
close(ppp_unit_fd);
return -1;
}
if (open_pcap() < 0)
{
close(ppp_unit_fd);
return -1;
}
make_device_name(device, ppp_unit_number);
return ppp_unit_fd;
}
int tunemu_close(int ppp_sockfd)
{
int ret = close(ppp_sockfd);
if (ret == 0)
close_pcap();
return ret;
}
int tunemu_read(int ppp_sockfd, char *buffer, int length)
{
allocate_data_buffer(length + 2);
length = read(ppp_sockfd, data_buffer, length + 2);
if (length < 0)
{
tun_error("reading packet: %s", strerror(errno));
return length;
}
tun_noerror();
length -= 2;
if (length < 0)
return 0;
memcpy(buffer, data_buffer + 2, length);
return length;
}
int tunemu_write(int ppp_sockfd, char *buffer, int length)
{
allocate_data_buffer(length + 4);
data_buffer[0] = 0x02;
data_buffer[1] = 0x00;
data_buffer[2] = 0x00;
data_buffer[3] = 0x00;
memcpy(data_buffer + 4, buffer, length);
if (pcap == NULL)
{
tun_error("pcap not open");
return -1;
}
length = pcap_inject(pcap, data_buffer, length + 4);
if (length < 0)
{
tun_error("injecting packet: %s", pcap_geterr(pcap));
return length;
}
tun_noerror();
length -= 4;
if (length < 0)
return 0;
return length;
}
+41
View File
@@ -0,0 +1,41 @@
/*
* tunemu - Tun device emulation for Darwin
*
* Copyright (c) 2009-2010 Friedrich Schöller <hans@schoeller.se>
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*
*/
#ifndef TUNEMU_H
#define TUNEMU_H
typedef char tunemu_device[7];
extern char tunemu_error[];
int tunemu_open(tunemu_device dev);
int tunemu_close(int fd);
int tunemu_read(int fd, char *buffer, int length);
int tunemu_write(int fd, char *buffer, int length);
#endif
+43
View File
@@ -0,0 +1,43 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "utility.h"
#include <stdlib.h>
#include <stdio.h>
using namespace std;
string Utility::formatIp(uint32_t ip)
{
char buffer[16];
sprintf(buffer, "%d.%d.%d.%d", (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, ip & 0xff);
return buffer;
}
int Utility::rand()
{
static bool init = false;
if (!init)
{
init = true;
srand(time(NULL));
}
return ::rand();
}
+33
View File
@@ -0,0 +1,33 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef UTILITY_H
#define UTILITY_H
#include <string>
#include <stdint.h>
class Utility
{
public:
static std::string formatIp(uint32_t ip);
static int rand();
};
#endif
+198
View File
@@ -0,0 +1,198 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#include "worker.h"
#include "tun.h"
#include "exception.h"
#include "config.h"
#include <string.h>
#include <syslog.h>
#include <unistd.h>
using namespace std;
Worker::TunnelHeader::Magic::Magic(const char *magic)
{
memset(data, 0, sizeof(data));
strncpy(data, magic, sizeof(data));
}
bool Worker::TunnelHeader::Magic::operator==(const Magic &other) const
{
return memcmp(data, other.data, sizeof(data)) == 0;
}
bool Worker::TunnelHeader::Magic::operator!=(const Magic &other) const
{
return memcmp(data, other.data, sizeof(data)) != 0;
}
Worker::Worker(int tunnelMtu, const char *deviceName, bool answerEcho, uid_t uid, gid_t gid)
{
this->tunnelMtu = tunnelMtu;
this->answerEcho = answerEcho;
this->uid = uid;
this->gid = gid;
this->privilegesDropped = false;
echo = NULL;
tun = NULL;
try
{
echo = new Echo(tunnelMtu + sizeof(TunnelHeader));
tun = new Tun(deviceName, tunnelMtu);
}
catch (...)
{
delete echo;
delete tun;
throw;
}
}
Worker::~Worker()
{
delete echo;
delete tun;
}
void Worker::sendEcho(const TunnelHeader::Magic &magic, int type, int length, uint32_t realIp, bool reply, uint16_t id, uint16_t seq)
{
if (length > payloadBufferSize())
throw Exception("packet too big");
TunnelHeader *header = (TunnelHeader *)echo->sendPayloadBuffer();
header->magic = magic;
header->type = type;
DEBUG_ONLY(printf("sending: type %d, length %d, id %d, seq %d\n", type, length, id, seq));
echo->send(length + sizeof(TunnelHeader), realIp, reply, id, seq);
}
void Worker::sendToTun(int length)
{
tun->write(echoReceivePayloadBuffer(), length);
}
void Worker::setTimeout(Time delta)
{
nextTimeout = now + delta;
}
void Worker::run()
{
now = Time::now();
alive = true;
int maxFd = echo->getFd() > tun->getFd() ? echo->getFd() : tun->getFd();
while (alive)
{
fd_set fs;
Time timeout;
FD_ZERO(&fs);
FD_SET(tun->getFd(), &fs);
FD_SET(echo->getFd(), &fs);
if (nextTimeout != Time::ZERO)
{
timeout = nextTimeout - now;
if (timeout < Time::ZERO)
timeout = Time::ZERO;
}
// wait for data or timeout
int result = select(maxFd + 1 , &fs, NULL, NULL, nextTimeout != Time::ZERO ? &timeout.getTimeval() : NULL);
if (result == -1)
throw Exception("select", true);
now = Time::now();
// timeout
if (result == 0)
{
nextTimeout = Time::ZERO;
handleTimeout();
continue;
}
// icmp data
if (FD_ISSET(echo->getFd(), &fs))
{
bool reply;
uint16_t id, seq;
uint32_t ip;
int dataLength = echo->receive(ip, reply, id, seq);
if (dataLength != -1)
{
bool valid = dataLength >= sizeof(TunnelHeader);
if (valid)
{
TunnelHeader *header = (TunnelHeader *)echo->receivePayloadBuffer();
DEBUG_ONLY(printf("received: type %d, length %d, id %d, seq %d\n", header->type, dataLength - sizeof(TunnelHeader), id, seq));
valid = handleEchoData(*header, dataLength - sizeof(TunnelHeader), ip, reply, id, seq);
}
if (!valid && !reply && answerEcho)
{
memcpy(echo->sendPayloadBuffer(), echo->receivePayloadBuffer(), dataLength);
echo->send(dataLength, ip, true, id, seq);
}
}
}
// data from tun
if (FD_ISSET(tun->getFd(), &fs))
{
uint32_t sourceIp, destIp;
int dataLength = tun->read(echoSendPayloadBuffer(), sourceIp, destIp);
if (dataLength == 0)
throw Exception("tunnel closed");
if (dataLength != -1)
handleTunData(dataLength, sourceIp, destIp);
}
}
}
void Worker::dropPrivileges()
{
if (uid <= 0 || privilegesDropped)
return;
syslog(LOG_INFO, "dropping privileges");
if (setgid(gid) == -1)
throw Exception("setgid", true);
if (setuid(uid) == -1)
throw Exception("setuid", true);
privilegesDropped = true;
}
+104
View File
@@ -0,0 +1,104 @@
/*
* Hans - IP over ICMP
* Copyright (C) 2009 Friedrich Schöller <hans@schoeller.se>
*
* This program 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
* (at your option) any later version.
*
* 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. If not, see <http://www.gnu.org/licenses/>.
*
*/
#ifndef WORKER_H
#define WORKER_H
#include "time.h"
#include "echo.h"
#include "tun.h"
#include <string>
class Worker
{
public:
Worker(int tunnelMtu, const char *deviceName, bool answerEcho, uid_t uid, gid_t gid);
virtual ~Worker();
virtual void run();
static int headerSize() { return sizeof(TunnelHeader); }
protected:
struct TunnelHeader
{
struct Magic
{
Magic() { }
Magic(const char *magic);
bool operator==(const Magic &other) const;
bool operator!=(const Magic &other) const;
char data[4];
};
Magic magic;
uint8_t type;
enum Type
{
TYPE_RESET_CONNECTION = 1,
TYPE_CONNECTION_REQUEST = 2,
TYPE_CHALLENGE = 3,
TYPE_CHALLENGE_RESPONSE = 4,
TYPE_CONNECTION_ACCEPT = 5,
TYPE_CHALLENGE_ERROR = 6,
TYPE_DATA = 7,
TYPE_POLL = 8,
TYPE_SERVER_FULL = 9
};
}; // size = 5
virtual bool handleEchoData(const TunnelHeader &header, int dataLength, uint32_t realIp, bool reply, uint16_t id, uint16_t seq) { return true; }
virtual void handleTunData(int dataLength, uint32_t sourceIp, uint32_t destIp) { } // to echoSendPayloadBuffer
virtual void handleTimeout() { }
void sendEcho(const TunnelHeader::Magic &magic, int type, int length, uint32_t realIp, bool reply, uint16_t id, uint16_t seq);
void sendToTun(int length); // from echoReceivePayloadBuffer
void setTimeout(Time delta);
char *echoSendPayloadBuffer() { return echo->sendPayloadBuffer() + sizeof(TunnelHeader); }
char *echoReceivePayloadBuffer() { return echo->receivePayloadBuffer() + sizeof(TunnelHeader); }
int payloadBufferSize() { return tunnelMtu; }
void dropPrivileges();
Echo *echo;
Tun *tun;
bool alive;
bool answerEcho;
int tunnelMtu;
int maxTunnelHeaderSize;
uid_t uid;
gid_t gid;
bool privilegesDropped;
Time now;
private:
int readIcmpData(int *realIp, int *id, int *seq);
Time nextTimeout;
};
#endif