Compare commits

...

121 Commits

Author SHA1 Message Date
orianelou
448991ef75 Update docker-compose.yaml 2025-03-03 11:54:03 +02:00
orianelou
2b1ee84280 Update docker-compose.yaml 2025-03-03 11:53:53 +02:00
orianelou
77dd288eee Update docker-compose.yaml 2025-03-03 11:52:47 +02:00
orianelou
3cb4def82e Update docker-compose.yaml 2025-03-03 11:52:26 +02:00
orianelou
a0dd7dd614 Update docker-compose.yaml 2025-03-03 11:51:13 +02:00
orianelou
88eed946ec Update docker-compose.yaml 2025-03-03 11:50:49 +02:00
orianelou
3e1ad8b0f7 Update docker-compose.yaml 2025-03-03 11:50:23 +02:00
Daniel-Eisenberg
bd35c421c6 Merge pull request #263 from openappsec/Feb_27_2025-Dev
Feb 27 2025 dev
2025-03-02 18:23:10 +02:00
Ned Wright
9d6e883724 sync code 2025-02-27 16:08:31 +00:00
Ned Wright
cd020a7ddd sync code 2025-02-27 16:03:28 +00:00
orianelou
bb35eaf657 Update open-appsec-k8s-prevent-config-v1beta2.yaml 2025-02-26 16:16:16 +02:00
orianelou
648f9ae2b1 Update open-appsec-k8s-default-config-v1beta2.yaml 2025-02-26 16:15:54 +02:00
orianelou
47e47d706a Update open-appsec-k8s-default-config-v1beta2.yaml 2025-02-26 16:15:39 +02:00
orianelou
b852809d1a Update open-appsec-crd-v1beta2.yaml 2025-02-19 13:35:51 +02:00
orianelou
a77732f84c Update open-appsec-k8s-prevent-config-v1beta1.yaml 2025-02-17 16:08:50 +02:00
orianelou
a1a8e28019 Update open-appsec-k8s-default-config-v1beta1.yaml 2025-02-17 16:08:32 +02:00
orianelou
a99c2ec4a3 Update open-appsec-k8s-prevent-config-v1beta1.yaml 2025-02-17 16:06:02 +02:00
orianelou
f1303c1703 Update open-appsec-crd-v1beta1.yaml 2025-02-17 15:52:02 +02:00
Daniel Eisenberg
bd8174ead3 fix connection 2025-02-17 12:20:20 +02:00
Daniel-Eisenberg
4ddcd2462a Feb 10 2025 dev (#255)
* sync code

* sync code

* code sync

* code sync

---------

Co-authored-by: Ned Wright <nedwright@proton.me>
Co-authored-by: Daniel Eisenberg <danielei@checkpoint.com>
2025-02-12 10:56:44 +02:00
orianelou
81433bac25 Create local_policy.yaml 2025-02-11 15:42:20 +02:00
orianelou
8d03b49176 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2025-02-10 10:34:40 +02:00
orianelou
84f9624c00 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2025-02-10 10:23:00 +02:00
orianelou
3ecda7b979 Update docker-compose.yaml 2025-02-09 15:57:29 +02:00
orianelou
8f05508e02 Update docker-compose.yaml 2025-02-09 15:41:55 +02:00
orianelou
f5b9c93fbe Update docker-compose.yaml 2025-02-09 15:40:03 +02:00
orianelou
62b74c9a10 Update docker-compose.yaml 2025-02-09 15:32:02 +02:00
orianelou
e3163cd4fa Create .env 2025-02-03 16:34:47 +02:00
orianelou
1e98fc8c66 Add files via upload 2025-02-03 16:16:50 +02:00
orianelou
6fbe272378 Delete deployment/docker-compose/envoy directory 2025-02-03 16:16:31 +02:00
orianelou
7b3320ce10 Rename default.conf to default.conf 2025-01-21 14:04:01 +02:00
orianelou
25cc2d66e7 Rename .env to .env 2025-01-21 14:03:28 +02:00
orianelou
66e2112afb Rename docker-compose.yaml to docker-compose.yaml 2025-01-21 14:03:05 +02:00
orianelou
ba7c9afd52 Create .env 2025-01-20 15:14:44 +02:00
orianelou
2aa0993d7e Create .env 2025-01-20 15:13:52 +02:00
orianelou
0cdfc9df90 Create .env 2025-01-20 15:13:28 +02:00
orianelou
010814d656 Update .env 2025-01-20 14:36:03 +02:00
orianelou
3779dd360d Create .env 2025-01-20 14:34:54 +02:00
orianelou
0e7dc2133d Update .env 2025-01-20 14:31:39 +02:00
orianelou
c9095acbef Create .env 2025-01-20 14:29:39 +02:00
orianelou
e47e29321d Create .env 2025-01-20 14:24:03 +02:00
orianelou
25a66e77df Create default.conf 2025-01-20 14:16:18 +02:00
orianelou
6eea40f165 Create docker-compose.yaml 2025-01-20 14:15:35 +02:00
orianelou
cee6ed511a Create .env 2025-01-20 14:15:12 +02:00
orianelou
4f145fd74f Update .env 2025-01-20 14:14:31 +02:00
orianelou
3fe5c5b36f Create .env 2025-01-20 14:14:15 +02:00
orianelou
7542a85ddb Update docker-compose.yaml 2025-01-20 14:14:04 +02:00
orianelou
fae4534e5c Merge pull request #226 from openappsec/oriane-23.12.24-adding-new-composes
Oriane 23.12.24 adding new composes
2025-01-20 12:02:00 +02:00
orianelou
923a8a804b Add files via upload 2025-01-20 12:00:49 +02:00
orianelou
b1731237d1 Delete deployment directory 2025-01-20 11:58:01 +02:00
orianelou
3d3d6e73b9 Rename deployment/envoy/docker-compose.yaml to deployment/docker-compose/envoy/docker-compose.yaml 2025-01-20 11:49:03 +02:00
Daniel-Eisenberg
3f80127ec5 Merge pull request #224 from openappsec/Jan_12_2025-Dev
Jan 12 2025 dev
2025-01-19 11:16:59 +02:00
Ned Wright
abdee954bb fix log-file-handler 2025-01-15 12:22:16 +00:00
Ned Wright
9a516899e8 central nginx manager 2025-01-14 16:14:25 +00:00
Ned Wright
4fd2aa6c6b central nginx manager 2025-01-14 16:00:54 +00:00
Ned Wright
0db666ac4f central nginx manager - add new package to packages list 2025-01-13 14:29:58 +00:00
Ned Wright
493d9a6627 central nginx manager 2025-01-13 13:25:05 +00:00
Ned Wright
6db87fc7fe central nginx manager 2025-01-13 12:35:42 +00:00
orianelou
d2b9bc8c9c Create envoy.yaml 2025-01-13 14:23:49 +02:00
orianelou
886a5befe1 Create .env 2025-01-13 14:23:17 +02:00
orianelou
1f2502f9e4 Create docker-compose.yaml 2025-01-13 14:22:57 +02:00
orianelou
9e4c5014ce Create .env 2025-01-13 14:21:50 +02:00
orianelou
024423cce9 Create docker-compose.yaml 2025-01-13 14:21:35 +02:00
orianelou
dc4b546bd1 Update .env 2025-01-13 14:20:38 +02:00
orianelou
a86aca13b4 Update docker-compose.yaml 2025-01-13 14:20:21 +02:00
orianelou
87b34590d4 Update .env 2025-01-13 14:18:04 +02:00
orianelou
e0198a1a95 Update docker-compose.yaml 2025-01-13 14:17:49 +02:00
orianelou
d024ad5845 Update .env 2025-01-13 14:15:28 +02:00
orianelou
46d42c8fa3 Update docker-compose.yaml 2025-01-13 14:15:15 +02:00
orianelou
f6c36f3363 Update .env 2025-01-13 14:14:07 +02:00
orianelou
63541a4c3c Update docker-compose.yaml 2025-01-13 14:13:53 +02:00
orianelou
d14fa7a468 Update docker-compose.yaml 2025-01-13 14:13:23 +02:00
orianelou
ae0de5bf14 Update docker-compose.yaml 2025-01-13 14:13:12 +02:00
orianelou
d39919f348 Update .env 2025-01-13 14:12:32 +02:00
orianelou
4f215e1409 Update docker-compose.yaml 2025-01-13 14:12:09 +02:00
orianelou
f05b5f8cee Create default.conf 2025-01-13 14:11:47 +02:00
orianelou
949b656b13 Update .env 2025-01-13 14:11:02 +02:00
orianelou
bbe293d215 Update docker-compose.yaml 2025-01-13 14:10:48 +02:00
Daniel-Eisenberg
35b2df729f Merge pull request #214 from openappsec/Dec_29_2024-Dev
Dec 29 2024 dev
2025-01-02 10:56:50 +02:00
orianelou
7600b6218f Rename examples/juiceshop/default.conf to examples/juiceshop/nginx/default.conf 2025-01-02 10:21:02 +02:00
orianelou
20e8e65e14 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:52:26 +02:00
orianelou
414130a789 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:40:13 +02:00
orianelou
9d704455e8 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:30:36 +02:00
orianelou
602442fed4 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:24:12 +02:00
orianelou
4e9a90db01 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:21:15 +02:00
orianelou
20f92afbc2 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:18:59 +02:00
orianelou
ee7adc37d0 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 16:13:51 +02:00
orianelou
c0b3e9c0d0 Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 14:34:17 +02:00
orianelou
f1f4b13327 Update open-appsec-k8s-prevent-config-v1beta2.yaml 2024-12-30 13:51:59 +02:00
orianelou
4354a98d37 Update open-appsec-k8s-default-config-v1beta2.yaml 2024-12-30 13:51:19 +02:00
orianelou
09fa11516c Update open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 13:39:09 +02:00
orianelou
446b043128 Rename pen-appsec-k8s-full-example-config-v1beta2.yaml to open-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 13:36:31 +02:00
orianelou
91bcadf930 Create pen-appsec-k8s-full-example-config-v1beta2.yaml 2024-12-30 13:35:05 +02:00
orianelou
0824cf4b23 Update README.md 2024-12-30 09:42:10 +02:00
Ned Wright
108abdb35e sync code 2024-12-29 12:47:25 +00:00
Ned Wright
64ebf013eb sync code 2024-12-29 12:13:27 +00:00
orianelou
2c91793f08 Create .env 2024-12-24 11:04:38 +02:00
orianelou
72a263d25a Create docker-compose.yaml 2024-12-24 11:00:58 +02:00
orianelou
4e14ff9a58 Create default.conf 2024-12-23 17:25:23 +02:00
orianelou
1fb28e14d6 Create juiceshop.subfolder.conf 2024-12-23 17:24:26 +02:00
orianelou
e38bb9525c Create .env 2024-12-23 17:22:40 +02:00
orianelou
63b8bb22c2 Create docker-compose.yaml 2024-12-23 17:21:53 +02:00
orianelou
11c97330f5 Create apisix.yaml 2024-12-23 16:59:40 +02:00
orianelou
e56fb0bc1a Create .env 2024-12-23 16:59:07 +02:00
orianelou
4571d563f4 Create docker-compose.yaml 2024-12-23 16:58:35 +02:00
orianelou
02c1db01f6 Create default.conf 2024-12-23 16:47:53 +02:00
orianelou
c557affd9b Create .env 2024-12-23 16:46:38 +02:00
orianelou
8889c3c054 Create docker-compose.yaml 2024-12-23 16:46:16 +02:00
orianelou
f67eff87bc Create kong.yaml 2024-12-23 16:19:32 +02:00
orianelou
fa6a2e4233 Create .env 2024-12-23 16:18:53 +02:00
orianelou
b7e2efbf7e Create docker-compose.yaml 2024-12-23 10:20:02 +02:00
orianelou
96ce290e5f Update open-appsec-crd-v1beta2.yaml 2024-12-19 14:42:51 +02:00
orianelou
de8e2d9970 Merge pull request #210 from openappsec/orianelou-test-as-top-level-7
Update local_policy.yaml
2024-12-12 12:50:29 +02:00
orianelou
0048708af1 Update local_policy.yaml 2024-12-12 12:49:40 +02:00
orianelou
4fe0f44e88 Update local_policy.yaml 2024-12-12 12:45:22 +02:00
orianelou
5f139d13d7 Update docker-compose.yaml 2024-12-09 10:59:01 +02:00
orianelou
919d775a73 Update docker-compose.yaml 2024-12-05 14:42:04 +02:00
orianelou
ac8e353598 Update docker-compose.yaml 2024-12-05 13:43:23 +02:00
Daniel-Eisenberg
0663f20691 Merge pull request #207 from openappsec/Nov_28_2024-Dev
Nov 28 2024 dev
2024-12-01 11:53:26 +02:00
Ned Wright
2dda6231f6 sync code 2024-11-28 10:53:40 +00:00
Ned Wright
1c1f0b7e29 sync code 2024-11-28 10:41:59 +00:00
243 changed files with 9604 additions and 1672 deletions

View File

@@ -74,7 +74,7 @@ For Linux, if youve built your own package use the following commands:
```bash
$ install-cp-nano-agent.sh --install --hybrid_mode
$ install-cp-nano-service-http-transaction-handler.sh install
$ install-cp-nano-service-http-transaction-handler.sh --install
$ install-cp-nano-attachment-registration-manager.sh --install
```
You can add the ```--token <token>``` and ```--email <email address>``` options to the first command, to get a token follow [documentation](https://docs.openappsec.io/getting-started/using-the-web-ui-saas/connect-deployed-agents-to-saas-management-k8s-and-linux).

View File

@@ -95,6 +95,18 @@ getFailOpenHoldTimeout()
return conf_data.getNumericalValue("fail_open_hold_timeout");
}
unsigned int
getHoldVerdictPollingTime()
{
return conf_data.getNumericalValue("hold_verdict_polling_time");
}
unsigned int
getHoldVerdictRetries()
{
return conf_data.getNumericalValue("hold_verdict_retries");
}
unsigned int
getMaxSessionsPerMinute()
{
@@ -173,6 +185,12 @@ getReqBodySizeTrigger()
return conf_data.getNumericalValue("body_size_trigger");
}
unsigned int
getRemoveResServerHeader()
{
return conf_data.getNumericalValue("remove_server_header");
}
int
isIPAddress(c_str ip_str)
{

View File

@@ -66,7 +66,10 @@ TEST_F(HttpAttachmentUtilTest, GetValidAttachmentConfiguration)
"\"static_resources_path\": \"" + static_resources_path + "\",\n"
"\"min_retries_for_verdict\": 1,\n"
"\"max_retries_for_verdict\": 3,\n"
"\"body_size_trigger\": 777\n"
"\"hold_verdict_retries\": 3,\n"
"\"hold_verdict_polling_time\": 1,\n"
"\"body_size_trigger\": 777,\n"
"\"remove_server_header\": 1\n"
"}\n";
ofstream valid_configuration_file(attachment_configuration_file_name);
valid_configuration_file << valid_configuration;
@@ -95,6 +98,9 @@ TEST_F(HttpAttachmentUtilTest, GetValidAttachmentConfiguration)
EXPECT_EQ(getReqBodySizeTrigger(), 777u);
EXPECT_EQ(getWaitingForVerdictThreadTimeout(), 75u);
EXPECT_EQ(getInspectionMode(), ngx_http_inspection_mode::BLOCKING_THREAD);
EXPECT_EQ(getRemoveResServerHeader(), 1u);
EXPECT_EQ(getHoldVerdictRetries(), 3u);
EXPECT_EQ(getHoldVerdictPollingTime(), 1u);
EXPECT_EQ(isDebugContext("1.2.3.4", "5.6.7.8", 80, "GET", "test", "/abc"), 1);
EXPECT_EQ(isDebugContext("1.2.3.9", "5.6.7.8", 80, "GET", "test", "/abc"), 0);

View File

@@ -98,19 +98,19 @@ while true; do
init=true
/etc/cp/watchdog/cp-nano-watchdog >/dev/null 2>&1 &
sleep 5
active_watchdog_pid=$(pgrep -f -x -o "/bin/bash /etc/cp/watchdog/cp-nano-watchdog")
active_watchdog_pid=$(pgrep -f -x -o "/bin/(bash|sh) /etc/cp/watchdog/cp-nano-watchdog")
fi
current_watchdog_pid=$(pgrep -f -x -o "/bin/bash /etc/cp/watchdog/cp-nano-watchdog")
current_watchdog_pid=$(pgrep -f -x -o "/bin/(bash|sh) /etc/cp/watchdog/cp-nano-watchdog")
if [ ! -f /tmp/restart_watchdog ] && [ "$current_watchdog_pid" != "$active_watchdog_pid" ]; then
echo "Error: Watchdog exited abnormally"
exit 1
elif [ -f /tmp/restart_watchdog ]; then
rm -f /tmp/restart_watchdog
kill -9 "$(pgrep -f -x -o "/bin/bash /etc/cp/watchdog/cp-nano-watchdog")"
kill -9 "$(pgrep -f -x -o "/bin/(bash|sh) /etc/cp/watchdog/cp-nano-watchdog")"
/etc/cp/watchdog/cp-nano-watchdog >/dev/null 2>&1 &
sleep 5
active_watchdog_pid=$(pgrep -f -x -o "/bin/bash /etc/cp/watchdog/cp-nano-watchdog")
active_watchdog_pid=$(pgrep -f -x -o "/bin/(bash|sh) /etc/cp/watchdog/cp-nano-watchdog")
fi
sleep 5

View File

@@ -7,3 +7,4 @@ add_subdirectory(pending_key)
add_subdirectory(utils)
add_subdirectory(attachment-intakers)
add_subdirectory(security_apps)
add_subdirectory(nginx_message_reader)

View File

@@ -31,6 +31,7 @@
#include <stdarg.h>
#include <boost/range/iterator_range.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include "nginx_attachment_config.h"
@@ -260,6 +261,22 @@ public:
);
}
const char* ignored_headers_env = getenv("SAAS_IGNORED_UPSTREAM_HEADERS");
if (ignored_headers_env) {
string ignored_headers_str = ignored_headers_env;
ignored_headers_str = NGEN::Strings::trim(ignored_headers_str);
if (!ignored_headers_str.empty()) {
dbgInfo(D_HTTP_MANAGER)
<< "Ignoring SAAS_IGNORED_UPSTREAM_HEADERS environment variable: "
<< ignored_headers_str;
vector<string> ignored_headers_vec;
boost::split(ignored_headers_vec, ignored_headers_str, boost::is_any_of(";"));
for (const string &header : ignored_headers_vec) ignored_headers.insert(header);
}
}
dbgInfo(D_NGINX_ATTACHMENT) << "Successfully initialized NGINX Attachment";
}
@@ -1034,7 +1051,11 @@ private:
case ChunkType::REQUEST_START:
return handleStartTransaction(data, opaque);
case ChunkType::REQUEST_HEADER:
return handleMultiModifiableChunks(NginxParser::parseRequestHeaders(data), "request header", true);
return handleMultiModifiableChunks(
NginxParser::parseRequestHeaders(data, ignored_headers),
"request header",
true
);
case ChunkType::REQUEST_BODY:
return handleModifiableChunk(NginxParser::parseRequestBody(data), "request body", true);
case ChunkType::REQUEST_END: {
@@ -1135,7 +1156,11 @@ private:
"webUserResponse"
);
bool remove_event_id_param =
getProfileAgentSettingWithDefault<string>("false", "nginxAttachment.removeRedirectEventId") == "true";
string uuid;
string redirectUrl;
if (i_transaction_table->hasState<NginxAttachmentOpaque>()) {
NginxAttachmentOpaque &opaque = i_transaction_table->getState<NginxAttachmentOpaque>();
uuid = opaque.getSessionUUID();
@@ -1145,7 +1170,12 @@ private:
if (web_trigger_conf.getDetailsLevel() == "Redirect") {
web_response_data.response_data.redirect_data.redirect_location_size =
web_trigger_conf.getRedirectURL().size();
web_response_data.response_data.redirect_data.add_event_id = web_trigger_conf.getAddEventId() ? 1 : 0;
bool add_event = web_trigger_conf.getAddEventId();
if (add_event && !remove_event_id_param) {
web_response_data.response_data.redirect_data.redirect_location_size +=
strlen("?event_id=") + uuid.size();
}
web_response_data.response_data.redirect_data.add_event_id = add_event ? 1 : 0;
web_response_data.web_repsonse_type = static_cast<uint8_t>(ngx_web_response_type_e::REDIRECT_WEB_RESPONSE);
} else {
web_response_data.response_data.custom_response_data.title_size =
@@ -1159,8 +1189,13 @@ private:
verdict_data_sizes.push_back(sizeof(ngx_http_cp_web_response_data_t));
if (web_trigger_conf.getDetailsLevel() == "Redirect") {
verdict_data.push_back(reinterpret_cast<const char *>(web_trigger_conf.getRedirectURL().data()));
verdict_data_sizes.push_back(web_trigger_conf.getRedirectURL().size());
redirectUrl = web_trigger_conf.getRedirectURL();
if (!remove_event_id_param && web_trigger_conf.getAddEventId()) {
redirectUrl += "?event-id=" + uuid;
}
verdict_data.push_back(reinterpret_cast<const char *>(redirectUrl.data()));
verdict_data_sizes.push_back(redirectUrl.size());
} else {
verdict_data.push_back(reinterpret_cast<const char *>(web_trigger_conf.getResponseTitle().data()));
verdict_data_sizes.push_back(web_trigger_conf.getResponseTitle().size());
@@ -1800,6 +1835,7 @@ private:
HttpAttachmentConfig attachment_config;
I_MainLoop::RoutineID attachment_routine_id = 0;
bool traffic_indicator = false;
unordered_set<string> ignored_headers;
// Interfaces
I_Socket *i_socket = nullptr;

View File

@@ -203,6 +203,13 @@ HttpAttachmentConfig::setFailOpenTimeout()
"NGINX wait thread timeout msec"
));
conf_data.setNumericalValue("remove_server_header", getAttachmentConf<uint>(
0,
"agent.removeServerHeader.nginxModule",
"HTTP manager",
"Response server header removal"
));
uint inspection_mode = getAttachmentConf<uint>(
static_cast<uint>(ngx_http_inspection_mode_e::NON_BLOCKING_THREAD),
"agent.inspectionMode.nginxModule",
@@ -233,6 +240,21 @@ HttpAttachmentConfig::setRetriesForVerdict()
"Max retries for verdict"
));
conf_data.setNumericalValue("hold_verdict_retries", getAttachmentConf<uint>(
3,
"agent.retriesForHoldVerdict.nginxModule",
"HTTP manager",
"Retries for hold verdict"
));
conf_data.setNumericalValue("hold_verdict_polling_time", getAttachmentConf<uint>(
1,
"agent.holdVerdictPollingInterval.nginxModule",
"HTTP manager",
"Hold verdict polling interval seconds"
));
conf_data.setNumericalValue("body_size_trigger", getAttachmentConf<uint>(
200000,
"agent.reqBodySizeTrigger.nginxModule",

View File

@@ -19,12 +19,15 @@
#include "config.h"
#include "virtual_modifiers.h"
#include "agent_core_utilities.h"
using namespace std;
using namespace boost::uuids;
USE_DEBUG_FLAG(D_HTTP_MANAGER);
extern bool is_keep_alive_ctx;
NginxAttachmentOpaque::NginxAttachmentOpaque(HttpTransactionData _transaction_data)
:
TableOpaqueSerialize<NginxAttachmentOpaque>(this),
@@ -119,3 +122,47 @@ NginxAttachmentOpaque::setSavedData(const string &name, const string &data, EnvK
saved_data[name] = data;
ctx.registerValue(name, data, log_ctx);
}
bool
NginxAttachmentOpaque::setKeepAliveCtx(const string &hdr_key, const string &hdr_val)
{
if (!is_keep_alive_ctx) return false;
static pair<string, string> keep_alive_hdr;
static bool keep_alive_hdr_initialized = false;
if (keep_alive_hdr_initialized) {
if (!keep_alive_hdr.first.empty() && hdr_key == keep_alive_hdr.first && hdr_val == keep_alive_hdr.second) {
dbgTrace(D_HTTP_MANAGER) << "Registering keep alive context";
ctx.registerValue("keep_alive_request_ctx", true);
return true;
}
return false;
}
const char* saas_keep_alive_hdr_name_env = getenv("SAAS_KEEP_ALIVE_HDR_NAME");
if (saas_keep_alive_hdr_name_env) {
keep_alive_hdr.first = NGEN::Strings::trim(saas_keep_alive_hdr_name_env);
dbgInfo(D_HTTP_MANAGER) << "Using SAAS_KEEP_ALIVE_HDR_NAME environment variable: " << keep_alive_hdr.first;
}
if (!keep_alive_hdr.first.empty()) {
const char* saas_keep_alive_hdr_value_env = getenv("SAAS_KEEP_ALIVE_HDR_VALUE");
if (saas_keep_alive_hdr_value_env) {
keep_alive_hdr.second = NGEN::Strings::trim(saas_keep_alive_hdr_value_env);
dbgInfo(D_HTTP_MANAGER)
<< "Using SAAS_KEEP_ALIVE_HDR_VALUE environment variable: "
<< keep_alive_hdr.second;
}
if (!keep_alive_hdr.second.empty() && (hdr_key == keep_alive_hdr.first && hdr_val == keep_alive_hdr.second)) {
dbgTrace(D_HTTP_MANAGER) << "Registering keep alive context";
ctx.registerValue("keep_alive_request_ctx", true);
keep_alive_hdr_initialized = true;
return true;
}
}
keep_alive_hdr_initialized = true;
return false;
}

View File

@@ -85,6 +85,7 @@ public:
EnvKeyAttr::LogSection log_ctx = EnvKeyAttr::LogSection::NONE
);
void setApplicationState(const ApplicationState &app_state) { application_state = app_state; }
bool setKeepAliveCtx(const std::string &hdr_key, const std::string &hdr_val);
private:
CompressionStream *response_compression_stream;

View File

@@ -29,6 +29,7 @@ USE_DEBUG_FLAG(D_NGINX_ATTACHMENT_PARSER);
Buffer NginxParser::tenant_header_key = Buffer();
static const Buffer proxy_ip_header_key("X-Forwarded-For", 15, Buffer::MemoryType::STATIC);
static const Buffer source_ip("sourceip", 8, Buffer::MemoryType::STATIC);
bool is_keep_alive_ctx = getenv("SAAS_KEEP_ALIVE_HDR_NAME") != nullptr;
map<Buffer, CompressionType> NginxParser::content_encodings = {
{Buffer("identity"), CompressionType::NO_COMPRESSION},
@@ -177,22 +178,54 @@ getActivetenantAndProfile(const string &str, const string &deli = ",")
}
Maybe<vector<HttpHeader>>
NginxParser::parseRequestHeaders(const Buffer &data)
NginxParser::parseRequestHeaders(const Buffer &data, const unordered_set<string> &ignored_headers)
{
auto parsed_headers = genHeaders(data);
if (!parsed_headers.ok()) return parsed_headers.passErr();
auto maybe_parsed_headers = genHeaders(data);
if (!maybe_parsed_headers.ok()) return maybe_parsed_headers.passErr();
auto i_transaction_table = Singleton::Consume<I_TableSpecific<SessionID>>::by<NginxAttachment>();
auto parsed_headers = maybe_parsed_headers.unpack();
NginxAttachmentOpaque &opaque = i_transaction_table->getState<NginxAttachmentOpaque>();
for (const HttpHeader &header : *parsed_headers) {
if (is_keep_alive_ctx || !ignored_headers.empty()) {
bool is_last_header_removed = false;
parsed_headers.erase(
remove_if(
parsed_headers.begin(),
parsed_headers.end(),
[&opaque, &is_last_header_removed, &ignored_headers](const HttpHeader &header)
{
string hdr_key = static_cast<string>(header.getKey());
string hdr_val = static_cast<string>(header.getValue());
if (
opaque.setKeepAliveCtx(hdr_key, hdr_val)
|| ignored_headers.find(hdr_key) != ignored_headers.end()
) {
dbgTrace(D_NGINX_ATTACHMENT_PARSER) << "Header was removed from headers list: " << hdr_key;
if (header.isLastHeader()) {
dbgTrace(D_NGINX_ATTACHMENT_PARSER) << "Last header was removed from headers list";
is_last_header_removed = true;
}
return true;
}
return false;
}
),
parsed_headers.end()
);
if (is_last_header_removed) {
dbgTrace(D_NGINX_ATTACHMENT_PARSER) << "Adjusting last header flag";
if (!parsed_headers.empty()) parsed_headers.back().setIsLastHeader();
}
}
for (const HttpHeader &header : parsed_headers) {
auto source_identifiers = getConfigurationWithDefault<UsersAllIdentifiersConfig>(
UsersAllIdentifiersConfig(),
"rulebase",
"usersIdentifiers"
);
source_identifiers.parseRequestHeaders(header);
NginxAttachmentOpaque &opaque = i_transaction_table->getState<NginxAttachmentOpaque>();
opaque.addToSavedData(
HttpTransactionData::req_headers,
static_cast<string>(header.getKey()) + ": " + static_cast<string>(header.getValue()) + "\r\n"

View File

@@ -28,7 +28,10 @@ public:
static Maybe<HttpTransactionData> parseStartTrasaction(const Buffer &data);
static Maybe<ResponseCode> parseResponseCode(const Buffer &data);
static Maybe<uint64_t> parseContentLength(const Buffer &data);
static Maybe<std::vector<HttpHeader>> parseRequestHeaders(const Buffer &data);
static Maybe<std::vector<HttpHeader>> parseRequestHeaders(
const Buffer &data,
const std::unordered_set<std::string> &ignored_headers
);
static Maybe<std::vector<HttpHeader>> parseResponseHeaders(const Buffer &data);
static Maybe<HttpBody> parseRequestBody(const Buffer &data);
static Maybe<HttpBody> parseResponseBody(const Buffer &raw_response_body, CompressionStream *compression_stream);

View File

@@ -282,21 +282,39 @@ isIpTrusted(const string &value, const vector<CIDRSData> &cidr_values)
}
Maybe<string>
UsersAllIdentifiersConfig::parseXForwardedFor(const string &str) const
UsersAllIdentifiersConfig::parseXForwardedFor(const string &str, ExtractType type) const
{
vector<string> header_values = split(str);
if (header_values.empty()) return genError("No IP found in the xff header list");
vector<string> xff_values = getHeaderValuesFromConfig("x-forwarded-for");
vector<CIDRSData> cidr_values(xff_values.begin(), xff_values.end());
string last_valid_ip;
for (const string &value : header_values) {
if (!IPAddr::createIPAddr(value).ok()) {
dbgWarning(D_NGINX_ATTACHMENT_PARSER) << "Invalid IP address found in the xff header IPs list: " << value;
return genError("Invalid IP address");
for (auto it = header_values.rbegin(); it != header_values.rend() - 1; ++it) {
if (!IPAddr::createIPAddr(*it).ok()) {
dbgWarning(D_NGINX_ATTACHMENT_PARSER) << "Invalid IP address found in the xff header IPs list: " << *it;
if (last_valid_ip.empty()) {
return genError("Invalid IP address");
}
return last_valid_ip;
}
if (!isIpTrusted(value, cidr_values)) return genError("Untrusted Ip found");
last_valid_ip = *it;
if (type == ExtractType::PROXYIP) continue;
if (!isIpTrusted(*it, cidr_values)) {
dbgDebug(D_NGINX_ATTACHMENT_PARSER) << "Found untrusted IP in the xff header IPs list: " << *it;
return *it;
}
}
if (!IPAddr::createIPAddr(header_values[0]).ok()) {
dbgWarning(D_NGINX_ATTACHMENT_PARSER)
<< "Invalid IP address found in the xff header IPs list: "
<< header_values[0];
if (last_valid_ip.empty()) {
return genError("No Valid Ip address was found");
}
return last_valid_ip;
}
return header_values[0];
@@ -312,7 +330,7 @@ UsersAllIdentifiersConfig::setXFFValuesToOpaqueCtx(const HttpHeader &header, Ext
return;
}
NginxAttachmentOpaque &opaque = i_transaction_table->getState<NginxAttachmentOpaque>();
auto value = parseXForwardedFor(header.getValue());
auto value = parseXForwardedFor(header.getValue(), type);
if (!value.ok()) {
dbgTrace(D_NGINX_ATTACHMENT_PARSER) << "Could not extract source identifier from X-Forwarded-For header";
return;
@@ -321,12 +339,13 @@ UsersAllIdentifiersConfig::setXFFValuesToOpaqueCtx(const HttpHeader &header, Ext
if (type == ExtractType::SOURCEIDENTIFIER) {
opaque.setSourceIdentifier(header.getKey(), value.unpack());
dbgDebug(D_NGINX_ATTACHMENT_PARSER)
<< "Added source identifir to XFF "
<< "Added source identifier from XFF header"
<< value.unpack();
opaque.setSavedData(HttpTransactionData::xff_vals_ctx, header.getValue());
opaque.setSavedData(HttpTransactionData::source_identifier, value.unpack());
dbgTrace(D_NGINX_ATTACHMENT_PARSER)
<< "XFF found, set ctx with value from header: "
<< static_cast<string>(header.getValue());
<< "XFF found, set ctx with value from header: "
<< static_cast<string>(header.getValue());
} else {
opaque.setSavedData(HttpTransactionData::proxy_ip_ctx, value.unpack());
}

View File

@@ -15,19 +15,18 @@
#include <string>
#include <map>
#include <sys/stat.h>
#include <climits>
#include <unordered_map>
#include <boost/range/iterator_range.hpp>
#include <unordered_set>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <algorithm>
#include "common.h"
#include "config.h"
#include "table_opaque.h"
#include "http_manager_opaque.h"
#include "log_generator.h"
#include "http_inspection_events.h"
#include "agent_core_utilities.h"
USE_DEBUG_FLAG(D_HTTP_MANAGER);
@@ -95,6 +94,7 @@ public:
HttpManagerOpaque &state = i_transaction_table->getState<HttpManagerOpaque>();
string event_key = static_cast<string>(event.getKey());
if (event_key == getProfileAgentSettingWithDefault<string>("", "agent.customHeaderValueLogging")) {
string event_value = static_cast<string>(event.getValue());
dbgTrace(D_HTTP_MANAGER)

View File

@@ -0,0 +1,45 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __CENTRAL_NGINX_MANAGER_H__
#define __CENTRAL_NGINX_MANAGER_H__
#include "component.h"
#include "singleton.h"
#include "i_messaging.h"
#include "i_rest_api.h"
#include "i_mainloop.h"
#include "i_agent_details.h"
class CentralNginxManager
:
public Component,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_AgentDetails>
{
public:
CentralNginxManager();
~CentralNginxManager();
void preload() override;
void init() override;
void fini() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __CENTRAL_NGINX_MANAGER_H__

View File

@@ -239,6 +239,7 @@ public:
const Buffer & getValue() const { return value; }
bool isLastHeader() const { return is_last_header; }
void setIsLastHeader() { is_last_header = true; }
uint8_t getHeaderIndex() const { return header_index; }
private:

View File

@@ -62,6 +62,7 @@ public:
private:
Maybe<std::string> downloadPackage(const Package &package, bool is_clean_installation);
std::string getCurrentTimestamp();
std::string manifest_file_path;
std::string temp_ext;

View File

@@ -0,0 +1,28 @@
#ifndef __NGINX_MESSAGE_READER_H__
#define __NGINX_MESSAGE_READER_H__
#include "singleton.h"
#include "i_mainloop.h"
#include "i_socket_is.h"
#include "component.h"
class NginxMessageReader
:
public Component,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Socket>
{
public:
NginxMessageReader();
~NginxMessageReader();
void init() override;
void fini() override;
void preload() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif //__NGINX_MESSAGE_READER_H__

View File

@@ -0,0 +1,51 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __NGINX_UTILS_H__
#define __NGINX_UTILS_H__
#include <string>
#include "maybe_res.h"
#include "singleton.h"
#include "i_shell_cmd.h"
class NginxConfCollector
{
public:
NginxConfCollector(const std::string &nginx_conf_input_path, const std::string &nginx_conf_output_path);
Maybe<std::string> generateFullNginxConf() const;
private:
std::vector<std::string> expandIncludes(const std::string &includePattern) const;
void processConfigFile(
const std::string &path,
std::ostringstream &conf_output,
std::vector<std::string> &errors
) const;
std::string main_conf_input_path;
std::string main_conf_output_path;
std::string main_conf_directory_path;
};
class NginxUtils : Singleton::Consume<I_ShellCmd>
{
public:
static std::string getModulesPath();
static std::string getMainNginxConfPath();
static Maybe<void> validateNginxConf(const std::string &nginx_conf_path);
static Maybe<void> reloadNginx(const std::string &nginx_conf_path);
};
#endif // __NGINX_UTILS_H__

View File

@@ -7,15 +7,21 @@
#include "singleton.h"
#include "i_mainloop.h"
#include "i_environment.h"
#include "i_geo_location.h"
#include "i_generic_rulebase.h"
#include "i_shell_cmd.h"
#include "i_env_details.h"
class RateLimit
:
public Component,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_GeoLocation>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_GenericRulebase>
Singleton::Consume<I_GenericRulebase>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_EnvDetails>
{
public:
RateLimit();

View File

@@ -28,7 +28,7 @@ static const std::string default_nginx_config_file = "/etc/cp/conf/rpmanager/ngi
static const std::string default_prepare_nginx_config_file = "/etc/cp/conf/rpmanager/nginx_prepare.conf";
static const std::string default_global_conf_template = "/etc/cp/conf/rpmanager/nginx-conf-template";
static const std::string default_nginx_config_include_file =
"/etc/cp/conf/rpmanager/servers/nginx_conf_include.conf";
"/etc/cp/conf/rpmanager/servers/00_nginx_conf_include.conf";
static const std::string default_global_conf_include_template =
"/etc/cp/conf/rpmanager/nginx-conf-include-template";
static const std::string default_global_conf_include_template_no_responses =

View File

@@ -30,6 +30,7 @@
#include "generic_metric.h"
#define LOGGING_INTERVAL_IN_MINUTES 10
USE_DEBUG_FLAG(D_WAAP);
enum class AssetType { API, WEB, ALL, COUNT };
class WaapTelemetryEvent : public Event<WaapTelemetryEvent>
@@ -132,6 +133,7 @@ private:
std::map<std::string, std::shared_ptr<T>>& telemetryMap
) {
if (!telemetryMap.count(asset_id)) {
dbgTrace(D_WAAP) << "creating telemetry data for asset: " << data.assetName;
telemetryMap.emplace(asset_id, std::make_shared<T>());
telemetryMap[asset_id]->init(
telemetryName,
@@ -139,7 +141,9 @@ private:
ReportIS::IssuingEngine::AGENT_CORE,
std::chrono::minutes(LOGGING_INTERVAL_IN_MINUTES),
true,
ReportIS::Audience::SECURITY
ReportIS::Audience::SECURITY,
false,
asset_id
);
telemetryMap[asset_id]->template registerContext<std::string>(
@@ -152,29 +156,30 @@ private:
std::string("Web Application"),
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"assetId",
asset_id,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"assetName",
data.assetName,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"practiceId",
data.practiceId,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"practiceName",
data.practiceName,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->registerListener();
}
dbgTrace(D_WAAP) << "updating telemetry data for asset: " << data.assetName;
telemetryMap[asset_id]->template registerContext<std::string>(
"assetId",
asset_id,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"assetName",
data.assetName,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"practiceId",
data.practiceId,
EnvKeyAttr::LogSection::SOURCE
);
telemetryMap[asset_id]->template registerContext<std::string>(
"practiceName",
data.practiceName,
EnvKeyAttr::LogSection::SOURCE
);
}
};

View File

@@ -58,7 +58,7 @@ private:
const std::string::const_iterator &end,
const std::string &key) const;
Buffer extractKeyValueFromCookie(const std::string &cookie_value, const std::string &key) const;
Maybe<std::string> parseXForwardedFor(const std::string &str) const;
Maybe<std::string> parseXForwardedFor(const std::string &str, ExtractType type) const;
std::vector<UsersIdentifiersConfig> user_identifiers;
};

View File

@@ -0,0 +1,3 @@
link_directories(${BOOST_ROOT}/lib)
add_library(nginx_message_reader nginx_message_reader.cc)

View File

@@ -0,0 +1,735 @@
#include "nginx_message_reader.h"
#include <string>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/algorithm/string/regex.hpp>
#include "config.h"
#include "singleton.h"
#include "i_mainloop.h"
#include "enum_array.h"
#include "log_generator.h"
#include "maybe_res.h"
#include "http_transaction_data.h"
#include "generic_rulebase/rulebase_config.h"
#include "generic_rulebase/evaluators/asset_eval.h"
#include "generic_rulebase/triggers_config.h"
#include "agent_core_utilities.h"
#include "rate_limit_config.h"
USE_DEBUG_FLAG(D_NGINX_MESSAGE_READER);
using namespace std;
static const string syslog_regex_string = (
"<[0-9]+>([A-Z][a-z][a-z]\\s{1,2}\\d{1,2}\\s\\d{2}"
"[:]\\d{2}[:]\\d{2})\\s([\\w][\\w\\d\\.@-]*)\\s(nginx:)"
);
static const boost::regex socket_address_regex("(\\d+\\.\\d+\\.\\d+\\.\\d+):(\\d+)");
static const boost::regex syslog_regex(syslog_regex_string);
static const boost::regex alert_log_regex(
"("
+ syslog_regex_string + ") "
+ "(.+?\\[alert\\] )(.+?)"
", (client: .+?)"
", (server: .+?)"
", (request: \".+?\")"
", (upstream: \".+?\")"
", (host: \".+?\")$"
);
static const boost::regex error_log_regex(
"("
+ syslog_regex_string + ") "
+ "(.+?\\[error\\] )(.+?)"
", (client: .+?)"
", (server: .+?)"
", (request: \".+?\")"
", (upstream: \".+?\")"
", (host: \".+?\")$"
);
static const boost::regex server_regex("(\\d+\\.\\d+\\.\\d+\\.\\d+)|(\\w+\\.\\w+)");
static const boost::regex uri_regex("^/");
static const boost::regex port_regex("\\d+");
static const boost::regex response_code_regex("[0-9]{3}");
static const boost::regex http_method_regex("[A-Za-z]+");
class NginxMessageReader::Impl
{
public:
void
init()
{
dbgFlow(D_NGINX_MESSAGE_READER);
I_MainLoop *mainloop = Singleton::Consume<I_MainLoop>::by<NginxMessageReader>();
mainloop->addOneTimeRoutine(
I_MainLoop::RoutineType::System,
[this] ()
{
initSyslogServerSocket();
handleNginxLogs();
},
"Initialize nginx syslog",
true
);
}
void
preload()
{
registerConfigLoadCb([this]() { loadNginxMessageReaderConfig(); });
}
void
fini()
{
I_Socket *i_socket = Singleton::Consume<I_Socket>::by<NginxMessageReader>();
i_socket->closeSocket(syslog_server_socket);
}
void
loadNginxMessageReaderConfig()
{
rate_limit_status_code = getProfileAgentSettingWithDefault<string>(
"429",
"accessControl.rateLimit.returnCode"
);
dbgTrace(D_NGINX_MESSAGE_READER) << "Selected rate-limit status code: " << rate_limit_status_code;
}
private:
enum class LogInfo {
HTTP_METHOD,
URI,
RESPONSE_CODE,
HOST,
SOURCE,
DESTINATION_IP,
DESTINATION_PORT,
EVENT_MESSAGE,
ASSET_ID,
ASSET_NAME,
RULE_NAME,
RULE_ID,
COUNT
};
void
initSyslogServerSocket()
{
dbgFlow(D_NGINX_MESSAGE_READER);
I_MainLoop *mainloop = Singleton::Consume<I_MainLoop>::by<NginxMessageReader>();
I_Socket *i_socket = Singleton::Consume<I_Socket>::by<NginxMessageReader>();
string nginx_syslog_server_address = getProfileAgentSettingWithDefault<string>(
"127.0.0.1:1514",
"reverseProxy.nginx.syslogAddress"
);
dbgInfo(D_NGINX_MESSAGE_READER) << "Attempting to open a socket: " << nginx_syslog_server_address;
do {
Maybe<I_Socket::socketFd> new_socket = i_socket->genSocket(
I_Socket::SocketType::UDP,
false,
true,
nginx_syslog_server_address
);
if (!new_socket.ok()) {
dbgError(D_NGINX_MESSAGE_READER) << "Failed to open a socket. Error: " << new_socket.getErr();
mainloop->yield(chrono::milliseconds(500));
continue;
}
if (new_socket.unpack() < 0) {
dbgError(D_NGINX_MESSAGE_READER)<< "Generated socket is OK yet negative";
mainloop->yield(chrono::milliseconds(500));
continue;
}
syslog_server_socket = new_socket.unpack();
dbgInfo(D_NGINX_MESSAGE_READER)
<< "Opened socket for nginx logs over syslog. Socket: "
<< syslog_server_socket;
} while (syslog_server_socket < 0);
}
void
handleNginxLogs()
{
dbgFlow(D_NGINX_MESSAGE_READER);
I_MainLoop::Routine read_logs =
[this] ()
{
Maybe<string> logs = getLogsFromSocket(syslog_server_socket);
if (!logs.ok()) {
dbgWarning(D_NGINX_MESSAGE_READER)
<< "Failed to get NGINX logs from the socket. Error: "
<< logs.getErr();
return;
}
string raw_logs_to_parse = logs.unpackMove();
vector<string> logs_to_parse = separateLogs(raw_logs_to_parse);
for (auto const &log: logs_to_parse) {
bool log_sent;
if (isAccessLog(log)) {
log_sent = sendAccessLog(log);
} else if (isAlertErrorLog(log) || isErrorLog(log)) {
log_sent = sendErrorLog(log);
} else {
dbgWarning(D_NGINX_MESSAGE_READER) << "Unexpected nginx log format";
continue;
}
if (!log_sent) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Failed to send Log to Infinity Portal";
} else {
dbgTrace(D_NGINX_MESSAGE_READER) << "Succesfully sent nginx log to Infinity Portal";
}
}
};
I_MainLoop *mainloop = Singleton::Consume<I_MainLoop>::by<NginxMessageReader>();
mainloop->addFileRoutine(
I_MainLoop::RoutineType::RealTime,
syslog_server_socket,
read_logs,
"Process nginx logs",
true
);
}
bool
sendAccessLog(const string &log)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Access log" << log;
Maybe<EnumArray<LogInfo, string>> log_info = parseAccessLog(log);
if (!log_info.ok()) {
dbgWarning(D_NGINX_MESSAGE_READER)
<< "Failed parsing the NGINX logs. Error: "
<< log_info.getErr();
return false;
}
auto unpacked_log_info = log_info.unpack();
if (unpacked_log_info[LogInfo::RESPONSE_CODE] == rate_limit_status_code) {
return sendRateLimitLog(unpacked_log_info);
}
return sendLog(unpacked_log_info);
}
bool
sendErrorLog(const string &log)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Error log" << log;
Maybe<EnumArray<LogInfo, string>> log_info = parseErrorLog(log);
if (!log_info.ok()) {
dbgWarning(D_NGINX_MESSAGE_READER)
<< "Failed parsing the NGINX logs. Error: "
<< log_info.getErr();
return false;
}
return sendLog(log_info.unpack());
}
bool
isAccessLog(const string &log) const
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Chekck if string contains \"accessLog\"" << log;
return log.find("accessLog") != string::npos;
}
bool
isAlertErrorLog(const string &log) const
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Check if log is of type 'error log'. Log: " << log;
return log.find("[alert]") != string::npos;
}
bool
isErrorLog(const string &log) const
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Check if log is of type 'error log'. Log: " << log;
return log.find("[error]") != string::npos;
}
bool
sendLog(const EnumArray<LogInfo, string> &log_info)
{
dbgFlow(D_NGINX_MESSAGE_READER);
string event_name;
switch (log_info[LogInfo::RESPONSE_CODE][0]) {
case '4': {
event_name = "Invalid request or incorrect reverse proxy configuration - Request dropped."
" Please check the reverse proxy configuration of your relevant assets";
break;
}
case '5': {
event_name = "AppSec Gateway reverse proxy error - Request dropped. "
"Please verify the reverse proxy configuration of your relevant assets. "
"If the issue persists please contact Check Point Support";
break;
}
default: {
dbgError(D_NGINX_MESSAGE_READER) << "Irrelevant status code";
return false;
}
}
dbgTrace(D_NGINX_MESSAGE_READER)
<< "Nginx log's event name and response code: "
<< event_name
<< ", "
<< log_info[LogInfo::RESPONSE_CODE];
LogGen log(
event_name,
ReportIS::Audience::SECURITY,
ReportIS::Severity::INFO,
ReportIS::Priority::LOW,
ReportIS::Tags::REVERSE_PROXY
);
log << LogField("eventConfidence", "High");
for (LogInfo field : makeRange<LogInfo>()) {
Maybe<string> string_field = convertLogFieldToString(field);
if (!string_field.ok()) {
dbgDebug(D_NGINX_MESSAGE_READER) << "Enum field was not converted: " << string_field.getErr();
return false;
}
if (field != LogInfo::DESTINATION_PORT) {
log << LogField(string_field.unpack(), log_info[field]);
continue;
}
try {
log << LogField(string_field.unpack(), stoi(log_info[field]));
} catch (const exception &e) {
dbgError(D_NGINX_MESSAGE_READER)
<< "Unable to convert port to numeric value: "
<< e.what();
log << LogField(string_field.unpack(), 0);
}
}
return true;
}
bool
sendRateLimitLog(const EnumArray<LogInfo, string> &log_info)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Getting rate-limit rules of asset ID: " << log_info[LogInfo::ASSET_ID];
ScopedContext rate_limit_ctx;
rate_limit_ctx.registerValue<GenericConfigId>(AssetMatcher::ctx_key, log_info[LogInfo::ASSET_ID]);
auto rate_limit_config = getConfiguration<RateLimitConfig>("rulebase", "rateLimit");
if (!rate_limit_config.ok()) {
dbgTrace(D_NGINX_MESSAGE_READER)
<< "Rate limit context does not match asset ID: " << log_info[LogInfo::ASSET_ID];
return false;
}
RateLimitConfig unpacked_rate_limit_config = rate_limit_config.unpack();
string nginx_uri = log_info[LogInfo::URI];
const LogTriggerConf &rate_limit_trigger = unpacked_rate_limit_config.getRateLimitTrigger(nginx_uri);
dbgTrace(D_NGINX_MESSAGE_READER)<< "About to generate NGINX rate-limit log";
string event_name = "Rate limit";
string security_action = "Drop";
bool is_log_required = false;
// Prevent events checkbox (in triggers)
if (rate_limit_trigger.isPreventLogActive(LogTriggerConf::SecurityType::AccessControl)) {
is_log_required = true;
}
if (!is_log_required) {
dbgTrace(D_NGINX_MESSAGE_READER) << "Not sending NGINX rate-limit log as it is not required";
return false;
}
ostringstream src_ip;
ostringstream dst_ip;
src_ip << log_info[LogInfo::SOURCE];
dst_ip << log_info[LogInfo::DESTINATION_IP];
ReportIS::Severity log_severity = ReportIS::Severity::MEDIUM;
ReportIS::Priority log_priority = ReportIS::Priority::MEDIUM;
LogGen log = rate_limit_trigger(
event_name,
LogTriggerConf::SecurityType::AccessControl,
log_severity,
log_priority,
true, // is drop
LogField("practiceType", "Rate Limit"),
ReportIS::Tags::RATE_LIMIT
);
for (LogInfo field : makeRange<LogInfo>()) {
Maybe<string> string_field = convertLogFieldToString(field);
if (!string_field.ok()) {
dbgDebug(D_NGINX_MESSAGE_READER) << "Enum field was not converted: " << string_field.getErr();
return false;
}
if (
field == LogInfo::HOST ||
field == LogInfo::URI ||
field == LogInfo::HTTP_METHOD ||
field == LogInfo::SOURCE ||
field == LogInfo::DESTINATION_IP ||
field == LogInfo::ASSET_ID ||
field == LogInfo::ASSET_NAME ||
field == LogInfo::RESPONSE_CODE
) {
if (!log_info[field].empty()) {
log << LogField(string_field.unpack(), log_info[field]);
continue;
}
}
if (field == LogInfo::DESTINATION_PORT) {
try {
int numeric_dst_port = stoi(log_info[field]);
log << LogField(string_field.unpack(), numeric_dst_port);
} catch (const exception &e) {
dbgWarning(D_NGINX_MESSAGE_READER)
<< "Unable to convert dst port: "
<< log_info[field]
<< " to numberic value. Error: "
<< e.what();
}
}
}
return true;
}
Maybe<string>
convertLogFieldToString(LogInfo field)
{
dbgFlow(D_NGINX_MESSAGE_READER);
switch (field) {
case LogInfo::HTTP_METHOD:
return string("httpMethod");
case LogInfo::URI:
return string("httpUriPath");
case LogInfo::RESPONSE_CODE:
return string("httpResponseCode");
case LogInfo::HOST:
return string("httpHostName");
case LogInfo::SOURCE:
return string("httpSourceId");
case LogInfo::DESTINATION_IP:
return string("destinationIp");
case LogInfo::DESTINATION_PORT:
return string("destinationPort");
case LogInfo::ASSET_ID:
return string("assetId");
case LogInfo::ASSET_NAME:
return string("assetName");
case LogInfo::EVENT_MESSAGE:
return string("httpResponseBody");
case LogInfo::RULE_ID:
return string("ruleId");
case LogInfo::RULE_NAME:
return string("ruleName");
case LogInfo::COUNT:
dbgError(D_NGINX_MESSAGE_READER) << "LogInfo::COUNT is not allowed";
return genError("LogInfo::COUNT is not allowed");
}
dbgError(D_NGINX_MESSAGE_READER) << "No Enum found, int value: " << static_cast<int>(field);
return genError("No Enum found");
}
static vector<string>
separateLogs(const string &raw_logs_to_parse)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "separating logs. logs: " << raw_logs_to_parse;
dbgTrace(D_NGINX_MESSAGE_READER) << "separateLogs start of function. Logs to parse: " << raw_logs_to_parse;
boost::smatch matcher;
vector<string> logs;
if (raw_logs_to_parse.empty()) return logs;
size_t pos = 0;
while (NGEN::Regex::regexSearch(__FILE__, __LINE__, raw_logs_to_parse.substr(pos), matcher, syslog_regex)) {
if (pos == 0) {
dbgTrace(D_NGINX_MESSAGE_READER) << "separateLogs pos = 0";
pos++;
continue;
}
auto log_length = matcher.position();
logs.push_back(raw_logs_to_parse.substr(pos - 1, log_length));
pos += log_length + 1;
}
logs.push_back(raw_logs_to_parse.substr(pos - 1));
dbgTrace(D_NGINX_MESSAGE_READER) << "separateLogs end of function";
return logs;
}
static pair<string, string>
parseErrorLogRequestField(const string &request)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "parsing request field. request: " << request;
string formatted_request = request;
vector<string> result;
boost::erase_all(formatted_request, "\"");
boost::erase_all(formatted_request, "\n");
boost::split(result, formatted_request, boost::is_any_of(" "), boost::token_compress_on);
const int http_method_index = 1;
const int uri_index = 2;
return pair<string, string>(result[http_method_index], result[uri_index]);
}
static string
parseErrorLogField(const string &field)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "parsing error log field " << field;
string formatted_field = field;
vector<string> result;
boost::erase_all(formatted_field, "\"");
boost::erase_all(formatted_field, "\n");
boost::split(result, formatted_field, boost::is_any_of(" "), boost::token_compress_on);
const int field_index = 1;
return result[field_index];
}
void
addContextFieldsToLogInfo(EnumArray<LogInfo, string> &log_info)
{
dbgFlow(D_NGINX_MESSAGE_READER);
ScopedContext ctx;
try {
ctx.registerValue<uint16_t>(
HttpTransactionData::listening_port_ctx,
static_cast<uint16_t>(stoi(log_info[LogInfo::DESTINATION_PORT]))
);
} catch (const exception &e) {
dbgError(D_NGINX_MESSAGE_READER) << "Failed register values for context " << e.what();
}
ctx.registerValue<string>(HttpTransactionData::host_name_ctx, log_info[LogInfo::HOST]);
ctx.registerValue<string>(HttpTransactionData::uri_ctx, log_info[LogInfo::URI]);
auto rule_by_ctx = getConfiguration<BasicRuleConfig>("rulebase", "rulesConfig");
if (!rule_by_ctx.ok()) {
dbgWarning(D_NGINX_MESSAGE_READER)
<< "AssetId was not found by the given context. Reason: "
<< rule_by_ctx.getErr();
return;
}
BasicRuleConfig context = rule_by_ctx.unpack();
log_info[LogInfo::ASSET_ID] = context.getAssetId();
log_info[LogInfo::ASSET_NAME] = context.getAssetName();
log_info[LogInfo::RULE_ID] = context.getRuleId();
log_info[LogInfo::RULE_NAME] = context.getRuleName();
}
Maybe<EnumArray<LogInfo, string>>
parseErrorLog(const string &log_line)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Handling log line:" << log_line;
string port;
EnumArray<LogInfo, string> log_info(EnumArray<LogInfo, string>::Fill(), string(""));
boost::smatch matcher;
vector<string> result;
if (
!NGEN::Regex::regexSearch(
__FILE__,
__LINE__,
log_line,
matcher,
isAlertErrorLog(log_line) ? alert_log_regex : error_log_regex
)
) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Unexpected nginx log format";
return genError("Unexpected nginx log format");
}
const int event_message_index = 6;
const int source_index = 7;
const int request_index = 9;
const int host_index = 11;
string host = string(matcher[host_index].first, matcher[host_index].second);
string source = string(matcher[source_index].first, matcher[source_index].second);
string event_message = string(matcher[event_message_index].first, matcher[event_message_index].second);
string request = string(matcher[request_index].first, matcher[request_index].second);
host = parseErrorLogField(host);
source = parseErrorLogField(source);
pair<string, string> parsed_request = parseErrorLogRequestField(request);
string http_method = parsed_request.first;
string uri = parsed_request.second;
if (NGEN::Regex::regexSearch(__FILE__, __LINE__, host, matcher, socket_address_regex)) {
int host_index = 1;
int port_index = 2;
host = string(matcher[host_index].first, matcher[host_index].second);
port = string(matcher[port_index].first, matcher[port_index].second);
} else if (NGEN::Regex::regexSearch(__FILE__, __LINE__, host, matcher, boost::regex("https://"))) {
port = "443";
} else {
port = "80";
}
log_info[LogInfo::HOST] = host;
log_info[LogInfo::URI] = uri;
log_info[LogInfo::RESPONSE_CODE] = "500";
log_info[LogInfo::HTTP_METHOD] = http_method;
log_info[LogInfo::SOURCE] = source;
log_info[LogInfo::DESTINATION_IP] = host;
log_info[LogInfo::DESTINATION_PORT] = port;
log_info[LogInfo::EVENT_MESSAGE] = event_message;
addContextFieldsToLogInfo(log_info);
if (!validateLog(log_info)) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Unexpected nginx log format";
return genError("Unexpected nginx log format");
}
return log_info;
}
Maybe<EnumArray<LogInfo, string>>
parseAccessLog(const string &log_line)
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Parsing log line: " << log_line;
string formatted_log = log_line;
EnumArray<LogInfo, string> log_info(EnumArray<LogInfo, string>::Fill(), string(""));
vector<string> result;
boost::erase_all(formatted_log, "\"");
boost::erase_all(formatted_log, "\n");
boost::split(result, formatted_log, boost::is_any_of(" "), boost::token_compress_on);
const int valid_log_size = 20;
if (result.size() < valid_log_size) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Unexpected nginx log format";
return genError("Unexpected nginx log format");
}
const int host_index = 6;
const int host_port_index = 7;
const int http_method_index = 13;
const int uri_index = 14;
const int response_cod_index = 16;
const int source_index = 8;
log_info[LogInfo::HOST] = result[host_index];
log_info[LogInfo::URI] = result[uri_index];
log_info[LogInfo::RESPONSE_CODE] = result[response_cod_index];
log_info[LogInfo::HTTP_METHOD] = result[http_method_index];
log_info[LogInfo::SOURCE] = result[source_index];
log_info[LogInfo::DESTINATION_IP] = result[host_index];
log_info[LogInfo::DESTINATION_PORT] = result[host_port_index];
log_info[LogInfo::EVENT_MESSAGE] = "Invalid request or incorrect reverse proxy configuration - "
"Request dropped. Please check the reverse proxy configuration of your relevant assets";
addContextFieldsToLogInfo(log_info);
if (!validateLog(log_info)) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Unexpected nginx log format";
return genError("Unexpected nginx log format");
}
return log_info;
}
static bool
validateLog(const EnumArray<LogInfo, string> &log_info)
{
dbgFlow(D_NGINX_MESSAGE_READER);
boost::smatch matcher;
if (!NGEN::Regex::regexSearch(__FILE__, __LINE__, log_info[LogInfo::HOST], matcher, server_regex)) {
dbgTrace(D_NGINX_MESSAGE_READER) << "Could not validate server (Host): " << log_info[LogInfo::HOST];
return false;
}
if (!NGEN::Regex::regexSearch(__FILE__, __LINE__, log_info[LogInfo::URI], matcher, uri_regex)) {
dbgTrace(D_NGINX_MESSAGE_READER) << "Could not validate Uri: " << log_info[LogInfo::URI];
return false;
}
if (
!NGEN::Regex::regexSearch(
__FILE__,
__LINE__,
log_info[LogInfo::RESPONSE_CODE],
matcher, response_code_regex
)
) {
dbgTrace(D_NGINX_MESSAGE_READER)
<< "Could not validate response code: "
<< log_info[LogInfo::RESPONSE_CODE];
return false;
}
if (
!NGEN::Regex::regexSearch(__FILE__, __LINE__, log_info[LogInfo::HTTP_METHOD], matcher, http_method_regex)
) {
dbgTrace(D_NGINX_MESSAGE_READER) << "Could not validate HTTP method: " << log_info[LogInfo::HTTP_METHOD];
return false;
}
if (!NGEN::Regex::regexSearch(__FILE__, __LINE__, log_info[LogInfo::DESTINATION_PORT], matcher, port_regex)) {
dbgTrace(D_NGINX_MESSAGE_READER)
<< "Could not validate destination port : "
<< log_info[LogInfo::DESTINATION_PORT];
return false;
}
if (!NGEN::Regex::regexSearch(__FILE__, __LINE__, log_info[LogInfo::SOURCE], matcher, server_regex)) {
dbgTrace(D_NGINX_MESSAGE_READER) << "Could not validate source : " << log_info[LogInfo::SOURCE];
return false;
}
return true;
}
Maybe<string>
getLogsFromSocket(const I_Socket::socketFd &client_socket) const
{
dbgFlow(D_NGINX_MESSAGE_READER) << "Reading logs from socket. fd: " << client_socket;
I_Socket *i_socket = Singleton::Consume<I_Socket>::by<NginxMessageReader>();
Maybe<vector<char>> raw_log_data = i_socket->receiveData(client_socket, 0, false);
if (!raw_log_data.ok()) {
dbgWarning(D_NGINX_MESSAGE_READER) << "Error receiving data from socket";
return genError("Error receiving data from socket");
}
string raw_log(raw_log_data.unpack().begin(), raw_log_data.unpack().end());
return move(raw_log);
}
I_Socket::socketFd syslog_server_socket = -1;
string rate_limit_status_code = "429";
};
NginxMessageReader::NginxMessageReader() : Component("NginxMessageReader"), pimpl(make_unique<Impl>()) {}
NginxMessageReader::~NginxMessageReader() {}
void
NginxMessageReader::init()
{
pimpl->init();
}
void
NginxMessageReader::preload()
{
pimpl->preload();
}
void
NginxMessageReader::fini()
{
pimpl->fini();
}

