Skip to content
API Documentation
BastionGuard™
Backend.cpp File Reference

Go to the source code of this file.

Classes

struct  DbInfo

Namespaces

namespace  anonymous_namespace{Backend.cpp}

Typedefs

using json = nlohmann::json

Functions

static std::string b64_encode (const std::string &s)
static std::string b64_decode (const std::string &s)
static std::string xor_crypt (const std::string &input)
static std::string encrypt_pass (const std::string &pass)
static std::string decrypt_pass (const std::string &enc)
static std::string trim (const std::string &s)
static std::string extract_path_from_clamav_line (const std::string &line)
static std::vector< std::string > clamDbDirs ()
static std::time_t filetime_to_time_t (fs::file_time_type ft)
static bool read_cvd_header (const std::string &path, DbInfo &out)
static std::string first_existing (const std::vector< std::string > &names)
std::pair< int, int > read_ports_from_conf ()
static void restart_clamd ()
static bool install_to_system_data (const std::string &src, const std::string &dest)
static std::string getUserConfigDir ()
static std::string getConfigFilePath ()
static void persistQuarantinePath (const std::string &path)
static void loadQuarantinePathFromConfig ()
static void ensureQuarantinePath ()
static std::string getRuntimeDataDir ()
static bool copy_to_final (const std::string &src, const std::string &dest)
static std::string findClamonaccService ()
static int installPackages (const std::vector< std::string > &args)
static std::string detectDistro ()
static bool isClamdInstalled ()
static bool run_phishing_updater_script (const std::string &staging_dir)
static bool is_writable_dir (const std::filesystem::path &dir)
static std::filesystem::path make_temp_scan_dir ()
static size_t write_cb (void *c, size_t s, size_t n, std::string *o)
bool anonymous_namespace{Backend.cpp}::create_secure_firewall_input (const std::vector< std::string > &blacklistLines, std::string &outPath)
int anonymous_namespace{Backend.cpp}::run_firewall_helper (const std::string &inputPath)

Variables

static const std::string SMB_KEY = "BastionGuard0101SecretKey"
static std::string quarantinePath = Glib::get_home_dir() + "/.local/share/BastionGuard/quarantine"
static const char * CLAMONACC_SERVICES []
sigc::signal< void(const std::string &)> antiphish_signal_

Typedef Documentation

◆ json

using json = nlohmann::json

Definition at line 2908 of file Backend.cpp.

Function Documentation

◆ b64_decode()

std::string b64_decode ( const std::string & s)
static

Definition at line 90 of file Backend.cpp.

90 {
91 return Glib::Base64::decode(s);
92}

References b64_decode().

Referenced by b64_decode(), decrypt_pass(), Backend::getCreds(), Backend::loadSMBCredentials(), and Backend::saveSMBCredentials().

◆ b64_encode()

std::string b64_encode ( const std::string & s)
static

Definition at line 86 of file Backend.cpp.

86 {
87 return Glib::Base64::encode(s);
88}

References b64_encode().

Referenced by b64_encode(), encrypt_pass(), and Backend::saveSMBCredentials().

◆ clamDbDirs()

std::vector< std::string > clamDbDirs ( )
static

Definition at line 132 of file Backend.cpp.

133{
134 std::vector<std::string> dirs = {
135 "/var/lib/clamav",
136 Glib::get_home_dir() + "/.local/share/clamav",
137 "/usr/local/share/clamav"
138 };
139 return dirs;
140}

References clamDbDirs().

Referenced by clamDbDirs(), and first_existing().

◆ copy_to_final()

bool copy_to_final ( const std::string & src,
const std::string & dest )
static

Definition at line 431 of file Backend.cpp.

431 {
432 try {
433 fs::create_directories(fs::path(dest).parent_path());
434 fs::copy_file(src, dest, fs::copy_options::overwrite_existing);
435 return true;
436 } catch (const std::exception& e) {
437 std::cerr << _("❌ Errore copia ") << src << " -> " << dest << ": " << e.what() << std::endl;
438 return false;
439 }
440}
#define _(s)

References _, and copy_to_final().

Referenced by copy_to_final(), Backend::updatePhishLists(), and Backend::updateSanesecurityDB().

◆ decrypt_pass()

std::string decrypt_pass ( const std::string & enc)
static

