-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Expand file tree
/
Copy pathNetworkTests.cpp
More file actions
5098 lines (4163 loc) · 210 KB
/
NetworkTests.cpp
File metadata and controls
5098 lines (4163 loc) · 210 KB
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
/*++
Copyright (c) Microsoft. All rights reserved.
Module Name:
NetworkTests.cpp
Abstract:
This file contains test cases for the networking logic.
--*/
#include "precomp.h"
#include "computenetwork.h"
#include "Common.h"
#include "wslpolicies.h"
#include "hns_schema.h"
#include <mstcpip.h>
#include <winhttp.h>
#include <winsock2.h>
#include <netlistmgr.h>
using wsl::shared::hns::GuestEndpointResourceType;
using wsl::shared::hns::ModifyGuestEndpointSettingRequest;
using wsl::shared::hns::ModifyRequestType;
bool TryLoadWinhttpProxyMethods() noexcept
{
constexpr auto winhttpModuleName = L"Winhttp.dll";
const wil::shared_hmodule winhttpModule{LoadLibraryEx(winhttpModuleName, nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32)};
if (!winhttpModule)
{
return false;
}
try
{
// attempt to find the functions for the Winhttp proxy APIs.
static LxssDynamicFunction<decltype(WinHttpRegisterProxyChangeNotification)> WinHttpRegisterProxyChangeNotification{
winhttpModule, "WinHttpRegisterProxyChangeNotification"};
static LxssDynamicFunction<decltype(WinHttpUnregisterProxyChangeNotification)> WinHttpUnregisterProxyChangeNotification{
winhttpModule, "WinHttpUnregisterProxyChangeNotification"};
static LxssDynamicFunction<decltype(WinHttpGetProxySettingsEx)> WinHttpGetProxySettingsEx{
winhttpModule, "WinHttpGetProxySettingsEx"};
static LxssDynamicFunction<decltype(WinHttpGetProxySettingsResultEx)> WinHttpGetProxySettingsResultEx{
winhttpModule, "WinHttpGetProxySettingsResultEx"};
static LxssDynamicFunction<decltype(WinHttpFreeProxySettingsEx)> WinHttpFreeProxySettingsEx{
winhttpModule, "WinHttpFreeProxySettingsEx"};
}
catch (...)
{
return false;
}
return true;
}
#define HYPERV_FIREWALL_TEST_ONLY() \
{ \
WSL2_TEST_ONLY(); \
WINDOWS_11_TEST_ONLY(); \
if (!AreExperimentalNetworkingFeaturesSupported() || !IsHyperVFirewallSupported()) \
{ \
LogSkipped("Hyper-V Firewall not supported on this OS. Skipping test..."); \
return; \
} \
}
#define MIRRORED_NETWORKING_TEST_ONLY() \
{ \
WSL2_TEST_ONLY(); \
WINDOWS_11_TEST_ONLY(); \
if (!AreExperimentalNetworkingFeaturesSupported() || !IsHyperVFirewallSupported()) \
{ \
LogSkipped("Mirrored networking not supported on this OS. Skipping test.."); \
return; \
} \
}
#define DNS_TUNNELING_TEST_ONLY() \
{ \
WSL2_TEST_ONLY(); \
WINDOWS_11_TEST_ONLY(); \
if (!AreExperimentalNetworkingFeaturesSupported()) \
{ \
LogSkipped("DNS tunneling not supported on this OS. Skipping test..."); \
return; \
} \
if (!TryLoadDnsResolverMethods()) \
{ \
LogSkipped("DNS tunneling APIs not present on this OS. Skipping test..."); \
return; \
} \
}
#define WINHTTP_PROXY_TEST_ONLY() \
{ \
WSL2_TEST_ONLY(); \
if (!TryLoadWinhttpProxyMethods()) \
{ \
LogSkipped("Winhttp proxy APIs not present on this OS. Skipping test..."); \
return; \
} \
}
#define VIRTIOPROXY_TEST_ONLY() \
{ \
WSL2_TEST_ONLY(); \
}
static constexpr auto c_wslVmCreatorId = L"\'{40e0ac32-46a5-438a-A0B2-2B479E8F2E90}\'";
static constexpr auto c_wsaVmCreatorId = L"\'{9E288F02-CE00-4D9E-BE2B-14CE463B0298}\'";
static constexpr auto c_anyVmCreatorId = L"\'{00000000-0000-0000-0000-000000000000}\'";
static constexpr auto c_firewallRuleActionBlock = L"Block";
static constexpr auto c_firewallRuleActionAllow = L"Allow";
static constexpr auto c_firewallTrafficTestCmd = L"ping -c 3 -W 5 1.1.1.1";
static const std::wstring c_firewallTrafficTestPort = L"80";
static const std::wstring c_firewallTestOtherPort = L"443";
static const std::wstring c_dnsTunnelingDefaultIp = L"10.255.255.254";
// Set ManualConnectivityValidation to true to manually check stdout from the test to verify the correct calls are made in Linux/Init
static constexpr bool ManualConnectivityValidation = false;
namespace {
std::wstring GetMacAddress(const std::wstring& adapter = L"eth0")
{
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(L"cat /sys/class/net/" + adapter + L"/address", 0);
out.pop_back(); // remove LF
return out;
}
template <class T>
class Stopwatch
{
private:
LARGE_INTEGER m_startQpc;
LARGE_INTEGER m_frequencyQpc;
T m_timeoutInterval;
public:
Stopwatch(_In_opt_ T TimeoutInterval = T::max()) : m_timeoutInterval(TimeoutInterval)
{
QueryPerformanceFrequency(&m_frequencyQpc);
QueryPerformanceCounter(&m_startQpc);
}
T Elapsed()
{
LARGE_INTEGER End;
UINT64 ElapsedQpc;
QueryPerformanceCounter(&End);
ElapsedQpc = End.QuadPart - m_startQpc.QuadPart;
return T((ElapsedQpc * T::period::den) / T::period::num / m_frequencyQpc.QuadPart);
}
bool IsExpired()
{
return Elapsed() >= m_timeoutInterval;
}
};
} // namespace
namespace NetworkTests {
class VirtioProxyTests;
class NetworkTests
{
WSL_TEST_CLASS(NetworkTests)
friend class MirroredTests;
friend class BridgedTests;
friend class VirtioProxyTests;
struct IpAddress
{
std::wstring Address;
uint8_t PrefixLength;
bool Preferred = false;
bool operator==(const IpAddress& other) const
{
return Address == other.Address && PrefixLength == other.PrefixLength;
}
std::wstring GetPrefix() const
{
DWORD status = ERROR_INVALID_FUNCTION;
SOCKADDR_INET* address = nullptr;
unsigned char* addressPointer{};
NET_ADDRESS_INFO netAddrInfo{};
status = ParseNetworkString(Address.c_str(), NET_STRING_IP_ADDRESS, &netAddrInfo, nullptr, nullptr);
if (status != NO_ERROR)
{
return std::wstring(L"");
}
address = reinterpret_cast<SOCKADDR_INET*>(&netAddrInfo.IpAddress);
addressPointer = (address->si_family == AF_INET) ? reinterpret_cast<unsigned char*>(&address->Ipv4.sin_addr)
: address->Ipv6.sin6_addr.u.Byte;
constexpr int c_numBitsPerByte = 8;
for (int i = 0, currPrefixLength = PrefixLength; i < INET_ADDR_LENGTH(address->si_family); i++, currPrefixLength -= c_numBitsPerByte)
{
if (currPrefixLength < c_numBitsPerByte)
{
const int bitShiftAmt = (c_numBitsPerByte - std::max(currPrefixLength, 0));
addressPointer[i] &= (0xFF >> bitShiftAmt) << bitShiftAmt;
}
}
return wsl::windows::common::string::SockAddrInetToWstring(*address) + L"/" + std::to_wstring(PrefixLength);
}
};
struct InterfaceState
{
std::wstring Name;
std::vector<IpAddress> V4Addresses;
std::optional<std::wstring> Gateway;
std::vector<IpAddress> V6Addresses;
std::optional<std::wstring> V6Gateway;
bool Up = false;
int Mtu = 0;
bool Rename = false;
};
struct Route
{
std::wstring Via;
std::wstring Device;
std::optional<std::wstring> Prefix;
int Metric = 0;
bool operator==(const Route& other) const
{
return Via == other.Via && Device == other.Device && Prefix == other.Prefix;
}
};
struct RoutingTableState
{
std::optional<Route> DefaultRoute;
std::vector<Route> Routes;
};
enum class FirewallType
{
Host,
HyperV
};
struct FirewallRule
{
FirewallType Type;
std::wstring Name;
std::wstring RemotePorts;
std::wstring Action;
std::wstring VmCreatorId;
};
GUID AdapterId;
TEST_CLASS_SETUP(TestClassSetup)
{
VERIFY_ARE_EQUAL(LxsstuInitialize(false), TRUE);
return true;
}
TEST_CLASS_CLEANUP(TestClassCleanup)
{
if (LxsstuVmMode())
{
WslShutdown();
}
VERIFY_NO_THROW(LxsstuUninitialize(false));
return true;
}
TEST_METHOD_SETUP(MethodSetup)
{
if (!LxsstuVmMode())
{
return true;
}
AdapterId = NetworkTests::QueryAdapterId();
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"ln -f -s /init /gns"), (DWORD)0);
return true;
}
TEST_METHOD(RemoveAndAddDefaultRoute)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
// Verify that the default routes are set
auto state = GetIpv4RoutingTableState();
VERIFY_IS_TRUE(state.DefaultRoute.has_value());
VERIFY_ARE_EQUAL(state.DefaultRoute->Via, L"192.168.0.1");
auto v6State = GetIpv6RoutingTableState();
VERIFY_IS_TRUE(v6State.DefaultRoute.has_value());
VERIFY_ARE_EQUAL(v6State.DefaultRoute->Via, L"fc00::1");
// Now remove them
wsl::shared::hns::Route route;
route.NextHop = L"192.168.0.1";
route.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_PREFIX;
route.Family = AF_INET;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
wsl::shared::hns::Route v6Route;
v6Route.NextHop = L"fc00::1";
v6Route.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_V6_PREFIX;
v6Route.Family = AF_INET6;
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
// Verify that the routes are removed
state = GetIpv4RoutingTableState();
VERIFY_IS_FALSE(state.DefaultRoute.has_value());
v6State = GetIpv6RoutingTableState();
VERIFY_IS_FALSE(v6State.DefaultRoute.has_value());
// Add them again
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Add, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Add, GuestEndpointResourceType::Route);
// Verify that the routes are restored
state = GetIpv4RoutingTableState();
VERIFY_IS_TRUE(state.DefaultRoute.has_value());
VERIFY_ARE_EQUAL(state.DefaultRoute->Via, L"192.168.0.1");
VERIFY_ARE_EQUAL(state.DefaultRoute->Device, L"eth0");
v6State = GetIpv6RoutingTableState();
VERIFY_IS_TRUE(v6State.DefaultRoute.has_value());
VERIFY_ARE_EQUAL(v6State.DefaultRoute->Via, L"fc00::1");
VERIFY_ARE_EQUAL(v6State.DefaultRoute->Device, L"eth0");
}
TEST_METHOD(AddRemoveDefaultOnlinkRoutes)
{
WSL2_TEST_ONLY();
wsl::shared::hns::Route defaultRouteV4;
defaultRouteV4.NextHop = L"0.0.0.0";
defaultRouteV4.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_PREFIX;
defaultRouteV4.Family = AF_INET;
defaultRouteV4.Metric = 1;
SendDeviceSettingsRequest(L"eth0", defaultRouteV4, ModifyRequestType::Add, GuestEndpointResourceType::Route);
wsl::shared::hns::Route defaultRouteV6;
defaultRouteV6.NextHop = L"::";
defaultRouteV6.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_V6_PREFIX;
defaultRouteV6.Family = AF_INET6;
defaultRouteV6.Metric = 1;
SendDeviceSettingsRequest(L"eth0", defaultRouteV6, ModifyRequestType::Add, GuestEndpointResourceType::Route);
const bool defaultV4RouteExists =
LxsstuLaunchWsl(L"ip -4 route show | grep \"default dev eth0\" | grep -w \"metric 1\"") == (DWORD)0;
const bool defaultV6RouteExists =
LxsstuLaunchWsl(L"ip -6 route show | grep \"default dev eth0\" | grep -w \"metric 1\"") == (DWORD)0;
SendDeviceSettingsRequest(L"eth0", defaultRouteV4, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", defaultRouteV6, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
const bool defaultV4RouteRemoved =
LxsstuLaunchWsl(L"ip -4 route show | grep \"default dev eth0\" | grep -w \"metric 1\"") != (DWORD)0;
const bool defaultV6RouteRemoved =
LxsstuLaunchWsl(L"ip -6 route show | grep \"default dev eth0\" | grep -w \"metric 1\"") != (DWORD)0;
VERIFY_IS_TRUE(defaultV4RouteExists);
VERIFY_IS_TRUE(defaultV6RouteExists);
VERIFY_IS_TRUE(defaultV4RouteRemoved);
VERIFY_IS_TRUE(defaultV6RouteRemoved);
}
TEST_METHOD(SetInterfaceDownAndUp)
{
WSL2_TEST_ONLY();
// Disconnect interface
wsl::shared::hns::NetworkInterface link;
link.Connected = false;
RunGns(link, ModifyRequestType::Update, GuestEndpointResourceType::Interface);
VERIFY_IS_FALSE(GetInterfaceState(L"eth0").Up);
// Connect it again
link.Connected = true;
RunGns(link, ModifyRequestType::Update, GuestEndpointResourceType::Interface);
VERIFY_IS_TRUE(GetInterfaceState(L"eth0").Up);
}
TEST_METHOD(SetMtu)
{
WSL2_TEST_ONLY();
// Set MTU - must be 1280 bytes or above to meet IPv6 minimum MTU requirement
wsl::shared::hns::NetworkInterface link;
link.Connected = true;
link.NlMtu = 1280;
RunGns(link, ModifyRequestType::Update, GuestEndpointResourceType::Interface);
VERIFY_ARE_EQUAL(GetInterfaceState(L"eth0").Mtu, 1280);
}
TEST_METHOD(AddAndRemoveCustomRoute)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
// Add custom routes, one per address family
wsl::shared::hns::Route route;
route.NextHop = L"192.168.0.12";
route.DestinationPrefix = L"192.168.2.0/24";
route.Family = AF_INET;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
wsl::shared::hns::Route v6Route;
v6Route.NextHop = L"fc00::12";
v6Route.DestinationPrefix = L"fc00:abcd::/80";
v6Route.Family = AF_INET6;
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
// Check that the routes are there
const bool v4CustomRouteExists = RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24"});
const bool v6CustomRouteExists = RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/80"});
// Now remove them
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
// Check that the routes are gone
const bool v4CustomRouteGone = !RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24"});
const bool v6CustomRouteGone = !RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/80"});
VERIFY_IS_TRUE(v4CustomRouteExists);
VERIFY_IS_TRUE(v6CustomRouteExists);
VERIFY_IS_TRUE(v4CustomRouteGone);
VERIFY_IS_TRUE(v6CustomRouteGone);
}
TEST_METHOD(AddRouteWithMetrics)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
// Add a custom route per address family
wsl::shared::hns::Route route;
route.NextHop = L"192.168.0.12";
route.DestinationPrefix = L"192.168.2.0/24";
route.Family = AF_INET;
route.Metric = 12;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
wsl::shared::hns::Route v6Route;
v6Route.NextHop = L"fc00::12";
v6Route.DestinationPrefix = L"fc00:abcd::/64";
v6Route.Family = AF_INET6;
v6Route.Metric = 12;
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
// Check that the routes are there
const bool v4CustomRouteExists = RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24", 12});
const bool v6CustomRouteExists = RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/64", 12});
// Now remove them
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Remove, GuestEndpointResourceType::Route);
// Check that the routes are gone
const bool v4CustomRouteGone = !RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24", 12});
const bool v6CustomRouteGone = !RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/64", 12});
VERIFY_IS_TRUE(v4CustomRouteExists);
VERIFY_IS_TRUE(v6CustomRouteExists);
VERIFY_IS_TRUE(v4CustomRouteGone);
VERIFY_IS_TRUE(v6CustomRouteGone);
}
TEST_METHOD(ResetRoutes)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
// Add a custom route per address family
wsl::shared::hns::Route route;
route.NextHop = L"192.168.0.12";
route.DestinationPrefix = L"192.168.2.0/24";
route.Family = AF_INET;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
wsl::shared::hns::Route v6Route;
v6Route.NextHop = L"fc00::12";
v6Route.DestinationPrefix = L"fc00:abcd::/80";
v6Route.Family = AF_INET6;
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
// Check that the custom routes are there
bool v4RouteExists = RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24"});
bool v6RouteExists = RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/80"});
// Reset the routing table
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
// Check that both routes are gone, per address family
bool v4RouteGoneAfterReset = !RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24"});
auto state = GetIpv4RoutingTableState();
bool v4GwGoneAfterReset = !state.DefaultRoute.has_value();
bool v6RouteGoneAfterReset = !RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/80"});
auto v6State = GetIpv6RoutingTableState();
bool v6GwGoneAfterReset = !v6State.DefaultRoute.has_value();
// Add the custom and default routes back
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
route.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_PREFIX;
route.NextHop = L"192.168.0.1";
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
v6Route.DestinationPrefix = LX_INIT_DEFAULT_ROUTE_V6_PREFIX;
v6Route.NextHop = L"fc00::1";
SendDeviceSettingsRequest(L"eth0", v6Route, ModifyRequestType::Update, GuestEndpointResourceType::Route);
// Verify that all the routes are there
bool v4RouteRestored = RouteExists({L"192.168.0.12", L"eth0", L"192.168.2.0/24"});
state = GetIpv4RoutingTableState();
bool v4GwRestored = state.DefaultRoute.has_value();
bool v4GwRestoredCorrectly = state.DefaultRoute->Via == L"192.168.0.1";
bool v6RouteRestored = RouteExists({L"fc00::12", L"eth0", L"fc00:abcd::/80"});
v6State = GetIpv6RoutingTableState();
bool v6GwRestored = v6State.DefaultRoute.has_value();
bool v6GwRestoredCorrectly = v6State.DefaultRoute->Via == L"fc00::1";
VERIFY_IS_TRUE(v4RouteExists);
VERIFY_IS_TRUE(v6RouteExists);
VERIFY_IS_TRUE(v4RouteGoneAfterReset);
VERIFY_IS_TRUE(v4GwGoneAfterReset);
VERIFY_IS_TRUE(v6RouteGoneAfterReset);
VERIFY_IS_TRUE(v6GwGoneAfterReset);
VERIFY_IS_TRUE(v4RouteRestored);
VERIFY_IS_TRUE(v4GwRestored);
VERIFY_IS_TRUE(v4GwRestoredCorrectly);
VERIFY_IS_TRUE(v6RouteRestored);
VERIFY_IS_TRUE(v6GwRestored);
VERIFY_IS_TRUE(v6GwRestoredCorrectly);
}
TEST_METHOD(ResetRoutesTwice)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
auto state = GetIpv4RoutingTableState();
VERIFY_IS_TRUE(state.DefaultRoute.has_value());
auto v6State = GetIpv6RoutingTableState();
VERIFY_IS_TRUE(v6State.DefaultRoute.has_value());
// Reset the IPv4 table twice
wsl::shared::hns::Route route;
route.Family = AF_INET;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
state = GetIpv4RoutingTableState();
VERIFY_IS_FALSE(state.DefaultRoute.has_value());
VERIFY_IS_TRUE(state.Routes.empty());
// Then reset the IPv6 table twice
route.Family = AF_INET6;
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
SendDeviceSettingsRequest(L"eth0", route, ModifyRequestType::Reset, GuestEndpointResourceType::Route);
state = GetIpv6RoutingTableState();
VERIFY_IS_FALSE(state.DefaultRoute.has_value());
VERIFY_IS_TRUE(state.Routes.empty());
}
TEST_METHOD(UpdateIpAddress)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
// Verify that the IPs are in the preferred state
auto interfaceState = GetInterfaceState(L"eth0");
VERIFY_ARE_EQUAL(1, interfaceState.V4Addresses.size());
VERIFY_ARE_EQUAL(L"192.168.0.2", interfaceState.V4Addresses[0].Address);
VERIFY_IS_TRUE(interfaceState.V4Addresses[0].Preferred);
VERIFY_ARE_EQUAL(1, interfaceState.V6Addresses.size());
VERIFY_ARE_EQUAL(L"fc00::2", interfaceState.V6Addresses[0].Address);
VERIFY_IS_TRUE(interfaceState.V6Addresses[0].Preferred);
// Change current ip addresses to be deprecated
wsl::shared::hns::IPAddress address;
address.Address = L"192.168.0.2";
address.OnLinkPrefixLength = 24;
address.Family = AF_INET;
address.PreferredLifetime = 0;
SendDeviceSettingsRequest(L"eth0", address, ModifyRequestType::Update, GuestEndpointResourceType::IPAddress);
wsl::shared::hns::IPAddress v6Address;
v6Address.Address = L"fc00::2";
v6Address.OnLinkPrefixLength = 64;
v6Address.Family = AF_INET6;
address.PreferredLifetime = 0;
SendDeviceSettingsRequest(L"eth0", v6Address, ModifyRequestType::Update, GuestEndpointResourceType::IPAddress);
// Validate that the IPs are no longer preferred
interfaceState = GetInterfaceState(L"eth0");
VERIFY_ARE_EQUAL(1, interfaceState.V4Addresses.size());
VERIFY_ARE_EQUAL(L"192.168.0.2", interfaceState.V4Addresses[0].Address);
VERIFY_IS_FALSE(interfaceState.V4Addresses[0].Preferred);
VERIFY_ARE_EQUAL(1, interfaceState.V6Addresses.size());
VERIFY_ARE_EQUAL(L"fc00::2", interfaceState.V6Addresses[0].Address);
VERIFY_IS_FALSE(interfaceState.V6Addresses[0].Preferred);
}
enum IpPrefixOrigin
{
IpPrefixOriginOther = 0,
IpPrefixOriginManual,
IpPrefixOriginWellKnown,
IpPrefixOriginDhcp,
IpPrefixOriginRouterAdvertisement,
};
enum IpSuffixOrigin
{
IpSuffixOriginOther = 0,
IpSuffixOriginManual,
IpSuffixOriginWellKnown,
IpSuffixOriginDhcp,
IpSuffixOriginLinkLayerAddress,
IpSuffixOriginRandom,
};
TEST_METHOD(TemporaryAddress)
{
WSL2_TEST_ONLY();
TestCase({{L"eth0", {}, {}, {{L"fc00::2", 64}}, L"fc00::1"}});
// Make the address public
wsl::shared::hns::IPAddress v6Address;
v6Address.Address = L"fc00::2";
v6Address.OnLinkPrefixLength = 64;
v6Address.Family = AF_INET6;
v6Address.PrefixOrigin = IpPrefixOriginRouterAdvertisement;
v6Address.SuffixOrigin = IpSuffixOriginLinkLayerAddress;
v6Address.PreferredLifetime = 0xFFFFFFFF;
SendDeviceSettingsRequest(L"eth0", v6Address, ModifyRequestType::Update, GuestEndpointResourceType::IPAddress);
// Add a temporary address
v6Address.Address = L"fc00::abcd:1234:5678:9999";
v6Address.OnLinkPrefixLength = 64;
v6Address.Family = AF_INET6;
v6Address.PrefixOrigin = IpPrefixOriginRouterAdvertisement;
v6Address.SuffixOrigin = IpSuffixOriginRandom;
v6Address.PreferredLifetime = 0xFFFFFFFF;
SendDeviceSettingsRequest(L"eth0", v6Address, ModifyRequestType::Add, GuestEndpointResourceType::IPAddress);
// Wait for DAD to finish to avoid it being a factor in source address selection
std::this_thread::sleep_for(std::chrono::milliseconds(2000));
VERIFY_ARE_EQUAL(2, GetInterfaceState(L"eth0").V6Addresses.size());
// Ensure that the temporary address is preferred during source address selection
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(L"ip route get 2001::5");
LogInfo("'ip route get 2001::5' - '%ls'", out.c_str());
auto [out5, _5] = LxsstuLaunchWslAndCaptureOutput(L"ip addr show eth0");
LogInfo("[TemporaryAddress] ip addr show output:\r\n%ls", FixLineEndings(out5).c_str());
std::wsmatch match;
std::wregex pattern(L"2001::5 from :: via fc00::1 dev eth0 proto kernel src ([a-f,A-F,0-9,:]+)");
VERIFY_IS_TRUE(std::regex_search(out, match, pattern));
VERIFY_ARE_EQUAL(2, match.size());
VERIFY_ARE_EQUAL(L"fc00::abcd:1234:5678:9999", match.str(1));
// Make another public address
v6Address.Address = L"fc00::3";
v6Address.OnLinkPrefixLength = 64;
v6Address.Family = AF_INET6;
v6Address.PrefixOrigin = IpPrefixOriginRouterAdvertisement;
v6Address.SuffixOrigin = IpSuffixOriginLinkLayerAddress;
v6Address.PreferredLifetime = 0xFFFFFFFF;
SendDeviceSettingsRequest(L"eth0", v6Address, ModifyRequestType::Add, GuestEndpointResourceType::IPAddress);
// Test source address selection again
auto [out2, _2] = LxsstuLaunchWslAndCaptureOutput(L"ip route get 2001::6");
LogInfo("'ip route get 2001::6' - '%ls'", out2.c_str());
std::wregex pattern2(L"2001::6 from :: via fc00::1 dev eth0 proto kernel src ([a-f,A-F,0-9,:]+)");
VERIFY_IS_TRUE(std::regex_search(out2, match, pattern2));
VERIFY_ARE_EQUAL(2, match.size());
VERIFY_ARE_EQUAL(L"fc00::abcd:1234:5678:9999", match.str(1));
}
TEST_METHOD(SimpleCase)
{
TestCase({{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
}
TEST_METHOD(AddressChange)
{
TestCase(
{{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"},
{L"eth0", {{L"192.168.0.3", 24}}, L"192.168.0.1", {{L"fc00::3", 64}}, L"fc00::1"}});
}
TEST_METHOD(GatewayChange)
{
TestCase(
{{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"},
{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.3", {{L"fc00::2", 64}}, L"fc00::3"}});
}
TEST_METHOD(NetworkChange)
{
TestCase(
{{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"},
{L"eth0", {{L"10.0.0.2", 16}}, L"10.0.0.1", {{L"fc00:abcd::5", 80}}, L"fc00:abcd::1"}});
}
TEST_METHOD(NetworkChangeAndBack)
{
TestCase(
{{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"},
{L"eth0", {{L"10.0.0.2", 16}}, L"10.0.0.1", {{L"fc00:abcd::5", 80}}, L"fc00:abcd::1"},
{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
}
TEST_METHOD(NoChange)
{
TestCase(
{{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"},
{L"eth0", {{L"192.168.0.2", 24}}, L"192.168.0.1", {{L"fc00::2", 64}}, L"fc00::1"}});
}
TEST_METHOD(MultipleIps)
{
TestCase(
{{L"eth0",
{{L"192.168.0.2", 24}, {L"192.168.0.3", 24}},
L"192.168.0.1",
{{L"fc00::2", 64}, {L"fc00::3", 64}},
L"fc00::1"}});
}
TEST_METHOD(MacAddressChangeAndBack)
{
WSL2_TEST_ONLY();
const auto originalMac = GetMacAddress();
wsl::shared::hns::MacAddress macAddress;
macAddress.PhysicalAddress = "AA-AA-FF-FF-FF-FF";
SendDeviceSettingsRequest(L"eth0", macAddress, ModifyRequestType::Update, GuestEndpointResourceType::MacAddress);
VERIFY_ARE_EQUAL(GetMacAddress(), L"aa:aa:ff:ff:ff:ff");
macAddress.PhysicalAddress = wsl::shared::string::WideToMultiByte(originalMac);
std::replace(macAddress.PhysicalAddress.begin(), macAddress.PhysicalAddress.end(), ':', '-');
SendDeviceSettingsRequest(L"eth0", macAddress, ModifyRequestType::Update, GuestEndpointResourceType::MacAddress);
VERIFY_ARE_EQUAL(GetMacAddress(), originalMac);
}
static void VerifyDigDnsResolution(const std::wstring& digCommandLine)
{
// dig has exit code 0 when it receives a DNS response
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(digCommandLine.data(), 0);
// Verify dig returned a non-empty output
VERIFY_IS_TRUE(!out.empty());
}
static void VerifyDnsResolutionBasic()
{
// Verify basic DNS resolution using getent
auto [out, _] = LxsstuLaunchWslAndCaptureOutput(L"getent ahosts bing.com", 0);
VERIFY_IS_TRUE(!out.empty());
}
static void VerifyDnsResolutionDig()
{
if (HostHasInternetConnectivity(AF_INET))
{
// Test A record resolution (IPv4) with both UDP and TCP
VerifyDigDnsResolution(L"dig +short +time=5 A bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 A bing.com");
// Test reverse DNS lookup
VerifyDigDnsResolution(L"dig +short +time=5 -x 8.8.8.8");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 -x 8.8.8.8");
}
else
{
LogInfo("Host does not have IPv4 internet connectivity. Skipping IPv4 DNS tests.");
}
if (HostHasInternetConnectivity(AF_INET6))
{
// Test AAAA record resolution (IPv6) with both UDP and TCP
VerifyDigDnsResolution(L"dig +short +time=5 AAAA bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 AAAA bing.com");
}
else
{
LogInfo("Host does not have IPv6 internet connectivity. Skipping IPv6 DNS tests.");
}
}
static void VerifyDnsResolutionRecordTypes()
{
// Test various DNS record types
VerifyDigDnsResolution(L"dig +short +time=5 MX bing.com");
VerifyDigDnsResolution(L"dig +short +time=5 NS bing.com");
VerifyDigDnsResolution(L"dig +short +time=5 TXT bing.com");
VerifyDigDnsResolution(L"dig +short +time=5 SOA bing.com");
}
static void VerifyDnsQueries()
{
// query for A/IPv4 records
VerifyDigDnsResolution(L"dig +short +time=5 A bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 A bing.com");
// query for AAAA/IPv6 records
VerifyDigDnsResolution(L"dig +short +time=5 AAAA bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 AAAA bing.com");
// query for MX records
VerifyDigDnsResolution(L"dig +short +time=5 MX bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 MX bing.com");
// query for NS records
VerifyDigDnsResolution(L"dig +short +time=5 NS bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 NS bing.com");
// reverse DNS lookup
VerifyDigDnsResolution(L"dig +short +time=5 -x 8.8.8.8");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 -x 8.8.8.8");
// query for SOA records
VerifyDigDnsResolution(L"dig +short +time=5 SOA bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 SOA bing.com");
// query for TXT records
VerifyDigDnsResolution(L"dig +short +time=5 TXT bing.com");
VerifyDigDnsResolution(L"dig +tcp +short +time=5 TXT bing.com");
// query for CNAME records
VerifyDigDnsResolution(L"dig +time=5 CNAME bing.com");
VerifyDigDnsResolution(L"dig +tcp +time=5 CNAME bing.com");
// query for SRV records
VerifyDigDnsResolution(L"dig +time=5 SRV bing.com");
VerifyDigDnsResolution(L"dig +tcp +time=5 SRV bing.com");
// query for ANY - for this option dig expects a large response so it will query directly over TCP,
// instead of trying UDP first and falling back to TCP.
VerifyDigDnsResolution(L"dig +short ANY bing.com");
}
static void VerifyDnsSuffixes()
{
bool foundSuffix = false;
// Verify global DNS suffixes are reflected in Linux
auto [outGlobal, errGlobal] = LxsstuLaunchPowershellAndCaptureOutput(
L"Get-DnsClientGlobalSetting | Select-Object -Property SuffixSearchList | ForEach-Object {$_.SuffixSearchList}");
const std::wstring separators = L" \n\t\r";
for (const auto& suffix : wsl::shared::string::SplitByMultipleSeparators(outGlobal, separators))
{
if (!suffix.empty())
{
foundSuffix = true;
// use grep -F as suffixes can contain '.'
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"cat /etc/resolv.conf | grep search | grep -F " + suffix), static_cast<DWORD>(0));
}
}
// Verify per-interface DNS suffixes are reflected in Linux
auto [outPerInterface, errPerInterface] =
LxsstuLaunchPowershellAndCaptureOutput(L"Get-DnsClient | ForEach-Object {$_.ConnectionSpecificSuffix}");
for (const auto& suffix : wsl::shared::string::SplitByMultipleSeparators(outPerInterface, separators))
{
if (!suffix.empty())
{
foundSuffix = true;
// use grep -F as suffixes can contain '.'
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"cat /etc/resolv.conf | grep search | grep -F " + suffix), static_cast<DWORD>(0));
}
}
// No suffix was found - configure a dummy global suffix, verify it's reflected in Linux, then delete it
if (!foundSuffix)
{
LxsstuLaunchPowershellAndCaptureOutput(L"Set-DnsClientGlobalSetting -SuffixSearchList @('test.com')");
auto restoreGlobalSuffixes = wil::scope_exit(
[&] { LxsstuLaunchPowershellAndCaptureOutput(L"Set-DnsClientGlobalSetting -SuffixSearchList @()"); });
std::this_thread::sleep_for(std::chrono::seconds(1));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"cat /etc/resolv.conf | grep search | grep -F test.com"), static_cast<DWORD>(0));
LxsstuLaunchPowershellAndCaptureOutput(L"Set-DnsClientGlobalSetting -SuffixSearchList @()");
std::this_thread::sleep_for(std::chrono::seconds(1));
VERIFY_ARE_NOT_EQUAL(LxsstuLaunchWsl(L"cat /etc/resolv.conf | grep search | grep -F test.com"), static_cast<DWORD>(0));
}
}
static void VerifyEtcHosts()
{
const auto windowsHostsPath = "C:\\Windows\\System32\\drivers\\etc\\hosts";
// Save existing Windows /etc/hosts
std::wifstream windowsHostsRead(windowsHostsPath);
const auto oldWindowsHosts = std::wstring{std::istreambuf_iterator<wchar_t>(windowsHostsRead), {}};
windowsHostsRead.close();
auto restoreWindowsHosts = wil::scope_exit([&] {
std::wofstream windowsHostsWrite(windowsHostsPath);
windowsHostsWrite << oldWindowsHosts;
});
// Add dummy entry matching bing.com to IP 1.2.3.4
std::wofstream windowsHostsWrite(windowsHostsPath, std::ios_base::app);
windowsHostsWrite << "\n1.2.3.4 bing.com";
windowsHostsWrite.close();
// Verify Linux /etc/hosts does *not* contain 1.2.3.4
VERIFY_ARE_NOT_EQUAL(LxsstuLaunchWsl(L"cat /etc/hosts | grep -F 1.2.3.4"), static_cast<DWORD>(0));
// Verify bing.com gets resolved to 1.2.3.4 by dig
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"dig bing.com | grep -F 1.2.3.4"), static_cast<DWORD>(0));
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"dig +tcp bing.com | grep -F 1.2.3.4"), static_cast<DWORD>(0));
}
static void VerifyDnsTunneling(const std::wstring& dnsTunnelingIpAddress)
{
// Verify /etc/resolv.conf is configured with the expected nameserver
VERIFY_ARE_EQUAL(LxsstuLaunchWsl(L"cat /etc/resolv.conf | grep nameserver | grep -F " + dnsTunnelingIpAddress), static_cast<DWORD>(0));
// Verify that we have a working connection.
GuestClient(L"tcp-connect:bing.com:80");
// Verify multiple types of DNS queries
VerifyDnsQueries();
// Verify resolution via Windows /etc/hosts
VerifyEtcHosts();
// Verify DNS tunneling works with systemd enabled
auto revert = EnableSystemd();
GuestClient(L"tcp-connect:bing.com:80");
VerifyDnsQueries();
}
TEST_METHOD(NatDnsTunneling)
{
DNS_TUNNELING_TEST_ONLY();
WslConfigChange config(LxssGenerateTestConfig({.dnsTunneling = true}));
VerifyDnsTunneling(c_dnsTunnelingDefaultIp);
}