First release of open-appsec source code

This commit is contained in:
roybarda
2022-10-26 19:33:19 +03:00
parent 3883109caf
commit a883352f79
1353 changed files with 276290 additions and 1 deletions

71
components/include/WaapEnums.h Executable file
View File

@@ -0,0 +1,71 @@
// 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 __WAAP_ENUMS_H__
#define __WAAP_ENUMS_H__
#include <cstddef>
#include <functional>
#define NO_THREAT_FINAL_SCORE 0.0
#define INFO_THREAT_THRESHOLD 1.0
#define LOW_THREAT_THRESHOLD 3.0
#define MED_THREAT_THRESHOLD 6.0
#define MAX_FINAL_SCORE 10.0
#define ATTACK_IN_PARAM "attack_in_param"
enum ThreatLevel {
NO_THREAT = 0,
THREAT_INFO,
LOW_THREAT,
MEDIUM_THREAT,
HIGH_THREAT
};
enum BlockType {
NOT_BLOCKING,
FORCE_EXCEPTION,
FORCE_BLOCK,
API_BLOCK,
BOT_BLOCK,
WAF_BLOCK,
CSRF_BLOCK,
LIMIT_BLOCK
};
enum ParamType {
UNKNOWN_PARAM_TYPE,
HTML_PARAM_TYPE,
URL_PARAM_TYPE,
FREE_TEXT_PARAM_TYPE,
PIPE_PARAM_TYPE,
LONG_RANDOM_TEXT_PARAM_TYPE,
BASE64_PARAM_TYPE,
ADMINISTRATOR_CONFIG_PARAM_TYPE,
FILE_PATH_PARAM_TYPE,
SEMICOLON_DELIMITED_PARAM_TYPE,
ASTERISK_DELIMITED_PARAM_TYPE,
COMMA_DELIMITED_PARAM_TYPE,
AMPERSAND_DELIMITED_PARAM_TYPE,
BINARY_PARAM_TYPE,
PARAM_TYPE_COUNT
};
namespace std {
template<>
struct hash<ParamType>
{
std::size_t operator()(const ParamType& type) const noexcept { return (size_t)type; }
};
}
#endif

View File

@@ -0,0 +1,47 @@
// 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 __ATTACHMENT_REGISTRATOR_H__
#define __ATTACHMENT_REGISTRATOR_H__
#include "singleton.h"
#include "i_mainloop.h"
#include "i_shell_cmd.h"
#include "i_socket_is.h"
#include "attachment_types.h"
#include "component.h"
#define default_keep_alive_path "/etc/cp/attachmentRegistrator/expiration-socket"
class AttachmentRegistrator
:
public Component,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_Socket>
{
public:
AttachmentRegistrator();
~AttachmentRegistrator();
void preload();
void init();
void fini();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __ATTACHMENT_REGISTRATOR_H__

48
components/include/byteorder.h Executable file
View File

@@ -0,0 +1,48 @@
#ifndef __BYTEORDER_H__
#define __BYTEORDER_H__
// Byte Order (Net-to-Host, Host-to-Net) operations
//
// C provides htons, ntohs, htonl, ntohl, but they're not "constexpr" so are unusable in case labels.
// C++ proposal N3620 adds some function, but it's not accepted (yet?). It uses templates which are,
// IMO, a bit complicated so I chose not to adapt it.
static inline constexpr uint16_t
constHTONS(uint16_t h_ord)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
return ((h_ord>>8) & 0xff) |
((h_ord&0xff) << 8);
#elif __BYTE_ORDER == __BIG_ENDIAN
return h_ord;
#else
#error unknown byte order
#endif // __BYTE_ORDER
}
static inline constexpr uint16_t
constNTOHS(uint16_t n_ord)
{
return constHTONS(n_ord); // Same thing
}
static inline constexpr uint32_t
constHTONL(uint32_t h_ord)
{
#if __BYTE_ORDER == __LITTLE_ENDIAN
return ((constHTONS(h_ord>>16)) & 0xffff) |
((constHTONS(h_ord&0xffff)) << 16);
#elif __BYTE_ORDER == __BIG_ENDIAN
return h_ord;
#else
#error unknown byte order
#endif // __BYTE_ORDER
}
static inline constexpr uint32_t
constNTOHL(uint32_t n_ord)
{
return constHTONL(n_ord); // Same thing
}
#endif // __BYTEORDER_H__

View File

@@ -0,0 +1,43 @@
// 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 __DETAILS_RESOLVER_H__
#define __DETAILS_RESOLVER_H__
#include <memory>
#include <string>
#include "i_orchestration_tools.h"
#include "i_details_resolver.h"
#include "i_shell_cmd.h"
#include "singleton.h"
#include "component.h"
class DetailsResolver
:
public Component,
Singleton::Provide<I_DetailsResolver>,
Singleton::Consume<I_OrchestrationTools>
{
public:
DetailsResolver();
~DetailsResolver();
void preload() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __DETAILS_RESOLVER_H__

50
components/include/downloader.h Executable file
View File

@@ -0,0 +1,50 @@
// 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 __DOWNLOADER_H__
#define __DOWNLOADER_H__
#include "i_downloader.h"
#include "i_orchestration_tools.h"
#include "i_update_communication.h"
#include "i_encryptor.h"
#include "url_parser.h"
#include "i_agent_details.h"
#include "i_mainloop.h"
#include "singleton.h"
#include "component.h"
class Downloader
:
public Component,
Singleton::Provide<I_Downloader>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_Encryptor>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_UpdateCommunication>
{
public:
Downloader();
~Downloader();
void preload() override;
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __DOWNLOADER_H__

View File

@@ -0,0 +1,43 @@
// 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 __EXTERNAL_SDK_SERVER_H__
#define __EXTERNAL_SDK_SERVER_H__
#include <memory>
#include "i_external_sdk_server.h"
#include "i_rest_api.h"
#include "component.h"
class ExternalSdkServer
:
public Component,
Singleton::Provide<I_ExternalSdkServer>,
Singleton::Consume<I_RestApi>
{
public:
ExternalSdkServer();
~ExternalSdkServer();
void init();
void fini();
void preload();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __EXTERNAL_SDK_SERVER_H__

View File

@@ -0,0 +1,31 @@
// 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 __ASSET_H__
#define __ASSET_H__
#include <unordered_map>
#include "i_environment.h"
class Asset
{
public:
const std::map<Context::MetaDataType, std::string> & getAttrs() const { return attr; }
void setAttr(Context::MetaDataType type, const std::string &attr_val) { attr[type] = attr_val; }
private:
std::map<Context::MetaDataType, std::string> attr;
};
#endif // __ASSET_H__

View File

@@ -0,0 +1,91 @@
// 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 __ASSETS_CONFIG_H__
#define __ASSETS_CONFIG_H__
#include <vector>
#include <string>
#include <arpa/inet.h>
#include "generic_rulebase_context.h"
#include "c_common/ip_common.h"
#include "connkey.h"
class RuleAsset
{
public:
class AssetUrl
{
public:
void
load(cereal::JSONInputArchive &archive_in);
const std::string & getProtocol() const { return protocol; }
const std::string & getIp() const { return ip; }
const std::string & getPort() const { return port; }
uint8_t getParsedProtocol() const { return parsed_proto; }
const IpAddress & getParsedIp() const { return parsed_ip; }
uint16_t getParsedPort() const { return parsed_port; }
bool isAnyIp() const { return is_any_ip; }
bool isAnyPort() const { return is_any_port; }
bool isAnyProto() const { return is_any_proto; }
private:
static IpAddress ConvertToIpAddress(const IPAddr &addr);
std::string protocol;
std::string ip;
std::string port;
IpAddress parsed_ip;
uint16_t parsed_port;
uint8_t parsed_proto;
bool is_any_ip;
bool is_any_port;
bool is_any_proto;
};
void load(cereal::JSONInputArchive &archive_in);
const GenericConfigId & getId() const { return asset_id; }
const std::string & getName() const { return asset_name; }
const std::vector<AssetUrl> & getUrls() const { return asset_urls; }
private:
GenericConfigId asset_id;
std::string asset_name;
std::vector<AssetUrl> asset_urls;
};
class Assets
{
public:
static void preload();
void load(cereal::JSONInputArchive &archive_in)
{
try {
cereal::load(archive_in, assets);
}catch (const cereal::Exception &) {
}
}
static const Assets empty_assets_config;
const std::vector<RuleAsset> & getAssets() const { return assets; }
private:
std::vector<RuleAsset> assets;
};
#endif //__ASSETS_CONFIG_H__

View File

@@ -0,0 +1,36 @@
// 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 __ASSET_EVAL_H__
#define __ASSET_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
class AssetMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
AssetMatcher(const std::vector<std::string> &params);
static std::string getName() { return "assetId"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::string asset_id;
};
#endif // __ASSET_EVAL_H__

View File

@@ -0,0 +1,127 @@
// 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 __CONNECTION_EVAL_H__
#define __CONNECTION_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
#include "connkey.h"
class IpAddressMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
IpAddressMatcher(const std::vector<std::string> &params);
static std::string getName() { return "ipAddress"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<IPAddr>> values;
};
class SourceIpMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
SourceIpMatcher(const std::vector<std::string> &params);
static std::string getName() { return "sourceIP"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<IPAddr>> values;
};
class DestinationIpMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
DestinationIpMatcher(const std::vector<std::string> &params);
static std::string getName() { return "destinationIP"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<IPAddr>> values;
};
class SourcePortMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
SourcePortMatcher(const std::vector<std::string> &params);
static std::string getName() { return "sourcePort"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<PortNumber>> values;
};
class ListeningPortMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
ListeningPortMatcher(const std::vector<std::string> &params);
static std::string getName() { return "listeningPort"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<PortNumber>> values;
};
class IpProtocolMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
IpProtocolMatcher(const std::vector<std::string> &params);
static std::string getName() { return "ipProtocol"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<CustomRange<IPProto>> values;
};
class UrlMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
UrlMatcher(const std::vector<std::string> &params);
static std::string getName() { return "url"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::vector<std::string> values;
};
#endif // __CONNECTION_EVAL_H__

View File

@@ -0,0 +1,74 @@
// 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 __HTTP_TRANSACTION_DATA_EVAL_H__
#define __HTTP_TRANSACTION_DATA_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
#include "connkey.h"
class EqualHost : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
EqualHost(const std::vector<std::string> &params);
static std::string getName() { return "EqualHost"; }
Maybe<bool, Context::Error> evalVariable() const override;
private:
std::string host;
};
class EqualListeningIP : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
EqualListeningIP(const std::vector<std::string> &params);
static std::string getName() { return "EqualListeningIP"; }
Maybe<bool, Context::Error> evalVariable() const override;
private:
IPAddr listening_ip;
};
class EqualListeningPort : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
EqualListeningPort(const std::vector<std::string> &params);
static std::string getName() { return "EqualListeningPort"; }
Maybe<bool, Context::Error> evalVariable() const override;
private:
PortNumber listening_port;
};
class BeginWithUri : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
BeginWithUri(const std::vector<std::string> &params);
static std::string getName() { return "BeginWithUri"; }
Maybe<bool, Context::Error> evalVariable() const override;
private:
std::string uri_prefix;
};
#endif // __HTTP_TRANSACTION_DATA_EVAL_H__

View File

@@ -0,0 +1,36 @@
// 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 __PARAMETER_EVAL_H__
#define __PARAMETER_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
class ParameterMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
ParameterMatcher(const std::vector<std::string> &params);
static std::string getName() { return "parameterId"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::string parameter_id;
};
#endif // __PARAMETER_EVAL_H__

View File

@@ -0,0 +1,36 @@
// 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 __PRACTICE_EVAL_H__
#define __PRACTICE_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
class PracticeMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
PracticeMatcher(const std::vector<std::string> &params);
static std::string getName() { return "practiceId"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::string practice_id;
};
#endif // __PRACTICE_EVAL_H__

View File

@@ -0,0 +1,43 @@
// 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 __QUERY_EVAL_H__
#define __QUERY_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "i_generic_rulebase.h"
#include "singleton.h"
class QueryMatcher
:
public EnvironmentEvaluator<bool>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_GenericRulebase>
{
public:
QueryMatcher(const std::vector<std::string> &query_params);
static std::string getName() { return "matchQuery"; }
Maybe<bool, Context::Error> evalVariable() const override;
private:
static const std::string contextKeyToString(Context::MetaDataType type);
std::string key;
std::unordered_set<std::string> values;
bool is_any = false;
};
#endif // __QUERY_EVAL_H__

View File

@@ -0,0 +1,36 @@
// 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 __TRIGGER_EVAL_H__
#define __TRIGGER_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
class TriggerMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
TriggerMatcher(const std::vector<std::string> &params);
static std::string getName() { return "triggerId"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::string trigger_id;
};
#endif // __TRIGGER_EVAL_H__

View File

@@ -0,0 +1,36 @@
// 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 __ZONE_EVAL_H__
#define __ZONE_EVAL_H__
#include "environment/evaluator_templates.h"
#include "i_environment.h"
#include "singleton.h"
class ZoneMatcher : public EnvironmentEvaluator<bool>, Singleton::Consume<I_Environment>
{
public:
ZoneMatcher(const std::vector<std::string> &zones);
static std::string getName() { return "zoneId"; }
Maybe<bool, Context::Error> evalVariable() const override;
static std::string ctx_key;
private:
std::string zone_id;
};
#endif // __ZONE_EVAL_H__

View File

