Imported Upstream version 0.3.4
[anytun.git] / src / anytun.cpp
1 /*
2  *  anytun
3  *
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.
12  *
13  *
14  *  Copyright (C) 2007-2009 Othmar Gsenger, Erwin Nindl,
15  *                          Christian Pointner <satp@wirdorange.org>
16  *
17  *  This file is part of Anytun.
18  *
19  *  Anytun is free software: you can redistribute it and/or modify
20  *  it under the terms of the GNU General Public License as published by
21  *  the Free Software Foundation, either version 3 of the License, or
22  *  any later version.
23  *
24  *  Anytun is distributed in the hope that it will be useful,
25  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
26  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27  *  GNU General Public License for more details.
28  *
29  *  You should have received a copy of the GNU General Public License
30  *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
31  */
32
33 #include <boost/bind.hpp>
34 #include <boost/thread.hpp>
35 #include <boost/assign.hpp>
36 #include <iostream>
37 #include <fstream>
38
39 #include "datatypes.h"
40
41 #include "log.h"
42 #include "resolver.h"
43 #include "buffer.h"
44 #include "plainPacket.h"
45 #include "encryptedPacket.h"
46 #include "cipher.h"
47 #include "keyDerivation.h"
48 #include "authAlgo.h"
49 #include "cipherFactory.h"
50 #include "authAlgoFactory.h"
51 #include "keyDerivationFactory.h"
52 #include "signalController.h"
53 #ifndef _MSC_VER
54 # include "daemonService.h"
55 #else
56 # ifdef WIN_SERVICE
57 #  include "win32/winService.h"
58 # else
59 #  include "nullDaemon.h"
60 # endif
61 #endif
62 #include "packetSource.h"
63 #include "tunDevice.h"
64 #include "options.h"
65 #include "seqWindow.h"
66 #include "connectionList.h"
67 #ifndef NO_ROUTING
68 #include "routingTable.h"
69 #include "networkAddress.h"
70 #endif
71
72 #ifndef ANYTUN_NOSYNC
73 #include "syncQueue.h"
74 #include "syncCommand.h"
75 #include "syncServer.h"
76 #include "syncClient.h"
77 #include "syncOnConnect.hpp"
78 #endif
79
80 #include "cryptinit.hpp"
81 #include "sysExec.h"
82
83 bool disableRouting = false;
84
85 void createConnection(const PacketSourceEndpoint& remote_end, window_size_t seqSize, mux_t mux)
86 {
87   SeqWindow* seq = new SeqWindow(seqSize);
88   seq_nr_t seq_nr_=0;
89   KeyDerivation* kd = KeyDerivationFactory::create(gOpt.getKdPrf());
90   kd->init(gOpt.getKey(), gOpt.getSalt(), gOpt.getPassphrase());
91   kd->setRole(gOpt.getRole());
92   cLog.msg(Log::PRIO_NOTICE) << "added connection remote host " << remote_end;
93
94   ConnectionParam connparam((*kd), (*seq), seq_nr_, remote_end);
95   gConnectionList.addConnection(connparam,mux);
96 #ifndef ANYTUN_NOSYNC
97   SyncCommand sc(gConnectionList,mux);
98   gSyncQueue.push(sc);
99 #endif
100 }
101
102 void createConnectionResolver(PacketSourceResolverIt& it, window_size_t seqSize, mux_t mux)
103 {
104   createConnection(*it, seqSize, mux);
105 }
106
107 void createConnectionError(const std::exception& e)
108 {
109   gSignalController.inject(SIGERROR, e.what());
110 }
111
112 #ifndef ANYTUN_NOSYNC
113 void syncConnector(const OptionHost& connto)
114 {
115   SyncClient sc(connto.addr, connto.port);
116   sc.run();
117 }
118
119 void syncListener()
120 {
121   try {
122     SyncServer server(gOpt.getLocalSyncAddr(), gOpt.getLocalSyncPort(), boost::bind(syncOnConnect, _1));
123     gSyncQueue.setSyncServerPtr(&server);
124     server.run();
125   } catch(std::runtime_error& e) {
126     cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught runtime_error: " << e.what();
127   } catch(std::exception& e) {
128     cLog.msg(Log::PRIO_ERROR) << "sync listener thread died due to an uncaught exception: " << e.what();
129   }
130 }
131 #endif
132
133 void sender(TunDevice* dev, PacketSource* src)
134 {
135   if(!dev || !src) {
136     cLog.msg(Log::PRIO_ERROR) << "sender thread died because either dev or src pointer is null";
137     return;
138   }
139
140   try {
141     std::auto_ptr<Cipher> c(CipherFactory::create(gOpt.getCipher(), KD_OUTBOUND));
142     std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_OUTBOUND));
143
144     PlainPacket plain_packet(MAX_PACKET_LENGTH);
145     EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH, gOpt.getAuthTagLength());
146
147     uint16_t mux = gOpt.getMux();
148     PacketSourceEndpoint emptyEndpoint;
149     while(1) {
150       plain_packet.setLength(MAX_PACKET_LENGTH);
151       encrypted_packet.withAuthTag(false);
152       encrypted_packet.setLength(MAX_PACKET_LENGTH);
153
154       // read packet from device
155       int len = dev->read(plain_packet.getPayload(), plain_packet.getPayloadLength());
156       if(len < 0) {
157         continue;  // silently ignore device read errors, this is probably no good idea...
158       }
159
160       if(static_cast<uint32_t>(len) < PlainPacket::getHeaderLength()) {
161         continue;  // ignore short packets
162       }
163       plain_packet.setPayloadLength(len);
164       // set payload type
165       if(dev->getType() == TYPE_TUN) {
166         plain_packet.setPayloadType(PAYLOAD_TYPE_TUN);
167       } else if(dev->getType() == TYPE_TAP) {
168         plain_packet.setPayloadType(PAYLOAD_TYPE_TAP);
169       } else {
170         plain_packet.setPayloadType(0);
171       }
172
173       if(gConnectionList.empty()) {
174         continue;
175       }
176       //std::cout << "got Packet for plain "<<plain_packet.getDstAddr().toString();
177       ConnectionMap::iterator cit;
178 #ifndef NO_ROUTING
179       if(!disableRouting)
180         try {
181           mux = gRoutingTable.getRoute(plain_packet.getDstAddr());
182           //std::cout << " -> "<<mux << std::endl;
183           cit = gConnectionList.getConnection(mux);
184         } catch(std::exception&) { continue; }  // no route
185       else {
186         cit = gConnectionList.getBegin();
187       }
188 #else
189       cit = gConnectionList.getBegin();
190 #endif
191
192       if(cit==gConnectionList.getEnd()) {
193         continue;  //no connection
194       }
195       ConnectionParam& conn = cit->second;
196
197       if(conn.remote_end_ == emptyEndpoint) {
198         //cLog.msg(Log::PRIO_INFO) << "no remote address set";
199         continue;
200       }
201
202       // encrypt packet
203       c->encrypt(conn.kd_, plain_packet, encrypted_packet, conn.seq_nr_, gOpt.getSenderId(), mux);
204
205       encrypted_packet.setHeader(conn.seq_nr_, gOpt.getSenderId(), mux);
206       conn.seq_nr_++;
207
208       // add authentication tag
209       a->generate(conn.kd_, encrypted_packet);
210
211       try {
212         src->send(encrypted_packet.getBuf(), encrypted_packet.getLength(), conn.remote_end_);
213       } catch(std::exception& /*e*/) {
214         //TODO: do something here
215         //cLog.msg(Log::PRIO_ERROR) << "could not send data: " << e.what();
216       }
217     }
218   } catch(std::runtime_error& e) {
219     cLog.msg(Log::PRIO_ERROR) << "sender thread died due to an uncaught runtime_error: " << e.what();
220   } catch(std::exception& e) {
221     cLog.msg(Log::PRIO_ERROR) << "sender thread died due to an uncaught exception: " << e.what();
222   }
223 }
224
225 void receiver(TunDevice* dev, PacketSource* src)
226 {
227   if(!dev || !src) {
228     cLog.msg(Log::PRIO_ERROR) << "receiver thread died because either dev or src pointer is null";
229     return;
230   }
231
232   try {
233     std::auto_ptr<Cipher> c(CipherFactory::create(gOpt.getCipher(), KD_INBOUND));
234     std::auto_ptr<AuthAlgo> a(AuthAlgoFactory::create(gOpt.getAuthAlgo(), KD_INBOUND));
235
236     uint32_t auth_tag_length = gOpt.getAuthTagLength();
237     EncryptedPacket encrypted_packet(MAX_PACKET_LENGTH, auth_tag_length);
238     PlainPacket plain_packet(MAX_PACKET_LENGTH);
239
240     while(1) {
241       PacketSourceEndpoint remote_end;
242
243       plain_packet.setLength(MAX_PACKET_LENGTH);
244       encrypted_packet.withAuthTag(false);
245       encrypted_packet.setLength(MAX_PACKET_LENGTH);
246
247       // read packet from socket
248       int len;
249       try {
250         len = src->recv(encrypted_packet.getBuf(), encrypted_packet.getLength(), remote_end);
251       } catch(std::exception& /*e*/) {
252         //TODO: do something here
253         //cLog.msg(Log::PRIO_ERROR) << "could not recive packet "<< e.what();
254         continue;
255       }
256       if(len < 0) {
257         continue;  // silently ignore socket recv errors, this is probably no good idea...
258       }
259
260       if(static_cast<uint32_t>(len) < (EncryptedPacket::getHeaderLength() + auth_tag_length)) {
261         continue;  // ignore short packets
262       }
263       encrypted_packet.setLength(len);
264
265       mux_t mux = encrypted_packet.getMux();
266       // autodetect peer
267       if(gConnectionList.empty() && gOpt.getRemoteAddr() == "") {
268         cLog.msg(Log::PRIO_NOTICE) << "autodetected remote host " << remote_end;
269         createConnection(remote_end, gOpt.getSeqWindowSize(),mux);
270       }
271
272       ConnectionMap::iterator cit = gConnectionList.getConnection(mux);
273       if(cit == gConnectionList.getEnd()) {
274         continue;
275       }
276       ConnectionParam& conn = cit->second;
277
278       // check whether auth tag is ok or not
279       if(!a->checkTag(conn.kd_, encrypted_packet)) {
280         cLog.msg(Log::PRIO_NOTICE) << "wrong Authentication Tag!";
281         continue;
282       }
283
284       // Replay Protection
285       if(conn.seq_window_.checkAndAdd(encrypted_packet.getSenderId(), encrypted_packet.getSeqNr())) {
286         cLog.msg(Log::PRIO_NOTICE) << "Replay attack from " << conn.remote_end_
287                                    << " seq:"<< encrypted_packet.getSeqNr() << " sid: "<< encrypted_packet.getSenderId();
288         continue;
289       }
290
291       //Allow dynamic IP changes
292       //TODO: add command line option to turn this off
293       if(remote_end != conn.remote_end_) {
294         cLog.msg(Log::PRIO_NOTICE) << "connection "<< mux << " autodetected remote host ip changed " << remote_end;
295         conn.remote_end_=remote_end;
296 #ifndef ANYTUN_NOSYNC
297         SyncCommand sc(gConnectionList,mux);
298         gSyncQueue.push(sc);
299 #endif
300       }
301       // ignore zero length packets
302       if(encrypted_packet.getPayloadLength() <= PlainPacket::getHeaderLength()) {
303         continue;
304       }
305
306       // decrypt packet
307       c->decrypt(conn.kd_, encrypted_packet, plain_packet);
308
309       // check payload_type
310       if((dev->getType() == TYPE_TUN && plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN4 &&
311           plain_packet.getPayloadType() != PAYLOAD_TYPE_TUN6) ||
312           (dev->getType() == TYPE_TAP && plain_packet.getPayloadType() != PAYLOAD_TYPE_TAP)) {
313         continue;
314       }
315
316       // write it on the device
317       dev->write(plain_packet.getPayload(), plain_packet.getLength());
318     }
319   } catch(std::runtime_error& e) {
320     cLog.msg(Log::PRIO_ERROR) << "receiver thread died due to an uncaught runtime_error: " << e.what();
321   } catch(std::exception& e) {
322     cLog.msg(Log::PRIO_ERROR) << "receiver thread died due to an uncaught exception: " << e.what();
323   }
324 }
325
326 void startSendRecvThreads(TunDevice* dev, PacketSource* src)
327 {
328   src->waitUntilReady();
329
330   boost::thread(boost::bind(sender, dev, src));
331   boost::thread(boost::bind(receiver, dev, src));
332 }
333
334
335 #ifdef WIN_SERVICE
336 int main(int argc, char* argv[])
337 {
338   try {
339     if(argc > 1) {
340       if(std::string(argv[1]) == "install") {
341         WinService::install();
342         return 0;
343       } else if(std::string(argv[1]) == "uninstall") {
344         WinService::uninstall();
345         return 0;
346       }
347     }
348     WinService::start();
349     return 0;
350   } catch(std::runtime_error& e) {
351     std::cout << "caught runtime error, exiting: " << e.what() << std::endl;
352   } catch(std::exception& e) {
353     std::cout << "caught exception, exiting: " << e.what() << std::endl;
354   }
355 }
356
357 int real_main(int argc, char* argv[], WinService& service)
358 {
359 #else
360 int main(int argc, char* argv[])
361 {
362   DaemonService service;
363 #endif
364   try {
365     try {
366       if(!gOpt.parse(argc, argv)) {
367         exit(0);
368       }
369
370       StringList targets = gOpt.getLogTargets();
371       for(StringList::const_iterator it = targets.begin(); it != targets.end(); ++it) {
372         cLog.addTarget(*it);
373       }
374     } catch(syntax_error& e) {
375       std::cerr << e << std::endl;
376       gOpt.printUsage();
377       exit(-1);
378     }
379
380     cLog.msg(Log::PRIO_NOTICE) << "anytun started...";
381     gOpt.parse_post(); // print warnings
382
383     // daemonizing has to done before any thread gets started
384     service.initPrivs(gOpt.getUsername(), gOpt.getGroupname());
385     if(gOpt.getDaemonize()) {
386       service.daemonize();
387     }
388
389     OptionNetwork net = gOpt.getIfconfigParam();
390     TunDevice dev(gOpt.getDevName(), gOpt.getDevType(), net.net_addr, net.prefix_length);
391     cLog.msg(Log::PRIO_NOTICE) << "dev opened - name '" << dev.getActualName() << "', node '" << dev.getActualNode() << "'";
392     cLog.msg(Log::PRIO_NOTICE) << "dev type is '" << dev.getTypeString() << "'";
393
394     SysExec* postup_script = NULL;
395     if(gOpt.getPostUpScript() != "") {
396       cLog.msg(Log::PRIO_NOTICE) << "executing post-up script '" << gOpt.getPostUpScript() << "'";
397       StringVector args = boost::assign::list_of(dev.getActualName())(dev.getActualNode());
398       postup_script = new SysExec(gOpt.getPostUpScript(), args);
399     }
400
401     if(gOpt.getChrootDir() != "") {
402       try {
403         service.chroot(gOpt.getChrootDir());
404       } catch(const std::runtime_error& e) {
405         cLog.msg(Log::PRIO_WARNING) << "ignoring chroot error: " << e.what();
406       }
407     }
408     service.dropPrivs();
409
410     // this has to be called before the first thread is started
411     gSignalController.init(service);
412     gResolver.init();
413     boost::thread(boost::bind(&TunDevice::waitUntilReady,&dev));
414     if(postup_script) {
415       boost::thread(boost::bind(&SysExec::waitAndDestroy,postup_script));
416     }
417
418     initCrypto();
419
420     PacketSource* src = new UDPPacketSource(gOpt.getLocalAddr(), gOpt.getLocalPort());
421
422     if(gOpt.getRemoteAddr() != "") {
423       gResolver.resolveUdp(gOpt.getRemoteAddr(), gOpt.getRemotePort(), boost::bind(createConnectionResolver, _1, gOpt.getSeqWindowSize(), gOpt.getMux()), boost::bind(createConnectionError, _1), gOpt.getResolvAddrType());
424     }
425
426     HostList connect_to = gOpt.getRemoteSyncHosts();
427 #ifndef NO_ROUTING
428     NetworkList routes = gOpt.getRoutes();
429     NetworkList::const_iterator rit;
430     for(rit = routes.begin(); rit != routes.end(); ++rit) {
431       NetworkAddress addr(rit->net_addr);
432       NetworkPrefix prefix(addr, static_cast<uint8_t>(rit->prefix_length));
433       gRoutingTable.addRoute(prefix, gOpt.getMux());
434     }
435     if(connect_to.begin() == connect_to.end() || gOpt.getDevType()!="tun") {
436       cLog.msg(Log::PRIO_NOTICE) << "No sync/control host defined or not a tun device. Disabling multi connection support (routing)";
437       disableRouting=true;
438     }
439 #endif
440
441 #ifndef ANYTUN_NOSYNC
442     boost::thread* syncListenerThread = NULL;
443     if(gOpt.getLocalSyncPort() != "") {
444       syncListenerThread = new boost::thread(boost::bind(syncListener));
445     }
446
447     boost::thread_group connectThreads;
448     for(HostList::const_iterator it = connect_to.begin() ; it != connect_to.end(); ++it) {
449       connectThreads.create_thread(boost::bind(syncConnector, *it));
450     }
451 #endif
452
453     // wait for packet source to finish in a seperate thread in order
454     // to be still able to process signals while waiting
455     boost::thread(boost::bind(startSendRecvThreads, &dev, src));
456
457     int ret = gSignalController.run();
458
459     // TODO: stop all threads and cleanup
460     //
461     //     if(src)
462     //       delete src;
463     //     if(connTo)
464     //       delete connTo;
465     return ret;
466   } catch(std::runtime_error& e) {
467     cLog.msg(Log::PRIO_ERROR) << "uncaught runtime error, exiting: " << e.what();
468     if(!service.isDaemonized()) {
469       std::cout << "uncaught runtime error, exiting: " << e.what() << std::endl;
470     }
471   } catch(std::exception& e) {
472     cLog.msg(Log::PRIO_ERROR) << "uncaught exception, exiting: " << e.what();
473     if(!service.isDaemonized()) {
474       std::cout << "uncaught exception, exiting: " << e.what() << std::endl;
475     }
476   }
477   return -1;
478 }
479
480