#include "strawberry/opensnitch_events.hpp" #include "strawberry/parse_num.hpp" #include "strawberry/proc_read.hpp" #include "strawberry/swallowed.hpp" #include "strawberry/thread_entry.hpp" #include #include #include #include #include #include #include #include #include #if defined(__APPLE__) #include // _NSGetEnviron #include #include #include #endif #include #include #include #include namespace strawberry { namespace { constexpr std::size_t kMaxClients = 4; constexpr std::size_t kMaxObject = 256u << 10; constexpr std::size_t kMaxBuffered = 1u << 20; std::string socket_hex(uint32_t s_addr, uint16_t port_host_order) { char buf[16]; std::snprintf(buf, sizeof buf, "%08X:%04X", s_addr, port_host_order); return buf; } std::optional json_int(const nlohmann::json& j, const char* key) { const auto it = j.find(key); if (it == j.end()) return std::nullopt; if (it->is_number_integer()) return it->get(); if (it->is_number_unsigned()) return static_cast(it->get()); if (it->is_string()) return parse_number(it->get_ref()); return std::nullopt; } std::string json_str(const nlohmann::json& j, const char* key) { const auto it = j.find(key); return it != j.end() && it->is_string() ? it->get() : std::string{}; } } // namespace std::optional parse_opensnitch_event(std::string_view text) noexcept { try { const auto record = nlohmann::json::parse(text, nullptr, false); if (!record.is_object()) return std::nullopt; const auto ev = record.find("Event"); const nlohmann::json& event = ev != record.end() && ev->is_object() ? *ev : record; // Only these fields are read; process_args and process_env are never // copied out of the parsed message. OpenSnitchConnection c; c.dst_host = json_str(event, "dst_host"); c.dst_ip = json_str(event, "dst_ip"); if (c.dst_host.empty() && c.dst_ip.empty()) return std::nullopt; c.process_path = json_str(event, "process_path"); c.protocol = json_str(event, "protocol"); c.action = json_str(record, "Action"); const auto pid = json_int(event, "process_id"); const auto uid = json_int(event, "user_id"); const auto port = json_int(event, "dst_port"); c.pid = pid && *pid > 0 && *pid <= INT32_MAX ? static_cast(*pid) : 0; c.uid = uid && *uid >= 0 && *uid <= UINT32_MAX ? static_cast(*uid) : 0; c.dst_port = port && *port >= 0 && *port <= 65535 ? static_cast(*port) : 0; return c; } catch (...) { STRAWBERRY_NOTE_SWALLOWED(); return std::nullopt; } } std::vector take_json_objects(std::string& buffer, std::size_t max_object, bool& overflow) { std::vector out; overflow = false; std::size_t pos = 0; while (true) { const auto start = buffer.find('{', pos); // bytes between objects are skipped if (start == std::string::npos) { pos = buffer.size(); break; } int depth = 0; bool in_string = false, escape = false; std::size_t end = std::string::npos; for (std::size_t i = start; i < buffer.size(); ++i) { const char ch = buffer[i]; if (i - start >= max_object) { overflow = true; break; } if (in_string) { if (escape) escape = false; else if (ch == '\\') escape = true; else if (ch == '"') in_string = false; } else if (ch == '"') { in_string = true; } else if (ch == '{') { ++depth; } else if (ch == '}' && --depth == 0) { end = i + 1; break; } } if (overflow || end == std::string::npos) { pos = start; // partial: keep it for the next read break; } out.emplace_back(buffer, start, end - start); pos = end; } buffer.erase(0, pos); return out; } std::optional tcp_socket_uid(std::string_view table, std::string_view local_hex, std::string_view remote_hex) { const auto same = [](std::string_view a, std::string_view b) { return a.size() == b.size() && std::equal(a.begin(), a.end(), b.begin(), [](char x, char y) { return std::toupper(static_cast(x)) == std::toupper(static_cast(y)); }); }; std::size_t pos = 0; while (pos < table.size()) { const auto nl = std::min(table.find('\n', pos), table.size()); const auto line = table.substr(pos, nl - pos); pos = nl + 1; std::vector f; std::size_t i = 0; while (i < line.size() && f.size() < 9) { while (i < line.size() && line[i] == ' ') ++i; const auto j = std::min(line.find(' ', i), line.size()); if (j > i) f.push_back(line.substr(i, j - i)); i = j; } if (f.size() < 8 || !same(f[1], local_hex) || !same(f[2], remote_hex)) continue; return parse_number(f[7]); } return std::nullopt; } bool parse_events_address(const std::string& address, uint16_t& port, std::string& error) { constexpr std::string_view kPrefix = "127.0.0.1:"; if (!address.starts_with(kPrefix)) { error = "must be 127.0.0.1: (loopback only)"; return false; } const auto p = parse_number(address.substr(kPrefix.size())); if (!p || *p == 0 || *p >= 1024) { error = "port must be 1-1023, so only root can listen on it (the events carry process environments)"; return false; } port = *p; return true; } OpenSnitchEventListener::~OpenSnitchEventListener() { stop(); } bool OpenSnitchEventListener::start(const std::string& address, Callback callback, std::string& error, bool check_peer) { stop(); #if !defined(__linux__) (void) address; (void) callback; (void) check_peer; error = "OpenSnitch events are Linux-only"; return false; #else uint16_t port = 0; if (check_peer) { if (!parse_events_address(address, port, error)) return false; } else if (address.starts_with("127.0.0.1:")) { port = parse_number(address.substr(10)).value_or(0); // tests: 0 picks a free port } const int fd = ::socket(AF_INET, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { error = std::string("socket: ") + std::strerror(errno); return false; } const int one = 1; (void) ::setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &one, sizeof one); sockaddr_in sa{}; sa.sin_family = AF_INET; sa.sin_port = htons(port); sa.sin_addr.s_addr = htonl(INADDR_LOOPBACK); socklen_t len = sizeof sa; if (::bind(fd, reinterpret_cast(&sa), sizeof sa) != 0 || ::listen(fd, 4) != 0 || ::getsockname(fd, reinterpret_cast(&sa), &len) != 0) { error = "listen on 127.0.0.1:" + std::to_string(port) + ": " + std::strerror(errno); ::close(fd); return false; } if (::pipe2(wake_, O_CLOEXEC | O_NONBLOCK) != 0) { error = std::string("pipe: ") + std::strerror(errno); ::close(fd); return false; } listen_fd_ = fd; check_peer_ = check_peer; callback_ = std::move(callback); stop_ = false; { std::lock_guard lock(mutex_); stats_ = {}; stats_.listening = true; stats_.address = "127.0.0.1:" + std::to_string(ntohs(sa.sin_port)); } thread_ = std::thread(run_guarded("opensnitch-events", [this] { loop(); })); return true; #endif } void OpenSnitchEventListener::stop() { stop_ = true; if (wake_[1] >= 0) (void) !::write(wake_[1], "x", 1); if (thread_.joinable()) thread_.join(); const auto close_fd = [](int& fd) { if (fd >= 0) ::close(fd); fd = -1; }; close_fd(listen_fd_); close_fd(wake_[0]); close_fd(wake_[1]); std::lock_guard lock(mutex_); stats_.listening = false; } OpenSnitchListenerStats OpenSnitchEventListener::stats() const { std::lock_guard lock(mutex_); return stats_; } void OpenSnitchEventListener::loop() { #if defined(__linux__) struct Client { int fd; std::string buffer; }; std::vector clients; sockaddr_in self{}; socklen_t self_len = sizeof self; (void) ::getsockname(listen_fd_, reinterpret_cast(&self), &self_len); const auto count = [this](uint64_t OpenSnitchListenerStats::*field) { std::lock_guard lock(mutex_); ++(stats_.*field); }; while (!stop_) { std::vector fds{{wake_[0], POLLIN, 0}, {listen_fd_, POLLIN, 0}}; for (const auto& c : clients) fds.push_back({c.fd, POLLIN, 0}); if (::poll(fds.data(), fds.size(), 1000) < 0) { if (errno == EINTR) continue; std::lock_guard lock(mutex_); stats_.error = std::string("poll: ") + std::strerror(errno); break; } if (fds[0].revents != 0) break; if ((fds[1].revents & POLLIN) != 0) { sockaddr_in peer{}; socklen_t plen = sizeof peer; const int cfd = ::accept4(listen_fd_, reinterpret_cast(&peer), &plen, SOCK_CLOEXEC); if (cfd >= 0) { bool ok = clients.size() < kMaxClients; if (ok && check_peer_) { // OpenSnitch's daemon runs as root; anything else could // feed made-up events. const auto table = read_small_file("/proc/net/tcp", 16u << 20); const auto uid = table ? tcp_socket_uid(*table, socket_hex(peer.sin_addr.s_addr, ntohs(peer.sin_port)), socket_hex(self.sin_addr.s_addr, ntohs(self.sin_port))) : std::nullopt; ok = uid && *uid == 0; } if (ok) { clients.push_back({cfd, {}}); count(&OpenSnitchListenerStats::connections); } else { ::close(cfd); count(&OpenSnitchListenerStats::rejected_peers); } } } for (std::size_t k = 2; k < fds.size(); ++k) { if (fds[k].revents == 0) continue; auto& c = clients[k - 2]; char buf[65536]; const auto n = ::recv(c.fd, buf, sizeof buf, 0); if (n <= 0) { if (n < 0 && (errno == EINTR || errno == EAGAIN)) continue; ::close(c.fd); c.fd = -1; continue; } c.buffer.append(buf, static_cast(n)); bool overflow = false; for (const auto& object : take_json_objects(c.buffer, kMaxObject, overflow)) { const auto event = parse_opensnitch_event(object); if (!event) { count(&OpenSnitchListenerStats::parse_errors); continue; } count(&OpenSnitchListenerStats::events); try { if (callback_) callback_(*event); } catch (...) { STRAWBERRY_NOTE_SWALLOWED(); // advisory only: the stream keeps flowing } } if (overflow || c.buffer.size() > kMaxBuffered) { count(&OpenSnitchListenerStats::oversized); ::close(c.fd); c.fd = -1; } } std::erase_if(clients, [](const Client& c) { return c.fd < 0; }); } for (const auto& c : clients) ::close(c.fd); #endif } std::string encode_connection(const OpenSnitchConnection& c) { // Only the redacted fields; argv/env are never present in OpenSnitchConnection. const nlohmann::json j{{"pid", c.pid}, {"uid", c.uid}, {"path", c.process_path}, {"host", c.dst_host}, {"ip", c.dst_ip}, {"port", c.dst_port}, {"proto", c.protocol}, {"action", c.action}}; return j.dump(-1, ' ', false, nlohmann::json::error_handler_t::replace); } std::optional decode_connection(std::string_view json) noexcept { try { const auto j = nlohmann::json::parse(json, nullptr, false); if (!j.is_object()) return std::nullopt; OpenSnitchConnection c; c.pid = j.value("pid", 0); c.uid = j.value("uid", 0u); c.process_path = j.value("path", std::string{}); c.dst_host = j.value("host", std::string{}); c.dst_ip = j.value("ip", std::string{}); c.dst_port = j.value("port", 0); c.protocol = j.value("proto", std::string{}); c.action = j.value("action", std::string{}); if (c.dst_host.empty() && c.dst_ip.empty()) return std::nullopt; return c; } catch (...) { STRAWBERRY_NOTE_SWALLOWED(); return std::nullopt; } } std::vector split_csv_line(std::string_view line) { std::vector out; std::string field; bool in_quotes = false; for (std::size_t i = 0; i < line.size(); ++i) { const char ch = line[i]; if (in_quotes) { if (ch == '"') { if (i + 1 < line.size() && line[i + 1] == '"') { field.push_back('"'); ++i; // doubled "" -> literal " } else { in_quotes = false; } } else { field.push_back(ch); } } else if (ch == '"') { in_quotes = true; } else if (ch == ',') { out.push_back(std::move(field)); field.clear(); } else if (ch != '\r') { field.push_back(ch); } } out.push_back(std::move(field)); return out; } std::optional LittleSnitchParser::feed_line(std::string_view line) { if (line.empty()) return std::nullopt; const auto fields = split_csv_line(line); if (!have_header_) { // First line names the columns; map the ones we use (ignore the rest, // so column reordering or new columns across versions is tolerated). for (int idx = 0; idx < static_cast(fields.size()); ++idx) { const auto& name = fields[idx]; if (name == "direction") i_direction_ = idx; else if (name == "uid") i_uid_ = idx; else if (name == "ipAddress") i_ip_ = idx; else if (name == "remoteHostname") i_host_ = idx; else if (name == "protocol") i_proto_ = idx; else if (name == "port") i_port_ = idx; else if (name == "denyCount") i_deny_ = idx; else if (name == "connectingExecutable") i_exe_ = idx; } have_header_ = true; return std::nullopt; } const auto at = [&](int idx) -> std::string { return idx >= 0 && idx < static_cast(fields.size()) ? fields[idx] : std::string{}; }; if (i_direction_ < 0 || i_host_ < 0 || i_exe_ < 0) return std::nullopt; // header lacked required columns if (at(i_direction_) != "out") return std::nullopt; // only outbound contacts OpenSnitchConnection c; c.process_path = at(i_exe_); c.dst_host = at(i_host_); c.dst_ip = at(i_ip_); if ((c.dst_host.empty() && c.dst_ip.empty()) || c.process_path.empty()) return std::nullopt; if (const auto uid = parse_number(at(i_uid_))) c.uid = *uid; if (const auto port = parse_number(at(i_port_)); port && *port >= 0 && *port <= 65535) c.dst_port = *port; const auto proto = parse_number(at(i_proto_)); c.protocol = proto ? (*proto == 6 ? "tcp" : *proto == 17 ? "udp" : std::to_string(*proto)) : std::string{}; const auto deny = parse_number(at(i_deny_)); c.action = deny && *deny > 0 ? "deny" : "allow"; return c; } TrackerIngestServer::~TrackerIngestServer() { stop(); } bool TrackerIngestServer::start(const std::string& path, Callback callback, std::string& error, bool require_root) { stop(); #if !defined(__linux__) (void) path; (void) callback; (void) require_root; error = "tracker ingest socket is Linux-only"; return false; #else const int fd = ::socket(AF_UNIX, SOCK_STREAM | SOCK_CLOEXEC, 0); if (fd < 0) { error = std::string("socket: ") + std::strerror(errno); return false; } sockaddr_un sa{}; sa.sun_family = AF_UNIX; if (path.size() + 1 > sizeof(sa.sun_path)) { error = "ingest socket path too long"; ::close(fd); return false; } std::strncpy(sa.sun_path, path.c_str(), sizeof(sa.sun_path) - 1); ::unlink(path.c_str()); // a stale socket from a previous run if (::bind(fd, reinterpret_cast(&sa), sizeof sa) != 0 || ::listen(fd, 4) != 0) { error = "listen on " + path + ": " + std::strerror(errno); ::close(fd); return false; } (void) ::chmod(path.c_str(), 0660); if (::pipe2(wake_, O_CLOEXEC | O_NONBLOCK) != 0) { error = std::string("pipe: ") + std::strerror(errno); ::close(fd); ::unlink(path.c_str()); return false; } listen_fd_ = fd; require_root_ = require_root; path_ = path; callback_ = std::move(callback); stop_ = false; { std::lock_guard lock(mutex_); stats_ = {}; stats_.listening = true; stats_.path = path; } thread_ = std::thread(run_guarded("tracker-ingest", [this] { loop(); })); return true; #endif } void TrackerIngestServer::stop() { stop_ = true; if (wake_[1] >= 0) (void) !::write(wake_[1], "x", 1); if (thread_.joinable()) thread_.join(); const auto close_fd = [](int& fd) { if (fd >= 0) ::close(fd); fd = -1; }; close_fd(listen_fd_); close_fd(wake_[0]); close_fd(wake_[1]); if (!path_.empty()) ::unlink(path_.c_str()); std::lock_guard lock(mutex_); stats_.listening = false; } TrackerIngestStats TrackerIngestServer::stats() const { std::lock_guard lock(mutex_); return stats_; } void TrackerIngestServer::loop() { #if defined(__linux__) struct Client { int fd; std::string buffer; }; std::vector clients; const auto count = [this](uint64_t TrackerIngestStats::*field) { std::lock_guard lock(mutex_); ++(stats_.*field); }; while (!stop_) { std::vector fds{{wake_[0], POLLIN, 0}, {listen_fd_, POLLIN, 0}}; for (const auto& c : clients) fds.push_back({c.fd, POLLIN, 0}); if (::poll(fds.data(), fds.size(), 1000) < 0) { if (errno == EINTR) continue; std::lock_guard lock(mutex_); stats_.error = std::string("poll: ") + std::strerror(errno); break; } if (fds[0].revents != 0) break; if ((fds[1].revents & POLLIN) != 0) { const int cfd = ::accept4(listen_fd_, nullptr, nullptr, SOCK_CLOEXEC); if (cfd >= 0) { bool ok = clients.size() < kMaxClients; if (ok && require_root_) { // The relay runs as root; nothing else may feed tuples. ucred cred{}; socklen_t len = sizeof cred; ok = ::getsockopt(cfd, SOL_SOCKET, SO_PEERCRED, &cred, &len) == 0 && cred.uid == 0; } if (ok) { clients.push_back({cfd, {}}); count(&TrackerIngestStats::connections); } else { ::close(cfd); count(&TrackerIngestStats::rejected_peers); } } } for (std::size_t k = 2; k < fds.size(); ++k) { if (fds[k].revents == 0) continue; auto& c = clients[k - 2]; char buf[65536]; const auto n = ::recv(c.fd, buf, sizeof buf, 0); if (n <= 0) { if (n < 0 && (errno == EINTR || errno == EAGAIN)) continue; ::close(c.fd); c.fd = -1; continue; } c.buffer.append(buf, static_cast(n)); bool overflow = false; for (const auto& object : take_json_objects(c.buffer, kMaxObject, overflow)) { const auto conn = decode_connection(object); if (!conn) { count(&TrackerIngestStats::parse_errors); continue; } count(&TrackerIngestStats::events); try { if (callback_) callback_(*conn); } catch (...) { STRAWBERRY_NOTE_SWALLOWED(); // advisory only: keep reading } } if (overflow || c.buffer.size() > kMaxBuffered) { count(&TrackerIngestStats::oversized); ::close(c.fd); c.fd = -1; } } std::erase_if(clients, [](const Client& c) { return c.fd < 0; }); } for (const auto& c : clients) ::close(c.fd); #endif } #if defined(__APPLE__) LittleSnitchSource::~LittleSnitchSource() { stop(); } bool LittleSnitchSource::start(const std::string& cli_path, Callback callback, std::string& error) { stop(); int fds[2]; if (::pipe(fds) != 0) { error = std::string("pipe: ") + std::strerror(errno); return false; } posix_spawn_file_actions_t actions; posix_spawn_file_actions_init(&actions); posix_spawn_file_actions_adddup2(&actions, fds[1], STDOUT_FILENO); posix_spawn_file_actions_addclose(&actions, fds[0]); posix_spawn_file_actions_addclose(&actions, fds[1]); const char* argv[] = {cli_path.c_str(), "log-traffic", "--stream", nullptr}; pid_t pid = -1; const int rc = ::posix_spawn(&pid, cli_path.c_str(), &actions, nullptr, const_cast(argv), *_NSGetEnviron()); posix_spawn_file_actions_destroy(&actions); ::close(fds[1]); // the child owns the write end now if (rc != 0) { ::close(fds[0]); error = std::string("spawn ") + cli_path + ": " + std::strerror(rc); return false; } child_ = pid; read_fd_ = fds[0]; cli_ = cli_path; callback_ = std::move(callback); stop_ = false; { std::lock_guard lock(mutex_); stats_ = {}; stats_.running = true; stats_.cli = cli_path; } thread_ = std::thread(run_guarded("littlesnitch", [this] { loop(); })); return true; } void LittleSnitchSource::stop() { stop_ = true; // SIGTERM the CLI: it exits, its pipe end closes, read() returns EOF and the // loop ends. (Closing read_fd_ from here would race the reader thread.) if (child_ > 0) ::kill(child_, SIGTERM); if (thread_.joinable()) thread_.join(); if (read_fd_ >= 0) { ::close(read_fd_); read_fd_ = -1; } if (child_ > 0) { int status = 0; ::waitpid(child_, &status, 0); child_ = -1; } std::lock_guard lock(mutex_); stats_.running = false; } LittleSnitchStats LittleSnitchSource::stats() const { std::lock_guard lock(mutex_); return stats_; } void LittleSnitchSource::loop() { LittleSnitchParser parser; std::string buffer; char buf[65536]; while (!stop_) { const auto n = ::read(read_fd_, buf, sizeof buf); if (n <= 0) { if (n < 0 && errno == EINTR) continue; break; // EOF (CLI exited) or error } buffer.append(buf, static_cast(n)); std::size_t nl; while ((nl = buffer.find('\n')) != std::string::npos) { const std::string line = buffer.substr(0, nl); buffer.erase(0, nl + 1); { std::lock_guard lock(mutex_); ++stats_.lines; } const auto conn = parser.feed_line(line); if (!conn) continue; { std::lock_guard lock(mutex_); ++stats_.events; } try { if (callback_) callback_(*conn); } catch (...) { STRAWBERRY_NOTE_SWALLOWED(); // advisory: keep reading the stream } } if (buffer.size() > (1u << 20)) buffer.clear(); // guard a runaway partial line } } #endif // __APPLE__ } // namespace strawberry