starting work on init script
[anytun.git] / anytun.cpp
bloba115ff61759d9679c129c592b5faea1d65f9cfb6
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(), mux);
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);
174 param->src.send(encrypted_packet.getBuf(), encrypted_packet.getLength(), conn.remote_host_, conn.remote_port_);
176 catch (Exception e)
180 pthread_exit(NULL);
183 void* syncConnector(void* p )
185 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
187 SocketHandler h;
188 SyncClientSocket sock(h,param->cl);
189 // sock.EnableSSL();
190 sock.Open( param->connto.host, param->connto.port);
191 h.Add(&sock);
192 while (h.GetCount())
194 h.Select();
196 pthread_exit(NULL);
199 void* syncListener(void* p )
201 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
203 SyncSocketHandler h(param->queue);
204 SyncListenSocket<SyncSocket,ConnectionList> l(h,param->cl);
206 if (l.Bind(gOpt.getLocalSyncPort()))
207 pthread_exit(NULL);
209 Utility::ResolveLocal(); // resolve local hostname
210 h.Add(&l);
211 h.Select(1,0);
212 while (1) {
213 h.Select(1,0);
217 void* receiver(void* p)
219 ThreadParam* param = reinterpret_cast<ThreadParam*>(p);
221 std::auto_ptr<Cipher> c( CipherFactory::create(gOpt.getCipher()) );
222 std::auto_ptr<AuthAlgo> a( AuthAlgoFactory::create(gOpt.getAuthAlgo()) );
224 EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH);
225 PlainPacket plain_packet(MAX_PACKET_LENGTH);
227 Buffer session_key(u_int32_t(SESSION_KEYLEN_ENCR)); // TODO: hardcoded size
228 Buffer session_salt(u_int32_t(SESSION_KEYLEN_SALT)); // TODO: hardcoded size
229 Buffer session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH)); // TODO: hardcoded size
231 while(1)
233 string remote_host;
234 u_int16_t remote_port;
236 plain_packet.setLength(MAX_PACKET_LENGTH);
237 encrypted_packet.withAuthTag(false);
238 encrypted_packet.setLength(MAX_PACKET_LENGTH);
240 // read packet from socket
241 u_int32_t len = param->src.recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_host, remote_port);
242 encrypted_packet.setLength(len);
244 mux_t mux = encrypted_packet.getMux();
245 // autodetect peer
246 if(gOpt.getRemoteAddr() == "" && param->cl.empty())
248 cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_host << ":" << remote_port;
249 createConnection(remote_host, remote_port, param->cl, gOpt.getSeqWindowSize(),param->queue,mux);
252 ConnectionMap::iterator cit = param->cl.getConnection(mux);
253 if (cit == param->cl.getEnd())
254 continue;
255 ConnectionParam & conn = cit->second;
257 // check whether auth tag is ok or not
258 if(a->getMaxLength()) {
259 encrypted_packet.withAuthTag(true);
260 conn.kd_.generate(LABEL_SATP_MSG_AUTH, encrypted_packet.getSeqNr(), session_auth_key);
261 a->setKey(session_auth_key);
262 if(!a->checkTag(encrypted_packet)) {
263 cLog.msg(Log::PRIO_NOTICE) << "wrong Authentication Tag!" << std::endl;
264 continue;
266 encrypted_packet.removeAuthTag();
269 //Allow dynamic IP changes
270 //TODO: add command line option to turn this off
271 if (remote_host != conn.remote_host_ || remote_port != conn.remote_port_)
273 cLog.msg(Log::PRIO_NOTICE) << "connection "<< mux << " autodetected remote host ip changed " << remote_host << ":" << remote_port;
274 conn.remote_host_=remote_host;
275 conn.remote_port_=remote_port;
276 SyncCommand sc (param->cl,mux);
277 param->queue.push(sc);
280 // Replay Protection
281 if (!checkPacketSeqNr(encrypted_packet, conn))
282 continue;
284 // generate packet-key
285 conn.kd_.generate(LABEL_SATP_ENCRYPTION, encrypted_packet.getSeqNr(), session_key);
286 conn.kd_.generate(LABEL_SATP_SALT, encrypted_packet.getSeqNr(), session_salt);
287 c->setKey(session_key);
288 c->setSalt(session_salt);
290 // decrypt packet
291 c->decrypt(encrypted_packet, plain_packet);
293 // check payload_type
294 if((param->dev.getType() == TunDevice::TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN4 &&
295 plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN6) ||
296 (param->dev.getType() == TunDevice::TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP))
297 continue;
299 // write it on the device
300 param->dev.write(plain_packet.getPayload(), plain_packet.getLength());
302 pthread_exit(NULL);
305 #define MIN_GCRYPT_VERSION "1.2.3"
306 // make libgcrypt thread safe
307 extern "C" {
308 GCRY_THREAD_OPTION_PTHREAD_IMPL;
311 bool initLibGCrypt()
313 // make libgcrypt thread safe
314 // this must be called before any other libgcrypt call
315 gcry_control( GCRYCTL_SET_THREAD_CBS, &gcry_threads_pthread );
317 // this must be called right after the GCRYCTL_SET_THREAD_CBS command
318 // no other function must be called till now
319 if( !gcry_check_version( MIN_GCRYPT_VERSION ) ) {
320 std::cout << "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION << std::endl;
321 return false;
324 gcry_error_t err = gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
325 if( err ) {
326 std::cout << "initLibGCrypt: Failed to disable secure memory: " << gpg_strerror( err ) << std::endl;
327 return false;
330 // Tell Libgcrypt that initialization has completed.
331 err = gcry_control(GCRYCTL_INITIALIZATION_FINISHED);
332 if( err ) {
333 std::cout << "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err ) << std::endl;
334 return false;
337 cLog.msg(Log::PRIO_NOTICE) << "initLibGCrypt: libgcrypt init finished";
338 return true;
341 void daemonize()
343 pid_t pid;
345 pid = fork();
346 if(pid) exit(0);
347 setsid();
348 pid = fork();
349 if(pid) exit(0);
351 std::cout << "running in background now..." << std::endl;
353 int fd;
354 for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
355 close(fd);
356 fd=open("/dev/null",O_RDWR); // stdin
357 dup(fd); // stdout
358 dup(fd); // stderr
359 umask(027);
362 int main(int argc, char* argv[])
364 std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
365 if(!gOpt.parse(argc, argv))
367 gOpt.printUsage();
368 exit(-1);
370 if(gOpt.getDaemonize())
371 daemonize();
373 cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
375 SignalController sig;
376 sig.init();
377 std::string dev_type(gOpt.getDevType());
378 TunDevice dev(gOpt.getDevName().c_str(), dev_type=="" ? NULL : dev_type.c_str(),
379 gOpt.getIfconfigParamLocal() =="" ? NULL : gOpt.getIfconfigParamLocal().c_str(),
380 gOpt.getIfconfigParamRemoteNetmask() =="" ? NULL : gOpt.getIfconfigParamRemoteNetmask().c_str());
382 PacketSource* src;
383 if(gOpt.getLocalAddr() == "")
384 src = new UDPPacketSource(gOpt.getLocalPort());
385 else
386 src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort());
388 ConnectionList cl;
389 ConnectToList connect_to = gOpt.getConnectTo();
390 SyncQueue queue;
392 if(gOpt.getRemoteAddr() != "")
393 createConnection(gOpt.getRemoteAddr(),gOpt.getRemotePort(),cl,gOpt.getSeqWindowSize(), queue, gOpt.getMux());
395 ThreadParam p(dev, *src, cl, queue,*(new OptionConnectTo()));
397 cLog.msg(Log::PRIO_NOTICE) << "dev created (opened)";
398 cLog.msg(Log::PRIO_NOTICE) << "dev opened - actual name is '" << p.dev.getActualName() << "'";
399 cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << p.dev.getTypeString() << "'";
401 // this must be called before any other libgcrypt call
402 if(!initLibGCrypt())
403 return -1;
405 pthread_t senderThread;
406 pthread_create(&senderThread, NULL, sender, &p);
407 pthread_t receiverThread;
408 pthread_create(&receiverThread, NULL, receiver, &p);
410 pthread_t syncListenerThread;
411 if ( gOpt.getLocalSyncPort())
412 pthread_create(&syncListenerThread, NULL, syncListener, &p);
414 std::list<pthread_t> connectThreads;
415 for(ConnectToList::iterator it = connect_to.begin() ;it != connect_to.end(); ++it)
417 connectThreads.push_back(pthread_t());
418 ThreadParam * point = new ThreadParam(dev, *src, cl, queue,*it);
419 pthread_create(& connectThreads.back(), NULL, syncConnector, point);
422 int ret = sig.run();
424 pthread_cancel(senderThread);
425 pthread_cancel(receiverThread);
426 if ( gOpt.getLocalSyncPort())
427 pthread_cancel(syncListenerThread);
428 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
429 pthread_cancel(*it);
431 pthread_join(senderThread, NULL);
432 pthread_join(receiverThread, NULL);
433 if ( gOpt.getLocalSyncPort())
434 pthread_join(syncListenerThread, NULL);
436 for( std::list<pthread_t>::iterator it = connectThreads.begin() ;it != connectThreads.end(); ++it)
437 pthread_join(*it, NULL);
439 delete src;
440 delete &p.connto;
442 return ret;