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
36 #include <cerrno> // for ENOMEM
38 #include "datatypes.h"
42 #include "plainPacket.h"
43 #include "encryptedPacket.h"
45 #include "keyDerivation.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"
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
);
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
);
89 SyncCommand
sc2 (prefix
);
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();
103 conn
.seq_window_
.addSeqNr(pack
.getSenderId(), pack
.getSeqNr());
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
122 u_int16_t mux
= gOpt
.getMux();
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
);
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
);
138 plain_packet
.setPayloadType(0);
140 if(param
->cl
.empty())
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())
148 ConnectionParam
& conn
= cit
->second
;
150 if(conn
.remote_host_
==""||!conn
.remote_port_
)
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
);
160 c
->encrypt(plain_packet
, encrypted_packet
, conn
.seq_nr_
, gOpt
.getSenderId());
162 encrypted_packet
.setHeader(conn
.seq_nr_
, gOpt
.getSenderId(), mux
);
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_
);
178 void* syncConnector(void* p
)
180 ThreadParam
* param
= reinterpret_cast<ThreadParam
*>(p
);
183 SyncClientSocket
sock(h
,param
->cl
);
185 sock
.Open( param
->connto
.host
, param
->connto
.port
);
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()))
204 Utility::ResolveLocal(); // resolve local hostname
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
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();
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())
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
;
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
);
276 if (!checkPacketSeqNr(encrypted_packet
, conn
))
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
);
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
))
293 // write it on the device
294 param
->dev
.write(plain_packet
.getPayload(), plain_packet
.getLength());
299 #define MIN_GCRYPT_VERSION "1.2.3"
300 // make libgcrypt thread safe
302 GCRY_THREAD_OPTION_PTHREAD_IMPL
;
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
;
318 gcry_error_t err
= gcry_control (GCRYCTL_DISABLE_SECMEM
, 0);
320 std::cout
<< "initLibGCrypt: Failed to disable secure memory: " << gpg_strerror( err
) << std::endl
;
324 // Tell Libgcrypt that initialization has completed.
325 err
= gcry_control(GCRYCTL_INITIALIZATION_FINISHED
);
327 std::cout
<< "initLibGCrypt: Failed to finish the initialization of libgcrypt: " << gpg_strerror( err
) << std::endl
;
331 cLog
.msg(Log::PRIO_NOTICE
) << "initLibGCrypt: libgcrypt init finished";
345 std::cout
<< "running in background now..." << std::endl
;
348 for (fd
=getdtablesize();fd
>=0;--fd
) // close all file descriptors
350 fd
=open("/dev/null",O_RDWR
); // stdin
356 int main(int argc
, char* argv
[])
358 std::cout
<< "anytun - secure anycast tunneling protocol" << std::endl
;
359 if(!gOpt
.parse(argc
, argv
))
364 if(gOpt
.getDaemonize())
367 cLog
.msg(Log::PRIO_NOTICE
) << "anytun started...";
369 SignalController sig
;
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());
375 if(gOpt
.getLocalAddr() == "")
376 src
= new UDPPacketSource(gOpt
.getLocalPort());
378 src
= new UDPPacketSource(gOpt
.getLocalAddr(), gOpt
.getLocalPort());
381 ConnectToList connect_to
= gOpt
.getConnectTo();
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
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
);
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
)
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
);