-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfunctions.cpp
More file actions
448 lines (415 loc) · 15.8 KB
/
functions.cpp
File metadata and controls
448 lines (415 loc) · 15.8 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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
#include <iostream>
#include <array>
#include <filesystem>
#include <fstream>
#include <cstdio>
#include <memory>
#include <stdexcept>
#include <string>
#include <boost/program_options.hpp>
#include <mysql/mysql.h>
#include <mysql/mysqld_error.h>
#include <tuple>
#include <ctime>
#include <sstream>
#include <vector>
#include <regex>
/**
* Split String by delimiter
*
* @param string "string_to_split", string "delimiter"
* @return vector of strings
*/
std::vector<std::string> split(std::string s, std::string delimiter) {
size_t pos_start = 0, pos_end, delim_len = delimiter.length();
std::string token;
std::vector<std::string> res;
while ((pos_end = s.find(delimiter, pos_start)) != std::string::npos) {
token = s.substr (pos_start, pos_end - pos_start);
pos_start = pos_end + delim_len;
res.push_back (token);
}
res.push_back (s.substr (pos_start));
return res;
}
/**
* Execute system command and returns output
*
* @param Command
* @return string output
*/
std::string exec(const char* cmd) {
std::array<char, 128> buffer;
std::string result;
std::unique_ptr<FILE, decltype(&pclose)> pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (fgets(buffer.data(), static_cast<int>(buffer.size()), pipe.get()) != nullptr) {
result += buffer.data();
}
return result;
}
struct SQLConnection {
std::string server, user, password, database;
SQLConnection(std::string server, std::string user, std::string password, std::string database)
{
this->server = server;
this->user = user;
this->password = password;
this->database = database;
}
};
/**
* @brief
* Will try to connect to SQL, return a tuple, first value will be true if connection was a success
*
* @param mysql_details Details to connect ot SQL db
* @return std::tuple<bool, MYSQL *>
*/
std::tuple<bool, MYSQL *> sqlConnectionSetup(struct SQLConnection mysql_details) {
// there are multiple ways to return multiple values, here we use a tuple
MYSQL *connection = mysql_init(NULL); // mysql instance
bool success = true;
// connect database
// c_str -> converts std::string to char
if (!mysql_real_connect(connection, mysql_details.server.c_str(), mysql_details.user.c_str(), mysql_details.password.c_str(), mysql_details.database.c_str(), 0, NULL, 0)) {
success = false;
std::cout << "Connection Error: " << mysql_error(connection) << std::endl;
}
return std::make_tuple(success, connection);
}
/**
* @brief
* Execute a SQL query, will return a tuple, first value will be true if success
*
* @param connection SQL connection
* @param query SQL query
* @return result struct with success and res (result)
*/
auto execSQLQuery(MYSQL *connection, std::string query) {
// instead of returning a tuple, you could return a struct instead
struct result {
bool success;
MYSQL_RES *res;
};
bool success = true;
// send query to db
if (mysql_query(connection, query.c_str())) {
std::cout << "MySQL Query Error: " << mysql_error(connection) << std::endl;
success = false;
}
return result{success, mysql_use_result(connection)};
}
/**
* Replaces all occurrences of a string with another string
* @param string subject, string search, string replace
* @return string replaced_string
*/
void replaceAll (std::string& str, const std::string& from, const std::string& to) {
if(from.empty()) {
return;
}
size_t start_pos = 0;
while((start_pos = str.find(from, start_pos)) != std::string::npos) {
str.replace(start_pos, from.length(), to);
start_pos += to.length(); // In case 'to' contains 'from', like replacing 'x' with 'yx'
}
}
/**
* read each line from a file and save the line into a variable if the line matches dns-nameservers
* @param file
* @return std::string nameserver
*/
std::string get_nameserver (std::string file, std::string regex, std::string delimiter = "false") {
std::string nameserver;
if (!std::filesystem::exists(file)) {
std::cerr<<std::endl<<"Error! "<<file<<" does not exists!" <<std::endl<<std::endl;
return "Error";
}
std::string line;
std::ifstream dnsfile (file);
if (!dnsfile.is_open()) {
std::cerr<<std::endl<<"Error! Could not open "<<file<<std::endl<<std::endl;
return "Error";
}
std::regex dnsRegex("(^"+regex+"(.*)$)");
while (getline(dnsfile,line)) {
if (std::regex_match(line, dnsRegex)) {
std::vector<std::string> server = split(line, delimiter);
for(int i = 0; i < server.size(); i++) {
int already_listed = nameserver.find(server[i]);
if (already_listed == std::string::npos and (!regex_match(server[i], dnsRegex) and server[i] != " ")) {
nameserver += server[i]+" ";
}
}
}
}
return nameserver;
}
/**
* read ech line from a file and save the line into a variable if the line matches dns-search
* @param file
* @return std::string dns_domains
*/
std::string get_dns_domains (std::string file, std::string regex, std::string delimiter = "false") {
std::string dns_domains;
if (!std::filesystem::exists(file)) {
std::cerr<<std::endl<<"Error! "<<file<<" does not exists!" <<std::endl<<std::endl;
return "Error";
}
std::string line;
std::ifstream dnsfile (file);
if (!dnsfile.is_open()) {
std::cerr<<std::endl<<"Error! Could not open "<<file<<std::endl<<std::endl;
return "Error";
}
std::regex domainRegex("(^"+regex+"(.*)$)");
while (getline(dnsfile,line)) {
if (std::regex_match(line, domainRegex)) {
std::vector<std::string> domain = split(line, delimiter);
for(int i = 0; i < domain.size(); i++) {
int already_listed = dns_domains.find(domain[i]);
if (already_listed == std::string::npos and (!regex_match(domain[i], domainRegex) and domain[i] != " ")) {
dns_domains += domain[i]+" ";
}
}
}
}
return dns_domains;
}
/**
* Test if program is executed manualy by query the database for a valid entry.
* The entry is made by the admin-interface when you press the "Submit" button
*
* @param Module-Name (hostname, packet_capture etc)
* @return bool true/false
*/
bool check_auth (const std::string module) {
int timestamp_diff;
bool auth_ok = false;
try {
boost::program_options::options_description configfile{"File"};
configfile.add_options()
("use_timestamp", boost::program_options::value<std::string>(), "Use timestamp")
("timestamp_diff", boost::program_options::value<int>(), "timestamp_diff")
("hostname", boost::program_options::value<std::string>(), "Hostname")
("port", boost::program_options::value<int>(), "Port")
("dbname", boost::program_options::value<std::string>(), "Database Name")
("username", boost::program_options::value<std::string>(), "Username")
("password", boost::program_options::value<std::string>(), "Password");
boost::program_options::variables_map chk_auth;
if (!std::filesystem::exists("/home/hannes/Downloads/c++/freepbx.conf")) {
std::cerr<<std::endl<<"Error! Could not open file /home/hannes/Downloads/c++/freepbx.conf"<<std::endl<<std::endl;
return false;
}
std::ifstream conffile ("/home/hannes/Downloads/c++/freepbx.conf");
if (conffile) {
store(parse_config_file(conffile, configfile), chk_auth);
}
notify(chk_auth);
if (chk_auth["use_timestamp"].as<std::string>() == "yes") {
int timestamp_diff = chk_auth["timestamp_diff"].as<int>();
std::string hostname = chk_auth["hostname"].as<std::string>();
int port = chk_auth["port"].as<int>();
std::string dbname = chk_auth["dbname"].as<std::string>();
std::string username = chk_auth["username"].as<std::string>();
std::string password = chk_auth["password"].as<std::string>();
bool success;
MYSQL *con; // the connection
// MYSQL_RES *res; // the results
MYSQL_ROW row; // the results rows (array)
struct SQLConnection sqlDetails(hostname, username, password, dbname);
// connect to the mysql database
std::tie(success, con) = sqlConnectionSetup(sqlDetails);
if (!success) {
std::cerr<<std::endl<<"Error! Could not connect to database!"<<std::endl<<std::endl;
return false;
}
// get the results from executing commands
auto result = execSQLQuery(con, "SELECT timestamp from systemadmin_logs WHERE module='"+module+"';");
if (!result.success) {
// handle any errors
std::cerr<<std::endl<<"Error! Could not query the database!"<<std::endl<<std::endl;
return false;
}
auto t = std::time(nullptr);
auto tm = *std::localtime(&t);
auto time_now = std::put_time(&tm, "%Y-%m-%d %H-%M-%S");
int timestamp_now = std::mktime(std::localtime(&t));
while ((row = mysql_fetch_row(result.res)) != NULL) {
int timestamp_query = atoi(row[0]);
if (timestamp_now - timestamp_query <= timestamp_diff) {
auth_ok = true;
}
}
}
else {
auth_ok = true;
}
}
catch (const boost::program_options::error &ex) {
std::cerr << ex.what() << '\n';
}
return auth_ok;
}
/**
* Validate ipv4/ipv6 addresses
*
* @param ipv4/ipv6 addresses, delimiter
* @return bool true/false
*/
bool validate_ip_address (std::string addresses, std::string delimiter) {
bool valid_address = true;
std::regex ipv4Regex(R"(^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$)");
std::regex ipv6Regex(R"(^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$)");
std::vector<std::string> address = split(addresses, delimiter);
for(int i = 0; i < address.size(); i++) {
if (!std::regex_match(address[i], ipv4Regex) and !std::regex_match(address[i], ipv6Regex)) {
valid_address = false;
}
}
return valid_address;
}
/**
* Check if adress is a ipv4 address
*
* @param ipv4 address
* @return bool true/false
*/
bool is_ipv4_address (std::string address) {
bool ipv4_address = false;
std::regex ipv4Regex(R"(^((25[0-5]|(2[0-4]|1\d|[1-9]|)\d)(\.(?!$)|$)){4}$)");
if (std::regex_match(address, ipv4Regex)) {
ipv4_address = true;
}
return ipv4_address;
}
/**
* Check if adress is a ipv6 address
*
* @param ipv6 address
* @return bool true/false
*/
bool is_ipv6_address (std::string address) {
bool ipv6_address = false;
std::regex ipv6Regex(R"(^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$)");
if (std::regex_match(address, ipv6Regex)) {
ipv6_address = true;
}
return ipv6_address;
}
/**
* Checks whether interface is managed by ifupdown
*
* @param Name of the interface
* @return bool true/false
*/
/*
bool check_ifupdown (const std::string interface) {
bool ifupdown = false;
if(!std::filesystem::exists("/sys/class/net/"+interface)) {
std::cerr<<std::endl<<"Error! Could not open interface file! Is "<<interface<<" a valid network interface?"<<std::endl<<std::endl;
std::abort();
}
else if (std::filesystem::exists("/run/network/ifstate") && !(std::filesystem::file_size("/run/network/ifstate") == 0)) {
std::ifstream ifstate;
ifstate.open("/run/network/ifstate");
if(ifstate.good()) {
std::string line_ifstate;
while(getline(ifstate, line_ifstate)) {
std::size_t found = line_ifstate.find(interface);
if (found!=std::string::npos) {
ifupdown = true;
break;
}
}
}
}
return ifupdown;
}*/
/**
* Function checks whether the interface is managed by netplan.io
*
* @param Name of the interface
* @return bool true/false
*/
/*
bool check_netplan (const std::string interface) {
bool netplan = false;
if(!std::filesystem::exists("/sys/class/net/"+interface)) {
std::cerr<<std::endl<<"Error! Could not open interface file! Is "<<interface<<" a valid network interface?"<<std::endl<<std::endl;
std::abort();
}
else if (std::filesystem::exists("/etc/netplan")) {
netplan = true;
}
return netplan;
}*/
/**
* Function checks whether the interface is managed by NetworkManager
*
* @param Name of the interface
* @return bool true/false
*/
/*
bool check_networkManager (const std::string interface) {
bool nm = false;
if(!std::filesystem::exists("/sys/class/net/"+interface)) {
std::cerr<<std::endl<<"Error! Could not open interface file! Is "<<interface<<" a valid network interface?"<<std::endl<<std::endl;
std::abort();
}
else {
int check_nm_process = system("/usr/bin/systemctl status NetworkManager >> /dev/null 2>&1");
if (check_nm_process == 0) {
if (check_ifupdown(interface) || check_netplan(interface)) {
nm = false;
}
else {
nm = true;
//}
}
else {
nm = false;
}
}
return nm;
}
*/
/**
* Function checks whether the interface is managed by systemd
*
* @param Name of the interface
* @return bool true/false
*/
/*bool check_systemd_networkd (const std::string interface) {
bool systemd = false;
if(!std::filesystem::exists("/sys/class/net/"+interface)) {
std::cerr<<std::endl<<"Error! Could not open interface file! Is "<<interface<<" a valid network interface?"<<std::endl<<std::endl;
std::abort();
}
else {
if (check_netplan(interface)) {
systemd = false;
}
else {
int check_systemd_process = system("/usr/bin/systemctl status systemd-networkd >> /dev/null 2>&1");
if (check_systemd_process == 0) {
systemd = true;
}
else {
systemd = false;
}
}
//}
return systemd;
}*/
/*bool check_resolvconf () {
int check_resolvconf = std::system("/usr/bin/dpkg-query -W --showformat='${Status}\n' resolvconf | grep \"install ok installed\" >> /dev/null 2>&1");
if(check_resolvconf == 0) {
return true;
}
else {
return false;
}
}*/