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 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627
|
/*
* This file is part of PowerDNS or weakforced.
* Copyright -- PowerDNS.COM B.V. and its contributors
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of version 3 of the GNU General Public License as
* published by the Free Software Foundation.
*
* In addition, for the avoidance of any doubt, permission is granted to
* link this program with OpenSSL and to (re)distribute the binaries
* produced as the result of such linking.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
#include "wforce.hh"
#include "sstuff.hh"
#include "json11.hpp"
#include "ext/incbin/incbin.h"
#include "dolog.hh"
#include <chrono>
#include <thread>
#include <sstream>
#include "namespaces.hh"
#include <ctime>
#include <sys/resource.h>
#include "base64.hh"
#include "blackwhitelist.hh"
#include "twmap-wrapper.hh"
#include "customfunc.hh"
#include "perf-stats.hh"
#include "luastate.hh"
#include "login_tuple.hh"
#include "webhook.hh"
#include "boost/date_time/posix_time/posix_time.hpp"
#include "boost/date_time/gregorian/gregorian.hpp"
#include "boost/algorithm/string.hpp"
#include "boost/regex.hpp"
#include "wforce-prometheus.hh"
#include "wforce-sibling.hh"
#include "wforce-replication.hh"
using std::thread;
using namespace boost::posix_time;
using namespace boost::gregorian;
GlobalStateHolder<vector<shared_ptr<Sibling>>> g_report_sinks;
GlobalStateHolder<std::map<std::string, std::pair<std::shared_ptr<std::atomic<unsigned int>>, vector<shared_ptr<Sibling>>>>> g_named_report_sinks;
bool g_builtin_bl_enabled = true;
bool g_builtin_wl_enabled = true;
static time_t start = time(0);
static inline std::string getIPJA3(const std::string& ip, const std::string& ja3)
{
return ip+"::"+ja3;
}
static inline void setErrorCodeAndReason(drogon::HttpStatusCode code, const std::string& reason, const drogon::HttpResponsePtr& resp)
{
resp->setStatusCode(code);
json11::Json j = json11::Json::object {
{ "status", "failure" },
{ "reason", reason },
};
resp->setBody(j.dump());
}
static int uptimeOfProcess()
{
return time(0) - start;
}
void reportLog(const LoginTuple& lt)
{
if (g_verbose) {
std::ostringstream os;
os << "reportLog: ";
os << "remote=\"" << lt.remote.toString() << "\" ";
os << "login=\"" << lt.login << "\" ";
os << "success=\"" << lt.success << "\" ";
os << "policy_reject=\"" << lt.policy_reject << "\" ";
os << "pwhash=\"" << std::hex << std::uppercase << lt.pwhash << "\" ";
os << "protocol=\"" << lt.protocol << "\" ";
os << "device_id=\"" << lt.device_id << "\" ";
os << "session_id=\"" << lt.session_id << "\" ";
os << DeviceAttrsToString(lt);
os << LtAttrsToString(lt);
infolog(os.str().c_str());
}
}
bool g_allowlog_verbose = false;
void allowLog(int retval, const std::string& msg, const LoginTuple& lt,
const std::vector<pair<std::string, std::string>>& kvs)
{
std::ostringstream os;
if ((retval != 0) || g_allowlog_verbose) {
os << "allowLog " << msg << ": ";
os << "allow=\"" << retval << "\" ";
os << "remote=\"" << lt.remote.toString() << "\" ";
os << "login=\"" << lt.login << "\" ";
os << "protocol=\"" << lt.protocol << "\" ";
os << "device_id=\"" << lt.device_id << "\" ";
os << "session_id=\"" << lt.session_id << "\" ";
os << DeviceAttrsToString(lt);
os << LtAttrsToString(lt);
os << "rattrs={";
for (const auto& i : kvs) {
os << i.first << "=" << "\"" << i.second << "\"" << " ";
}
os << "}";
}
if ((retval == 0) && (!g_allowlog_verbose)) {
// do not log if retval == 0 and not verbose
}
else if ((retval == 0) && g_allowlog_verbose) {
infolog(os.str().c_str());
}
else {
// only log at notice if login was rejected or tarpitted
noticelog(os.str().c_str());
}
}
void addBLWLEntries(const std::vector<BlackWhiteListEntry>& blv, const char* key_name, json11::Json::array& my_entries)
{
for (auto i = blv.begin(); i != blv.end(); ++i) {
json11::Json my_entry = json11::Json::object{
{key_name, (std::string) i->key},
{"expiration", (std::string) boost::posix_time::to_simple_string(i->expiration)},
{"reason", (std::string) i->reason}
};
my_entries.push_back(my_entry);
}
}
bool canonicalizeLogin(std::string& login, const drogon::HttpResponsePtr& resp)
{
bool retval = true;
try {
// canonicalize the login - e.g. turn "foo" into "foo@foobar.com" and bar into "bar@barfoo.com"
login = g_luamultip->canonicalize(login);
}
catch (LuaContext::ExecutionErrorException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua canonicalize function exception: %s", e.what());
retval = false;
}
catch (...) {
setErrorCodeAndReason(drogon::k500InternalServerError, "unknown", resp);
retval = false;
}
return retval;
}
static std::mutex dump_mutex;
void parseDumpEntriesCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
if (msg["dump_host"].is_null() ||
msg["dump_port"].is_null()) {
throw WforceException("One of mandatory parameters [dump_host, dump_port] is missing");
}
string myip = msg["dump_host"].string_value();
int myport = msg["dump_port"].int_value();
ComboAddress replication_ca(myip, myport);
std::unique_lock<std::mutex> lock(dump_mutex, std::defer_lock);
if (lock.try_lock()) {
thread t(dumpEntriesThread, replication_ca, std::move(lock));
t.detach();
}
else {
setErrorCodeAndReason(drogon::k503ServiceUnavailable, "A DB dump is already in progress", resp);
}
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
incCommandStat("dumpEntries");
incPrometheusCommandMetric("dumpEntries");
}
void parseSyncCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
if (msg["replication_host"].is_null() ||
msg["replication_port"].is_null() ||
msg["callback_url"].is_null() ||
msg["callback_auth_pw"].is_null()) {
throw WforceException(
"One of mandatory parameters [replication_host, replication_port, callback_url, callback_auth_pw] is missing");
}
string myip = msg["replication_host"].string_value();
int myport = msg["replication_port"].int_value();
ComboAddress replication_ca(myip, myport);
std::string callback_url = msg["callback_url"].string_value();
std::string callback_pw = msg["callback_auth_pw"].string_value();
std::string encryption_key;
if (!msg["encryption_key"].is_null()) {
encryption_key = msg["encryption_key"].string_value();
}
else {
encryption_key = g_replication.getEncryptionKey();
}
thread t(syncDBThread, replication_ca, callback_url, callback_pw, encryption_key);
t.detach();
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
incCommandStat("syncDBs");
incPrometheusCommandMetric("syncDBs");
}
void parseAddSiblingCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
if (msg["sibling_host"].is_null() ||
msg["sibling_port"].is_null()) {
throw WforceException("One of mandatory parameters [sibling_host, sibling_port] is missing");
}
std::string sibling_host = msg["sibling_host"].string_value();
int sibling_port = msg["sibling_port"].int_value();
bool has_encryption_key = false;
std::string encryption_key;
if (!msg["encryption_key"].is_null()) {
has_encryption_key = true;
encryption_key = msg["encryption_key"].string_value();
}
Sibling::Protocol proto = Sibling::Protocol::UDP;
if (!msg["sibling_protocol"].is_null()) {
proto = Sibling::stringToProtocol(msg["sibling_protocol"].string_value());
}
if (proto == Sibling::Protocol::NONE) {
throw WforceException(std::string("Invalid sibling_protocol: ") + msg["sibling_protocol"].string_value());
}
std::string error_msg;
if (!has_encryption_key) {
if (!addSibling(sibling_host, sibling_port, proto, g_replication.getSiblings(), error_msg)) {
throw WforceException(error_msg);
}
}
else {
if (!addSiblingWithKey(sibling_host, sibling_port, proto, g_replication.getSiblings(), error_msg,
encryption_key)) {
throw WforceException(error_msg);
}
}
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
incCommandStat("addSibling");
incPrometheusCommandMetric("addSibling");
}
void parseRemoveSiblingCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
if (msg["sibling_host"].is_null() ||
msg["sibling_port"].is_null()) {
throw WforceException("One of mandatory parameters [sibling_host, sibling_port] is missing");
}
std::string sibling_host = msg["sibling_host"].string_value();
int sibling_port = msg["sibling_port"].int_value();
std::string error_msg;
if (!removeSibling(sibling_host, sibling_port, g_replication.getSiblings(), error_msg)) {
throw WforceException(error_msg);
}
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
incCommandStat("removeSibling");
incPrometheusCommandMetric("removeSibling");
}
void parseSetSiblingsCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
std::vector<std::pair<int, std::vector<std::pair<int, std::string>>>> new_siblings;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
if (msg["siblings"].is_null() || !msg["siblings"].is_array()) {
throw WforceException("Mandatory parameter [siblings] is missing or is not an array");
}
auto siblings = msg["siblings"].array_items();
for (auto& i : siblings) {
if (i["sibling_host"].is_null() || i["sibling_port"].is_null()) {
throw WforceException("Mandatory parameter(s) [sibling_host, sibling_port] are missing");
}
std::string sibling_host = i["sibling_host"].string_value();
int sibling_port = i["sibling_port"].int_value();
std::string encryption_key;
if (!i["encryption_key"].is_null()) {
encryption_key = i["encryption_key"].string_value();
}
else {
encryption_key = Base64Encode(g_replication.getEncryptionKey());
}
Sibling::Protocol proto = Sibling::Protocol::UDP;
if (!i["sibling_protocol"].is_null()) {
proto = Sibling::stringToProtocol(i["sibling_protocol"].string_value());
}
if (proto == Sibling::Protocol::NONE) {
throw WforceException(std::string("Invalid sibling_protocol: ") + msg["sibling_protocol"].string_value());
}
new_siblings.emplace_back(std::pair<int, std::vector<std::pair<int, std::string>>>{0, {{0, createSiblingAddress(
sibling_host, sibling_port, proto)}, {1, encryption_key}}});
}
std::string error_msg;
if (!setSiblingsWithKey(new_siblings, g_replication.getSiblings(), error_msg)) {
throw WforceException(error_msg);
}
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
incCommandStat("setSiblings");
incPrometheusCommandMetric("setSiblings");
}
void parseAddDelBLWLEntryCmd(const drogon::HttpRequestPtr& req,
const drogon::HttpResponsePtr& resp,
bool addCmd, bool blacklist)
{
json11::Json msg;
string err;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
bool haveIP = false;
bool haveLogin = false;
bool haveJA3 = false;
bool haveNetmask = false;
unsigned int bl_seconds = 0;
std::string bl_reason;
std::string en_ja3;
std::string en_login;
ComboAddress en_ca;
Netmask en_nm;
try {
if (!msg["ip"].is_null()) {
string myip = msg["ip"].string_value();
en_ca = ComboAddress(myip);
en_nm = Netmask(myip);
haveIP = true;
}
if (!msg["netmask"].is_null()) {
string mynm = msg["netmask"].string_value();
en_nm = Netmask(mynm);
haveNetmask = true;
}
if (!msg["login"].is_null()) {
en_login = msg["login"].string_value();
if (!canonicalizeLogin(en_login, resp))
return;
haveLogin = true;
}
if (!msg["ja3"].is_null()) {
en_ja3 = msg["ja3"].string_value();
haveJA3 = true;
}
if (!haveJA3 && !haveLogin && !haveIP && !haveNetmask) {
throw std::runtime_error("Must provide at least one of login, ip, netmask or ja3");
}
if (addCmd) {
if (!msg["expire_secs"].is_null()) {
bl_seconds = msg["expire_secs"].int_value();
}
else {
throw std::runtime_error("Missing mandatory expire_secs field");
}
if (!msg["reason"].is_null()) {
bl_reason = msg["reason"].string_value();
}
else {
throw std::runtime_error("Missing mandatory reason field");
}
}
if (haveLogin && haveJA3) {
throw std::runtime_error("login and ja3 are mutually exclusive parameters");
}
if (haveLogin && haveIP) {
if (addCmd) {
if (blacklist)
g_bl_db.addEntry(en_ca, en_login, bl_seconds, bl_reason);
else
g_wl_db.addEntry(en_ca, en_login, bl_seconds, bl_reason);
}
else {
if (blacklist)
g_bl_db.deleteEntry(en_ca, en_login);
else
g_wl_db.deleteEntry(en_ca, en_login);
}
}
else if (haveJA3 && haveIP) {
if (addCmd) {
if (blacklist)
g_bl_db.addIPJA3Entry(en_ca, en_ja3, bl_seconds, bl_reason);
else
g_wl_db.addIPJA3Entry(en_ca, en_ja3, bl_seconds, bl_reason);
}
else {
if (blacklist)
g_bl_db.deleteIPJA3Entry(en_ca, en_ja3);
else
g_wl_db.deleteIPJA3Entry(en_ca, en_ja3);
}
}
else if (haveLogin) {
if (addCmd) {
if (blacklist)
g_bl_db.addEntry(en_login, bl_seconds, bl_reason);
else
g_wl_db.addEntry(en_login, bl_seconds, bl_reason);
}
else {
if (blacklist)
g_bl_db.deleteEntry(en_login);
else
g_wl_db.deleteEntry(en_login);
}
}
else if (haveJA3) {
if (addCmd) {
if (blacklist)
g_bl_db.addJA3Entry(en_ja3, bl_seconds, bl_reason);
else
g_wl_db.addJA3Entry(en_ja3, bl_seconds, bl_reason);
}
else {
if (blacklist)
g_bl_db.deleteJA3Entry(en_ja3);
else
g_wl_db.deleteJA3Entry(en_ja3);
}
}
else if (haveIP || haveNetmask) {
if (addCmd) {
if (blacklist)
g_bl_db.addEntry(en_nm, bl_seconds, bl_reason);
else
g_wl_db.addEntry(en_nm, bl_seconds, bl_reason);
}
else {
if (blacklist)
g_bl_db.deleteEntry(en_nm);
else
g_wl_db.deleteEntry(en_nm);
}
}
}
catch (std::runtime_error& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
}
catch (...) {
resp->setStatusCode(drogon::k500InternalServerError);
resp->setBody(R"({"status":"failure"})");
}
}
if (resp->getStatusCode() == drogon::k200OK)
resp->setBody(R"({"status":"ok"})");
}
void parseAddBLEntryCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseAddDelBLWLEntryCmd(req, resp, true, true);
incCommandStat("addBLEntry");
incPrometheusCommandMetric("addBLEntry");
}
void parseDelBLEntryCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseAddDelBLWLEntryCmd(req, resp, false, true);
incCommandStat("delBLEntry");
incPrometheusCommandMetric("delBLEntry");
}
void parseAddWLEntryCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseAddDelBLWLEntryCmd(req, resp, true, false);
incCommandStat("addWLEntry");
incPrometheusCommandMetric("addWLEntry");
}
void parseDelWLEntryCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseAddDelBLWLEntryCmd(req, resp, false, false);
incCommandStat("delWLEntry");
incPrometheusCommandMetric("delWLEntry");
}
void parseResetCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
bool haveIP = false;
bool haveLogin = false;
bool haveJA3 = false;
std::string en_type, en_login, en_ja3;
ComboAddress en_ca;
if (!msg["ip"].is_null()) {
en_ca = ComboAddress(msg["ip"].string_value());
haveIP = true;
}
if (!msg["login"].is_null()) {
en_login = msg["login"].string_value();
// canonicalize the login - e.g. turn "foo" into "foo@foobar.com" and bar into "bar@barfoo.com"
if (!canonicalizeLogin(en_login, resp))
return;
haveLogin = true;
}
if (!msg["ja3"].is_null()) {
en_ja3 = msg["ja3"].string_value();
haveJA3 = true;
}
if (haveLogin && haveJA3) {
throw std::runtime_error("login and ja3 are mutually exclusive parameters");
}
if (haveLogin && haveIP) {
en_type = "ip:login";
g_bl_db.deleteEntry(en_ca, en_login);
}
else if (haveJA3 && haveIP) {
en_type = "ip:ja3";
g_bl_db.deleteIPJA3Entry(en_ca, en_ja3);
}
else if (haveLogin) {
en_type = "login";
g_bl_db.deleteEntry(en_login);
}
else if (haveJA3) {
en_type = "ja3";
g_bl_db.deleteJA3Entry(en_ja3);
}
else if (haveIP) {
en_type = "ip";
g_bl_db.deleteEntry(en_ca);
}
if (!haveLogin && !haveIP && !haveJA3) {
setErrorCodeAndReason(drogon::k400BadRequest, "No ip, login or ja3 field supplied", resp);
}
else {
bool reset_ret;
{
std::string login_or_ja3 = haveLogin ? en_login : en_ja3;
reset_ret = g_luamultip->reset(en_type, login_or_ja3, en_ca);
}
if (reset_ret) {
resp->setStatusCode(drogon::k200OK);
resp->setBody(R"({"status":"ok"})");
}
else {
setErrorCodeAndReason(drogon::k500InternalServerError, "reset function returned false", resp);
}
}
// generate webhook events
json11::Json jobj = json11::Json::object{{"login", en_login},
{"ip", en_ca.toString()},
{"ja3", en_ja3},
{"type", "wforce_reset"}};
for (const auto& h : g_webhook_db.getWebHooksForEvent("reset")) {
if (auto hs = h.lock()) {
g_webhook_runner.runHook("reset", hs, jobj);
}
}
}
catch (LuaContext::ExecutionErrorException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua reset function exception: %s", e.what());
}
catch (...) {
resp->setStatusCode(drogon::k500InternalServerError);
resp->setBody(R"({"status":"failure"})");
}
}
incCommandStat("reset");
incPrometheusCommandMetric("reset");
}
void parseReportCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
try {
LoginTuple lt;
lt.from_json(msg, g_ua_parser_p);
// canonicalize the login - e.g. turn "foo" into "foo@foobar.com" and bar into "bar@barfoo.com"
if (!canonicalizeLogin(lt.login, resp))
return;
lt.t = getDoubleTime(); // set the time
reportLog(lt);
g_stats.reports++;
{
g_luamultip->report(lt);
}
// If any normal or named report sinks are configured, send the report to one of them
sendReportSink(lt); // XXX - this is deprecated now in favour of NamedReportSinks
sendNamedReportSink(lt.serialize());
json11::Json msg = lt.to_json();
json11::Json::object jobj = msg.object_items();
jobj.insert(make_pair("type", "wforce_report"));
for (const auto& h : g_webhook_db.getWebHooksForEvent("report")) {
if (auto hs = h.lock())
g_webhook_runner.runHook("report", hs, jobj);
}
resp->setStatusCode(drogon::k200OK);
resp->setBody(R"({"status":"ok"})");
}
catch (LuaContext::ExecutionErrorException& e) {
resp->setStatusCode(drogon::k500InternalServerError);
std::stringstream ss;
try {
std::rethrow_if_nested(e);
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua function [%s] exception: %s", command, e.what());
}
catch (const std::exception& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.what(), resp);
errlog("Exception in command [%s] exception: %s", command, ne.what());
}
catch (const WforceException& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.reason, resp);
errlog("Exception in command [%s] exception: %s", command, ne.reason);
}
}
catch (const std::exception& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Exception in command [%s] exception: %s", command, e.what());
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
incCommandStat("report");
incPrometheusCommandMetric("report");
}
#define OX_PROTECT_NOTIFY 0
void genProtectHookData(const json11::Json& lt, const std::string& msg, json11::Json& ret_json)
{
json11::Json::object jobj;
double dtime = lt["t"].number_value();
unsigned int isecs = (int) dtime;
unsigned int iusecs = (dtime - isecs) * 1000000;
ptime t(date(1970, Jan, 01), seconds(isecs) + microsec(iusecs));
jobj.insert(std::make_pair("timestamp", to_iso_extended_string(t) + "Z"));
jobj.insert(std::make_pair("user", lt["login"].string_value()));
jobj.insert(std::make_pair("device", lt["device_id"].string_value()));
jobj.insert(std::make_pair("ip", lt["remote"].string_value()));
jobj.insert(std::make_pair("message", msg));
jobj.insert(std::make_pair("code", OX_PROTECT_NOTIFY));
jobj.insert(std::make_pair("application", "wforce"));
ret_json = json11::Json(std::move(jobj));
}
bool allow_filter(std::shared_ptr<const WebHook> hook, int status)
{
bool retval = false;
if (hook->hasConfigKey("allow_filter")) {
std::string filter = hook->getConfigKey("allow_filter");
if (((filter.find("reject") != string::npos) && (status < 0)) ||
(((filter.find("allow") != string::npos) && (status == 0))) ||
(((filter.find("tarpit") != string::npos) && (status > 0)))) {
retval = true;
vdebuglog("allow_filter: filter evaluates to true (allowing event)");
}
}
else
retval = true;
return retval;
}
void runAllowWebHook(const json11::Json& request, const json11::Json& response, int status)
{
json11::Json jobj = json11::Json::object{{"request", request},
{"response", response},
{"type", "wforce_allow"}};
for (const auto& h : g_webhook_db.getWebHooksForEvent("allow")) {
if (auto hs = h.lock()) {
json11::Json pj;
if (hs->hasConfigKey("ox-protect")) {
genProtectHookData(jobj["request"],
hs->getConfigKey("ox-protect"),
pj);
if (allow_filter(hs, status))
g_webhook_runner.runHook("allow", hs, pj);
}
else {
if (allow_filter(hs, status))
g_webhook_runner.runHook("allow", hs, jobj);
}
}
}
}
enum AllowReturnFields {
allowRetStatus = 0, allowRetMsg = 1, allowRetLogMsg = 2, allowRetAttrs = 3
};
const std::string ipPattern = "{ip}";
const std::string loginPattern = "{login}";
const std::string ja3Pattern = "{ja3}";
std::string substituteStrings(const std::string msg,
const ComboAddress& ca,
const std::string login,
const std::string ja3)
{
bool replace_ip = false;
bool replace_login = false;
bool replace_ja3 = false;
std::string new_msg;
if (msg.find(ipPattern) != std::string::npos)
replace_ip = true;
if (msg.find(loginPattern) != std::string::npos)
replace_login = true;
if (msg.find(ja3Pattern) != std::string::npos)
replace_ja3 = true;
if (replace_ip || replace_login || replace_ja3)
// The maximum length of an IPv6 address string is 39 characters
new_msg.reserve(msg.length()+39+login.length()+ja3.length()); // This should prevent a realloc in the majority of cases
if (replace_ip)
new_msg = boost::algorithm::replace_all_copy(msg, ipPattern, ca.toString());
else
new_msg = msg;
if (replace_login)
boost::algorithm::replace_all(new_msg, loginPattern, login);
if (replace_ja3)
boost::algorithm::replace_all(new_msg, ja3Pattern, ja3);
return new_msg;
}
void parseAllowCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
std::vector<pair<std::string, std::string>> ret_attrs;
incCommandStat("allow");
incPrometheusCommandMetric("allow");
g_stats.allows++;
resp->setStatusCode(drogon::k200OK);
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
LoginTuple lt;
int status = -1;
std::string ret_msg;
try {
lt.from_json(msg, g_ua_parser_p);
lt.t = getDoubleTime();
}
catch (const std::exception& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Exception in command [%s] exception: %s", command, e.what());
return;
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
return;
}
if (!canonicalizeLogin(lt.login, resp)) {
return;
}
string ja3;
try {
ja3 = lt.attrs.at(g_ja3_attrname);
}
catch (const std::out_of_range& oor) {
vdebuglog("ja3 not found in attrs using name: %s", g_ja3_attrname, oor.what());
}
// check the built-in whitelists
bool whitelisted = false;
BlackWhiteListEntry wle;
if (g_builtin_wl_enabled) {
if (g_wl_db.getEntry(lt.remote, wle)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(wle.expiration)},
{"reason", wle.reason},
{"whitelisted", "1"},
{"key", "ip"}};
status = 0;
allowLog(status, std::string("whitelisted IP"), lt, log_attrs);
ret_msg = substituteStrings(g_wl_db.getIPRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
whitelisted = true;
}
else if (g_wl_db.getEntry(lt.login, wle)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(wle.expiration)},
{"reason", wle.reason},
{"whitelisted", "1"},
{"key", "login"}};
status = 0;
allowLog(status, std::string("whitelisted Login"), lt, log_attrs);
ret_msg = substituteStrings(g_wl_db.getLoginRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
whitelisted = true;
}
else if (!ja3.empty() && g_wl_db.getJA3Entry(ja3, wle)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(wle.expiration)},
{"reason", wle.reason},
{"whitelisted", "1"},
{"key", "ja3"}};
status = 0;
allowLog(status, std::string("whitelisted JA3"), lt, log_attrs);
ret_msg = substituteStrings(g_wl_db.getJA3RetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
whitelisted = true;
}
else if (g_wl_db.getEntry(lt.remote, lt.login, wle)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(wle.expiration)},
{"reason", wle.reason},
{"whitelisted", "1"},
{"key", "iplogin"}};
status = 0;
allowLog(status, std::string("whitelisted IPLogin"), lt, log_attrs);
ret_msg = substituteStrings(g_wl_db.getIPLoginRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
whitelisted = true;
}
else if (!ja3.empty() && g_wl_db.getIPJA3Entry(lt.remote, ja3, wle)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(wle.expiration)},
{"reason", wle.reason},
{"whitelisted", "1"},
{"key", "ipja3"}};
status = 0;
allowLog(status, std::string("whitelisted IPJA3"), lt, log_attrs);
ret_msg = substituteStrings(g_wl_db.getIPJA3RetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
whitelisted = true;
}
}
// next check the built-in blacklists
bool blacklisted = false;
BlackWhiteListEntry ble;
if (g_builtin_bl_enabled) {
if (g_bl_db.getEntry(lt.remote, ble)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(ble.expiration)},
{"reason", ble.reason},
{"blacklisted", "1"},
{"key", "ip"}};
allowLog(status, std::string("blacklisted IP"), lt, log_attrs);
ret_msg = substituteStrings(g_bl_db.getIPRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
blacklisted = true;
}
else if (g_bl_db.getEntry(lt.login, ble)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(ble.expiration)},
{"reason", ble.reason},
{"blacklisted", "1"},
{"key", "login"}};
allowLog(status, std::string("blacklisted Login"), lt, log_attrs);
ret_msg = substituteStrings(g_bl_db.getLoginRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
blacklisted = true;
}
else if (!ja3.empty() && g_bl_db.getJA3Entry(ja3, ble)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(ble.expiration)},
{"reason", ble.reason},
{"blacklisted", "1"},
{"key", "ja3"}};
allowLog(status, std::string("blacklisted JA3"), lt, log_attrs);
ret_msg = substituteStrings(g_bl_db.getJA3RetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
blacklisted = true;
}
else if (g_bl_db.getEntry(lt.remote, lt.login, ble)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(ble.expiration)},
{"reason", ble.reason},
{"blacklisted", "1"},
{"key", "iplogin"}};
allowLog(status, std::string("blacklisted IPLogin"), lt, log_attrs);
ret_msg = substituteStrings(g_bl_db.getIPLoginRetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
blacklisted = true;
}
else if (!ja3.empty() && g_bl_db.getIPJA3Entry(lt.remote, ja3, ble)) {
std::vector<pair<std::string, std::string>> log_attrs =
{{"expiration", boost::posix_time::to_simple_string(ble.expiration)},
{"reason", ble.reason},
{"blacklisted", "1"},
{"key", "ipja3"}};
allowLog(status, std::string("blacklisted IPJA3"), lt, log_attrs);
ret_msg = substituteStrings(g_bl_db.getIPJA3RetMsg(), lt.remote, lt.login, ja3);
ret_attrs = std::move(log_attrs);
blacklisted = true;
}
}
if (blacklisted || whitelisted) {
// run webhook
json11::Json::object jattrs;
for (auto& i : ret_attrs) {
jattrs.insert(make_pair(i.first, json11::Json(i.second)));
}
msg = json11::Json::object{{"status", status},
{"msg", ret_msg},
{"r_attrs", jattrs}};
runAllowWebHook(lt.to_json(), msg, status);
if (blacklisted) {
g_stats.denieds++;
incCommandStat("allow_blacklisted");
incPrometheusAllowStatusMetric("blacklisted");
incCommandStat("allow_denied");
incPrometheusAllowStatusMetric("denied");
}
if (whitelisted) {
incCommandStat("allow_whitelisted");
incPrometheusAllowStatusMetric("whitelisted");
}
}
else {
try {
AllowReturn ar;
{
ar = g_luamultip->allow(lt);
}
status = std::get<allowRetStatus>(ar);
ret_msg = std::get<allowRetMsg>(ar);
std::string log_msg = std::get<allowRetLogMsg>(ar);
std::vector<pair<std::string, std::string>> log_attrs = std::get<allowRetAttrs>(ar);
// log the results of the allow function
allowLog(status, log_msg, lt, log_attrs);
ret_attrs = std::move(log_attrs);
if (status < 0) {
g_stats.denieds++;
incCommandStat("allow_denied");
incPrometheusAllowStatusMetric("denied");
}
else if (status > 0) {
incCommandStat("allow_tarpitted");
incPrometheusAllowStatusMetric("tarpitted");
}
else {
incCommandStat("allow_allowed");
incPrometheusAllowStatusMetric("allowed");
}
json11::Json::object jattrs;
for (auto& i : ret_attrs) {
jattrs.insert(make_pair(i.first, json11::Json(i.second)));
}
msg = json11::Json::object{{"status", status},
{"msg", ret_msg},
{"r_attrs", jattrs}};
// generate webhook events
runAllowWebHook(lt.to_json(), msg, status);
resp->setStatusCode(drogon::k200OK);
resp->setBody(msg.dump());
}
catch (LuaContext::ExecutionErrorException& e) {
resp->setStatusCode(drogon::k500InternalServerError);
std::stringstream ss;
try {
std::rethrow_if_nested(e);
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua function [%s] exception: %s", command, e.what());
}
catch (const std::exception& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.what(), resp);
errlog("Exception in command [%s] exception: %s", command, ne.what());
}
catch (const WforceException& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.reason, resp);
errlog("Exception in command [%s] exception: %s", command, ne.reason);
}
}
catch (const std::exception& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Exception in command [%s] exception: %s", command, e.what());
}
catch (const WforceException& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.reason, resp);
errlog("Exception in command [%s] exception: %s", command, e.reason);
}
}
if (resp->getStatusCode() == drogon::k200OK) {
json11::Json::object jattrs;
for (auto& i : ret_attrs) {
jattrs.insert(make_pair(i.first, json11::Json(i.second)));
}
msg = json11::Json::object{{"status", status},
{"msg", ret_msg},
{"r_attrs", jattrs}};
resp->setBody(msg.dump());
}
}
}
// XXX BEGIN Deprecated functions - will be removed in a later release
void parseStatsCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
struct rusage ru;
getrusage(RUSAGE_SELF, &ru);
json11::Json my_json = json11::Json::object{
{"reports", (int) g_stats.reports},
{"allows", (int) g_stats.allows},
{"denieds", (int) g_stats.denieds},
{"user-msec", (int) (ru.ru_utime.tv_sec * 1000ULL + ru.ru_utime.tv_usec / 1000)},
{"sys-msec", (int) (ru.ru_stime.tv_sec * 1000ULL + ru.ru_stime.tv_usec / 1000)},
{"uptime", uptimeOfProcess()},
{"perfstats", perfStatsToJson()},
{"commandstats", commandStatsToJson()},
{"customstats", customStatsToJson()}
};
resp->setStatusCode(drogon::k200OK);
resp->setBody(my_json.dump());
incCommandStat("stats");
incPrometheusCommandMetric("stats");
}
// XXX END Deprecated functions - will be removed in a later release
void parseGetBLWLCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp, bool blacklist)
{
json11::Json::array my_entries;
std::vector<BlackWhiteListEntry> lv;
std::string key_name;
std::string cmd_stat;
if (blacklist) {
key_name = "bl_entries";
cmd_stat = "getBL";
}
else {
key_name = "wl_entries";
cmd_stat = "getWL";
}
BlackWhiteListDB* blwl;
if (blacklist) {
blwl = &g_bl_db;
}
else {
blwl = &g_wl_db;
}
lv = blwl->getIPEntries();
addBLWLEntries(lv, "ip", my_entries);
lv = blwl->getLoginEntries();
addBLWLEntries(lv, "login", my_entries);
lv = blwl->getIPLoginEntries();
addBLWLEntries(lv, "iplogin", my_entries);
lv = blwl->getJA3Entries();
addBLWLEntries(lv, "ja3", my_entries);
lv = blwl->getIPJA3Entries();
addBLWLEntries(lv, "ipja3", my_entries);
json11::Json ret_json = json11::Json::object{
{key_name, my_entries}
};
resp->setStatusCode(drogon::k200OK);
resp->setBody(ret_json.dump());
incCommandStat(cmd_stat);
incPrometheusCommandMetric(cmd_stat);
}
void parseGetBLCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseGetBLWLCmd(req, command, resp, true);
}
void parseGetWLCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
parseGetBLWLCmd(req, command, resp, false);
}
void parseGetStatsCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
bool haveIP = false;
bool haveLogin = false;
bool haveJA3 = false;
std::string en_type, en_login, en_ja3;
std::string key_name, key_value;
TWKeyType lookup_key;
bool is_blacklisted = false;
bool is_whitelisted = false;
std::string bl_reason;
std::string bl_expire;
std::string wl_reason;
std::string wl_expire;
ComboAddress en_ca;
BlackWhiteListEntry bwle;
try {
if (!msg["ip"].is_null()) {
string myip = msg["ip"].string_value();
en_ca = ComboAddress(myip);
haveIP = true;
}
if (!msg["login"].is_null()) {
en_login = msg["login"].string_value();
if (!canonicalizeLogin(en_login, resp))
return;
haveLogin = true;
}
if (!msg["ja3"].is_null()) {
en_ja3 = msg["ja3"].string_value();
haveJA3 = true;
}
if (haveLogin && haveJA3) {
setErrorCodeAndReason(drogon::k400BadRequest, "ja3 and login fields are mutually exclusive", resp);
return;
}
if (haveLogin && haveIP) {
key_name = "ip_login";
key_value = en_ca.toString() + ":" + en_login;
lookup_key = key_value;
if (g_bl_db.getEntry(en_ca, en_login, bwle)) {
is_blacklisted = true;
bl_reason = bwle.reason;
bl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
if (g_wl_db.getEntry(en_ca, en_login, bwle)) {
is_whitelisted = true;
wl_reason = bwle.reason;
wl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
}
else if (haveJA3 && haveIP) {
key_name = "ip_ja3";
key_value = getIPJA3(en_ca.toString(), en_ja3);
lookup_key = key_value;
if (g_bl_db.getIPJA3Entry(en_ca, en_ja3, bwle)) {
is_blacklisted = true;
bl_reason = bwle.reason;
bl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
if (g_wl_db.getIPJA3Entry(en_ca, en_ja3, bwle)) {
is_whitelisted = true;
wl_reason = bwle.reason;
wl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
}
else if (haveLogin) {
key_name = "login";
key_value = en_login;
lookup_key = en_login;
if (g_bl_db.getEntry(en_login, bwle)) {
is_blacklisted = true;
bl_reason = bwle.reason;
bl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
if (g_wl_db.getEntry(en_login, bwle)) {
is_whitelisted = true;
wl_reason = bwle.reason;
wl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
}
else if (haveJA3) {
key_name = "ja3";
key_value = en_ja3;
lookup_key = key_value;
if (g_bl_db.getJA3Entry(en_ja3, bwle)) {
is_blacklisted = true;
bl_reason = bwle.reason;
bl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
if (g_wl_db.getJA3Entry(en_ja3, bwle)) {
is_whitelisted = true;
wl_reason = bwle.reason;
wl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
}
else if (haveIP) {
key_name = "ip";
key_value = en_ca.toString();
lookup_key = en_ca;
if (g_bl_db.getEntry(en_ca, bwle)) {
is_blacklisted = true;
bl_reason = bwle.reason;
bl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
if (g_wl_db.getEntry(en_ca, bwle)) {
is_whitelisted = true;
wl_reason = bwle.reason;
wl_expire = boost::posix_time::to_simple_string(bwle.expiration);
}
}
}
catch (...) {
setErrorCodeAndReason(drogon::k400BadRequest, "Could not parse input", resp);
return;
}
if (!haveLogin && !haveIP && !haveJA3) {
setErrorCodeAndReason(drogon::k400BadRequest, "No ja3, ip or login field supplied", resp);
}
else {
json11::Json::object js_db_stats;
{
std::lock_guard<std::mutex> lock(dbMap_mutx);
for (auto i = dbMap.begin(); i != dbMap.end(); ++i) {
std::string dbName = i->first;
std::vector<std::pair<std::string, int>> db_fields;
if (i->second.get_all_fields(lookup_key, db_fields)) {
json11::Json::object js_db_fields;
for (auto j = db_fields.begin(); j != db_fields.end(); ++j) {
js_db_fields.insert(make_pair(j->first, j->second));
}
js_db_stats.insert(make_pair(dbName, js_db_fields));
}
}
}
json11::Json ret_json = json11::Json::object{
{key_name, key_value},
{"whitelisted", is_whitelisted},
{"wl_reason", wl_reason},
{"wl_expire", wl_expire},
{"blacklisted", is_blacklisted},
{"bl_reason", bl_reason},
{"bl_expire", bl_expire},
{"stats", js_db_stats}
};
resp->setStatusCode(drogon::k200OK);
resp->setBody(ret_json.dump());
}
}
incCommandStat("getDBStats");
incPrometheusCommandMetric("getDBStats");
}
enum CustomReturnFields {
customRetStatus = 0, customRetAttrs = 1
};
void parseCustomCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
json11::Json msg;
string err;
KeyValVector ret_attrs;
msg = json11::Json::parse(req->bodyData(), err);
if (msg.is_null()) {
setErrorCodeAndReason(drogon::k400BadRequest, err, resp);
}
else {
CustomFuncArgs cfa;
bool status = false;
try {
cfa.setAttrs(msg);
}
catch (...) {
setErrorCodeAndReason(drogon::k400BadRequest, "Could not parse input", resp);
return;
}
try {
bool reportSink = false;
CustomFuncReturn cr;
{
cr = g_luamultip->custom_func(command, cfa, reportSink);
}
status = std::get<customRetStatus>(cr);
ret_attrs = std::get<customRetAttrs>(cr);
json11::Json::object jattrs;
for (auto& i : ret_attrs) {
jattrs.insert(make_pair(i.first, json11::Json(i.second)));
}
msg = json11::Json::object{{"success", status},
{"r_attrs", jattrs}};
// send the custom parameters to the report sink if configured
if (reportSink)
sendNamedReportSink(cfa.serialize());
resp->setStatusCode(drogon::k200OK);
resp->setBody(msg.dump());
}
catch (LuaContext::ExecutionErrorException& e) {
resp->setStatusCode(drogon::k500InternalServerError);
std::stringstream ss;
try {
std::rethrow_if_nested(e);
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua custom function [%s] exception: %s", command, e.what());
}
catch (const std::exception& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.what(), resp);
errlog("Exception in command [%s] exception: %s", command, ne.what());
}
catch (const WforceException& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.reason, resp);
errlog("Exception in command [%s] exception: %s", command, ne.reason);
}
}
catch (const std::exception& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Exception in command [%s] exception: %s", command, e.what());
}
}
incCommandStat(command);
incPrometheusCommandMetric(command);
}
void parseCustomGetCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
string err;
try {
std::string ret_msg = g_luamultip->custom_get_func(command);
resp->setStatusCode(drogon::k200OK);
resp->setBody(ret_msg);
}
catch (LuaContext::ExecutionErrorException& e) {
resp->setStatusCode(drogon::k500InternalServerError);
std::stringstream ss;
try {
std::rethrow_if_nested(e);
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Lua custom function [%s] exception: %s", command, e.what());
}
catch (const std::exception& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.what(), resp);
errlog("Exception in command [%s] exception: %s", command, ne.what());
}
catch (const WforceException& ne) {
setErrorCodeAndReason(drogon::k500InternalServerError, ne.reason, resp);
errlog("Exception in command [%s] exception: %s", command, ne.reason);
}
}
catch (const std::exception& e) {
setErrorCodeAndReason(drogon::k500InternalServerError, e.what(), resp);
errlog("Exception in command [%s] exception: %s", command, e.what());
}
incCommandStat(command + "_Get");
incPrometheusCommandMetric(command + "_Get");
}
std::atomic<bool> g_ping_up{false};
void parsePingCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
resp->setStatusCode(drogon::k200OK);
if (g_ping_up)
resp->setBody(R"({"status":"ok"})");
else
resp->setBody(R"({"status":"warmup"})");
incCommandStat("ping");
incPrometheusCommandMetric("ping");
}
void parseReadyzCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
if (g_ping_up)
resp->setStatusCode(drogon::k200OK);
else
resp->setStatusCode(drogon::k503ServiceUnavailable);
incCommandStat("readyz");
incPrometheusCommandMetric("readyz");
}
void parseSyncDoneCmd(const drogon::HttpRequestPtr& req,
const std::string& command,
const drogon::HttpResponsePtr& resp)
{
resp->setStatusCode(drogon::k200OK);
g_ping_up = true;
resp->setBody(R"({"status":"ok"})");
incCommandStat("syncDone");
incPrometheusCommandMetric("syncDone");
}
void registerWebserverCommands()
{
addCommandStat("addWLEntry");
addPrometheusCommandMetric("addWLEntry");
g_webserver.registerFunc("addWLEntry", HTTPVerb::POST, WforceWSFunc(parseAddWLEntryCmd));
addCommandStat("delWLEntry");
addPrometheusCommandMetric("delWLEntry");
g_webserver.registerFunc("delWLEntry", HTTPVerb::POST, WforceWSFunc(parseDelWLEntryCmd));
addCommandStat("addBLEntry");
addPrometheusCommandMetric("addBLEntry");
g_webserver.registerFunc("addBLEntry", HTTPVerb::POST, WforceWSFunc(parseAddBLEntryCmd));
addCommandStat("delBLEntry");
addPrometheusCommandMetric("delWLEntry");
g_webserver.registerFunc("delBLEntry", HTTPVerb::POST, WforceWSFunc(parseDelBLEntryCmd));
addCommandStat("reset");
addPrometheusCommandMetric("reset");
g_webserver.registerFunc("reset", HTTPVerb::POST, WforceWSFunc(parseResetCmd));
addCommandStat("report");
addPrometheusCommandMetric("report");
g_webserver.registerFunc("report", HTTPVerb::POST, WforceWSFunc(parseReportCmd));
addCommandStat("allow");
addPrometheusCommandMetric("allow");
addCommandStat("allow_allowed");
addPrometheusAllowStatusMetric("allowed");
addCommandStat("allow_blacklisted");
addPrometheusAllowStatusMetric("blacklisted");
addCommandStat("allow_whitelisted");
addPrometheusAllowStatusMetric("whitelisted");
addCommandStat("allow_denied");
addPrometheusAllowStatusMetric("denied");
addCommandStat("allow_tarpitted");
addPrometheusAllowStatusMetric("tarpitted");
g_webserver.registerFunc("allow", HTTPVerb::POST, WforceWSFunc(parseAllowCmd));
addCommandStat("stats");
addPrometheusCommandMetric("stats");
g_webserver.registerFunc("stats", HTTPVerb::GET, WforceWSFunc(parseStatsCmd));
addCommandStat("getBL");
addPrometheusCommandMetric("getBL");
g_webserver.registerFunc("getBL", HTTPVerb::GET, WforceWSFunc(parseGetBLCmd));
addCommandStat("getWL");
addPrometheusCommandMetric("getWL");
g_webserver.registerFunc("getWL", HTTPVerb::GET, WforceWSFunc(parseGetWLCmd));
addCommandStat("getDBStats");
addPrometheusCommandMetric("getDBStats");
g_webserver.registerFunc("getDBStats", HTTPVerb::POST, WforceWSFunc(parseGetStatsCmd));
addCommandStat("ping");
addPrometheusCommandMetric("ping");
g_webserver.registerFunc("ping", HTTPVerb::GET, WforceWSFunc(parsePingCmd));
addCommandStat("syncDBs");
addPrometheusCommandMetric("syncDBs");
g_webserver.registerFunc("syncDBs", HTTPVerb::POST, WforceWSFunc(parseSyncCmd));
addCommandStat("syncDone");
addPrometheusCommandMetric("syncDone");
g_webserver.registerFunc("syncDone", HTTPVerb::GET, WforceWSFunc(parseSyncDoneCmd));
addCommandStat("dumpEntries");
addPrometheusCommandMetric("dumpEntries");
g_webserver.registerFunc("dumpEntries", HTTPVerb::POST, WforceWSFunc(parseDumpEntriesCmd));
addCommandStat("addSibling");
addPrometheusCommandMetric("addSibling");
g_webserver.registerFunc("addSibling", HTTPVerb::POST, WforceWSFunc(parseAddSiblingCmd));
addCommandStat("removeSibling");
addPrometheusCommandMetric("removeSibling");
g_webserver.registerFunc("removeSibling", HTTPVerb::POST, WforceWSFunc(parseRemoveSiblingCmd));
addCommandStat("setSiblings");
addPrometheusCommandMetric("setSiblings");
g_webserver.registerFunc("setSiblings", HTTPVerb::POST, WforceWSFunc(parseSetSiblingsCmd));
addCommandStat("readyz");
addPrometheusCommandMetric("readyz");
g_webserver.registerFuncNoAuth("readyz", HTTPVerb::GET, WforceWSFunc(parseReadyzCmd));
}
|