Repository navigation
Expand file tree
/
Copy pathsocket_block.cpp
More file actions
177 lines (165 loc) · 7.75 KB
/
Copy pathsocket_block.cpp
File metadata and controls
177 lines (165 loc) · 7.75 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
#include <windows.h>
#include <fwpmu.h>
#include <shellapi.h>
#include <wrl/wrappers/corewrappers.h>
#include <filesystem>
#include <iostream>
#include <stdexcept>
#include <string>
#include <system_error>
#include <utility>
#include <vector>
namespace rage {
namespace {
void check_status(DWORD status, const char* operation) {
if (status != ERROR_SUCCESS)
throw std::system_error(static_cast<int>(status), std::system_category(), operation);
}
class SocketBlock {
public:
SocketBlock() = default;
SocketBlock(const SocketBlock&) = delete;
SocketBlock& operator=(const SocketBlock&) = delete;
~SocketBlock() {
if (in_transaction_) FwpmTransactionAbort0(engine_);
if (engine_) FwpmEngineClose0(engine_);
}
void install(const std::vector<std::filesystem::path>& images) {
wchar_t label[] = L"rdna4rage direct socket block";
FWPM_SESSION0 session{};
session.displayData.name = label;
session.flags = FWPM_SESSION_FLAG_DYNAMIC;
session.txnWaitTimeoutInMSec = 2000;
check_status(FwpmEngineOpen0(nullptr, RPC_C_AUTHN_WINNT, nullptr, &session, &engine_), "Open WFP session");
check_status(FwpmTransactionBegin0(engine_, 0), "Begin WFP transaction");
in_transaction_ = true;
FWPM_SUBLAYER0 layer{};
const RPC_STATUS uuid_status = UuidCreate(&layer.subLayerKey);
if (uuid_status != RPC_S_UUID_LOCAL_ONLY) check_status(uuid_status, "Create WFP sublayer identifier");
layer.displayData.name = label;
layer.weight = 0x8000;
check_status(FwpmSubLayerAdd0(engine_, &layer, nullptr), "Add WFP sublayer");
FWPM_FILTER_CONDITION0 condition{};
condition.fieldKey = FWPM_CONDITION_ALE_APP_ID;
condition.matchType = FWP_MATCH_EQUAL;
condition.conditionValue.type = FWP_BYTE_BLOB_TYPE;
FWPM_FILTER0 filter{};
filter.displayData.name = label;
filter.subLayerKey = layer.subLayerKey;
filter.action.type = FWP_ACTION_BLOCK;
filter.flags = FWPM_FILTER_FLAG_CLEAR_ACTION_RIGHT;
filter.numFilterConditions = 1;
filter.filterCondition = &condition;
for (const auto& image : images) {
struct AppId {
FWP_BYTE_BLOB* value{};
~AppId() { if (value) FwpmFreeMemory0(reinterpret_cast<void**>(&value)); }
} app;
check_status(FwpmGetAppIdFromFileName0(image.c_str(), &app.value), "Identify the executable for WFP");
condition.conditionValue.byteBlob = app.value;
for (const GUID* key : {&FWPM_LAYER_ALE_AUTH_CONNECT_V4, &FWPM_LAYER_ALE_AUTH_CONNECT_V6,
&FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V4, &FWPM_LAYER_ALE_AUTH_RECV_ACCEPT_V6}) {
filter.layerKey = *key;
check_status(FwpmFilterAdd0(engine_, &filter, nullptr, nullptr), "Add WFP socket filter");
}
}
check_status(FwpmTransactionCommit0(engine_), "Commit WFP socket filters");
in_transaction_ = false;
}
private:
HANDLE engine_{};
bool in_transaction_{};
};
}
using Handle = Microsoft::WRL::Wrappers::HandleT<Microsoft::WRL::Wrappers::HandleTraits::HANDLENullTraits>;
void wait_for_release() {
std::cout << "Direct IPv4 and IPv6 socket filters active. Press Enter to release them." << std::endl;
std::string line;
std::getline(std::cin, line);
}
std::wstring event_name(const wchar_t* id, const wchar_t* suffix) {
GUID guid{};
if (wcslen(id) != 38 || FAILED(CLSIDFromString(id, &guid))) throw std::invalid_argument("Invalid filter session ID");
return std::wstring(L"Local\\rdna4rage-filter-") + id + suffix;
}
DWORD broker(const std::vector<std::filesystem::path>& images, const wchar_t* id, const wchar_t* pid) {
wchar_t* end{};
const auto parent_pid = wcstoul(pid, &end, 10);
if (!parent_pid || *end) return ERROR_INVALID_PARAMETER;
Handle parent(OpenProcess(SYNCHRONIZE, FALSE, parent_pid));
if (!parent.IsValid()) return GetLastError();
Handle stop(OpenEventW(SYNCHRONIZE, FALSE, event_name(id, L"-stop").c_str()));
if (!stop.IsValid()) return GetLastError();
Handle ready(OpenEventW(EVENT_MODIFY_STATE, FALSE, event_name(id, L"-ready").c_str()));
if (!ready.IsValid()) return GetLastError();
SocketBlock block;
block.install(images);
if (!SetEvent(ready.Get())) return GetLastError();
HANDLE lifetime[]{stop.Get(), parent.Get()};
return WaitForMultipleObjects(2, lifetime, FALSE, INFINITE) == WAIT_FAILED ? GetLastError() : ERROR_SUCCESS;
}
DWORD elevated_filter(const std::vector<std::filesystem::path>& images) {
GUID guid{};
if (FAILED(CoCreateGuid(&guid))) throw std::runtime_error("Could not create filter session ID");
wchar_t id[40]{};
if (!StringFromGUID2(guid, id, 40)) throw std::runtime_error("Could not format filter session ID");
Handle ready(CreateEventW(nullptr, TRUE, FALSE, event_name(id, L"-ready").c_str()));
if (!ready.IsValid()) return GetLastError();
Handle stop(CreateEventW(nullptr, TRUE, FALSE, event_name(id, L"-stop").c_str()));
if (!stop.IsValid()) return GetLastError();
wchar_t self[32768]{};
const DWORD chars = GetModuleFileNameW(nullptr, self, static_cast<DWORD>(std::size(self)));
if (!chars || chars >= std::size(self)) return ERROR_BAD_PATHNAME;
auto args = std::wstring(L"--broker ") + id + L" " + std::to_wstring(GetCurrentProcessId());
for (const auto& image : images) args += L" \"" + image.wstring() + L"\"";
SHELLEXECUTEINFOW exec{sizeof(exec)};
exec.fMask = SEE_MASK_NOCLOSEPROCESS | SEE_MASK_NOASYNC;
exec.lpVerb = L"runas";
exec.lpFile = self;
exec.lpParameters = args.c_str();
exec.nShow = SW_HIDE;
if (!ShellExecuteExW(&exec)) return GetLastError();
Handle child(exec.hProcess);
if (!child.IsValid()) return ERROR_INVALID_HANDLE;
HANDLE signals[]{ready.Get(), child.Get()};
const DWORD started = WaitForMultipleObjects(2, signals, FALSE, 15000);
if (started == WAIT_OBJECT_0) wait_for_release();
if (!SetEvent(stop.Get())) return GetLastError();
if (WaitForSingleObject(child.Get(), 5000) != WAIT_OBJECT_0) return ERROR_TIMEOUT;
DWORD status{};
if (!GetExitCodeProcess(child.Get(), &status)) return GetLastError();
if (started != WAIT_OBJECT_0 && !status) return ERROR_OPERATION_ABORTED;
return status;
}
}
int wmain(int argc, wchar_t** argv) try {
const bool broker = argc >= 5 && std::wstring_view(argv[1]) == L"--broker";
const bool elevate = !broker && argc > 3 && std::wstring_view(argv[argc - 1]) == L"--elevate-filter";
if (!broker && (argc < 3 || std::wstring_view(argv[1]) != L"hold-socket-block")) {
std::fputs("Usage: rdna4rage-netguard hold-socket-block <executable> [additional executables] [--elevate-filter]\n", stderr);
return 2;
}
std::vector<std::filesystem::path> images;
for (int n = broker ? 4 : 2; n < argc - int(elevate); ++n) {
auto path = std::filesystem::canonical(argv[n]);
if (!std::filesystem::is_regular_file(path))
throw std::invalid_argument("The socket filter requires an existing executable file");
images.push_back(std::move(path));
}
if (broker) return static_cast<int>(rage::broker(images, argv[2], argv[3]));
if (elevate) {
const auto status = rage::elevated_filter(images);
if (status) throw std::system_error(int(status), std::system_category(), "Elevated WFP helper");
} else {
rage::SocketBlock block;
block.install(images);
rage::wait_for_release();
}
return 0;
} catch (const std::system_error& error) {
std::cerr << error.what() << '\n';
return error.code().value() ? error.code().value() : 1;
} catch (const std::exception& error) {
std::cerr << error.what() << '\n';
return 1;
}