Definition at line 107 of file Backend.cpp.

107 {
108 return xor_crypt(b64_decode(enc));
109}
static std::string xor_crypt(const std::string &input)
Definition Backend.cpp:96
static std::string b64_decode(const std::string &s)
Definition Backend.cpp:90

References b64_decode(), decrypt_pass(), and xor_crypt().

Referenced by decrypt_pass(), Backend::getCreds(), and Backend::saveSMBCredentials().

◆ detectDistro()

std::string detectDistro ( )
static

Definition at line 653 of file Backend.cpp.

653 {
654 const std::string id = BastionGuard::Platform::distribution_id();
655 return id.empty() ? "unknown" : id;
656}
std::string distribution_id()

References detectDistro(), and BastionGuard::Platform::distribution_id().

Referenced by detectDistro(), and Backend::installClamdIfMissing().

◆ encrypt_pass()

std::string encrypt_pass ( const std::string & pass)
static

Definition at line 103 of file Backend.cpp.

103 {
104 return b64_encode(xor_crypt(pass));
105}
static std::string b64_encode(const std::string &s)
Definition Backend.cpp:86

References b64_encode(), encrypt_pass(), and xor_crypt().

Referenced by encrypt_pass(), and Backend::saveSMBCredentials().

◆ ensureQuarantinePath()

void ensureQuarantinePath ( )
static

Definition at line 399 of file Backend.cpp.

399 {
400 try {
401 fs::create_directories(quarantinePath);
402 } catch (const std::exception& e) {
403 std::cerr << _("❌ Errore creazione cartella quarantena: ") << e.what() << std::endl;
404 }
405}
static std::string quarantinePath
Definition Backend.cpp:339

References _, ensureQuarantinePath(), and quarantinePath.

Referenced by ensureQuarantinePath().

◆ extract_path_from_clamav_line()

std::string extract_path_from_clamav_line ( const std::string & line)
static

Definition at line 122 of file Backend.cpp.

123{
124 auto pos = line.find(':');
125 if (pos == std::string::npos)
126 return line;
127
128 return line.substr(0, pos);
129}

References extract_path_from_clamav_line().

Referenced by extract_path_from_clamav_line().

◆ filetime_to_time_t()

std::time_t filetime_to_time_t ( fs::file_time_type ft)
static

Definition at line 149 of file Backend.cpp.

150{
151 using namespace std::chrono;
152 auto sctp = time_point_cast<system_clock::duration>(
153 ft - fs::file_time_type::clock::now() + system_clock::now()
154 );
155 return system_clock::to_time_t(sctp);
156}

References filetime_to_time_t().

Referenced by filetime_to_time_t(), and read_cvd_header().

◆ findClamonaccService()

std::string findClamonaccService ( )
static

Definition at line 443 of file Backend.cpp.

443 {
444 for (auto service : CLAMONACC_SERVICES) {
445 if (bg_process::run({"/usr/libexec/bastionguard/bastionguard-service",
446 "--system", "is-active", service}).ok()) {
447 return service;
448 }
449 }
450 return CLAMONACC_SERVICES[0];
451}
static const char * CLAMONACC_SERVICES[]
Definition Backend.cpp:407
Result run(const std::vector< std::string > &args, bool merge_stderr=false, std::size_t limit=8U *1024U *1024U, const std::map< std::string, std::string > &environment={}, const std::function< bool(const std::string &)> &on_line={})

References CLAMONACC_SERVICES, findClamonaccService(), bg_process::Result::ok(), and bg_process::run().

Referenced by Backend::disableClamonacc(), Backend::enableClamonacc(), and findClamonaccService().

◆ first_existing()

std::string first_existing ( const std::vector< std::string > & names)
static

Definition at line 227 of file Backend.cpp.

228{
229 for (const auto& dir : clamDbDirs()) {
230 for (const auto& n : names) {
231 std::string p = dir + "/" + n;
232 if (fs::exists(p)) return p;
233 }
234 }
235 return {};
236}
static std::vector< std::string > clamDbDirs()
Definition Backend.cpp:132

References clamDbDirs(), and first_existing().

Referenced by first_existing().

◆ getConfigFilePath()

std::string getConfigFilePath ( )
static

Definition at line 351 of file Backend.cpp.

