-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.cpp
467 lines (377 loc) · 14 KB
/
main.cpp
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
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
#include <winsock2.h>
#include <iphlpapi.h>
#include <string>
#include <vector>
#include <sstream>
using namespace std;
#pragma comment(lib, "Ws2_32.lib") // dev-c++ need linker param -lWs2_32
#pragma comment(lib, "iphlpapi.lib") // dev-c++ need linker param -liphlpapi
//flag to do pre-exit processing and then exit
volatile bool exitflag = false;
// needed for NotifyRouteChange
OVERLAPPED overlap;
HANDLE hand = NULL;
class DefaultRouteSplitter {
private:
//(store copy of default route. will modify dest and mask to make routes and later to re-create default route)
PMIB_IPFORWARDROW pRowToSplit;
//arrays of destination addresses and masks for split routes
vector<string> destIPs;
vector<string> maskIPs;
//how many routes
int numOfRoutes;
int addModifiedRoute(const char* dest, const char* mask, BOOL change = false) {
if (this->pRowToSplit == NULL) {
printf("error: no stored default route\n");
return 1;
}
this->pRowToSplit->dwForwardDest = inet_addr(dest);
this->pRowToSplit->dwForwardMask = inet_addr(mask);
printf("adding new route for Destination=%s, Mask=%s\n\t", dest, mask);
DWORD dwStatus;
if (change) {
dwStatus = SetIpForwardEntry(this->pRowToSplit);
} else {
dwStatus = CreateIpForwardEntry(this->pRowToSplit);
}
if (dwStatus == ERROR_SUCCESS)
printf("route add success\n");
else if (dwStatus == ERROR_INVALID_PARAMETER)
printf("Invalid parameter.\n");
else {
printf("route add error: %d", dwStatus);
if (dwStatus == 5010) {
printf(" (route already exists)\n");
}
else {
printf("\n");
}
}
}
int deleteModifiedRoute(const char* dest, const char* mask) {
if (this->pRowToSplit == NULL) {
printf("error: no routes to delete\n");
return 1;
}
this->pRowToSplit->dwForwardDest = inet_addr(dest);
this->pRowToSplit->dwForwardMask = inet_addr(mask);
printf("deleting route for Destination=%s, Mask=%s\n\t", dest, mask);
DWORD dwStatus = DeleteIpForwardEntry(this->pRowToSplit);
if (dwStatus == ERROR_SUCCESS)
printf("delete success\n");
else if (dwStatus == ERROR_INVALID_PARAMETER)
printf("Invalid parameter.\n");
else {
printf("route delete error: %d", dwStatus);
if (dwStatus == 1168) {
printf(" (route does not exist)\n");
}
else {
printf("\n");
}
}
}
public:
DefaultRouteSplitter() {
this->pRowToSplit = NULL;
}
int splitDefaultRoute(int index, vector<string> newDestIPs, vector<string> newMaskIPs) {
//store destination ips and masks into class members
this->destIPs = newDestIPs;
this->maskIPs = newMaskIPs;
this->numOfRoutes = newDestIPs.size();
/* variables used for GetIfForwardTable */
PMIB_IPFORWARDTABLE pIpForwardTable;
DWORD dwSize = 0;
//PMIB_IPFORWARDROW pRow = NULL;
DWORD dwStatus = 0;
pIpForwardTable = (MIB_IPFORWARDTABLE *) malloc(sizeof (MIB_IPFORWARDTABLE));
if (pIpForwardTable == NULL) {
printf("Error allocating memory\n");
return 1;
}
if (GetIpForwardTable(pIpForwardTable, &dwSize, 0) == ERROR_INSUFFICIENT_BUFFER) {
free(pIpForwardTable);
pIpForwardTable = (MIB_IPFORWARDTABLE *) malloc(dwSize);
if (pIpForwardTable == NULL) {
printf("Error allocating memory\n");
return 1;
}
}
if (GetIpForwardTable(pIpForwardTable, &dwSize, 0) != ERROR_SUCCESS) {
printf("GetIpForwardTable failed.\n");
free(pIpForwardTable);
return 1;
}
bool foundDefaultVPNRoute = false;
int defaultRouteIndex;
for (int i = 0; i < (int) pIpForwardTable->dwNumEntries; i++) {
//if default route (==0), and index is the index we are interested in
if (pIpForwardTable->table[i].dwForwardDest == 0 && pIpForwardTable->table[i].dwForwardIfIndex == index) {
foundDefaultVPNRoute = true;
defaultRouteIndex = i;
break; //exit for loop
}
}
bool foundCustomRoute = false;
bool foundAnyVPNRoute = false;
for (int i = 0; i < (int) pIpForwardTable->dwNumEntries; i++) {
// if first one of our routes exists
if (pIpForwardTable->table[i].dwForwardDest == inet_addr(newDestIPs[0].c_str()) && pIpForwardTable->table[i].dwForwardIfIndex == index) {
foundCustomRoute = true;
printf("custom route for interface index %d found\n", index);
foundAnyVPNRoute = true;
break; //exit for loop
}
}
if (!foundCustomRoute){
printf("custom route for interface index %d NOT found\n", index);
}
if (!foundCustomRoute) {
for (int i = 0; i < (int) pIpForwardTable->dwNumEntries; i++) {
// if any VPN route exists
if (pIpForwardTable->table[i].dwForwardIfIndex == index) {
foundAnyVPNRoute = true;
break; //exit for loop
}
}
if (!foundAnyVPNRoute){
printf("no routes for index %d found\n", index);
}
}
if (foundDefaultVPNRoute) {
printf("default route for interface index %d found\n\t", index);
//copy route row to class member so we can change it a bit and re-add it later
this->pRowToSplit = (PMIB_IPFORWARDROW) malloc(sizeof (MIB_IPFORWARDROW));
if (!this->pRowToSplit) {
printf("Malloc failed. Out of memory.\n");
free(pIpForwardTable);
return 1;
}
memcpy(this->pRowToSplit, &(pIpForwardTable->table[defaultRouteIndex]), sizeof (MIB_IPFORWARDROW));
printf("deleting... ");
dwStatus = DeleteIpForwardEntry(&(pIpForwardTable->table[defaultRouteIndex]));
if (dwStatus != ERROR_SUCCESS) {
printf("delete FAILED\n");
//free(this->pRowToSplit);
free(pIpForwardTable);
return 1;
}
printf("delete success\n");
//add new routes for VPN sites
for (int i = 0; i < this->numOfRoutes; i++) {
deleteModifiedRoute(this->destIPs[i].c_str(), this->maskIPs[i].c_str());
addModifiedRoute(this->destIPs[i].c_str(), this->maskIPs[i].c_str());
}
}
if (foundAnyVPNRoute && !foundCustomRoute) {
//add new routes for VPN sites
for (int i = 0; i < this->numOfRoutes; i++) {
addModifiedRoute(this->destIPs[i].c_str(), this->maskIPs[i].c_str());
}
}
//free(this->pRowToSplit);
free(pIpForwardTable);
if (foundDefaultVPNRoute == false) {
printf("default route for interface index %d NOT found\n", index);
return 1;
}
return 0;
}
// restore default route and delete all the split routes that we added
int restoreDefaultRoute() {
printf("restoring default route\n");
// default route has destination and mask = 0.0.0.0
addModifiedRoute("0.0.0.0", "0.0.0.0");
// delete new routes for VPN sites that we added previously
for (int i = 0; i < this->numOfRoutes; i++) {
deleteModifiedRoute(this->destIPs[i].c_str(), this->maskIPs[i].c_str());
}
}
};
//make routesplitter object
DefaultRouteSplitter vpnDefaultRouteSplitter;
BOOL IsElevated() {
BOOL fRet = FALSE;
HANDLE hToken = NULL;
if( OpenProcessToken( GetCurrentProcess( ), TOKEN_QUERY, &hToken ) ) {
TOKEN_ELEVATION Elevation;
DWORD cbSize = sizeof( TOKEN_ELEVATION );
if( GetTokenInformation( hToken, TokenElevation, &Elevation, sizeof( Elevation ), &cbSize ) ) {
fRet = Elevation.TokenIsElevated;
}
}
if( hToken ) {
CloseHandle( hToken );
}
return fRet;
}
int getInterfaceIndexFromDesc(string Desc) {
int Index = -1;
ULONG buflen = sizeof(IP_ADAPTER_INFO);
IP_ADAPTER_INFO *pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);
if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_BUFFER_OVERFLOW) {
free(pAdapterInfo);
pAdapterInfo = (IP_ADAPTER_INFO *)malloc(buflen);
}
if (GetAdaptersInfo(pAdapterInfo, &buflen) == ERROR_SUCCESS) {
for (IP_ADAPTER_INFO *pAdapter = pAdapterInfo; pAdapter; pAdapter = pAdapter->Next) {
string strDescription(pAdapter->Description);
switch (strDescription.compare(Desc)) {
case 0:
// printf("found Interface\n");
// printf("desc=\"%s\"\nip=%s\nname=%s\nindex=%d\n",
// pAdapter->Description,
// pAdapter->IpAddressList.IpAddress.String,
// pAdapter->AdapterName,
// pAdapter->Index);
Index = pAdapter->Index;
break;
}
}
}
if (pAdapterInfo) free(pAdapterInfo);
return Index;
}
BOOL CtrlHandler( DWORD fdwCtrlType ) {
switch( fdwCtrlType ) {
case CTRL_C_EVENT:
case CTRL_CLOSE_EVENT:
case CTRL_BREAK_EVENT:
case CTRL_LOGOFF_EVENT:
case CTRL_SHUTDOWN_EVENT:
exitflag = true;
// unregister to route change events
CancelIPChangeNotify(&overlap);
WSAResetEvent(overlap.hEvent);
vpnDefaultRouteSplitter.restoreDefaultRoute();
Sleep(1000);
return FALSE;
default:
return FALSE;
}
}
//funcs for string splitting
template<typename Out>
void split(const std::string &s, char delim, Out result) {
std::stringstream ss(s);
std::string item;
while (std::getline(ss, item, delim)) {
*(result++) = item;
}
}
std::vector<std::string> split(const std::string &s, char delim) {
std::vector<std::string> elems;
split(s, delim, std::back_inserter(elems));
return elems;
}
int main() {
//check that this is run as admin
if (!IsElevated()) {
printf("This program must be run as administrator\n");
system("pause");
return 1;
}
//get folder that this exe is in
char thisexepath[MAX_PATH]; //or wchar_t * buffer;
GetModuleFileName(NULL, thisexepath, MAX_PATH);
std::vector<std::string> thisexepath_v = split(thisexepath, '\\');
std::string exefolder;
for (int idx = 0; idx < thisexepath_v.size() - 1; idx++) {
exefolder += thisexepath_v[idx] + "\\";
}
//ini filename
std::string inifilename (exefolder + "config.ini");
//printf("%s\n", inifilename.c_str());
//ini section name
std::string inisectionname ("config");
//base names for ini keys
std::string addrbasekeyname ("dest");
std::string maskbasekeyname ("mask");
// max num of keybasenameX to check
int max_keynum = 100;
std::string keyname;
//buffers to temp hold number to be appended to keybasename and value read from ini
char numstring[3];
char valuestring[100];
//make string vectors to hold addr and mask strings
vector<string> newDestIPs_v;
vector<string> newMaskIPs_v;
//read addresses and masks from ini
//try to read keybasenameX from 1 thru max_keynum
for (int keynum = 1; keynum <= max_keynum; keynum++) {
//convert keynum to string and append to keybasename
keyname = addrbasekeyname + itoa(keynum, numstring, 10);
//read value from ini. if not found, valuestring will get zero-length string "" and we will stop trying to read more keys
GetPrivateProfileString(inisectionname.c_str(), keyname.c_str(), NULL, valuestring, sizeof(valuestring) / sizeof(valuestring[0]), inifilename.c_str());
if (*valuestring == 0) {
//printf("%s NOT FOUND\n", keyname.c_str());
break;
}
//printf("%s = %s\n", keyname.c_str(), valuestring);
//add value to end of valuevector
newDestIPs_v.push_back(valuestring);
//convert keynum to string and append to keybasename
keyname = maskbasekeyname + itoa(keynum, numstring, 10);
//read value from ini. if not found, valuestring will get zero-length string "" and we will stop trying to read more keys
GetPrivateProfileString(inisectionname.c_str(), keyname.c_str(), NULL, valuestring, sizeof(valuestring) / sizeof(valuestring[0]), inifilename.c_str());
if (*valuestring == 0) {
//printf("%s NOT FOUND\n", keyname.c_str());
newDestIPs_v.pop_back(); //delete last addr we added since there is no mask to go with it
break;
}
//printf("%s = %s\n", keyname.c_str(), valuestring);
//add value to end of valuevector
newMaskIPs_v.push_back(valuestring);
}
GetPrivateProfileString(inisectionname.c_str(), "VPNDesc", NULL, valuestring, sizeof(valuestring) / sizeof(valuestring[0]), inifilename.c_str());
printf("\"%s\"\n", valuestring);
if (*valuestring == 0) {
printf("VPNDesc not found in config file\n");
system("pause");
return 1;
}
string VPNDesc = valuestring;
//just output valuevector elements
// for (int idx = 0; idx < newDestIPs_v.size(); idx++) {
// printf("%s\n", newDestIPs_v[idx].c_str());
// printf("%s\n", newMaskIPs_v[idx].c_str());
// }
// return 0;
//set handler for close events
SetConsoleCtrlHandler( (PHANDLER_ROUTINE) CtrlHandler, TRUE );
//set initial route change notification
overlap.hEvent = WSACreateEvent();
NotifyRouteChange(&hand, &overlap);
//main loop checking for route change
while (true) {
time_t t = time(NULL);
char mbstr[100];
strftime(mbstr, sizeof(mbstr), "%Y/%m/%d %H:%M:%S", localtime(&t));
printf("%s\n", mbstr);
int VPNIndex = getInterfaceIndexFromDesc(VPNDesc);
if (VPNIndex != -1) {
printf("Found %s index: %d\n", VPNDesc.c_str(), VPNIndex);
}
else {
//this happens a bunch after resuming from sleep for some reason...
printf("Couldn't find VPN interface\n");
goto endloop; // if we can't find the interface then just skip past changing routes
// system("pause");
// return 1;
}
//delete default route and replace with non-default routes
vpnDefaultRouteSplitter.splitDefaultRoute(VPNIndex, newDestIPs_v, newMaskIPs_v);
endloop:
printf("\n");
// this will block until route changes, at which point it will run everything in the loop again
WaitForSingleObject(overlap.hEvent, INFINITE);
// just get stuck here until close event finishes and the program exits
if (exitflag) {
while (true) { };
}
// must call this again to get next event
NotifyRouteChange(&hand, &overlap);
printf("TCP route change detected\n");
}
}