summaryrefslogtreecommitdiff
path: root/src/win32/tunDevice.cpp
blob: 9d95b3048f132aaafae2eeb5a9488837f1622de4 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
/*
 *  anytun
 *
 *  The secure anycast tunneling protocol (satp) defines a protocol used
 *  for communication between any combination of unicast and anycast
 *  tunnel endpoints.  It has less protocol overhead than IPSec in Tunnel
 *  mode and allows tunneling of every ETHER TYPE protocol (e.g.
 *  ethernet, ip, arp ...). satp directly includes cryptography and
 *  message authentication based on the methodes used by SRTP.  It is
 *  intended to deliver a generic, scaleable and secure solution for
 *  tunneling and relaying of packets of any protocol.
 *
 *
 *  Copyright (C) 2007-2008 Othmar Gsenger, Erwin Nindl, 
 *                          Christian Pointner <satp@wirdorange.org>
 *
 *  This file is part of Anytun.
 *
 *  Anytun is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License version 3 as
 *  published by the Free Software Foundation.
 *
 *  Anytun is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with anytun.  If not, see <http://www.gnu.org/licenses/>.
 */

#include <string.h>
#include <sstream>
#include <windows.h>
#include <winioctl.h>

#include "../endian.h"
#include "../tunDevice.h"
#include "../threadUtils.hpp"
#include "../log.h"

#include "registryKey.h"
#include "common.h"

#define MIN_TAP_VER_MAJOR 8
#define MIN_TAP_VER_MINOR 2

TunDevice::TunDevice(std::string dev_name, std::string dev_type, std::string ifcfg_addr, u_int16_t ifcfg_prefix) : conf_(dev_name, dev_type, ifcfg_addr, ifcfg_prefix, 1400)
{
  if(conf_.type_ != TYPE_TUN && conf_.type_ != TYPE_TAP)
    throw std::runtime_error("unable to recognize type of device (tun or tap)");

  handle_ = INVALID_HANDLE_VALUE;
  if(!getAdapter(dev_name))
    throw std::runtime_error("can't find any suitable device");

  if(handle_ == INVALID_HANDLE_VALUE) {
    std::stringstream tapname;
	  tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX;
    handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
    if(handle_ == INVALID_HANDLE_VALUE) {
      std::stringstream msg;
      msg << "Unable to open device: " << actual_node_ << " (" << actual_name_ << "): " << LogErrno(GetLastError());
      throw std::runtime_error(msg.str());
	  }
  }

  DWORD err;
  u_long info[3];
  info[0] = info[1] = info[2] = 0;
  err = performIoControl(TAP_IOCTL_GET_VERSION, info, sizeof(info), info, sizeof(info));
  if(err != ERROR_SUCCESS) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "Unable to get device version: " << LogErrno(err);
	  throw std::runtime_error(msg.str());
  }
  cLog.msg(Log::PRIO_NOTICE) << "Windows TAP Driver Version " << info[0] << "." << info[1] << " " << (info[2] ? "(DEBUG)" : "");
  if(!(info[0] > MIN_TAP_VER_MAJOR || (info[0] == MIN_TAP_VER_MAJOR && info[1] >= MIN_TAP_VER_MINOR))) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "need a higher Version of TAP Driver (at least " << MIN_TAP_VER_MAJOR << "." << MIN_TAP_VER_MINOR << ")";
	  throw std::runtime_error(msg.str());
  }

  if(conf_.type_ == TYPE_TUN) {
    u_long ep[3];
    ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong());
    ep[1] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong());
    ep[2] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong());
    err = performIoControl(TAP_IOCTL_CONFIG_TUN, ep, sizeof(ep), ep, sizeof(ep));
    if(err != ERROR_SUCCESS) {
      CloseHandle(handle_);
      std::stringstream msg;
      msg << "Unable to set device tun mode: " << LogErrno(err);
	    throw std::runtime_error(msg.str());
    }
  }

  if(ifcfg_addr != "")
    do_ifconfig();

  int status = true;
  err = performIoControl(TAP_IOCTL_SET_MEDIA_STATUS, &status, sizeof(status), &status, sizeof(status));
  if(err != ERROR_SUCCESS) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "Unable to set device media status: " << LogErrno(err);
    throw std::runtime_error(msg.str());
	}

  roverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  woverlapped_.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
}

