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
43 #include <cerrno> // for ENOMEM
45 #include "datatypes.h"
49 #include "plainPacket.h"
50 #include "encryptedPacket.h"
52 #include "keyDerivation.h"
54 #include "cipherFactory.h"
55 #include "authAlgoFactory.h"
56 #include "keyDerivationFactory.h"
57 #include "signalController.h"
58 #include "packetSource.h"
59 #include "tunDevice.h"
61 #include "seqWindow.h"
62 #include "connectionList.h"
63 #include "routingTable.h"
64 #include "networkAddress.h"
66 #include "syncQueue.h"
67 #include "syncCommand.h"
70 #include "syncSocketHandler.h"
71 #include "syncListenSocket.h"
73 #include "syncSocket.h"
74 #include "syncClientSocket.h"
77 #include "threadParam.h"
79 #define MAX_PACKET_LENGTH 1600
81 #define SESSION_KEYLEN_AUTH 20 // TODO: hardcoded size
82 #define SESSION_KEYLEN_ENCR 16 // TODO: hardcoded size
83 #define SESSION_KEYLEN_SALT 14 // TODO: hardcoded size
85 void createConnection(const std::string
& remote_host
, u_int16_t remote_port
, ConnectionList
& cl
, u_int16_t seqSize
, SyncQueue
& queue
, mux_t mux
)
87 SeqWindow
* seq
= new SeqWindow(seqSize
);
89 KeyDerivation
* kd
= KeyDerivationFactory::create(gOpt
.getKdPrf());
90 kd
->init(gOpt
.getKey(), gOpt
.getSalt());
91 cLog
.msg(Log::PRIO_NOTICE
) << "added connection remote host " << remote_host
<< ":" << remote_port
;
92 ConnectionParam
connparam ( (*kd
), (*seq
), seq_nr_
, remote_host
, remote_port
);
93 cl
.addConnection(connparam
,mux
);
94 NetworkAddress
addr(ipv4
,gOpt
.getIfconfigParamRemoteNetmask().c_str());
95 NetworkPrefix
prefix(addr
,32);
96 gRoutingTable
.addRoute(prefix
,mux
);
97 SyncCommand
sc (cl
,mux
);
99 SyncCommand
sc2 (prefix
);
103 bool checkPacketSeqNr(EncryptedPacket
& pack
,ConnectionParam
& conn
)
105 // compare sender_id and seq with window
106 if(conn
.seq_window_
.hasSeqNr(pack
.getSenderId(), pack
.getSeqNr()))
108 cLog
.msg(Log::PRIO_NOTICE
) << "Replay attack from " << conn
.remote_host_
<<":"<< conn
.remote_port_
109 << " seq:"<<pack
.getSeqNr() << " sid: "<<pack
.getSenderId();
113 conn
.seq_window_
.addSeqNr(pack
.getSenderId(), pack
.getSeqNr());
117 void* sender(void* p
)
121 ThreadParam
* param
= reinterpret_cast<ThreadParam
*>(p
);
123 std::auto_ptr
<Cipher
> c(CipherFactory::create(gOpt
.getCipher()));
124 std::auto_ptr
<AuthAlgo
> a(AuthAlgoFactory::create(gOpt
.getAuthAlgo()) );
126 PlainPacket
plain_packet(MAX_PACKET_LENGTH
);
127 EncryptedPacket
encrypted_packet(MAX_PACKET_LENGTH
);
129 Buffer
session_key(u_int32_t(SESSION_KEYLEN_ENCR
)); // TODO: hardcoded size
130 Buffer
session_salt(u_int32_t(SESSION_KEYLEN_SALT
)); // TODO: hardcoded size
131 Buffer
session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH
)); // TODO: hardcoded size
134 u_int16_t mux
= gOpt
.getMux();
137 plain_packet
.setLength(MAX_PACKET_LENGTH
);
138 encrypted_packet
.withAuthTag(false);
139 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
->dev
.getType() == TYPE_TUN
)
146 plain_packet
.setPayloadType(PAYLOAD_TYPE_TUN
);
147 else if(param
->dev
.getType() == TYPE_TAP
)
148 plain_packet
.setPayloadType(PAYLOAD_TYPE_TAP
);
150 plain_packet
.setPayloadType(0);
152 if(param
->cl
.empty())
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())
160 ConnectionParam
& conn
= cit
->second
;
162 if(conn
.remote_host_
==""||!conn
.remote_port_
)
164 // generate packet-key TODO: do this only when needed
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
);
172 c
->encrypt(plain_packet
, encrypted_packet
, conn
.seq_nr_
, gOpt
.getSenderId(), mux
);
174 encrypted_packet
.setHeader(conn
.seq_nr_
, gOpt
.getSenderId(), mux
);
177 // add authentication tag
178 if(a
->getMaxLength()) {
179 encrypted_packet
.addAuthTag();
180 conn
.kd_
.generate(LABEL_SATP_MSG_AUTH
, encrypted_packet
.getSeqNr(), session_auth_key
);
181 a
->setKey(session_auth_key
);
182 a
->generate(encrypted_packet
);
186 param
->src
.send(encrypted_packet
.getBuf(), encrypted_packet
.getLength(), conn
.remote_host_
, conn
.remote_port_
);
188 catch (std::exception e
)
190 // ignoring icmp port unreachable :) and other socket errors :(
194 catch(std::runtime_error e
)
196 cLog
.msg(Log::PRIO_ERR
) << "sender thread died due to an uncaught runtime_error: " << e
.what();
198 catch(std::exception e
)
200 cLog
.msg(Log::PRIO_ERR
) << "sender thread died due to an uncaught exception: " << e
.what();
205 #ifndef ANYTUN_NOSYNC
206 void* syncConnector(void* p
)
208 ThreadParam
* param
= reinterpret_cast<ThreadParam
*>(p
);
211 SyncClientSocket
sock(h
,param
->cl
);
213 sock
.Open( param
->connto
.host
, param
->connto
.port
);
222 void* syncListener(void* p
)
224 ThreadParam
* param
= reinterpret_cast<ThreadParam
*>(p
);
226 SyncSocketHandler
h(param
->queue
);
227 SyncListenSocket
<SyncSocket
,ConnectionList
> l(h
,param
->cl
);
229 if (l
.Bind(gOpt
.getLocalSyncPort()))
232 Utility::ResolveLocal(); // resolve local hostname
241 void* receiver(void* p
)
245 ThreadParam
* param
= reinterpret_cast<ThreadParam
*>(p
);
247 std::auto_ptr
<Cipher
> c( CipherFactory::create(gOpt
.getCipher()) );
248 std::auto_ptr
<AuthAlgo
> a( AuthAlgoFactory::create(gOpt
.getAuthAlgo()) );
250 EncryptedPacket
encrypted_packet(MAX_PACKET_LENGTH
);
251 PlainPacket
plain_packet(MAX_PACKET_LENGTH
);
253 Buffer
session_key(u_int32_t(SESSION_KEYLEN_ENCR
)); // TODO: hardcoded size
254 Buffer
session_salt(u_int32_t(SESSION_KEYLEN_SALT
)); // TODO: hardcoded size
255 Buffer
session_auth_key(u_int32_t(SESSION_KEYLEN_AUTH
)); // TODO: hardcoded size
260 u_int16_t remote_port
;
262 plain_packet
.setLength(MAX_PACKET_LENGTH
);
263 encrypted_packet
.withAuthTag(false);
264 encrypted_packet
.setLength(MAX_PACKET_LENGTH
);
266 // read packet from socket
267 u_int32_t len
= param
->src
.recv(encrypted_packet
.getBuf(), encrypted_packet
.getLength(), remote_host
, remote_port
);
268 encrypted_packet
.setLength(len
);
270 mux_t mux
= encrypted_packet
.getMux();
272 if(gOpt
.getRemoteAddr() == "" && param
->cl
.empty())
274 cLog
.msg(Log::PRIO_NOTICE
) << "autodetected remote host " << remote_host
<< ":" << remote_port
;
275 createConnection(remote_host
, remote_port
, param
->cl
, gOpt
.getSeqWindowSize(),param
->queue
,mux
);
278 ConnectionMap::iterator cit
= param
->cl
.getConnection(mux
);
279 if (cit
== param
->cl
.getEnd())
281 ConnectionParam
& conn
= cit
->second
;
283 // check whether auth tag is ok or not
284 if(a
->getMaxLength()) {
285 encrypted_packet
.withAuthTag(true);
286 conn
.kd_
.generate(LABEL_SATP_MSG_AUTH
, encrypted_packet
.getSeqNr(), session_auth_key
);
287 a
->setKey(session_auth_key
);
288 if(!a
->checkTag(encrypted_packet
)) {
289 cLog
.msg(Log::PRIO_NOTICE
) << "wrong Authentication Tag!" << std::endl
;
292 encrypted_packet
.removeAuthTag();
295 //Allow dynamic IP changes
296 //TODO: add command line option to turn this off
297 if (remote_host
!= conn
.remote_host_
|| remote_port
!= conn
.remote_port_
)
299 cLog
.msg(Log::PRIO_NOTICE
) << "connection "<< mux
<< " autodetected remote host ip changed "
300 << remote_host
<< ":" << remote_port
;
301 conn
.remote_host_
=remote_host
;
302 conn
.remote_port_
=remote_port
;
303 SyncCommand
sc (param
->cl
,mux
);
304 param
->queue
.push(sc
);
308 if (!checkPacketSeqNr(encrypted_packet
, conn
))
311 // generate packet-key
312 conn
.kd_
.generate(LABEL_SATP_ENCRYPTION
, encrypted_packet
.getSeqNr(), session_key
);
313 conn
.kd_
.generate(LABEL_SATP_SALT
, encrypted_packet
.getSeqNr(), session_salt
);
314 c
->setKey(session_key
);
315 c
->setSalt(session_salt
);
318 c
->decrypt(encrypted_packet
, plain_packet
);
320 // check payload_type
321 if((param
->dev
.getType() == TYPE_TUN
&& plain_packet
.getPayloadType() != PAYLOAD_TYPE_TUN4
&&
322 plain_packet
.getPayloadType() != PAYLOAD_TYPE_TUN6
) ||
323 (param
->dev
.getType() == TYPE_TAP
&& plain_packet
.getPayloadType() != PAYLOAD_TYPE_TAP
))
326 // write it on the device
327 param
->dev
.write(plain_packet
.getPayload(), plain_packet
.getLength());
330 catch(std::runtime_error e
)
332 cLog
.msg(Log::PRIO_ERR
) << "sender thread died due to an uncaught runtime_error: " << e
.what();
334 catch(std::exception e
)
336 cLog
.msg(Log::PRIO_ERR
) << "receiver thread died due to an uncaught exception: " << e
.what();
341 #define MIN_GCRYPT_VERSION "1.2.0"
342 #if defined(__GNUC__) && !defined(__OpenBSD__) // TODO: thread-safety on OpenBSD
343 // make libgcrypt thread safe
345 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
351 // make libgcrypt thread safe
352 // this must be called before any other libgcrypt call
353 #if defined(__GNUC__) && !defined(__OpenBSD__) // TODO: thread-safety on OpenBSD
354 gcry_control( GCRYCTL_SET_THREAD_CBS
, &gcry_threads_pthread
);
357 // this must be called right after the GCRYCTL_SET_THREAD_CBS command
358 // no other function must be called till now
359 if( !gcry_check_version( MIN_GCRYPT_VERSION
) ) {
360 std::cout
<< "initLibGCrypt: Invalid Version of libgcrypt, should be >= " << MIN_GCRYPT_VERSION
<< std::endl
;
364 gcry_error_t err
= gcry_control (GCRYCTL_DISABLE_SECMEM
, 0);
366 char buf
[STERROR_TEXT_MAX
];
368 std::cout
<< "initLibGCrypt: Failed to disable secure memory: " << gpg_strerror_r(err
, buf
, STERROR_TEXT_MAX
) << std::endl
;
372 // Tell Libgcrypt that initialization has completed.
373 err
= gcry_control(GCRYCTL_INITIALIZATION_FINISHED
);
375 char buf
[STERROR_TEXT_MAX
];
377 std::cout
<< "initLibGCrypt: Failed to finish initialization: " << gpg_strerror_r(err
, buf
, STERROR_TEXT_MAX
) << std::endl
;
381 cLog
.msg(Log::PRIO_NOTICE
) << "initLibGCrypt: libgcrypt init finished";
385 void chrootAndDrop(std::string
const& chrootdir
, std::string
const& username
)
389 std::cerr
<< "this programm has to be run as root in order to run in a chroot" << std::endl
;
393 struct passwd
*pw
= getpwnam(username
.c_str());
395 if(chroot(chrootdir
.c_str()))
397 std::cerr
<< "can't chroot to " << chrootdir
<< std::endl
;
400 cLog
.msg(Log::PRIO_NOTICE
) << "we are in chroot jail (" << chrootdir
<< ") now" << std::endl
;
402 if (initgroups(pw
->pw_name
, pw
->pw_gid
) || setgid(pw
->pw_gid
) || setuid(pw
->pw_uid
))
404 std::cerr
<< "can't drop to user " << username
<< " " << pw
->pw_uid
<< ":" << pw
->pw_gid
<< std::endl
;
407 cLog
.msg(Log::PRIO_NOTICE
) << "dropped user to " << username
<< " " << pw
->pw_uid
<< ":" << pw
->pw_gid
<< std::endl
;
411 std::cerr
<< "unknown user " << username
<< std::endl
;
426 // std::cout << "running in background now..." << std::endl;
429 // for (fd=getdtablesize();fd>=0;--fd) // close all file descriptors
430 for (fd
=0;fd
<=2;fd
++) // close all file descriptors
432 fd
=open("/dev/null",O_RDWR
); // stdin
438 int execScript(string
const& script
, string
const& ifname
)
444 for (fd
=getdtablesize();fd
>=0;--fd
) // close all file descriptors
446 fd
=open("/dev/null",O_RDWR
); // stdin
449 return execl("/bin/sh", "/bin/sh", script
.c_str(), ifname
.c_str(), NULL
);
452 waitpid(pid
, &status
, 0);
456 int main(int argc
, char* argv
[])
458 bool daemonized
=false;
462 // std::cout << "anytun - secure anycast tunneling protocol" << std::endl;
463 if(!gOpt
.parse(argc
, argv
)) {
468 cLog
.msg(Log::PRIO_NOTICE
) << "anytun started...";
470 std::ofstream pidFile
;
471 if(gOpt
.getPidFile() != "") {
472 pidFile
.open(gOpt
.getPidFile().c_str());
473 if(!pidFile
.is_open()) {
474 std::cout
<< "can't open pid file" << std::endl
;
478 TunDevice
dev(gOpt
.getDevName() =="" ? NULL
: gOpt
.getDevName().c_str(),
479 gOpt
.getDevType() =="" ? NULL
: gOpt
.getDevType().c_str(),
480 gOpt
.getIfconfigParamLocal() =="" ? NULL
: gOpt
.getIfconfigParamLocal().c_str(),
481 gOpt
.getIfconfigParamRemoteNetmask() =="" ? NULL
: gOpt
.getIfconfigParamRemoteNetmask().c_str());
482 cLog
.msg(Log::PRIO_NOTICE
) << "dev created (opened)";
483 cLog
.msg(Log::PRIO_NOTICE
) << "dev opened - actual name is '" << dev
.getActualName() << "'";
484 cLog
.msg(Log::PRIO_NOTICE
) << "dev type is '" << dev
.getTypeString() << "'";
485 if(gOpt
.getPostUpScript() != "") {
486 int postup_ret
= execScript(gOpt
.getPostUpScript(), dev
.getActualName());
487 cLog
.msg(Log::PRIO_NOTICE
) << "post up script '" << gOpt
.getPostUpScript() << "' returned " << postup_ret
;
491 // Buffer buff(u_int32_t(1600));
495 // len = dev.read(buff.getBuf(), buff.getLength());
496 // std::cout << "read " << len << " bytes from interface " << dev.getActualName() << std::endl;
497 // dev.write(buff.getBuf(), len);
505 chrootAndDrop(gOpt
.getChrootDir(), gOpt
.getUsername());
506 if(gOpt
.getDaemonize())
510 if(pidFile
.is_open()) {
511 pid_t pid
= getpid();
516 SignalController sig
;
520 if(gOpt
.getLocalAddr() == "")
521 src
= new UDPPacketSource(gOpt
.getLocalPort());
523 src
= new UDPPacketSource(gOpt
.getLocalAddr(), gOpt
.getLocalPort());
526 ConnectToList connect_to
= gOpt
.getConnectTo();
529 if(gOpt
.getRemoteAddr() != "")
530 createConnection(gOpt
.getRemoteAddr(),gOpt
.getRemotePort(),cl
,gOpt
.getSeqWindowSize(), queue
, gOpt
.getMux());
532 ThreadParam
p(dev
, *src
, cl
, queue
,*(new OptionConnectTo()));
534 // this must be called before any other libgcrypt call
538 pthread_t senderThread
;
539 pthread_create(&senderThread
, NULL
, sender
, &p
);
540 pthread_t receiverThread
;
541 pthread_create(&receiverThread
, NULL
, receiver
, &p
);
542 #ifndef ANYTUN_NOSYNC
543 pthread_t syncListenerThread
;
544 if ( gOpt
.getLocalSyncPort())
545 pthread_create(&syncListenerThread
, NULL
, syncListener
, &p
);
547 std::list
<pthread_t
> connectThreads
;
548 for(ConnectToList::iterator it
= connect_to
.begin() ;it
!= connect_to
.end(); ++it
) {
549 connectThreads
.push_back(pthread_t());
550 ThreadParam
* point
= new ThreadParam(dev
, *src
, cl
, queue
,*it
);
551 pthread_create(& connectThreads
.back(), NULL
, syncConnector
, point
);
557 pthread_cancel(senderThread
);
558 pthread_cancel(receiverThread
);
559 #ifndef ANYTUN_NOSYNC
560 if ( gOpt
.getLocalSyncPort())
561 pthread_cancel(syncListenerThread
);
562 for( std::list
<pthread_t
>::iterator it
= connectThreads
.begin() ;it
!= connectThreads
.end(); ++it
)
566 pthread_join(senderThread
, NULL
);
567 pthread_join(receiverThread
, NULL
);
568 #ifndef ANYTUN_NOSYNC
569 if ( gOpt
.getLocalSyncPort())
570 pthread_join(syncListenerThread
, NULL
);
572 for( std::list
<pthread_t
>::iterator it
= connectThreads
.begin() ;it
!= connectThreads
.end(); ++it
)
573 pthread_join(*it
, NULL
);
580 catch(std::runtime_error e
)
583 cLog
.msg(Log::PRIO_ERR
) << "uncaught runtime error, exiting: " << e
.what();
585 std::cout
<< "uncaught runtime error, exiting: " << e
.what() << std::endl
;
587 catch(std::exception e
)
590 cLog
.msg(Log::PRIO_ERR
) << "uncaught exception, exiting: " << e
.what();
592 std::cout
<< "uncaught exception, exiting: " << e
.what() << std::endl
;