minor changes
[anytun.git] / anytun.cpp
blob2a0ee073baa987055db59d5af39f9bab9cd854a1
1 /*
2 * anytun
4 * The secure anycast tunneling protocol (satp) defines a protocol used
5 * for communication between any combination of unicast and anycast
6 * tunnel endpoints. It has less protocol overhead than IPSec in Tunnel
7 * mode and allows tunneling of every ETHER TYPE protocol (e.g.
8 * ethernet, ip, arp ...). satp directly includes cryptography and
9 * message authentication based on the methodes used by SRTP. It is
10 * intended to deliver a generic, scaleable and secure solution for
11 * tunneling and relaying of packets of any protocol.
14 * Copyright (C) 2007 anytun.org <satp@wirdorange.org>
16 * This program is free software; you can redistribute it and/or modify
17 * it under the terms of the GNU General Public License version 2
18 * as published by the Free Software Foundation.
20 * This program is distributed in the hope that it will be useful,
21 * but WITHOUT ANY WARRANTY; without even the implied warranty of
22 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
23 * GNU General Public License for more details.
25 * You should have received a copy of the GNU General Public License
26 * along with this program (see the file COPYING included with this
27 * distribution); if not, write to the Free Software Foundation, Inc.,
28 * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
31 #include <iostream>
32 #include <poll.h>
34 #include <gcrypt.h> // for thread safe libgcrypt initialisation
35 #include <cerrno> // for ENOMEM
37 #include "datatypes.h"
39 #include "log.h"
40 #include "buffer.h"
41 #include "plainPacket.h"
42 #include "encryptedPacket.h"
43 #include "cypher.h"
44 #include "keyDerivation.h"
45 #include "authAlgo.h"
46 #include "authTag.h"
47 #include "cypherFactory.h"
48 #include "authAlgoFactory.h"
49 #include "signalController.h"
50 #include "packetSource.h"
51 #include "tunDevice.h"
52 #include "options.h"
53 #include "seqWindow.h"
54 #include "connectionList.h"
56 #include "syncQueue.h"
57 #include "syncSocketHandler.h"
58 #include "syncListenSocket.h"
60 #include "syncSocket.h"
61 #include "syncClientSocket.h"
62 #include "syncCommand.h"
64 #include "threadParam.h"
66 #define PAYLOAD_TYPE_TAP 0x6558
67 #define PAYLOAD_TYPE_TUN 0x0800
69 #define SESSION_KEYLEN_AUTH 20
70 #define SESSION_KEYLEN_ENCR 16
71 #define SESSION_KEYLEN_SALT 14
73 void createConnection(const std::string & remote_host , u_int16_t remote_port, ConnectionList & cl, u_int16_t seqSize, SyncQueue & queue)
75 uint8_t key[] = {
76 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
77 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p'
80 uint8_t salt[] = {
81 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
82 'i', 'j', 'k', 'l', 'm', 'n'
85 SeqWindow * seq= new SeqWindow(seqSize);
86 seq_nr_t seq_nr_=0;
87 KeyDerivation * kd = new KeyDerivation;
88 kd->init(Buffer(key, sizeof(key)), Buffer(salt, sizeof(salt)));
89 cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_host << ":" << remote_port;
90 ConnectionParam connparam ( (*kd), (*seq), seq_nr_, remote_host, remote_port);
91 cl.addConnection(connparam,0);
92 SyncCommand sc (cl,0);
93 queue.push(sc);
97 void addPacketAuthTag(EncryptedPacket& pack, AuthAlgo* a, ConnectionParam& conn)
99 AuthTag at = a->calc(pack);
100 pack.setAuthTag( at );
103 bool checkPacketAuthTag(EncryptedPacket& pack, AuthAlgo* a, ConnectionParam & conn)
105 // check auth_tag and remove it
106 AuthTag at = pack.getAuthTag();
107 return (at == a->calc(pack));
110 bool checkPacketSeqNr(EncryptedPacket& pack,ConnectionParam& conn)
112 // compare sender_id and seq with window
113 if(conn.seq_window_.hasSeqNr(pack.getSenderId(), pack.getSeqNr()))
115 cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_host_<<":"<< conn.remote_port_
116 << " seq:"<<pack.getSeqNr() << " sid: "<<pack.getSenderId();
117 return false;
120 conn.seq_window_.addSeqNr(pack.getSenderId(), pack.getSeqNr());
121 return true;
124 void* sender(void* p)
126 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
128 std::auto_ptr<Cypher> c(CypherFactory::create(param->opt.getCypher()));
129 std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(param->opt.getAuthAlgo()) );
131 PlainPacket plain_packet(1600); // TODO: fix me... mtu size
132 EncryptedPacket packet(1600);
134 // TODO: hardcoded keySize!!!
135 Buffer session_key(SESSION_KEYLEN_ENCR);
136 Buffer session_salt(SESSION_KEYLEN_SALT);
137 Buffer session_auth_key(SESSION_KEYLEN_AUTH);
139 //TODO replace mux
140 u_int16_t mux = 0;
141 while(1)
143 plain_packet.setLength( plain_packet.getMaxLength()); // Q@NINE wtf???
145 // read packet from device
146 u_int32_t len = param->dev.read(plain_packet);
147 plain_packet.setLength(len);
148 packet.setLength( len );
149 if( param->cl.empty())
150 continue;
151 ConnectionMap::iterator cit = param->cl.getConnection(mux);
152 if(cit==param->cl.getEnd())
153 continue;
154 ConnectionParam & conn = cit->second;
156 // add payload type
157 if(param->dev.getType() == TunDevice::TYPE_TUN)
158 plain_packet.setPayloadType(PAYLOAD_TYPE_TUN);
159 else if(param->dev.getType() == TunDevice::TYPE_TAP)
160 plain_packet.setPayloadType(PAYLOAD_TYPE_TAP);
161 else
162 plain_packet.setPayloadType(0);
164 // generate packet-key
165 conn.kd_.generate(LABEL_SATP_ENCRYPTION, conn.seq_nr_, session_key);
166 conn.kd_.generate(LABEL_SATP_SALT, conn.seq_nr_, session_salt);
167 c->setKey(session_key);
168 c->setSalt(session_salt);
170 // encrypt packet
171 c->encrypt(plain_packet, packet, conn.seq_nr_, param->opt.getSenderId());
173 packet.setHeader(conn.seq_nr_, param->opt.getSenderId(), mux);
174 conn.seq_nr_++;
176 // TODO: activate authentication
177 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, packet.getSeqNr(), session_auth_key);
178 // a->setKey(session_auth_key);
179 // addPacketAuthTag(packet, a.get(), conn);
180 param->src.send(packet, conn.remote_host_, conn.remote_port_);
182 pthread_exit(NULL);
185 void* syncConnector(void* p )
187 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
189 SocketHandler h;
190 SyncClientSocket sock(h,param->cl);
191 // sock.EnableSSL();
192 sock.Open( param->connto.host, param->connto.port);
193 h.Add(&sock);
194 while (h.GetCount())
196 h.Select();
198 pthread_exit(NULL);
201 void* syncListener(void* p )
203 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
205 SyncSocketHandler h(param->queue);
206 SyncListenSocket<SyncSocket,ConnectionList> l(h,param->cl);
208 if (l.Bind(param->opt.getLocalSyncPort()))
209 pthread_exit(NULL);
210 Utility::ResolveLocal(); // resolve local hostname
211 h.Add(&l);
212 h.Select(1,0);
213 while (1)
215 h.Select(1,0);
219 void* receiver(void* p)
221 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
223 std::auto_ptr<Cypher> c( CypherFactory::create(param->opt.getCypher()) );
224 std::auto_ptr<AuthAlgo> a( AuthAlgoFactory::create(param->opt.getAuthAlgo()) );
226 EncryptedPacket packet(1600); // TODO: dynamic mtu size
227 PlainPacket plain_packet(1600);
229 // TODO: hardcoded keysize!!!
230 Buffer session_key(SESSION_KEYLEN_SALT);
231 Buffer session_salt(SESSION_KEYLEN_SALT);
232 Buffer session_auth_key(SESSION_KEYLEN_AUTH);
234 while(1)
236 string remote_host;
237 u_int16_t remote_port;
238 packet.setLength( packet.getMaxLength() ); // Q@NINE wtf???
239 plain_packet.setLength( plain_packet.getMaxLength() ); // Q@NINE wtf???
240 // u_int16_t sid = 0, seq = 0;
242 // read packet from socket
243 u_int32_t len = param->src.recv(packet, remote_host, remote_port);
244 packet.setLength(len);
246 // TODO: check auth tag first
247 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, packet.getSeqNr(), session_auth_key);
248 // a->setKey( session_auth_key );
249 // if(!checkPacketAuthTag(packet, a.get(), conn))
250 // continue;
253 // autodetect peer
254 if(param->opt.getRemoteAddr() == "" && param->cl.empty())
256 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_host << ":" << remote_port;
257 createConnection(remote_host, remote_port, param->cl,param->opt.getSeqWindowSize(),param->queue);
260 // TODO: Add multi connection support here
261 ConnectionParam & conn = param->cl.getConnection(0)->second;
263 //Allow dynamic IP changes
264 //TODO: add command line option to turn this off
265 if (remote_host != conn.remote_host_ || remote_port != conn.remote_port_)
267 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host ip changed " << remote_host << ":" << remote_port;
268 conn.remote_host_=remote_host;
269 conn.remote_port_=remote_port;
270 SyncCommand sc (param->cl,0);
271 param->queue.push(sc);
274 // Replay Protection
275 if (!checkPacketSeqNr(packet, conn))
276 continue;
278 // generate packet-key
279 conn.kd_.generate(LABEL_SATP_ENCRYPTION, packet.getSeqNr(), session_key);
280 conn.kd_.generate(LABEL_SATP_SALT, packet.getSeqNr(), session_salt);
281 c->setKey(session_key);
282 c->setSalt(session_salt);
284 // decrypt packet
285 c->decrypt(packet, plain_packet);
287 // check payload_type
288 if((param->dev.getType() == TunDevice::TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN) ||
289 (param->dev.getType() == TunDevice::TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP))
290 continue;
292 // write it on the device
293 param->dev.write(plain_packet);
295 pthread_exit(NULL);
298 #define MIN_GCRYPT_VERSION "1.2.3"
299 #define GCRYPT_SEC_MEM 32768 // 32k secure memory
300 // make libgcrypt thread safe
301 extern "C" {
302 GCRY_THREAD_OPTION_PTHREAD_IMPL;
305 bool initLibGCrypt()
307 // make libgcrypt thread safe
308 gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
310 gcry_error_t err;
311 // No other library has already initialized libgcrypt.
312 if( !gcry_control(GCRYCTL_ANY_INITIALIZATION_P) )
314 if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) {
315 cLog.msg(Log::PRIO_ERR) << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION;
316 std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl;
317 return false;
320 // do NOT allocate a pool uof secure memory! Q@NINE?
321 // this is NOT thread safe! ??????????????????????????????????
323 /* Allocate a pool of 16k secure memory. This also drops priviliges
324 * on some systems. */
325 err = gcry_control(GCRYCTL_INIT_SECMEM, GCRYPT_SEC_MEM, 0);
326 if( err )
328 cLog.msg(Log::PRIO_ERR) << "Failed to allocate " << GCRYPT_SEC_MEM << " bytes of secure memory: " << gpg_strerror( err );
329 std::cout << "Failed to allocate " << GCRYPT_SEC_MEM << " bytes of secure memory: " << gpg_strerror( err ) << std::endl;
330 return false;
333 /* Tell Libgcrypt that initialization has completed. */
334 err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
335 if( err ) {
336 cLog.msg(Log::PRIO_ERR) << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err );
337 std::cout << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err ) << std::endl;
338 return false;
341 cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished";
343 return true;
346 int main(int argc, char* argv[])
348 std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
349 Options opt;
350 if(!opt.parse(argc, argv))
352 opt.printUsage();
353 exit(-1);
355 cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
357 SignalController sig;
358 sig.init();
359 std::string dev_type(opt.getDevType());
360 TunDevice dev(opt.getDevName().c_str(), dev_type=="" ? NULL : dev_type.c_str(), opt.getIfconfigParamLocal().c_str(), opt.getIfconfigParamRemoteNetmask().c_str());
362 PacketSource* src;
363 if(opt.getLocalAddr() == "")
364 src = new UDPPacketSource(opt.getLocalPort());
365 else
366 src = new UDPPacketSource(opt.getLocalAddr(), opt.getLocalPort());
368 ConnectionList cl;
369 ConnectToList connect_to = opt.getConnectTo();
370 SyncQueue queue;
372 if(opt.getRemoteAddr() != "")
373 createConnection(opt.getRemoteAddr(),opt.getRemotePort(),cl,opt.getSeqWindowSize(), queue);
375 ThreadParam p(opt, dev, *src, cl, queue,*(new OptionConnectTo()));
377 cLog.msg(Log::PRIO_NOTICE) << "dev created (opened)";
378 cLog.msg(Log::PRIO_NOTICE) << "dev opened - actual name is '" << p.dev.getActualName() << "'";
379 cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << p.dev.getTypeString() << "'";
381 if(!initLibGCrypt())
382 return -1;
384 pthread_t senderThread;
385 pthread_create(&senderThread, NULL, sender, &p);
386 pthread_t receiverThread;
387 pthread_create(&receiverThread, NULL, receiver, &p);
388 pthread_t syncListenerThread;
390 if ( opt.getLocalSyncPort())
391 pthread_create(&syncListenerThread, NULL, syncListener, &p);
393 std::list<pthread_t> connectThreads;
394 for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it)
396 connectThreads.push_back(pthread_t());
397 ThreadParam * point = new ThreadParam(opt, dev, *src, cl, queue,*it);
398 pthread_create(& connectThreads.back(), NULL, syncConnector, point);
401 int ret = sig.run();
403 pthread_cancel(senderThread);
404 pthread_cancel(receiverThread);
405 if ( opt.getLocalSyncPort())
406 pthread_cancel(syncListenerThread);
407 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
408 pthread_cancel(*it);
410 pthread_join(senderThread, NULL);
411 pthread_join(receiverThread, NULL);
412 if ( opt.getLocalSyncPort())
413 pthread_join(syncListenerThread, NULL);
415 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
416 pthread_join(*it, NULL);
418 delete src;
419 delete &p.connto;
421 return ret;