bool TunDevice::getAdapter(std::string const& dev_name)
{
  RegistryKey akey;
  DWORD err = akey.open(HKEY_LOCAL_MACHINE, ADAPTER_KEY, KEY_ENUMERATE_SUB_KEYS);
  if(err != ERROR_SUCCESS) {
    std::stringstream msg;
    msg << "Unable to open registry key (HKLM\\" << ADAPTER_KEY << "): " << LogErrno(err);
    throw std::runtime_error(msg.str());
  }
  
  bool found = false;
  for(int i=0; ; ++i) {
    RegistryKey ckey;
    DWORD err = akey.getSubKey(i, ckey, KEY_QUERY_VALUE);
    if(err == ERROR_NO_MORE_ITEMS)
      break;
    if(err != ERROR_SUCCESS)
      continue;

    try {
	  if(ckey["ComponentId"] != TAP_COMPONENT_ID)
        continue;
      actual_node_ = ckey["NetCfgInstanceId"];

      RegistryKey nkey;
      std::stringstream keyname;
      keyname << NETWORK_CONNECTIONS_KEY << "\\" << actual_node_ << "\\Connection";
      err = nkey.open(HKEY_LOCAL_MACHINE, keyname.str().c_str(), KEY_QUERY_VALUE);;
      if(err != ERROR_SUCCESS)
        continue;
	  
	  actual_name_ = nkey["Name"];
	} catch(LogErrno& e) { continue; }

    if(dev_name != "") {
      if(dev_name == actual_name_) {
        found = true;
        break;
      }
    }
    else {
      std::stringstream tapname;
      tapname << USERMODEDEVICEDIR << actual_node_ << TAPSUFFIX;
      handle_ = CreateFileA(tapname.str().c_str(), GENERIC_WRITE | GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_SYSTEM | FILE_FLAG_OVERLAPPED, 0);
      if(handle_ == INVALID_HANDLE_VALUE)
        continue;
      found = true;
      break;
    }
  }
  if(!found) {
    actual_node_ = "";
    actual_name_ = "";
  }
  return found;
}

DWORD TunDevice::performIoControl(DWORD controlCode, LPVOID inBuffer, DWORD inBufferSize, LPVOID outBuffer, DWORD outBufferSize)
{
  OVERLAPPED overlapped;
  overlapped.hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
  overlapped.Offset = 0;
	overlapped.OffsetHigh = 0;
  
  DWORD len;
  if(!DeviceIoControl(handle_, controlCode, inBuffer, inBufferSize, outBuffer, outBufferSize, &len, &overlapped)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(overlapped.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &overlapped, &len, FALSE))
        return GetLastError();
    }
    else
      return GetLastError();
  }
  return ERROR_SUCCESS;
}


TunDevice::~TunDevice()
{
  if(handle_ != INVALID_HANDLE_VALUE)
    CloseHandle(handle_);
  if(roverlapped_.hEvent != INVALID_HANDLE_VALUE)
    CloseHandle(roverlapped_.hEvent);
  if(woverlapped_.hEvent != INVALID_HANDLE_VALUE)
    CloseHandle(woverlapped_.hEvent);
}

int TunDevice::fix_return(int ret, size_t pi_length)
{
// nothing to be done here
	return 0;
}

int TunDevice::read(u_int8_t* buf, u_int32_t len)
{
  DWORD lenout;
  roverlapped_.Offset = 0;
	roverlapped_.OffsetHigh = 0;
  ResetEvent(roverlapped_.hEvent);
  
  if(!ReadFile(handle_, buf, len, &lenout, &roverlapped_)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(roverlapped_.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &roverlapped_, &lenout, FALSE)) {
        cLog.msg(Log::PRIO_ERR) << "Error while trying to get overlapped result: " << LogErrno(GetLastError());
        return -1;
      }
    }
    else {
      cLog.msg(Log::PRIO_ERR) << "Error while reading from device: " << LogErrno(GetLastError());
      return -1;
    }
  }
  return lenout;
}

int TunDevice::write(u_int8_t* buf, u_int32_t len)
{
  DWORD lenout;
  woverlapped_.Offset = 0;
	woverlapped_.OffsetHigh = 0;
  ResetEvent(woverlapped_.hEvent);

	if(!WriteFile(handle_, buf, len, &lenout, &woverlapped_)) {
    DWORD err = GetLastError();
    if(err == ERROR_IO_PENDING) {
      WaitForSingleObject(woverlapped_.hEvent, INFINITE);
      if(!GetOverlappedResult(handle_, &woverlapped_, &lenout, FALSE)) {
        cLog.msg(Log::PRIO_ERR) << "Error while trying to get overlapped result: " << LogErrno(GetLastError());
        return -1;
      }
    }
    else {
      cLog.msg(Log::PRIO_ERR) << "Error while writing to device: " << LogErrno(GetLastError());
      return -1;
    }
  }
  return lenout;	
}

void TunDevice::init_post()
{
// nothing to be done here
}

void TunDevice::do_ifconfig()
{
  u_long ep[4];
  ep[0] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong());
  ep[1] = htonl(conf_.netmask_.getNetworkAddressV4().to_ulong());
  ep[2] = htonl(conf_.addr_.getNetworkAddressV4().to_ulong() & conf_.netmask_.getNetworkAddressV4().to_ulong());
  ep[3] = 365 * 24 * 3600;  // lease time in seconds
  DWORD err = performIoControl(TAP_IOCTL_CONFIG_DHCP_MASQ, ep, sizeof(ep), ep, sizeof(ep));
  if(err != ERROR_SUCCESS) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "Unable to set device dhcp masq mode: " << LogErrno(err);
    throw std::runtime_error(msg.str());
	}

  u_long mtu;
  err = performIoControl(TAP_IOCTL_GET_MTU, &mtu, sizeof(mtu), &mtu, sizeof(mtu));
  if(err != ERROR_SUCCESS) {
    CloseHandle(handle_);
    std::stringstream msg;
    msg << "Unable to get device mtu: " << LogErrno(err);
    throw std::runtime_error(msg.str());
	}
  conf_.mtu_ = static_cast<u_int16_t>(mtu);
}