351 {
352 return getUserConfigDir() + "/BastionGuard/config.ini";
353}
static std::string getUserConfigDir()
Definition Backend.cpp:341

References getConfigFilePath(), and getUserConfigDir().

Referenced by getConfigFilePath(), and loadQuarantinePathFromConfig().

◆ getRuntimeDataDir()

std::string getRuntimeDataDir ( )
static

Definition at line 413 of file Backend.cpp.

413 {
414 const char* xdg_data = std::getenv("XDG_DATA_HOME");
415 if (xdg_data && std::strlen(xdg_data) > 0) {
416 return std::string(xdg_data) + "/BastionGuard";
417 }
418
419 const char* home = std::getenv("HOME");
420 if (home)
421 return std::string(home) + "/.local/share/BastionGuard";
422
423 return "/tmp/BastionGuard";
424}

References getRuntimeDataDir().

Referenced by getRuntimeDataDir(), Backend::updatePhishLists(), Backend::updateSanesecurityDB(), and Backend::updateYaraRules().

◆ getUserConfigDir()

std::string getUserConfigDir ( )
static

Definition at line 341 of file Backend.cpp.

341 {
342 const char* xdg = std::getenv("XDG_CONFIG_HOME");
343 if (xdg && std::strlen(xdg) > 0) {
344 return std::string(xdg);
345 }
346 const char* home = std::getenv("HOME");
347 if (home) return std::string(home) + "/.config";
348 return std::string("/tmp");
349}

References getUserConfigDir().

Referenced by getConfigFilePath(), getUserConfigDir(), and persistQuarantinePath().

◆ install_to_system_data()

bool install_to_system_data ( const std::string & src,
const std::string & dest )
static

Definition at line 321 of file Backend.cpp.

321 {
322 try {
323 // One fixed privileged executable, with src/dest as literal argv entries.
324 const auto installation = bg_process::run({"pkexec", "/usr/bin/install", "-D", "-m", "0644", src, dest});
325 if (!installation.ok()) {
326 std::cerr << _("⚠ install_to_system_data: pkexec failed (code ")
327 << installation.exit_code << ")\n";
328 return false;
329 }
331 return true;
332 } catch (const std::exception& e) {
333 std::cerr << _("❌ install_to_system_data exception: ") << e.what() << "\n";
334 return false;
335 }
336}
static void restart_clamd()
Definition Backend.cpp:308

References _, install_to_system_data(), restart_clamd(), and bg_process::run().

Referenced by install_to_system_data(), and Backend::updateSanesecurityDB().

◆ installPackages()

int installPackages ( const std::vector< std::string > & args)
static

Definition at line 646 of file Backend.cpp.

646 {
647 if (args.empty()) return 127;
648 std::vector<std::string> argv = {"pkexec"};
649 argv.insert(argv.end(), args.begin(), args.end());
650 return bg_process::run(argv, true).exit_code;
651}

References bg_process::Result::exit_code, installPackages(), and bg_process::run().

Referenced by Backend::installClamdIfMissing(), and installPackages().

◆ is_writable_dir()

bool is_writable_dir ( const std::filesystem::path & dir)
static

Definition at line 1783 of file Backend.cpp.

1784{
1785 namespace fs = std::filesystem;
1786 std::error_code ec;
1787
1788 if (!fs::exists(dir, ec) || !fs::is_directory(dir, ec))
1789 return false;
1790
1791 // Prova a creare un file temporaneo (probe)
1792 auto probe = dir / ".bastionguard_write_test";
1793 {
1794 std::ofstream out(probe, std::ios::out | std::ios::trunc);
1795 if (!out.is_open())
1796 return false;
1797 out << "ok\n";
1798 }
1799 fs::remove(probe, ec);
1800 return true;
1801}

References is_writable_dir().

Referenced by is_writable_dir(), and make_temp_scan_dir().

◆ isClamdInstalled()

bool isClamdInstalled ( )
static

Definition at line 658 of file Backend.cpp.

658 {
659 return ((bg_process::exists_on_path("clamd") ? 0 : 1) == 0) ||
660 (std::filesystem::exists("/usr/sbin/clamd") ||
661 std::filesystem::exists("/usr/bin/clamd"));
662}
bool exists_on_path(const std::string &name)

References bg_process::exists_on_path(), and isClamdInstalled().