View File

@@ -5,3 +5,4 @@ add_subdirectory(local_policy_mgmt_gen)
add_subdirectory(orchestration)
add_subdirectory(rate_limit)
add_subdirectory(waap)
add_subdirectory(central_nginx_manager)

View File

@@ -0,0 +1,3 @@
include_directories(include)
add_library(central_nginx_manager central_nginx_manager.cc lets_encrypt_listener.cc)

View File

@@ -0,0 +1,418 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "central_nginx_manager.h"
#include "lets_encrypt_listener.h"
#include <string>
#include <vector>
#include <cereal/external/base64.hpp>
#include "debug.h"
#include "config.h"
#include "rest.h"
#include "log_generator.h"
#include "nginx_utils.h"
#include "agent_core_utilities.h"
using namespace std;
USE_DEBUG_FLAG(D_NGINX_MANAGER);
class CentralNginxConfig
{
public:
void load(cereal::JSONInputArchive &ar)
{
try {
string nginx_conf_base64;
ar(cereal::make_nvp("id", file_id));
ar(cereal::make_nvp("name", file_name));
ar(cereal::make_nvp("data", nginx_conf_base64));
nginx_conf_content = cereal::base64::decode(nginx_conf_base64);
central_nginx_conf_path = getCentralNginxConfPath();
shared_config_path = getSharedConfigPath();
if (!nginx_conf_content.empty()) configureCentralNginx();
} catch (const cereal::Exception &e) {
dbgDebug(D_NGINX_MANAGER) << "Could not load Central Management Config JSON. Error: " << e.what();
ar.setNextName(nullptr);
}
}
const string & getFileId() const { return file_id; }
const string & getFileName() const { return file_name; }
const string & getFileContent() const { return nginx_conf_content; }
static string
getCentralNginxConfPath()
{
string central_nginx_conf_path = getProfileAgentSettingWithDefault<string>(
string("/tmp/central_nginx.conf"),
"centralNginxManagement.confDownloadPath"
);
dbgInfo(D_NGINX_MANAGER) << "Central NGINX configuration path: " << central_nginx_conf_path;
return central_nginx_conf_path;
}
static string
getSharedConfigPath()
{
string central_shared_conf_path = getConfigurationWithDefault<string>(
"/etc/cp/conf",
"Config Component",
"configuration path"
);
central_shared_conf_path += "/centralNginxManager/shared/central_nginx_shared.conf";
dbgInfo(D_NGINX_MANAGER) << "Shared NGINX configuration path: " << central_shared_conf_path;
return central_shared_conf_path;
}
private:
void
loadAttachmentModule()
{
string attachment_module_path = NginxUtils::getModulesPath() + "/ngx_cp_attachment_module.so";
if (!NGEN::Filesystem::exists(attachment_module_path)) {
dbgTrace(D_NGINX_MANAGER) << "Attachment module " << attachment_module_path << " does not exist";
return;
}
string attachment_module_conf = "load_module " + attachment_module_path + ";";
if (nginx_conf_content.find(attachment_module_conf) != string::npos) {
dbgTrace(D_NGINX_MANAGER) << "Attachment module " << attachment_module_path << " already loaded";
return;
}
nginx_conf_content = attachment_module_conf + "\n" + nginx_conf_content;
}
Maybe<void>
loadSharedDirective(const string &directive)
{
dbgFlow(D_NGINX_MANAGER) << "Loading shared directive into the servers " << directive;
if (!NGEN::Filesystem::copyFile(shared_config_path, shared_config_path + ".bak", true)) {
return genError("Could not create a backup of the shared NGINX configuration file");
}
ifstream shared_config(shared_config_path);
if (!shared_config.is_open()) {
return genError("Could not open shared NGINX configuration file");
}
string shared_config_content((istreambuf_iterator<char>(shared_config)), istreambuf_iterator<char>());
shared_config.close();
if (shared_config_content.find(directive) != string::npos) {
dbgTrace(D_NGINX_MANAGER) << "Shared directive " << directive << " already loaded";
return {};
}
ofstream new_shared_config(shared_config_path, ios::app);
if (!new_shared_config.is_open()) {
return genError("Could not open shared NGINX configuration file");
}
dbgTrace(D_NGINX_MANAGER) << "Adding shared directive " << directive;
new_shared_config << directive << "\n";
new_shared_config.close();
auto validation = NginxUtils::validateNginxConf(central_nginx_conf_path);
if (!validation.ok()) {
if (!NGEN::Filesystem::copyFile(shared_config_path + ".bak", shared_config_path, true)) {
return genError("Could not restore the shared NGINX configuration file");
}
return genError("Could not validate shared NGINX configuration file. Error: " + validation.getErr());
}
return {};
}
Maybe<void>
loadSharedConfig()
{
dbgFlow(D_NGINX_MANAGER) << "Loading shared configuration into the servers";
ofstream shared_config(shared_config_path);
if (!shared_config.is_open()) {
return genError("Could not create shared NGINX configuration file");
}
shared_config.close();
string shared_config_directive = "include " + shared_config_path + ";\n";
boost::regex server_regex("server\\s*\\{");
nginx_conf_content = NGEN::Regex::regexReplace(
__FILE__,
__LINE__,
nginx_conf_content,
server_regex,
"server {\n" + shared_config_directive
);
ofstream nginx_conf_file(central_nginx_conf_path);
if (!nginx_conf_file.is_open()) {
return genError("Could not open a temporary central NGINX configuration file");
}
nginx_conf_file << nginx_conf_content;
nginx_conf_file.close();
auto validation = NginxUtils::validateNginxConf(central_nginx_conf_path);
if (!validation.ok()) {
return genError("Could not validate central NGINX configuration file. Error: " + validation.getErr());
}
return {};
}
Maybe<void>
configureSyslog()
{
if (!getProfileAgentSettingWithDefault<bool>(false, "centralNginxManagement.syslogEnabled")) {
dbgTrace(D_NGINX_MANAGER) << "Syslog is disabled via settings";
return {};
}
string syslog_directive = "error_log syslog:server=127.0.0.1:1514 warn;";
auto load_shared_directive_result = loadSharedDirective(syslog_directive);
if (!load_shared_directive_result.ok()) {
return genError("Could not configure syslog directive, error: " + load_shared_directive_result.getErr());
}
return {};
}
Maybe<void>
saveBaseCentralNginxConf()
{
ofstream central_nginx_conf_base_file(central_nginx_conf_path + ".base");
if (!central_nginx_conf_base_file.is_open()) {
return genError("Could not open a temporary central NGINX configuration file");
}
central_nginx_conf_base_file << nginx_conf_content;
central_nginx_conf_base_file.close();
return {};
}
void
configureCentralNginx()
{
loadAttachmentModule();
auto save_base_nginx_conf = saveBaseCentralNginxConf();
if (!save_base_nginx_conf.ok()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not save base NGINX configuration. Error: "
<< save_base_nginx_conf.getErr();
return;
}
string nginx_conf_content_backup = nginx_conf_content;
auto shared_config_result = loadSharedConfig();
if (!shared_config_result.ok()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not load shared configuration. Error: "
<< shared_config_result.getErr();
nginx_conf_content = nginx_conf_content_backup;
return;
}
auto syslog_result = configureSyslog();
if (!syslog_result.ok()) {
dbgWarning(D_NGINX_MANAGER) << "Could not configure syslog. Error: " << syslog_result.getErr();
}
}
string file_id;
string file_name;
string nginx_conf_content;
string central_nginx_conf_path;
string shared_config_path;
};
class CentralNginxManager::Impl
{
public:
void
init()
{
dbgInfo(D_NGINX_MANAGER) << "Starting Central NGINX Manager";
string main_nginx_conf_path = NginxUtils::getMainNginxConfPath();
if (
NGEN::Filesystem::exists(main_nginx_conf_path)
&& !NGEN::Filesystem::exists(main_nginx_conf_path + ".orig")
) {
dbgInfo(D_NGINX_MANAGER) << "Creating a backup of the original main NGINX configuration file";
NGEN::Filesystem::copyFile(main_nginx_conf_path, main_nginx_conf_path + ".orig", true);
}
i_mainloop = Singleton::Consume<I_MainLoop>::by<CentralNginxManager>();
if (!lets_encrypt_listener.init()) {
dbgWarning(D_NGINX_MANAGER) << "Could not start Lets Encrypt Listener, scheduling retry";
i_mainloop->addOneTimeRoutine(
I_MainLoop::RoutineType::System,
[this] ()
{
while(!lets_encrypt_listener.init()) {
dbgWarning(D_NGINX_MANAGER) << "Could not start Lets Encrypt Listener, will retry";
i_mainloop->yield(chrono::seconds(5));
}
},
"Lets Encrypt Listener initializer",
false
);
}
}
void
loadPolicy()
{
auto central_nginx_config = getSetting<vector<CentralNginxConfig>>("centralNginxManagement");
if (!central_nginx_config.ok() || central_nginx_config.unpack().empty()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not load Central NGINX Management settings. Error: "
<< central_nginx_config.getErr();
return;
}
auto &config = central_nginx_config.unpack().front();
if (config.getFileContent().empty()) {
dbgWarning(D_NGINX_MANAGER) << "Empty NGINX configuration file";
return;
}
dbgTrace(D_NGINX_MANAGER)
<< "Handling Central NGINX Management settings: "
<< config.getFileId()
<< ", "
<< config.getFileName()
<< ", "
<< config.getFileContent();
string central_nginx_conf_path = config.getCentralNginxConfPath();
ofstream central_nginx_conf_file(central_nginx_conf_path);
if (!central_nginx_conf_file.is_open()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not open central NGINX configuration file: "
<< central_nginx_conf_path;
return;
}
central_nginx_conf_file << config.getFileContent();
central_nginx_conf_file.close();
auto validation_result = NginxUtils::validateNginxConf(central_nginx_conf_path);
if (!validation_result.ok()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not validate central NGINX configuration file. Error: "
<< validation_result.getErr();
logError(validation_result.getErr());
return;
}
dbgTrace(D_NGINX_MANAGER) << "Validated central NGINX configuration file";
auto reload_result = NginxUtils::reloadNginx(central_nginx_conf_path);
if (!reload_result.ok()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not reload central NGINX configuration. Error: "
<< reload_result.getErr();
logError("Could not reload central NGINX configuration. Error: " + reload_result.getErr());
return;
}
logInfo("Central NGINX configuration has been successfully reloaded");
}
void
fini()
{
string central_nginx_base_path = CentralNginxConfig::getCentralNginxConfPath() + ".base";
if (!NGEN::Filesystem::exists(central_nginx_base_path)) {
dbgWarning(D_NGINX_MANAGER) << "Could not find base NGINX configuration file: " << central_nginx_base_path;
return;
}
NginxUtils::reloadNginx(central_nginx_base_path);
}
private:
void
logError(const string &error)
{
LogGen log(
error,
ReportIS::Level::ACTION,
ReportIS::Audience::SECURITY,
ReportIS::Severity::CRITICAL,
ReportIS::Priority::URGENT,
ReportIS::Tags::POLICY_INSTALLATION
);
log.addToOrigin(LogField("eventTopic", "Central NGINX Management"));
log << LogField("notificationId", "4165c3b1-e9bc-44c3-888b-863e204c1bfb");
log << LogField(
"eventRemediation",
"Please verify your NGINX configuration and enforce policy again. "
"Contact Check Point support if the issue persists."
);
}
void
logInfo(const string &info)
{
LogGen log(
info,
ReportIS::Level::ACTION,
ReportIS::Audience::SECURITY,
ReportIS::Severity::INFO,
ReportIS::Priority::LOW,
ReportIS::Tags::POLICY_INSTALLATION
);
log.addToOrigin(LogField("eventTopic", "Central NGINX Management"));
log << LogField("notificationId", "4165c3b1-e9bc-44c3-888b-863e204c1bfb");
log << LogField("eventRemediation", "No action required");
}
I_MainLoop *i_mainloop = nullptr;
LetsEncryptListener lets_encrypt_listener;
};
CentralNginxManager::CentralNginxManager()
:
Component("Central NGINX Manager"),
pimpl(make_unique<CentralNginxManager::Impl>()) {}
CentralNginxManager::~CentralNginxManager() {}
void
CentralNginxManager::init()
{
pimpl->init();
}
void
CentralNginxManager::fini()
{
pimpl->fini();
}
void
CentralNginxManager::preload()
{
registerExpectedSetting<vector<CentralNginxConfig>>("centralNginxManagement");
registerExpectedConfiguration<string>("Config Component", "configuration path");
registerConfigLoadCb([this]() { pimpl->loadPolicy(); });
}