@@ -0,0 +1,44 @@
// 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 __GENERIC_RULEBASE_H__
#define __GENERIC_RULEBASE_H__
#include <memory>
#include "i_generic_rulebase.h"
#include "i_intelligence_is_v2.h"
#include "singleton.h"
#include "component.h"
class GenericRulebase
:
public Component,
Singleton::Provide<I_GenericRulebase>,
Singleton::Consume<I_Intelligence_IS_V2>
{
public:
GenericRulebase();
~GenericRulebase();
void preload();
void init();
void fini();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __GENERIC_RULEBASE_H__

View File

@@ -0,0 +1,39 @@
// 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 __GENERIC_RULEBASE_CONTEXT_H__
#define __GENERIC_RULEBASE_CONTEXT_H__
#include "rulebase_config.h"
#include "context.h"
#include "config.h"
enum class RuleRegistrationState {REGISTERED, UNREGISTERED, UNINITIALIZED};
class GenericRulebaseContext
{
public:
GenericRulebaseContext() : ctx(), registration_state(RuleRegistrationState::UNINITIALIZED) {}
void activate(const BasicRuleConfig &rule);
void activate();
void deactivate() { if (registration_state == RuleRegistrationState::REGISTERED) ctx.deactivate(); }
private:
Context ctx;
RuleRegistrationState registration_state;
};
#endif //__GENERIC_RULEBASE_CONTEXT_H__

View File

@@ -0,0 +1,39 @@
// 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 __GENERIC_RULEBASE_UTILS_H__
#define __GENERIC_RULEBASE_UTILS_H__
#include <string>
#include "debug.h"
#include "cereal/archives/json.hpp"
USE_DEBUG_FLAG(D_RULEBASE_CONFIG);
template <typename T>
void
parseJSONKey(const std::string &key_name, T &value, cereal::JSONInputArchive &archive_in)
{
try {
archive_in(cereal::make_nvp(key_name, value));
} catch (const cereal::Exception &e) {
dbgDebug(D_RULEBASE_CONFIG)
<< "Could not parse the required key. Key: "
<< key_name
<< ", Error: "
<< e.what();
}
}
#endif //__GENERIC_RULEBASE_UTILS_H__

View File

@@ -0,0 +1,93 @@
// 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 __MATCH_QUERY_H__
#define __MATCH_QUERY_H__
#include <vector>
#include <string>
#include <set>
#include <map>
#include <arpa/inet.h>
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/json.hpp"
#include <boost/regex.hpp>
#include "c_common/ip_common.h"
class MatchQuery
{
public:
enum class MatchType { Condition, Operator };
enum class Operators { And, Or, None };
enum class Conditions { Equals, NotEquals, In, NotIn, Exist, None };
enum class StaticKeys
{
IpAddress,
SrcIpAddress,
DstIpAddress,
SrcPort,
ListeningPort,
IpProtocol,
Domain,
NotStatic
};
void load(cereal::JSONInputArchive &archive_in);
MatchType getType() const { return type; }
Operators getOperatorType() const { return operator_type; }
Conditions getConditionType() const { return condition_type; }
const std::string & getKey() const { return key; }
const std::set<std::string> & getValue() const { return value; }
const std::vector<IPRange> & getIpAddrValue() const { return ip_addr_value; }
const std::vector<PortsRange> & getPortValue() const { return port_value; }
const std::vector<IpProtoRange> & getProtoValue() const { return ip_proto_value; }
const std::vector<MatchQuery> & getItems() const { return items; }
std::string getFirstValue() const { return first_value; }
bool matchAttributes(const std::unordered_map<std::string, std::set<std::string>> &key_value_pairs) const;
bool matchException(const std::string &behaviorKey, const std::string &behaviorValue) const;
bool isKeyTypeIp() const;
bool isKeyTypePort() const;
bool isKeyTypeProtocol() const;
bool isKeyTypeDomain() const;
bool isKeyTypeSpecificLabel() const;
bool isKeyTypeStatic() const;
std::set<std::string> getAllKeys() const;
private:
StaticKeys getKeyByName(const std::string &key_type_name);
bool matchAttributes(const std::set<std::string> &values) const;
bool matchAttributesRegEx(const std::set<std::string> &values) const;
bool matchAttributesString(const std::set<std::string> &values) const;
bool isRegEx() const;
MatchType type;
Operators operator_type;
Conditions condition_type;
std::string key;
StaticKeys key_type;
bool is_specific_label;
std::string first_value;
std::set<std::string> value;
std::set<boost::regex> regex_values;
std::vector<IPRange> ip_addr_value;
std::vector<PortsRange> port_value;
std::vector<IpProtoRange> ip_proto_value;
std::vector<MatchQuery> items;
};
#endif // __MATCH_QUERY_H__

View File

@@ -0,0 +1,221 @@
// 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 __PARAMETERS_CONFIG_H__
#define __PARAMETERS_CONFIG_H__
#include <string>
#include <vector>
#include <set>
#include <unordered_map>
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/json.hpp"
#include "generic_rulebase/generic_rulebase_utils.h"
#include "match_query.h"
#include "maybe_res.h"
#include "config.h"
enum class BehaviorKey
{
ACTION,
LOG,
SOURCE_IDENTIFIER,
HTTP_SOURCE_ID,
HTTPS_SOURCE_ID
};
enum class BehaviorValue
{
REJECT,
ACCEPT,
IGNORE,
DROP,
X_FORWARDED_FOR,
COOKIE_AOUTH2_PROXY,
COOKIE_JSESSIONID
};
static const std::unordered_map<std::string, BehaviorKey> string_to_behavior_key = {
{ "action", BehaviorKey::ACTION },
{ "log", BehaviorKey::LOG },
{ "sourceIdentifier", BehaviorKey::SOURCE_IDENTIFIER },
{ "httpSourceId", BehaviorKey::HTTP_SOURCE_ID },
{ "httpsSourceId", BehaviorKey::HTTPS_SOURCE_ID }
};
static const std::unordered_map<std::string, BehaviorValue> string_to_behavior_val = {
{ "Cookie:_oauth2_proxy", BehaviorValue::COOKIE_AOUTH2_PROXY },
{ "Cookie:JSESSIONID", BehaviorValue::COOKIE_JSESSIONID },
{ "X-Forwarded-For", BehaviorValue::X_FORWARDED_FOR },
{ "reject", BehaviorValue::REJECT },
{ "accept", BehaviorValue::ACCEPT },
{ "ignore", BehaviorValue::IGNORE },
{ "drop", BehaviorValue::DROP }
};
class ParameterOverrides
{
public:
class ParsedBehavior
{
public:
void
serialize(cereal::JSONInputArchive &archive_in)
{
parseJSONKey<std::string>("log", log, archive_in);
}
const std::string & getParsedBehaviorLog() const { return log; }
private:
std::string log;
};
void load(cereal::JSONInputArchive &archive_in);
const std::vector<ParsedBehavior> & getParsedBehaviors() const { return parsed_behaviors; }
private:
std::vector<ParsedBehavior> parsed_behaviors;
};
class ParameterTrustedSources
{
public:
class SourcesIdentifier
{
public:
SourcesIdentifier() = default;
void
serialize(cereal::JSONInputArchive &archive_in)
{
parseJSONKey<std::string>("sourceIdentifier", source_identifier, archive_in);
parseJSONKey<std::string>("value", value, archive_in);
}
const std::string & getSourceIdentifier() const {return source_identifier; }
const std::string & getValue() const {return value; }
private:
std::string source_identifier;
std::string value;
};
void load(cereal::JSONInputArchive &archive_in);
uint getNumOfSources() const { return num_of_sources; }
const std::vector<SourcesIdentifier> & getSourcesIdentifiers() const { return sources_identidiers; }
private:
uint num_of_sources;
std::vector<SourcesIdentifier> sources_identidiers;
};
class ParameterBehavior
{
public:
ParameterBehavior() = default;
ParameterBehavior(BehaviorKey &_key, BehaviorValue &_value) : key(_key), value(_value) {}
ParameterBehavior(BehaviorKey &&_key, BehaviorValue &&_value)
:
key(std::move(_key)),
value(std::move(_value))
{}
void load(cereal::JSONInputArchive &archive_in);
const BehaviorValue & getValue() const { return value; }
const BehaviorKey & getKey() const { return key; }
const std::string & getId() const { return id; }
bool
operator<(const ParameterBehavior &other) const {
return (key < other.key) || (key == other.key && value < other.value);
}
bool operator==(const ParameterBehavior &other) const { return key == other.key && value == other.value; }
private:
std::string id;
BehaviorKey key;
BehaviorValue value;
};
class ParameterAntiBot
{
public:
void load(cereal::JSONInputArchive &archive_in);
std::vector<std::string> & getInjected() { return injected; }
std::vector<std::string> & getValidated() { return validated; }
private:
std::vector<std::string> injected;
std::vector<std::string> validated;
};
class ParameterOAS
{
public:
void load(cereal::JSONInputArchive &archive_in);
const std::string & getValue() const { return value; }
private:
std::string value;
};
class ParameterException
{
public:
static void
preload()
{
registerExpectedConfiguration<ParameterException>("rulebase", "exception");
registerConfigLoadCb([](){ is_geo_location_exception_exists = is_geo_location_exception_being_loaded; });
registerConfigPrepareCb([](){ is_geo_location_exception_being_loaded = false; });
}
void load(cereal::JSONInputArchive &archive_in);
std::set<ParameterBehavior>
getBehavior(const std::unordered_map<std::string, std::set<std::string>> &key_value_pairs) const;
static bool isGeoLocationExceptionExists() { return is_geo_location_exception_exists; }
private:
class MatchBehaviorPair
{
public:
void load(cereal::JSONInputArchive &archive_in);
MatchQuery match;
ParameterBehavior behavior;
};
std::vector<MatchBehaviorPair> match_queries;
MatchQuery match;
ParameterBehavior behavior;
static bool is_geo_location_exception_exists;
static bool is_geo_location_exception_being_loaded;
};
#endif //__PARAMETERS_CONFIG_H__

View File

@@ -0,0 +1,167 @@
// 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 __RULEBASE_CONFIG_H__
#define __RULEBASE_CONFIG_H__
#include <vector>
#include <string>
#include <set>
#include <unordered_map>
#include "generic_rulebase/generic_rulebase_utils.h"
#include "environment/evaluator_templates.h"
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/json.hpp"
#include "i_environment.h"
#include "singleton.h"
#include "maybe_res.h"
#include "config.h"
using GenericConfigId = std::string;
class RulePractice
{
public:
RulePractice() = default;
RulePractice(GenericConfigId &_id, std::string &_name) : practice_id(_id), practice_name(_name) {};
void
serialize(cereal::JSONInputArchive &ar)
{
parseJSONKey<GenericConfigId>("practiceId", practice_id, ar);
parseJSONKey<std::string>("practiceName", practice_name, ar);
}
const GenericConfigId getId() const { return practice_id; }
const std::string getName() const { return practice_name; }
bool
operator==(const RulePractice &other) const
{
return practice_id == other.getId() && practice_name == other.getName();
}
private:
GenericConfigId practice_id;
std::string practice_name;
};
class RuleTrigger
{
public:
void
serialize(cereal::JSONInputArchive &ar)
{
parseJSONKey<GenericConfigId>("triggerId", trigger_id, ar);
parseJSONKey<std::string>("triggerType", trigger_type, ar);
parseJSONKey<std::string>("triggerName", trigger_name, ar);
}
const GenericConfigId getId() const { return trigger_id; }
const std::string getType() const { return trigger_type; }
const std::string getName() const { return trigger_name; }
private:
GenericConfigId trigger_id;
std::string trigger_type;
std::string trigger_name;
};
class RuleParameter
{
public:
void
serialize(cereal::JSONInputArchive &ar)
{
parseJSONKey<GenericConfigId>("parameterId", parameter_id, ar);
parseJSONKey<std::string>("parameterType", parameter_type, ar);
parseJSONKey<std::string>("parameterName", parameter_name, ar);
}
const GenericConfigId getId() const { return parameter_id; }
const std::string getType() const { return parameter_type; }
const std::string getName() const { return parameter_name; }
private:
GenericConfigId parameter_id;
std::string parameter_type;
std::string parameter_name;
};
class BasicRuleConfig
{
public:
static void
preload()
{
registerExpectedConfiguration<BasicRuleConfig>("rulebase", "rulesConfig");
registerExpectedSetting<std::vector<BasicRuleConfig>>("rulebase", "rulesConfig");
registerConfigLoadCb(BasicRuleConfig::updateCountMetric);
registerConfigPrepareCb([](){ BasicRuleConfig::assets_ids_aggregation.clear(); });
}
void load(cereal::JSONInputArchive &ar);
static void updateCountMetric();
bool isPracticeActive(const GenericConfigId &practice_id) const;
bool isTriggerActive(const GenericConfigId &trigger_id) const;
bool isParameterActive(const GenericConfigId &parameter_id) const;
uint8_t getPriority() const { return priority; }
const GenericConfigId & getRuleId() const { return rule_id; }
const std::string & getRuleName() const { return rule_name; }
const GenericConfigId & getAssetId() const { return asset_id; }
const std::string & getAssetName() const { return asset_name; }
const GenericConfigId & getZoneId() const { return zone_id; }
const std::string & getZoneName() const { return zone_name; }
const std::vector<RulePractice> & getPractices() const { return practices; }
const std::vector<RuleTrigger> & getTriggers() const { return triggers; }
const std::vector<RuleParameter> & getParameters() const { return parameters; }
private:
uint8_t priority = 0;
GenericConfigId rule_id = "";
std::string rule_name;
GenericConfigId asset_id;
std::string asset_name;
GenericConfigId zone_id;
std::string zone_name;
std::vector<RulePractice> practices;
std::vector<RuleTrigger> triggers;
std::vector<RuleParameter> parameters;
static std::set<std::string> assets_ids;
static std::set<std::string> assets_ids_aggregation;
};
#endif // __RULEBASE_CONFIG_H__

View File

@@ -0,0 +1,174 @@
// 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 __TRIGGERS_CONFIG_H__
#define __TRIGGERS_CONFIG_H__
#include <vector>
#include <string>
#include "environment/evaluator_templates.h"
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "cereal/archives/json.hpp"
#include "i_environment.h"
#include "i_logging.h"
#include "singleton.h"
#include "maybe_res.h"
#include "config.h"
#include "log_generator.h"
#include "generic_rulebase_utils.h"
class WebTriggerConf
{
public:
WebTriggerConf();
WebTriggerConf(const std::string &title, const std::string &body, uint code);
static void
preload()
{
registerExpectedConfiguration<WebTriggerConf>("rulebase", "webUserResponse");
}
void load(cereal::JSONInputArchive &archive_in);
bool operator==(const WebTriggerConf &other) const;
uint getResponseCode() const { return response_code; }
const std::string & getResponseTitle() const { return response_title; }
const std::string & getResponseBody() const { return response_body; }
const std::string & getDetailsLevel() const { return details_level; }
const std::string & getRedirectURL() const { return redirect_url; }
bool getAddEventId() const { return add_event_id_to_header; }
static WebTriggerConf default_trigger_conf;
private:
std::string response_title;
std::string details_level;
std::string response_body;
std::string redirect_url;
uint response_code;
bool add_event_id_to_header = false;
};
class LogTriggerConf : Singleton::Consume<I_Logging>
{
public:
enum class SecurityType { AccessControl, ThreatPrevention, Compliance, COUNT };
enum class extendLoggingSeverity { None, High, Critical };
enum class WebLogFields {
webBody,
webHeaders,
webRequests,
webUrlPath,
webUrlQuery,
responseBody,
responseCode,
COUNT
};
LogTriggerConf() {}
LogTriggerConf(std::string trigger_name, bool log_detect, bool log_prevent);
static void
preload()
{
registerExpectedConfiguration<LogTriggerConf>("rulebase", "log");
}
template <typename ...Tags>
LogGen
operator()(
const std::string &title,
SecurityType security,
ReportIS::Severity severity,
ReportIS::Priority priority,
bool is_action_drop_or_prevent,
Tags ...tags) const
{
return LogGen(
title,
ReportIS::Level::LOG,
ReportIS::Audience::SECURITY,
severity,
priority,
std::forward<Tags>(tags)...,
getStreams(security, is_action_drop_or_prevent),
getEnrechments(security)
);
}
template <typename ...Tags>
LogGen
operator()(const std::string &title, SecurityType security, bool is_action_drop_or_prevent, Tags ...tags) const
{
return (*this)(
title,
security,
getSeverity(is_action_drop_or_prevent),
getPriority(is_action_drop_or_prevent),
is_action_drop_or_prevent,
std::forward<Tags>(tags)...
);
}
void load(cereal::JSONInputArchive &archive_in);
bool isWebLogFieldActive(WebLogFields log_field) const { return log_web_fields.isSet(log_field); }
bool isLogStreamActive(ReportIS::StreamType stream_type) const { return active_streams.isSet(stream_type); }
bool isPreventLogActive(SecurityType security_type) const { return should_log_on_prevent.isSet(security_type); }
bool isDetectLogActive(SecurityType security_type) const { return should_log_on_detect.isSet(security_type); }
bool isLogGeoLocationActive(SecurityType security_type) const { return log_geo_location.isSet(security_type); }
extendLoggingSeverity getExtendLoggingSeverity() const { return extend_logging_severity; }
const std::string & getVerbosity() const { return verbosity; }
const std::string & getName() const { return name; }
const std::string & getUrlForSyslog() const { return url_for_syslog; }
const std::string & getUrlForCef() const { return url_for_cef; }
private:
ReportIS::Severity getSeverity(bool is_action_drop_or_prevent) const;
ReportIS::Priority getPriority(bool is_action_drop_or_prevent) const;
Flags<ReportIS::StreamType> getStreams(SecurityType security_type, bool is_action_drop_or_prevent) const;
Flags<ReportIS::Enreachments> getEnrechments(SecurityType security_type) const;
std::string name;
std::string verbosity;
std::string url_for_syslog = "";
std::string url_for_cef = "";
Flags<ReportIS::StreamType> active_streams;
Flags<SecurityType> should_log_on_detect;
Flags<SecurityType> should_log_on_prevent;
Flags<SecurityType> log_geo_location;
Flags<WebLogFields> log_web_fields;
extendLoggingSeverity extend_logging_severity = extendLoggingSeverity::None;
bool should_format_output = false;
};
#endif //__TRIGGERS_CONFIG_H__

View File

@@ -0,0 +1,55 @@
// 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 __ZONE_H__
#define __ZONE_H__
#include <vector>
#include <string>
#include <set>
#include <arpa/inet.h>
#include "generic_rulebase_context.h"
#include "match_query.h"
#include "i_environment.h"
#include "i_intelligence_is_v2.h"
#include "asset.h"
class Zone : Singleton::Consume<I_Intelligence_IS_V2>, Singleton::Consume<I_Environment>
{
using AttrData = std::unordered_map<std::string, std::set<std::string>>;
public:
enum class Direction { To, From, Bidirectional };
void load(cereal::JSONInputArchive &archive_in);
bool contains(const Asset &asset);
GenericConfigId getId() const { return zone_id; }
const std::string & getName() const { return zone_name; }
const std::vector<std::pair<Direction, GenericConfigId>> & getAdjacentZones() const { return adjacent_zones; }
const MatchQuery & getMatchQuery() const { return match_query; }
bool isAnyZone() const { return is_any; }
private:
bool matchAttributes(const AttrData &data);
GenericConfigId zone_id;
std::string zone_name;
std::vector<std::pair<Direction, GenericConfigId>> adjacent_zones;
MatchQuery match_query;
bool is_any;
};
#endif // __ZONE_H__

View File

@@ -0,0 +1,53 @@
// 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 __ZONES_CONFIG_H__
#define __ZONES_CONFIG_H__
#include <vector>
#include <string>
#include <set>
#include <arpa/inet.h>
#include "generic_rulebase_context.h"
#include "match_query.h"
#include "i_generic_rulebase.h"
#include "zone.h"
class Zones
{
public:
void load(cereal::JSONInputArchive &archive_in)
{
cereal::load(archive_in, zones);
}
const std::vector<Zone> & getZones() const { return zones; }
std::vector<Zone> zones;
};
class ZonesConfig : Singleton::Consume<I_GenericRulebase>
{
public:
static void preload();
void load(cereal::JSONInputArchive &archive_in);
const std::vector<Zone> & getZones() const { return zones; }
private:
std::vector<Zone> zones;
};
#endif //__ZONES_CONFIG_H__

View File

@@ -0,0 +1,43 @@
// 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 __GRADUAL_DEPLOYMENT_H__
#define __GRADUAL_DEPLOYMENT_H__
#include "i_gradual_deployment.h"
#include "singleton.h"
#include "i_rest_api.h"
#include "i_table.h"
#include "i_mainloop.h"
#include "component.h"
class GradualDeployment
:
public Component,
Singleton::Provide<I_GradualDeployment>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_MainLoop>
{
public:
GradualDeployment();
~GradualDeployment();
void init();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __GRADUAL_DEPLOYMENT_H__

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 __HEALTH_CHECK_MANAGER_H__
#define __HEALTH_CHECK_MANAGER_H__
#include "singleton.h"
#include "i_health_check_manager.h"
#include "i_mainloop.h"
#include "i_rest_api.h"
#include "component.h"
#include "i_messaging.h"
#include "i_environment.h"
class HealthCheckManager
:
public Component,
Singleton::Provide<I_Health_Check_Manager>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_Environment>
{
public:
HealthCheckManager();
~HealthCheckManager();
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __HEALTH_CHECK_MANAGER_H__

View File

@@ -0,0 +1,44 @@
// 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 __HEALTH_CHECKER_H__
#define __HEALTH_CHECKER_H__
#include "singleton.h"
#include "i_mainloop.h"
#include "i_socket_is.h"
#include "i_health_check_manager.h"
#include "component.h"
class HealthChecker
:
public Component,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Socket>,
Singleton::Consume<I_Health_Check_Manager>
{
public:
HealthChecker();
~HealthChecker();
void init() override;
void fini() override;
void preload() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __HEALTH_CHECKER_H__

View File

@@ -0,0 +1,69 @@
// 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 __FILTER_VERDICT_H__
#define __FILTER_VERDICT_H__
#include <memory>
#include "maybe_res.h"
#include "i_http_event_impl.h"
class FilterVerdict
{
public:
FilterVerdict(ngx_http_cp_verdict_e _verdict = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_INSPECT)
:
verdict(_verdict)
{}
FilterVerdict(const EventVerdict &_verdict, ModifiedChunkIndex _event_idx = -1)
:
verdict(_verdict.getVerdict())
{
if (verdict == ngx_http_cp_verdict_e::TRAFFIC_VERDICT_INJECT) {
addModifications(_verdict.getModifications(), _event_idx);
}
}
void
addModifications(const FilterVerdict &other)
{
if (other.verdict != ngx_http_cp_verdict_e::TRAFFIC_VERDICT_INJECT) return;
modifications.insert(modifications.end(), other.modifications.begin(), other.modifications.end());
total_modifications += other.total_modifications;
}
void
addModifications(
const ModificationList &mods,
ModifiedChunkIndex _event_idx,
ngx_http_cp_verdict_e alt_verdict = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_IRRELEVANT)
{
total_modifications += mods.size();
modifications.push_back(EventModifications(_event_idx, mods));
if (alt_verdict != ngx_http_cp_verdict_e::TRAFFIC_VERDICT_IRRELEVANT) verdict = alt_verdict;
}
uint getModificationsAmount() const { return total_modifications; }
ngx_http_cp_verdict_e getVerdict() const { return verdict; }
const std::vector<EventModifications> & getModifications() const { return modifications; }
private:
ngx_http_cp_verdict_e verdict = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_INSPECT;
std::vector<EventModifications> modifications;
uint total_modifications = 0;
};
#endif // __FILTER_VERDICT_H__

View File

@@ -0,0 +1,387 @@
// 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 __I_HTTP_EVENT_IMPL_H__
#define __I_HTTP_EVENT_IMPL_H__
#ifndef __HTTP_INSPECTION_EVENTS_H__
#error i_http_event_impl.h should not be included directly!
#endif //__HTTP_INSPECTION_EVENTS_H__
#include <string>
#include <map>
#include <vector>
#include "debug.h"
#include "buffer.h"
#include "http_transaction_data.h"
#include "nginx_attachment_common.h"
USE_DEBUG_FLAG(D_HTTP_MANAGER);
using ModificationType = ngx_http_modification_type_e;
using ModificationPosition = ngx_http_cp_inject_pos_t;
static const ModificationPosition injection_pos_irrelevant = INJECT_POS_IRRELEVANT;
template <typename TMod>
class Modification
{
public:
Modification(const TMod &mod, ModificationType mod_type)
:
Modification(mod, mod_type, injection_pos_irrelevant)
{}
Modification(const TMod &mod, ModificationType mod_type, ModificationPosition mod_position)
:
modification(mod),
type(mod_type),
position(mod_position)
{
dbgAssert(mod_type != ModificationType::APPEND || position == injection_pos_irrelevant)
<< "Injection position is not applicable to a modification of type \"Append\"";
dbgAssert(mod_type != ModificationType::INJECT || position >= 0)
<< "Invalid injection position: must be non-negative. Position: "
<< position;
}
ModificationPosition getModificationPosition() const { return position; }
ModificationType getModificationType() const { return type; }
const TMod & getModification() const { return modification; }
private:
TMod modification;
ModificationType type;
ModificationPosition position;
};
using ModifiedChunkIndex = int;
using ModificationBuffer = std::tuple<ModificationPosition, ModificationType, Buffer>;
using ModificationList = std::vector<ModificationBuffer>;
using EventModifications = std::pair<ModifiedChunkIndex, ModificationList>;
template <typename TMod>
class I_ModifiableContent
{
public:
virtual Maybe<void> modify(const Modification<TMod> &mod) = 0;
virtual ModificationList getModificationList() const = 0;
protected:
virtual ~I_ModifiableContent() {}
};
using HeaderKey = std::string;
using HeaderModification = std::pair<std::pair<ModificationPosition, HeaderKey>, Buffer>;
class HttpHeaderModification : I_ModifiableContent<HeaderModification>
{
public:
Maybe<void>
appendHeader(const HeaderKey &key, const Buffer &value)
{
return modify(
Modification<HeaderModification>(
HeaderModification({ { injection_pos_irrelevant, key }, value }),
ModificationType::APPEND
)
);
}
Maybe<void>
injectValue(ModificationPosition position, const Buffer &data)
{
return modify(
Modification<HeaderModification>(
HeaderModification({ { position, HeaderKey() }, data }),
ModificationType::INJECT,
position
)
);
}
ModificationList
getModificationList() const override
{
ModificationList modification_list;
for (const auto &modification : headers_to_append) {
modification_list.emplace_back(injection_pos_irrelevant, ModificationType::APPEND, modification.first);
modification_list.emplace_back(injection_pos_irrelevant, ModificationType::APPEND, modification.second);
}
for (const auto &modification : header_injections) {
modification_list.emplace_back(modification.first, ModificationType::INJECT, modification.second);
}
return modification_list;
}
private:
Maybe<void>
modify(const Modification<HeaderModification> &mod) override
{
auto modification_type = mod.getModificationType();
switch (modification_type) {
case ModificationType::APPEND: {
const HeaderKey &appended_header_key = mod.getModification().first.second;
auto iterator = headers_to_append.find(appended_header_key);
if (iterator != headers_to_append.end()) {
return
genError(
"Append modification with provided header key already exists. Header key: \"" +
appended_header_key +
"\""
);
}
headers_to_append.emplace(appended_header_key, mod.getModification().second);
break;
}
case ModificationType::INJECT: {
auto iterator = header_injections.find(mod.getModificationPosition());
if (iterator != header_injections.end()) {
return genError("Inject modification with provided position already exists");
}
header_injections.emplace(mod.getModificationPosition(), mod.getModification().second);
break;
}
case ModificationType::REPLACE: {
// future support to pass new Content-Length
dbgWarning(D_HTTP_MANAGER) << "Replace modification is not yet supported";
break;
}
default:
dbgAssert(false)
<< "Unknown type of ModificationType: "
<< static_cast<int>(modification_type);
}
return Maybe<void>();
}
private:
std::map<HeaderKey, Buffer> headers_to_append;
std::map<ModificationPosition, Buffer> header_injections;
};
class HttpHeader
{
public:
HttpHeader() = default;
HttpHeader(const Buffer &_key, const Buffer &_value, uint8_t _header_index, bool _is_last_header = false)
:
key(_key),
value(_value),
is_last_header(_is_last_header),
header_index(_header_index)
{
}
// LCOV_EXCL_START - sync functions, can only be tested once the sync module exists
template <class Archive>
void
save(Archive &ar) const
{
ar(
key,
value,
is_last_header,
header_index
);
}
template <class Archive>
void
load(Archive &ar)
{
ar(
key,
value,
is_last_header,
header_index
);
}
// LCOV_EXCL_STOP
void
print(std::ostream &out_stream) const
{
out_stream
<< "'"
<< std::dumpHex(key)
<< "': '"
<< std::dumpHex(value)
<< "' (Index: "
<< std::to_string(header_index)
<< ", Is last header: "
<< (is_last_header ? "True" : "False")
<< ")";
}
const Buffer & getKey() const { return key; }
const Buffer & getValue() const { return value; }
bool isLastHeader() const { return is_last_header; }
uint8_t getHeaderIndex() const { return header_index; }
private:
Buffer key;
Buffer value;
bool is_last_header = false;
uint8_t header_index = 0;
};
using BodyModification = Buffer;
class HttpBodyModification : I_ModifiableContent<BodyModification>
{
public:
Maybe<void>
inject(ModificationPosition position, const Buffer &data)
{
return modify(
Modification<BodyModification>(
std::move(data),
ModificationType::INJECT,
position
)
);
}
ModificationList
getModificationList() const override
{
ModificationList injected_data;
for (const auto &injection : modifications) {
auto injection_buffer = injection.second;
injected_data.emplace_back(injection.first, ModificationType::INJECT, injection_buffer);
}
return injected_data;
}
private:
Maybe<void>
modify(const Modification<BodyModification> &mod) override
{
if (modifications.find(mod.getModificationPosition()) != modifications.end()) {
return genError("Modification at the provided index already exists");
}
modifications[mod.getModificationPosition()] = mod.getModification();
return Maybe<void>();
}
std::map<ModificationPosition, Buffer> modifications;
};
class HttpBody
{
public:
HttpBody()
:
data(),
previous_chunked_data(),
is_last_chunk(false),
body_chunk_index(0)
{}
HttpBody(const Buffer &body_data, bool _is_last_chunk, uint8_t _body_chunk_index)
:
data(body_data),
previous_chunked_data(),
is_last_chunk(_is_last_chunk),
body_chunk_index(_body_chunk_index)
{}
// LCOV_EXCL_START - sync functions, can only be tested once the sync module exists
template <class Archive>
void
save(Archive &ar) const
{
ar(
data,
previous_chunked_data,
is_last_chunk,
body_chunk_index
);
}
template <class Archive>
void
load(Archive &ar)
{
ar(
data,
previous_chunked_data,
is_last_chunk,
body_chunk_index
);
}
// LCOV_EXCL_STOP
void
print(std::ostream &out_stream) const
{
out_stream
<< "'"
<< std::dumpHex(data)
<< "' (Index: "
<< std::to_string(body_chunk_index)
<< ", Is last chunk: "
<< (is_last_chunk ? "True" : "False")
<< ")";
}
const Buffer & getData() const { return data; }
const Buffer & getPreviousChunkedData() const { return previous_chunked_data; }
void setPreviousChunkedData(const Buffer &prev_body_data) { previous_chunked_data = prev_body_data; }
bool isLastChunk() const { return is_last_chunk; }
uint8_t getBodyChunkIndex() const { return body_chunk_index; }
private:
Buffer data;
Buffer previous_chunked_data;
bool is_last_chunk;
uint8_t body_chunk_index;
};
class EventVerdict
{
public:
EventVerdict() = default;
EventVerdict(ngx_http_cp_verdict_e event_verdict) : modifications(), verdict(event_verdict) {}
EventVerdict(const ModificationList &mods) : modifications(mods) {}
EventVerdict(const ModificationList &mods, ngx_http_cp_verdict_e event_verdict) :
modifications(mods),
verdict(event_verdict)
{}
// LCOV_EXCL_START - sync functions, can only be tested once the sync module exists
template <typename T> void serialize(T &ar, uint) { ar(verdict); }
// LCOV_EXCL_STOP
const ModificationList & getModifications() const { return modifications; }
ngx_http_cp_verdict_e getVerdict() const { return verdict; }
private:
ModificationList modifications;
ngx_http_cp_verdict_e verdict = ngx_http_cp_verdict_e::TRAFFIC_VERDICT_INSPECT;
};
#endif // __I_HTTP_EVENT_IMPL_H__

View File

@@ -0,0 +1,186 @@
// 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 __HTTP_INSPECTION_EVENTS_H__
#define __HTTP_INSPECTION_EVENTS_H__
#include "debug.h"
#include "event.h"
#include "http_event_impl/filter_verdict.h"
#include "http_event_impl/i_http_event_impl.h"
using ResponseCode = uint16_t;
class HttpRequestHeaderEvent : public Event<HttpRequestHeaderEvent, EventVerdict>
{
public:
HttpRequestHeaderEvent(const HttpHeader &header) : req_header(header) {}
const Buffer & getKey() const { return req_header.getKey(); }
const Buffer & getValue() const { return req_header.getValue(); }
bool isLastHeader() const { return req_header.isLastHeader(); }
uint8_t getHeaderIndex() const { return req_header.getHeaderIndex(); }
template <class Archive>
void
save(Archive &ar) const
{
req_header.save(ar);
}
void print(std::ostream &out_stream) const { req_header.print(out_stream); }
private:
const HttpHeader &req_header;
};
class HttpResponseHeaderEvent: public Event<HttpResponseHeaderEvent, EventVerdict>
{
public:
HttpResponseHeaderEvent(const HttpHeader &header) : res_header(header) {}
const Buffer & getKey() const { return res_header.getKey(); }
const Buffer & getValue() const { return res_header.getValue(); }
bool isLastHeader() const { return res_header.isLastHeader(); }
uint8_t getHeaderIndex() const { return res_header.getHeaderIndex(); }
template <class Archive>
void
save(Archive &ar) const
{
res_header.save(ar);
}
void print(std::ostream &out_stream) const { res_header.print(out_stream); }
private:
const HttpHeader &res_header;
};
class HttpRequestBodyEvent: public Event<HttpRequestBodyEvent, EventVerdict>
{
public:
HttpRequestBodyEvent(const HttpBody &body, const Buffer &previous_chunked_data)
:
req_body(body),
prev_chunked_data(previous_chunked_data)
{}
const Buffer & getData() const { return req_body.getData(); }
const Buffer & getPreviousChunkedData() const { return prev_chunked_data; }
bool isLastChunk() const { return req_body.isLastChunk(); }
template <class Archive>
void
save(Archive &ar) const
{
req_body.save(ar);
}
void print(std::ostream &out_stream) const { req_body.print(out_stream); }
private:
const HttpBody &req_body;
const Buffer &prev_chunked_data;
};
class HttpResponseBodyEvent: public Event<HttpResponseBodyEvent, EventVerdict>
{
public:
HttpResponseBodyEvent(const HttpBody &body, const Buffer &previous_chunked_data)
:
res_body(body),
prev_chunked_data(previous_chunked_data)
{}
const Buffer & getData() const { return res_body.getData(); }
const Buffer & getPreviousChunkedData() const { return prev_chunked_data; }
bool isLastChunk() const { return res_body.isLastChunk(); }
uint8_t getBodyChunkIndex() const { return res_body.getBodyChunkIndex(); }
template <class Archive>
void
save(Archive &ar) const
{
res_body.save(ar);
}
void print(std::ostream &out_stream) const { res_body.print(out_stream); }
private:
const HttpBody &res_body;
const Buffer &prev_chunked_data;
};
class NewHttpTransactionEvent : public Event<NewHttpTransactionEvent, EventVerdict>
{
public:
NewHttpTransactionEvent(const HttpTransactionData &event_data) : http_transaction_event_data(event_data) {}
const IPAddr & getSourceIP() const { return http_transaction_event_data.getSourceIP(); }
uint16_t getSourcePort() const { return http_transaction_event_data.getSourcePort(); }
const IPAddr & getListeningIP() const { return http_transaction_event_data.getListeningIP(); }
uint16_t getListeningPort() const { return http_transaction_event_data.getListeningPort(); }
const std::string & getDestinationHost() const { return http_transaction_event_data.getDestinationHost(); }
const std::string & getHttpProtocol() const { return http_transaction_event_data.getHttpProtocol(); }
const std::string & getURI() const { return http_transaction_event_data.getURI(); }
const std::string & getHttpMethod() const { return http_transaction_event_data.getHttpMethod(); }
void print(std::ostream &out_stream) const { http_transaction_event_data.print(out_stream); }
template <class Archive>
void
save(Archive &ar) const
{
http_transaction_event_data.save(ar);
}
private:
const HttpTransactionData &http_transaction_event_data;
};
class ResponseCodeEvent : public Event<ResponseCodeEvent, EventVerdict>
{
public:
ResponseCodeEvent(const ResponseCode &res_code) : http_response_code(res_code) {}
const ResponseCode & getResponseCode() const { return http_response_code; }
template <class Archive>
void
save(Archive &ar) const
{
ar(http_response_code);
}
void print(std::ostream &out_stream) const { out_stream << http_response_code; }
private:
ResponseCode http_response_code;
};
class EndRequestEvent : public Event<EndRequestEvent, EventVerdict>
{
};
class EndTransactionEvent : public Event<EndTransactionEvent, EventVerdict>
{
};
class WaitTransactionEvent : public Event<WaitTransactionEvent, EventVerdict>
{
};
#endif // __HTTP_INSPECTION_EVENTS_H__

View File

@@ -0,0 +1,47 @@
// 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 __HTTP_MANAGER_H__
#define __HTTP_MANAGER_H__
#include "singleton.h"
#include "i_mainloop.h"
#include "i_http_manager.h"
#include "i_rest_api.h"
#include "i_table.h"
#include "i_logging.h"
#include "component.h"
class HttpManager
:
public Component,
Singleton::Provide<I_HttpManager>,
Singleton::Consume<I_Table>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Logging>,
Singleton::Consume<I_TimeGet>
{
public:
HttpManager();
~HttpManager();
void preload();
void init();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __HTTP_MANAGER_H__

View File

@@ -0,0 +1,37 @@
// 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 __HTTP_TRANSACTION_ENUM_H__
#define __HTTP_TRANSACTION_ENUM_H__
namespace HttpTransaction {
enum class Method { GET, HEAD, POST, DELETE, CONNECT, OPTIONS, TRACE, PATCH, PUT };
enum class Dir { REQUEST, RESPONSE };
enum class Verdict { ACCEPT, DROP, INJECT, REDIRECT, NONE, DEFAULT };
enum class StatusCode {
OK = 200,
CREATED = 201,
NO_CONTENT = 204,
NOT_MODIFIED = 304,
BAD_REQUEST = 400,
UNAUTHORIZED = 401,
FORBIDDEN = 403,
NOT_FOUND = 404,
CONFLICT = 409,
INTERNAL_SERVER_ERROR = 500
};
}
#endif // __HTTP_TRANSACTION_ENUM_H__

View File

@@ -0,0 +1,136 @@
// 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 __HTTP_TRANSACTION_DATA_H__
#define __HTTP_TRANSACTION_DATA_H__
#include <iostream>
#include <string>
#include <list>
#include <string>
#include <vector>
#include "connkey.h"
#include "buffer.h"
#include "enum_range.h"
#include "maybe_res.h"
#include "http_transaction_common.h"
#include "compression_utils.h"
class HttpTransactionData
{
public:
HttpTransactionData();
HttpTransactionData (
std::string http_proto,
std::string method,
std::string host_name,
IPAddr listening_ip,
uint16_t listening_port,
std::string uri,
IPAddr client_ip,
uint16_t client_port
);
// LCOV_EXCL_START - sync functions, can only be tested once the sync module exists
template <class Archive>
void
save(Archive &ar) const
{
ar(
http_proto,
method,
host_name,
listening_ip,
listening_port,
uri,
client_ip,
client_port,
response_content_encoding
);
}
template <class Archive>
void
load(Archive &ar)
{
ar(
http_proto,
method,
host_name,
listening_ip,
listening_port,
uri,
client_ip,
client_port,
response_content_encoding
);
}
// LCOV_EXCL_STOP
static Maybe<HttpTransactionData> createTransactionData(const Buffer &transaction_raw_data);
const IPAddr & getSourceIP() const { return client_ip; }
uint16_t getSourcePort() const { return client_port; }
const IPAddr & getListeningIP() const { return listening_ip; }
uint16_t getListeningPort() const { return listening_port; }
const std::string & getDestinationHost() const { return host_name; }
const std::string & getHttpProtocol() const { return http_proto; }
const std::string & getURI() const { return uri; }
const std::string & getHttpMethod() const { return method; }
void print(std::ostream &out_stream) const;
CompressionType getResponseContentEncoding() const { return response_content_encoding; }
bool isRequest() const { return is_request; }
void setDirection(bool _is_request) { is_request = _is_request; }
void
setResponseContentEncoding(const CompressionType _response_content_encoding)
{
response_content_encoding = _response_content_encoding;
}
static const std::string http_proto_ctx;
static const std::string method_ctx;
static const std::string host_name_ctx;
static const std::string listening_port_ctx;
static const std::string listening_ip_ctx;
static const std::string uri_ctx;
static const std::string uri_path_decoded;
static const std::string uri_query_decoded;
static const std::string client_ip_ctx;
static const std::string client_port_ctx;
static const std::string req_headers;
static const std::string req_body;
static const std::string source_identifier;
static const std::string proxy_ip_ctx;
static const CompressionType default_response_content_encoding;
private:
std::string http_proto;
std::string method = "GET";
std::string host_name;
IPAddr listening_ip;
uint16_t listening_port;
std::string uri;
IPAddr client_ip;
uint16_t client_port;
bool is_request;
CompressionType response_content_encoding;
};
#endif // __HTTP_TRANSACTION_DATA_H__

View File

@@ -0,0 +1,34 @@
// 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 __HYBRID_MODE_TELEMETRY_H__
#define __HYBRID_MODE_TELEMETRY_H__
#include "generic_metric.h"
class HybridModeMetricEvent : public Event<HybridModeMetricEvent>
{
public:
HybridModeMetricEvent() {}
};
class HybridModeMetric : public GenericMetric, public Listener<HybridModeMetricEvent>
{
public:
void upon(const HybridModeMetricEvent &event) override;
private:
MetricCalculations::LastReportedValue<int> wd_process_restart{this, "watchdogProcessStartupEventsSum"};
};
#endif // __HYBRID_MODE_TELEMETRY_H__

View File

@@ -0,0 +1,42 @@
// 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 __I_DETAILS_RESOLVER_H__
#define __I_DETAILS_RESOLVER_H__
#include "maybe_res.h"
#include <string>
class I_DetailsResolver
{
public:
virtual Maybe<std::string> getHostname() = 0;
virtual Maybe<std::string> getPlatform() = 0;
virtual Maybe<std::string> getArch() = 0;
virtual std::string getAgentVersion() = 0;
virtual bool isKernelVersion3OrHigher() = 0;
virtual bool isGwNotVsx() = 0;
virtual bool isVersionEqualOrAboveR8110() = 0;
virtual bool isReverseProxy() = 0;
virtual Maybe<std::tuple<std::string, std::string, std::string>> parseNginxMetadata() = 0;
virtual std::map<std::string, std::string> getResolvedDetails() = 0;
#if defined(gaia) || defined(smb)
virtual bool compareCheckpointVersion(int cp_version, std::function<bool(int, int)> compare_operator) const = 0;
#endif // gaia || smb
protected:
virtual ~I_DetailsResolver() {}
};
#endif // __I_DETAILS_RESOLVER_H__

View File

@@ -0,0 +1,44 @@
// 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 __I_DOWNLOADER_H__
#define __I_DOWNLOADER_H__
#include "i_orchestration_tools.h"
#include "i_update_communication.h"
#include <string>
class I_Downloader
{
public:
virtual Maybe<std::string> downloadFileFromFog(
const std::string &checksum,
Package::ChecksumTypes,
const GetResourceFile &resourse_file
) const = 0;
virtual Maybe<std::map<std::string, std::string>>downloadVirtualFileFromFog(
const GetResourceFile &resourse_file,
Package::ChecksumTypes checksum_type
) const = 0;
virtual Maybe<std::string> downloadFileFromURL(
const std::string &url,
const std::string &checksum,
Package::ChecksumTypes checksum_type,
const std::string &service_name
) const = 0;
};
#endif // __I_DOWNLOADER_H__

View File

@@ -0,0 +1,60 @@
// 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 __I_EXTERNAL_SDK_SERVER_H__
#define __I_EXTERNAL_SDK_SERVER_H__
#include <string>
#include <map>
#include "report/report.h"
#include "debug.h"
class I_ExternalSdkServer
{
public:
virtual void
sendLog(
const std::string &event_name,
ReportIS::Audience audience,
ReportIS::Severity severity,
ReportIS::Priority priority,
const std::string &tag,
const std::map<std::string, std::string> &additional_fields) = 0;
virtual void
sendDebug(
const std::string &file_name,
const std::string &function_name,
unsigned int line_number,
Debug::DebugLevel debug_level,
const std::string &trace_id,
const std::string &span_id,
const std::string &message,
const std::map<std::string, std::string> &additional_fields) = 0;
virtual void
sendMetric(
const std::string &event_title,
const std::string &service_name,
ReportIS::AudienceTeam team,
ReportIS::IssuingEngine issuing_engine,
const std::map<std::string, std::string> &additional_fields) = 0;
virtual Maybe<std::string> getConfigValue(const std::string &config_path) = 0;
protected:
virtual ~I_ExternalSdkServer() {}
};
#endif // __I_EXTERNAL_SDK_SERVER_H__

View File

@@ -0,0 +1,36 @@
// 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 __I_GENERIC_RULEBASE_H__
#define __I_GENERIC_RULEBASE_H__
#include <vector>
#include "generic_rulebase/parameters_config.h"
#include "generic_rulebase/zone.h"
#include "config.h"
class I_GenericRulebase
{
public:
virtual Maybe<Zone, Config::Errors> getLocalZone() const = 0;
virtual Maybe<Zone, Config::Errors> getOtherZone() const = 0;
using ParameterKeyValues = std::unordered_map<std::string, std::set<std::string>>;
virtual std::set<ParameterBehavior> getBehavior(const ParameterKeyValues &key_value_pairs) const = 0;
protected:
~I_GenericRulebase() {}
};
#endif // __I_GENERIC_RULEBASE_H__

View File

@@ -0,0 +1,37 @@
// 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 __I_GRADUAL_DEPLOYMENT_H__
#define __I_GRADUAL_DEPLOYMENT_H__
#include <memory>
#include <vector>
#include <arpa/inet.h>
#include "maybe_res.h"
#include "c_common/ip_common.h"
class I_GradualDeployment
{
public:
enum class AttachmentType { NGINX, KERNEL, COUNT };
virtual Maybe<void> setPolicy(AttachmentType type, const std::vector<std::string> &str_ip_ranges) = 0;
virtual std::vector<std::string> getPolicy(AttachmentType type) = 0;
virtual std::vector<IPRange> & getParsedPolicy(AttachmentType type) = 0;
protected:
virtual ~I_GradualDeployment() {}
};
#endif // __I_GRADUAL_DEPLOYMENT_H__

View File

@@ -0,0 +1,34 @@
// 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 __I_HTTP_MANAGER_H__
#define __I_HTTP_MANAGER_H__
#include "http_inspection_events.h"
class I_HttpManager
{
public:
virtual FilterVerdict inspect(const HttpTransactionData &event) = 0;
virtual FilterVerdict inspect(const HttpHeader &event, bool is_request) = 0;
virtual FilterVerdict inspect(const HttpBody &event, bool is_request) = 0;
virtual FilterVerdict inspect(const ResponseCode &event) = 0;
virtual FilterVerdict inspectEndRequest() = 0;
virtual FilterVerdict inspectEndTransaction() = 0;
virtual FilterVerdict inspectDelayedVerdict() = 0;
protected:
virtual ~I_HttpManager() {}
};
#endif // __I_HTTP_MANAGER_H__

View File

@@ -0,0 +1,27 @@
// 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 __I_K8S_POLICY_GEN_H__
#define __I_K8S_POLICY_GEN_H__
class I_K8S_Policy_Gen
{
public:
virtual std::string parsePolicy(const std::string &policy_version) = 0;
virtual const std::string & getPolicyPath(void) const = 0;
protected:
~I_K8S_Policy_Gen() {}
};
#endif //__I_K8S_POLICY_GEN_H__

View File

@@ -0,0 +1,26 @@
// 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 __I_MANIFEST_CONTROLLER_H__
#define __I_MANIFEST_CONTROLLER_H__
#include <string>
class I_ManifestController
{
public:
virtual bool updateManifest(const std::string &new_manifest_file) = 0;
virtual bool loadAfterSelfUpdate() = 0;
};
#endif // __I_MANIFEST_CONTROLLER_H__

View File

@@ -0,0 +1,87 @@
// 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 __I_ORCHESTRATION_STATUS_H__
#define __I_ORCHESTRATION_STATUS_H__
#include <string>
#include <chrono>
#include <cereal/archives/json.hpp>
#include "enum_array.h"
enum class OrchestrationStatusResult { SUCCESS, FAILED };
enum class OrchestrationStatusFieldType { REGISTRATION, MANIFEST, LAST_UPDATE, COUNT };
enum class OrchestrationStatusConfigType { MANIFEST, POLICY, SETTINGS, DATA, COUNT };
class I_OrchestrationStatus
{
public:
virtual void writeStatusToFile() = 0;
virtual const std::string & getLastUpdateAttempt() const = 0;
virtual const std::string & getUpdateStatus() const = 0;
virtual const std::string & getUpdateTime() const = 0;
virtual const std::string & getLastManifestUpdate() const = 0;
virtual const std::string & getPolicyVersion() const = 0;
virtual const std::string & getLastPolicyUpdate() const = 0;
virtual const std::string & getLastSettingsUpdate() const = 0;
virtual const std::string & getUpgradeMode() const = 0;
virtual const std::string & getFogAddress() const = 0;
virtual const std::string & getRegistrationStatus() const = 0;
virtual const std::string & getAgentId() const = 0;
virtual const std::string & getProfileId() const = 0;
virtual const std::string & getTenantId() const = 0;
virtual const std::string & getManifestStatus() const = 0;
virtual const std::string & getManifestError() const = 0;
virtual const std::map<std::string, std::string> & getServicePolicies() const = 0;
virtual const std::map<std::string, std::string> & getServiceSettings() const = 0;
virtual const std::string getRegistrationDetails() const = 0;
virtual void recoverFields() = 0;
virtual void setIsConfigurationUpdated(EnumArray<OrchestrationStatusConfigType, bool> config_types) = 0;
virtual void setFogAddress(const std::string &_fog_address) = 0;
virtual void setLastUpdateAttempt() = 0;
virtual void setPolicyVersion(const std::string &_policy_version) = 0;
virtual void setRegistrationStatus(const std::string &_reg_status) = 0;
virtual void setUpgradeMode(const std::string &_upgrade_mode) = 0;
virtual void setAgentType(const std::string &_agent_type) = 0;
virtual void setAgentDetails(
const std::string &_agent_id,
const std::string &_profile_id,
const std::string &_tenant_id
) = 0;
virtual void
setFieldStatus(
const OrchestrationStatusFieldType &field_type_status,
const OrchestrationStatusResult &status,
const std::string &failure_reason = ""
) = 0;
virtual void
setRegistrationDetails(
const std::string &name,
const std::string &type,
const std::string &platform,
const std::string &arch
) = 0;
virtual void
setServiceConfiguration(
const std::string &service_name,
const std::string &path,
const OrchestrationStatusConfigType &configuration_file_type
) = 0;
};
#endif // __I_ORCHESTRATION_STATUS_H__

View File

@@ -0,0 +1,125 @@
// 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 __I_ORCHESTRATION_TOOLS_H__
#define __I_ORCHESTRATION_TOOLS_H__
#include "package.h"
#include "debug.h"
#include "maybe_res.h"
#include <fstream>
USE_DEBUG_FLAG(D_ORCHESTRATOR);
class I_OrchestrationTools
{
public:
// Used for the calculation of the manifest and the policy files
static const Package::ChecksumTypes SELECTED_CHECKSUM_TYPE = Package::ChecksumTypes::SHA256;
static constexpr const char * SELECTED_CHECKSUM_TYPE_STR = "sha256sum";
using packageName = std::string;
using packageDetails = std::string;
template<class T>
Maybe<T>
jsonFileToObject(const std::string &file_path) const
{
Maybe<std::string> file_data = readFile(file_path);
if (file_data.ok()) {
return jsonStringToObject<T>(file_data.unpack());
}
return genError(file_data.getErr());
}
template<class T>
Maybe<T>
jsonStringToObject(const std::string &input) const
{
std::stringstream string_stream;
string_stream << input;
return jsonStringToObject<T>(string_stream);
}
template<class T>
Maybe<T>
jsonStringToObject(std::stringstream &string_stream) const
{
try {
cereal::JSONInputArchive archive_in(string_stream);
T object;
object.serialize(archive_in);
return object;
} catch (cereal::Exception &e) {
return genError(e.what());
}
}
template<class T>
bool
objectToJsonFile(T &obj, const std::string &file_path) const
{
try {
std::ofstream ostream(file_path);
cereal::JSONOutputArchive archive_out(ostream);
obj.serialize(archive_out);
} catch (cereal::Exception &e) {
dbgWarning(D_ORCHESTRATOR) << "Failed to write object to JSON file. Object: " << typeid(T).name()
<< ", file : "<< file_path << ", error: " << e.what();
return false;
}
return true;
}
template<class T>
Maybe<std::string>
objectToJson(const T &obj) const
{
std::stringstream sstream;
try {
cereal::JSONOutputArchive archive_out(sstream);
obj.serialize(archive_out);
} catch (cereal::Exception &e) {
std::string error_msg = "Failed to write object to JSON. Object: " + std::string(typeid(T).name())
+ ", error: " + e.what();
return genError(error_msg);
}
return sstream.str();
}
virtual bool packagesToJsonFile(const std::map<packageName, Package> &packages, const std::string &path) const = 0;
virtual Maybe<std::map<packageName, Package>> loadPackagesFromJson(const std::string &path) const = 0;
virtual Maybe<std::map<packageName, packageDetails>> jsonObjectSplitter(
const std::string &json,
const std::string &tenant_id = "") const = 0;
virtual bool isNonEmptyFile(const std::string &path) const = 0;
virtual Maybe<std::string> readFile(const std::string &path) const = 0;
virtual bool writeFile(const std::string &text, const std::string &path) const = 0;
virtual bool removeFile(const std::string &path) const = 0;
virtual bool copyFile(const std::string &src_path, const std::string &dst_path) const = 0;
virtual bool doesFileExist(const std::string &file_path) const = 0;
virtual bool createDirectory(const std::string &directory_path) const = 0;
virtual bool doesDirectoryExist(const std::string &dir_path) const = 0;
virtual bool executeCmd(const std::string &cmd) const = 0;
virtual std::string base64Encode(const std::string &input) const = 0;
virtual std::string base64Decode(const std::string &input) const = 0;
virtual Maybe<std::string> calculateChecksum(
Package::ChecksumTypes checksum_type,
const std::string &path) const = 0;
};
#endif // __I_ORCHESTRATION_TOOLS_H__

View File

@@ -0,0 +1,47 @@
// 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 __I_PACKAGE_HANDLER_H__
#define __I_PACKAGE_HANDLER_H__
#include <string>
class I_PackageHandler
{
public:
virtual bool shouldInstallPackage(const std::string &package_name, const std::string &install_file_path) const = 0;
virtual bool installPackage(
const std::string &package_name,
const std::string &install_file_path,
bool restore_mode
) const = 0;
virtual bool uninstallPackage(
const std::string &package_name,
const std::string &package_path,
const std::string &install_file_path
) const = 0;
virtual bool preInstallPackage(
const std::string &package_name,
const std::string &install_file_path
) const = 0;
virtual bool postInstallPackage(
const std::string &package_name,
const std::string &install_file_path
) const = 0;
virtual bool updateSavedPackage(
const std::string &package_name,
const std::string &install_file_path
) const = 0;
};
#endif // __I_PACKAGE_HANDLER_H__

67
components/include/i_pm_scan.h Executable file
View File

@@ -0,0 +1,67 @@
// 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 __I_PM_SCAN_H__
#define __I_PM_SCAN_H__
#include <sys/types.h>
#include <set>
#include <iostream>
#include <functional>
#include "buffer.h"
#include "maybe_res.h"
class PMPattern
{
public:
PMPattern() {}
PMPattern(const std::string &pat, bool start, bool end, uint index = 0)
:
pattern(pat),
match_start(start),
match_end(end),
index(index)
{}
bool operator<(const PMPattern &other) const;
bool operator==(const PMPattern &other) const;
bool isStartMatch() const { return match_start; }
bool isEndMatch() const { return match_end; }
const unsigned char * data() const { return reinterpret_cast<const unsigned char *>(pattern.data()); }
size_t size() const { return pattern.size(); }
bool empty() const { return pattern.empty(); }
uint getIndex() const { return index; }
private:
std::string pattern;
bool match_start = false;
bool match_end = false;
uint index;
};
class I_PMScan
{
public:
using CBFunction = std::function<void(uint, const PMPattern &)>;
virtual std::set<PMPattern> scanBuf(const Buffer &buf) const = 0;
virtual std::set<std::pair<uint, PMPattern>> scanBufWithOffset(const Buffer &buf) const = 0;
virtual void scanBufWithOffsetLambda(const Buffer &buf, CBFunction cb) const = 0;
protected:
~I_PMScan() {}
};
#endif // __I_PM_SCAN_H__

View File

@@ -0,0 +1,62 @@
// 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 __I_SERVICE_CONTROLLER_H__
#define __I_SERVICE_CONTROLLER_H__
#include <string>
#include <vector>
#include <map>
#include "connkey.h"
#include "rest.h"
enum class ReconfStatus { SUCCEEDED, IN_PROGRESS, FAILED, INACTIVE };
class I_ServiceController
{
public:
virtual const std::string & getPolicyVersion() const = 0;
virtual const std::string & getUpdatePolicyVersion() const = 0;
virtual void updateReconfStatus(int id, ReconfStatus status) = 0;
virtual void startReconfStatus(
int id,
ReconfStatus status,
const std::string &service_name,
const std::string &service_id
) = 0;
virtual bool
updateServiceConfiguration(
const std::string &new_policy_path,
const std::string &new_settings_path,
const std::vector<std::string> &new_data_files = {},
const std::string &tenant_id = ""
) = 0;
virtual bool isServiceInstalled(const std::string &service_name) = 0;
virtual void registerServiceConfig(
const std::string &service_name,
PortNumber listening_port,
const std::vector<std::string> &expected_configurations,
const std::string &service_id
) = 0;
virtual std::map<std::string, PortNumber> getServiceToPortMap() = 0;
protected:
virtual ~I_ServiceController() {}
};
#endif // __I_SERVICE_CONTROLLER_H__

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 __I_STATIC_RESOURCES_HANDLER_H__
#define __I_STATIC_RESOURCES_HANDLER_H__
#include <memory>
#include "maybe_res.h"
class I_StaticResourcesHandler
{
public:
virtual bool registerStaticResource(const std::string &resource_name, const std::string &resource_full_path) = 0;
protected:
virtual ~I_StaticResourcesHandler() {}
};
#endif // __I_STATIC_RESOURCES_HANDLER_H__

View File

@@ -0,0 +1,36 @@
// 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 __I_UPDATE_COMMUNICATION_H__
#define __I_UPDATE_COMMUNICATION_H__
#include "maybe_res.h"
#include "orchestrator/rest_api/get_resource_file.h"
#include "orchestrator/rest_api/orchestration_check_update.h"
using OrchManifest = Maybe<std::string>;
using OrchPolicy = Maybe<std::string>;
using OrchSettings = Maybe<std::string>;
using OrchData = Maybe<std::string>;
class I_UpdateCommunication
{
public:
virtual Maybe<void> authenticateAgent() = 0;
virtual Maybe<void> getUpdate(CheckUpdateRequest &request) = 0;
virtual Maybe<void> sendPolicyVersion(const std::string &policy_version) const = 0;
virtual Maybe<std::string> downloadAttributeFile(const GetResourceFile &resourse_file) = 0;
virtual void setAddressExtenesion(const std::string &extension) = 0;
};
#endif // __I_UPDATE_COMMUNICATION_H__

View File

@@ -0,0 +1,46 @@
// 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.
#pragma once
#include "WaapEnums.h"
struct DecisionTelemetryData
{
BlockType blockType;
ThreatLevel threat;
std::string assetName;
std::string practiceId;
std::string practiceName;
std::string source;
std::set<std::string> attackTypes;
DecisionTelemetryData() :
blockType(NOT_BLOCKING),
threat(NO_THREAT),
assetName(),
practiceId(),
practiceName(),
source(),
attackTypes()
{
}
};
class I_Telemetry
{
public:
virtual void logDecision(std::string assetId, DecisionTelemetryData& data) = 0;
protected:
virtual ~I_Telemetry() {}
};

108
components/include/ip_utilities.h Executable file
View File

@@ -0,0 +1,108 @@
// 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 __IP_UTILITIES_H__
#define __IP_UTILITIES_H__
#include <map>
#include <sys/types.h>
#include <ifaddrs.h>
#include <string.h>
#include <vector>
#include <arpa/inet.h>
#include "c_common/ip_common.h"
#include "common.h"
#include "maybe_res.h"
#include "debug.h"
// LCOV_EXCL_START Reason: temporary until we add relevant UT until 07/10
bool operator<(const IpAddress &this_ip_addr, const IpAddress &other_ip_addr);
bool operator==(const IpAddress &this_ip_addr, const IpAddress &other_ip_addr);
// LCOV_EXCL_STOP
Maybe<std::pair<std::string, int>> extractAddressAndMaskSize(const std::string &cidr);
template<typename Integer>
std::pair<Integer, Integer> applyMaskOnAddress(const std::vector<Integer> &oct, Integer mask);
Maybe<std::pair<std::string, std::string>> createRangeFromCidrV4(const std::pair<std::string, int> &cidr_values);
Maybe<std::pair<std::string, std::string>> createRangeFromCidrV6(const std::pair<std::string, int> &cidr_values);
namespace IPUtilities {
Maybe<std::map<IpAddress, std::string>> getInterfaceIPs();
Maybe<std::pair<std::string, std::string>> createRangeFromCidr(const std::string &cidr);
bool isIpAddrInRange(const IPRange &rule_ip_range, const IpAddress &ip_addr);
std::string IpAddrToString(const IpAddress &address);
IpAddress createIpFromString(const std::string &ip_string);
template <typename Range, typename Type>
Maybe<Range> createRangeFromString(const std::string &range, const std::string &type_name);
using IpProto = uint8_t;
using Port = uint16_t;
class IpAttrFromString
{
public:
IpAttrFromString(const std::string &in_data) : data(in_data) {}
operator Maybe<IpAddress>();
operator Maybe<IpProto>();
operator Maybe<Port>();
private:
std::string data;
};
template <typename Range, typename Type>
Maybe<Range>
createRangeFromString(const std::string &range, const std::string &type_name)
{
std::string range_start;
std::string range_end;
size_t delimiter_pos = range.find("/");
if (delimiter_pos != std::string::npos) {
auto cidr = IPUtilities::createRangeFromCidr(range);
if (!cidr.ok()) return genError("Couldn't create ip range from CIDR, error: " + cidr.getErr());
range_start = cidr.unpack().first;
range_end = cidr.unpack().second;
} else {
delimiter_pos = range.find("-");
range_start = range.substr(0, delimiter_pos);
range_end = delimiter_pos == std::string::npos ? range_start : range.substr(delimiter_pos + 1);
}
Maybe<Type> range_start_value = IpAttrFromString(range_start);
if (!range_start_value.ok()) {
return genError("provided value is not a legal " + type_name + ". Provided value: " + range_start);
}
Maybe<Type> range_end_value = IpAttrFromString(range_end);
if (!range_end_value.ok()) {
return genError("provided value is not a legal " + type_name + ". Provided value: " + range_end);
}
if (*range_end_value < *range_start_value) {
return genError("Could not create " + type_name + "range. Error: start value is greater than end value");
}
return Range{.start = *range_start_value, .end = *range_end_value};
}
}
#endif // __IP_UTILITIES_H__

View File

@@ -0,0 +1,44 @@
// 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 __K8S_POLICY_GEN_H__
#define __K8S_POLICY_GEN_H__
#include "config.h"
#include "component.h"
#include "i_mainloop.h"
#include "i_environment.h"
#include "i_k8s_policy_gen.h"
class K8sPolicyGenerator
:
public Component,
Singleton::Provide<I_K8S_Policy_Gen>,
Singleton::Consume<Config::I_Config>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Environment>
{
public:
K8sPolicyGenerator();
~K8sPolicyGenerator();
void preload() override;
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __K8S_POLICY_GEN_H__

View File

@@ -0,0 +1,53 @@
// 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 __MANIFEST_CONTROLLER_H__
#define __MANIFEST_CONTROLLER_H__
#include "i_manifest_controller.h"
#include <set>
#include "i_orchestration_tools.h"
#include "i_package_handler.h"
#include "i_downloader.h"
#include "manifest_diff_calculator.h"
#include "manifest_handler.h"
#include "i_orchestration_status.h"
#include "i_environment.h"
#include "i_shell_cmd.h"
#include "component.h"
class ManifestController
:
public Component,
Singleton::Provide<I_ManifestController>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_PackageHandler>,
Singleton::Consume<I_Downloader>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_OrchestrationStatus>
{
public:
ManifestController();
~ManifestController();
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __MANIFEST_CONTROLLER_H__

View File

@@ -0,0 +1,50 @@
// 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 __MANIFEST_DIFF_CALCULATOR_H__
#define __MANIFEST_DIFF_CALCULATOR_H__
#include "package.h"
#include "i_orchestration_tools.h"
class ManifestDiffCalculator : Singleton::Consume<I_OrchestrationTools>
{
public:
ManifestDiffCalculator() = default;
void init();
std::map<std::string, Package>
filterUntrackedPackages(
const std::map<std::string, Package> &current_packages,
std::map<std::string, Package> &new_packages
);
bool
filterCorruptedPackages(
std::map<std::string, Package> &new_packages,
std::map<std::string, Package> &corrupted_packages
);
bool
buildInstallationQueue(
const Package &updated_package,
std::vector<Package> &installation_queue,
const std::map<std::string, Package> &current_packages,
const std::map<std::string, Package> &new_packages
);
private:
std::string corrupted_file_path;
};
#endif // __MANIFEST_DIFF_CALCULATOR_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.
#ifndef __MANIFEST_HANDLER_H__
#define __MANIFEST_HANDLER_H__
#include "package.h"
#include "i_package_handler.h"
#include "i_downloader.h"
#include "i_orchestration_tools.h"
#include "i_orchestration_status.h"
#include "i_environment.h"
#include "i_agent_details.h"
#include "i_details_resolver.h"
#include "i_time_get.h"
class ManifestHandler
:
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_PackageHandler>,
Singleton::Consume<I_Downloader>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_OrchestrationStatus>,
Singleton::Consume<I_DetailsResolver>
{
public:
using packageFilePath = std::string;
ManifestHandler() = default;
void init();
bool
downloadPackages(
const std::vector<Package> &updated_packages,
std::vector<std::pair<Package, packageFilePath>> &downloaded_packages
);
bool
installPackages(
const std::vector<std::pair<Package, packageFilePath>> &downloaded_packages_files,
std::map<packageFilePath, Package> &current_packages,
std::map<packageFilePath, Package> &corrupted_packages
);
bool uninstallPackage(Package &removed_package);
bool
selfUpdate(
const Package &updated_package,
std::map<packageFilePath, Package> &current_packages,
const packageFilePath &installation_file
);
private:
Maybe<std::string> downloadPackage(const Package &package, bool is_clean_installation);
std::string manifest_file_path;
std::string temp_ext;
std::string backup_ext;
std::string packages_dir;
std::string orch_service_name;
std::string default_dir;
};
#endif // __MANIFEST_HANDLER_H__

View File

@@ -0,0 +1,49 @@
// 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 __MESSAGING_DOWNLOADER_H__
#define __MESSAGING_DOWNLOADER_H__
#include "i_messaging_downloader.h"
#include "i_messaging.h"
#include "i_rest_api.h"
#include "i_mainloop.h"
#include "i_environment.h"
#include "component.h"
USE_DEBUG_FLAG(D_COMMUNICATION);
class MessagingDownloaderClient
:
public Component,
Singleton::Provide<I_MessagingDownloader>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Environment>
{
public:
MessagingDownloaderClient();
~MessagingDownloaderClient();
void preload() override;
void init() override;
void fini() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __MESSAGING_DOWNLOADER_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 __MESSAGING_DOWNLOADER_SERVER_H__
#define __MESSAGING_DOWNLOADER_SERVER_H__
#include "i_messaging_downloader.h"
#include "i_messaging.h"
#include "i_rest_api.h"
#include "i_mainloop.h"
#include "i_environment.h"
#include "i_agent_details.h"
#include "component.h"
USE_DEBUG_FLAG(D_COMMUNICATION);
class MessagingDownloaderServer
:
public Component,
Singleton::Provide<I_MessagingDownloader>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_AgentDetails>
{
public:
MessagingDownloaderServer();
~MessagingDownloaderServer();
void init();
void fini();
void preload();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __MESSAGING_DOWNLOADER_SERVER_H__

View File

@@ -0,0 +1,16 @@
#ifndef __MOCK_NGINX_ATTACHMENT_H__
#define __MOCK_NGINX_ATTACHMENT_H__
#include "nginx_attachment.h"
class MockNginxAttachment:
public Singleton::Provide<I_StaticResourcesHandler>::From<MockProvider<I_StaticResourcesHandler>>
{
public:
MOCK_METHOD2(
registerStaticResource,
bool(const std::string &static_resource_name, const std::string &static_resource_path)
);
};
#endif // __MOCK_NGINX_ATTACHMENT_H__

View File

@@ -0,0 +1,57 @@
// 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_ATTACHMENT_H__
#define __NGINX_ATTACHMENT_H__
#include "singleton.h"
#include "i_mainloop.h"
#include "i_table.h"
#include "i_gradual_deployment.h"
#include "i_http_manager.h"
#include "i_static_resources_handler.h"
#include "i_socket_is.h"
#include "transaction_table_metric.h"
#include "nginx_attachment_metric.h"
#include "nginx_intaker_metric.h"
#include "component.h"
using SessionID = uint32_t;
class NginxAttachment
:
public Component,
Singleton::Provide<I_StaticResourcesHandler>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_GradualDeployment>,
Singleton::Consume<I_TableSpecific<SessionID>>,
Singleton::Consume<I_HttpManager>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_Socket>,
Singleton::Consume<I_InstanceAwareness>
{
public:
NginxAttachment();
~NginxAttachment();
void preload();
void init();
void fini();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __NGINX_ATTACHMENT_H__

View File

@@ -0,0 +1,87 @@
// 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_ATTACHMENT_METRIC_H__
#define __NGINX_ATTACHMENT_METRIC_H__
#include "generic_metric.h"
class nginxAttachmentEvent : public Event<nginxAttachmentEvent>
{
public:
enum class networkVerdict {
REGISTRATION_SUCCESS,
REGISTRATION_FAIL,
CONNECTION_FAIL
};
enum class trafficVerdict {
INSPECT,
ACCEPT,
DROP,
INJECT,
IRRELEVANT,
RECONF,
WAIT
};
void resetAllCounters();
void addNetworkingCounter(networkVerdict _verdict);
void addTrafficVerdictCounter(trafficVerdict _verdict);
void addResponseInspectionCounter(uint64_t _counter);
uint64_t getNetworkingCounter(networkVerdict _verdict) const;
uint64_t getTrafficVerdictCounter(trafficVerdict _verdict) const;
uint64_t getResponseInspectionCounter() const;
private:
uint64_t successfull_registrations_counter = 0;
uint64_t failed_registrations_counter = 0;
uint64_t failed_connections_counter = 0;
uint64_t accept_verdict_counter = 0;
uint64_t inspect_verdict_counter = 0;
uint64_t drop_verdict_counter = 0;
uint64_t inject_verdict_counter = 0;
uint64_t irrelevant_verdict_counter = 0;
uint64_t reconf_verdict_counter = 0;
uint64_t response_inspection_counter = 0;
uint64_t wait_verdict_counter = 0;
};
class nginxAttachmentMetric
:
public GenericMetric,
public Listener<nginxAttachmentEvent>
{
public:
void upon(const nginxAttachmentEvent &event) override;
private:
MetricCalculations::Counter successfull_registrations{this, "successfullRegistrationsSum"};
MetricCalculations::Counter failed_registrations{this, "failedRegistrationsSum"};
MetricCalculations::Counter failed_connections{this, "failedConnectionsSum"};
MetricCalculations::Counter inspect_verdict{this, "inspectVerdictSum"};
MetricCalculations::Counter accept_verdict{this, "acceptVeridctSum"};
MetricCalculations::Counter drop_verdict{this, "dropVerdictSum"};
MetricCalculations::Counter inject_verdict{this, "injectVerdictSum"};
MetricCalculations::Counter irrelevant_verdict{this, "irrelevantVerdictSum"};
MetricCalculations::Counter reconf_verdict{this, "reconfVerdictSum"};
MetricCalculations::Counter response_inspection{this, "responseInspection"};
};
#endif // __NGINX_ATTACHMENT_METRIC_H__

View File

@@ -0,0 +1,146 @@
// 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_INTAKER_METRIC_H__
#define __NGINX_INTAKER_METRIC_H__
#include "nginx_attachment_common.h"
#include "generic_metric.h"
#include "cpu/cpu_metric.h"
class nginxIntakerEvent : public Event<nginxIntakerEvent>
{
public:
nginxIntakerEvent() : cpu_event(0, true) {}
void resetAllCounters();
ngx_http_plugin_metric_type_e EnumOfIndex(int i);
void addPluginMetricCounter(const ngx_http_cp_metric_data_t *recieved_metric_data);
uint64_t getPluginMetricCounter(ngx_http_plugin_metric_type_e _verdict) const;
void notifyCPU() const { cpu_event.notify(); }
private:
uint64_t successfull_inspection_counter = 0;
uint64_t open_failure_inspection_counter = 0;
uint64_t close_failure_inspection_counter = 0;
uint64_t transparent_mode_counter = 0;
uint64_t total_transparent_time = 0;
uint64_t accept_verdict_counter = 0;
uint64_t inspect_verdict_counter = 0;
uint64_t drop_verdict_counter = 0;
uint64_t inject_verdict_counter = 0;
uint64_t irrelevant_verdict_counter = 0;
uint64_t reconf_verdict_counter = 0;
uint64_t wait_verdict_counter = 0;
uint64_t average_overall_processing_time_until_verdict = 0;
uint64_t max_overall_processing_time_until_verdict = 0;
uint64_t min_overall_processing_time_until_verdict = 0;
uint64_t average_req_processing_time_until_verdict = 0;
uint64_t max_req_processing_time_until_verdict = 0;
uint64_t min_req_processing_time_until_verdict = 0;
uint64_t average_res_processing_time_until_verdict = 0;
uint64_t max_res_processing_time_until_verdict = 0;
uint64_t min_res_processing_time_until_verdict = 0;
uint64_t req_failed_compression_counter = 0;
uint64_t res_failed_compression_counter = 0;
uint64_t req_failed_decompression_counter = 0;
uint64_t res_failed_decompression_counter = 0;
uint64_t req_successful_compression_counter = 0;
uint64_t res_successful_compression_counter = 0;
uint64_t req_successful_decompression_counter = 0;
uint64_t res_successful_decompression_counter = 0;
uint64_t corrupted_zip_skipped_session_counter = 0;
uint64_t thread_timeout = 0;
uint64_t reg_thread_timeout = 0;
uint64_t req_header_thread_timeout = 0;
uint64_t req_body_thread_timeout = 0;
uint64_t average_req_body_size_upon_timeout = 0;
uint64_t max_req_body_size_upon_timeout = 0;
uint64_t min_req_body_size_upon_timeout = 0;
uint64_t res_header_thread_timeout = 0;
uint64_t res_body_thread_timeout = 0;
uint64_t average_res_body_size_upon_timeout = 0;
uint64_t max_res_body_size_upon_timeout = 0;
uint64_t min_res_body_size_upon_timeout = 0;
uint64_t thread_failure = 0;
uint64_t req_proccessing_timeout = 0;
uint64_t res_proccessing_timeout = 0;
uint64_t req_failed_to_reach_upstream = 0;
CPUEvent cpu_event;
};
class nginxIntakerMetric
:
public GenericMetric,
public Listener<nginxIntakerEvent>
{
public:
void upon(const nginxIntakerEvent &event) override;
private:
using Counter = MetricCalculations::Counter;
using LastValue = MetricCalculations::LastReportedValue<uint64_t>;
Counter successfull_inspection_counter{this, "successfullInspectionTransactionsSum"};
Counter open_failure_inspection_counter{this, "failopenTransactionsSum"};
Counter close_failure_inspection_counter{this, "failcloseTransactionsSum"};
Counter transparent_mode_counter{this, "transparentModeTransactionsSum"};
Counter total_transparent_time{this, "totalTimeInTransparentModeSum"};
Counter inspect_verdict_counter{this, "reachInspectVerdictSum"};
Counter accept_verdict_counter{this, "reachAcceptVerdictSum"};
Counter drop_verdict_counter{this, "reachDropVerdictSum"};
Counter inject_verdict_counter{this, "reachInjectVerdictSum"};
Counter irrelevant_verdict_counter{this, "reachIrrelevantVerdictSum"};
Counter reconf_verdict_counter{this, "reachReconfVerdictSum"};
LastValue average_overall_processing_time_until_verdict{this, "overallSessionProcessTimeToVerdictAvgSample"};
LastValue max_overall_processing_time_until_verdict{this, "overallSessionProcessTimeToVerdictMaxSample"};
LastValue min_overall_processing_time_until_verdict{this, "overallSessionProcessTimeToVerdictMinSample"};
LastValue average_req_processing_time_until_verdict{this, "requestProcessTimeToVerdictAvgSample"};
LastValue max_req_processing_time_until_verdict{this, "requestProcessTimeToVerdictMaxSample"};
LastValue min_req_processing_time_until_verdict{this, "requestProcessTimeToVerdictMinSample"};
LastValue average_res_processing_time_until_verdict{this, "responseProcessTimeToVerdictAvgSample"};
LastValue max_res_processing_time_until_verdict{this, "responseProcessTimeToVerdictMaxSample"};
LastValue min_res_processing_time_until_verdict{this, "responseProcessTimeToVerdictMinSample"};
Counter req_failed_compression_counter{this, "requestCompressionFailureSum"};
Counter res_failed_compression_counter{this, "responseCompressionFailureSum"};
Counter req_failed_decompression_counter{this, "requestDecompressionFailureSum"};
Counter res_failed_decompression_counter{this, "responseDecompressionFailureSum"};
Counter req_successful_compression_counter{this, "requestCompressionSuccessSum"};
Counter res_successful_compression_counter{this, "responseCompressionSuccessSum"};
Counter req_successful_decompression_counter{this, "requestDecompressionSuccessSum"};
Counter res_successful_decompression_counter{this, "responseDecompressionSuccessSum"};
Counter corrupted_zip_skipped_session_counter{this, "skippedSessionsUponCorruptedZipSum"};
Counter thread_timeout{this, "attachmentThreadReachedTimeoutSum"};
Counter reg_thread_timeout{this, "registrationThreadReachedTimeoutSum"};
Counter req_header_thread_timeout{this, "requestHeaderThreadReachedTimeoutSum"};
Counter req_body_thread_timeout{this, "requestBodyThreadReachedTimeoutSum"};
LastValue average_req_body_size_upon_timeout{this, "requestBodySizeUponTimeoutAvgSample"};
LastValue max_req_body_size_upon_timeout{this, "requestBodySizeUponTimeoutMaxSample"};
LastValue min_req_body_size_upon_timeout{this, "requestBodySizeUponTimeoutMinSample"};
Counter res_header_thread_timeout{this, "respondHeaderThreadReachedTimeoutSum"};
Counter res_body_thread_timeout{this, "respondBodyThreadReachedTimeoutSum"};
LastValue average_res_body_size_upon_timeout{this, "responseBodySizeUponTimeoutAvgSample"};
LastValue max_res_body_size_upon_timeout{this, "responseBodySizeUponTimeoutMaxSample"};
LastValue min_res_body_size_upon_timeout{this, "responseBodySizeUponTimeoutMinSample"};
Counter thread_failure{this, "attachmentThreadFailureSum"};
Counter req_proccessing_timeout{this, "httpRequestProcessingReachedTimeoutSum"};
Counter res_proccessing_timeout{this, "httpResponseProcessingReachedTimeoutSum"};
Counter req_failed_to_reach_upstream{this, "httpRequestFailedToReachWebServerUpstreamSum"};
};
#endif // __NGINX_INTAKER_METRIC_H__

View File

@@ -0,0 +1,73 @@
// 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 __ORCHESTRATION_COMP_H__
#define __ORCHESTRATION_COMP_H__
#include "i_messaging_downloader.h"
#include "i_messaging.h"
#include "i_mainloop.h"
#include "i_shell_cmd.h"
#include "i_encryptor.h"
#include "i_orchestration_status.h"
#include "i_rest_api.h"
#include "i_orchestration_tools.h"
#include "i_downloader.h"
#include "i_service_controller.h"
#include "i_manifest_controller.h"
#include "i_update_communication.h"
#include "i_details_resolver.h"
#include "i_shell_cmd.h"
#include "i_agent_details.h"
#include "i_environment.h"
#include "i_tenant_manager.h"
#include "i_package_handler.h"
#include "component.h"
class OrchestrationComp
:
public Component,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_OrchestrationStatus>,
Singleton::Consume<I_Encryptor>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_DetailsResolver>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_TenantManager>,
Singleton::Consume<I_MessagingDownloader>,
Singleton::Consume<I_PackageHandler>,
Singleton::Consume<I_ServiceController>,
Singleton::Consume<I_UpdateCommunication>,
Singleton::Consume<I_Downloader>,
Singleton::Consume<I_ManifestController>
{
public:
OrchestrationComp();
~OrchestrationComp();
void preload() override;
void init() override;
void fini() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __ORCHESTRATION_COMP_H__

View File

@@ -0,0 +1,49 @@
// 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 __ORCHESTRATION_STATUS_H__
#define __ORCHESTRATION_STATUS_H__
#include "i_orchestration_status.h"
#include <cereal/archives/json.hpp>
#include "singleton.h"
#include "component.h"
#include "i_orchestration_tools.h"
#include "i_time_get.h"
#include "i_mainloop.h"
#include "i_agent_details.h"
#include "customized_cereal_map.h"
class OrchestrationStatus
:
public Component,
Singleton::Provide<I_OrchestrationStatus>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_MainLoop>
{
public:
OrchestrationStatus();
~OrchestrationStatus();
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __ORCHESTRATION_STATUS_H__

View File

@@ -0,0 +1,33 @@
// 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 __ORCHESTRATION_TOOLS_H__
#define __ORCHESTRATION_TOOLS_H__
#include <fstream>
#include "i_orchestration_tools.h"
#include "component.h"
class OrchestrationTools : public Component, Singleton::Provide<I_OrchestrationTools>
{
public:
OrchestrationTools();
~OrchestrationTools();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __ORCHESTRATION_TOOLS_H__

View File

@@ -0,0 +1,46 @@
// 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 __DATA_H__
#define __DATA_H__
#include <string>
#include <map>
#include "cereal/archives/json.hpp"
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "debug.h"
#include "maybe_res.h"
class Data
{
public:
enum class ChecksumTypes { SHA1, SHA256, SHA512, MD5 };
const std::string & getDownloadPath() const { return download_path; }
const std::string & getVersion() const { return version; }
const std::string & getChecksum() const { return checksum_value; }
const ChecksumTypes & getChecksumType() const { return checksum_type; }
void serialize(cereal::JSONInputArchive & in_archive);
private:
ChecksumTypes checksum_type = ChecksumTypes::SHA256;
std::string version;
std::string download_path;
std::string checksum_value;
};
#endif // __DATA_H__

View File

@@ -0,0 +1,123 @@
// 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 __GET_RESOURCE_FILE_H__
#define __GET_RESOURCE_FILE_H__
#include <string>
#include "rest.h"
#include "i_messaging.h"
class GetResourceFile : public ClientRest
{
class TenantResource : public ClientRest
{
public:
TenantResource(const std::string &_tenant_id, const std::string &_version, const std::string &_checksum)
:
tenant_id(_tenant_id),
version(_version),
checksum(_checksum)
{
}
bool
operator==(const TenantResource &other) const
{
return
tenant_id.get() == other.tenant_id.get() &&
version.get() == other.version.get() &&
checksum.get() == other.checksum.get();
}
C2S_LABEL_PARAM(std::string, tenant_id, "tenantId");
C2S_LABEL_PARAM(std::string, version, "version");
C2S_LABEL_PARAM(std::string, checksum, "checksum");
};
public:
enum class ResourceFileType {
MANIFEST,
POLICY,
SETTINGS,
DATA,
VIRTUAL_SETTINGS,
VIRTUAL_POLICY,
COUNT
};
GetResourceFile() = default;
GetResourceFile(const ResourceFileType _file_type)
:
file_type(_file_type)
{
}
bool
operator==(const GetResourceFile &other) const
{
if (file_type != other.file_type) return false;
if (tenants.isActive() && other.tenants.isActive()) return tenants.get() == other.tenants.get();
return (!tenants.isActive() && !other.tenants.isActive());
}
void
addTenant(const std::string &tenant_id, const std::string &version, const std::string &checksum)
{
if (!isVirtual()) return;
if (!tenants.isActive()) tenants = std::vector<TenantResource>();
tenants.get().emplace_back(tenant_id, version, checksum);
}
std::string
getFileName() const
{
switch (file_type)
{
case ResourceFileType::MANIFEST: return "manifest";
case ResourceFileType::POLICY: return "policy";
case ResourceFileType::SETTINGS: return "settings";
case ResourceFileType::DATA: return "data";
case ResourceFileType::VIRTUAL_SETTINGS: return "virtualSettings";
case ResourceFileType::VIRTUAL_POLICY: return "virtualPolicy";
default:
dbgAssert(false) << "Unknown file type";
}
return std::string();
}
I_Messaging::Method
getRequestMethod() const
{
return isVirtual() ? I_Messaging::Method::POST : I_Messaging::Method::GET;
}
private:
bool
isVirtual() const
{
return
file_type == ResourceFileType::VIRTUAL_SETTINGS ||
file_type == ResourceFileType::VIRTUAL_POLICY;
}
C2S_LABEL_OPTIONAL_PARAM(std::vector<TenantResource>, tenants, "tenants");
ResourceFileType file_type;
};
#endif // __GET_RESOURCE_FILE_H__

View File

@@ -0,0 +1,182 @@
// 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 __ORCHESTRATION_CHECK_UPDATE_H__
#define __ORCHESTRATION_CHECK_UPDATE_H__
#include <string>
#include "rest.h"
#include "maybe_res.h"
class CheckUpdateRequest : public ClientRest
{
public:
class Tenants : public ClientRest
{
public:
Tenants() = default;
Tenants(const Tenants &other)
{
tenant_id = other.tenant_id;
checksum = other.checksum;
version = other.version;
}
Tenants(const std::string &_tenant_id, const std::string &_checksum, const std::string &_version)
:
tenant_id(_tenant_id),
checksum(_checksum),
version(_version)
{
}
bool
operator==(const Tenants &other) const
{
return
tenant_id.get() == other.tenant_id.get() &&
checksum.get() == other.checksum.get() &&
version.get() == other.version.get();
}
const std::string & getTenantID() const { return tenant_id.get(); }
const std::string & getChecksum() const { return checksum.get(); }
const std::string & getVersion() const { return version.get(); }
private:
BOTH_LABEL_PARAM(std::string, tenant_id, "tenantId");
BOTH_LABEL_PARAM(std::string, checksum, "checksum");
BOTH_LABEL_PARAM(std::string, version, "version");
};
CheckUpdateRequest(
const std::string &_manifest,
const std::string &_policy,
const std::string &_settings,
const std::string &_data,
const std::string &_checksum_type,
const std::string &_policy_version)
:
manifest(_manifest),
policy(_policy),
settings(_settings),
data(_data),
checksum_type(_checksum_type),
policy_version(_policy_version)
{
out_virtual_policy.setActive(true);
out_virtual_settings.setActive(true);
}
Maybe<std::string>
getManifest() const
{
if (manifest.get().empty()) return genError("No manifest");
return manifest.get();
}
Maybe<std::string>
getPolicy() const
{
if (policy.get().empty()) return genError("No policy");
return policy.get();
}
Maybe<std::string>
getSettings() const
{
if (settings.get().empty()) return genError("No settings");
return settings.get();
}
Maybe<std::string>
getData() const
{
if (data.get().empty()) return genError("No data");
return data.get();
}
Maybe<std::vector<Tenants>>
getVirtualPolicy() const
{
if (!in_virtual_policy.isActive()) return genError("no virtual policy is found");
return in_virtual_policy.get().getTenants();
}
Maybe<std::vector<Tenants>>
getVirtualSettings() const
{
if (!in_virtual_settings.isActive()) return genError("no virtual settings are found");
return in_virtual_settings.get().getTenants();
}
template <typename ...Args>
void
addTenantPolicy(Args ...args)
{
if (!out_virtual_policy.isActive()) out_virtual_policy.setActive(true);
out_virtual_policy.get().addTenant(std::forward<Args>(args)...);
}
template <typename ...Args>
void
addTenantSettings(Args ...args)
{
if (!out_virtual_settings.isActive()) out_virtual_settings.setActive(true);
out_virtual_settings.get().addTenant(std::forward<Args>(args)...);
}
void setGreedyMode() { check_all_tenants = true; }
private:
class VirtualConfig : public ClientRest
{
public:
VirtualConfig()
{
tenants.setActive(true);
}
template <typename ...Args>
void
addTenant(Args ...args)
{
if (!tenants.isActive()) tenants.setActive(true);
tenants.get().emplace_back(std::forward<Args>(args)...);
}
const std::vector<Tenants> & getTenants() const { return tenants.get(); }
private:
BOTH_LABEL_PARAM(std::vector<Tenants>, tenants, "tenants");
};
BOTH_LABEL_PARAM(std::string, manifest, "manifest");
BOTH_LABEL_PARAM(std::string, policy, "policy");
BOTH_LABEL_PARAM(std::string, settings, "settings");
BOTH_LABEL_OPTIONAL_PARAM(std::string, data, "data");
C2S_LABEL_OPTIONAL_PARAM(VirtualConfig, out_virtual_settings, "virtualSettings");
C2S_LABEL_OPTIONAL_PARAM(VirtualConfig, out_virtual_policy, "virtualPolicy");
BOTH_LABEL_OPTIONAL_PARAM(bool, check_all_tenants, "checkForAllTenants");
C2S_LABEL_PARAM(std::string, checksum_type, "checksum-type");
C2S_LABEL_PARAM(std::string, policy_version, "policyVersion");
S2C_LABEL_OPTIONAL_PARAM(VirtualConfig, in_virtual_policy, "virtualPolicy");
S2C_LABEL_OPTIONAL_PARAM(VirtualConfig, in_virtual_settings, "virtualSettings");
};
#endif // __ORCHESTRATION_CHECK_UPDATE_H__

75
components/include/package.h Executable file
View File

@@ -0,0 +1,75 @@
// 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 __PACKAGE_H__
#define __PACKAGE_H__
#include <string>
#include <map>
#include "cereal/archives/json.hpp"
#include "cereal/types/string.hpp"
#include "cereal/types/vector.hpp"
#include "debug.h"
#include "maybe_res.h"
class Package
{
public:
enum class ChecksumTypes { SHA1, SHA256, SHA512, MD5 };
enum class PackageType { Service, SharedObject };
const std::string & getDownloadPath() const { return download_path; }
const std::string & getRelativeDownloadPath() const { return relative_path; }
const std::string & getName() const { return name; }
const std::string & getVersion() const { return version; }
const std::string & getChecksum() const { return checksum_value; }
const PackageType & getType() const { return package_type; }
const std::vector<std::string> & getRequire() const { return require_packages; }
const ChecksumTypes & getChecksumType() const { return checksum_type; }
const Maybe<void> & isInstallable() const { return installable; }
bool operator==(const Package &other) const;
bool operator!=(const Package &other) const;
void serialize(cereal::JSONOutputArchive & out_archive) const;
void serialize(cereal::JSONInputArchive & in_archive);
private:
template<typename T>
std::string
mapTypeToString(const T &type, const std::map<std::string, T> &type_mapper) const
{
for (auto &mapped_type : type_mapper) {
if (mapped_type.second == type) return mapped_type.first;
}
dbgAssert(false) << "Unsupported type " << static_cast<int>(type);
// Just satisfying the compiler, this return never reached
return std::string();
}
Maybe<void> installable = Maybe<void>();
std::string mirror;
std::string name;
std::string version;
std::string download_path;
std::string relative_path;
ChecksumTypes checksum_type;
std::string checksum_value;
PackageType package_type;
std::vector<std::string> require_packages;
};
#endif // __PACKAGE_H__

View File

@@ -0,0 +1,42 @@
// 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 __PACKAGE_HANDLER_H__
#define __PACKAGE_HANDLER_H__
#include "i_package_handler.h"
#include "i_orchestration_tools.h"
#include "i_shell_cmd.h"
#include "component.h"
class PackageHandler
:
public Component,
Singleton::Provide<I_PackageHandler>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_OrchestrationTools>
{
public:
PackageHandler();
~PackageHandler();
void preload() override;
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __PACKAGE_HANDLER_H__

189
components/include/packet.h Executable file
View File

@@ -0,0 +1,189 @@
#ifndef __PACKET_H__
#define __PACKET_H__
#include <memory>
#include <vector>
#include <ostream>
#include "connkey.h"
#include "buffer.h"
#include "maybe_res.h"
#include "type_defs.h"
enum class CDir : u_char
{
C2S,
S2C
};
static inline CDir
otherCDir(CDir cdir)
{
return static_cast<CDir>(static_cast<int>(CDir::S2C) - static_cast<int>(cdir));
}
static inline std::ostream &
operator<<(std::ostream &os, CDir cdir)
{
switch (cdir) {
case CDir::C2S: {
return os << "c2s";
}
case CDir::S2C: {
return os << "s2c";
}
}
return os << "Could not match direction of a connection - neither C2S, nor S2C (" << static_cast<int>(cdir) << ")";
}
enum class PktErr
{
UNINITIALIZED,
NON_ETHERNET_FRAME,
MAC_LEN_TOO_BIG,
NON_IP_PACKET,
UNKNOWN_L3_PROTOCOL,
IP_SIZE_MISMATCH,
IP_VERSION_MISMATCH,
IP_HEADER_TOO_SMALL,
PKT_TOO_SHORT_FOR_IP_HEADER,
PKT_TOO_SHORT_FOR_IP_EXTENSION_HEADER,
PKT_TOO_SHORT_FOR_IP_EXTENSION_HEADER_BODY,
UNKNOWN_IPV6_EXTENSION_HEADER,
PKT_TOO_SHORT_FOR_L4_HEADER,
PKT_TOO_SHORT_FOR_TCP_OPTIONS,
TCP_HEADER_TOO_SMALL,
PKT_TOO_SHORT_FOR_ICMP_ERROR_DATA,
ICMP_VERSION_MISMATCH,
};
enum class PktType
{
PKT_L2 = 1,
PKT_L3 = 2,
};
std::ostream & operator<<(std::ostream &os, const PktErr &err);
USE_DEBUG_FLAG(D_PACKET);
class Packet
{
public:
explicit Packet() {}
template <typename... Args>
static Maybe<std::unique_ptr<Packet>, PktErr>
genPacket(PktType type, IPType proto, Args&&... args)
{
// Same as make_unique, but I can't use make unique and keep the ctor private...
auto pkt = std::unique_ptr<Packet>(new Packet());
pkt->setPacketType(type);
pkt->pkt_data = Buffer(std::forward<Args>(args)...);
auto key = pkt->parsePacket(type, proto);
if (!key.ok()) {
return genError(key.getErr());
}
dbgTrace(D_PACKET) << "Extracted key: " << *key;
pkt->key = *key;
return std::move(pkt);
}
PktType getPacketType() const { return pkt_type; }
IPType getPacketProto() const { return key.getType(); }
bool isFragment() const { return is_fragment; }
const Buffer & getL4Data() const { return l4_payload; }
const Buffer & getL4Header() const { return l4_header; }
const Buffer & getL3() const { return l3; }
const Buffer & getL3Data() const { return l3_payload; }
const Buffer & getL3Header() const { return l3_header; }
const Buffer & getL2Data() const { return l2_payload; }
const Buffer & getL2Header() const { return l2_header; }
const Buffer & getPacket() const { return pkt_data; }
const ConnKey & getKey() const { return key; }
void setInterface(NetworkIfNum value);
Maybe<NetworkIfNum> getInterface() const;
void setKey(const ConnKey &_key) { key = _key; }
CDir getCDir() const { return cdir; }
void setCDir(CDir _cdir) { cdir = _cdir; }
void setZecoOpaque(u_int64_t _zeco_opaque);
Maybe<u_int64_t> getZecoOpaque() const;
// Get the data (L2 and up) as a vector. Copies everything.
std::vector<u_char> getL2DataVec() const;
template<class Archive>
void
serialize(Archive &ar, uint32_t)
{
ar(
key,
cdir,
pkt_type,
has_zeco_opaque,
zeco_opaque,
is_interface,
is_fragment,
interface,
pkt_data,
l2_header,
l2_payload,
l3,
l3_header,
l3_payload,
l4_header,
l4_payload
);
}
private:
ConnKey key;
CDir cdir;
PktType pkt_type;
bool is_interface = false;
bool is_fragment = false;
NetworkIfNum interface;
Buffer pkt_data;
Buffer l2_header;
Buffer l2_payload;
Buffer l3;
Buffer l3_header;
Buffer l3_payload;
Buffer l4_header;
Buffer l4_payload;
bool has_zeco_opaque = false;
u_int64_t zeco_opaque;
Maybe<ConnKey, PktErr> parsePacket(PktType type, IPType proto);
Maybe<ConnKey, PktErr> parseFromL2();
Maybe<ConnKey, PktErr> parseFromL3v4();
Maybe<ConnKey, PktErr> parseFromL3v6();
Maybe<IPProto, PktErr> getIPv6Proto(IPProto proto);
Maybe<int, PktErr> getIPv6ExtLen(uint offset_to_ext_hdr, IPProto ext_hdr_type);
Maybe<int, PktErr> getIPv6GenericExtLen(uint offset_to_ext_hdr, uint length_multiplier);
Maybe<ConnKey, PktErr> parseFromL4(const IPAddr &src, const IPAddr &dst, IPProto proto);
std::tuple<PortNumber, PortNumber> getICMPPortsV6();
std::tuple<PortNumber, PortNumber> getICMPPortsV4();
std::tuple<PortNumber, PortNumber> getICMPPorts(IPProto proto);
void setPacketType(const PktType _pkt_type) { pkt_type = _pkt_type; }
Maybe<uint, PktErr> getIcmpHdrLen(IPProto proto, IPType ip_type);
};
#endif // __PACKET_H__

View File

@@ -0,0 +1,85 @@
#ifndef __PENDING_KEY_H__
#define __PENDING_KEY_H__
#include <netinet/in.h>
#include <tuple>
#include <string.h>
#include "debug.h"
#include "maybe_res.h"
#include "connkey.h"
class PendingKey
{
public:
explicit PendingKey() {}
explicit PendingKey(
const IPAddr &_src,
const IPAddr &_dst,
PortNumber dport,
IPProto proto)
:
src(_src),
dst(_dst)
{
dst.port = dport;
src.proto = proto;
dst.proto = proto;
}
PendingKey(const ConnKey &key) : PendingKey(key.getSrc(), key.getDst(), key.getDPort(), key.getProto()) {}
bool
operator==(const PendingKey &other) const
{
auto my_tuple = std::tie(src, dst, dst.port, src.proto);
auto other_tuple = std::tie(other.src, other.dst, other.dst.port, other.src.proto);
return my_tuple == other_tuple;
}
bool
operator!=(const PendingKey &other) const
{
return !(*this == other);
}
const IPAddr & getSrc() const { return src; }
const IPAddr & getDst() const { return dst; }
PortNumber getDPort() const { return dst.port; }
IPProto getProto() const { return src.proto; }
Maybe<IPType>
getType() const
{
if(src.type != dst.type) return genError("Mismatch in connection types (Src and Dst types are not identical)");
return src.type;
}
std::ostream & print(std::ostream &os) const;
size_t hash() const;
template<class Archive>
void
serialize(Archive &ar, uint32_t)
{
ar(src, dst);
}
private:
IPAddr src, dst;
};
// Specialization of std::hash<> for ConnKey
namespace std
{
template <>
struct hash<PendingKey>
{
size_t operator()(const PendingKey &k) const { return k.hash(); }
};
} // namespace std
static inline std::ostream & operator<<(std::ostream &os, const PendingKey &k) { return k.print(os); }
#endif // __PENDING_KEY_H__

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 __PM_HOOK_H__
#define __PM_HOOK_H__
#include <memory>
#include <string>
#include <map>
#include <sys/types.h>
#include "i_pm_scan.h"
class KissThinNFA;
class PMHook final : public I_PMScan
{
public:
explicit PMHook();
~PMHook();
Maybe<void> prepare(const std::set<PMPattern> &patterns);
std::set<PMPattern> scanBuf(const Buffer &buf) const override;
std::set<std::pair<uint, PMPattern>> scanBufWithOffset(const Buffer &buf) const override;
void scanBufWithOffsetLambda(const Buffer &buf, I_PMScan::CBFunction cb) const override;
// Line may begin with ^ or $ sign to mark LSS is at begin/end of buffer.
static Maybe<PMPattern> lineToPattern(const std::string &line);
bool ok() const { return static_cast<bool>(handle); }
private:
std::shared_ptr<KissThinNFA> handle;
std::map<int, PMPattern> patterns;
};
#endif // __PM_HOOK_H__

View File

@@ -0,0 +1,150 @@
// 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 __REPORT_MESSAGING_H__
#define __REPORT_MESSAGING_H__
#include "singleton.h"
#include "i_time_get.h"
#include "i_messaging.h"
#include "report/report.h"
class ReportMessaging
:
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_TimeGet>
{
public:
template <typename ...Args, typename T>
ReportMessaging(
const std::string &title,
const ReportIS::AudienceTeam &audience_team,
const T &obj,
Args ...args)
:
ReportMessaging(
title,
audience_team,
obj,
false,
MessageTypeTag::GENERIC,
std::forward<Args>(args)...
)
{
}
template <typename ...Args, typename T>
ReportMessaging(
const std::string &title,
const ReportIS::AudienceTeam &audience_team,
const T &obj,
bool is_async_message,
Args ...args)
:
ReportMessaging(
title,
audience_team,
obj,
is_async_message,
MessageTypeTag::GENERIC,
std::forward<Args>(args)...
)
{
}
template <typename ...Args, typename T>
ReportMessaging(
const std::string &title,
const ReportIS::AudienceTeam &audience_team,
const T &obj,
bool is_async_message,
const MessageTypeTag &message_type,
Args ...args)
:
ReportMessaging(
title,
audience_team,
ReportIS::Severity::INFO,
ReportIS::Priority::LOW,
obj,
is_async_message,
message_type,
std::forward<Args>(args)...
)
{
}
template <typename ...Args, typename T>
ReportMessaging(
const std::string &title,
const ReportIS::AudienceTeam &audience_team,
const ReportIS::Severity &severity,
const ReportIS::Priority &priority,
const T &obj,
Args ...args)
:
ReportMessaging(
title,
audience_team,
severity,
priority,
obj,
false,
MessageTypeTag::GENERIC,
std::forward<Args>(args)...
)
{
}
template <typename ...Args, typename T>
ReportMessaging(
const std::string &title,
const ReportIS::AudienceTeam &audience_team,
const ReportIS::Severity &severity,
const ReportIS::Priority &priority,
const T &obj,
bool _is_async_message,
const MessageTypeTag &message_type,
Args ...args)
:
report(
title,
Singleton::Consume<I_TimeGet>::by<ReportMessaging>()->getWalltime(),
ReportIS::Type::EVENT,
ReportIS::Level::LOG,
ReportIS::LogLevel::INFO,
ReportIS::Audience::INTERNAL,
audience_team,
severity,
priority,
std::chrono::seconds(0),
std::forward<Args>(args)...
),
is_async_message(_is_async_message),
message_type_tag(message_type)
{
report << LogField("eventObject", obj);
}
~ReportMessaging();
ReportMessaging & operator<<(const LogField &field);
private:
Report report;
bool is_async_message;
MessageTypeTag message_type_tag;
};
#endif // __REPORT_MESSAGING_H__

View File

@@ -0,0 +1,55 @@
// 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 __SERVICE_CONTROLLER_H__
#define __SERVICE_CONTROLLER_H__
#include "i_service_controller.h"
#include <map>
#include <set>
#include "i_orchestration_tools.h"
#include "i_orchestration_status.h"
#include "i_shell_cmd.h"
#include "i_rest_api.h"
#include "i_tenant_manager.h"
#include "service_details.h"
#include "i_mainloop.h"
#include "component.h"
class ServiceController
:
public Component,
Singleton::Provide<I_ServiceController>,
Singleton::Consume<I_ShellCmd>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_OrchestrationStatus>,
Singleton::Consume<I_OrchestrationTools>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_TenantManager>,
Singleton::Consume<I_TimeGet>
{
public:
ServiceController();
~ServiceController();
void init() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __SERVICE_CONTROLLER_H__

View File

@@ -0,0 +1,79 @@
// 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 __SERVICE_DETAILS_H__
#define __SERVICE_DETAILS_H__
#include <string>
#include <vector>
#include "connkey.h"
#include "rest.h"
#include "config.h"
#include "i_service_controller.h"
class ServiceDetails : Singleton::Consume<I_ServiceController>
{
public:
ServiceDetails() = default;
ServiceDetails(
const std::string &name,
const PortNumber &port,
const std::vector<std::string> relevant_configurations,
const std::string &id = "")
:
service_name(name),
service_id(id),
service_port(port)
{
relevant_configs.insert(relevant_configurations.begin(), relevant_configurations.end());
}
template <typename Archive>
void serialize(Archive &ar);
ReconfStatus sendNewConfigurations(int conf_id, const std::string &policy_version);
bool isConfigurationRelevant(const std::string &config) const { return relevant_configs.count(config) > 0; }
bool sendRequest(const std::string &uri, ClientRest &request_json) const;
bool isServiceActive() const;
const PortNumber & getPort() const { return service_port; }
const std::string & getServiceID() const {return service_id; }
const std::string & getServiceName() const {return service_name; }
private:
std::string service_name;
std::string service_id;
PortNumber service_port;
std::unordered_set<std::string> relevant_configs;
};
class SetNanoServiceConfig : public ServerRest
{
public:
void doCall() override;
C2S_PARAM(std::string, service_name);
C2S_OPTIONAL_PARAM(std::string, service_id);
C2S_PARAM(int, service_listening_port);
C2S_PARAM(std::vector<std::string>, expected_configurations);
S2C_PARAM(bool, status);
};
#endif // __SERVICE_DETAILS_H__

View File

@@ -0,0 +1,50 @@
// 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 __SIGNAL_HANDLER_H__
#define __SIGNAL_HANDLER_H__
#include "config.h"
#include "i_mainloop.h"
#include "i_time_get.h"
#include "i_agent_details.h"
#include "i_environment.h"
#include "i_messaging.h"
#include "i_signal_handler.h"
#include "config/i_config.h"
#include "component.h"
class SignalHandler
:
public Component,
Singleton::Provide<I_SignalHandler>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_Environment>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<Config::I_Config>
{
public:
SignalHandler();
~SignalHandler();
void init();
void preload();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __SIGNAL_HANDLER_H__

122
components/include/telemetry.h Executable file
View File

@@ -0,0 +1,122 @@
// 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.
#pragma once
#ifndef __TELEMETRY_H__
#define __TELEMETRY_H__
#include <thread>
#include <time.h>
#include <chrono>
#include "i_mainloop.h"
#include "i_waap_telemetry.h"
#include "i_agent_details.h"
#include "i_logging.h"
#include "logging_comp.h"
#include <map>
#include <set>
#include <unordered_set>
#include "waap.h"
#include "generic_metric.h"
enum class AssetType { API, WEB, ALL, COUNT };
class WaapTelemetryEvent : public Event<WaapTelemetryEvent>
{
public:
WaapTelemetryEvent(const std::string &_asset_id, const DecisionTelemetryData &_data)
:
asset_id(_asset_id),
data(_data)
{}
const DecisionTelemetryData & getData() const { return data; }
const std::string & getAssetId() const { return asset_id; }
private:
std::string asset_id;
DecisionTelemetryData data;
};
class WaapTelemetrics : public GenericMetric
{
public:
void updateMetrics(const std::string &asset_id, const DecisionTelemetryData &data);
void initMetrics();
private:
MetricCalculations::Counter requests{this, "reservedNgenA"};
MetricCalculations::Counter sources{this, "reservedNgenB"};
MetricCalculations::Counter force_and_block_exceptions{this, "reservedNgenC"};
MetricCalculations::Counter waf_blocked{this, "reservedNgenD"};
MetricCalculations::Counter api_blocked{this, "reservedNgenE"};
MetricCalculations::Counter bot_blocked{this, "reservedNgenF"};
MetricCalculations::Counter threat_info{this, "reservedNgenG"};
MetricCalculations::Counter threat_low{this, "reservedNgenH"};
MetricCalculations::Counter threat_medium{this, "reservedNgenI"};
MetricCalculations::Counter threat_high{this, "reservedNgenJ"};
std::unordered_set<std::string> sources_seen;
};
class WaapAttackTypesMetrics : public GenericMetric
{
public:
void updateMetrics(const std::string &asset_id, const DecisionTelemetryData &data);
void initMetrics();
private:
MetricCalculations::Counter sql_inj{this, "reservedNgenA"};
MetricCalculations::Counter vulnerability_scan{this, "reservedNgenB"};
MetricCalculations::Counter path_traversal{this, "reservedNgenC"};
MetricCalculations::Counter ldap_inj{this, "reservedNgenD"};
MetricCalculations::Counter evasion_techs{this, "reservedNgenE"};
MetricCalculations::Counter remote_code_exec{this, "reservedNgenF"};
MetricCalculations::Counter xml_extern_entity{this, "reservedNgenG"};
MetricCalculations::Counter cross_site_scripting{this, "reservedNgenH"};
MetricCalculations::Counter general{this, "reservedNgenI"};
};
class WaapMetricWrapper : public Listener<WaapTelemetryEvent>, Singleton::Consume<I_AgentDetails>
{
public:
void upon(const WaapTelemetryEvent &event) override;
private:
std::map<std::string, std::shared_ptr<WaapTelemetrics>> metrics;
std::map<std::string, std::shared_ptr<WaapTelemetrics>> telemetries;
std::map<std::string, std::shared_ptr<WaapAttackTypesMetrics>> attack_types;
std::map<std::string, std::shared_ptr<WaapAttackTypesMetrics>> attack_types_telemetries;
};
class AssetCountEvent : public Event<AssetCountEvent>
{
public:
AssetCountEvent(AssetType type, const int &asset_count) : asset_type(type), assets_count(asset_count) {};
const AssetType & getAssetType() const { return asset_type; }
const int & getAssetCount() const { return assets_count; }
private:
AssetType asset_type;
int assets_count;
};
class AssetsMetric : public GenericMetric, Listener<AssetCountEvent>
{
public:
void upon(const AssetCountEvent &event) override;
private:
MetricCalculations::LastReportedValue<int> api_assets{this, "numberOfProtectedApiAssetsSample"};
MetricCalculations::LastReportedValue<int> web_assets{this, "numberOfProtectedWebAppAssetsSample"};
MetricCalculations::LastReportedValue<int> all_assets{this, "numberOfProtectedAssetsSample"};
};
#endif // __TELEMETRY_H__

View File

@@ -0,0 +1,61 @@
// 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 __TRANSACTION_TABLE_METRIC_H__
#define __TRANSACTION_TABLE_METRIC_H__
#include "generic_metric.h"
class TransactionTableEvent : public Event<TransactionTableEvent>
{
public:
void
setTransactionTableSize(uint64_t _value)
{
transaction_table_size = _value;
}
uint64_t
getTransactionTableSize() const
{
return transaction_table_size;
}
private:
uint64_t transaction_table_size = 0;
};
class TransactionTableMetric
:
public GenericMetric,
public Listener<TransactionTableEvent>
{
public:
void
upon(const TransactionTableEvent &event) override
{
max_transaction_table_size.report(event.getTransactionTableSize());
avg_transaction_table_size.report(event.getTransactionTableSize());
last_report_transaction_handler_size.report(event.getTransactionTableSize());
}
private:
MetricCalculations::Max<uint64_t> max_transaction_table_size{this, "maxTransactionTableSizeSample", 0};
MetricCalculations::Average<double> avg_transaction_table_size{this, "averageTransactionTableSizeSample"};
MetricCalculations::LastReportedValue<uint64_t> last_report_transaction_handler_size{
this,
"lastReportTransactionTableSizeSample"
};
};
#endif // __TRANSACTION_TABLE_METRIC_H__

View File

@@ -0,0 +1,7 @@
#ifndef __TYPE_DEFS_H__
#define __TYPE_DEFS_H__
// Definition of FD.io interface information
using NetworkIfNum = uint16_t;
#endif // __TYPE_DEFS_H__

View File

@@ -0,0 +1,46 @@
// 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 __UPDATE_COMMUNICATION_H__
#define __UPDATE_COMMUNICATION_H__
#include "i_update_communication.h"
#include "i_environment.h"
#include "i_rest_api.h"
#include "i_mainloop.h"
#include "i_orchestration_tools.h"
#include "component.h"
class UpdateCommunication
:
public Component,
Singleton::Provide<I_UpdateCommunication>,
Singleton::Consume<I_RestApi>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_OrchestrationTools>
{
public:
UpdateCommunication();
~UpdateCommunication();
void preload() override;
void init() override;
void fini() override;
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __UPDATE_COMMUNICATION_H__

56
components/include/url_parser.h Executable file
View File

@@ -0,0 +1,56 @@
// 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 __URL_PARSER_H__
#define __URL_PARSER_H__
#include "orchestration_tools.h"
#include <string>
#include <ostream>
enum class URLProtocol
{
HTTP,
HTTPS,
LOCAL_FILE
};
class URLParser
{
public:
URLParser(const std::string &url);
Maybe<std::string> getBaseURL() const;
bool isOverSSL() const { return over_ssl; }
std::string getPort() const { return port; }
std::string getQuery() const { return query; }
URLProtocol getProtocol() const { return protocol; }
std::string toString() const;
void setQuery(const std::string &new_query);
private:
void parseURL(const std::string &url);
URLProtocol parseProtocol(const std::string &url) const;
bool over_ssl;
std::string base_url;
std::string port;
std::string query;
URLProtocol protocol;
};
std::ostream & operator<<(std::ostream &os, const URLParser &url);
std::ostream & operator<<(std::ostream &os, const URLProtocol &protocol);
#endif // __URL_PARSER_H__

View File

@@ -0,0 +1,66 @@
// 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 __USER_IDENTIFIERS_CONFIG_H__
#define __USER_IDENTIFIERS_CONFIG_H__
#include <vector>
#include <string>
#include "http_inspection_events.h"
#include "cereal/archives/json.hpp"
class UsersAllIdentifiersConfig
{
public:
enum class ExtractType { SOURCEIDENTIFIER, PROXYIP};
UsersAllIdentifiersConfig();
void load(cereal::JSONInputArchive &ar);
void parseRequestHeaders(const HttpHeader &header) const;
std::vector<std::string> getHeaderValuesFromConfig(const std::string &header_key) const;
void setXFFValuesToOpaqueCtx(const HttpHeader &header, ExtractType type) const;
private:
class UsersIdentifiersConfig
{
public:
UsersIdentifiersConfig();
UsersIdentifiersConfig(const std::string &identifier);
bool operator==(const UsersIdentifiersConfig &other) const;
void load(cereal::JSONInputArchive &ar);
bool isEqualSourceIdentifier(const std::string &other) const;
const std::string & getSourceIdentifier() const { return source_identifier; }
const std::vector<std::string> & getIdentifierValues() const { return identifier_values; }
private:
std::string source_identifier;
std::vector<std::string> identifier_values;
};
bool isHigherPriority(const std::string &current_identifier, const std::string &header_key) const;
void setIdentifierTopaqueCtx(const HttpHeader &header) const;
void setCookieValuesToOpaqueCtx(const HttpHeader &header) const;
void setJWTValuesToOpaqueCtx(const HttpHeader &header) const;
void setCustomHeaderToOpaqueCtx(const HttpHeader &header) const;
Maybe<std::string> parseCookieElement(
const std::string::const_iterator &start,
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;
std::vector<UsersIdentifiersConfig> user_identifiers;
};
#endif // __USER_IDENTIFIERS_CONFIG_H__

66
components/include/waap.h Executable file
View File

@@ -0,0 +1,66 @@
// 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 __WAAP_H__
#define __WAAP_H__
#include <memory>
#include "singleton.h"
#include "i_mainloop.h"
#include "i_table.h"
#include "i_static_resources_handler.h"
#include "http_inspection_events.h"
#include "i_instance_awareness.h"
#include "table_opaque.h"
#include "component.h"
// forward decleration
class I_Telemetry;
class I_DeepAnalyzer;
class I_WaapAssetStatesManager;
class I_Messaging;
class I_AgentDetails;
class I_Encryptor;
class WaapComponent
:
public Component,
Singleton::Consume<I_StaticResourcesHandler>,
Singleton::Consume<I_MainLoop>,
Singleton::Consume<I_TimeGet>,
Singleton::Consume<I_Table>,
Singleton::Consume<I_Telemetry>,
Singleton::Consume<I_DeepAnalyzer>,
Singleton::Consume<I_InstanceAwareness>,
Singleton::Consume<I_WaapAssetStatesManager>,
Singleton::Consume<I_AgentDetails>,
Singleton::Consume<I_Messaging>,
Singleton::Consume<I_Encryptor>,
Singleton::Consume<I_Environment>
{
public:
WaapComponent();
~WaapComponent();
void preload();
void init();
void fini();
private:
class Impl;
std::unique_ptr<Impl> pimpl;
};
#endif // __WAAP_H__