Closed amitschendel closed 8 months ago
PR Description updated to latest commit (https://github.com/kubescape/node-agent/commit/32a12f1dd0959d5b08ca8d89c4a62dca192e996b)
⏱️ Estimated effort to review [1-5] | 5, because the PR introduces significant changes across multiple files, including the addition of new features (e.g., `AlertManagerExporter`, `StdoutExporter`), refactoring of existing code to use new data structures (e.g., changes from specific getters to a more generic approach in `MalwareResult` interface), and modifications to the rule processing logic to incorporate these changes. The PR touches on various aspects of the system, including rule processing, malware detection, and alert exporting, requiring a thorough review to ensure compatibility and correctness. |
🧪 Relevant tests | No |
🔍 Possible issues | Possible Bug: The refactoring introduces changes in how data is passed and processed across different components (e.g., from specific getters to a more generic approach in `MalwareResult` interface). This could potentially introduce bugs if not all instances where the old methods were used have been correctly updated to the new approach. |
Performance Concern: The addition of new exporters and the changes in the rule processing logic could potentially impact the performance of the system. It's important to evaluate the performance implications of these changes, especially in environments with a high volume of events. | |
🔒 Security concerns | No |
Category | Suggestions |
Enhancement |
Improve error handling in
___
**Consider handling the error returned by |
Add detailed logging for error scenarios in
___
**For the | |
Implement batch alert sending in
___
**In the | |
Include PID in error messages for better debugging context.___ **For error messages, consider including the PID in the message when logging errors relatedto getting command line or parent process details. This will make debugging easier by providing more context.** [pkg/malwaremanager/v1/clamav/clamav.go [198-206]](https://github.com/kubescape/node-agent/pull/231/files#diff-946a7b5957a07b2ec4516a5a7e935c1b17de7cb6a27511e48463ed6f3d8cd159R198-R206) ```diff -logger.L().Error("Error getting command line of pid", helpers.Error(err)) -logger.L().Error("Error getting ppid of pid", helpers.Error(err)) +logger.L().Error(fmt.Sprintf("Error getting command line of pid %d", openEvent.Pid), helpers.Error(err)) +logger.L().Error(fmt.Sprintf("Error getting ppid of pid %d", openEvent.Pid), helpers.Error(err)) ``` | |
Use meaningful default values instead of
___
**Instead of using | |
Improve error handling after writing the syslog message.___ **Use a more descriptive error handling strategy after attempting to write the syslogmessage. Logging the error or retrying the write operation could be beneficial.** [pkg/exporters/syslog_exporter.go [108]](https://github.com/kubescape/node-agent/pull/231/files#diff-d84d67a80745d135f3f4af7c387c52361f506fc84f626e517ea8b37b150f8bb7R108-R108) ```diff -_, err := message.WriteTo(se.writer) +if _, err := message.WriteTo(se.writer); err != nil { + log.Printf("Failed to write syslog message: %v", err) + // Consider retrying the write operation or handling the error accordingly. +} ``` | |
Use a more relevant process ID for malware alerts.___ **For theProcessID field in the malware alert, consider using a more relevant process identifier related to the malware event, if available, instead of the exporter's process ID.** [pkg/exporters/syslog_exporter.go [121]](https://github.com/kubescape/node-agent/pull/231/files#diff-d84d67a80745d135f3f4af7c387c52361f506fc84f626e517ea8b37b150f8bb7R121-R121) ```diff -ProcessID: fmt.Sprintf("%d", os.Getpid()), // TODO: is this correct? +ProcessID: fmt.Sprintf("%d", relevantProcessID), // Replace `relevantProcessID` with the actual process ID related to the malware event. ``` | |
Maintainability |
Refactor
___
**To enhance the readability and maintainability of the |
Move struct definitions into separate files for better organization.___ **For better code organization and readability, consider moving the struct definitions( HTTPExporterConfig , HTTPExporter , HTTPAlertsListSpec , etc.) into separate files. This can make the codebase easier to navigate and maintain.** [pkg/exporters/http_exporter.go [23-57]](https://github.com/kubescape/node-agent/pull/231/files#diff-6e04fd42d767812ea2855370a21a524371930b320544c0ee0954e1500242fbbdR23-R57) ```diff -type HTTPExporterConfig struct { -... -} -type HTTPExporter struct { -... -} -type HTTPAlertsListSpec struct { -... -} +// Suggestion to move struct definitions into separate files +// Example: http_exporter_config.go, http_exporter.go, http_alerts_list_spec.go ``` | |
Use constants for severity levels to improve code clarity.___ **To improve maintainability, consider defining the severity levels as constants withdescriptive names. This will make the code easier to understand and modify in the future.** [pkg/malwaremanager/v1/clamav/clamav.go [125]](https://github.com/kubescape/node-agent/pull/231/files#diff-946a7b5957a07b2ec4516a5a7e935c1b17de7cb6a27511e48463ed6f3d8cd159R125-R125) ```diff -Severity: 10, // TODO: Get severity from api. +Severity: SEVERITY_HIGH, // Assuming SEVERITY_HIGH is a constant defined elsewhere ``` | |
Use constants for repeated string literals.___ **Use a constant for the repeated string literals like "testcontainerid", "testnamespace",etc., to avoid typos and make future changes easier.** [pkg/exporters/http_exporter_test.go [46-50]](https://github.com/kubescape/node-agent/pull/231/files#diff-89585231dfa94efdc4cac61ef6426f59bf494acd49c810bb29d56e16574fd350R46-R50) ```diff -ContainerID: "testcontainerid", -Namespace: "testnamespace", +const ( + testContainerID = "testcontainerid" + testNamespace = "testnamespace" +) +ContainerID: testContainerID, +Namespace: testNamespace, ``` | |
Extract URL and summary construction into separate functions.___ **Extract the construction ofsourceUrl and summary into separate functions to improve readability and maintainability of SendRuleAlert and SendMalwareAlert methods.**
[pkg/exporters/alert_manager.go [47-57]](https://github.com/kubescape/node-agent/pull/231/files#diff-40568094a80f334c1148d539cedecc426f810a6e32e5eeab274195f4c80693d5R47-R57)
```diff
-sourceUrl := fmt.Sprintf("https://armosec.github.io/kubecop/alertviewer/?AlertMessage=%s&AlertRuleName=%s&AlertRuleID=%s&AlertFix=%s&AlertNamespace=%s&AlertPod=%s&AlertContainer=%s&AlertProcess=%s",
-summary := fmt.Sprintf("Rule '%s' in '%s' namespace '%s' failed", failedRule.GetBaseRuntimeAlert().AlertName, failedRule.GetRuntimeAlertK8sDetails().PodName, failedRule.GetRuntimeAlertK8sDetails().Namespace)
+sourceUrl := constructSourceUrl(failedRule)
+summary := constructSummary(failedRule)
```
| |
Abstract the construction of syslog messages into a separate method.___ **Consider abstracting the construction of therfc5424.Message into a separate method or function to improve code readability and maintainability.** [pkg/exporters/syslog_exporter.go [48-106]](https://github.com/kubescape/node-agent/pull/231/files#diff-d84d67a80745d135f3f4af7c387c52361f506fc84f626e517ea8b37b150f8bb7R48-R106) ```diff -message := rfc5424.Message{ - Priority: rfc5424.Error, - Timestamp: failedRule.GetBaseRuntimeAlert().Timestamp, - ... -} +message := constructSyslogMessage(failedRule) +// Implement `constructSyslogMessage` to construct the `rfc5424.Message` from a `failedRule`. ``` | |
Best practice |
Handle potential errors from time conversion for robustness.___ **Consider handling the error fromtime.Unix to ensure robustness. While time.Unix is unlikely to fail with valid inputs, explicitly checking for errors can prevent potential issues in edge cases or future changes.** [pkg/malwaremanager/v1/clamav/clamav.go [127]](https://github.com/kubescape/node-agent/pull/231/files#diff-946a7b5957a07b2ec4516a5a7e935c1b17de7cb6a27511e48463ed6f3d8cd159R127-R127) ```diff -Timestamp: time.Unix(int64(execEvent.Timestamp), 0), +timestamp, err := time.Unix(int64(execEvent.Timestamp), 0) +if err != nil { + logger.L().Error("Error converting timestamp", helpers.Error(err)) + return nil +} +Timestamp: timestamp, ``` |
Use explicit boolean values instead of nil for clarity.___ **Instead of usingnil directly for IsPartOfImage in the open event, consider a more explicit approach to indicate the absence of this information, such as using a boolean variable set to false .**
[pkg/malwaremanager/v1/clamav/clamav.go [220]](https://github.com/kubescape/node-agent/pull/231/files#diff-946a7b5957a07b2ec4516a5a7e935c1b17de7cb6a27511e48463ed6f3d8cd159R220-R220)
```diff
-IsPartOfImage: nil, // We don't have that enrichement in the open event.
+isPartOfImage := false
+IsPartOfImage: &isPartOfImage,
```
| |
Check for nil before dereferencing to improve code safety.___ **To avoid potential nil pointer dereference and improve code safety, check ifexecEvent.Runtime and execEvent.K8s are not nil before accessing their fields.**
[pkg/malwaremanager/v1/clamav/clamav.go [242-247]](https://github.com/kubescape/node-agent/pull/231/files#diff-946a7b5957a07b2ec4516a5a7e935c1b17de7cb6a27511e48463ed6f3d8cd159R242-R247)
```diff
-ContainerID: execEvent.Runtime.ContainerID,
-HostNetwork: &execEvent.K8s.HostNetwork,
+ContainerID: safeString(execEvent.Runtime.ContainerID),
+HostNetwork: safeBoolPointer(execEvent.K8s.HostNetwork),
```
| |
Handle errors returned by
___
**Consider handling the error returned by | |
Add error handling for system calls in
___
**Implement error handling for | |
Possible issue |
Add nil pointer checks before dereferencing to avoid runtime panics.___ **Consider checking for nil pointers before dereferencingfailedRule.GetRuntimeProcessDetails() , failedRule.GetRuntimeAlertK8sDetails() , and failedRule.GetBaseRuntimeAlert() to avoid potential runtime panics.**
[pkg/exporters/syslog_exporter.go [50-53]](https://github.com/kubescape/node-agent/pull/231/files#diff-d84d67a80745d135f3f4af7c387c52361f506fc84f626e517ea8b37b150f8bb7R50-R53)
```diff
-Timestamp: failedRule.GetBaseRuntimeAlert().Timestamp,
-Hostname: failedRule.GetRuntimeAlertK8sDetails().PodName,
-AppName: failedRule.GetRuntimeAlertK8sDetails().ContainerName,
-ProcessID: fmt.Sprintf("%d", failedRule.GetRuntimeProcessDetails().PID),
+if baseRuntimeAlert := failedRule.GetBaseRuntimeAlert(); baseRuntimeAlert != nil {
+ Timestamp: baseRuntimeAlert.Timestamp,
+}
+if k8sDetails := failedRule.GetRuntimeAlertK8sDetails(); k8sDetails != nil {
+ Hostname: k8sDetails.PodName,
+ AppName: k8sDetails.ContainerName,
+}
+if processDetails := failedRule.GetRuntimeProcessDetails(); processDetails != nil {
+ ProcessID: fmt.Sprintf("%d", processDetails.PID),
+}
```
|
Check for nil before dereferencing the
___
**For the |
Summary:
User description
Overview
Type
enhancement, bug_fix
Description
HTTPExporter
,SyslogExporter
, andCsvExporter
to useapitypes.RuntimeAlert
.AlertManagerExporter
for sending alerts to Prometheus Alertmanager.apitypes.RuntimeAlert
and added enrichment with additional metadata.StdoutExporter
for logging alerts to stdout.HTTPExporter
,SyslogExporter
,CsvExporter
, andAlertManagerExporter
.Changes walkthrough
17 files
http_exporter.go
Refactor HTTPExporter to use RuntimeAlert and support cluster details
pkg/exporters/http_exporter.go
ClusterName
,k8sClient
toHTTPExporter
struct.HTTPAlert
struct withapitypes.RuntimeAlert
.sendAlertLimitReached
,SendRuleAlert
, andSendMalwareAlert
methods to use
apitypes.RuntimeAlert
.getWorkloadIdentifiers
to retrieve workload details.clamav.go
Enhance ClamAV malware detection with additional metadata and
refactoring
pkg/malwaremanager/v1/clamav/clamav.go
handleExecEvent
andhandleOpenEvent
to useapitypes.RuntimeAlert
.alert_manager.go
Implement AlertManagerExporter for sending alerts to Prometheus
Alertmanager
pkg/exporters/alert_manager.go
AlertManagerExporter
struct with methods to send rule andmalware alerts.
syslog_exporter.go
Refactor SyslogExporter to use RuntimeAlert
pkg/exporters/syslog_exporter.go
SyslogExporter
to useapitypes.RuntimeAlert
.SendRuleAlert
andSendMalwareAlert
methods.helpers.go
Add helper methods for rule failure enrichment in rule engine
pkg/ruleengine/v1/helpers.go
getPathFromPid
,getCommFromPid
, andenrichRuleFailure
.r0007_kubernetes_client_executed.go
Update Kubernetes client executed rule to use RuntimeAlert and
enrichment
pkg/ruleengine/v1/r0007_kubernetes_client_executed.go
apitypes.RuntimeAlert
for rule failure.malwareresult.go
Refactor GenericMalwareResult to use new RuntimeAlert types
pkg/malwaremanager/v1/types/malwareresult.go
GenericMalwareResult
to useapitypes.BaseRuntimeAlert
andrelated types.
utils.go
Add utility methods for file hash calculation and command line
retrieval
pkg/utils/utils.go
retrieval.
r0003_unexpected_system_call.go
Update unexpected system call rule to use RuntimeAlert and enrichment
pkg/ruleengine/v1/r0003_unexpected_system_call.go
apitypes.RuntimeAlert
for rule failure.csv_exporter.go
Update CsvExporter to use RuntimeAlert
pkg/exporters/csv_exporter.go
CsvExporter
to useapitypes.RuntimeAlert
.SendRuleAlert
andSendMalwareAlert
methods.r0001_unexpected_process_launched.go
Update unexpected process launched rule to use RuntimeAlert and
enrichment
pkg/ruleengine/v1/r0001_unexpected_process_launched.go
apitypes.RuntimeAlert
for rule failure.r0004_unexpected_capability_used.go
Update unexpected capability used rule to use RuntimeAlert and
enrichment
pkg/ruleengine/v1/r0004_unexpected_capability_used.go
apitypes.RuntimeAlert
for rule failure.r1001_exec_binary_not_in_base_image.go
Update exec binary not in base image rule to use RuntimeAlert and
enrichment
pkg/ruleengine/v1/r1001_exec_binary_not_in_base_image.go
apitypes.RuntimeAlert
for rule failure.r0002_unexpected_file_access.go
Update unexpected file access rule to use RuntimeAlert and enrichment
pkg/ruleengine/v1/r0002_unexpected_file_access.go
apitypes.RuntimeAlert
for rule failure.r1003_malicious_ssh_connection.go
Update malicious SSH connection rule to use RuntimeAlert and
enrichment
pkg/ruleengine/v1/r1003_malicious_ssh_connection.go
apitypes.RuntimeAlert
for rule failure.malware_manager_interface.go
Refactor MalwareResult interface to use new RuntimeAlert types
pkg/malwaremanager/malware_manager_interface.go
MalwareResult
interface to useapitypes.BaseRuntimeAlert
and related types.
stdout_exporter.go
Implement StdoutExporter for logging alerts to stdout
pkg/exporters/stdout_exporter.go
StdoutExporter
for logging alerts to stdout.SendRuleAlert
andSendMalwareAlert
methods.4 files
http_exporter_test.go
Update HTTPExporter tests for new RuntimeAlert structure
pkg/exporters/http_exporter_test.go
HTTPExporter
.GenericRuleFailure
withruleenginev1.GenericRuleFailure
andapitypes.BaseRuntimeAlert
.syslog_exporter_test.go
Add tests for SyslogExporter with RuntimeAlert structure
pkg/exporters/syslog_exporter_test.go
SyslogExporter
reflecting the newRuntimeAlert
structure.
alert_manager_test.go
Add tests for AlertManagerExporter with RuntimeAlert structure
pkg/exporters/alert_manager_test.go
AlertManagerExporter
reflecting the newRuntimeAlert
structure.
csv_exporter_test.go
Update CsvExporter tests for new RuntimeAlert structure
pkg/exporters/csv_exporter_test.go
CsvExporter
to reflect changes inRuntimeAlert
structure.