View File

@@ -0,0 +1,30 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __LETS_ENCRYPT_HANDLER_H__
#define __LETS_ENCRYPT_HANDLER_H__
#include <string>
#include "maybe_res.h"
class LetsEncryptListener
{
public:
bool init();
private:
Maybe<std::string> getChallengeValue(const std::string &uri) const;
};
#endif // __LETS_ENCRYPT_HANDLER_H__

View File

@@ -0,0 +1,76 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "lets_encrypt_listener.h"
#include <string>
#include "central_nginx_manager.h"
#include "debug.h"
using namespace std;
USE_DEBUG_FLAG(D_NGINX_MANAGER);
bool
LetsEncryptListener::init()
{
dbgInfo(D_NGINX_MANAGER) << "Starting Lets Encrypt Listener";
return Singleton::Consume<I_RestApi>::by<CentralNginxManager>()->addWildcardGetCall(
".well-known/acme-challenge/",
[&] (const string &uri) -> string
{
Maybe<string> maybe_challenge_value = getChallengeValue(uri);
if (!maybe_challenge_value.ok()) {
dbgWarning(D_NGINX_MANAGER)
<< "Could not get challenge value for uri: "
<< uri
<< ", error: "
<< maybe_challenge_value.getErr();
return string{""};
};
dbgTrace(D_NGINX_MANAGER) << "Got challenge value: " << maybe_challenge_value.unpack();
return maybe_challenge_value.unpack();
}
);
}
Maybe<string>
LetsEncryptListener::getChallengeValue(const string &uri) const
{
string challenge_key = uri.substr(uri.find_last_of('/') + 1);
string api_query = "/api/lets-encrypt-challenge?http_challenge_key=" + challenge_key;
dbgInfo(D_NGINX_MANAGER) << "Getting challenge value via: " << api_query;
MessageMetadata md;
md.insertHeader("X-Tenant-Id", Singleton::Consume<I_AgentDetails>::by<CentralNginxManager>()->getTenantId());
Maybe<HTTPResponse, HTTPResponse> maybe_http_challenge_value =
Singleton::Consume<I_Messaging>::by<CentralNginxManager>()->sendSyncMessage(
HTTPMethod::GET,
api_query,
string("{}"),
MessageCategory::GENERIC,
md
);
if (!maybe_http_challenge_value.ok()) return genError(maybe_http_challenge_value.getErr().getBody());
string challenge_value = maybe_http_challenge_value.unpack().getBody();
if (!challenge_value.empty() && challenge_value.front() == '"' && challenge_value.back() == '"') {
challenge_value = challenge_value.substr(1, challenge_value.size() - 2);
}
return challenge_value;
}

View File

@@ -88,9 +88,17 @@ public:
dbgWarning(D_GEO_FILTER) << "failed to get source ip from env";
return EventVerdict(default_action);
}
auto source_ip = convertIpAddrToString(maybe_source_ip.unpack());
ip_set.insert(source_ip);
// saas profile setting
bool ignore_source_ip =
getProfileAgentSettingWithDefault<bool>(false, "agent.geoProtaction.ignoreSourceIP");
if (ignore_source_ip){
dbgDebug(D_GEO_FILTER) << "Geo protection ignoring source ip: " << source_ip;
} else {
ip_set.insert(convertIpAddrToString(maybe_source_ip.unpack()));
}
ngx_http_cp_verdict_e exception_verdict = getExceptionVerdict(ip_set);
if (exception_verdict != ngx_http_cp_verdict_e::TRAFFIC_VERDICT_IRRELEVANT) {
@@ -343,7 +351,7 @@ private:
auto asset_location = i_geo_location->lookupLocation(maybe_source_ip.unpack());
if (!asset_location.ok()) {
dbgWarning(D_GEO_FILTER) << "Lookup location failed for source: " <<
dbgDebug(D_GEO_FILTER) << "Lookup location failed for source: " <<
source <<
", Error: " <<
asset_location.getErr();

View File

@@ -336,9 +336,16 @@ public:
return metadata.getYear();
}
bool
isOk() const
{
return is_loaded;
}
private:
IPSSignatureMetaData metadata;
std::shared_ptr<BaseSignature> rule;
bool is_loaded;
};
/// \class SignatureAndAction

View File

@@ -219,10 +219,16 @@ IPSSignatureMetaData::getYear() const
void
CompleteSignature::load(cereal::JSONInputArchive &ar)
{
ar(cereal::make_nvp("protectionMetadata", metadata));
RuleDetection rule_detection(metadata.getName());
ar(cereal::make_nvp("detectionRules", rule_detection));
rule = rule_detection.getRule();
try {
ar(cereal::make_nvp("protectionMetadata", metadata));
RuleDetection rule_detection(metadata.getName());
ar(cereal::make_nvp("detectionRules", rule_detection));
rule = rule_detection.getRule();
is_loaded = true;
} catch (cereal::Exception &e) {
is_loaded = false;
dbgWarning(D_IPS) << "Failed to load signature: " << e.what();
}
}
MatchType
@@ -367,7 +373,16 @@ SignatureAndAction::matchSilent(const Buffer &sample) const
if (method.ok()) log << LogField("httpMethod", method.unpack());
auto path = env->get<Buffer>("HTTP_PATH_DECODED");
if (path.ok()) log << LogField("httpUriPath", getSubString(path, 1536), LogFieldOption::XORANDB64);
if (path.ok()) {
log << LogField("httpUriPath", getSubString(path, 1536), LogFieldOption::XORANDB64);
} else {
auto transaction_path = env->get<string>(HttpTransactionData::uri_path_decoded);
if (transaction_path.ok()) {
auto uri_path = transaction_path.unpack();
auto question_mark = uri_path.find('?');
log << LogField("httpUriPath", uri_path.substr(0, question_mark), LogFieldOption::XORANDB64);
}
}
auto req_header = ips_state.getTransactionData(IPSCommonTypes::requests_header_for_log);
if (req_header.ok()) log << LogField("httpRequestHeaders", getSubString(req_header), LogFieldOption::XORANDB64);
@@ -485,13 +500,30 @@ SignatureAndAction::isMatchedPrevent(const Buffer &context_buffer, const set<PMP
auto method = env->get<string>(HttpTransactionData::method_ctx);
if (method.ok()) log << LogField("httpMethod", method.unpack());
uint max_size = getConfigurationWithDefault<uint>(1536, "IPS", "Max Field Size");
auto path = env->get<Buffer>("HTTP_PATH_DECODED");
if (path.ok() && trigger.isWebLogFieldActive(url_path)) {
log << LogField("httpUriPath", getSubString(path, max_size), LogFieldOption::XORANDB64);
if (trigger.isWebLogFieldActive(url_path)) {
auto path = env->get<Buffer>("HTTP_PATH_DECODED");
if (path.ok()) {
log << LogField("httpUriPath", getSubString(path, max_size), LogFieldOption::XORANDB64);
} else {
auto transaction_path = env->get<string>(HttpTransactionData::uri_path_decoded);
if (transaction_path.ok()) {
auto uri_path = transaction_path.unpack();
auto question_mark = uri_path.find('?');
log << LogField("httpUriPath", uri_path.substr(0, question_mark), LogFieldOption::XORANDB64);
}
}
}
auto query = env->get<Buffer>("HTTP_QUERY_DECODED");
if (query.ok() && trigger.isWebLogFieldActive(url_query)) {
log << LogField("httpUriQuery", getSubString(query, max_size), LogFieldOption::XORANDB64);
if (trigger.isWebLogFieldActive(url_query)) {
auto query = env->get<Buffer>("HTTP_QUERY_DECODED");
if (query.ok()) {
log << LogField("httpUriQuery", getSubString(query, max_size), LogFieldOption::XORANDB64);
} else {
auto transaction_query = env->get<string>(HttpTransactionData::uri_query_decoded);
if (transaction_query.ok()) {
log << LogField("httpUriQuery", transaction_query.unpack());
}
}
}
auto res_code = env->get<Buffer>("HTTP_RESPONSE_CODE");
@@ -533,7 +565,9 @@ IPSSignaturesResource::load(cereal::JSONInputArchive &ar)
all_signatures.reserve(sigs.size());
for (auto &sig : sigs) {
all_signatures.emplace_back(make_shared<CompleteSignature>(move(sig)));
if (sig.isOk()) {
all_signatures.emplace_back(make_shared<CompleteSignature>(move(sig)));
}
}
}

View File

@@ -104,6 +104,12 @@ public:
cereal::JSONInputArchive ar(ss);
high_medium_confidance_signatures.load(ar);
}
{
stringstream ss;
ss << "[" << signature_performance_high << ", " << signature_broken << "]";
cereal::JSONInputArchive ar(ss);
single_broken_signature.load(ar);
}
}
~SignatureTest()
@@ -250,6 +256,7 @@ public:
IPSSignaturesResource performance_signatures1;
IPSSignaturesResource performance_signatures2;
IPSSignaturesResource performance_signatures3;
IPSSignaturesResource single_broken_signature;
NiceMock<MockTable> table;
MockAgg mock_agg;
@@ -483,6 +490,26 @@ private:
"\"context\": [\"HTTP_REQUEST_BODY\", \"HTTP_RESPONSE_BODY\"]"
"}"
"}";
string signature_broken =
"{"
"\"protectionMetadata\": {"
"\"protectionName\": \"BrokenTest\","
"\"maintrainId\": \"101\","
"\"severity\": \"Medium High\","
"\"confidenceLevel\": \"Low\","
"\"performanceImpact\": \"High\","
"\"lastUpdate\": \"20210420\","
"\"tags\": [],"
"\"cveList\": []"
"},"
"\"detectionRules\": {"
"\"type\": \"simple\","
"\"SSM\": \"\","
"\"keywosrds\": \"data: \\\"www\\\";\","
"\"context\": [\"HTTP_REQUEST_BODY\", \"HTTP_RESPONSE_BODY\"]"
"}"
"}";
};
TEST_F(SignatureTest, basic_load_of_signatures)
@@ -665,3 +692,14 @@ TEST_F(SignatureTest, high_confidance_signatures_matching)
expectLog("\"protectionId\": \"Test4\"", "\"matchedSignatureConfidence\": \"Medium\"");
EXPECT_FALSE(checkData("mmm"));
}
TEST_F(SignatureTest, broken_signature)
{
load(single_broken_signature, "Low or above", "Low");
EXPECT_FALSE(checkData("ggg"));
expectLog("\"matchedSignaturePerformance\": \"High\"");
EXPECT_TRUE(checkData("fff"));
EXPECT_FALSE(checkData("www"));
}

View File

@@ -22,4 +22,5 @@ add_library(local_policy_mgmt_gen
access_control_practice.cc
configmaps.cc
reverse_proxy_section.cc
policy_activation_data.cc
)

View File

@@ -497,7 +497,8 @@ WebAppSection::WebAppSection(
const AppsecPracticeAntiBotSection &_anti_bots,
const LogTriggerSection &parsed_log_trigger,
const AppSecTrustedSources &parsed_trusted_sources,
const NewAppSecWebAttackProtections &protections)
const NewAppSecWebAttackProtections &protections,
const vector<InnerException> &exceptions)
:
application_urls(_application_urls),
asset_id(_asset_id),
@@ -541,6 +542,10 @@ WebAppSection::WebAppSection(
overrides.push_back(AppSecOverride(source_ident));
}
for (const auto &exception : exceptions) {
overrides.push_back(AppSecOverride(exception));
}
}
// LCOV_EXCL_STOP

View File

@@ -298,7 +298,8 @@ public:
const AppsecPracticeAntiBotSection &_anti_bots,
const LogTriggerSection &parsed_log_trigger,
const AppSecTrustedSources &parsed_trusted_sources,
const NewAppSecWebAttackProtections &protections);
const NewAppSecWebAttackProtections &protections,
const std::vector<InnerException> &exceptions);
void save(cereal::JSONOutputArchive &out_ar) const;

View File

