Skip to content

A Hardware Hacking Tool with Web-Based CLI That Speaks Every Protocol

correctly sanitize utf8 before send to websocket

Geo07074e549899
diff --git a/src/Servers/WebSocketServer.cpp b/src/Servers/WebSocketServer.cpp
index 9f65ca77..915f3e4d 100644
--- a/src/Servers/WebSocketServer.cpp
+++ b/src/Servers/WebSocketServer.cpp
@@ -87,15 +87,7 @@ void WebSocketServer::sendText(const std::string& msg) {
if (clientFd < 0) return;
// Sanitize UTF8
- std::string safeMsg;
- for (unsigned char c : msg) {
- if ((c >= 32 && c <= 126) || c == '\n' || c == '\r' || c == '\t') {
- safeMsg += c;
- }
- // None UTF8, cant send that to socket
- }
-
- if (safeMsg.empty()) return;
+ std::string safeMsg = sanitizeUtf8(msg);
httpd_ws_frame_t ws_pkt = {};
ws_pkt.type = HTTPD_WS_TYPE_TEXT;
@@ -104,3 +96,37 @@ void WebSocketServer::sendText(const std::string& msg) {
httpd_ws_send_frame_async(server, clientFd, &ws_pkt);
}
+
+std::string WebSocketServer::sanitizeUtf8(const std::string& input) {
+ std::string output;
+ size_t i = 0;
+
+ while (i < input.size()) {
+ unsigned char c = input[i];
+
+ if (c <= 0x7F) { // ASCII
+ output += c;
+ i++;
+ } else if ((c & 0xE0) == 0xC0 && i + 1 < input.size() &&
+ (input[i+1] & 0xC0) == 0x80) {
+ output += input.substr(i, 2);
+ i += 2;
+ } else if ((c & 0xF0) == 0xE0 && i + 2 < input.size() &&
+ (input[i+1] & 0xC0) == 0x80 &&
+ (input[i+2] & 0xC0) == 0x80) {
+ output += input.substr(i, 3);
+ i += 3;
+ } else if ((c & 0xF8) == 0xF0 && i + 3 < input.size() &&
+ (input[i+1] & 0xC0) == 0x80 &&
+ (input[i+2] & 0xC0) == 0x80 &&
+ (input[i+3] & 0xC0) == 0x80) {
+ output += input.substr(i, 4);
+ i += 4;
+ } else {
+ // Invalid byte or sequence, skip it
+ i++;
+ }
+ }
+
+ return output;
+}
\ No newline at end of file
diff --git a/src/Servers/WebSocketServer.h b/src/Servers/WebSocketServer.h
index 651715ec..626e54a2 100644
--- a/src/Servers/WebSocketServer.h
+++ b/src/Servers/WebSocketServer.h
@@ -17,6 +17,7 @@ public:
char readCharBlocking();
char readCharNonBlocking();
void sendText(const std::string& msg);
+ std::string sanitizeUtf8(const std::string& input);
private:
static esp_err_t wsHandler(httpd_req_t *req);