added showtable
[anytun.git] / anytun.cpp
blob703e1cf1994af857c6bcbeae5f704142ad5cbd4f
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>
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 "cipher.h"
44 #include "keyDerivation.h"
45 #include "authAlgo.h"
46 #include "authTag.h"
47 #include "cipherFactory.h"
48 #include "authAlgoFactory.h"
49 #include "keyDerivationFactory.h"
50 #include "signalController.h"
51 #include "packetSource.h"
52 #include "tunDevice.h"
53 #include "options.h"
54 #include "seqWindow.h"
55 #include "connectionList.h"
56 #include "routingTable.h"
57 #include "networkAddress.h"
59 #include "syncQueue.h"
60 #include "syncSocketHandler.h"
61 #include "syncListenSocket.h"
63 #include "syncSocket.h"
64 #include "syncClientSocket.h"
65 #include "syncCommand.h"
67 #include "threadParam.h"
69 #define MAX_PACKET_LENGTH 1600
71 #define SESSION_KEYLEN_AUTH 20 // TODO: hardcoded size
72 #define SESSION_KEYLEN_ENCR 16 // TODO: hardcoded size
73 #define SESSION_KEYLEN_SALT 14 // TODO: hardcoded size
75 void createConnection(const std::string & remote_host, u_int16_t remote_port, ConnectionList & cl, u_int16_t seqSize, SyncQueue & queue, mux_t mux)
77 SeqWindow * seq= new SeqWindow(seqSize);
78 seq_nr_t seq_nr_=0;
79 KeyDerivation * kd = KeyDerivationFactory::create(gOpt.getKdPrf());
80 kd->init(gOpt.getKey(), gOpt.getSalt());
81 cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_host << ":" << remote_port;
82 ConnectionParam connparam ( (*kd), (*seq), seq_nr_, remote_host, remote_port);
83 cl.addConnection(connparam,mux);
84 NetworkAddress addr(ipv4,gOpt.getIfconfigParamRemoteNetmask().c_str());
85 NetworkPrefix prefix(addr,32);
86 gRoutingTable.addRoute(prefix,mux);
87 SyncCommand sc (cl,mux);
88 queue.push(sc);
89 SyncCommand sc2 (prefix);
90 queue.push(sc2);
94 void addPacketAuthTag(EncryptedPacket& pack, AuthAlgo* a, ConnectionParam& conn)
96 AuthTag at = a->calc(pack);
97 pack.setAuthTag( at );
100 bool checkPacketAuthTag(EncryptedPacket& pack, AuthAlgo* a, ConnectionParam & conn)
102 // check auth_tag and remove it
103 AuthTag at = pack.getAuthTag();
104 return (at == a->calc(pack));
107 bool checkPacketSeqNr(EncryptedPacket& pack,ConnectionParam& conn)
109 // compare sender_id and seq with window
110 if(conn.seq_window_.hasSeqNr(pack.getSenderId(), pack.getSeqNr()))
112 cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_host_<<":"<< conn.remote_port_
113 << " seq:"<<pack.getSeqNr() << " sid: "<<pack.getSenderId();
114 return false;
117 conn.seq_window_.addSeqNr(pack.getSenderId(), pack.getSeqNr());
118 return true;
121 void* sender(void* p)
123 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
125 std::auto_ptr<Cipher> c(CipherFactory::create(gOpt.getCipher()));
126 // std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
128 PlainPacket plain_packet(MAX_PACKET_LENGTH);
129 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
131 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
132 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
133 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
135 //TODO replace mux
136 u_int16_t mux = gOpt.getMux();
137 while(1)
139 plain_packet.setLength(MAX_PACKET_LENGTH);
140 encrypted_packet.setLength(MAX_PACKET_LENGTH);
141 // read packet from device
142 u_int32_t len = param->dev.read(plain_packet.getPayload(), plain_packet.getPayloadLength());
143 plain_packet.setPayloadLength(len);
144 // set payload type
145 if(param->dev.getType() == TunDevice::TYPE_TUN)
146 plain_packet.setPayloadType(PAYLOAD_TYPE_TUN);
147 else if(param->dev.getType() == TunDevice::TYPE_TAP)
148 plain_packet.setPayloadType(PAYLOAD_TYPE_TAP);
149 else
150 plain_packet.setPayloadType(0);
152 if(param->cl.empty())
153 continue;
154 //std::cout << "got Packet for plain "<<plain_packet.getDstAddr().toString();
155 mux = gRoutingTable.getRoute(plain_packet.getDstAddr());
156 //std::cout << " -> "<<mux << std::endl;
157 ConnectionMap::iterator cit = param->cl.getConnection(mux);
158 if(cit==param->cl.getEnd())
159 continue;
160 ConnectionParam & conn = cit->second;
162 if(conn.remote_host_==""||!conn.remote_port_)
163 continue;
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);
168 c->setKey(session_key);
169 c->setSalt(session_salt);
171 // encrypt packet
172 c->encrypt(plain_packet, encrypted_packet, conn.seq_nr_, gOpt.getSenderId());
174 encrypted_packet.setHeader(conn.seq_nr_, gOpt.getSenderId(), mux);
175 conn.seq_nr_++;
177 // TODO: activate authentication
178 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
179 // a->setKey(session_auth_key);
180 // addPacketAuthTag(encrypted_packet, a.get(), conn);
182 param->src.send(encrypted_packet.getBuf(), encrypted_packet.getLength(), conn.remote_host_, conn.remote_port_);
184 pthread_exit(NULL);
187 void* syncConnector(void* p )
189 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
191 SocketHandler h;
192 SyncClientSocket sock(h,param->cl);
193 // sock.EnableSSL();
194 sock.Open( param->connto.host, param->connto.port);
195 h.Add(&sock);
196 while (h.GetCount())
198 h.Select();
200 pthread_exit(NULL);
203 void* syncListener(void* p )
205 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
207 SyncSocketHandler h(param->queue);
208 SyncListenSocket<SyncSocket,ConnectionList> l(h,param->cl);
210 if (l.Bind(gOpt.getLocalSyncPort()))
211 pthread_exit(NULL);
213 Utility::ResolveLocal(); // resolve local hostname
214 h.Add(&l);
215 h.Select(1,0);
216 while (1) {
217 h.Select(1,0);
221 void* receiver(void* p)
223 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
225 std::auto_ptr<Cipher> c( CipherFactory::create(gOpt.getCipher()) );
226 // std::auto_ptr<AuthAlgo> a( AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
228 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
229 PlainPacket plain_packet(MAX_PACKET_LENGTH);
231 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
232 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
233 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
235 while(1)
237 string remote_host;
238 u_int16_t remote_port;
240 plain_packet.setLength(MAX_PACKET_LENGTH);
241 encrypted_packet.setLength(MAX_PACKET_LENGTH);
243 // read packet from socket
244 u_int32_t len = param->src.recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_host, remote_port);
245 encrypted_packet.setLength(len);
247 // TODO: check auth tag first
248 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
249 // a->setKey( session_auth_key );
250 // if(!checkPacketAuthTag(encrypted_packet, a.get(), conn))
251 // continue;
253 mux_t mux = encrypted_packet.getMux();
254 // autodetect peer
255 if(gOpt.getRemoteAddr() == "" && param->cl.empty())
257 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_host << ":" << remote_port;
258 createConnection(remote_host, remote_port, param->cl, gOpt.getSeqWindowSize(),param->queue,mux);
261 ConnectionMap::iterator cit = param->cl.getConnection(mux);
262 if (cit == param->cl.getEnd())
263 continue;
264 ConnectionParam & conn = cit->second;
266 //Allow dynamic IP changes
267 //TODO: add command line option to turn this off
268 if (remote_host != conn.remote_host_ || remote_port != conn.remote_port_)
270 cLog.msg(Log::PRIO_NOTICE) << "connection "<< mux << " autodetected remote host ip changed " << remote_host << ":" << remote_port;
271 conn.remote_host_=remote_host;
272 conn.remote_port_=remote_port;
273 SyncCommand sc (param->cl,mux);
274 param->queue.push(sc);
277 // Replay Protection
278 if (!checkPacketSeqNr(encrypted_packet, conn))
279 continue;
281 // generate packet-key
282 conn.kd_.generate(LABEL_SATP_ENCRYPTION, encrypted_packet.getSeqNr(), session_key);
283 conn.kd_.generate(LABEL_SATP_SALT, encrypted_packet.getSeqNr(), session_salt);
284 c->setKey(session_key);
285 c->setSalt(session_salt);
287 // decrypt packet
288 c->decrypt(encrypted_packet, plain_packet);
290 // check payload_type
291 if((param->dev.getType() == TunDevice::TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN) ||
292 (param->dev.getType() == TunDevice::TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP))
293 continue;
295 // write it on the device
296 param->dev.write(plain_packet.getPayload(), plain_packet.getLength());
298 pthread_exit(NULL);
301 #define MIN_GCRYPT_VERSION "1.2.3"
302 // make libgcrypt thread safe
303 extern "C" {
304 GCRY_THREAD_OPTION_PTHREAD_IMPL;
307 bool initLibGCrypt()
309 // make libgcrypt thread safe
310 // this must be called before any other libgcrypt call
311 gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
313 // this must be called right after the GCRYCTL_SET_THREAD_CBS command
314 // no other function must be called till now
315 if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) {
316 std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl;
317 return false;
320 // Tell Libgcrypt that initialization has completed.
321 gcry_error_t err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
322 if( err ) {
323 std::cout << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err ) << std::endl;
324 return false;
327 cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished";
328 return true;
331 int main(int argc, char* argv[])
333 std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
334 if(!gOpt.parse(argc, argv))
336 gOpt.printUsage();
337 exit(-1);
339 cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
341 SignalController sig;
342 sig.init();
343 std::string dev_type(gOpt.getDevType());
344 TunDevice dev(gOpt.getDevName().c_str(), dev_type=="" ? NULL : dev_type.c_str(), gOpt.getIfconfigParamLocal().c_str(), gOpt.getIfconfigParamRemoteNetmask().c_str());
346 PacketSource* src;
347 if(gOpt.getLocalAddr() == "")
348 src = new UDPPacketSource(gOpt.getLocalPort());
349 else
350 src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort());
352 ConnectionList cl;
353 ConnectToList connect_to = gOpt.getConnectTo();
354 SyncQueue queue;
356 if(gOpt.getRemoteAddr() != "")
357 createConnection(gOpt.getRemoteAddr(),gOpt.getRemotePort(),cl,gOpt.getSeqWindowSize(), queue, gOpt.getMux());
359 ThreadParam p(dev, *src, cl, queue,*(new OptionConnectTo()));
361 cLog.msg(Log::PRIO_NOTICE) << "dev created (opened)";
362 cLog.msg(Log::PRIO_NOTICE) << "dev opened - actual name is '" << p.dev.getActualName() << "'";
363 cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << p.dev.getTypeString() << "'";
365 // this must be called before any other libgcrypt call
366 if(!initLibGCrypt())
367 return -1;
369 pthread_t senderThread;
370 pthread_create(&senderThread, NULL, sender, &p);
371 pthread_t receiverThread;
372 pthread_create(&receiverThread, NULL, receiver, &p);
374 pthread_t syncListenerThread;
375 if ( gOpt.getLocalSyncPort())
376 pthread_create(&syncListenerThread, NULL, syncListener, &p);
378 std::list<pthread_t> connectThreads;
379 for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it)
381 connectThreads.push_back(pthread_t());
382 ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it);
383 pthread_create(& connectThreads.back(), NULL, syncConnector, point);
386 int ret = sig.run();
388 pthread_cancel(senderThread);
389 pthread_cancel(receiverThread);
390 if ( gOpt.getLocalSyncPort())
391 pthread_cancel(syncListenerThread);
392 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
393 pthread_cancel(*it);
395 pthread_join(senderThread, NULL);
396 pthread_join(receiverThread, NULL);
397 if ( gOpt.getLocalSyncPort())
398 pthread_join(syncListenerThread, NULL);
400 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
401 pthread_join(*it, NULL);
403 delete src;
404 delete &p.connto;
406 return ret;