@@ -48,7 +48,7 @@ public:
void init();
std::tuple<std::map<std::string, AppsecLinuxPolicy>, std::map<std::string, V1beta2AppsecLinuxPolicy>>
createAppsecPoliciesFromIngresses();
createAppsecPolicies();
void getClusterId() const;
private:
@@ -101,12 +101,18 @@ private:
) const;
template<class T, class K>
void createPolicy(
void createPolicyFromIngress(
T &appsec_policy,
std::map<std::string, T> &policies,
std::map<AnnotationKeys, std::string> &annotations_values,
const SingleIngressData &item) const;
template<class T, class K>
void createPolicyFromActivation(
T &appsec_policy,
std::map<std::string, T> &policies,
const EnabledPolicy &policy) const;
std::tuple<Maybe<AppsecLinuxPolicy>, Maybe<V1beta2AppsecLinuxPolicy>> createAppsecPolicyK8s(
const std::string &policy_name,
const std::string &ingress_mode

View File

@@ -0,0 +1,89 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __POLICY_ACTIVATION_DATA_H__
#define __POLICY_ACTIVATION_DATA_H__
#include <vector>
#include <map>
#include "config.h"
#include "debug.h"
#include "rest.h"
#include "cereal/archives/json.hpp"
#include <cereal/types/map.hpp>
#include "customized_cereal_map.h"
#include "local_policy_common.h"
class PolicyActivationMetadata
{
public:
void load(cereal::JSONInputArchive &archive_in);
private:
std::string name;
};
class EnabledPolicy
{
public:
void load(cereal::JSONInputArchive &archive_in);
const std::string & getName() const;
const std::vector<std::string> & getHosts() const;
private:
std::string name;
std::vector<std::string> hosts;
};
class PolicyActivationSpec
{
public:
void load(cereal::JSONInputArchive &archive_in);
const std::vector<EnabledPolicy> & getPolicies() const;
private:
std::string appsec_class_name;
std::vector<EnabledPolicy> policies;
};
class SinglePolicyActivationData
{
public:
void load(cereal::JSONInputArchive &archive_in);
const PolicyActivationSpec & getSpec() const;
private:
std::string api_version;
std::string kind;
PolicyActivationMetadata metadata;
PolicyActivationSpec spec;
};
class PolicyActivationData : public ClientRest
{
public:
bool loadJson(const std::string &json);
const std::vector<SinglePolicyActivationData> & getItems() const;
private:
std::string api_version;
std::vector<SinglePolicyActivationData> items;
};
#endif // __POLICY_ACTIVATION_DATA_H__

View File

@@ -32,6 +32,7 @@
#include "i_messaging.h"
#include "appsec_practice_section.h"
#include "ingress_data.h"
#include "policy_activation_data.h"
#include "settings_section.h"
#include "triggers_section.h"
#include "local_policy_common.h"
@@ -205,7 +206,8 @@ private:
const RulesConfigRulebase& rule_config,
const std::string &practice_id, const std::string &full_url,
const std::string &default_mode,
std::map<AnnotationTypes, std::string> &rule_annotations
std::map<AnnotationTypes, std::string> &rule_annotations,
std::vector<InnerException>
);
void

View File

@@ -577,7 +577,7 @@ K8sPolicyUtils::createAppsecPolicyK8s(const string &policy_name, const string &i
template<class T, class K>
void
K8sPolicyUtils::createPolicy(
K8sPolicyUtils::createPolicyFromIngress(
T &appsec_policy,
map<std::string, T> &policies,
map<AnnotationKeys, string> &annotations_values,
@@ -615,10 +615,35 @@ K8sPolicyUtils::createPolicy(
}
}
std::tuple<map<string, AppsecLinuxPolicy>, map<string, V1beta2AppsecLinuxPolicy>>
K8sPolicyUtils::createAppsecPoliciesFromIngresses()
template<class T, class K>
void
K8sPolicyUtils::createPolicyFromActivation(
T &appsec_policy,
map<std::string, T> &policies,
const EnabledPolicy &policy) const
{
dbgFlow(D_LOCAL_POLICY) << "Getting all policy object from Ingresses";
if (policies.find(policy.getName()) == policies.end()) {
policies[policy.getName()] = appsec_policy;
}
auto default_mode = appsec_policy.getAppsecPolicySpec().getDefaultRule().getMode();
for (const string &host : policy.getHosts()) {
if (!appsec_policy.getAppsecPolicySpec().isAssetHostExist(host)) {
dbgTrace(D_LOCAL_POLICY)
<< "Inserting Host data to the specific asset set:"
<< "URL: '"
<< host
<< "'";
K ingress_rule = K(host, default_mode);
policies[policy.getName()].addSpecificRule(ingress_rule);
}
}
}
std::tuple<map<string, AppsecLinuxPolicy>, map<string, V1beta2AppsecLinuxPolicy>>
K8sPolicyUtils::createAppsecPolicies()
{
dbgFlow(D_LOCAL_POLICY) << "Getting all policy object from Ingresses and PolicyActivation";
map<string, AppsecLinuxPolicy> v1bet1_policies;
map<string, V1beta2AppsecLinuxPolicy> v1bet2_policies;
auto maybe_ingress = getObjectFromCluster<IngressData>("/apis/networking.k8s.io/v1/ingresses");
@@ -628,7 +653,7 @@ K8sPolicyUtils::createAppsecPoliciesFromIngresses()
dbgWarning(D_LOCAL_POLICY)
<< "Failed to retrieve K8S Ingress configurations. Error: "
<< maybe_ingress.getErr();
return make_tuple(v1bet1_policies, v1bet2_policies);
maybe_ingress = IngressData{};
}
@@ -658,19 +683,54 @@ K8sPolicyUtils::createAppsecPoliciesFromIngresses()
if (!std::get<0>(maybe_appsec_policy).ok()) {
auto appsec_policy=std::get<1>(maybe_appsec_policy).unpack();
createPolicy<V1beta2AppsecLinuxPolicy, NewParsedRule>(
createPolicyFromIngress<V1beta2AppsecLinuxPolicy, NewParsedRule>(
appsec_policy,
v1bet2_policies,
annotations_values,
item);
} else {
auto appsec_policy=std::get<0>(maybe_appsec_policy).unpack();
createPolicy<AppsecLinuxPolicy, ParsedRule>(
createPolicyFromIngress<AppsecLinuxPolicy, ParsedRule>(
appsec_policy,
v1bet1_policies,
annotations_values,
item);
}
}
string ns_suffix = getAppSecScopeType() == "namespaced" ? "ns" : "";
string ns = getAppSecScopeType() == "namespaced" ? "namespaces/" : "";
auto maybe_policy_activation = getObjectFromCluster<PolicyActivationData>(
"/apis/openappsec.io/v1beta2/" + ns + agent_ns + "policyactivations" + ns_suffix
);
if (!maybe_policy_activation.ok()) {
dbgWarning(D_LOCAL_POLICY)
<< "Failed to retrieve K8S PolicyActivation configurations. Error: "
<< maybe_policy_activation.getErr();
return make_tuple(v1bet1_policies, v1bet2_policies);
}
PolicyActivationData policy_activation = maybe_policy_activation.unpack();
for (const SinglePolicyActivationData &item : policy_activation.getItems()) {
for (const auto &policy : item.getSpec().getPolicies()) {
auto maybe_appsec_policy = createAppsecPolicyK8s(policy.getName(), "");
if (!std::get<1>(maybe_appsec_policy).ok()) {
dbgWarning(D_LOCAL_POLICY)
<< "Failed to create appsec policy. v1beta2 Error: "
<< std::get<1>(maybe_appsec_policy).getErr();
continue;
} else {
auto appsec_policy=std::get<1>(maybe_appsec_policy).unpack();
createPolicyFromActivation<V1beta2AppsecLinuxPolicy, NewParsedRule>(
appsec_policy,
v1bet2_policies,
policy);
}
}
}
return make_tuple(v1bet1_policies, v1bet2_policies);
}

View File

@@ -36,6 +36,7 @@
#include "customized_cereal_map.h"
#include "include/appsec_practice_section.h"
#include "include/ingress_data.h"
#include "include/policy_activation_data.h"
#include "include/settings_section.h"
#include "include/triggers_section.h"
#include "include/local_policy_common.h"
@@ -85,7 +86,7 @@ public:
K8sPolicyUtils k8s_policy_utils;
k8s_policy_utils.init();
auto appsec_policies = k8s_policy_utils.createAppsecPoliciesFromIngresses();
auto appsec_policies = k8s_policy_utils.createAppsecPolicies();
if (!std::get<0>(appsec_policies).empty()) {
return policy_maker_utils.proccesMultipleAppsecPolicies<AppsecLinuxPolicy, ParsedRule>(
std::get<0>(appsec_policies),

View File

@@ -69,7 +69,7 @@ Identifier::load(cereal::JSONInputArchive &archive_in)
dbgWarning(D_LOCAL_POLICY) << "AppSec identifier invalid: " << identifier;
identifier = "sourceip";
}
parseMandatoryAppsecJSONKey<vector<string>>("value", value, archive_in);
parseAppsecJSONKey<vector<string>>("value", value, archive_in);
}
const string &

View File

@@ -0,0 +1,103 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "policy_activation_data.h"
#include "customized_cereal_map.h"
using namespace std;
USE_DEBUG_FLAG(D_LOCAL_POLICY);
void
PolicyActivationMetadata::load(cereal::JSONInputArchive &archive_in)
{
dbgTrace(D_LOCAL_POLICY) << "PolicyActivationMetadata load";
parseAppsecJSONKey<string>("name", name, archive_in);
}
void
EnabledPolicy::load(cereal::JSONInputArchive &archive_in)
{
dbgTrace(D_LOCAL_POLICY) << "Loading policyActivation enabled policy";
parseMandatoryAppsecJSONKey<vector<string>>("hosts", hosts, archive_in);
parseAppsecJSONKey<string>("name", name, archive_in);
}
const string &
EnabledPolicy::getName() const
{
return name;
}
const vector<string> &
EnabledPolicy::getHosts() const
{
return hosts;
}
void
PolicyActivationSpec::load(cereal::JSONInputArchive &archive_in)
{
dbgTrace(D_LOCAL_POLICY) << "PolicyActivationSpec load";
parseAppsecJSONKey<string>("appsecClassName", appsec_class_name, archive_in);
parseMandatoryAppsecJSONKey<vector<EnabledPolicy>>("enabledPolicies", policies, archive_in);
}
const vector<EnabledPolicy> &
PolicyActivationSpec::getPolicies() const
{
return policies;
}
void
SinglePolicyActivationData::load(cereal::JSONInputArchive &archive_in)
{
dbgTrace(D_LOCAL_POLICY) << "Loading single policy activation data";
parseAppsecJSONKey<string>("apiVersion", api_version, archive_in);
parseAppsecJSONKey<string>("kind", kind, archive_in);
parseAppsecJSONKey<PolicyActivationMetadata>("metadata", metadata, archive_in);
parseAppsecJSONKey<PolicyActivationSpec>("spec", spec, archive_in);
}
const PolicyActivationSpec &
SinglePolicyActivationData::getSpec() const
{
return spec;
}
bool
PolicyActivationData::loadJson(const string &json)
{
string modified_json = json;
modified_json.pop_back();
stringstream in;
in.str(modified_json);
dbgTrace(D_LOCAL_POLICY) << "Loading policy activations data";
try {
cereal::JSONInputArchive in_ar(in);
in_ar(
cereal::make_nvp("apiVersion", api_version),
cereal::make_nvp("items", items)
);
} catch (cereal::Exception &e) {
dbgError(D_LOCAL_POLICY) << "Failed to load policy activations data JSON. Error: " << e.what();
return false;
}
return true;
}
const vector<SinglePolicyActivationData> &
PolicyActivationData::getItems() const
{
return items;
}

View File

@@ -928,7 +928,6 @@ createMultiRulesSections(
PracticeSection practice = PracticeSection(practice_id, practice_type, practice_name);
vector<ParametersSection> exceptions_result;
for (auto exception : exceptions) {
const auto &exception_name = exception.first;
for (const auto &inner_exception : exception.second) {
exceptions_result.push_back(ParametersSection(inner_exception.getBehaviorId(), exception_name));
@@ -1220,7 +1219,8 @@ PolicyMakerUtils::createWebAppSection(
const string &practice_id,
const string &full_url,
const string &default_mode,
map<AnnotationTypes, string> &rule_annotations)
map<AnnotationTypes, string> &rule_annotations,
vector<InnerException> rule_inner_exceptions)
{
auto apssec_practice =
getAppsecPracticeSpec<V1beta2AppsecLinuxPolicy, NewAppSecPracticeSpec>(
@@ -1255,7 +1255,8 @@ PolicyMakerUtils::createWebAppSection(
apssec_practice.getAntiBot(),
log_triggers[rule_annotations[AnnotationTypes::TRIGGER]],
trusted_sources[rule_annotations[AnnotationTypes::TRUSTED_SOURCES]],
apssec_practice.getWebAttacks().getProtections()
apssec_practice.getWebAttacks().getProtections(),
rule_inner_exceptions
);
web_apps[rule_config.getAssetName()] = web_app;
}
@@ -1366,7 +1367,8 @@ PolicyMakerUtils::createThreatPreventionPracticeSections(
practice_id,
asset_name,
default_mode,
rule_annotations);
rule_annotations,
inner_exceptions[rule_annotations[AnnotationTypes::EXCEPTION]]);
}
}

View File

@@ -14,7 +14,6 @@ add_subdirectory(details_resolver)
add_subdirectory(health_check)
add_subdirectory(health_check_manager)
add_subdirectory(updates_process_reporter)
add_subdirectory(env_details)
add_subdirectory(external_sdk_server)
#add_subdirectory(orchestration_ut)

View File

@@ -80,7 +80,9 @@ DetailsResolver::Impl::getHostname()
Maybe<string>
DetailsResolver::Impl::getPlatform()
{
#if defined(gaia)
#if defined(gaia_arm)
return string("gaia_arm");
#elif defined(gaia)
return string("gaia");
#elif defined(arm32_rpi)
return string("glibc");
@@ -350,7 +352,7 @@ DetailsResolver::Impl::readCloudMetadata()
}
if (!cloud_metadata.ok()) {
dbgWarning(D_ORCHESTRATOR) << cloud_metadata.getErr();
dbgDebug(D_ORCHESTRATOR) << cloud_metadata.getErr();
return genError("Failed to fetch cloud metadata");
}

View File

@@ -18,6 +18,8 @@
#include <regex>
#include <boost/regex.hpp>
#include <boost/algorithm/string.hpp>
#include <cereal/external/rapidjson/document.h>
#include <cereal/external/rapidjson/filereadstream.h>
#if defined(gaia)
@@ -69,7 +71,18 @@ checkPepIdaIdnStatus(const string &command_output)
Maybe<string>
getRequiredNanoServices(const string &command_output)
{
return command_output;
string idaRequiredServices[2] = {"idaSaml", "idaIdn"};
string platform_str = "gaia";
#if defined(gaia_arm)
platform_str = "gaia_arm";
#endif // gaia_arm
string result = "";
for(const string &serv : idaRequiredServices) {
string add_service = serv + "_" + platform_str;
result = result + add_service + ";";
}
command_output.empty(); // overcome unused variable
return result;
}
Maybe<string>
@@ -100,6 +113,14 @@ checkIsInstallHorizonTelemetrySucceeded(const string &command_output)
return command_output;
}
Maybe<string>
getOtlpAgentGaiaOsRole(const string &command_output)
{
if (command_output == "" ) return string("-1");
return command_output;
}
Maybe<string>
getQUID(const string &command_output)
{
@@ -111,6 +132,13 @@ getQUID(const string &command_output)
return command_output;
}
Maybe<string>
getIsAiopsRunning(const string &command_output)
{
if (command_output == "" ) return string("false");
return command_output;
}
Maybe<string>
checkHasSDWan(const string &command_output)
@@ -186,6 +214,24 @@ getMgmtObjAttr(shared_ptr<istream> file_stream, const string &attr)
return genError("Object attribute was not found. Attr: " + attr);
}
Maybe<string>
getAttrFromCpsdwanGetDataJson(const string &attr)
{
static const std::string get_data_json_path = "/tmp/cpsdwan_getdata_orch.json";
std::ifstream ifs(get_data_json_path);
if (ifs.is_open()) {
rapidjson::IStreamWrapper isw(ifs);
rapidjson::Document document;
document.ParseStream(isw);
if (!document.HasParseError() && document.HasMember(attr.c_str()) && document[attr.c_str()].IsString()) {
return string(document[attr.c_str()].GetString());
}
}
return genError("Attribute " + attr + " was not found in " + get_data_json_path);
}
Maybe<string>
getMgmtObjUid(const string &command_output)
{
@@ -193,6 +239,11 @@ getMgmtObjUid(const string &command_output)
return command_output;
}
Maybe<string> obj_uuid = getAttrFromCpsdwanGetDataJson("uuid");
if (obj_uuid.ok()) {
return obj_uuid.unpack();
}
static const string obj_path = (getenv("FWDIR") ? string(getenv("FWDIR")) : "") + "/database/myown.C";
auto file_stream = std::make_shared<std::ifstream>(obj_path);
if (!file_stream->is_open()) {
@@ -302,6 +353,28 @@ getSMCBasedMgmtName(const string &command_output)
return getAttr(command_output, "Mgmt object Name was not found");
}
Maybe<string>
getSmbObjectUid(const string &command_output)
{
static const char centrally_managed_comd_output = '0';
if (command_output.empty() || command_output[0] != centrally_managed_comd_output) {
return genError("Object UUID was not found");
}
Maybe<string> obj_uuid = getAttrFromCpsdwanGetDataJson("uuid");
if (obj_uuid.ok()) {
return obj_uuid.unpack();
}
static const string obj_path = (getenv("FWDIR") ? string(getenv("FWDIR")) : "") + "/database/myown.C";
auto file_stream = std::make_shared<std::ifstream>(obj_path);
if (!file_stream->is_open()) {
return genError("Failed to open the object file");
}
return getMgmtObjAttr(file_stream, "uuid ");
}
Maybe<string>
getSmbObjectName(const string &command_output)
{
@@ -310,7 +383,12 @@ getSmbObjectName(const string &command_output)
if (command_output.empty() || command_output[0] != centrally_managed_comd_output) {
return genError("Object name was not found");
}
Maybe<string> obj_name = getAttrFromCpsdwanGetDataJson("name");
if (obj_name.ok()) {
return obj_name.unpack();
}
static const string obj_path = (getenv("FWDIR") ? string(getenv("FWDIR")) : "") + "/database/myown.C";
auto ifs = std::make_shared<std::ifstream>(obj_path);
if (!ifs->is_open()) {

View File

@@ -29,7 +29,7 @@
// shell command execution output as its input
#ifdef SHELL_PRE_CMD
#if defined(gaia) || defined(smb)
#if defined(gaia) || defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_PRE_CMD("read sdwan data",
"(cpsdwan get_data > /tmp/cpsdwan_getdata_orch.json~) "
"&& (mv /tmp/cpsdwan_getdata_orch.json~ /tmp/cpsdwan_getdata_orch.json)")
@@ -40,17 +40,20 @@ SHELL_PRE_CMD("gunzip local.cfg", "gunzip -c $FWDIR/state/local/FW1/local.cfg.gz
#endif
#ifdef SHELL_CMD_HANDLER
#if defined(gaia) || defined(smb)
#if defined(gaia) || defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_CMD_HANDLER("cpProductIntegrationMgmtObjectType", "cpprod_util CPPROD_IsMgmtMachine", getMgmtObjType)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtObjectUid",
"mgmt_cli --format json -r true show-session | jq -r '.[\"connected-server\"].uid'",
getMgmtObjUid
)
SHELL_CMD_HANDLER("prerequisitesForHorizonTelemetry",
"FS_PATH=<FILESYSTEM-PREFIX>; [ -f ${FS_PATH}/cp-nano-horizon-telemetry-prerequisites.log ] "
"&& head -1 ${FS_PATH}/cp-nano-horizon-telemetry-prerequisites.log || echo ''",
checkIsInstallHorizonTelemetrySucceeded)
SHELL_CMD_HANDLER(
"IS_AIOPS_RUNNING",
"FS_PATH=<FILESYSTEM-PREFIX>; "
"PID=$(ps auxf | grep -v grep | grep -E ${FS_PATH}.*cp-nano-horizon-telemetry | awk -F' ' '{printf $2}'); "
"[ -z \"${PID}\" ] && echo 'false' || echo 'true'",
getIsAiopsRunning)
#endif
#if defined(gaia)
SHELL_CMD_HANDLER("GLOBAL_QUID", "[ -d /opt/CPquid ] "
"&& python3 /opt/CPquid/Quid_Api.py -i /opt/CPotelcol/quid_api/get_global_id.json | jq -r .message || echo ''",
getQUID)
@@ -73,6 +76,24 @@ SHELL_CMD_HANDLER("MGMT_QUID", "[ -d /opt/CPquid ] "
"&& python3 /opt/CPquid/Quid_Api.py -i "
"/opt/CPotelcol/quid_api/get_mgmt_quid.json | jq -r .message[0].MGMT_QUID || echo ''",
getQUID)
SHELL_CMD_HANDLER("AIOPS_AGENT_ROLE", "[ -d /opt/CPOtlpAgent/custom_scripts ] "
"&& ENV_NO_FORMAT=1 /opt/CPOtlpAgent/custom_scripts/agent_role.sh",
getOtlpAgentGaiaOsRole)
#endif
#if defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_CMD_HANDLER("GLOBAL_QUID",
"cat $FWDIR/database/myown.C "
"| awk -F'[()]' '/:name/ { found=1; next } found && /:uuid/ { uid=tolower($2); print uid; exit }'",
getQUID)
SHELL_CMD_HANDLER("QUID",
"cat $FWDIR/database/myown.C "
"| awk -F'[()]' '/:name/ { found=1; next } found && /:uuid/ { uid=tolower($2); print uid; exit }'",
getQUID)
SHELL_CMD_HANDLER("SMO_QUID", "echo ''", getQUID)
SHELL_CMD_HANDLER("MGMT_QUID", "echo ''", getQUID)
SHELL_CMD_HANDLER("AIOPS_AGENT_ROLE", "echo 'SMB'", getOtlpAgentGaiaOsRole)
#endif
#if defined(gaia) || defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_CMD_HANDLER("hasSDWan", "[ -f $FWDIR/bin/sdwan_steering ] && echo '1' || echo '0'", checkHasSDWan)
SHELL_CMD_HANDLER(
"canUpdateSDWanData",
@@ -124,12 +145,17 @@ SHELL_CMD_HANDLER("hasSAMLSupportedBlade", "enabled_blades", checkSAMLSupportedB
SHELL_CMD_HANDLER("hasIDABlade", "enabled_blades", checkIDABlade)
SHELL_CMD_HANDLER("hasSAMLPortal", "mpclient status nac", checkSAMLPortal)
SHELL_CMD_HANDLER("hasIdaIdnEnabled", "fw ctl get int nac_pep_identity_next_enabled", checkPepIdaIdnStatus)
SHELL_CMD_HANDLER("requiredNanoServices", "echo 'idaSaml_gaia;idaIdn_gaia;'", getRequiredNanoServices)
SHELL_CMD_HANDLER("requiredNanoServices", "echo ida", getRequiredNanoServices)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtObjectName",
"mgmt_cli --format json -r true show-session | jq -r '.[\"connected-server\"].name'",
getMgmtObjName
)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtObjectUid",
"mgmt_cli --format json -r true show-session | jq -r '.[\"connected-server\"].uid'",
getMgmtObjUid
)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtParentObjectName",
"cat $FWDIR/database/myself_objects.C "
@@ -180,13 +206,12 @@ SHELL_CMD_HANDLER(
)
SHELL_CMD_HANDLER(
"managements",
"sed -n '/:masters (/,$p' $FWDIR/database/myself_objects.C |"
" sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n//g' -e 's/\t//g' -e 's/ //g' | sed 's/))):.*/)))):/'",
"echo 1",
extractManagements
)
#endif //gaia
#if defined(smb)
#if defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtParentObjectName",
"jq -r .cluster_name /tmp/cpsdwan_getdata_orch.json",
@@ -202,6 +227,11 @@ SHELL_CMD_HANDLER(
"cpprod_util FwIsLocalMgmt",
getSmbObjectName
)
SHELL_CMD_HANDLER(
"cpProductIntegrationMgmtObjectUid",
"cpprod_util FwIsLocalMgmt",
getSmbObjectUid
)
SHELL_CMD_HANDLER(
"Application Control",
"cat $FWDIR/conf/active_blades.txt | grep -o 'APCL [01]' | cut -d ' ' -f2",
@@ -237,15 +267,13 @@ SHELL_CMD_HANDLER(
SHELL_CMD_HANDLER(
"managements",
"sed -n '/:masters (/,$p' /tmp/local.cfg |"
" sed -e ':a' -e 'N' -e '$!ba' -e 's/\\n//g' -e 's/\t//g' -e 's/ //g' | sed 's/))):.*/)))):/'",
"echo 1",
extractManagements
)
#endif//smb
SHELL_CMD_OUTPUT("kernel_version", "uname -r")
SHELL_CMD_OUTPUT("helloWorld", "cat /tmp/agentHelloWorld 2>/dev/null")
SHELL_CMD_OUTPUT("report_timestamp", "date -u +\%s")
#endif // SHELL_CMD_OUTPUT
@@ -275,7 +303,7 @@ FILE_CONTENT_HANDLER("AppSecModelVersion", "<FILESYSTEM-PREFIX>/conf/waap/waap.d
#endif // FILE_CONTENT_HANDLER
#ifdef SHELL_POST_CMD
#if defined(smb)
#if defined(smb) || defined(smb_thx_v3) || defined(smb_sve_v2) || defined(smb_mrv_v1)
SHELL_POST_CMD("remove local.cfg", "rm -rf /tmp/local.cfg")
#endif //smb
#endif

View File

@@ -266,10 +266,10 @@ private:
case OrchestrationStatusFieldType::COUNT : return "Count";
}
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration health")
<< "Trying to convert unknown orchestration status field to string.";
return "";
return "Unknown Field";
}
HealthCheckStatus
@@ -282,7 +282,7 @@ private:
case UpdatesProcessResult::DEGRADED : return HealthCheckStatus::DEGRADED;
}
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration health")
<< "Trying to convert unknown update process result field to health check status.";
return HealthCheckStatus::IGNORED;

View File

@@ -34,7 +34,9 @@ HybridModeMetric::upon(const HybridModeMetricEvent &)
{
auto shell_cmd = Singleton::Consume<I_ShellCmd>::by<OrchestrationComp>();
auto maybe_cmd_output = shell_cmd->getExecOutput(
getFilesystemPathConfig() + "/watchdog/cp-nano-watchdog --restart_count"
getFilesystemPathConfig() + "/watchdog/cp-nano-watchdog --restart_count",
1000,
false
);
// get wd process restart count

View File

@@ -79,8 +79,8 @@ public:
) override;
std::string getUpdate(CheckUpdateRequest &request) override;
bool shouldApplyPolicy() override;
void turnOffApplyPolicyFlag() override;
void turnOnApplyPolicyFlag() override;
void turnOffApplyLocalPolicyFlag() override;
void turnOnApplyLocalPolicyFlag() override;
std::string getCurrPolicy() override { return curr_policy; }
@@ -94,7 +94,7 @@ private:
std::string curr_version;
std::string curr_policy;
std::string curr_checksum;
bool should_apply_policy;
bool should_apply_local_policy;
};
#endif // __DECLARATIVE_POLICY_UTILS_H__

View File

@@ -22,8 +22,8 @@ public:
virtual std::string getCurrPolicy() = 0;
virtual void turnOffApplyPolicyFlag() = 0;
virtual void turnOnApplyPolicyFlag() = 0;
virtual void turnOffApplyLocalPolicyFlag() = 0;
virtual void turnOnApplyLocalPolicyFlag() = 0;
protected:
virtual ~I_DeclarativePolicy() {}

View File

@@ -100,6 +100,7 @@ private:
string packages_dir;
string orch_service_name;
set<string> ignore_packages;
Maybe<string> forbidden_versions = genError("Forbidden versions file does not exist");
};
void
@@ -135,7 +136,8 @@ ManifestController::Impl::init()
"Ignore packages list file path"
);
if (Singleton::Consume<I_OrchestrationTools>::by<ManifestController>()->doesFileExist(ignore_packages_path)) {
auto orchestration_tools = Singleton::Consume<I_OrchestrationTools>::by<ManifestController>();
if (orchestration_tools->doesFileExist(ignore_packages_path)) {
try {
ifstream input_stream(ignore_packages_path);
if (!input_stream) {
@@ -156,6 +158,9 @@ ManifestController::Impl::init()
<< " Error: " << f.what();
}
}
const string forbidden_versions_path = getFilesystemPathConfig() + "/revert/forbidden_versions";
forbidden_versions = orchestration_tools->readFile(forbidden_versions_path);
}
bool
@@ -271,6 +276,17 @@ ManifestController::Impl::updateManifest(const string &new_manifest_file)
}
map<string, Package> new_packages = parsed_manifest.unpack();
if (!new_packages.empty()) {
const Package &package = new_packages.begin()->second;
if (forbidden_versions.ok() &&
forbidden_versions.unpack().find(package.getVersion()) != string::npos
) {
dbgWarning(D_ORCHESTRATOR)
<< "Packages version is in the forbidden versions list. No upgrade will be performed.";
return true;
}
}
map<string, Package> all_packages = parsed_manifest.unpack();
map<string, Package> current_packages;
parsed_manifest = orchestration_tools->loadPackagesFromJson(manifest_file_path);

View File

