length to size
[anytun.git] / anytun.cpp
blob2e27b8b3a9ace29ea2a18a894db1225a40c4a1bc
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);
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);
145 if(param->cl.empty())
146 continue;
148 mux = gRoutingTable.getRoute(NetworkAddress());
149 ConnectionMap::iterator cit = param->cl.getConnection(mux);
150 if(cit==param->cl.getEnd())
151 continue;
152 ConnectionParam & conn = cit->second;
154 // set payload type
155 if(param->dev.getType() == TunDevice::TYPE_TUN)
156 plain_packet.setPayloadType(PAYLOAD_TYPE_TUN);
157 else if(param->dev.getType() == TunDevice::TYPE_TAP)
158 plain_packet.setPayloadType(PAYLOAD_TYPE_TAP);
159 else
160 plain_packet.setPayloadType(0);
162 // generate packet-key
163 conn.kd_.generate(LABEL_SATP_ENCRYPTION, conn.seq_nr_, session_key);
164 conn.kd_.generate(LABEL_SATP_SALT, conn.seq_nr_, session_salt);
166 c->setKey(session_key);
167 c->setSalt(session_salt);
169 // encrypt packet
170 c->encrypt(plain_packet, encrypted_packet, conn.seq_nr_, gOpt.getSenderId());
172 encrypted_packet.setHeader(conn.seq_nr_, gOpt.getSenderId(), mux);
173 conn.seq_nr_++;
175 // TODO: activate authentication
176 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
177 // a->setKey(session_auth_key);
178 // addPacketAuthTag(encrypted_packet, a.get(), conn);
180 param->src.send(encrypted_packet.getBuf(), encrypted_packet.getLength(), 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(gOpt.getLocalSyncPort()))
209 pthread_exit(NULL);
211 Utility::ResolveLocal(); // resolve local hostname
212 h.Add(&l);
213 h.Select(1,0);
214 while (1) {
215 h.Select(1,0);
219 void* receiver(void* p)
221 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
223 std::auto_ptr<Cipher> c( CipherFactory::create(gOpt.getCipher()) );
224 // std::auto_ptr<AuthAlgo> a( AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
226 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
227 PlainPacket plain_packet(MAX_PACKET_LENGTH);
229 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
230 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
231 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
233 while(1)
235 string remote_host;
236 u_int16_t remote_port;
238 plain_packet.setLength(MAX_PACKET_LENGTH);
239 encrypted_packet.setLength(MAX_PACKET_LENGTH);
241 // read packet from socket
242 u_int32_t len = param->src.recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_host, remote_port);
243 encrypted_packet.setLength(len);
245 // TODO: check auth tag first
246 // conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
247 // a->setKey( session_auth_key );
248 // if(!checkPacketAuthTag(encrypted_packet, a.get(), conn))
249 // continue;
252 // autodetect peer
253 if(gOpt.getRemoteAddr() == "" && param->cl.empty())
255 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_host << ":" << remote_port;
256 createConnection(remote_host, remote_port, param->cl, gOpt.getSeqWindowSize(),param->queue,encrypted_packet.getMux());
259 // TODO: Add multi connection support here
260 ConnectionMap::iterator cit = param->cl.getConnection(encrypted_packet.getMux());
261 if (cit == param->cl.getEnd())
262 continue;
263 ConnectionParam & conn = cit->second;
265 //Allow dynamic IP changes
266 //TODO: add command line option to turn this off
267 if (remote_host != conn.remote_host_ || remote_port != conn.remote_port_)
269 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host ip changed " << remote_host << ":" << remote_port;
270 conn.remote_host_=remote_host;
271 conn.remote_port_=remote_port;
272 SyncCommand sc (param->cl,0);
273 param->queue.push(sc);
276 // Replay Protection
277 if (!checkPacketSeqNr(encrypted_packet, conn))
278 continue;
280 // generate packet-key
281 conn.kd_.generate(LABEL_SATP_ENCRYPTION, encrypted_packet.getSeqNr(), session_key);
282 conn.kd_.generate(LABEL_SATP_SALT, encrypted_packet.getSeqNr(), session_salt);
283 c->setKey(session_key);
284 c->setSalt(session_salt);
286 // decrypt packet
287 c->decrypt(encrypted_packet, plain_packet);
289 // check payload_type
290 if((param->dev.getType() == TunDevice::TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN) ||
291 (param->dev.getType() == TunDevice::TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP))
292 continue;
294 // write it on the device
295 param->dev.write(plain_packet.getPayload(), plain_packet.getLength());
297 pthread_exit(NULL);
300 #define MIN_GCRYPT_VERSION "1.2.3"
301 // make libgcrypt thread safe
302 extern "C" {
303 GCRY_THREAD_OPTION_PTHREAD_IMPL;
306 bool initLibGCrypt()
308 // make libgcrypt thread safe
309 // this must be called before any other libgcrypt call
310 gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
312 // this must be called right after the GCRYCTL_SET_THREAD_CBS command
313 // no other function must be called till now
314 if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) {
315 std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl;
316 return false;
319 // Tell Libgcrypt that initialization has completed.
320 gcry_error_t err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
321 if( err ) {
322 std::cout << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err ) << std::endl;
323 return false;
326 cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished";
327 return true;
330 int main(int argc, char* argv[])
332 std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
333 if(!gOpt.parse(argc, argv))
335 gOpt.printUsage();
336 exit(-1);
338 cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
340 SignalController sig;
341 sig.init();
342 std::string dev_type(gOpt.getDevType());
343 TunDevice dev(gOpt.getDevName().c_str(), dev_type=="" ? NULL : dev_type.c_str(), gOpt.getIfconfigParamLocal().c_str(), gOpt.getIfconfigParamRemoteNetmask().c_str());
345 PacketSource* src;
346 if(gOpt.getLocalAddr() == "")
347 src = new UDPPacketSource(gOpt.getLocalPort());
348 else
349 src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort());
351 ConnectionList cl;
352 ConnectToList connect_to = gOpt.getConnectTo();
353 SyncQueue queue;
355 if(gOpt.getRemoteAddr() != "")
356 createConnection(gOpt.getRemoteAddr(),gOpt.getRemotePort(),cl,gOpt.getSeqWindowSize(), queue, gOpt.getMux());
358 ThreadParam p(dev, *src, cl, queue,*(new OptionConnectTo()));
360 cLog.msg(Log::PRIO_NOTICE) << "dev created (opened)";
361 cLog.msg(Log::PRIO_NOTICE) << "dev opened - actual name is '" << p.dev.getActualName() << "'";
362 cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << p.dev.getTypeString() << "'";
364 // this must be called before any other libgcrypt call
365 if(!initLibGCrypt())
366 return -1;
368 pthread_t senderThread;
369 pthread_create(&senderThread, NULL, sender, &p);
370 pthread_t receiverThread;
371 pthread_create(&receiverThread, NULL, receiver, &p);
373 pthread_t syncListenerThread;
374 if ( gOpt.getLocalSyncPort())
375 pthread_create(&syncListenerThread, NULL, syncListener, &p);
377 std::list<pthread_t> connectThreads;
378 for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it)
380 connectThreads.push_back(pthread_t());
381 ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it);
382 pthread_create(& connectThreads.back(), NULL, syncConnector, point);
385 int ret = sig.run();
387 pthread_cancel(senderThread);
388 pthread_cancel(receiverThread);
389 if ( gOpt.getLocalSyncPort())
390 pthread_cancel(syncListenerThread);
391 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
392 pthread_cancel(*it);
394 pthread_join(senderThread, NULL);
395 pthread_join(receiverThread, NULL);
396 if ( gOpt.getLocalSyncPort())
397 pthread_join(syncListenerThread, NULL);
399 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
400 pthread_join(*it, NULL);
402 delete src;
403 delete &p.connto;
405 return ret;