added SyncRtpCommand
[anytun.git] / anytun.cpp
blob5983962ce8aca67fab26a6b066c87a187808ec18
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>
33 #include <fcntl.h>
35 #include <gcrypt.h>
36 #include <cerrno> // for ENOMEM
38 #include "datatypes.h"
40 #include "log.h"
41 #include "buffer.h"
42 #include "plainPacket.h"
43 #include "encryptedPacket.h"
44 #include "cipher.h"
45 #include "keyDerivation.h"
46 #include "authAlgo.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);
93 bool checkPacketSeqNr(EncryptedPacket& pack,ConnectionParam& conn)
95 // compare sender_id and seq with window
96 if(conn.seq_window_.hasSeqNr(pack.getSenderId(), pack.getSeqNr()))
98 cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_host_<<":"<< conn.remote_port_
99 << " seq:"<<pack.getSeqNr() << " sid: "<<pack.getSenderId();
100 return false;
103 conn.seq_window_.addSeqNr(pack.getSenderId(), pack.getSeqNr());
104 return true;
107 void* sender(void* p)
109 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
111 std::auto_ptr<Cipher> c(CipherFactory::create(gOpt.getCipher()));
112 std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
114 PlainPacket plain_packet(MAX_PACKET_LENGTH);
115 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
117 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
118 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
119 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
121 //TODO replace mux
122 u_int16_t mux = gOpt.getMux();
123 while(1)
125 plain_packet.setLength(MAX_PACKET_LENGTH);
126 encrypted_packet.withAuthTag(false);
127 encrypted_packet.setLength(MAX_PACKET_LENGTH);
129 // read packet from device
130 u_int32_t len = param->dev.read(plain_packet.getPayload(), plain_packet.getPayloadLength());
131 plain_packet.setPayloadLength(len);
132 // set payload type
133 if(param->dev.getType() == TunDevice::TYPE_TUN)
134 plain_packet.setPayloadType(PAYLOAD_TYPE_TUN);
135 else if(param->dev.getType() == TunDevice::TYPE_TAP)
136 plain_packet.setPayloadType(PAYLOAD_TYPE_TAP);
137 else
138 plain_packet.setPayloadType(0);
140 if(param->cl.empty())
141 continue;
142 //std::cout << "got Packet for plain "<<plain_packet.getDstAddr().toString();
143 mux = gRoutingTable.getRoute(plain_packet.getDstAddr());
144 //std::cout << " -> "<<mux << std::endl;
145 ConnectionMap::iterator cit = param->cl.getConnection(mux);
146 if(cit==param->cl.getEnd())
147 continue;
148 ConnectionParam & conn = cit->second;
150 if(conn.remote_host_==""||!conn.remote_port_)
151 continue;
152 // generate packet-key TODO: do this only when needed
153 conn.kd_.generate(LABEL_SATP_ENCRYPTION, conn.seq_nr_, session_key);
154 conn.kd_.generate(LABEL_SATP_SALT, conn.seq_nr_, session_salt);
156 c->setKey(session_key);
157 c->setSalt(session_salt);
159 // encrypt packet
160 c->encrypt(plain_packet, encrypted_packet, conn.seq_nr_, gOpt.getSenderId());
162 encrypted_packet.setHeader(conn.seq_nr_, gOpt.getSenderId(), mux);
163 conn.seq_nr_++;
165 // add authentication tag
166 if(a->getMaxLength()) {
167 encrypted_packet.addAuthTag();
168 conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
169 a->setKey(session_auth_key);
170 a->generate(encrypted_packet);
173 param->src.send(encrypted_packet.getBuf(), encrypted_packet.getLength(), conn.remote_host_, conn.remote_port_);
175 pthread_exit(NULL);
178 void* syncConnector(void* p )
180 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
182 SocketHandler h;
183 SyncClientSocket sock(h,param->cl);
184 // sock.EnableSSL();
185 sock.Open( param->connto.host, param->connto.port);
186 h.Add(&sock);
187 while (h.GetCount())
189 h.Select();
191 pthread_exit(NULL);
194 void* syncListener(void* p )
196 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
198 SyncSocketHandler h(param->queue);
199 SyncListenSocket<SyncSocket,ConnectionList> l(h,param->cl);
201 if (l.Bind(gOpt.getLocalSyncPort()))
202 pthread_exit(NULL);
204 Utility::ResolveLocal(); // resolve local hostname
205 h.Add(&l);
206 h.Select(1,0);
207 while (1) {
208 h.Select(1,0);
212 void* receiver(void* p)
214 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
216 std::auto_ptr<Cipher> c( CipherFactory::create(gOpt.getCipher()) );
217 std::auto_ptr<AuthAlgo> a( AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
219 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
220 PlainPacket plain_packet(MAX_PACKET_LENGTH);
222 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
223 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
224 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
226 while(1)
228 string remote_host;
229 u_int16_t remote_port;
231 plain_packet.setLength(MAX_PACKET_LENGTH);
232 encrypted_packet.withAuthTag(false);
233 encrypted_packet.setLength(MAX_PACKET_LENGTH);
235 // read packet from socket
236 u_int32_t len = param->src.recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_host, remote_port);
237 encrypted_packet.setLength(len);
239 mux_t mux = encrypted_packet.getMux();
240 // autodetect peer
241 if(gOpt.getRemoteAddr() == "" && param->cl.empty())
243 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_host << ":" << remote_port;
244 createConnection(remote_host, remote_port, param->cl, gOpt.getSeqWindowSize(),param->queue,mux);
247 ConnectionMap::iterator cit = param->cl.getConnection(mux);
248 if (cit == param->cl.getEnd())
249 continue;
250 ConnectionParam & conn = cit->second;
252 // check whether auth tag is ok or not
253 if(a->getMaxLength()) {
254 encrypted_packet.withAuthTag(true);
255 conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
256 a->setKey(session_auth_key);
257 if(!a->checkTag(encrypted_packet)) {
258 cLog.msg(Log::PRIO_NOTICE) << "wrong Authentication Tag!" << std::endl;
259 continue;
261 encrypted_packet.removeAuthTag();
264 //Allow dynamic IP changes
265 //TODO: add command line option to turn this off
266 if (remote_host != conn.remote_host_ || remote_port != conn.remote_port_)
268 cLog.msg(Log::PRIO_NOTICE) << "connection "<< mux << " autodetected remote host ip changed " << remote_host << ":" << remote_port;
269 conn.remote_host_=remote_host;
270 conn.remote_port_=remote_port;
271 SyncCommand sc (param->cl,mux);
272 param->queue.push(sc);
275 // Replay Protection
276 if (!checkPacketSeqNr(encrypted_packet, conn))
277 continue;
279 // generate packet-key
280 conn.kd_.generate(LABEL_SATP_ENCRYPTION, encrypted_packet.getSeqNr(), session_key);
281 conn.kd_.generate(LABEL_SATP_SALT, encrypted_packet.getSeqNr(), session_salt);
282 c->setKey(session_key);
283 c->setSalt(session_salt);
285 // decrypt packet
286 c->decrypt(encrypted_packet, plain_packet);
288 // check payload_type
289 if((param->dev.getType() == TunDevice::TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN) ||
290 (param->dev.getType() == TunDevice::TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP))
291 continue;
293 // write it on the device
294 param->dev.write(plain_packet.getPayload(), plain_packet.getLength());
296 pthread_exit(NULL);
299 #define MIN_GCRYPT_VERSION "1.2.3"
300 // make libgcrypt thread safe
301 extern "C" {
302 GCRY_THREAD_OPTION_PTHREAD_IMPL;
305 bool initLibGCrypt()
307 // make libgcrypt thread safe
308 // this must be called before any other libgcrypt call
309 gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
311 // this must be called right after the GCRYCTL_SET_THREAD_CBS command
312 // no other function must be called till now
313 if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) {
314 std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl;
315 return false;
318 gcry_error_t err = gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
319 if( err ) {
320 std::cout << "initLibGCrypt: Failed to disable secure memory: " << gpg_strerror( err ) << std::endl;
321 return false;
324 // Tell Libgcrypt that initialization has completed.
325 err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
326 if( err ) {
327 std::cout << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err ) << std::endl;
328 return false;
331 cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished";
332 return true;
335 void daemonize()
337 pid_t pid;
339 pid = fork();
340 if(pid) exit(0);
341 setsid();
342 pid = fork();
343 if(pid) exit(0);
345 std::cout << "running in background now..." << std::endl;
347 int fd;
348 for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
349 close(fd);
350 fd=open("/dev/null",O_RDWR); // stdin
351 dup(fd); // stdout
352 dup(fd); // stderr
353 umask(027);
356 int main(int argc, char* argv[])
358 std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
359 if(!gOpt.parse(argc, argv))
361 gOpt.printUsage();
362 exit(-1);
364 if(gOpt.getDaemonize())
365 daemonize();
367 cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
369 SignalController sig;
370 sig.init();
371 std::string dev_type(gOpt.getDevType());
372 TunDevice dev(gOpt.getDevName().c_str(), dev_type=="" ? NULL : dev_type.c_str(), gOpt.getIfconfigParamLocal().c_str(), gOpt.getIfconfigParamRemoteNetmask().c_str());
374 PacketSource* src;
375 if(gOpt.getLocalAddr() == "")
376 src = new UDPPacketSource(gOpt.getLocalPort());
377 else
378 src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort());
380 ConnectionList cl;
381 ConnectToList connect_to = gOpt.getConnectTo();
382 SyncQueue queue;
384 if(gOpt.getRemoteAddr() != "")
385 createConnection(gOpt.getRemoteAddr(),gOpt.getRemotePort(),cl,gOpt.getSeqWindowSize(), queue, gOpt.getMux());
387 ThreadParam p(dev, *src, cl, queue,*(new OptionConnectTo()));
389 cLog.msg(Log::PRIO_NOTICE) << "dev created (opened)";
390 cLog.msg(Log::PRIO_NOTICE) << "dev opened - actual name is '" << p.dev.getActualName() << "'";
391 cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << p.dev.getTypeString() << "'";
393 // this must be called before any other libgcrypt call
394 if(!initLibGCrypt())
395 return -1;
397 pthread_t senderThread;
398 pthread_create(&senderThread, NULL, sender, &p);
399 pthread_t receiverThread;
400 pthread_create(&receiverThread, NULL, receiver, &p);
402 pthread_t syncListenerThread;
403 if ( gOpt.getLocalSyncPort())
404 pthread_create(&syncListenerThread, NULL, syncListener, &p);
406 std::list<pthread_t> connectThreads;
407 for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it)
409 connectThreads.push_back(pthread_t());
410 ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it);
411 pthread_create(& connectThreads.back(), NULL, syncConnector, point);
414 int ret = sig.run();
416 pthread_cancel(senderThread);
417 pthread_cancel(receiverThread);
418 if ( gOpt.getLocalSyncPort())
419 pthread_cancel(syncListenerThread);
420 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
421 pthread_cancel(*it);
423 pthread_join(senderThread, NULL);
424 pthread_join(receiverThread, NULL);
425 if ( gOpt.getLocalSyncPort())
426 pthread_join(syncListenerThread, NULL);
428 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
429 pthread_join(*it, NULL);
431 delete src;
432 delete &p.connto;
434 return ret;