@@ -58,6 +58,9 @@ public:
Debug::setUnitTestFlag(D_ORCHESTRATOR, Debug::DebugLevel::TRACE);
const string ignore_packages_file = "/etc/cp/conf/ignore-packages.txt";
EXPECT_CALL(mock_orchestration_tools, doesFileExist(ignore_packages_file)).WillOnce(Return(false));
Maybe<string> forbidden_versions(string("a1\na2"));
EXPECT_CALL(mock_orchestration_tools, readFile("/etc/cp/revert/forbidden_versions"))
.WillOnce(Return(forbidden_versions));
manifest_controller.init();
manifest_file_path = getConfigurationWithDefault<string>(
"/etc/cp/conf/manifest.json",
@@ -224,6 +227,10 @@ TEST_F(ManifestControllerTest, createNewManifest)
EXPECT_CALL(mock_orchestration_tools, copyFile(file_name, manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -363,6 +370,11 @@ TEST_F(ManifestControllerTest, updateManifest)
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
manifest =
@@ -417,6 +429,9 @@ TEST_F(ManifestControllerTest, updateManifest)
EXPECT_CALL(mock_orchestration_tools, loadPackagesFromJson(file_name)).WillOnce(Return(new_services));
EXPECT_CALL(mock_orchestration_tools,
loadPackagesFromJson(manifest_file_path)).WillOnce(Return(old_services));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillRepeatedly(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -478,6 +493,11 @@ TEST_F(ManifestControllerTest, selfUpdate)
EXPECT_CALL(mock_orchestration_tools, copyFile("/tmp/temp_file", path +
temp_ext)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -607,6 +627,10 @@ TEST_F(ManifestControllerTest, removeCurrentErrorPackage)
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
corrupted_packages.clear();
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -666,6 +690,10 @@ TEST_F(ManifestControllerTest, selfUpdateWithOldCopy)
EXPECT_CALL(mock_orchestration_tools, copyFile("/tmp/temp_file", path +
temp_ext)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -722,6 +750,10 @@ TEST_F(ManifestControllerTest, selfUpdateWithOldCopyWithError)
EXPECT_CALL(mock_orchestration_tools, doesFileExist(path)).WillOnce(Return(false)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, copyFile(path, path + backup_ext + temp_ext)).WillOnce(Return(false));
EXPECT_CALL(mock_details_resolver, getHostname()).WillOnce(Return(hostname));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_FALSE(i_manifest_controller->updateManifest(file_name));
}
@@ -798,6 +830,10 @@ TEST_F(ManifestControllerTest, installAndRemove)
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).Times(2).WillRepeatedly(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
string new_manifest =
@@ -858,6 +894,63 @@ TEST_F(ManifestControllerTest, installAndRemove)
.WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/packages/my1/my1")).Times(2)
.WillOnce(Return(false));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillRepeatedly(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
TEST_F(ManifestControllerTest, manifestWithForbiddenVersion)
{
new_services.clear();
old_services.clear();
string manifest =
"{"
" \"packages\": ["
" {"
" \"download-path\": \"http://172.23.92.135/my.sh\","
" \"relative-path\": \"\","
" \"name\": \"my\","
" \"version\": \"a1\","
" \"checksum-type\": \"sha1sum\","
" \"checksum\": \"a58bbab8020b0e6d08568714b5e582a3adf9c805\","
" \"package-type\": \"service\","
" \"require\": []"
" },"
" {"
" \"download-path\": \"http://172.23.92.135/my.sh\","
" \"relative-path\": \"\","
" \"name\": \"orchestration\","
" \"version\": \"a1\","
" \"checksum-type\": \"sha1sum\","
" \"checksum\": \"a58bbab8020b0e6d08568714b5e582a3adf9c805\","
" \"package-type\": \"service\","
" \"require\": []"
" },"
" {"
" \"download-path\": \"\","
" \"relative-path\": \"\","
" \"name\": \"waap\","
" \"version\": \"a1\","
" \"checksum-type\": \"sha1sum\","
" \"checksum\": \"\","
" \"package-type\": \"service\","
" \"status\": false,\n"
" \"message\": \"This security app isn't valid for this agent\"\n"
" }"
" ]"
"}";
map<string, Package> manifest_services;
load(manifest, manifest_services);
checkIfFileExistsCall(manifest_services.at("my"));
load(manifest, new_services);
load(old_manifest, old_services);
EXPECT_CALL(mock_orchestration_tools, loadPackagesFromJson(file_name)).WillOnce(Return(new_services));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -947,6 +1040,10 @@ TEST_F(ManifestControllerTest, badInstall)
EXPECT_CALL(mock_orchestration_tools,
packagesToJsonFile(corrupted_packages, corrupted_file_list)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_FALSE(i_manifest_controller->updateManifest(file_name));
}
@@ -1112,6 +1209,12 @@ TEST_F(ManifestControllerTest, requireUpdate)
.WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile("new_manifest.json")).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1212,6 +1315,10 @@ TEST_F(ManifestControllerTest, sharedObjectNotInstalled)
).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, copyFile("/tmp/temp_file1", path +
temp_ext)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1313,6 +1420,12 @@ TEST_F(ManifestControllerTest, requireSharedObjectUpdate)
.WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile("new_manifest.json"))
.WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1389,6 +1502,7 @@ TEST_F(ManifestControllerTest, failureOnDownloadSharedObject)
EXPECT_CALL(mock_details_resolver, getHostname()).WillOnce(Return(string("hostname")));
EXPECT_CALL(mock_orchestration_tools, removeFile("/tmp/temp_file1")).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_FALSE(i_manifest_controller->updateManifest(file_name));
}
@@ -1524,6 +1638,12 @@ TEST_F(ManifestControllerTest, multiRequireUpdate)
.WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile("new_manifest.json"))
.WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1610,6 +1730,12 @@ TEST_F(ManifestControllerTest, createNewManifestWithUninstallablePackage)
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1624,7 +1750,7 @@ TEST_F(ManifestControllerTest, updateUninstallPackage)
" \"download-path\": \"\","
" \"relative-path\": \"\","
" \"name\": \"my\","
" \"version\": \"\","
" \"version\": \"c\","
" \"checksum-type\": \"sha1sum\","
" \"checksum\": \"\","
" \"package-type\": \"service\","
@@ -1721,6 +1847,11 @@ TEST_F(ManifestControllerTest, updateUninstallPackage)
EXPECT_CALL(mock_orchestration_tools, loadPackagesFromJson(file_name)).WillOnce(Return(new_services));
EXPECT_CALL(mock_orchestration_tools,
loadPackagesFromJson(manifest_file_path)).WillOnce(Return(old_services));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillOnce(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(false));
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -1744,6 +1875,9 @@ public:
setConfiguration<string>(ignore_packages_file, "orchestration", "Ignore packages list file path");
writeIgnoreList(ignore_packages_file, ignore_services);
EXPECT_CALL(mock_orchestration_tools, doesFileExist(ignore_packages_file)).WillOnce(Return(true));
Maybe<string> forbidden_versions(string("a1\na2"));
EXPECT_CALL(mock_orchestration_tools, readFile("/etc/cp/revert/forbidden_versions"))
.WillOnce(Return(forbidden_versions));
manifest_controller.init();
manifest_file_path = getConfigurationWithDefault<string>(
"/etc/cp/conf/manifest.json",
@@ -1839,6 +1973,7 @@ public:
StrictMock<MockOrchestrationStatus> mock_status;
StrictMock<MockDownloader> mock_downloader;
StrictMock<MockOrchestrationTools> mock_orchestration_tools;
StrictMock<MockDetailsResolver> mock_details_resolver;
NiceMock<MockShellCmd> mock_shell_cmd;
ManifestController manifest_controller;
@@ -2122,6 +2257,12 @@ TEST_F(ManifestControllerIgnorePakckgeTest, addIgnorePackageAndUpdateNormal)
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
}
@@ -2387,6 +2528,12 @@ TEST_F(ManifestControllerIgnorePakckgeTest, overrideIgnoredPackageFromProfileSet
EXPECT_CALL(mock_orchestration_tools, isNonEmptyFile(manifest_file_path)).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, removeFile(file_name)).WillOnce(Return(true));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("b"));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(false))
.WillRepeatedly(Return(true));;
EXPECT_CALL(mock_orchestration_tools, writeFile(_, "/etc/cp/revert/upgrade_status", false))
.WillOnce(Return(true));
EXPECT_TRUE(i_manifest_controller->updateManifest(file_name));
EXPECT_THAT(capture_debug.str(), Not(HasSubstr("Ignoring a package from the manifest. Package name: my")));
@@ -2411,6 +2558,9 @@ public:
doesFileExist("/etc/cp/conf/ignore-packages.txt")
).WillOnce(Return(false));
Maybe<string> forbidden_versions(string("a1\na2"));
EXPECT_CALL(mock_orchestration_tools, readFile("/etc/cp/revert/forbidden_versions"))
.WillOnce(Return(forbidden_versions));
manifest_controller.init();
}

View File

@@ -14,6 +14,7 @@
#include "manifest_handler.h"
#include <algorithm>
#include <ctime>
#include "debug.h"
#include "config.h"
@@ -201,18 +202,29 @@ ManifestHandler::installPackage(
auto span_scope = i_env->startNewSpanScope(Span::ContextType::CHILD_OF);
auto orchestration_status = Singleton::Consume<I_OrchestrationStatus>::by<ManifestHandler>();
auto details_resolver = Singleton::Consume<I_DetailsResolver>::by<ManifestHandler>();
auto orchestration_tools = Singleton::Consume<I_OrchestrationTools>::by<ManifestHandler>();
auto &package = package_downloaded_file.first;
auto &package_name = package.getName();
auto &package_handler_path = package_downloaded_file.second;
dbgInfo(D_ORCHESTRATOR) << "Handling package installation. Package: " << package_name;
string upgrade_info =
details_resolver->getAgentVersion() + " " + package.getVersion() + " " + getCurrentTimestamp();
if (!orchestration_tools->doesFileExist(getFilesystemPathConfig() + "/revert/upgrade_status") &&
!orchestration_tools->writeFile(upgrade_info, getFilesystemPathConfig() + "/revert/upgrade_status")
) {
dbgWarning(D_ORCHESTRATOR) << "Failed to write to " + getFilesystemPathConfig() + "/revert/upgrade_status";
}
if (package_name.compare(orch_service_name) == 0) {
orchestration_status->writeStatusToFile();
bool self_update_status = selfUpdate(package, current_packages, package_handler_path);
if (!self_update_status) {
auto details = Singleton::Consume<I_AgentDetails>::by<ManifestHandler>();
auto hostname = Singleton::Consume<I_DetailsResolver>::by<ManifestHandler>()->getHostname();
auto hostname = details_resolver->getHostname();
string err_hostname = (hostname.ok() ? "on host '" + *hostname : "'" + details->getAgentId()) + "'";
string install_error =
"Warning: Agent/Gateway " +
@@ -246,7 +258,6 @@ ManifestHandler::installPackage(
return true;
}
string current_installation_file = packages_dir + "/" + package_name + "/" + package_name;
auto orchestration_tools = Singleton::Consume<I_OrchestrationTools>::by<ManifestHandler>();
bool is_clean_installation = !orchestration_tools->doesFileExist(current_installation_file);
@@ -368,3 +379,13 @@ ManifestHandler::selfUpdate(
package_handler->preInstallPackage(orch_service_name, current_installation_file) &&
package_handler->installPackage(orch_service_name, current_installation_file, false);
}
string
ManifestHandler::getCurrentTimestamp()
{
time_t now = time(nullptr);
tm* now_tm = localtime(&now);
char timestamp[20];
strftime(timestamp, sizeof(timestamp), "%Y-%m-%d %H:%M:%S", now_tm);
return string(timestamp);
}

View File

@@ -429,7 +429,7 @@ public:
status.insertServiceSetting(service_name, path);
return;
case OrchestrationStatusConfigType::MANIFEST:
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "sesrvice configuration")
<< "Manifest is not a service configuration file type";
break;
@@ -438,7 +438,9 @@ public:
case OrchestrationStatusConfigType::COUNT:
break;
}
dbgAssert(false) << AlertInfo(AlertTeam::CORE, "sesrvice configuration") << "Unknown configuration file type";
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "service configuration")
<< "Unknown configuration file type";
}
void

View File

@@ -55,6 +55,8 @@ USE_DEBUG_FLAG(D_ORCHESTRATOR);
static string fw_last_update_time = "";
#endif // gaia || smb
static const size_t MAX_SERVER_NAME_LENGTH = 253;
class SetAgentUninstall
:
public ServerRest,
@@ -103,6 +105,19 @@ public:
<< "Initializing Orchestration component, file system path prefix: "
<< filesystem_prefix;
int check_upgrade_success_interval = getSettingWithDefault<uint>(10, "successUpgradeInterval");
Singleton::Consume<I_MainLoop>::by<OrchestrationComp>()->addOneTimeRoutine(
I_MainLoop::RoutineType::Timer,
[this, check_upgrade_success_interval]()
{
Singleton::Consume<I_MainLoop>::by<OrchestrationComp>()->yield(
std::chrono::minutes(check_upgrade_success_interval)
);
processUpgradeCompletion();
},
"Orchestration successfully updated (One-Time After Interval)",
true
);
auto orch_policy = loadDefaultOrchestrationPolicy();
if (!orch_policy.ok()) {
dbgWarning(D_ORCHESTRATOR) << "Failed to load Orchestration Policy. Error: " << orch_policy.getErr();
@@ -141,6 +156,113 @@ public:
}
private:
void
saveLastKnownOrchInfo(string curr_agent_version)
{
static const string upgrades_dir = filesystem_prefix + "/revert";
static const string last_known_orchestrator = upgrades_dir + "/last_known_working_orchestrator";
static const string current_orchestration_package =
filesystem_prefix + "/packages/orchestration/orchestration";
static const string last_known_manifest = upgrades_dir + "/last_known_manifest";
static const string current_manifest_file = getConfigurationWithDefault<string>(
filesystem_prefix + "/conf/manifest.json",
"orchestration",
"Manifest file path"
);
if (!i_orchestration_tools->copyFile(current_orchestration_package, last_known_orchestrator)) {
dbgWarning(D_ORCHESTRATOR) << "Failed to copy the orchestration package to " << upgrades_dir;
} else {
dbgInfo(D_ORCHESTRATOR) << "last known orchestrator version updated to: " << curr_agent_version;
}
if (!i_orchestration_tools->copyFile(current_manifest_file, last_known_manifest)) {
dbgWarning(D_ORCHESTRATOR) << "Failed to copy " << current_manifest_file << " to " << upgrades_dir;
} else {
dbgInfo(D_ORCHESTRATOR) << "last known manifest updated";
}
return;
}
void
processUpgradeCompletion()
{
if (!is_first_check_update_success) {
int check_upgrade_success_interval = getSettingWithDefault<uint>(10, "successUpgradeInterval");
// LCOV_EXCL_START
Singleton::Consume<I_MainLoop>::by<OrchestrationComp>()->addOneTimeRoutine(
I_MainLoop::RoutineType::Timer,
[this, check_upgrade_success_interval]()
{
Singleton::Consume<I_MainLoop>::by<OrchestrationComp>()->yield(
std::chrono::minutes(check_upgrade_success_interval)
);
processUpgradeCompletion();
},
"Orchestration successfully updated",
true
);
// LCOV_EXCL_STOP
return;
}
static const string upgrades_dir = filesystem_prefix + "/revert";
static const string upgrade_status = upgrades_dir + "/upgrade_status";
static const string last_known_orchestrator = upgrades_dir + "/last_known_working_orchestrator";
static const string upgrade_failure_info_path = upgrades_dir + "/failed_upgrade_info";
I_DetailsResolver *i_details_resolver = Singleton::Consume<I_DetailsResolver>::by<OrchestrationComp>();
bool is_upgrade_status_exist = i_orchestration_tools->doesFileExist(upgrade_status);
bool is_last_known_orchestrator_exist = i_orchestration_tools->doesFileExist(last_known_orchestrator);
if (!is_upgrade_status_exist) {
if (!is_last_known_orchestrator_exist) {
saveLastKnownOrchInfo(i_details_resolver->getAgentVersion());
}
return;
}
auto maybe_upgrade_data = i_orchestration_tools->readFile(upgrade_status);
string upgrade_data, from_version, to_version;
if (maybe_upgrade_data.ok()) {
upgrade_data = maybe_upgrade_data.unpack();
istringstream stream(upgrade_data);
stream >> from_version >> to_version;
}
i_orchestration_tools->removeFile(upgrade_status);
if (i_orchestration_tools->doesFileExist(upgrade_failure_info_path)) {
string info = "Orchestration revert. ";
auto failure_info = i_orchestration_tools->readFile(upgrade_failure_info_path);
if (failure_info.ok()) info.append(failure_info.unpack());
LogGen(
info,
ReportIS::Level::ACTION,
ReportIS::Audience::INTERNAL,
ReportIS::Severity::CRITICAL,
ReportIS::Priority::URGENT,
ReportIS::Tags::ORCHESTRATOR
);
dbgError(D_ORCHESTRATOR) <<
"Error in orchestration version: " << to_version <<
". Orchestration reverted to version: " << i_details_resolver->getAgentVersion();
i_orchestration_tools->removeFile(upgrade_failure_info_path);
return;
}
saveLastKnownOrchInfo(i_details_resolver->getAgentVersion());
i_orchestration_tools->writeFile(
upgrade_data + "\n",
getLogFilesPathConfig() + "/nano_agent/prev_upgrades",
true
);
dbgWarning(D_ORCHESTRATOR) <<
"Upgrade process from version: " << from_version <<
" to version: " << to_version <<
" completed successfully";
}
Maybe<void>
registerToTheFog()
{
@@ -1022,6 +1144,7 @@ private:
UpdatesProcessResult::SUCCESS,
UpdatesConfigType::GENERAL
).notify();
if (!is_first_check_update_success) is_first_check_update_success = true;
return Maybe<void>();
}
@@ -1347,9 +1470,10 @@ private:
string cc_opt;
tie(config_opt, cc_opt, nginx_version) = nginx_data.unpack();
agent_data_report
<< make_pair("nginxVersion", nginx_version)
<< make_pair("configureOpt", config_opt)
<< make_pair("extraCompilerOpt", cc_opt);
<< make_pair("attachmentVersion", "Legacy")
<< make_pair("nginxVersion", nginx_version)
<< make_pair("configureOpt", config_opt)
<< make_pair("extraCompilerOpt", cc_opt);
} else {
dbgDebug(D_ORCHESTRATOR) << nginx_data.getErr();
}
@@ -1389,6 +1513,8 @@ private:
agent_data_report << AgentReportFieldWithLabel("userEdition", FogCommunication::getUserEdition());
agent_data_report << make_pair("registeredServer", i_agent_details->getRegisteredServer());
#if defined(gaia) || defined(smb)
if (i_details_resolver->compareCheckpointVersion(8100, greater_equal<int>())) {
agent_data_report << AgentReportFieldWithLabel("isCheckpointVersionGER81", "true");
@@ -1403,6 +1529,7 @@ private:
} else {
curr_agent_data_report = agent_data_report;
curr_agent_data_report.disableReportSending();
agent_data_report << AgentReportFieldWithLabel("timestamp", i_time->getWalltimeStr());
}
}
@@ -1549,6 +1676,11 @@ private:
<< LogField("agentType", "Orchestration")
<< LogField("agentVersion", Version::get());
string registered_server = getAttribute("registered-server", "registered_server");
dbgTrace(D_ORCHESTRATOR) << "Registered server: " << registered_server;
if (!registered_server.empty()) {
i_agent_details->setRegisteredServer(registered_server.substr(0, MAX_SERVER_NAME_LENGTH));
}
auto mainloop = Singleton::Consume<I_MainLoop>::by<OrchestrationComp>();
mainloop->addOneTimeRoutine(
I_MainLoop::RoutineType::Offline,
@@ -1587,6 +1719,7 @@ private:
}
setDelayedUpgradeTime();
while (true) {
Singleton::Consume<I_Environment>::by<OrchestrationComp>()->startNewTrace(false);
if (shouldReportAgentDetailsMetadata()) {
@@ -1628,9 +1761,9 @@ private:
}
}
string server_name = getAttribute("registered-server", "registered_server");
string server_name = Singleton::Consume<I_AgentDetails>::by<OrchestrationComp>()->getRegisteredServer();
auto server = TagAndEnumManagement::convertStringToTag(server_name);
if (server_name == "'SWAG'") server = Tags::WEB_SERVER_SWAG;
if (server_name == "'SWAG'" || server_name == "'SWAG Server'") server = Tags::WEB_SERVER_SWAG;
if (server.ok()) tags.insert(*server);
if (getAttribute("no-setting", "CROWDSEC_ENABLED") == "true") tags.insert(Tags::CROWDSEC);
@@ -1652,7 +1785,7 @@ private:
tags
);
if (server_name != "") registration_report.addToOrigin(LogField("eventCategory", server_name));
registration_report.addToOrigin(LogField("eventCategory", server_name));
auto email = getAttribute("email-address", "user_email");
if (email != "") registration_report << LogField("userDefinedId", email);
@@ -1695,13 +1828,19 @@ private:
auto backup_installation_file = current_installation_file + backup_ext;
auto temp_ext = getConfigurationWithDefault<string>("_temp", "orchestration", "Temp file extension");
dbgAssert(i_orchestration_tools->doesFileExist(backup_installation_file))
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "There is no backup installation package";
if (!i_orchestration_tools->doesFileExist(backup_installation_file)) {
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "There is no backup installation package";
return;
}
dbgAssert(i_orchestration_tools->copyFile(backup_installation_file, current_installation_file))
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to copy backup installation package";
if (!i_orchestration_tools->copyFile(backup_installation_file, current_installation_file)) {
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to copy backup installation package";
return;
}
// Copy the backup manifest file to the default manifest file path.
auto manifest_file_path = getConfigurationWithDefault<string>(
@@ -1716,12 +1855,18 @@ private:
auto package_handler = Singleton::Consume<I_PackageHandler>::by<OrchestrationComp>();
// Install the backup orchestration service installation package.
dbgAssert(package_handler->preInstallPackage(service_name, current_installation_file))
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to restore from backup, pre install test failed";
dbgAssert(package_handler->installPackage(service_name, current_installation_file, true))
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to restore from backup, installation failed";
if (!package_handler->preInstallPackage(service_name, current_installation_file)) {
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to restore from backup, pre install test failed";
return;
}
if (!package_handler->installPackage(service_name, current_installation_file, true)) {
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "orchestration backup")
<< "Failed to restore from backup, installation failed";
return;
}
}
// LCOV_EXCL_STOP
@@ -2033,7 +2178,7 @@ private:
}
auto policy_mgmt_mode = getSettingWithDefault<string>("management", "profileManagedMode");
if (getOrchestrationMode() == OrchestrationMode::HYBRID || policy_mgmt_mode == "declarative") {
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOnApplyPolicyFlag();
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOnApplyLocalPolicyFlag();
}
auto policy_version = i_service_controller->getPolicyVersion();
@@ -2052,10 +2197,10 @@ private:
int failure_count = 0;
unsigned int sleep_interval = 0;
bool is_new_success = false;
bool is_first_check_update_success = false;
OrchestrationPolicy policy;
UpdatesProcessReporter updates_process_reporter_listener;
HybridModeMetric hybrid_mode_metric;
EnvDetails env_details;
chrono::minutes upgrade_delay_time;
string filesystem_prefix = "";
@@ -2118,6 +2263,7 @@ OrchestrationComp::preload()
registerExpectedSetting<vector<string>>("upgradeDay");
registerExpectedSetting<string>("email-address");
registerExpectedSetting<string>("registered-server");
registerExpectedSetting<uint>("successUpgradeInterval");
registerExpectedConfigFile("orchestration", Config::ConfigFileType::Policy);
registerExpectedConfigFile("registration-data", Config::ConfigFileType::Policy);
}

View File

@@ -386,7 +386,7 @@ OrchestrationTools::Impl::calculateChecksum(Package::ChecksumTypes checksum_type
return genError("Error while reading file " + path + ", " + e.what());
}
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "service configuration")
<< "Checksum type is not supported. Checksum type: "
<< static_cast<unsigned int>(checksum_type);

View File

@@ -89,6 +89,11 @@ public:
EXPECT_CALL(mock_service_controller, isServiceInstalled("Access Control")).WillRepeatedly(Return(false));
EXPECT_CALL(
mock_ml,
addOneTimeRoutine(_, _, "Orchestration successfully updated (One-Time After Interval)", true)
).WillOnce(DoAll(SaveArg<1>(&upgrade_routine), Return(0)));
// This Holding the Main Routine of the Orchestration.
EXPECT_CALL(
mock_ml,
@@ -156,6 +161,7 @@ public:
runRoutine()
{
routine();
upgrade_routine();
}
void
@@ -235,6 +241,7 @@ private:
}
I_MainLoop::Routine routine;
I_MainLoop::Routine upgrade_routine;
I_MainLoop::Routine status_routine;
};

View File

@@ -28,6 +28,7 @@ std::ostream & operator<<(std::ostream &os, const Package &) { return os; }
#include "health_check_status/health_check_status.h"
#include "updates_process_event.h"
#include "declarative_policy_utils.h"
#include "mock/mock_env_details.h"
using namespace testing;
using namespace std;
@@ -82,6 +83,12 @@ public:
EXPECT_CALL(mock_orchestration_tools, readFile(orchestration_policy_file_path)).WillOnce(Return(response));
EXPECT_CALL(mock_status, setFogAddress(host_url)).WillRepeatedly(Return());
EXPECT_CALL(mock_orchestration_tools, setClusterId());
EXPECT_CALL(
mock_ml,
addOneTimeRoutine(_, _, "Orchestration successfully updated (One-Time After Interval)", true)
).WillOnce(DoAll(SaveArg<1>(&upgrade_routine), Return(0)));
EXPECT_CALL(
mock_ml,
addOneTimeRoutine(I_MainLoop::RoutineType::System, _, "Orchestration runner", true)
@@ -280,6 +287,12 @@ public:
status_routine();
}
void
runUpgradeRoutine()
{
upgrade_routine();
}
void
preload()
{
@@ -324,6 +337,7 @@ public:
StrictMock<MockOrchestrationTools> mock_orchestration_tools;
StrictMock<MockDownloader> mock_downloader;
StrictMock<MockShellCmd> mock_shell_cmd;
StrictMock<EnvDetailsMocker> mock_env_details;
StrictMock<MockMessaging> mock_message;
StrictMock<MockRestApi> rest;
StrictMock<MockServiceController> mock_service_controller;
@@ -357,6 +371,7 @@ private:
I_MainLoop::Routine routine;
I_MainLoop::Routine status_routine;
I_MainLoop::Routine upgrade_routine;
};
@@ -583,6 +598,8 @@ TEST_F(OrchestrationTest, check_sending_registration_data)
env.init();
init();
EXPECT_CALL(mock_env_details, getEnvType()).WillRepeatedly(Return(EnvType::LINUX));
EXPECT_CALL(mock_service_controller, updateServiceConfiguration(_, _, _, _, _, _))
.WillOnce(Return(Maybe<void>()));
EXPECT_CALL(mock_orchestration_tools, calculateChecksum(_, _)).WillRepeatedly(Return(string()));
@@ -597,14 +614,6 @@ TEST_F(OrchestrationTest, check_sending_registration_data)
string version = "1";
EXPECT_CALL(mock_service_controller, getUpdatePolicyVersion()).WillOnce(ReturnRef(version));
EXPECT_CALL(mock_ml, yield(A<chrono::microseconds>()))
.WillOnce(Return())
.WillOnce(Invoke([] (chrono::microseconds) { throw invalid_argument("stop while loop"); }));
try {
runRoutine();
} catch (const invalid_argument& e) {}
string config_json =
"{\n"
" \"email-address\": \"fake@example.com\",\n"
@@ -613,9 +622,19 @@ TEST_F(OrchestrationTest, check_sending_registration_data)
istringstream ss(config_json);
Singleton::Consume<Config::I_Config>::from(config_comp)->loadConfiguration(ss);
EXPECT_CALL(mock_ml, yield(A<chrono::microseconds>()))
.WillOnce(Return())
.WillOnce(Invoke([] (chrono::microseconds) { throw invalid_argument("stop while loop"); }));
try {
runRoutine();
} catch (const invalid_argument& e) {}
sending_routine();
EXPECT_THAT(message_body, HasSubstr("\"userDefinedId\": \"fake@example.com\""));
EXPECT_THAT(message_body, HasSubstr("\"eventCategory\""));
EXPECT_THAT(message_body, AnyOf(HasSubstr("\"Embedded Deployment\""), HasSubstr("\"Kubernetes Deployment\"")));
EXPECT_THAT(message_body, HasSubstr("\"NGINX Server\""));
}
@@ -1000,6 +1019,11 @@ TEST_F(OrchestrationTest, loadOrchestrationPolicyFromBackup)
);
waitForRestCall();
EXPECT_CALL(
mock_ml,
addOneTimeRoutine(_, _, "Orchestration successfully updated (One-Time After Interval)", true)
);
EXPECT_CALL(
mock_ml,
addOneTimeRoutine(I_MainLoop::RoutineType::System, _, "Orchestration runner", true)
@@ -1166,6 +1190,29 @@ TEST_F(OrchestrationTest, manifestUpdate)
try {
runRoutine();
} catch (const invalid_argument& e) {}
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/upgrade_status")).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/last_known_working_orchestrator"))
.WillOnce(Return(true));
Maybe<string> upgrade_status(string("1.1.1 1.1.2 2025-01-28 07:53:23"));
EXPECT_CALL(mock_orchestration_tools, readFile("/etc/cp/revert/upgrade_status"))
.WillOnce(Return(upgrade_status));
EXPECT_CALL(mock_orchestration_tools, removeFile("/etc/cp/revert/upgrade_status")).WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, doesFileExist("/etc/cp/revert/failed_upgrade_info"))
.WillOnce(Return(false));
EXPECT_CALL(mock_details_resolver, getAgentVersion()).WillRepeatedly(Return("1.1.2"));
EXPECT_CALL(mock_orchestration_tools, copyFile(_, "/etc/cp/revert/last_known_working_orchestrator"))
.WillOnce(Return(true));
EXPECT_CALL(mock_orchestration_tools, copyFile(_, "/etc/cp/revert/last_known_manifest")).WillOnce(Return(true));
EXPECT_CALL(
mock_orchestration_tools,
writeFile("1.1.1 1.1.2 2025-01-28 07:53:23\n", "/var/log/nano_agent/prev_upgrades", true)
).WillOnce(Return(true));
EXPECT_CALL(mock_ml, yield(A<chrono::microseconds>())).WillOnce(Return());
runUpgradeRoutine();
}
TEST_F(OrchestrationTest, getBadPolicyUpdate)

View File

@@ -141,11 +141,11 @@ packageHandlerActionsToString(PackageHandlerActions action)
}
}
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "service configuration")
<< "Package handler action is not supported. Action: "
<< static_cast<unsigned int>(action);
return string();
return string("--UNSUPPORTED");
}
void

View File