Referenced by Backend::installClamdIfMissing(), and isClamdInstalled().

◆ loadQuarantinePathFromConfig()

void loadQuarantinePathFromConfig ( )
static

Definition at line 378 of file Backend.cpp.

378 {
379 std::string cfg = getConfigFilePath();
380 if (!fs::exists(cfg)) return;
381
382 std::ifstream f(cfg);
383 if (!f.is_open()) return;
384
385 std::string line;
386 while (std::getline(f, line)) {
387 auto pos = line.find('=');
388 if (pos == std::string::npos) continue;
389 std::string key = line.substr(0, pos);
390 std::string val = line.substr(pos + 1);
391 if (key == "quarantinePath" && !val.empty()) {
392 quarantinePath = val;
393 break;
394 }
395 }
396 f.close();
397}
static std::string getConfigFilePath()
Definition Backend.cpp:351

References getConfigFilePath(), loadQuarantinePathFromConfig(), and quarantinePath.

Referenced by Backend::Backend(), Backend::getQuarantinePath(), and loadQuarantinePathFromConfig().

◆ make_temp_scan_dir()

std::filesystem::path make_temp_scan_dir ( )
static

Definition at line 1803 of file Backend.cpp.

1804{
1805 namespace fs = std::filesystem;
1806 std::error_code ec;
1807
1808
1809 fs::path candidates[] = {
1810 fs::temp_directory_path(),
1811 fs::path("/var/tmp")
1812 };
1813
1814 auto ensure_dir_ok = [&](const fs::path& p) -> bool {
1815 ec.clear();
1816 if (!fs::exists(p, ec))
1817 return false;
1818 if (!fs::is_directory(p, ec))
1819 return false;
1820
1821
1822 return is_writable_dir(p);
1823 };
1824
1825 fs::path base;
1826 for (const auto& c : candidates) {
1827 if (ensure_dir_ok(c)) {
1828 base = c;
1829 break;
1830 }
1831 }
1832 if (base.empty())
1833 return {};
1834
1835 std::random_device rd;
1836 std::mt19937_64 gen(rd());
1837 std::uniform_int_distribution<unsigned long long> dis(1, ULLONG_MAX);
1838
1839 for (int tries = 0; tries < 60; ++tries) {
1840 fs::path tmp = base / ("BastionGuard_samba_" + std::to_string(dis(gen)));
1841
1842 ec.clear();
1843 if (!fs::create_directories(tmp, ec) || ec)
1844 continue;
1845
1846
1847 fs::permissions(tmp,
1848 fs::perms::owner_all |
1849 fs::perms::group_read | fs::perms::group_exec |
1850 fs::perms::others_read | fs::perms::others_exec,
1851 fs::perm_options::replace,
1852 ec);
1853
1854 if (ec) {
1855 fs::remove_all(tmp, ec);
1856 continue;
1857 }
1858
1859 if (is_writable_dir(tmp))
1860 return tmp;
1861
1862 fs::remove_all(tmp, ec);
1863 }
1864
1865 return {};
1866}
static bool is_writable_dir(const std::filesystem::path &dir)
Definition Backend.cpp:1783

References is_writable_dir(), and make_temp_scan_dir().

Referenced by make_temp_scan_dir(), and Backend::scanSambaDir().

◆ persistQuarantinePath()

void persistQuarantinePath ( const std::string & path)
static

Definition at line 355 of file Backend.cpp.

355 {
356 try {
357 std::string cfgDir = getUserConfigDir() + "/BastionGuard";
358 std::filesystem::create_directories(cfgDir);
359
360 std::string cfgPath = cfgDir + "/config.ini";
361 std::ofstream f(cfgPath, std::ios::trunc);
362 if (!f.is_open()) {
363 std::cerr << "⚠️ " << _("Impossibile aprire il file di configurazione per scrittura: ")
364 << cfgPath << std::endl;
365 return;
366 }
367
368 f << "quarantinePath=" << path << "\n";
369 f.close();
370
371 std::cout << "💾 " << _("Percorso quarantena salvato in configurazione: ") << path << std::endl;
372 } catch (const std::exception& e) {
373 std::cerr << "❌ " << _("Errore durante la scrittura della configurazione: ") << e.what() << std::endl;
374 }
375}

References _, getUserConfigDir(), and persistQuarantinePath().

