forked from TunSafe/TunSafe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tunsafe_win32.cpp
2080 lines (1780 loc) · 64.6 KB
/
tunsafe_win32.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
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// SPDX-License-Identifier: AGPL-1.0-only
// Copyright (C) 2018 Ludvig Strigeus <[email protected]>. All Rights Reserved.
#include "stdafx.h"
#include "wireguard_config.h"
#include "network_win32_api.h"
#include "network_win32_dnsblock.h"
#include "tunsafe_wg_plugin.h"
#include <Commctrl.h>
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>
#include <stddef.h>
#include "resource.h"
#include <string.h>
#include <Richedit.h>
#include <vector>
#include <Iphlpapi.h>
#include <assert.h>
#include <shldisp.h>
#include <shlobj.h>
#include <exdisp.h>
#include "tunsafe_endian.h"
#include "util.h"
#include <atlbase.h>
#include <algorithm>
#include "crypto/curve25519/curve25519-donna.h"
#include "service_win32.h"
#include "util_win32.h"
#pragma comment(lib, "iphlpapi.lib")
#pragma comment(lib, "rpcrt4.lib")
#pragma comment(lib,"comctl32.lib")
#pragma comment(linker,"/manifestdependency:\"type='win32' name='Microsoft.Windows.Common-Controls' version='6.0.0.0' processorArchitecture='*' publicKeyToken='6595b64144ccf1df' language='*'\"")
void InitCpuFeatures();
void PrintCpuFeatures();
void Benchmark();
void ShowTwoFactorDialog();
static const char *GetCurrentConfigTitle(char *buf, size_t max_size);
static char *PrintMB(char *buf, int64 bytes);
static void LoadConfigFile(const char *filename, bool save, bool force_start);
static void SetCurrentConfigFilename(const char *filename);
static void CreateLocalOrRemoteBackend(bool remote);
static void UpdateGraphReq();
#pragma warning(disable: 4200)
static bool g_is_connected_to_server;
static bool g_notified_connected_server;
static HWND g_ui_window;
static HICON g_icons[2];
static bool g_minimize_on_connect;
static bool g_ui_visible;
static char *g_current_filename;
static HINSTANCE g_hinstance;
static TunsafeBackend *g_backend;
static TunsafeBackend::Delegate *g_backend_delegate;
static const char *g_cmdline_filename;
static bool g_first_state_msg;
static bool g_is_limited_uac_account;
static bool g_is_tunsafe_service_running;
static bool g_disable_connect_on_start;
static bool g_not_first_status_msg;
static HANDLE g_runonce_mutex;
static int g_startup_flags;
static HKEY g_reg_key;
static HKEY g_hklm_reg_key;
static HKEY g_hklm_readonly_reg_key;
static HWND hwndPaintBox, hwndStatus, hwndGraphBox, hwndTab, hwndAdvancedBox, hwndEdit;
static WgProcessorStats g_processor_stats;
static int g_large_fonts;
static TunsafeBackend::StatusCode g_status_code;
static UINT g_message_taskbar_created;
static int g_current_tab;
static bool wm_dropfiles_recursive;
static bool g_has_icon;
static bool g_twofactor_dialog_shown;
static uint32 g_twofactor_dialog_request;
static int g_selected_graph_type;
static RECT comborect;
static HBITMAP arrowbitmap;
static uint32 g_timestamp_of_exit_menuloop;
enum UpdateIconWhy {
UIW_NONE = 0,
UIW_STOPPED_WORKING_FAIL = 1,
UIW_START = 2,
};
static void UpdateIcon(UpdateIconWhy error);
int RescaleDpi(int size) {
return (g_large_fonts == 96) ? size : size * g_large_fonts / 96;
}
RECT RescaleDpiRect(const RECT &r) {
RECT rr = r;
if (g_large_fonts != 96) {
rr.left = rr.left * g_large_fonts / 96;
rr.top = rr.top * g_large_fonts / 96;
rr.right = rr.right * g_large_fonts / 96;
rr.bottom = rr.bottom * g_large_fonts / 96;
}
return rr;
}
static void SetUiVisibility(bool visible) {
g_ui_visible = visible;
ShowWindow(g_ui_window, visible ? SW_SHOW : SW_HIDE);
g_backend->RequestStats(visible);
UpdateGraphReq();
}
void StopTunsafeBackend(UpdateIconWhy why) {
if (g_backend->is_started()) {
g_backend->Stop();
if (g_is_connected_to_server)
RINFO("Disconnected");
g_is_connected_to_server = false;
UpdateIcon(why);
RegWriteInt(g_reg_key, "IsConnected", 0);
}
}
const char *print_ip(char buf[kSizeOfAddress], uint32 ip) {
snprintf(buf, kSizeOfAddress, "%d.%d.%d.%d", (ip >> 24) & 0xff, (ip >> 16) & 0xff, (ip >> 8) & 0xff, (ip >> 0) & 0xff);
return buf;
}
void StartTunsafeBackend(UpdateIconWhy reason) {
if (!*g_current_filename)
return;
// recreate service connection
if (g_backend->status() == TunsafeBackend::kErrorServiceLost)
CreateLocalOrRemoteBackend(g_backend->is_remote());
if (g_backend->is_remote() && !EnsureValidConfigPath(g_current_filename)) {
RERROR("The config file needs to be in the Config-directory. Maybe the TunSafe\r\n process doesn't match with the running service. Try selecting 'Don't Use a Service'.");
StopTunsafeBackend(UIW_NONE);
return;
}
g_notified_connected_server = false;
g_is_connected_to_server = false;
memset(&g_processor_stats, 0, sizeof(g_processor_stats));
g_backend->Start(g_current_filename);
RegWriteInt(g_reg_key, "IsConnected", 1);
}
static void InvalidatePaintbox() {
InvalidateRect(hwndPaintBox, NULL, FALSE);
}
class MyBackendDelegate : public TunsafeBackend::Delegate {
public:
virtual void OnGraphAvailable() {
InvalidateRect(hwndGraphBox, NULL, FALSE);
}
virtual void OnGetStats(const WgProcessorStats &stats) {
g_processor_stats = stats;
InvalidatePaintbox();
char buf[64];
uint32 mbs_in = (uint32)(stats.data_bytes_in_per_second * (1.0 / 1250));
uint32 gb_in = (uint32)(stats.data_bytes_in * (1.0 / (1024 * 1024 * 1024 / 100)));
snprintf(buf, ARRAYSIZE(buf), "D: %d.%.2d Mbps (%d.%.2d GB)", mbs_in / 100, mbs_in % 100, gb_in / 100, gb_in % 100);
SendMessage(hwndStatus, SB_SETTEXT, 1, (LPARAM)buf);
uint32 mbs_out = (uint32)(stats.data_bytes_out_per_second * (1.0 / 1250));
uint32 gb_out = (uint32)(stats.data_bytes_out * (1.0 / (1024 * 1024 * 1024 / 100)));
snprintf(buf, ARRAYSIZE(buf), "U: %d.%.2d Mbps (%d.%.2d GB)", mbs_out / 100, mbs_out % 100, gb_out / 100, gb_out % 100);
SendMessage(hwndStatus, SB_SETTEXT, 2, (LPARAM)buf);
InvalidateRect(hwndAdvancedBox, NULL, FALSE);
}
virtual void OnLogLine(const char **s) {
const char *line = *s;
size_t len = strlen(line);
char *tmp = (char*)alloca(len + 3);
tmp[len + 0] = '\r';
tmp[len + 1] = '\n';
tmp[len + 2] = 0;
memcpy(tmp, line, len);
CHARRANGE cr;
cr.cpMin = -1;
cr.cpMax = -1;
// hwnd = rich edit hwnd
SendMessage(hwndEdit, EM_EXSETSEL, 0, (LPARAM)&cr);
SendMessage(hwndEdit, EM_REPLACESEL, 0, (LPARAM)tmp);
}
virtual void OnStateChanged() {
if (!g_first_state_msg) {
g_first_state_msg = true;
char fullname[1024];
const char *filename = g_cmdline_filename;
if (filename) {
if (ExpandConfigPath(filename, fullname, sizeof(fullname)))
SetCurrentConfigFilename(fullname);
} else {
std::string currconfig = g_backend->GetConfigFileName();
if (currconfig.empty()) {
char *conf = RegReadStr(g_reg_key, "ConfigFile", "TunSafe.conf");
if (ExpandConfigPath(conf, fullname, sizeof(fullname)))
SetCurrentConfigFilename(fullname);
free(conf);
} else {
SetCurrentConfigFilename(currconfig.c_str());
}
}
if (filename != NULL || !(g_startup_flags & kStartupFlag_BackgroundService) && !g_disable_connect_on_start && RegReadInt(g_reg_key, "IsConnected", 0)) {
StartTunsafeBackend(UIW_START);
} else {
if (!g_backend->is_started())
RINFO("Press Connect to initiate a connection to the WireGuard server.");
}
}
uint32 state = g_backend->GetInternetBlockState();
bool running = g_backend->is_started();
ShowWindow(GetDlgItem(g_ui_window, ID_BTN_KILLSWITCH), (!running || (state & kBlockInternet_Both) == 0) && (state & kBlockInternet_Active) ? SW_SHOW : SW_HIDE);
SetDlgItemText(g_ui_window, ID_START, running ? "Re&connect" : "&Connect");
InvalidatePaintbox();
EnableWindow(GetDlgItem(g_ui_window, ID_STOP), running);
if (running && !g_twofactor_dialog_shown) {
uint32 token_request = g_backend->GetTokenRequest();
if (token_request != 0) {
g_twofactor_dialog_shown = true;
g_twofactor_dialog_request = token_request;
PostMessage(g_ui_window, WM_USER + 3, 0, 0); // show two factor dialog
}
}
}
virtual void OnStatusCode(TunsafeBackend::StatusCode status) override {
if (status != g_status_code)
InvalidatePaintbox();
g_status_code = status;
if (TunsafeBackend::IsPermanentError(status)) {
UpdateIcon(g_is_connected_to_server ? UIW_STOPPED_WORKING_FAIL : UIW_NONE);
return;
}
bool is_connected = (status == TunsafeBackend::kStatusConnected);
if (is_connected && g_minimize_on_connect) {
g_minimize_on_connect = false;
SetUiVisibility(false);
}
bool not_first = g_not_first_status_msg;
g_not_first_status_msg = true;
if (is_connected != g_is_connected_to_server) {
g_is_connected_to_server = is_connected;
// avoid showing a notice if service is already connected
if (is_connected > not_first && (g_startup_flags & kStartupFlag_BackgroundService))
g_notified_connected_server = true;
UpdateIcon(UIW_NONE);
}
}
virtual void OnClearLog() override {
SetWindowText(hwndEdit, "");
}
virtual void OnConfigurationProtocolReply(uint32 ident, const std::string &&reply) override {
}
};
static MyBackendDelegate my_procdel;
static void CreateLocalOrRemoteBackend(bool remote) {
delete g_backend;
if (!remote) {
g_backend = CreateNativeTunsafeBackend(g_backend_delegate);
} else {
RINFO("Connecting to the TunSafe Service...");
g_backend = CreateTunsafeServiceClient(g_backend_delegate);
}
g_backend->RequestStats(g_ui_visible);
}
static char *PrintMB(char *buf, int64 bytes) {
char *bo = buf;
if (bytes < 0) {
*buf++ = '-';
bytes = -bytes;
}
int64 big = bytes / (1024*1024);
int little = bytes % (1024*1024);
if (bytes < 10*1024*1024) {
// X.XXX
snprintf(buf, 64, "%lld.%.3d MB", big, 1000 * little / (1024*1024));
} else if (bytes < 100*1024*1024) {
// XX.XX
snprintf(buf, 64, "%lld.%.2d MB", big, 100 * little / (1024*1024));
} else {
// XX.X
snprintf(buf, 64, "%lld.%.1d MB", big, 10 * little / (1024*1024));
}
return bo;
}
static void UpdateIcon(UpdateIconWhy why) {
NOTIFYICONDATA nid;
memset(&nid, 0, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = g_ui_window;
nid.uID = 1;
nid.uVersion = NOTIFYICON_VERSION;
nid.uCallbackMessage = WM_USER + 1;
nid.uFlags = NIF_MESSAGE | NIF_TIP | NIF_ICON;
nid.hIcon = g_icons[g_is_connected_to_server ? 0 : 1];
char buf[kSizeOfAddress];
char namebuf[128];
if (g_is_connected_to_server) {
snprintf(nid.szTip, sizeof(nid.szTip), "TunSafe [%s - %s]", GetCurrentConfigTitle(namebuf, sizeof(namebuf)), print_ip(buf, g_backend->GetIP()));
if (!g_notified_connected_server) {
g_notified_connected_server = true;
nid.uFlags |= NIF_INFO;
snprintf(nid.szInfoTitle, sizeof(nid.szInfoTitle), "Connected to: %s", namebuf);
snprintf(nid.szInfo, sizeof(nid.szInfo), "IP: %s", buf);
nid.uTimeout = 5000;
nid.dwInfoFlags = NIIF_INFO;
}
} else {
g_notified_connected_server = false;
snprintf(nid.szTip, sizeof(nid.szTip), "TunSafe [%s]", "Disconnected");
if (why == UIW_STOPPED_WORKING_FAIL) {
nid.uFlags |= NIF_INFO;
strcpy(nid.szInfoTitle, "Disconnected!");
strcpy(nid.szInfo, "There was a problem with the connection. You are now disconnected.");
nid.uTimeout = 5000;
nid.dwInfoFlags = NIIF_ERROR;
}
}
Shell_NotifyIcon(g_has_icon ? NIM_MODIFY : NIM_ADD, &nid);
SendMessage(g_ui_window, WM_SETICON, ICON_SMALL, (LPARAM)g_icons[g_is_connected_to_server ? 0 : 1]);
g_has_icon = true;
}
static void RemoveIcon() {
if (g_has_icon) {
NOTIFYICONDATA nid;
memset(&nid, 0, sizeof(nid));
nid.cbSize = sizeof(nid);
nid.hWnd = g_ui_window;
nid.uID = 1;
Shell_NotifyIcon(NIM_DELETE, &nid);
}
}
#define MAX_CONFIG_FILES 1024
#define ID_POPUP_CONFIG_FILE 10000
char *config_filenames[MAX_CONFIG_FILES];
uint8 config_filenames_indent[MAX_CONFIG_FILES];
static char *StripConfExtension(const char *src, char *target, size_t size) {
size_t len = strlen(src);
if (len >= 5 && memcmp(src + len - 5, ".conf", 5) == 0)
len -= 5;
len = std::min(len, size - 1);
target[len] = 0;
memcpy(target, src, len);
return target;
}
static const char *GetCurrentConfigTitle(char *target, size_t size) {
const char *ll = FindFilenameComponent(g_current_filename);
return StripConfExtension(ll, target, size);
}
static void SetCurrentConfigFilename(const char *filename) {
str_set(&g_current_filename, filename);
char namebuf[64];
char *f = str_cat_alloc("TunSafe - ", GetCurrentConfigTitle(namebuf, sizeof(namebuf)));
SetWindowText(g_ui_window, f);
free(f);
InvalidateRect(hwndPaintBox, NULL, FALSE);
}
static void LoadConfigFile(const char *filename, bool save, bool force_start) {
SetCurrentConfigFilename(filename);
if (force_start || g_backend->is_started())
StartTunsafeBackend(UIW_START);
if (save)
RegWriteStr(g_reg_key, "ConfigFile", filename);
}
class ConfigMenuBuilder {
public:
ConfigMenuBuilder();
void Recurse();
int depth_;
int nfiles_;
size_t bufpos_;
WIN32_FIND_DATA wfd_;
char buf_[1024];
};
ConfigMenuBuilder::ConfigMenuBuilder()
: nfiles_(0), depth_(0) {
if (!ExpandConfigPath("", buf_, sizeof(buf_)))
bufpos_ = sizeof(buf_);
else
bufpos_ = strlen(buf_);
}
void ConfigMenuBuilder::Recurse() {
if (bufpos_ >= sizeof(buf_) - 4)
return;
memcpy(buf_ + bufpos_, "*.*", 4);
HANDLE handle = FindFirstFile(buf_, &wfd_);
if (handle != INVALID_HANDLE_VALUE) {
do {
if (wfd_.cFileName[0] == '.')
continue;
size_t len = strlen(wfd_.cFileName);
if (bufpos_ + len >= sizeof(buf_) - 1)
continue;
// Ensure it ends with .conf
if (!(wfd_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && (len < 5 || _strnicmp(&wfd_.cFileName[len - 5], ".conf", 5) != 0))
continue;
size_t old_bufpos = bufpos_;
memcpy(buf_ + bufpos_, wfd_.cFileName, len + 1);
bufpos_ = bufpos_ + len + 1;
config_filenames_indent[nfiles_] = depth_ + !!(wfd_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY);
str_set(&config_filenames[nfiles_], buf_);
nfiles_++;
if (nfiles_ == MAX_CONFIG_FILES)
break;
if (wfd_.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
buf_[bufpos_ - 1] = '\\';
int old_nfiles = nfiles_;
depth_++;
if (depth_ < 16)
Recurse();
depth_--;
// Remove directory if it had no files
if (old_nfiles == nfiles_)
nfiles_--;
if (nfiles_ == MAX_CONFIG_FILES)
break;
}
bufpos_ = old_bufpos;
} while (FindNextFile(handle, &wfd_));
FindClose(handle);
}
}
static int AddToAvailableFilesPopup(HMENU menu, int max_num_items, bool is_settings) {
ConfigMenuBuilder menu_builder;
HMENU where[16] = {0};
menu_builder.Recurse();
bool is_connected = g_backend->is_started();
uint32 last_indent = 0;
where[0] = menu;
for (int i = 0; i < menu_builder.nfiles_; i++) {
uint32 indent = config_filenames_indent[i];
if (indent > last_indent) {
HMENU n = CreatePopupMenu();
where[indent] = n;
AppendMenu(where[last_indent], MF_POPUP, (UINT_PTR)n, FindFilenameComponent(config_filenames[i]));
} else {
bool selected_item = (strcmp(g_current_filename, config_filenames[i]) == 0);
AppendMenu(where[indent], (selected_item && is_connected) ?
MF_CHECKED : 0, ID_POPUP_CONFIG_FILE + i,
StripConfExtension(
FindFilenameComponent(config_filenames[i]), menu_builder.buf_, sizeof(menu_builder.buf_)));
if (selected_item)
SetMenuDefaultItem(where[indent], ID_POPUP_CONFIG_FILE + i, MF_BYCOMMAND);
}
last_indent = indent;
}
if (menu_builder.nfiles_ == 0)
AppendMenu(menu, MF_GRAYED | MF_DISABLED, 0, "(no config files found)");
return menu_builder.nfiles_;
}
static void ShowSettingsMenu(HWND wnd) {
HMENU menu = CreatePopupMenu();
AddToAvailableFilesPopup(menu, 10, true);
//POINT pt;
//GetCursorPos(&pt);
RECT r = GetParentRect(GetDlgItem(g_ui_window, ID_START));
RECT r2 = GetParentRect(hwndPaintBox);
POINT pt = {r2.left, r.bottom};
ClientToScreen(g_ui_window, &pt);
int rv = TrackPopupMenu(menu, 0, pt.x, pt.y, 0, wnd, NULL);
DestroyMenu(menu);
}
static bool HasReadWriteAccess(const char *filename) {
HANDLE fileH = CreateFile(filename,
GENERIC_READ | GENERIC_WRITE,
FILE_SHARE_READ | FILE_SHARE_WRITE, // For Exclusive access
0,
OPEN_EXISTING,
FILE_ATTRIBUTE_NORMAL,
NULL);
if (fileH != INVALID_HANDLE_VALUE) {
CloseHandle(fileH);
return true;
}
return false;
}
static void OpenEditor() {
SHELLEXECUTEINFO shinfo = {0};
shinfo.hwnd = g_ui_window;
shinfo.cbSize = sizeof(shinfo);
shinfo.nShow = SW_SHOWNORMAL;
if (g_current_filename[0]) {
if (!HasReadWriteAccess(g_current_filename)) {
// Need to runas admin
char buf[1024];
if (!ExpandEnvironmentStrings("%windir%\\system32\\notepad.exe", buf, sizeof(buf)))
return;
shinfo.lpFile = buf;
char *filename = str_cat_alloc("\"", g_current_filename, "\"");
shinfo.lpParameters = filename;
shinfo.lpVerb = "runas";
ShellExecuteEx(&shinfo);
free(filename);
} else {
shinfo.fMask = SEE_MASK_CLASSNAME;
shinfo.lpFile = g_current_filename;
shinfo.lpParameters = "";
shinfo.lpClass = ".txt";
ShellExecuteEx(&shinfo);
}
}
}
static void BrowseFiles() {
char buf[MAX_PATH];
if (ExpandConfigPath("", buf, ARRAYSIZE(buf))) {
size_t l = strlen(buf);
buf[l - 1] = 0;
ShellExecuteFromExplorer(buf, NULL, NULL, "explore");
}
}
bool ImportFile(const char *s, bool silent = false) {
char buf[1024];
char mesg[1024];
size_t filesize;
const char *last = FindFilenameComponent(s);
uint8 *filedata = NULL;
bool rv = false;
int filerv;
if (!*last || !ExpandConfigPath(last, buf, ARRAYSIZE(buf)) || _stricmp(buf, s) == 0)
goto out;
filedata = LoadFileSane(s, &filesize);
if (!filedata)
goto out;
if (!silent) {
if (FileExists(buf)) {
snprintf(mesg, ARRAYSIZE(mesg), "A file already exists with the name '%s' in the configuration folder. Do you want to overwrite it?", last);
if (MessageBoxA(g_ui_window, mesg, "TunSafe", MB_OKCANCEL | MB_ICONEXCLAMATION) != IDOK)
goto out;
} else {
snprintf(mesg, ARRAYSIZE(mesg), "Do you want to import '%s' into TunSafe?", last);
if (MessageBoxA(g_ui_window, mesg, "TunSafe", MB_OKCANCEL | MB_ICONQUESTION) != IDOK)
goto out;
}
}
filerv = WriteOutFile(buf, filedata, filesize);
// elevate?
if (filerv == kWriteOutFile_AccessError && g_is_limited_uac_account) {
char *args = str_cat_alloc("--import \"", s, "\"");
rv = RunProcessAsAdminWithArgs(args, true);
free(args);
return rv;
}
rv = (filerv == kWriteOutFile_Ok);
if (!rv)
DeleteFileA(buf);
out:
free(filedata);
if (!silent) {
if (rv)
LoadConfigFile(buf, true, false);
else
MessageBoxA(g_ui_window, "There was a problem importing the file.", "TunSafe", MB_ICONEXCLAMATION);
}
return !rv;
}
void ShowUI(HWND hWnd) {
SetUiVisibility(true);
BringWindowToTop(hWnd);
SetForegroundWindow(hWnd);
}
void HandleDroppedFiles(HWND wnd, HDROP hdrop) {
char buf[MAX_PATH];
if (DragQueryFile(hdrop, -1, NULL, 0) == 1) {
if (DragQueryFile(hdrop, 0, buf, ARRAYSIZE(buf))) {
SetForegroundWindow(wnd);
ImportFile(buf);
}
}
DragFinish(hdrop);
}
void BrowseFile(HWND wnd) {
char szFile[1024];
// open a file name
OPENFILENAME ofn = {0};
ofn.lStructSize = sizeof(ofn);
ofn.hwndOwner = g_ui_window;
ofn.lpstrFile = szFile;
ofn.lpstrFile[0] = '\0';
ofn.nMaxFile = sizeof(szFile);
ofn.lpstrFilter = "Config Files (*.conf)\0*.conf\0";
ofn.nFilterIndex = 1;
ofn.lpstrFileTitle = NULL;
ofn.nMaxFileTitle = 0;
ofn.lpstrInitialDir = NULL;
ofn.Flags = OFN_PATHMUSTEXIST | OFN_FILEMUSTEXIST;
if (GetOpenFileName(&ofn))
ImportFile(szFile);
}
static void SetKeyBox(HWND wnd, int ctr, uint8 buf[32]) {
char base64[WG_PUBLIC_KEY_LEN_BASE64 + 1];
SetDlgItemText(wnd, ctr, base64_encode(buf, 32, base64, sizeof(base64), NULL));
}
static INT_PTR WINAPI KeyPairDlgProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam) {
switch (message) {
case WM_INITDIALOG:
return TRUE;
case WM_CLOSE:
EndDialog(hWnd, 0);
return TRUE;
case WM_COMMAND:
switch (wParam) {
case IDCANCEL:
EndDialog(hWnd, 0);
return TRUE;
case IDC_PRIVATE_KEY | (EN_CHANGE << 16) : {
char buf[128];
uint8 pub[32];
uint8 priv[32];
buf[0] = 0;
size_t len = GetDlgItemText(hWnd, IDC_PRIVATE_KEY, buf, sizeof(buf));
size_t olen = 32;
if (base64_decode((uint8*)buf, len, priv, &olen) && olen == 32) {
curve25519_donna(pub, priv, kCurve25519Basepoint);
SetKeyBox(hWnd, IDC_PUBLIC_KEY, pub);
} else {
SetDlgItemText(hWnd, IDC_PUBLIC_KEY, "(Invalid Private Key)");
}
return TRUE;
}
case IDRAND: {
uint8 priv[32];
uint8 pub[32];
OsGetRandomBytes(priv, 32);
curve25519_normalize(priv);
curve25519_donna(pub, priv, kCurve25519Basepoint);
SetKeyBox(hWnd, IDC_PRIVATE_KEY, priv);
SetKeyBox(hWnd, IDC_PUBLIC_KEY, pub);
return TRUE;
}
}
}
return FALSE;
}
static void SetStartupFlags(int new_flags) {
// Determine whether to autorun or not.
bool autorun = (new_flags & kStartupFlag_MinimizeToTrayWhenWindowsStarts) ||
!(new_flags & kStartupFlag_BackgroundService) && (new_flags & kStartupFlag_ConnectWhenWindowsStarts);
// Update the autorun key.
HKEY hkey;
LSTATUS result;
result = RegOpenKeyEx(HKEY_CURRENT_USER, "Software\\Microsoft\\Windows\\CurrentVersion\\Run", 0, KEY_WRITE, &hkey);
if (result == 0) {
if (autorun) {
wchar_t buf[512 + 32];
buf[0] = '"';
DWORD len = GetModuleFileNameW(NULL, buf + 1, 512);
if (len < 512) {
memcpy(buf + len + 1, L"\" --autostart", sizeof(wchar_t) * 14);
result = RegSetValueExW(hkey, L"TunSafe", NULL, REG_SZ, (BYTE*)buf, (DWORD)(len + 15) * sizeof(wchar_t));
} else {
RERROR("Unable to add to startup list, filename too long.");
}
} else {
RegDeleteValueW(hkey, L"TunSafe");
}
RegCloseKey(hkey);
}
if (result != 0)
RERROR("Unable to modify startup list, error code = 0x%x", (int)result);
RegWriteInt(g_reg_key, "StartupFlags", new_flags);
bool was_started = g_backend && g_backend->is_started();
bool recreate_backend = false;
if (!!(new_flags & (kStartupFlag_BackgroundService | kStartupFlag_ForegroundService))) {
// Want to run as a service - make sure service is installed and running.
if (!IsTunsafeServiceRunning()) {
g_backend->Stop();
RINFO("Starting TunSafe service...");
InstallTunSafeWindowsService();
recreate_backend = true;
}
} else {
if (IsTunSafeServiceInstalled()) {
g_backend->Stop();
g_backend->Teardown();
RINFO("Removing TunSafe service...");
// Don't want to run as a service - Make sure we delete the service.
if (g_is_limited_uac_account) {
// Need to stop this early so service process is able to open.
CloseHandle(g_runonce_mutex);
if (!RunProcessAsAdminWithArgs("--delete-service-and-start", false)) {
RINFO("Unable to stop and remove service");
uint32 m = kStartupFlag_BackgroundService | kStartupFlag_ForegroundService;
new_flags = (g_startup_flags & m) | (new_flags & ~m);
} else {
PostQuitMessage(0);
return;
}
} else {
if (!UninstallTunSafeWindowsService()) {
RINFO("Unable to stop and remove service");
uint32 m = kStartupFlag_BackgroundService | kStartupFlag_ForegroundService;
new_flags = (g_startup_flags & m) | (new_flags & ~m);
}
}
recreate_backend = true;
}
}
if (recreate_backend) {
CreateLocalOrRemoteBackend(!!(new_flags & (kStartupFlag_BackgroundService | kStartupFlag_ForegroundService)));
if (was_started)
StartTunsafeBackend(UIW_START);
}
g_startup_flags = new_flags;
g_backend->SetServiceStartupFlags(g_startup_flags);
}
enum {
kTab_Logs = 0,
kTab_Charts = 1,
kTab_Advanced = 2,
};
static void UpdateGraphReq() {
if (g_backend && (g_current_tab != 1 || !g_ui_visible)) {
free(g_backend->GetGraph(-1));
}
}
static void UpdateTabSelection() {
int tab = TabCtrl_GetCurSel(hwndTab);
HWND wnd = g_ui_window;
g_current_tab = tab;
ShowWindow(hwndEdit, (tab == kTab_Logs) ? SW_SHOW : SW_HIDE);
ShowWindow(hwndGraphBox, (tab == kTab_Charts) ? SW_SHOW : SW_HIDE);
ShowWindow(hwndAdvancedBox, (tab == kTab_Advanced) ? SW_SHOW : SW_HIDE);
UpdateGraphReq();
}
struct WindowSizingItem {
uint16 id;
uint16 edges;
};
enum {
WSI_LEFT = 1,
WSI_RIGHT = 2,
WSI_TOP = 4,
WSI_BOTTOM = 8,
};
static const WindowSizingItem kWindowSizing[] = {
{ID_START,WSI_LEFT | WSI_RIGHT},
{ID_BTN_KILLSWITCH, WSI_LEFT | WSI_RIGHT},
{ID_STOP,WSI_LEFT | WSI_RIGHT},
{ID_EDITCONF,WSI_LEFT | WSI_RIGHT},
{IDC_PAINTBOX,WSI_RIGHT},
{IDC_TAB, WSI_RIGHT | WSI_BOTTOM},
};
static void HandleWindowSizing() {
RECT wr;
GetClientRect(g_ui_window, &wr);
static int g_orig_w, g_orig_h;
static RECT g_orig_rects[ARRAYSIZE(kWindowSizing)];
if (g_orig_w == 0) {
g_orig_w = wr.right;
g_orig_h = wr.bottom;
for (size_t i = 0; i < ARRAYSIZE(kWindowSizing); i++) {
const WindowSizingItem *it = &kWindowSizing[i];
g_orig_rects[i] = GetParentRect(GetDlgItem(g_ui_window, it->id));
}
}
int dx = wr.right - g_orig_w;
int dy = wr.bottom - g_orig_h;
if (dx|dy) {
HDWP dwp = BeginDeferWindowPos(10), dwp_next;
for (size_t i = 0; i < ARRAYSIZE(kWindowSizing); i++) {
const WindowSizingItem *it = &kWindowSizing[i];
HWND wnd = GetDlgItem(g_ui_window, it->id);
RECT r = g_orig_rects[i];
if (it->edges & WSI_LEFT) r.left += dx;
if (it->edges & WSI_RIGHT) r.right += dx;
if (it->edges & WSI_TOP) r.top += dy;
if (it->edges & WSI_BOTTOM) r.bottom += dy;
if (r.right < r.left) r.right = r.left;
if (r.bottom < r.top) r.bottom = r.top;
dwp_next = DeferWindowPos(dwp, wnd, NULL, r.left, r.top, r.right - r.left, r.bottom - r.top, SWP_NOZORDER | SWP_NOREPOSITION | SWP_NOACTIVATE);
dwp = dwp_next ? dwp_next : dwp;
}
EndDeferWindowPos(dwp);
}
RECT rect = GetParentRect(hwndTab);
TabCtrl_AdjustRect(hwndTab, false, &rect);
MoveWindow(hwndEdit, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
MoveWindow(hwndGraphBox, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
MoveWindow(hwndAdvancedBox, rect.left, rect.top, rect.right - rect.left, rect.bottom - rect.top, TRUE);
int parts[3] = {
(int)(wr.right * 0.2f),
(int)(wr.right * 0.6f),
(int)-1,
};
SendMessage(hwndStatus, SB_SETPARTS, 3, (LPARAM)parts);
SendMessage(hwndStatus, WM_SIZE, 0, 0);
InvalidateRect(hwndStatus, NULL, TRUE);
}
static void HandleClickedItem(HWND hWnd, int wParam) {
if (wParam >= ID_POPUP_CONFIG_FILE && wParam < ID_POPUP_CONFIG_FILE + MAX_CONFIG_FILES) {
const char *new_conf = config_filenames[wParam - ID_POPUP_CONFIG_FILE];
if (!new_conf)
return;
if (strcmp(new_conf, g_current_filename) == 0 && g_backend->is_started()) {
StopTunsafeBackend(UIW_NONE);
} else {
LoadConfigFile(new_conf, true, GetAsyncKeyState(VK_SHIFT) >= 0);
}
return;
}
switch (wParam) {
case ID_START: StartTunsafeBackend(UIW_START); break;
case ID_STOP: StopTunsafeBackend(UIW_NONE); break;
case ID_EXIT: PostQuitMessage(0); break;
case ID_MORE_BUTTON: ShowSettingsMenu(hWnd); break;
case IDSETT_WEB_PAGE: ShellExecute(g_ui_window, NULL, "https://tunsafe.com/", NULL, NULL, 0); break;
case IDSETT_OPENSOURCE: ShellExecute(g_ui_window, NULL, "https://tunsafe.com/open-source", NULL, NULL, 0); break;
case ID_EDITCONF: OpenEditor(); break;
case IDSETT_BROWSE_FILES:BrowseFiles(); break;
case IDSETT_OPEN_FILE: BrowseFile(hWnd); break;
case IDSETT_ABOUT:
MessageBoxA(g_ui_window, TUNSAFE_VERSION_STRING_LONG "\r\n\r\nCopyright © 2018, Ludvig Strigeus\r\n\r\nThanks for choosing TunSafe!\r\n\r\nThis version was built on " __DATE__ " " __TIME__, "About TunSafe", MB_ICONINFORMATION);
break;
case IDSETT_KEYPAIR:
DialogBox(g_hinstance, MAKEINTRESOURCE(IDD_DIALOG2), hWnd, &KeyPairDlgProc);
break;
case IDSETT_BLOCKINTERNET_OFF:
case IDSETT_BLOCKINTERNET_ROUTE:
case IDSETT_BLOCKINTERNET_FIREWALL:
case IDSETT_BLOCKINTERNET_BOTH:
{
uint32 old_state = g_backend->GetInternetBlockState();
uint32 new_state = wParam - IDSETT_BLOCKINTERNET_OFF;
if ((old_state & kBlockInternet_TypeMask) == kBlockInternet_Off && new_state != kBlockInternet_Off) {
if (MessageBoxA(g_ui_window, "Warning! All Internet traffic will be blocked while TunSafe is active. Only traffic through TunSafe will be allowed.\r\n\r\nThe blocking is activated the next time TunSafe connects.\r\n\r\nDo you want to continue?", "TunSafe", MB_ICONWARNING | MB_OKCANCEL) == IDCANCEL)
return;
}
g_backend->SetInternetBlockState((InternetBlockState)(new_state | (old_state & ~kBlockInternet_TypeMask)));
if ((~old_state & new_state) && g_backend->is_started())
StartTunsafeBackend(UIW_START);
return;
}
case IDSETT_BLOCKINTERNET_DISCONN: {
g_backend->SetInternetBlockState((InternetBlockState)(g_backend->GetInternetBlockState() ^ kBlockInternet_BlockOnDisconnect));
return;
}
case IDSETT_BLOCKINTERNET_ALLOWLOCAL: {
g_backend->SetInternetBlockState((InternetBlockState)(g_backend->GetInternetBlockState() ^ kBlockInternet_AllowLocalNetworks));
if (g_backend->is_started())
StartTunsafeBackend(UIW_START);
return;
}
case ID_BTN_KILLSWITCH: {
g_backend->SetInternetBlockState((InternetBlockState)(g_backend->GetInternetBlockState() & ~kBlockInternet_Active));
return;
}
case IDSETT_SERVICE_OFF:
case IDSETT_SERVICE_FOREGROUND:
case IDSETT_SERVICE_BACKGROUND:
SetStartupFlags((int)((g_startup_flags & ~3) + wParam - IDSETT_SERVICE_OFF));
break;
case IDSETT_SERVICE_CONNECT_AUTO:
SetStartupFlags(g_startup_flags ^ kStartupFlag_ConnectWhenWindowsStarts);
break;
case IDSETT_SERVICE_MINIMIZE_AUTO:
SetStartupFlags(g_startup_flags ^ kStartupFlag_MinimizeToTrayWhenWindowsStarts);
break;
case IDSETT_PREPOST:
{
if (!g_hklm_reg_key) {
if (!RunProcessAsAdminWithArgs(g_allow_pre_post ? "--set-allow-pre-post 0" : "--set-allow-pre-post 1", true))
MessageBox(g_ui_window, "You need to run TunSafe as an Administrator to be able to change this setting.", "TunSafe", MB_ICONWARNING);
g_allow_pre_post = RegReadInt(g_hklm_readonly_reg_key, "AllowPrePost", 0) != 0;
return;
}
g_allow_pre_post = !g_allow_pre_post;
RegWriteInt(g_hklm_reg_key, "AllowPrePost", g_allow_pre_post);
return;
}
}
}
static INT_PTR WINAPI DlgProc(HWND hWnd, UINT message, WPARAM wParam,
LPARAM lParam) {