@@ -208,6 +208,7 @@ ServiceDetails::sendNewConfigurations(int configuration_id, const string &policy
MessageMetadata new_config_req_md("127.0.0.1", service_port);
new_config_req_md.setConnectioFlag(MessageConnectionConfig::ONE_TIME_CONN);
new_config_req_md.setConnectioFlag(MessageConnectionConfig::UNSECURE_CONN);
new_config_req_md.setSuspension(false);
auto res = messaging->sendSyncMessage(
HTTPMethod::POST,
"/set-new-configuration",
@@ -793,7 +794,7 @@ ServiceController::Impl::updateServiceConfiguration(
<< "Policy file was not updated. Sending reload command regarding settings and data";
auto signal_services = sendSignalForServices(nano_services_to_update, "");
if (!signal_services.ok()) return signal_services.passErr();
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyPolicyFlag();
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyLocalPolicyFlag();
return Maybe<void>();
}
@@ -940,7 +941,7 @@ ServiceController::Impl::updateServiceConfiguration(
if (new_policy_path.compare(config_file_path) == 0) {
dbgDebug(D_SERVICE_CONTROLLER) << "Enforcing the default policy file";
policy_version = version_value;
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyPolicyFlag();
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyLocalPolicyFlag();
return Maybe<void>();
}
@@ -959,7 +960,7 @@ ServiceController::Impl::updateServiceConfiguration(
}
if (!was_policy_updated && !send_signal_for_services_err.empty()) return genError(send_signal_for_services_err);
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyPolicyFlag();
Singleton::Consume<I_DeclarativePolicy>::from<DeclarativePolicyUtils>()->turnOffApplyLocalPolicyFlag();
return Maybe<void>();
}

View File

@@ -17,7 +17,7 @@ void
DeclarativePolicyUtils::init()
{
local_policy_path = getFilesystemPathConfig() + "/conf/local_policy.yaml";
should_apply_policy = true;
should_apply_local_policy = true;
Singleton::Consume<I_RestApi>::by<DeclarativePolicyUtils>()->addRestCall<ApplyPolicyRest>(
RestAction::SET, "apply-policy"
);
@@ -40,7 +40,7 @@ DeclarativePolicyUtils::upon(const ApplyPolicyEvent &event)
{
dbgTrace(D_ORCHESTRATOR) << "Apply policy event";
local_policy_path = event.getPolicyPath();
should_apply_policy = true;
should_apply_local_policy = true;
}
// LCOV_EXCL_STOP
@@ -48,19 +48,24 @@ bool
DeclarativePolicyUtils::shouldApplyPolicy()
{
auto env_type = Singleton::Consume<I_EnvDetails>::by<DeclarativePolicyUtils>()->getEnvType();
return env_type == EnvType::K8S ? true : should_apply_policy;
if (env_type == EnvType::K8S) {
I_OrchestrationTools *orch_tools = Singleton::Consume<I_OrchestrationTools>::by<DeclarativePolicyUtils>();
auto maybe_new_version = orch_tools->readFile("/etc/cp/conf/k8s-policy-check.trigger");
return maybe_new_version != curr_version;
}
return should_apply_local_policy;
}
void
DeclarativePolicyUtils::turnOffApplyPolicyFlag()
DeclarativePolicyUtils::turnOffApplyLocalPolicyFlag()
{
should_apply_policy = false;
should_apply_local_policy = false;
}
void
DeclarativePolicyUtils::turnOnApplyPolicyFlag()
DeclarativePolicyUtils::turnOnApplyLocalPolicyFlag()
{
should_apply_policy = true;
should_apply_local_policy = true;
}
Maybe<string>
@@ -211,6 +216,6 @@ DeclarativePolicyUtils::periodicPolicyLoad()
if (*new_checksum == curr_checksum) return;
should_apply_policy = true;
should_apply_local_policy = true;
curr_checksum = *new_checksum;
}

View File

@@ -377,9 +377,13 @@ FogAuthenticator::registerLocalAgentToFog()
{
auto local_reg_token = getRegistrationToken();
if (!local_reg_token.ok()) return;
string reg_token = local_reg_token.unpack().getData();
if (reg_token.empty()) return;
dbgInfo(D_ORCHESTRATOR) << "Start local agent registration to the fog";
string exec_command = "open-appsec-ctl --set-mode --online_mode --token " + local_reg_token.unpack().getData();
string exec_command = "open-appsec-ctl --set-mode --online_mode --token " + reg_token;
auto i_agent_details = Singleton::Consume<I_AgentDetails>::by<FogAuthenticator>();
auto fog_address = i_agent_details->getFogDomain();
@@ -467,9 +471,9 @@ getDeplymentType()
case EnvType::COUNT: break;
}
dbgAssert(false)
dbgAssertOpt(false)
<< AlertInfo(AlertTeam::CORE, "fog communication")
<< "Failed to get a legitimate deplyment type: "
<< "Failed to get a legitimate deployment type: "
<< static_cast<uint>(deplyment_type);
return "Embedded";
}

View File

@@ -74,7 +74,7 @@ FogCommunication::getUpdate(CheckUpdateRequest &request)
<< " to: "
<< policy_mgmt_mode;
profile_mode = policy_mgmt_mode;
i_declarative_policy->turnOnApplyPolicyFlag();
i_declarative_policy->turnOnApplyLocalPolicyFlag();
}
if (i_declarative_policy->shouldApplyPolicy()) {

View File

@@ -246,6 +246,27 @@ public:
return matched_rule;
}
void
fetchReplicaCount()
{
string curl_cmd =
"curl -H \"Authorization: Bearer " + kubernetes_token + "\" "
"https://kubernetes.default.svc.cluster.local/apis/apps/v1/namespaces/" + kubernetes_namespace +
"/deployments/${AGENT_DEPLOYMENT_NAME} -k -s | jq .status.replicas";
auto maybe_replicas = i_shell_cmd->getExecOutput(curl_cmd);
if (maybe_replicas.ok()) {
try {
replicas = std::stoi(maybe_replicas.unpack());
} catch (const std::exception &e) {
dbgWarning(D_RATE_LIMIT) << "error while converting replicas: " << e.what();
}
}
if (replicas == 0) {
dbgWarning(D_RATE_LIMIT) << "replicas is set to 0, setting replicas to 1";
replicas = 1;
}
}
EventVerdict
respond(const HttpRequestHeaderEvent &event) override
{
@@ -271,10 +292,72 @@ public:
dbgDebug(D_RATE_LIMIT) << "source identifier value: " << source_identifier;
auto maybe_source_ip = env->get<IPAddr>(HttpTransactionData::client_ip_ctx);
set<string> ip_set;
string source_ip = "";
if (maybe_source_ip.ok()) source_ip = ipAddrToStr(maybe_source_ip.unpack());
if (maybe_source_ip.ok()) {
source_ip = ipAddrToStr(maybe_source_ip.unpack());
unordered_map<string, set<string>> condition_map = createConditionMap(uri, source_ip, source_identifier);
if (getProfileAgentSettingWithDefault<bool>(false, "agent.rateLimit.ignoreSourceIP")) {
dbgDebug(D_RATE_LIMIT) << "Rate limit ignoring source ip: " << source_ip;
} else {
ip_set.insert(source_ip);
}
}
auto maybe_xff = env->get<string>(HttpTransactionData::xff_vals_ctx);
if (!maybe_xff.ok()) {
dbgTrace(D_RATE_LIMIT) << "Rate limit failed to get xff vals from env";
} else {
auto ips = split(maybe_xff.unpack(), ',');
ip_set.insert(ips.begin(), ips.end());
}
EnumArray<I_GeoLocation::GeoLocationField, string> geo_location_data;
set<string> country_codes;
set<string> country_names;
for (const string& source : ip_set) {
Maybe<IPAddr> maybe_source_ip = IPAddr::createIPAddr(source);
if (!maybe_source_ip.ok()){
dbgWarning(D_RATE_LIMIT)
<< "Rate limit failed to create ip address from source: "
<< source
<< ", Error: "
<< maybe_source_ip.getErr();
continue;
}
auto asset_location =
Singleton::Consume<I_GeoLocation>::by<RateLimit>()->lookupLocation(maybe_source_ip.unpack());
if (!asset_location.ok()) {
dbgWarning(D_RATE_LIMIT)
<< "Rate limit lookup location failed for source: "
<< source_ip
<< ", Error: "
<< asset_location.getErr();
continue;
}
geo_location_data = asset_location.unpack();
auto code = geo_location_data[I_GeoLocation::GeoLocationField::COUNTRY_CODE];
auto name = geo_location_data[I_GeoLocation::GeoLocationField::COUNTRY_NAME];
country_codes.insert(code);
country_names.insert(name);
dbgTrace(D_RATE_LIMIT)
<< "Rate limit found "
<< "country code: "
<< code
<< ", country name: "
<< name
<< ", source ip address: "
<< source;
}
unordered_map<string, set<string>> condition_map = createConditionMap(
uri,
source_ip,
source_identifier,
country_codes,
country_names
);
if (shouldApplyException(condition_map)) {
dbgDebug(D_RATE_LIMIT) << "found accept exception, not enforcing rate limit on this URI: " << uri;
return ACCEPT;
@@ -293,8 +376,8 @@ public:
return ACCEPT;
}
burst = rule.getRateLimit();
limit = calcRuleLimit(rule);
burst = static_cast<float>(rule.getRateLimit()) / replicas;
limit = static_cast<float>(calcRuleLimit(rule)) / replicas;
dbgTrace(D_RATE_LIMIT)
<< "found rate limit rule with: "
@@ -471,10 +554,18 @@ public:
}
unordered_map<string, set<string>>
createConditionMap(const string &uri, const string &source_ip, const string &source_identifier)
createConditionMap(
const string &uri,
const string &source_ip,
const string &source_identifier,
const set<string> &country_codes,
const set<string> &country_names
)
{
unordered_map<string, set<string>> condition_map;
if (!source_ip.empty()) condition_map["sourceIP"].insert(source_ip);
if (!country_codes.empty()) condition_map["countryCode"].insert(country_codes.begin(), country_codes.end());
if (!country_names.empty()) condition_map["countryName"].insert(country_names.begin(), country_names.end());
condition_map["sourceIdentifier"].insert(source_identifier);
condition_map["url"].insert(uri);
@@ -611,6 +702,21 @@ public:
"Initialize rate limit component",
false
);
i_shell_cmd = Singleton::Consume<I_ShellCmd>::by<RateLimit>();
i_env_details = Singleton::Consume<I_EnvDetails>::by<RateLimit>();
env_type = i_env_details->getEnvType();
if (env_type == EnvType::K8S) {
kubernetes_token = i_env_details->getToken();
kubernetes_namespace = i_env_details->getNameSpace();
fetchReplicaCount();
Singleton::Consume<I_MainLoop>::by<RateLimit>()->addRecurringRoutine(
I_MainLoop::RoutineType::Offline,
chrono::seconds(120),
[this]() { fetchReplicaCount(); },
"Fetch current replica count from the Kubernetes cluster"
);
}
}
void
@@ -619,6 +725,9 @@ public:
disconnectRedis();
}
I_ShellCmd *i_shell_cmd = nullptr;
I_EnvDetails* i_env_details = nullptr;
private:
static constexpr auto DROP = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_DROP;
static constexpr auto ACCEPT = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_ACCEPT;
@@ -629,6 +738,10 @@ private:
int burst;
float limit;
redisContext* redis = nullptr;
int replicas = 1;
EnvType env_type;
string kubernetes_namespace = "";
string kubernetes_token = "";
};
RateLimit::RateLimit() : Component("RateLimit"), pimpl(make_unique<Impl>()) {}

View File

@@ -137,9 +137,13 @@ public:
void setRemoteSyncEnabled(bool enabled);
protected:
void mergeProcessedFromRemote();
std::string getWindowId();
void waitSync();
std::string getPostDataUrl();
std::string getUri();
size_t getIntervalsCount();
void incrementIntervalsCount();
bool isBase();
template<typename T>
bool sendObject(T &obj, HTTPMethod method, std::string uri)
@@ -252,14 +256,13 @@ protected:
const std::string m_remotePath; // Created from tenentId + / + assetId + / + class
std::chrono::seconds m_interval;
std::string m_owner;
const std::string m_assetId;
private:
bool localSyncAndProcess();
void updateStateFromRemoteService();
RemoteFilesList getProcessedFilesList();
RemoteFilesList getRemoteProcessedFilesList();
std::string getWindowId();
bool isBase();
std::string getLearningHost();
std::string getSharedStorageHost();
@@ -270,7 +273,6 @@ private:
size_t m_windowsCount;
size_t m_intervalsCounter;
bool m_remoteSyncEnabled;
const std::string m_assetId;
const bool m_isAssetIdUuid;
std::string m_type;
std::string m_lastProcessedModified;

View File

@@ -19,12 +19,14 @@
#include "../waap_clib/WaapParameters.h"
#include "../waap_clib/WaapOpenRedirectPolicy.h"
#include "../waap_clib/WaapErrorDisclosurePolicy.h"
#include "../waap_clib/DecisionType.h"
#include "../waap_clib/CsrfPolicy.h"
#include "../waap_clib/UserLimitsPolicy.h"
#include "../waap_clib/RateLimiting.h"
#include "../waap_clib/SecurityHeadersPolicy.h"
#include <memory>
enum class BlockingLevel {
NO_BLOCKING = 0,
LOW_BLOCKING_LEVEL,
@@ -44,8 +46,8 @@ public:
virtual const std::string& get_AssetId() const = 0;
virtual const std::string& get_AssetName() const = 0;
virtual const BlockingLevel& get_BlockingLevel() const = 0;
virtual const std::string& get_PracticeId() const = 0;
virtual const std::string& get_PracticeName() const = 0;
virtual const std::string& get_PracticeIdByPactice(DecisionType practiceType) const = 0;
virtual const std::string& get_PracticeNameByPactice(DecisionType practiceType) const = 0;
virtual const std::string& get_PracticeSubType() const = 0;
virtual const std::string& get_RuleId() const = 0;
virtual const std::string& get_RuleName() const = 0;

View File

@@ -1,37 +0,0 @@
// Copyright (C) 2024 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
class IWaf2Transaction;
struct Waf2ScanResult;
namespace Waap {
namespace Scores {
struct ModelLoggingSettings;
}
}
class I_WaapModelResultLogger {
public:
virtual ~I_WaapModelResultLogger() {}
virtual void
logModelResult(
Waap::Scores::ModelLoggingSettings &settings,
IWaf2Transaction* transaction,
Waf2ScanResult &res,
std::string modelName,
std::string otherModelName,
double newScore,
double baseScore) = 0;
};

View File

@@ -87,9 +87,11 @@ add_library(waap_clib
ParserPairs.cc
Waf2Util2.cc
ParserPDF.cc
ParserKnownBenignSkipper.cc
ParserScreenedJson.cc
ParserBinaryFile.cc
RegexComparator.cc
WaapModelResultLogger.cc
RequestsMonitor.cc
)
add_definitions("-Wno-unused-function")

View File

@@ -28,6 +28,8 @@
#include "ParserDelimiter.h"
#include "ParserPDF.h"
#include "ParserBinaryFile.h"
#include "ParserKnownBenignSkipper.h"
#include "ParserScreenedJson.h"
#include "WaapAssetState.h"
#include "Waf2Regex.h"
#include "Waf2Util.h"
@@ -111,6 +113,9 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
<< parser_depth
<< " v_len = "
<< v_len;
dbgTrace(D_WAAP_DEEP_PARSER) << m_key;
// Decide whether to push/pop the value in the keystack.
bool shouldUpdateKeyStack = (flags & BUFFERED_RECEIVER_F_UNNAMED) == 0;
@@ -273,13 +278,23 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
// Detect and decode potential base64 chunks in the value before further processing
bool base64ParamFound = false;
size_t base64_offset = 0;
Waap::Util::BinaryFileType base64BinaryFileType = Waap::Util::BinaryFileType::FILE_TYPE_NONE;
if (m_depth == 1 && flags == BUFFERED_RECEIVER_F_MIDDLE && m_key.depth() == 1 && m_key.first() != "#base64"){
dbgTrace(D_WAAP_DEEP_PARSER) << " === will not check base64 since prev data block was not b64-encoded ===";
} else {
dbgTrace(D_WAAP_DEEP_PARSER) << " ===Processing potential base64===";
if (isUrlPayload && m_depth == 1 && cur_val[0] == '/') {
dbgTrace(D_WAAP_DEEP_PARSER) << "removing leading '/' from URL param value";
base64_offset = 1;
}
std::string decoded_val, decoded_key;
base64_variants base64_status = Waap::Util::b64Test(cur_val, decoded_key, decoded_val, base64BinaryFileType);
base64_variants base64_status = Waap::Util::b64Test(
cur_val,
decoded_key,
decoded_val,
base64BinaryFileType,
base64_offset);
dbgTrace(D_WAAP_DEEP_PARSER)
<< " status = "
@@ -287,16 +302,50 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
<< " key = "
<< decoded_key
<< " value = "
<< decoded_val;
<< decoded_val
<< "m_depth = "
<< m_depth;
switch (base64_status) {
case SINGLE_B64_CHUNK_CONVERT:
cur_val = decoded_val;
if (base64_offset) {
cur_val = "/" + decoded_val;
} else {
cur_val = decoded_val;
}
base64ParamFound = true;
break;
case CONTINUE_DUAL_SCAN:
if (decoded_val.size() > 0) {
decoded_key = "#base64";
base64ParamFound = false;
if (base64_offset) {
decoded_val = "/" + decoded_val;
}
dbgTrace(D_WAAP_DEEP_PARSER) << m_key;
rc = onKv(
decoded_key.c_str(),
decoded_key.size(),
decoded_val.data(),
decoded_val.size(),
flags,
parser_depth
);
dbgTrace(D_WAAP_DEEP_PARSER) << "After call to onKv with suspected value rc = " << rc;
dbgTrace(D_WAAP_DEEP_PARSER) << m_key;
break;
} else {
dbgTrace(D_WAAP) << "base64 decode suspected and empty value. Skipping.";
base64ParamFound = false;
break;
}
break;
case KEY_VALUE_B64_PAIR:
// going deep with new pair in case value is not empty
if (decoded_val.size() > 0) {
if (base64_offset) {
decoded_key = "/" + decoded_key;
}
cur_val = decoded_val;
base64ParamFound = true;
rc = onKv(
@@ -307,9 +356,13 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
flags,
parser_depth
);
dbgTrace(D_WAAP_DEEP_PARSER) << " rc = " << rc;
dbgTrace(D_WAAP_DEEP_PARSER) << "After call to onKv with suspected value rc = " << rc;
dbgTrace(D_WAAP_DEEP_PARSER) << m_key;
if (rc != CONTINUE_PARSING) {
if (shouldUpdateKeyStack) {
m_key.pop("deep parser key");
}
m_depth--;
return rc;
}
}
@@ -321,7 +374,7 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
}
if (base64ParamFound) {
dbgTrace(D_WAAP_DEEP_PARSER) << "DeepParser::onKv(): pushing #base64 prefix to the key.";
dbgTrace(D_WAAP_DEEP_PARSER) << "pushing #base64 prefix to the key.";
m_key.push("#base64", 7, false);
}
}
@@ -359,6 +412,7 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
isRefererParamPayload,
isUrlPayload,
isUrlParamPayload,
isCookiePayload,
flags,
parser_depth,
base64BinaryFileType
@@ -410,6 +464,7 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
isRefererParamPayload,
isUrlPayload,
isUrlParamPayload,
isCookiePayload,
flags,
parser_depth,
base64BinaryFileType
@@ -433,7 +488,6 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
if (shouldUpdateKeyStack) {
m_key.pop("deep parser key");
}
m_depth--;
return rc;
}
@@ -461,6 +515,7 @@ DeepParser::onKv(const char *k, size_t k_len, const char *v, size_t v_len, int f
isRefererParamPayload,
isUrlPayload,
isUrlParamPayload,
isCookiePayload,
flags,
parser_depth,
base64ParamFound,
@@ -582,7 +637,6 @@ DeepParser::parseBuffer(
if (shouldUpdateKeyStack) {
m_key.pop("deep parser key");
}
m_depth--;
return DONE_PARSING;
}
@@ -835,6 +889,7 @@ DeepParser::parseAfterMisleadingMultipartBoundaryCleaned(
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth,
bool base64ParamFound,
@@ -854,6 +909,7 @@ DeepParser::parseAfterMisleadingMultipartBoundaryCleaned(
isRefererParamPayload,
isUrlPayload,
isUrlParamPayload,
isCookiePayload,
flags,
parser_depth,
b64FileType
@@ -902,7 +958,6 @@ DeepParser::parseAfterMisleadingMultipartBoundaryCleaned(
return rc;
}
}
return rc;
}
@@ -918,6 +973,7 @@ bool isRefererPayload,
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth
) {
@@ -959,6 +1015,7 @@ DeepParser::createInternalParser(
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth,
Waap::Util::BinaryFileType b64FileType
@@ -978,7 +1035,19 @@ DeepParser::createInternalParser(
<< "\n\tflags: "
<< flags
<< "\n\tparser_depth: "
<< parser_depth;
<< parser_depth
<< "\n\tisBodyPayload: "
<< isBodyPayload
<< "\n\tisRefererPayload: "
<< isRefererPayload
<< "\n\tisRefererParamPayload: "
<< isRefererParamPayload
<< "\n\tisUrlPayload: "
<< isUrlPayload
<< "\n\tisUrlParamPayload: "
<< isUrlParamPayload
<< "\n\tisCookiePayload: "
<< isCookiePayload;
bool isPipesType = false, isSemicolonType = false, isAsteriskType = false, isCommaType = false,
isAmperType = false;
bool isKeyValDelimited = false;
@@ -1045,6 +1114,53 @@ DeepParser::createInternalParser(
}
}
if (Waap::Util::isScreenedJson(cur_val)) {
dbgTrace(D_WAAP_DEEP_PARSER) << "Starting to parse screened JSON";
m_parsersDeque.push_back(std::make_shared<BufferedParser<ParserScreenedJson>>(*this, parser_depth + 1));
offset = 0;
return offset;
}
dbgTrace(D_WAAP_DEEP_PARSER)
<< "Offset = "
<< offset
<< " depth = "
<< m_depth
<< " isBodyPayload = "
<< isBodyPayload;
//Detect sensor_data format in body and just use dedicated filter for it
if ((m_depth == 1)
&& isBodyPayload
&& Waap::Util::detectKnownSource(cur_val) == Waap::Util::SOURCE_TYPE_SENSOR_DATA) {
m_parsersDeque.push_back(
std::make_shared<BufferedParser<ParserKnownBenignSkipper>>(
*this,
parser_depth + 1,
Waap::Util::SOURCE_TYPE_SENSOR_DATA
)
);
offset = 0;
dbgTrace(D_WAAP_DEEP_PARSER) << "Starting to parse data_sensor data - skipping it";
return offset;
}
// Detect cookie parameter sensorsdata2015jssdkcross
// and causes false positives due to malformed JSON. Make preprocessing to parse it correctly
if (m_depth == 2
&& isCookiePayload) {
offset = Waap::Util::definePrefixedJson(cur_val);
if (offset >= 0) {
m_parsersDeque.push_back(
std::make_shared<BufferedParser<ParserJson>>(
*this,
parser_depth + 1,
m_pTransaction
)
);
dbgTrace(D_WAAP_DEEP_PARSER) << "Starting to parse JSON data";
return offset;
}
}
// Detect wbxml (binary XML) data type
if (m_depth == 1 && isBodyPayload && !valueStats.isUTF16 && m_pWaapAssetState->isWBXMLSampleType(cur_val)) {
m_is_wbxml = true;
@@ -1374,6 +1490,7 @@ DeepParser::createInternalParser(
isRefererParamPayload,
isUrlPayload,
isUrlParamPayload,
isCookiePayload,
flags,
parser_depth
);

View File

@@ -129,6 +129,7 @@ private:
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth,
Waap::Util::BinaryFileType b64FileType
@@ -144,6 +145,7 @@ private:
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth
);
@@ -160,6 +162,7 @@ private:
bool isRefererParamPayload,
bool isUrlPayload,
bool isUrlParamPayload,
bool isCookiePayload,
int flags,
size_t parser_depth,
bool base64ParamFound,

View File

@@ -37,14 +37,24 @@ void KeyStack::push(const char* subkey, size_t subkeySize, bool countDepth) {
m_nameDepth++;
}
dbgTrace(D_WAAP) << "KeyStack(" << m_name << ")::push(): '" << std::string(subkey, subkeySize) <<
"' => full_key='" << std::string(m_key.data(), m_key.size()) << "'";
dbgTrace(D_WAAP)
<< "KeyStack("
<< m_name
<< ")::push(): '"
<< std::string(subkey, subkeySize)
<< "' => full_key='"
<< std::string(m_key.data(), m_key.size())
<< "'";
}
void KeyStack::pop(const char* log, bool countDepth) {
// Keep depth balanced even if m_key[] buffer is full
if (m_key.empty() || m_stack.empty()) {
dbgDebug(D_WAAP) << "KeyStack(" << m_name << ")::pop(): [ERROR] ATTEMPT TO POP FROM EMPTY KEY STACK! " << log;
dbgDebug(D_WAAP)
<< "KeyStack("
<< m_name
<< ")::pop(): [ERROR] ATTEMPT TO POP FROM EMPTY KEY STACK! "
<< log;
return;
}
@@ -55,6 +65,22 @@ void KeyStack::pop(const char* log, bool countDepth) {
// Remove last subkey.
m_key.erase(m_stack.back());
m_stack.pop_back();
dbgTrace(D_WAAP) << "KeyStack(" << m_name << ")::pop(): full_key='" <<
std::string(m_key.data(), (int)m_key.size()) << "': pop_key=" << log << "'";
dbgTrace(D_WAAP)
<< "KeyStack("
<< m_name
<< ")::pop(): full_key='"
<< std::string(m_key.data(), (int)m_key.size())
<< "': pop_key="
<< log
<< "'";
}
void KeyStack::print(std::ostream &os) const
{
os
<< "KeyStack("
<< m_name
<< ")::show(): full_key='"
<< std::string(m_key.data(), (int)m_key.size())
<< "'";
}

View File

@@ -28,6 +28,7 @@ public:
void pop(const char* log, bool countDepth=true);
bool empty() const { return m_key.empty(); }
void clear() { m_key.clear(); m_stack.clear(); }
void print(std::ostream &os) const;
size_t depth() const { return m_nameDepth; }
size_t size() const {
return str().size();

View File

@@ -111,8 +111,7 @@ int BufferedReceiver::onKvDone()
// This must be called even if m_value is empty in order to signal the BUFFERED_RECEIVER_F_LAST flag to the
// receiver!
dbgTrace(D_WAAP_PARSER)
<< " Call onKv on the remainder of the buffer not yet pushed to the receiver "
<< "calling onKv()";
<< " Call onKv on the remainder of the buffer not yet pushed to the receiver calling onKv()";
int rc = onKv(m_key.data(), m_key.size(), m_value.data(), m_value.size(), m_flags, m_parser_depth);
// Reset the object's state to allow reuse for other parsers

View File

@@ -0,0 +1,139 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "ParserKnownBenignSkipper.h"
#include "Waf2Util.h"
#include "debug.h"
#include <string.h>
USE_DEBUG_FLAG(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER);
USE_DEBUG_FLAG(D_WAAP);
const std::string ParserKnownBenignSkipper::m_parserName = "ParserKnownBenignSkipper";
const char* DATA_SENSOR_TAIL = "\"}";
ParserKnownBenignSkipper::ParserKnownBenignSkipper(
IParserStreamReceiver &receiver,
size_t parser_depth,
Waap::Util::KnownSourceType source_type
) :
m_receiver(receiver),
m_state(s_start),
m_parser_depth(parser_depth),
m_source_type(source_type)
{}
ParserKnownBenignSkipper::~ParserKnownBenignSkipper()
{}
size_t
ParserKnownBenignSkipper::push(const char *buf, size_t len)
{
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "buf='"
<< std::string(buf, std::min((size_t)200, len))
<< (len > 200 ? "..." : "")
<< "' len="
<< len
<< " depth="
<< depth();
const char *c;
if (m_state == s_error) {
return 0;
}
if (len == 0)
{
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "ParserKnownBenignSkipper::push(): end of stream. m_state="
<< m_state;
if (m_state == s_end) {
m_receiver.onKvDone();
} else {
m_state = s_error;
}
return 0;
}
size_t tail_lookup_offset = 0;
switch (m_state) {
case s_start:
m_state = s_body;
CP_FALL_THROUGH;
case s_body:
{
if (m_source_type == Waap::Util::SOURCE_TYPE_SENSOR_DATA) {
tail_lookup_offset =
(len > MAX_DATA_SENSOR_TAIL_LOOKUP) ? len - MAX_DATA_SENSOR_TAIL_LOOKUP : 0;
c = strstr(buf + tail_lookup_offset, DATA_SENSOR_TAIL);
if (c) {
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "ParserKnownBenignSkipper::push(): found end of sensor data";
m_state = s_end;
CP_FALL_THROUGH;
} else {
break;
}
} else {
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "ParserKnownBenignSkipper::push(): unknown source type";
m_state = s_error;
break;
}
}
case s_end:
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER) << "state = end";
if (m_receiver.onKey("SENSOR_DATA", 11) != 0) {
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER) << "state moving to error onKey";
m_state = s_error;
return 0;
}
if (m_receiver.onValue("", 0) != 0) {
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER) << "state moving to error onValue";
m_state = s_error;
return 0;
}
break;
case s_error:
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER) << "state = error";
break;
default:
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "ParserKnownBenignSkipper::push(): unknown state: "
<< m_state;
m_state = s_error;
return 0;
}
dbgTrace(D_WAAP_PARSER_KNOWN_SOURCE_SKIPPER)
<< "ParserKnownBenignSkipper::push(): final state: "
<< m_state;
return len;
}
void ParserKnownBenignSkipper::finish()
{
push(NULL, 0);
}
const std::string& ParserKnownBenignSkipper::name() const
{
return m_parserName;
}
bool ParserKnownBenignSkipper::error() const
{
return m_state == s_error;
}

View File

@@ -0,0 +1,52 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __PARSER_BENIGN_SKIPPER_H__
#define __PARSER_BENIGN_SKIPPER_H__
#include "ParserBase.h"
#include "Waf2Util.h"
#include <string.h>
#include "Waf2Util.h"
#define MAX_DATA_SENSOR_TAIL_LOOKUP 5
class ParserKnownBenignSkipper : public ParserBase {
public:
ParserKnownBenignSkipper(
IParserStreamReceiver &receiver,
size_t parser_depth,
Waap::Util::KnownSourceType source_type=Waap::Util::SOURCE_TYPE_UNKNOWN);
virtual ~ParserKnownBenignSkipper();
virtual size_t push(const char *buf, size_t len);
virtual void finish();
virtual const std::string &name() const;
virtual bool error() const;
virtual size_t depth() { return 1; }
private:
enum state {
s_start,
s_body,
s_end,
s_error
};
IParserStreamReceiver &m_receiver;
enum state m_state;
static const std::string m_parserName;
size_t m_parser_depth;
Waap::Util::KnownSourceType m_source_type;
};
#endif // __PARSER_BENIGN_SKIPPER_H__

View File