Referenced by persistQuarantinePath(), and Backend::setQuarantinePath().

◆ read_cvd_header()

bool read_cvd_header ( const std::string & path,
DbInfo & out )
static

Definition at line 159 of file Backend.cpp.

160{
161 std::ifstream f(path, std::ios::binary);
162 if (!f.is_open()) return false;
163
164 std::string line;
165 if (!std::getline(f, line)) return false;
166
167
168 std::vector<std::string> toks;
169 {
170 std::stringstream ss(line);
171 std::string seg;
172 while (std::getline(ss, seg, ':')) {
173 auto l = seg.find_first_not_of(" \t\r\n");
174 auto r = seg.find_last_not_of(" \t\r\n");
175 if (l == std::string::npos) toks.push_back("");
176 else toks.push_back(seg.substr(l, r - l + 1));
177 }
178 }
179
180 int nameIdx = -1;
181 for (int i = 0; i < (int)toks.size(); ++i) {
182 if (toks[i].find(".cvd") != std::string::npos ||
183 toks[i].find(".cld") != std::string::npos) {
184 nameIdx = i;
185 break;
186 }
187 }
188 if (nameIdx < 0) return false;
189
190 out.file = fs::path(path).filename().string();
191
192 // Versione = primo intero dopo nome file
193 for (int i = nameIdx + 1; i < (int)toks.size(); ++i) {
194 try {
195 long long v = std::stoll(toks[i]);
196 if (v > 0) { out.version = v; break; }
197 } catch (...) {}
198 }
199
200 for (int i = nameIdx + 1; i < (int)toks.size(); ++i) {
201 const std::string& t = toks[i];
202 if (std::all_of(t.begin(), t.end(), ::isdigit)) {
203 if (t.size() >= 10 && t.size() <= 13) {
204 try {
205 long long e = std::stoll(t);
206 if (t.size() > 10) e /= 1000;
207 if (e > 631152000LL && e < 4102444800LL) {
208 out.epoch = e;
209 break;
210 }
211 } catch (...) {}
212 }
213 }
214 }
215
216
217 if (out.epoch < 0) {
218 try {
219 auto ft = fs::last_write_time(path);
220 out.epoch = (long long)filetime_to_time_t(ft);
221 } catch (...) {}
222 }
223
224 return (out.version > 0);
225}
static std::time_t filetime_to_time_t(fs::file_time_type ft)
Definition Backend.cpp:149
long long version
Definition Backend.cpp:144
long long epoch
Definition Backend.cpp:145
std::string file
Definition Backend.cpp:143

References DbInfo::epoch, DbInfo::file, filetime_to_time_t(), read_cvd_header(), and DbInfo::version.

Referenced by read_cvd_header().

◆ read_ports_from_conf()

std::pair< int, int > read_ports_from_conf ( )

Definition at line 288 of file Backend.cpp.

289{
290 constexpr int default_http_port = 81;
291 constexpr int default_https_port = 444;
292
293 std::ifstream f("/etc/BastionGuard/webports.conf");
294 if (!f.is_open())
295 return {default_http_port, default_https_port};
296
297 int http_port = default_http_port;
298 int https_port = default_https_port;
299 if ((f >> http_port >> https_port) &&
300 http_port > 0 && http_port < 65536 &&
301 https_port > 0 && https_port < 65536) {
302 return {http_port, https_port};
303 }
304
305 return {default_http_port, default_https_port};
306}

References read_ports_from_conf().

Referenced by Backend::Backend(), and read_ports_from_conf().

◆ restart_clamd()

void restart_clamd ( )
static

Definition at line 308 of file Backend.cpp.

308 {
309 if ((bg_process::run({"/usr/libexec/bastionguard/bastionguard-service", "--system", "is-active", "clamav-daemon.service"}).exit_code) == 0) {
310 (bg_process::run({"pkexec", "/usr/libexec/bastionguard/bastionguard-service", "--system", "restart", "clamav-daemon.service"}).exit_code);
311 std::cout << _("✔ Riavviato clamav-daemon\n");
312 } else if ((bg_process::run({"/usr/libexec/bastionguard/bastionguard-service", "--system", "is-active", "clamd.service"}).exit_code) == 0) {
313 (bg_process::run({"pkexec", "/usr/libexec/bastionguard/bastionguard-service", "--system", "restart", "clamd.service"}).exit_code);
314 std::cout << _("✔ Riavviato clamd\n");
315 } else {
316 std::cerr << _("⚠ Nessun servizio clamd/clamav-daemon trovato\n");
317 }
318}

