-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathhttp_server.cpp
More file actions
274 lines (222 loc) · 7.5 KB
/
Copy pathhttp_server.cpp
File metadata and controls
274 lines (222 loc) · 7.5 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
#include "http_server.hpp"
#include <httplib.h>
#include <nlohmann/json.hpp>
#include <WinSock2.h>
#include <WS2tcpip.h>
#include <Windows.h>
#include <chrono>
#include <sstream>
#pragma comment(lib, "ws2_32.lib")
namespace windbg_agent {
class HttpServer::Impl {
public:
httplib::Server server;
};
HttpServer::HttpServer() = default;
HttpServer::~HttpServer() {
stop();
}
QueueResult HttpServer::queue_and_wait(const std::string& input) {
if (!running_.load()) {
return {false, "Error: HTTP server is not running"};
}
PendingCommand cmd;
cmd.input = input;
cmd.completed = false;
std::mutex done_mutex;
std::condition_variable done_cv;
cmd.done_mutex = &done_mutex;
cmd.done_cv = &done_cv;
{
std::lock_guard<std::mutex> lock(queue_mutex_);
pending_commands_.push(&cmd);
}
queue_cv_.notify_one();
{
std::unique_lock<std::mutex> lock(done_mutex);
done_cv.wait(lock, [&]() { return cmd.completed || !running_.load(); });
}
if (!cmd.completed) {
return {false, "Error: HTTP server stopped"};
}
return {true, cmd.result};
}
int HttpServer::start(ExecCallback exec_cb,
const std::string& bind_addr) {
if (running_.load()) {
return port_;
}
exec_cb_ = exec_cb;
bind_addr_ = bind_addr;
impl_ = std::make_unique<Impl>();
// Let the OS assign a free port
int assigned_port = impl_->server.bind_to_any_port(bind_addr.c_str());
if (assigned_port < 0) {
impl_.reset();
return -1;
}
impl_->server.Post("/exec", [this](const httplib::Request& req, httplib::Response& res) {
try {
auto json = nlohmann::json::parse(req.body);
std::string command = json.value("command", "");
if (command.empty()) {
res.status = 400;
res.set_content(R"({"error":"missing command","success":false})", "application/json");
return;
}
auto result = queue_and_wait(command);
nlohmann::json response = {{"output", result.payload}, {"success", result.success}};
if (!result.success) {
res.status = 503;
}
res.set_content(response.dump(), "application/json");
} catch (const std::exception& e) {
res.status = 500;
nlohmann::json response = {{"error", e.what()}, {"success", false}};
res.set_content(response.dump(), "application/json");
}
});
impl_->server.Get("/status", [](const httplib::Request&, httplib::Response& res) {
nlohmann::json response = {{"status", "ready"}, {"success", true}};
res.set_content(response.dump(), "application/json");
});
impl_->server.Post("/shutdown", [this](const httplib::Request&, httplib::Response& res) {
nlohmann::json response = {{"status", "stopping"}, {"success", true}};
res.set_content(response.dump(), "application/json");
std::thread([this]() {
std::this_thread::sleep_for(std::chrono::milliseconds(100));
stop();
}).detach();
});
port_ = assigned_port;
running_.store(true);
server_thread_ = std::thread([this]() {
impl_->server.listen_after_bind();
running_.store(false);
queue_cv_.notify_all();
complete_pending_commands("Error: HTTP server stopped");
});
return port_;
}
void HttpServer::set_interrupt_check(std::function<bool()> check) {
interrupt_check_ = check;
}
void HttpServer::wait() {
while (running_.load()) {
if (interrupt_check_ && interrupt_check_()) {
stop();
break;
}
PendingCommand* cmd = nullptr;
{
std::unique_lock<std::mutex> lock(queue_mutex_);
if (queue_cv_.wait_for(lock, std::chrono::milliseconds(100),
[this]() { return !pending_commands_.empty() || !running_.load(); })) {
if (!pending_commands_.empty()) {
cmd = pending_commands_.front();
pending_commands_.pop();
}
}
}
if (cmd) {
try {
if (exec_cb_) {
cmd->result = exec_cb_(cmd->input);
} else {
cmd->result = "Error: No exec handler";
}
} catch (const std::exception& e) {
cmd->result = std::string("Error: ") + e.what();
}
if (cmd->done_mutex && cmd->done_cv) {
{
std::lock_guard<std::mutex> lock(*cmd->done_mutex);
cmd->completed = true;
}
cmd->done_cv->notify_one();
}
}
}
if (server_thread_.joinable()) {
server_thread_.join();
}
}
void HttpServer::stop() {
if (impl_) {
impl_->server.stop();
}
running_.store(false);
queue_cv_.notify_all();
complete_pending_commands("Error: HTTP server stopped");
if (server_thread_.joinable()) {
server_thread_.join();
}
}
void HttpServer::complete_pending_commands(const std::string& result) {
std::queue<PendingCommand*> pending;
{
std::lock_guard<std::mutex> lock(queue_mutex_);
std::swap(pending, pending_commands_);
}
while (!pending.empty()) {
PendingCommand* cmd = pending.front();
pending.pop();
if (!cmd || !cmd->done_mutex || !cmd->done_cv) {
continue;
}
{
std::lock_guard<std::mutex> lock(*cmd->done_mutex);
if (!cmd->completed) {
cmd->result = result;
cmd->completed = true;
}
}
cmd->done_cv->notify_one();
}
}
bool copy_to_clipboard(const std::string& text) {
if (!OpenClipboard(nullptr)) {
return false;
}
EmptyClipboard();
HGLOBAL hg = GlobalAlloc(GMEM_MOVEABLE, text.size() + 1);
if (!hg) {
CloseClipboard();
return false;
}
memcpy(GlobalLock(hg), text.c_str(), text.size() + 1);
GlobalUnlock(hg);
SetClipboardData(CF_TEXT, hg);
CloseClipboard();
return true;
}
std::string format_http_info(
const std::string& target_name,
unsigned long pid,
const std::string& state,
const std::string& url
) {
std::ostringstream ss;
ss << "HTTP SERVER ACTIVE\n";
ss << "Target: " << target_name << " (PID " << pid << ")\n";
ss << "State: " << state << "\n";
ss << "URL: " << url << "\n\n";
ss << "HTTP API ENDPOINTS:\n";
ss << " POST " << url << "/exec - Execute raw debugger command\n";
ss << " GET " << url << "/status - Server status\n";
ss << " POST " << url << "/shutdown - Stop server\n\n";
ss << "CURL EXAMPLES:\n";
ss << " curl -X POST " << url << "/exec \\\n";
ss << " -H \"Content-Type: application/json\" \\\n";
ss << " -d '{\"command\": \"kb\"}'\n\n";
ss << " curl -X POST " << url << "/exec -H \"Content-Type: application/json\" -d '{\"command\": \"r rax\"}'\n";
ss << " curl -X POST " << url << "/exec -H \"Content-Type: application/json\" -d '{\"command\": \"!analyze -v\"}'\n\n";
ss << "PYTHON:\n";
ss << " import requests\n";
ss << " r = requests.post('" << url << "/exec', json={'command': 'kb'})\n";
ss << " print(r.json()['output'])\n\n";
ss << "RESPONSE FORMAT:\n";
ss << " /exec returns: {\"output\": \"...\", \"success\": true}\n";
return ss.str();
}
} // namespace windbg_agent