@@ -21,6 +21,7 @@ USE_DEBUG_FLAG(D_WAAP);
const std::string ParserPDF::m_parserName = "ParserPDF";
const char* PDF_TAIL = "%%EOF";
const size_t PDF_TAIL_LEN = 5;
ParserPDF::ParserPDF(
IParserStreamReceiver &receiver,
@@ -44,16 +45,21 @@ ParserPDF::push(const char *buf, size_t len)
<< "' len="
<< len;
const char *c;
if (m_state == s_error) {
return 0;
}
if (len == 0)
{
dbgTrace(D_WAAP_PARSER_PDF) << "ParserPDF::push(): end of stream. m_state=" << m_state;
if (m_state == s_end) {
if (len == 0) {
dbgTrace(D_WAAP_PARSER_PDF) << "ParserPDF::push(): end of stream. m_state=" << m_state;
if (m_state == s_body && m_tailOffset >= PDF_TAIL_LEN) {
if (m_receiver.onKey("PDF", 3) != 0) {
m_state = s_error;
return 0;
}
if (m_receiver.onValue("", 0) != 0) {
m_state = s_error;
return 0;
}
m_receiver.onKvDone();
} else {
m_state = s_error;
@@ -61,38 +67,43 @@ ParserPDF::push(const char *buf, size_t len)
return 0;
}
size_t start = (len > MAX_PDF_TAIL_LOOKUP) ? len - MAX_PDF_TAIL_LOOKUP : 0;
switch (m_state) {
case s_start:
m_state = s_body;
CP_FALL_THROUGH;
case s_body:
{
size_t tail_lookup_offset = (len > MAX_PDF_TAIL_LOOKUP) ? len - MAX_PDF_TAIL_LOOKUP : 0;
c = strstr(buf + tail_lookup_offset, PDF_TAIL);
for (size_t i = start; i < len; i++) {
dbgTrace(D_WAAP_PARSER_PDF)
<< "string to search: " << std::string(buf + tail_lookup_offset)
<< " c=" << c;
if (c) {
m_state = s_end;
CP_FALL_THROUGH;
<< "ParserPDF::push(): m_tailOffset="
<< m_tailOffset
<< " buf[i]="
<< buf[i];
if (m_tailOffset <= PDF_TAIL_LEN - 1) {
if (buf[i] == PDF_TAIL[m_tailOffset]) {
m_tailOffset++;
} else {
m_tailOffset = 0;
}
} else {
break;
if (buf[i] == '\r' || buf[i] == '\n' || buf[i] == ' ' || buf[i] == 0) {
m_tailOffset++;
} else {
m_tailOffset = 0;
i--;
}
}
}
case s_end:
if (m_receiver.onKey("PDF", 3) != 0) {
m_state = s_error;
return 0;
}
if (m_receiver.onValue("", 0) != 0) {
m_state = s_error;
return 0;
}
dbgTrace(D_WAAP_PARSER_PDF)
<< "ParserPDF::push()->s_body: m_tailOffset="
<< m_tailOffset;
break;
case s_error:
break;
default:
dbgTrace(D_WAAP_PARSER_PDF) << "ParserPDF::push(): unknown state: " << m_state;
dbgTrace(D_WAAP_PARSER_PDF)
<< "ParserPDF::push(): unknown state: "
<< m_state;
m_state = s_error;
return 0;
}

View File

@@ -34,7 +34,6 @@ private:
enum state {
s_start,
s_body,
s_end,
s_error
};
@@ -42,6 +41,7 @@ private:
enum state m_state;
static const std::string m_parserName;
size_t m_parser_depth;
size_t m_tailOffset = 0;
};
#endif // __PARSER_PDF_H__

View File

@@ -0,0 +1,187 @@
#include "ParserScreenedJson.h"
#include "debug.h"
USE_DEBUG_FLAG(D_WAAP_PARSER_SCREENED_JSON);
const std::string ParserScreenedJson::m_parserName = "ParserScreenedJson";
ParserScreenedJson::ParserScreenedJson(IParserStreamReceiver &receiver, size_t parser_depth) :
m_receiver(receiver),
m_state(s_start),
m_unscreenedLen(0),
m_leftoverLen(0),
m_parser_depth(parser_depth)
{
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "parser_depth="
<< parser_depth;
memset(m_unscreened, 0, sizeof(m_unscreened));
}
ParserScreenedJson::~ParserScreenedJson()
{}
size_t
ParserScreenedJson::push(const char *buf, size_t len)
{
size_t i = 0;
char c;
dbgTrace(D_WAAP_PARSER_SCREENED_JSON) << "ParserScreenedJson::push(): starting (len=" << len << ")";
if (len == 0) {
dbgTrace(D_WAAP_PARSER_SCREENED_JSON) << "ParserScreenedJson::push(): end of data signal! m_state=" << m_state;
// flush unescaped data collected (if any)
if (m_leftoverLen > 0) {
// No need any processing for leftover data - last char must be doublequote, else - error
m_state = s_error;
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): end of data and leftover detected m_state="
<< m_state;
return i;
}
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): s_value, pushing m_unscreened = "
<< m_unscreened
<< ", m_leftoverLen = "
<< m_leftoverLen
<< ", m_unscreenedLen = "
<< m_unscreenedLen;
if (m_receiver.onKey("json_unscreened", 15) != 0) {
m_state = s_error;
return i;
}
if (m_receiver.onValue(m_unscreened, m_unscreenedLen) != 0) {
m_state = s_error;
return i;
}
if (m_receiver.onKvDone() != 0)
{
m_state = s_error;
return i;
}
return 0;
}
while (i < len)
{
c = buf[i];
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): state="
<< m_state
<< "; c='"
<< c
<< "'"
<< "; i="
<< i
<< ", m_leftoverLen = "
<< m_leftoverLen
<< ", m_unscreenedLen = "
<< m_unscreenedLen
<< ", m_unscreened = "
<< m_unscreened;
switch (m_state)
{
case s_start:
{
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): s_start";
m_state = s_value;
// fallthrough not required, removing 1st doublequote, it denoted by regex //
//CP_FALL_THROUGH;
break;
}
case s_value:
{
if (c == '\\') {
if (m_leftoverLen > 0) {
m_unscreened[m_unscreenedLen] = '\\';
m_leftoverLen = 0;
m_unscreenedLen++;
} else {
m_leftoverLen++;
}
} else if (c =='\"') {
if (m_leftoverLen > 0) {
m_unscreened[m_unscreenedLen] = '\"';
m_unscreenedLen++;
if (m_leftoverLen > 0) {
m_leftoverLen = 0;
}
}
} else {
if (m_leftoverLen > 0) {
m_unscreened[m_unscreenedLen] = '\\';
m_unscreenedLen++;
m_leftoverLen = 0;
}
m_unscreened[m_unscreenedLen] = c;
m_unscreenedLen++;
}
if (m_unscreenedLen >= MAX_UNSCREENED_JSON_SIZE) {
if (m_receiver.onKey("json_unscreened", 15) != 0) {
m_state = s_error;
return i;
}
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): s_value, pushing m_unscreened = "
<< m_unscreened
<< ", m_leftoverLen = "
<< m_leftoverLen
<< ", m_unscreenedLen = "
<< m_unscreenedLen;
if (m_receiver.onValue(m_unscreened, m_unscreenedLen) != 0) {
m_state = s_error;
return i;
}
m_unscreenedLen = 0;
}
break;
}
case s_error:
{
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): s_error";
return 0;
}
default:
{
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): JSON parser unrecoverable error";
m_state = s_error;
return 0;
}
}
++i;
}
dbgTrace(D_WAAP_PARSER_SCREENED_JSON)
<< "ParserScreenedJson::push(): finished: len="
<< len;
return len;
}
void
ParserScreenedJson::finish()
{
push(NULL, 0);
}
const std::string &
ParserScreenedJson::name() const
{
return m_parserName;
}
bool
ParserScreenedJson::error() const
{
return m_state == s_error;
}

View File

@@ -0,0 +1,52 @@
// Copyright (C) 2022 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef __PARSER_SCREENED_JSON_H_
#define __PARSER_SCREENED_JSON_H_
#include "ParserBase.h"
#include <string.h>
#define MAX_UNSCREENED_JSON_SIZE 4095
class ParserScreenedJson : public ParserBase {
public:
ParserScreenedJson(IParserStreamReceiver &receiver, size_t parser_depth);
virtual ~ParserScreenedJson();
size_t push(const char *data, size_t data_len);
void finish();
virtual const std::string &name() const;
bool error() const;
// LCOV_EXCL_START Reason: The function not in use, compliance with the interface
virtual size_t depth() { return 1; }
// LCOV_EXCL_STOP
private:
enum state
{
s_start,
s_value,
s_error
};
IParserStreamReceiver &m_receiver;
enum state m_state;
size_t m_unscreenedLen;
char m_unscreened[MAX_UNSCREENED_JSON_SIZE];
size_t m_leftoverLen;
static const std::string m_parserName;
size_t m_parser_depth;
};
#endif

View File

@@ -0,0 +1,158 @@
#include "RequestsMonitor.h"
#include "waap.h"
#include "SyncLearningNotification.h"
#include "report_messaging.h"
#include "customized_cereal_map.h"
USE_DEBUG_FLAG(D_WAAP_CONFIDENCE_CALCULATOR);
using namespace std;
SourcesRequestMonitor::SourcesRequestMonitor(
const string& filePath,
const string& remotePath,
const string& assetId,
const string& owner) :
SerializeToLocalAndRemoteSyncBase(
chrono::minutes(10),
chrono::seconds(30),
filePath,
remotePath != "" ? remotePath + "/Monitor" : remotePath,
assetId,
owner
), m_sourcesRequests()
{
}
SourcesRequestMonitor::~SourcesRequestMonitor()
{
}
void SourcesRequestMonitor::syncWorker()
{
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR) << "Running the sync worker for assetId='" << m_assetId << "', owner='" <<
m_owner << "'";
incrementIntervalsCount();
OrchestrationMode mode = Singleton::exists<I_AgentDetails>() ?
Singleton::Consume<I_AgentDetails>::by<WaapComponent>()->getOrchestrationMode() : OrchestrationMode::ONLINE;
bool enabled = getProfileAgentSettingWithDefault<bool>(false, "appsec.sourceRequestsMonitor.enabled");
if (mode == OrchestrationMode::OFFLINE || !enabled || isBase() || !postData()) {
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR)
<< "Did not report data. for asset: "
<< m_assetId
<< " Remote URL: "
<< m_remotePath
<< " is enabled: "
<< to_string(enabled)
<< ", mode: " << int(mode);
return;
}
dbgTrace(D_WAAP_CONFIDENCE_CALCULATOR) << "Waiting for all agents to post their data";
waitSync();
if (mode == OrchestrationMode::HYBRID) {
dbgDebug(D_WAAP_CONFIDENCE_CALCULATOR) << "detected running in standalone mode. not sending sync notification";
} else {
SyncLearningNotificationObject syncNotification(m_assetId, "Monitor", getWindowId());
dbgDebug(D_WAAP_CONFIDENCE_CALCULATOR) << "sending sync notification: " << syncNotification;
ReportMessaging(
"sync notification for '" + m_assetId + "'",
ReportIS::AudienceTeam::WAAP,
syncNotification,
MessageCategory::GENERIC,
ReportIS::Tags::WAF,
ReportIS::Notification::SYNC_LEARNING
);
}
}
void SourcesRequestMonitor::logSourceHit(const string& source)
{
m_sourcesRequests[chrono::duration_cast<chrono::minutes>(
Singleton::Consume<I_TimeGet>::by<WaapComponent>()->getWalltime()
).count()][source]++;
}
// LCOV_EXCL_START Reason: internal functions not used
void SourcesRequestMonitor::pullData(const vector<string> &data)
{
// not used. report only
}
void SourcesRequestMonitor::processData()
{
// not used. report only
}
void SourcesRequestMonitor::postProcessedData()
{
// not used. report only
}
void SourcesRequestMonitor::pullProcessedData(const vector<string> &data)
{
// not used. report only
}
void SourcesRequestMonitor::updateState(const vector<string> &data)
{
// not used. report only
}
// LCOV_EXCL_STOP
typedef map<string, map<string, size_t>> MonitorJsonData;
class SourcesRequestsReport : public RestGetFile
{
public:
SourcesRequestsReport(MonitorData& _sourcesRequests, const string& _agentId)
: sourcesRequests(), agentId(_agentId)
{
MonitorJsonData montiorData;
for (const auto& window : _sourcesRequests) {
for (const auto& source : window.second) {
montiorData[to_string(window.first)][source.first] = source.second;
}
}
sourcesRequests = montiorData;
}
private:
C2S_PARAM(MonitorJsonData, sourcesRequests);
C2S_PARAM(string, agentId);
};
bool SourcesRequestMonitor::postData()
{
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR) << "Sending the data to remote";
// send collected data to remote and clear the local data
string url = getPostDataUrl();
string agentId = Singleton::Consume<I_AgentDetails>::by<WaapComponent>()->getAgentId();
SourcesRequestsReport currentWindow(m_sourcesRequests, agentId);
bool ok = sendNoReplyObjectWithRetry(currentWindow,
HTTPMethod::PUT,
url);
if (!ok) {
dbgError(D_WAAP_CONFIDENCE_CALCULATOR) << "Failed to post collected data to: " << url;
}
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR) << "Data sent to remote: " << ok;
m_sourcesRequests.clear();
return ok;
}
void SourcesRequestMonitor::serialize(ostream& stream)
{
cereal::JSONOutputArchive archive(stream);
archive(m_sourcesRequests);
}
void SourcesRequestMonitor::deserialize(istream& stream)
{
cereal::JSONInputArchive archive(stream);
archive(m_sourcesRequests);
}

View File

@@ -0,0 +1,33 @@
#ifndef __REQUESTS_MONITOR_H__
#define __REQUESTS_MONITOR_H__
#include "i_serialize.h"
typedef std::map<uint64_t, std::map<std::string, size_t>> MonitorData;
class SourcesRequestMonitor : public SerializeToLocalAndRemoteSyncBase
{
public:
SourcesRequestMonitor(
const std::string& filePath,
const std::string& remotePath,
const std::string& assetId,
const std::string& owner);
virtual ~SourcesRequestMonitor();
virtual void syncWorker() override;
void logSourceHit(const std::string& source);
protected:
virtual void pullData(const std::vector<std::string> &data) override;
virtual void processData() override;
virtual void postProcessedData() override;
virtual void pullProcessedData(const std::vector<std::string> &data) override;
virtual void updateState(const std::vector<std::string> &data) override;
virtual bool postData() override;
void serialize(std::ostream& stream);
void deserialize(std::istream& stream);
private:
// map of sources and their requests per minute (UNIX)
MonitorData m_sourcesRequests;
};
#endif // __REQUESTS_MONITOR_H__

View File