References _, bg_process::Result::exit_code, restart_clamd(), and bg_process::run().

Referenced by install_to_system_data(), and restart_clamd().

◆ run_phishing_updater_script()

bool run_phishing_updater_script ( const std::string & staging_dir)
static

Definition at line 1005 of file Backend.cpp.

1005 {
1006 const std::string helper =
1007 "/usr/share/BastionGuard/data/scripts/BastionGuard-phishing-updater.sh";
1008
1009 if (!std::filesystem::exists(helper)) {
1010 std::cerr << _("[Phishing] Helper non trovato: ") << helper << "\n";
1011 return false;
1012 }
1013
1014 // No shell and no passwordless sudo rule: pkexec performs the explicit
1015 // administrator authorization, while the staging directory is passed as
1016 // one opaque argv element.
1017 const pid_t pid = ::fork();
1018 if (pid < 0) {
1019 std::cerr << _("[Phishing] fork() fallita per helper privilegiato.\n");
1020 return false;
1021 }
1022
1023 if (pid == 0) {
1024 const char* argv[] = {
1025 "pkexec", helper.c_str(), staging_dir.c_str(), nullptr
1026 };
1027 ::execvp("pkexec", const_cast<char* const*>(argv));
1028 _exit(127);
1029 }
1030
1031 int status = 0;
1032 if (::waitpid(pid, &status, 0) < 0) return false;
1033 return WIFEXITED(status) && WEXITSTATUS(status) == 0;
1034}

References _, and run_phishing_updater_script().

Referenced by run_phishing_updater_script(), and Backend::updatePhishLists().

◆ trim()

std::string trim ( const std::string & s)
inlinestatic

Definition at line 112 of file Backend.cpp.

113{
114 size_t start = s.find_first_not_of(" \t\r\n");
115 if (start == std::string::npos) return "";
116
117 size_t end = s.find_last_not_of(" \t\r\n");
118 return s.substr(start, end - start + 1);
119}

References trim().

Referenced by fill_ext_set(), Backend::getSambaDirs(), load_allowlist(), load_config(), load_samba_dirs(), Backend::saveSambaConfig(), Backend::scanSambaDir(), split_semicolon_list(), trim(), trim(), trim(), trim(), and Backend::updatePhishLists().

◆ write_cb()

size_t write_cb ( void * c,
size_t s,
size_t n,
std::string * o )
static

Definition at line 2799 of file Backend.cpp.

2799 {
2800 o->append((char*)c, s * n);
2801 return s * n;
2802}

References write_cb().

Referenced by write_cb().

◆ xor_crypt()

std::string xor_crypt ( const std::string & input)
static

Definition at line 96 of file Backend.cpp.

96 {
97 std::string out = input;
98 for (size_t i = 0; i < input.size(); ++i)
99 out[i] = input[i] ^ SMB_KEY[i % SMB_KEY.size()];
100 return out;
101}
static const std::string SMB_KEY
Definition Backend.cpp:94

References SMB_KEY, and xor_crypt().

Referenced by decrypt_pass(), encrypt_pass(), and xor_crypt().

Variable Documentation

◆ antiphish_signal_

sigc::signal<void(const std::string&)> antiphish_signal_

Definition at line 1627 of file Backend.cpp.

Referenced by Backend::checkUrl(), and Backend::signal_antiphish_event().

◆ CLAMONACC_SERVICES

const char* CLAMONACC_SERVICES[]
static
Initial value:
= {
"clamav-clamonacc.service",
"clamonacc.service"
}

Definition at line 407 of file Backend.cpp.

Referenced by findClamonaccService(), Backend::getClamonaccLogs(), Backend::getOnAccessEvents(), and Backend::isClamonaccActive().

◆ quarantinePath

std::string quarantinePath = Glib::get_home_dir() + "/.local/share/BastionGuard/quarantine"
static

◆ SMB_KEY

const std::string SMB_KEY = "BastionGuard0101SecretKey"
static

Definition at line 94 of file Backend.cpp.

Referenced by xor_crypt().