@@ -194,6 +194,10 @@ void SerializeToFileBase::saveData()
dbgWarning(D_WAAP_CONFIDENCE_CALCULATOR) << "Failed to gzip data";
} else {
ss.str(string((const char *)res.output, res.num_output_bytes));
// free the memory allocated by compressData
if (res.output) free(res.output);
res.output = nullptr;
res.num_output_bytes = 0;
}
if (res.output) free(res.output);
res.output = nullptr;
@@ -403,6 +407,7 @@ SerializeToLocalAndRemoteSyncBase::SerializeToLocalAndRemoteSyncBase(
m_remotePath(replaceAllCopy(remotePath, "//", "/")),
m_interval(0),
m_owner(owner),
m_assetId(replaceAllCopy(assetId, "/", "")),
m_pMainLoop(nullptr),
m_waitForSync(waitForSync),
m_workerRoutineId(0),
@@ -410,7 +415,6 @@ SerializeToLocalAndRemoteSyncBase::SerializeToLocalAndRemoteSyncBase(
m_windowsCount(0),
m_intervalsCounter(0),
m_remoteSyncEnabled(true),
m_assetId(replaceAllCopy(assetId, "/", "")),
m_isAssetIdUuid(Waap::Util::isUuid(assetId)),
m_shared_storage_host(genError("not set")),
m_learning_host(genError("not set"))
@@ -465,6 +469,15 @@ bool SerializeToLocalAndRemoteSyncBase::isBase()
return m_remotePath == "";
}
void SerializeToLocalAndRemoteSyncBase::waitSync()
{
if (m_pMainLoop == nullptr)
{
return;
}
m_pMainLoop->yield(m_waitForSync);
}
string SerializeToLocalAndRemoteSyncBase::getUri()
{
static const string hybridModeUri = "/api";
@@ -480,6 +493,11 @@ size_t SerializeToLocalAndRemoteSyncBase::getIntervalsCount()
return m_intervalsCounter;
}
void SerializeToLocalAndRemoteSyncBase::incrementIntervalsCount()
{
m_intervalsCounter++;
}
SerializeToLocalAndRemoteSyncBase::~SerializeToLocalAndRemoteSyncBase()
{
@@ -599,6 +617,17 @@ void SerializeToLocalAndRemoteSyncBase::setInterval(ch::seconds newInterval)
bool SerializeToLocalAndRemoteSyncBase::localSyncAndProcess()
{
bool isBackupSyncEnabled = getProfileAgentSettingWithDefault<bool>(
true,
"appsecLearningSettings.backupLocalSync");
if (!isBackupSyncEnabled) {
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR) << "Local sync is disabled";
processData();
saveData();
return true;
}
RemoteFilesList rawDataFiles;
dbgTrace(D_WAAP_CONFIDENCE_CALCULATOR) << "Getting files of all agents";
@@ -655,7 +684,7 @@ void SerializeToLocalAndRemoteSyncBase::syncWorker()
{
dbgInfo(D_WAAP_CONFIDENCE_CALCULATOR) << "Running the sync worker for assetId='" << m_assetId << "', owner='" <<
m_owner << "'" << " last modified state: " << m_lastProcessedModified;
m_intervalsCounter++;
incrementIntervalsCount();
OrchestrationMode mode = Singleton::exists<I_AgentDetails>() ?
Singleton::Consume<I_AgentDetails>::by<WaapComponent>()->getOrchestrationMode() : OrchestrationMode::ONLINE;
@@ -674,7 +703,7 @@ void SerializeToLocalAndRemoteSyncBase::syncWorker()
}
dbgTrace(D_WAAP_CONFIDENCE_CALCULATOR) << "Waiting for all agents to post their data";
m_pMainLoop->yield(m_waitForSync);
waitSync();
// check if learning service is operational
if (m_lastProcessedModified == "")
{

View File

@@ -33,6 +33,7 @@ WaapTelemetryBase::sendLog(const LogRest &metric_client_rest) const
OrchestrationMode mode = Singleton::Consume<I_AgentDetails>::by<GenericMetric>()->getOrchestrationMode();
GenericMetric::sendLog(metric_client_rest);
dbgTrace(D_WAAP) << "Waap telemetry log sent: " << metric_client_rest.genJson().unpack();
if (mode == OrchestrationMode::ONLINE) {
return;
@@ -79,7 +80,16 @@ void
WaapTelemetrics::updateMetrics(const string &asset_id, const DecisionTelemetryData &data)
{
initMetrics();
requests.report(1);
auto is_keep_alive_ctx = Singleton::Consume<I_Environment>::by<GenericMetric>()->get<bool>(
"keep_alive_request_ctx"
);
if (!is_keep_alive_ctx.ok() || !*is_keep_alive_ctx) {
requests.report(1);
} else {
dbgTrace(D_WAAP) << "Not increasing the number of requests due to keep alive";
}
if (sources_seen.find(data.source) == sources_seen.end()) {
if (sources.getCounter() == 0) sources_seen.clear();
sources_seen.insert(data.source);
@@ -274,7 +284,9 @@ WaapMetricWrapper::upon(const WaapTelemetryEvent &event)
ReportIS::IssuingEngine::AGENT_CORE,
chrono::minutes(LOGGING_INTERVAL_IN_MINUTES),
true,
ReportIS::Audience::INTERNAL
ReportIS::Audience::INTERNAL,
false,
asset_id
);
metrics[asset_id]->registerListener();
}
@@ -286,7 +298,9 @@ WaapMetricWrapper::upon(const WaapTelemetryEvent &event)
ReportIS::IssuingEngine::AGENT_CORE,
chrono::minutes(LOGGING_INTERVAL_IN_MINUTES),
true,
ReportIS::Audience::INTERNAL
ReportIS::Audience::INTERNAL,
false,
asset_id
);
attack_types[asset_id]->registerListener();
}

View File

@@ -135,6 +135,7 @@ WaapAssetState::WaapAssetState(std::shared_ptr<Signatures> signatures,
m_Signatures(signatures),
m_waapDataFileName(waapDataFileName),
m_assetId(assetId),
m_requestsMonitor(nullptr),
scoreBuilder(this),
m_rateLimitingState(nullptr),
m_errorLimitingState(nullptr),
@@ -152,10 +153,14 @@ WaapAssetState::WaapAssetState(std::shared_ptr<Signatures> signatures,
I_AgentDetails* agentDetails = Singleton::Consume<I_AgentDetails>::by<WaapComponent>();
std::string path = agentDetails->getTenantId() + "/" + assetId;
m_filtersMngr = std::make_shared<IndicatorsFiltersManager>(path, assetId, this);
m_requestsMonitor = std::make_shared<SourcesRequestMonitor>
(getWaapDataDir() + "/monitor.data", path, assetId, "State");
}
else
{
m_filtersMngr = std::make_shared<IndicatorsFiltersManager>("", "", this);
m_requestsMonitor = std::make_shared<SourcesRequestMonitor>
(getWaapDataDir() + "/monitor.data", "", assetId, "State");
}
// Load keyword scores - copy from ScoreBuilder
updateScores();
@@ -783,6 +788,55 @@ WaapAssetState::filterKeywordsDueToLongText(Waf2ScanResult &res) const
#endif
}
// std::string nicePrint() - is a function used to create std::string that will represent all data that is
// collected inside Waf2ScanResult object. This function is used for debugging purposes. it should make deep-dive
// into the object easier.
std::string
WaapAssetState::nicePrint(Waf2ScanResult &res) const
{
std::string result = "Waf2ScanResult:\n";
result += "keyword_matches:\n";
for (const auto &keyword : res.keyword_matches) {
result += keyword + "\n";
}
result += "regex_matches:\n";
for (const auto &regex : res.regex_matches) {
result += regex + "\n";
}
result += "filtered_keywords:\n";
for (const auto &filtered : res.filtered_keywords) {
result += filtered + "\n";
}
result += "found_patterns:\n";
for (const auto &pattern : res.found_patterns) {
result += pattern.first + ":\n";
for (const auto &value : pattern.second) {
result += value + "\n";
}
}
result += "unescaped_line: " + res.unescaped_line + "\n";
result += "param_name: " + res.param_name + "\n";
result += "location: " + res.location + "\n";
result += "score: " + std::to_string(res.score) + "\n";
result += "scoreNoFilter: " + std::to_string(res.scoreNoFilter) + "\n";
result += "scoreArray:\n";
for (const auto &score : res.scoreArray) {
result += std::to_string(score) + "\n";
}
result += "keywordCombinations:\n";
for (const auto &combination : res.keywordCombinations) {
result += combination + "\n";
}
result += "attack_types:\n";
for (const auto &attack : res.attack_types) {
result += attack + "\n";
}
result += "m_isAttackInParam: " + std::to_string(res.m_isAttackInParam) + "\n";
return result;
}
bool
checkBinaryData(const std::string &line, bool binaryDataFound)
{
@@ -1033,7 +1087,7 @@ WaapAssetState::apply(
// Scan unescaped_line with aho-corasick once, and reuse it in multiple calls to checkRegex below
// This is done to improve performance of regex matching.
SampleValue unescapedLineSample(res.unescaped_line, m_Signatures->m_regexPreconditions);
dbgTrace(D_WAAP_SAMPLE_SCAN) << "after doing second set of checkRegex calls..." << nicePrint(res);
checkRegex(
unescapedLineSample,
m_Signatures->specific_acuracy_keywords_regex,
@@ -1111,7 +1165,7 @@ WaapAssetState::apply(
}
bool os_cmd_ev = Waap::Util::find_in_map_of_stringlists_keys("os_cmd_ev", res.found_patterns);
dbgTrace(D_WAAP_SAMPLE_SCAN) << "before evasion checking " << nicePrint(res);
if (os_cmd_ev) {
dbgTrace(D_WAAP_EVASIONS) << "os command evasion found";
@@ -1295,6 +1349,47 @@ WaapAssetState::apply(
}
}
bool path_traversal_ev = Waap::Util::find_in_map_of_stringlists_keys("path_traversal", res.found_patterns);
dbgTrace(D_WAAP_EVASIONS)
<< "path_traversal_ev = " << path_traversal_ev
<< " sample = " << res.unescaped_line
<< " res.unescaped_line.find(2f) = " << res.unescaped_line.find("2f");
if ((path_traversal_ev) && (res.unescaped_line.find("2f") != std::string::npos)) {
// Possible path traversal evasion .2f. detected: - clean up and scan with regexes again.
dbgTrace(D_WAAP_EVASIONS) << "comment evasion .2f. found" << res.unescaped_line
<< "Status beroe evasion checking " << nicePrint(res);
std::string unescaped = line;
replaceAll(unescaped, "2f", "/");
size_t kwCount = res.keyword_matches.size();
if (res.unescaped_line != unescaped) {
SampleValue unescapedSample(unescaped, m_Signatures->m_regexPreconditions);
checkRegex(unescapedSample, m_Signatures->specific_acuracy_keywords_regex, res.keyword_matches,
res.found_patterns, longTextFound, binaryDataFound);
checkRegex(unescapedSample, m_Signatures->words_regex, res.keyword_matches, res.found_patterns,
longTextFound, binaryDataFound);
checkRegex(unescapedSample, m_Signatures->pattern_regex, res.regex_matches, res.found_patterns,
longTextFound, binaryDataFound);
}
if (kwCount == res.keyword_matches.size()) {
// Remove the evasion keyword if no real evasion found
keywordsToRemove.push_back("path_traversal");
path_traversal_ev = false;
}
else if (!binaryDataFound) {
// Recalculate repetition and/or probing indicators
unsigned int newWordsCount = 0;
calcRepetitionAndProbing(res, ignored_keywords, unescaped, detectedRepetition, detectedProbing,
newWordsCount);
// Take minimal words count because empirically it means evasion was probably succesfully decoded
wordsCount = std::min(wordsCount, newWordsCount);
}
dbgTrace(D_WAAP_EVASIONS) << "status after evasion checking " << nicePrint(res);
}
bool quoutes_space_evasion = Waap::Util::find_in_map_of_stringlists_keys(
"quotes_space_ev_fast_reg",
res.found_patterns
@@ -1726,7 +1821,7 @@ WaapAssetState::apply(
wordsCount = std::min(wordsCount, newWordsCount);
}
}
dbgTrace(D_WAAP_SAMPLE_SCAN) << "after evasions..." << nicePrint(res);
// Remove evasion keywords that should not be reported because there's no real evasion found
if (!keywordsToRemove.empty()) {
dbgTrace(D_WAAP_SAMPLE_SCAN)

View File

@@ -33,6 +33,7 @@
#include "KeywordTypeValidator.h"
#include "ScanResult.h"
#include "WaapSampleValue.h"
#include "RequestsMonitor.h"
enum space_stage {SPACE_SYNBOL, BR_SYMBOL, BN_SYMBOL, BRN_SEQUENCE, BNR_SEQUENCE, NO_SPACES};
@@ -49,6 +50,7 @@ private: //ugly but needed for build
Waap::Util::map_of_stringlists_t & found_patterns, bool longTextFound, bool binaryDataFound) const;
void filterKeywordsDueToLongText(Waf2ScanResult &res) const;
std::string nicePrint(Waf2ScanResult &res) const;
public:
// Load and compile signatures from file
@@ -66,6 +68,8 @@ public:
const std::string m_assetId;
std::shared_ptr<SourcesRequestMonitor> m_requestsMonitor;
ScoreBuilder scoreBuilder;
std::shared_ptr<Waap::RateLimiting::State> m_rateLimitingState;
std::shared_ptr<Waap::RateLimiting::State> m_errorLimitingState;
@@ -89,6 +93,7 @@ public:
void logIndicatorsInFilters(const std::string &param, Waap::Keywords::KeywordsSet& keywords,
IWaf2Transaction* pTransaction);
void logParamHit(Waf2ScanResult& res, IWaf2Transaction* pTransaction);
void logSourceHit(const std::string& source);
void filterKeywords(const std::string &param, Waap::Keywords::KeywordsSet& keywords,
std::vector<std::string>& filteredKeywords);
void clearFilterVerbose();

View File

@@ -329,14 +329,37 @@ const std::string& WaapConfigBase::get_AssetName() const
return m_assetName;
}
const std::string& WaapConfigBase::get_PracticeId() const
const std::string& WaapConfigBase::get_PracticeIdByPactice(DecisionType practiceType) const
{
return m_practiceId;
switch (practiceType)
{
case DecisionType::AUTONOMOUS_SECURITY_DECISION:
return m_practiceId;
default:
dbgError(D_WAAP)
<< "Can't find practice type for practice ID by practice: "
<< practiceType
<< ", return web app practice ID";
return m_practiceId;
}
}
const std::string& WaapConfigBase::get_PracticeName() const
const std::string& WaapConfigBase::get_PracticeNameByPactice(DecisionType practiceType) const
{
return m_practiceName;
switch (practiceType)
{
case DecisionType::AUTONOMOUS_SECURITY_DECISION:
return m_practiceName;
default:
dbgError(D_WAAP)
<< "Can't find practice type for practice name by practice: "
<< practiceType
<< ", return web app practice name";
return m_practiceName;
}
}
const std::string& WaapConfigBase::get_RuleId() const

View File

@@ -39,8 +39,8 @@ public:
virtual const std::string& get_AssetId() const;
virtual const std::string& get_AssetName() const;
virtual const BlockingLevel& get_BlockingLevel() const;
virtual const std::string& get_PracticeId() const;
virtual const std::string& get_PracticeName() const;
virtual const std::string& get_PracticeIdByPactice(DecisionType practiceType) const;
virtual const std::string& get_PracticeNameByPactice(DecisionType practiceType) const;
virtual const std::string& get_RuleId() const;
virtual const std::string& get_RuleName() const;
virtual const bool& get_WebAttackMitigation() const;

View File

@@ -1,250 +0,0 @@
// Copyright (C) 2024 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include "WaapModelResultLogger.h"
#include "Waf2Engine.h"
#include "i_time_get.h"
#include "i_messaging.h"
#include "i_instance_awareness.h"
#include "http_manager.h"
#include "LogGenWrapper.h"
#include "rest.h"
#include "debug.h"
USE_DEBUG_FLAG(D_WAAP_MODEL_LOGGER);
using namespace std;
static const unsigned int MAX_FILES_PER_WINDOW = 5;
static const unsigned int MAX_LOGS_PER_WINDOW = 1800;
static constexpr std::chrono::minutes RATE_LIMIT_WINDOW_MINUTES = std::chrono::minutes(30);
class WaapModelReport : public RestGetFile
{
public:
WaapModelReport(const vector<WaapModelResult> &_data) : data(_data) {}
private:
C2S_PARAM(vector<WaapModelResult>, data);
};
class WaapModelResultLogger::Impl
:
Singleton::Provide<I_WaapModelResultLogger>::From<WaapModelResultLogger>
{
public:
Impl(size_t maxLogs) : max_logs(maxLogs), sent_files_count(0), sent_logs_count(0),
last_sent_s3(std::chrono::minutes::zero()),
last_kusto_log_window(std::chrono::minutes::zero()) {}
virtual ~Impl();
void
logModelResult(
Waap::Scores::ModelLoggingSettings &settings,
IWaf2Transaction* transaction,
Waf2ScanResult &res,
string modelName,
string otherModelName,
double score,
double otherScore) override;
private:
void logToStream(WaapModelResult &result, chrono::minutes now);
void logToS3(WaapModelResult &result, IWaf2Transaction* transaction, chrono::minutes now);
bool shouldSendLogsToS3(chrono::minutes now);
void sendLogsToS3();
size_t max_logs;
unsigned int sent_files_count;
unsigned int sent_logs_count;
std::chrono::minutes last_sent_s3;
std::chrono::minutes last_kusto_log_window;
std::map<std::string, vector<WaapModelResult>> logs;
};
WaapModelResultLogger::WaapModelResultLogger(size_t maxLogs) : pimpl(make_unique<WaapModelResultLogger::Impl>(maxLogs))
{
}
WaapModelResultLogger::~WaapModelResultLogger()
{
}
void
WaapModelResultLogger::logModelResult(
Waap::Scores::ModelLoggingSettings &settings,
IWaf2Transaction* transaction,
Waf2ScanResult &res,
std::string modelName,
std::string otherModelName,
double score,
double otherScore
)
{
pimpl->logModelResult(settings, transaction, res, modelName, otherModelName, score, otherScore);
}
void
WaapModelResultLogger::Impl::logModelResult(
Waap::Scores::ModelLoggingSettings &settings,
IWaf2Transaction* transaction,
Waf2ScanResult &res,
string modelName,
string otherModelName,
double score,
double otherScore)
{
if (transaction == NULL) return;
if (!Singleton::exists<I_Messaging>()) {
dbgError(D_WAAP_MODEL_LOGGER) << "Messaging service is not available, will not log";
return;
}
double score_diff = score - otherScore;
if (settings.logLevel == Waap::Scores::ModelLogLevel::DIFF &&
! ((score_diff > 0 && score >= 1.5f && otherScore < 4.0f) ||
(score_diff < 0 && score < 4.0f && otherScore >= 1.5f))) {
return;
}
auto current_time = Singleton::Consume<I_TimeGet>::by<WaapComponent>()->getWalltime();
auto now = chrono::duration_cast<chrono::minutes>(current_time);
WaapModelResult result = WaapModelResult(
*transaction,
res,
modelName,
otherModelName,
score,
otherScore,
now.count()
);
if (settings.logToStream) logToStream(result, now);
if (settings.logToS3) logToS3(result, transaction, now);
}
void WaapModelResultLogger::Impl::logToS3(WaapModelResult &result, IWaf2Transaction* transaction, chrono::minutes now)
{
auto asset_state = transaction->getAssetState();
string asset_id = (asset_state != nullptr) ? asset_state->m_assetId : "";
auto asset_logs = logs.find(asset_id);
if (asset_logs == logs.end()) {
logs.emplace(asset_id, vector<WaapModelResult>());
}
logs.at(asset_id).push_back(result);
if (shouldSendLogsToS3(now)) {
sendLogsToS3();
}
}
void WaapModelResultLogger::Impl::logToStream(WaapModelResult &result, chrono::minutes now)
{
if (now - last_kusto_log_window > RATE_LIMIT_WINDOW_MINUTES) {
last_kusto_log_window = now;
sent_logs_count = 0;
}
else if (sent_logs_count > MAX_LOGS_PER_WINDOW) {
return;
}
sent_logs_count++;
dbgTrace(D_WAAP_MODEL_LOGGER) << "Logging WAAP model telemetry";
auto maybeLogTriggerConf = getConfiguration<LogTriggerConf>("rulebase", "log");
LogGenWrapper logGenWrapper(
maybeLogTriggerConf,
"WAAP Model Telemetry",
ReportIS::Audience::SECURITY,
LogTriggerConf::SecurityType::ThreatPrevention,
ReportIS::Severity::CRITICAL,
ReportIS::Priority::HIGH,
false);
LogGen& waap_log = logGenWrapper.getLogGen();
waap_log.addMarkerSuffix(result.location);
waap_log << LogField("httpuripath", result.uri);
waap_log << LogField("matchedlocation", result.location);
waap_log << LogField("matchedparameter", result.param);
waap_log << LogField("matchedindicators", Waap::Util::vecToString(result.keywords), LogFieldOption::XORANDB64);
waap_log << LogField("matchedsample", result.sample, LogFieldOption::XORANDB64);
waap_log << LogField("waapkeywordsscore", (int)(result.otherScore * 100));
waap_log << LogField("waapfinalscore", (int)(result.score * 100));
waap_log << LogField("indicatorssource", result.modelName);
waap_log << LogField("indicatorsversion", result.otherModelName);
}
bool WaapModelResultLogger::Impl::shouldSendLogsToS3(chrono::minutes now)
{
if (now - last_sent_s3 > RATE_LIMIT_WINDOW_MINUTES) return true;
for (const auto &asset_logs : logs) {
if (asset_logs.second.size() >= max_logs) return true;
}
return false;
}
void WaapModelResultLogger::Impl::sendLogsToS3()
{
dbgFlow(D_WAAP_MODEL_LOGGER) << "Sending logs to fog";
I_Messaging *msg = Singleton::Consume<I_Messaging>::by<WaapComponent>();
for (auto &asset_logs : logs) {
if (asset_logs.second.empty()) {
continue;
}
if (sent_files_count >= MAX_FILES_PER_WINDOW) {
dbgInfo(D_WAAP_MODEL_LOGGER) << "Reached max files per window, will wait for next window";
asset_logs.second.clear();
continue;
}
I_AgentDetails *agentDetails = Singleton::Consume<I_AgentDetails>::by<WaapComponent>();
string tenant_id = agentDetails->getTenantId();
string agent_id = agentDetails->getAgentId();
string asset_id = asset_logs.first;
if (Singleton::exists<I_InstanceAwareness>()) {
I_InstanceAwareness* instance = Singleton::Consume<I_InstanceAwareness>::by<WaapComponent>();
Maybe<string> uniqueId = instance->getUniqueID();
if (uniqueId.ok())
{
agent_id += "/" + uniqueId.unpack();
}
}
string uri = "/storage/waap/" +
tenant_id + "/" + asset_id + "/waap_model_results/window_" +
to_string(last_sent_s3.count()) + "-" + to_string(sent_files_count) +
"/" + agent_id + "/data.data";
WaapModelReport report = WaapModelReport(asset_logs.second);
dbgInfo(D_WAAP_MODEL_LOGGER) << "Sending logs for asset " << asset_logs.first <<
", length " << asset_logs.second.size() <<
", uri " << uri;
msg->sendAsyncMessage(
HTTPMethod::PUT,
uri,
report,
MessageCategory::LOG
);
asset_logs.second.clear();
}
auto current_time = Singleton::Consume<I_TimeGet>::by<WaapComponent>()->getWalltime();
auto now = chrono::duration_cast<chrono::minutes>(current_time);
if (now - last_sent_s3 > RATE_LIMIT_WINDOW_MINUTES) {
last_sent_s3 = now;
sent_files_count = 0;
} else {
sent_files_count++;
}
}
WaapModelResultLogger::Impl::~Impl()
{}

View File

@@ -1,109 +0,0 @@
// Copyright (C) 2024 Check Point Software Technologies Ltd. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#pragma once
#include <memory>
#include <string>
#include <map>
#include <chrono>
#include <vector>
#include <ostream>
#include "cereal/archives/json.hpp"
#include "i_waap_model_result_logger.h"
#include "DeepAnalyzer.h"
#include "i_transaction.h"
#include "ScanResult.h"
#include "WaapAssetState.h"
#include "WaapScores.h"
class WaapModelResultLogger
:
Singleton::Provide<I_WaapModelResultLogger>
{
public:
WaapModelResultLogger(size_t maxLogs = MAX_WAAP_MODEL_LOGS);
virtual ~WaapModelResultLogger();
virtual void logModelResult(
Waap::Scores::ModelLoggingSettings &settings,
IWaf2Transaction* transaction,
Waf2ScanResult &res,
std::string modelName,
std::string otherModelName,
double score,
double otherScore
);
class Impl;
protected:
std::unique_ptr<Impl> pimpl;
static const size_t MAX_WAAP_MODEL_LOGS = 20000;
};
class WaapModelResult
{
public:
WaapModelResult(
IWaf2Transaction &transaction,
Waf2ScanResult &res,
const std::string &modelName,
const std::string &otherModelName,
double score,
double otherScore,
uint64_t time
) : uri(transaction.getUri()), location(res.location), param(res.param_name),
modelName(modelName), otherModelName(otherModelName),
score(score), otherScore(otherScore), keywords(res.keywordsAfterFilter),
sample(res.unescaped_line.substr(0, 100)), id(transaction.getIndex()), time(time)
{
}
template<class Archive>
void serialize(Archive &ar) const
{
ar(cereal::make_nvp("uri", uri));
ar(cereal::make_nvp("location", location));
ar(cereal::make_nvp("param", param));
ar(cereal::make_nvp("modelName", modelName));
ar(cereal::make_nvp("otherModelName", otherModelName));
ar(cereal::make_nvp("score", score));
ar(cereal::make_nvp("otherScore", otherScore));
ar(cereal::make_nvp("keywords", keywords));
ar(cereal::make_nvp("sample", sample));
ar(cereal::make_nvp("id", id));
ar(cereal::make_nvp("time", time));
}
std::string toString() const
{
std::stringstream message_stream;
{
cereal::JSONOutputArchive ar(message_stream);
serialize(ar);
}
return message_stream.str();
}
std::string uri;
std::string location;
std::string param;
std::string modelName;
std::string otherModelName;
double score;
double otherScore;
std::vector<std::string> keywords;
std::string sample;
uint64_t id;
uint64_t time;
};

View File

@@ -48,8 +48,9 @@ public:
m_tag = to_lower_copy(m_tag);
if (m_tag != "sourceip" && m_tag != "sourceidentifier" && m_tag != "url" && m_tag != "hostname" &&
m_tag != "keyword" && m_tag != "paramname" && m_tag != "paramvalue" && m_tag != "paramlocation" &&
m_tag != "responsebody" && m_tag != "headername" && m_tag != "headervalue" && m_tag != "method") {
m_tag != "keyword" && m_tag != "indicator" && m_tag != "paramname" && m_tag != "paramvalue" &&
m_tag != "paramlocation" && m_tag != "responsebody" && m_tag != "headername" &&
m_tag != "headervalue" && m_tag != "method") {
m_isValid = false;
dbgDebug(D_WAAP_OVERRIDE) << "Invalid override tag: " << m_tag;
}

View File

@@ -89,7 +89,7 @@ bool WaapOverrideFunctor::operator()(
}
else if (tagLower == "url") {
for (const auto &rx : rxes) {
if (W2T_REGX_MATCH(getUriStr)) return true;
if (W2T_REGX_MATCH(getUri)) return true;
}
return false;
}
@@ -105,7 +105,7 @@ bool WaapOverrideFunctor::operator()(
}
return false;
}
else if (tagLower == "keyword") {
else if (tagLower == "keyword" || tagLower == "indicator") {
for (const auto &rx : rxes) {
for (const std::string& keywordStr : waf2Transaction.getKeywordMatches()) {
if (REGX_MATCH(keywordStr)) {

View File

@@ -23,6 +23,7 @@ ResponseInjectReasons::ResponseInjectReasons()
:
csrf(false),
antibot(false),
captcha(false),
securityHeaders(false)
{
}
@@ -53,6 +54,13 @@ ResponseInjectReasons::setAntibot(bool flag)
antibot = flag;
}
void
ResponseInjectReasons::setCaptcha(bool flag)
{
dbgTrace(D_WAAP) << "Change ResponseInjectReasons(Captcha) " << captcha << " to " << flag;
captcha = flag;
}
void
ResponseInjectReasons::setCsrf(bool flag)
{
@@ -74,6 +82,13 @@ ResponseInjectReasons::shouldInjectAntibot() const
return antibot;
}
bool
ResponseInjectReasons::shouldInjectCaptcha() const
{
dbgTrace(D_WAAP) << "shouldInjectCaptcha():: " << captcha;
return captcha;
}
bool
ResponseInjectReasons::shouldInjectCsrf() const
{

View File

@@ -21,14 +21,17 @@ public:
void clear();
bool shouldInject() const;
void setAntibot(bool flag);
void setCaptcha(bool flag);
void setCsrf(bool flag);
void setSecurityHeaders(bool flag);
bool shouldInjectAntibot() const;
bool shouldInjectCaptcha() const;
bool shouldInjectCsrf() const;
bool shouldInjectSecurityHeaders() const;
private:
bool csrf;
bool antibot;
bool captcha;
bool securityHeaders;
};

View File

@@ -15,7 +15,6 @@
#include "WaapScores.h"
#include "Waf2Engine.h"
#include "i_transaction.h"
#include "WaapModelResultLogger.h"
#include <string>
#include "debug.h"
#include "reputation_features_events.h"
@@ -111,30 +110,8 @@ double Waap::Scanner::getScoreData(Waf2ScanResult& res, const std::string &poolN
for (auto keyword : newKeywords) {
res.keywordsAfterFilter.push_back(keyword);
}
res.scoreArray.clear();
res.coefArray.clear();
res.keywordCombinations.clear();
double res_score = getScoreFromPool(res, newKeywords, poolName);
std::string other_pool_name = Waap::Scores::getOtherScorePoolName();
Waap::Scores::ModelLoggingSettings modelLoggingSettings = Waap::Scores::getModelLoggingSettings();
if (applyLearning && poolName != other_pool_name &&
modelLoggingSettings.logLevel != Waap::Scores::ModelLogLevel::OFF) {
double other_score = getScoreFromPool(res, newKeywords, other_pool_name);
dbgDebug(D_WAAP_SCANNER) << "Comparing score from pool " << poolName << ": " << res_score
<< ", vs. pool " << other_pool_name << ": " << other_score
<< ", score difference: " << res_score - other_score
<< ", sample: " << res.unescaped_line;
Singleton::Consume<I_WaapModelResultLogger>::by<WaapComponent>()->logModelResult(
modelLoggingSettings, m_transaction, res, poolName, other_pool_name, res_score, other_score
);
res.other_model_score = other_score;
} else {
res.other_model_score = res_score;
}
return res_score;
}
@@ -142,6 +119,9 @@ double Waap::Scanner::getScoreFromPool(
Waf2ScanResult &res, const std::vector<std::string> &newKeywords, const std::string &poolName
)
{
res.scoreArray.clear();
res.coefArray.clear();
res.keywordCombinations.clear();
KeywordsStats stats = m_transaction->getAssetState()->scoreBuilder.getSnapshotStats(poolName);
if (!newKeywords.empty()) {

View File

@@ -97,7 +97,9 @@ calcIndividualKeywords(
std::sort(keywords.begin(), keywords.end());
for (auto pKeyword = keywords.begin(); pKeyword != keywords.end(); ++pKeyword) {
addKeywordScore(scoreBuilder, poolName, *pKeyword, 2.0f, 0.3f, scoresArray, coefArray);
addKeywordScore(
scoreBuilder, poolName, *pKeyword, DEFAULT_KEYWORD_SCORE, DEFAULT_KEYWORD_COEF, scoresArray, coefArray
);
}
}
@@ -112,8 +114,6 @@ calcCombinations(
std::vector<std::string>& keyword_combinations)
{
keyword_combinations.clear();
static const double max_combi_score = 1.0f;
double default_coef = 0.8f;
for (size_t i = 0; i < keyword_matches.size(); ++i) {
std::vector<std::string> combinations;
@@ -137,8 +137,10 @@ calcCombinations(
default_score += scoreBuilder.getSnapshotKeywordScore(*it, 0.0f, poolName);
}
// set default combination score to be the sum of its keywords, bounded by 1
default_score = std::min(default_score, max_combi_score);
addKeywordScore(scoreBuilder, poolName, combination, default_score, default_coef, scoresArray, coefArray);
default_score = std::min(default_score, DEFAULT_COMBI_SCORE);
addKeywordScore(
scoreBuilder, poolName, combination, default_score, DEFAULT_COMBI_COEF, scoresArray, coefArray
);
keyword_combinations.push_back(combination);
}
}
@@ -155,7 +157,7 @@ calcArrayScore(std::vector<double>& scoreArray)
// *pScore is always positive and there's a +10 offset
score = 10.0f - left * 10.0f / divisor;
}
dbgTrace(D_WAAP_SCORE_BUILDER) << "calculated score: " << score;
dbgDebug(D_WAAP_SCORE_BUILDER) << "calculated score: " << score;
return score;
}
@@ -171,7 +173,9 @@ calcLogisticRegressionScore(std::vector<double> &coefArray, double intercept, do
}
// Apply the expit function to the log-odds to obtain the probability,
// and multiply by 10 to obtain a 'score' in the range [0, 10]
return 1.0f / (1.0f + exp(-log_odds)) * 10.0f;
double score = 1.0f / (1.0f + exp(-log_odds)) * 10.0f;
dbgDebug(D_WAAP_SCORE_BUILDER) << "calculated score (log_odds): " << score << " (" << log_odds << ")";
return score;
}
}

View File

@@ -32,6 +32,11 @@ struct ModelLoggingSettings {
bool logToStream;
};
static const double DEFAULT_KEYWORD_COEF = 0.3f;
static const double DEFAULT_KEYWORD_SCORE = 2.0f;
static const double DEFAULT_COMBI_COEF = 0.8f;
static const double DEFAULT_COMBI_SCORE = 1.0f;
std::string getScorePoolNameByLocation(const std::string &location);
std::string getOtherScorePoolName();
ModelLoggingSettings getModelLoggingSettings();

View File

@@ -40,6 +40,7 @@
#include "WaapOpenRedirectPolicy.h"
#include "WaapErrorDisclosurePolicy.h"
#include <boost/algorithm/string.hpp>
#include <boost/regex.hpp>
#include "generic_rulebase/parameters_config.h"
#include <iostream>
#include "ParserDelimiter.h"
@@ -1098,6 +1099,7 @@ void Waf2Transaction::end_request_hdrs() {
// but the State itself is not needed now
Waap::Override::State overrideState = getOverrideState(m_siteConfig);
}
m_pWaapAssetState->m_requestsMonitor->logSourceHit(m_source_identifier);
IdentifiersEvent ids(m_source_identifier, m_pWaapAssetState->m_assetId);
ids.notify();
// Read relevant headers and extract meta information such as host name
@@ -1358,7 +1360,7 @@ Waf2Transaction::isHtmlType(const char* data, int data_len){
dbgTrace(D_WAAP) << "Waf2Transaction::isHtmlType: false";
return false;
}
std::string body(data);
std::string body(data, data_len);
if(!m_pWaapAssetState->getSignatures()->html_regex.hasMatch(body))
{
dbgTrace(D_WAAP) << "Waf2Transaction::isHtmlType: false";
@@ -1389,6 +1391,20 @@ Waf2Transaction::findHtmlTagToInject(const char* data, int data_len, int& pos)
size_t tagHistPosCheck = m_tagHistPos;
for (size_t i=0; i < tagSize; ++i) {
if (tag[i] != ::tolower(m_tagHist[tagHistPosCheck])) {
if (i == tagSize - 1 && m_tagHist[tagHistPosCheck] == ' ') {
// match regex on head element with attributes
string dataStr = Waap::Util::charToString(data + pos, data_len - pos);
dataStr = dataStr.substr(0, dataStr.find('>')+1);
tagMatches = NGEN::Regex::regexMatch(
__FILE__,
__LINE__,
dataStr,
boost::regex("(?:\\s+[a-zA-Z_:][-a-zA-Z0-9_:.]*(?:\\s*=\\s*(\"[^\"]*\"|'[^']*'|[^\\s\"'>]*))?)*\\s*>")
);
pos += dataStr.length() - 1;
dbgTrace(D_WAAP_BOT_PROTECTION) << "matching head element with attributes: " << dataStr << ". match: " << tagMatches;
break;
}
tagMatches = false;
break;
}
@@ -1402,12 +1418,8 @@ Waf2Transaction::findHtmlTagToInject(const char* data, int data_len, int& pos)
}
}
if(!headFound)
{
return false;
}
return true;
dbgTrace(D_WAAP_BOT_PROTECTION) << "head element tag found: " << headFound;
return headFound;
}
void
@@ -1421,6 +1433,15 @@ Waf2Transaction::completeInjectionResponseBody(std::string& strInjection)
m_responseInjectReasons.setAntibot(false);
}
if(m_responseInjectReasons.shouldInjectCaptcha()) {
dbgTrace(D_WAAP_BOT_PROTECTION) <<
"Waf2Transaction::completeInjectionResponseBody(): Injecting data (captcha)";
//todo add captcha script
strInjection += "<script src=\"cp-cp.js\"></script>";
// No need to inject more than once
m_responseInjectReasons.setCaptcha(false);
}
if (m_responseInjectReasons.shouldInjectCsrf()) {
dbgTrace(D_WAAP) << "Waf2Transaction::completeInjectionResponseBody(): Injecting data (csrf)";
strInjection += "<script src=\"cp-csrf.js\"></script>";
@@ -1568,6 +1589,8 @@ Waf2Transaction::decideFinal(
sitePolicy = &ngenAPIConfig;
m_overrideState = getOverrideState(sitePolicy);
// User limits
shouldBlock = (getUserLimitVerdict() == ngx_http_cp_verdict_e::TRAFFIC_VERDICT_DROP);
}
else if (WaapConfigApplication::getWaapSiteConfig(ngenSiteConfig)) {
dbgTrace(D_WAAP) << "Waf2Transaction::decideFinal(): got relevant Application configuration from the I/S";
@@ -1646,7 +1669,9 @@ void Waf2Transaction::appendCommonLogFields(LogGen& waapLog,
const std::shared_ptr<Waap::Trigger::Log> &triggerLog,
bool shouldBlock,
const std::string& logOverride,
const std::string& incidentType) const
const std::string& incidentType,
const std::string& practiceID,
const std::string& practiceName) const
{
auto env = Singleton::Consume<I_Environment>::by<WaapComponent>();
auto active_id = env->get<std::string>("ActiveTenantId");
@@ -1661,6 +1686,9 @@ void Waf2Transaction::appendCommonLogFields(LogGen& waapLog,
waapLog << LogField("sourcePort", m_remote_port);
waapLog << LogField("httpHostName", m_hostStr);
waapLog << LogField("httpMethod", m_methodStr);
if (!m_siteConfig->get_AssetId().empty()) waapLog << LogField("assetId", m_siteConfig->get_AssetId());
if (!m_siteConfig->get_AssetName().empty()) waapLog << LogField("assetName", m_siteConfig->get_AssetName());
const auto& autonomousSecurityDecision = std::dynamic_pointer_cast<AutonomousSecurityDecision>(
m_waapDecision.getDecision(AUTONOMOUS_SECURITY_DECISION));
bool send_extended_log = shouldSendExtendedLog(triggerLog);
@@ -1734,8 +1762,8 @@ void Waf2Transaction::appendCommonLogFields(LogGen& waapLog,
waapLog << LogField("practiceType", "Threat Prevention");
waapLog << LogField("practiceSubType", m_siteConfig->get_PracticeSubType());
waapLog << LogField("ruleName", m_siteConfig->get_RuleName());
waapLog << LogField("practiceId", m_siteConfig->get_PracticeId());
waapLog << LogField("practiceName", m_siteConfig->get_PracticeName());
waapLog << LogField("practiceId", practiceID);
waapLog << LogField("practiceName", practiceName);
waapLog << LogField("waapIncidentType", incidentType);
// Registering this value would append the list of matched override IDs to the unified log
@@ -1802,8 +1830,8 @@ Waf2Transaction::sendLog()
telemetryData.source = getSourceIdentifier();
telemetryData.assetName = m_siteConfig->get_AssetName();
telemetryData.practiceId = m_siteConfig->get_PracticeId();
telemetryData.practiceName = m_siteConfig->get_PracticeName();
telemetryData.practiceId = m_siteConfig->get_PracticeIdByPactice(AUTONOMOUS_SECURITY_DECISION);
telemetryData.practiceName = m_siteConfig->get_PracticeNameByPactice(AUTONOMOUS_SECURITY_DECISION);
if (m_scanResult) {
telemetryData.attackTypes = m_scanResult->attack_types;
}
@@ -1944,7 +1972,11 @@ Waf2Transaction::sendLog()
shouldBlock);
LogGen& waap_log = logGenWrapper.getLogGen();
appendCommonLogFields(waap_log, triggerLog, shouldBlock, logOverride, incidentType);
appendCommonLogFields(
waap_log, triggerLog, shouldBlock, logOverride, incidentType,
m_siteConfig->get_PracticeIdByPactice(AUTONOMOUS_SECURITY_DECISION),
m_siteConfig->get_PracticeNameByPactice(AUTONOMOUS_SECURITY_DECISION)
);
waap_log << LogField("waapIncidentDetails", incidentDetails);
waap_log << LogField("eventConfidence", "High");
break;
@@ -1977,7 +2009,11 @@ Waf2Transaction::sendLog()
waap_log << LogField("waapFoundIndicators", getKeywordMatchesStr(), LogFieldOption::XORANDB64);
}
appendCommonLogFields(waap_log, triggerLog, shouldBlock, logOverride, incidentType);
appendCommonLogFields(
waap_log, triggerLog, shouldBlock, logOverride, incidentType,
m_siteConfig->get_PracticeIdByPactice(AUTONOMOUS_SECURITY_DECISION),
m_siteConfig->get_PracticeNameByPactice(AUTONOMOUS_SECURITY_DECISION)
);
waap_log << LogField("waapIncidentDetails", incidentDetails);
break;
@@ -1993,7 +2029,11 @@ Waf2Transaction::sendLog()
shouldBlock);
LogGen& waap_log = logGenWrapper.getLogGen();
appendCommonLogFields(waap_log, triggerLog, shouldBlock, logOverride, "Cross Site Request Forgery");
appendCommonLogFields(
waap_log, triggerLog, shouldBlock, logOverride, "Cross Site Request Forgery",
m_siteConfig->get_PracticeIdByPactice(AUTONOMOUS_SECURITY_DECISION),
m_siteConfig->get_PracticeNameByPactice(AUTONOMOUS_SECURITY_DECISION)
);
waap_log << LogField("waapIncidentDetails", "CSRF Attack discovered.");
break;
}
@@ -2174,14 +2214,13 @@ Waf2Transaction::decideAutonomousSecurity(
" effective overrides count: " << m_effectiveOverrideIds.size() <<
" learned overrides count: " << m_exceptionLearned.size();
bool log_all = false;
const std::shared_ptr<Waap::Trigger::Policy> triggerPolicy = sitePolicy.get_TriggerPolicy();
if (triggerPolicy) {
const std::shared_ptr<Waap::Trigger::Log> triggerLog = getTriggerLog(triggerPolicy);
if (triggerLog && triggerLog->webRequests) log_all = true;
}
if(decision->getThreatLevel() <= ThreatLevel::THREAT_INFO && !log_all) {
decision->setLog(false);
} else {
@@ -2296,10 +2335,11 @@ bool Waf2Transaction::decideResponse()
bool
Waf2Transaction::reportScanResult(const Waf2ScanResult &res) {
if (get_ignoreScore() || (res.score >= SCORE_THRESHOLD &&
(m_scanResult == nullptr || res.score > m_scanResult->score)))
if ((get_ignoreScore() || res.score >= SCORE_THRESHOLD) &&
(m_scanResult == nullptr || res.score > m_scanResult->score))
{
// Forget any previous scan result and replace with new
dbgTrace(D_WAAP) << "Setting scan result. New score: " << res.score;
// Forget any previous scan result and replace wit, h new
delete m_scanResult;
m_scanResult = new Waf2ScanResult(res);
return true;
@@ -2343,6 +2383,7 @@ Waf2Transaction::shouldIgnoreOverride(const Waf2ScanResult &res) {
exceptions_dict["sourceIdentifier"].insert(m_source_identifier);
exceptions_dict["url"].insert(getUriStr());
exceptions_dict["hostName"].insert(m_hostStr);
exceptions_dict["method"].insert(m_methodStr);
for (auto &keyword : res.keyword_matches) {
exceptions_dict["indicator"].insert(keyword);
@@ -2355,8 +2396,9 @@ Waf2Transaction::shouldIgnoreOverride(const Waf2ScanResult &res) {
auto behaviors = exceptions.unpack().getBehavior(exceptions_dict,
getAssetState()->m_filtersMngr->getMatchedOverrideKeywords());
for (const auto &behavior : behaviors) {
dbgTrace(D_WAAP_OVERRIDE) << "got behavior: " << behavior.getId();
if (!res.filtered_keywords.empty() || res.score > 0) {
dbgTrace(D_WAAP_OVERRIDE) << "matched exceptions for " << res.param_name << " with filtered indicators";
dbgTrace(D_WAAP_OVERRIDE) << "matched exceptions for param '" << res.param_name << "' with filtered indicators";
std::string overrideId = behavior.getId();
if (m_overrideOriginalMaxScore.find(overrideId) == m_overrideOriginalMaxScore.end()){
m_overrideOriginalMaxScore[overrideId] = res.scoreNoFilter;
@@ -2375,7 +2417,7 @@ Waf2Transaction::shouldIgnoreOverride(const Waf2ScanResult &res) {
}
if (behavior == action_ignore)
{
dbgTrace(D_WAAP_OVERRIDE) << "matched exceptions for " << res.param_name << " should ignore.";
dbgTrace(D_WAAP_OVERRIDE) << "matched exceptions for param '" << res.param_name << "': should ignore.";
std::string overrideId = behavior.getId();
if (!overrideId.empty()) {
m_matchedOverrideIds.insert(overrideId);

View File

@@ -41,7 +41,6 @@
#include "i_waap_telemetry.h"
#include "i_deepAnalyzer.h"
#include "i_time_get.h"
#include "i_waap_model_result_logger.h"
#include "table_opaque.h"
#include "WaapResponseInspectReasons.h"
#include "WaapResponseInjectReasons.h"
@@ -248,7 +247,9 @@ private:
const std::shared_ptr<Waap::Trigger::Log> &triggerLog,
bool shouldBlock,
const std::string& logOverride,
const std::string& incidentType) const;
const std::string& incidentType,
const std::string& practiceID,
const std::string& practiceName) const;
std::string getUserReputationStr(double relativeReputation) const;
bool isTrustedSource() const;

Some files were not shown because too many files have changed in this diff Show More