* deprecate control name in posture exception policies
Signed-off-by: Amir Malka <amirm@armosec.io>
* deprecate control name in posture exception policies
Signed-off-by: Amir Malka <amirm@armosec.io>
* deprecate control name in posture exception policies
Signed-off-by: Amir Malka <amirm@armosec.io>
* deprecate control name in posture exception policies
Signed-off-by: Amir Malka <amirm@armosec.io>
---------
Signed-off-by: Amir Malka <amirm@armosec.io>
- Introduced a single context in main() to handle interrupt signals (os.Interrupt, syscall.SIGTERM).
- Removed repetitive context creation in the program by reusing the propagated context.
- Improved code readability and maintainability by centralizing context management.
- Ensured consistent handling of graceful shutdown across the program.
Signed-off-by: Ruslan Semagin <pixel.365.24@gmail.com>
This commit introduces the ability to specify targets in image
exceptions. Each target will have the following 4 attributes:
1. Registry
2. Organization
3. ImageName
4. ImageTag
These attributes will be used to match against the canonical image name
of the image to be scanned. The vulnerabilites and the severities
specified in the VulnerabilitiesIgnorePolicy object will be considered
only if the image to be scanned matches the targets specified for that
policy. Regular expressions can also be used to specify the image
attributes.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Added initial commit to start loading image exceptions from json files.
Currently, it supports vulnerability exceptions using their CVE-IDs.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
This commit introduces the "exceptions" flag in the scan image command.
Users can pass a list of vulnerabilities they ignore while scanning an
image using this flag. Also added tests for the same.
Fixes: https://github.com/kubescape/kubescape/issues/1564
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
In particular,
Replace scanResponseChan struct with a reply channel in req.
This removes one chokepoint with tracking a map of channel with a mutex wrapping by not sharing data across different requests and
makes it easier to reason about the correctness of the behavior.
Other changes are mostly cosmetic to group your operations related to
the primitives you are operating on, reducing the average lifetime of
a local variable (matters mostly for humans; compilers are very good at this nowadays).
Also this is net benefical by reducing LOCs by 45.
Signed-off-by: ttimonen <toni.timonen@iki.fi>
It plays wtih channels and goroutines, so having it
behave correctly is not completely trivial and test
worthy.
Signed-off-by: ttimonen <toni.timonen@iki.fi>
Add a new column in the PDF output to reference each control that has
been executed as control ID.
Signed-off-by: Massimiliano Giovagnoli <me@maxgio.it>
Wrote new tests to cover the unhandled statements in the
`NewFixPathLocationResolver` and `ResolveLocation` functions.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Wrote new tests for `categorytable` and `frameworkscan`
Refactored the `shortFormatRow` function for:
- Imporved readability
- Consistency
- Improve code modularity
- Encapsulation: The formatted string construction is encapsulated
within the function, maintaining code modularity and separation of
concerns.
Added the `MockISeverityCounters` mock struct to test the
`renderSeverityCountersSummary` function.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Improvments:
1. filterCVEsBySeverities
- This approach is faster than iterating over the severities slice
for each CVE. The map is created in advance, eliminating the
need for repeated string comparisons.
2. getSortPackageScores
- Avoids unnecessary map lookups by creating a slice of
imageprinter.PackageScore pointers.
3. getSortedCVEsBySeverity
- Avoiding Map Lookups
- Efficient Sorting
- Optimized Output
Added tests for tableprinter/utils
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Added tests for the following functions:
- `generateTable`
- `NewTableWriter`
- `PrintImageScanningTable`
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Added tests in the jsonprinter.go, junit.go pdf.go prometheus.go files
and updated the `Score` functions to handle invalid scores.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Wrote new tests for the functions in the resourcetable.go file.
Enhancements:
1. `generateResourceHeader`:
- Dynamic Header Length
- Efficient Header Creation
- Clearer Code Structure
2. `appendFailedPathsIfNotInPaths`:
- Create a set to efficiently check if a failed path already exists in
the paths slice
- Append failed paths if they are not already present
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Description:
This pull request introduces a new test case TestGetFrameworkCmdWithNonExistentFramework in the framework_test.go file. The purpose of this test case is to verify the behavior of the getFrameworkCmd function when it's run with a non-existent framework argument.
In this test case, we:
Create a mock Kubescape interface and a ScanInfo object
Call the getFrameworkCmd function with the mock interface and ScanInfo object
Run the command with a non-existent framework argument
Check that there is an error and the error message is "bad argument: account ID must be a valid UUID"
This test case enhances the test coverage of the getFrameworkCmd function and ensures that it correctly handles non-existent framework arguments.
Signed-off-by: Umair <58398786+Umair0343@users.noreply.github.com>
Description:
This pull request introduces a new test case TestGetControlCmdWithNonExistentControl in the control_test.go file. The purpose of this test case is to verify the behavior of the getControlCmd function when it's run with a non-existent control argument.
In this test case, we:
Create a mock Kubescape interface and a ScanInfo object
Call the getControlCmd function with the mock interface and ScanInfo object
Run the command with a non-existent control argument
Check that there is an error and the error message is "bad argument: account ID must be a valid UUID"
This test case enhances the test coverage of the getControlCmd function and ensures that it correctly handles non-existent control arguments.
Signed-off-by: Umair <58398786+Umair0343@users.noreply.github.com>
Title: Add Test Case for Non-Existent Image in GetPatchCmd
Description:
This pull request introduces a new test case TestGetPatchCmdWithNonExistentImage in the patch_test.go file. The purpose of this test case is to verify the behavior of the GetPatchCmd function when it's run with a non-existent image argument.
In this test case, we:
Create a mock Kubescape interface
Call the GetPatchCmd function with the mock interface
Run the command with a non-existent image argument
Check that there is an error and the error message is "image tag is required"
This test case enhances the test coverage of the GetPatchCmd function and ensures that it correctly handles non-existent image arguments.
Signed-off-by: Umair <58398786+Umair0343@users.noreply.github.com>
Pull Request Description:
Changes Made
Added a new test case TestParseSetArgs_InvalidKey in the config package to cover scenarios where an invalid key is provided in the set command arguments.
Test Case Details
Function Tested: TestParseSetArgs_InvalidKey
Test Objective: Ensures that the parseSetArgs function correctly handles the scenario where an invalid key is provided, returning an appropriate error message.
Test Input: Command arguments with an invalid key, e.g., invalidKey=value1.
Expected Output: The function should return an error message indicating that the provided key is unknown, along with the list of supported keys.
Motivation
This new test case enhances the test coverage for the parseSetArgs function, ensuring robust handling of invalid keys during the configuration setting process. By validating that the function produces the expected error message for such cases, we contribute to the overall reliability of the codebase. This addition further strengthens the testing suite for the config package, promoting code quality and correctness.
Signed-off-by: Umair <58398786+Umair0343@users.noreply.github.com>
Pull Request Description:
Changes Made
Added new test cases for different shell completions in the completion package to enhance test coverage.
New Test Cases
TestGetCompletionCmd_RunBashCompletionNotExpectedOutputs: Tests that the output for Bash completion does not match the specified unexpected outputs.
TestGetCompletionCmd_RunZshCompletionNotExpectedOutputs: Tests that the output for Zsh completion does not match the specified unexpected outputs.
TestGetCompletionCmd_RunFishCompletionNotExpectedOutputs: Tests that the output for Fish completion does not match the specified unexpected outputs.
TestGetCompletionCmd_RunPowerShellCompletionNotExpectedOutputs: Tests that the output for PowerShell completion does not match the specified unexpected outputs.
Motivation
These new test cases aim to further validate the behavior of the GetCompletionCmd function for various shell completions. By ensuring that the actual output does not match the unexpected outputs, we strengthen the reliability of the completion script generation for different shells.
These test cases enhance the robustness of the codebase and provide additional validation for the autocompletion script generation functionality.
Signed-off-by: Umair <58398786+Umair0343@users.noreply.github.com>
Wrote new tests for the printer package and refactored the CalculateMove
function to prevent potential out of bounds crash
Refactored the `addFix` function for better readability, understanding
and chaining method calls.
Used formatted string for logging.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
This PR focuses on adding unit tests for multiple packages in the
project. The main changes include:
- Addition of new tests for the 'printer' package in the
'core/pkg/resultshandling/printer' directory.
- New tests for the 'results' package in the
'core/pkg/resultshandling' directory.
- Addition of tests for the 'config' package in the
'httphandler/config' directory.
- New tests for the 'testutils' package in the 'internal/testutils'
directory.
- Addition of tests for the 'imagescan' package in the
'pkg/imagescan' directory.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Wrote new tests for the following packages
- operator
- patch
- scan
Also fixed potential crash in the RunE function of the image subcommand
in the scan package.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Wrote ne tsts for the following packages:
- completion
- config
- download
- fix
- list
Also addressed a potential crash in the compleition, download, and list
subcommands when no arguement was provided to the Args, RunE or Run
functions.
Updated `DownloadSupportCommands`, 'ListSupportActions' function to return sorted slice of
strings.
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
Signed-off-by: cbrom <kb.cbrom@gmail.com>
changed test input to clearly show its not a valid
Signed-off-by: cbrom <kb.cbrom@gmail.com>
added tests for valid json input to JSONDecoder function
Signed-off-by: cbrom <kb.cbrom@gmail.com>
check for specific error message instead of just error return
Signed-off-by: cbrom <kb.cbrom@gmail.com>
check for specific error message instead of just error return
Signed-off-by: cbrom <kb.cbrom@gmail.com>
package imports added
Signed-off-by: cbrom <kb.cbrom@gmail.com>
removed unnecessary mock json file
Signed-off-by: cbrom <kb.cbrom@gmail.com>
min function moved to kscloudapi.go
Signed-off-by: cbrom <kb.cbrom@gmail.com>
added necessary functions to make a post api call
Signed-off-by: cbrom <kb.cbrom@gmail.com>
getLatestVersion now uses KSCloudAPI functions
Signed-off-by: cbrom <kb.cbrom@gmail.com>
reverted moved function min back
Signed-off-by: cbrom <kb.cbrom@gmail.com>
removed unncessary functions and simplified post method
Signed-off-by: cbrom <kb.cbrom@gmail.com>
modified call to APIPostRequest
Signed-off-by: cbrom <kb.cbrom@gmail.com>
renamed HTTPPost request function and added httpClient param (for testing purposes)
Signed-off-by: cbrom <kb.cbrom@gmail.com>
changed function name call
Signed-off-by: cbrom <kb.cbrom@gmail.com>
removed HTTPPost function test
Signed-off-by: cbrom <kb.cbrom@gmail.com>
net/http imported
Signed-off-by: cbrom <kb.cbrom@gmail.com>
bytes import removed
Signed-off-by: cbrom <kb.cbrom@gmail.com>
test added for HTTPPost function
Signed-off-by: cbrom <kb.cbrom@gmail.com>
removed json decoder as it is not necessary anymore
Signed-off-by: cbrom <kb.cbrom@gmail.com>
removed HttpPost function
Signed-off-by: cbrom <kb.cbrom@gmail.com>
Wrote new tests for the following packages in the cmd package:
- completion
- config
* In addition to tests, updated the code for the `stringKeysToSlice`
to return the final string slice in sorted order of keys.
Added new MockIKubescape struct in the core/mocks package
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
1. Use time.Time for expiration to simplify expiration checks.
2. Added a stopChan and a Stop method to properly stop the invalidateTask goroutine instead of directly changing values
3. Used Ticker in invalidateTask for periodic expiration checks
4. Leak Prevention: The invalidateTask() loop checks the TTL value before continuing. If the TTL is zero, the goroutine exits gracefully, preventing a memory leak.
Signed-off-by: sulemaanhamza <sulemanhamza97@gmail.com>
Fix typo in error description
Bug fix where kubescape get policies from file
Signed-off-by: Mehdi Moussaif <m.moussaif42@gmail.com>
Missing '.json' extension when getting Framework Paths
Signed-off-by: Mehdi Moussaif <m.moussaif42@gmail.com>
Appropriate test case for FrameworksPaths
Bug fix where kubescape fails to read from frameworks local paths
Signed-off-by: Mehdi Moussaif <m.moussaif42@gmail.com>
Wrote new tests for the following files:
- controllink.go
- display.go
- fileutils.go
- getter/getpoliciesutils.go
- getter/utils.go
Signed-off-by: VaibhavMalik4187 <vaibhavmalik2018@gmail.com>
* add access key flag to the scan command
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* support triggering ns
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* Fixed json keys
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* get k8s config
Signed-off-by: David Wertenteil <dwertent@armosec.io>
---------
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* set cloud provider using nodes
* use scan metadata for scanning scope
* code cleanup
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* handle error
Signed-off-by: David Wertenteil <dwertent@armosec.io>
---------
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* print result to stdout when format argument specified
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* print pretty format to stdout if format is not specified
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* remove not relevant log
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
---------
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
Co-authored-by: rcohencyberarmor <rcohen@armosec.io>
* store scan results in storage
Signed-off-by: Amir Malka <amirm@armosec.io>
* store scan results in storage
Signed-off-by: Amir Malka <amirm@armosec.io>
* save resources in their namespaces, load namespace from env var, extend the config obj
Signed-off-by: Amir Malka <amirm@armosec.io>
* setting context name
Signed-off-by: Amir Malka <amirm@armosec.io>
* updated k8s-interface
Signed-off-by: Amir Malka <amirm@armosec.io>
* scanning a deleted resource
Signed-off-by: Amir Malka <amirm@armosec.io>
* cr changes
Signed-off-by: Amir Malka <amirm@armosec.io>
* cr changes
Signed-off-by: Amir Malka <amirm@armosec.io>
* fix
Signed-off-by: Amir Malka <amirm@armosec.io>
* remove unused constants
Signed-off-by: Amir Malka <amirm@armosec.io>
* use t.Setenv
Signed-off-by: Amir Malka <amirm@armosec.io>
* added tests for rbac triplet slugs
Signed-off-by: Amir Malka <amirm@armosec.io>
* updated namespace logic
Signed-off-by: Amir Malka <amirm@armosec.io>
* fix test
Signed-off-by: Amir Malka <amirm@armosec.io>
---------
Signed-off-by: Amir Malka <amirm@armosec.io>
* adding corrections to cmd
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* remove decorative line
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* wip: changed results indicator
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* replace status test with icons
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* print workloads in a different line
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* update display
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* deprecate commands
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* removed unused functions
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* fixed tests
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* update cloud provider detection
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* rename column name
Signed-off-by: David Wertenteil <dwertent@armosec.io>
---------
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* support scanning scope
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update white list
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* scope empty return control should tested
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update rego scope for system test
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update test + mock
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add comment
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update rego library
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update k8s-interface
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update opa utils - lots of file changes in this commit since armoapi-go bump up in opa-utils
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* move to temp k8s-interface - till PR in k8s-interface repo will approved
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update k8s-interface with released tag
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod in httphandler
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* support unified configuration
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* unitest adjustment
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* config-unified
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* CR corrections
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* remove system test till it will be merged
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add relevant system test
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* remove delete test
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* return config delete system test
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
---------
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
Co-authored-by: rcohencyberarmor <rcohen@armosec.io>
* Implementing container image name normalization built-in function for Rego
Signed-off-by: Ben <ben@armosec.io>
* updating go.mod t include docker/distribution
Signed-off-by: Ben <ben@armosec.io>
* fix test
Signed-off-by: Ben <ben@armosec.io>
---------
Signed-off-by: Ben <ben@armosec.io>
* support scanning scope
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update white list
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* scope empty return control should tested
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update rego scope for system test
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update test + mock
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add comment
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update rego library
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update k8s-interface
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update opa utils - lots of file changes in this commit since armoapi-go bump up in opa-utils
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* move to temp k8s-interface - till PR in k8s-interface repo will approved
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update k8s-interface with released tag
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go mod in httphandler
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* PR review corrections
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* change test name
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* scanning scope support for framework
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* test/mock adjustments after merge
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add more informative log to the user
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update go.mod and go.sum of the http handler
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* remove framework just scanning scope not matched to framework config scope
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add system tests to workflow
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* add system test to github workflow
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
---------
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
Signed-off-by: David Wertenteil <dwertent@armosec.io>
Co-authored-by: rcohencyberarmor <rcohen@armosec.io>
Co-authored-by: David Wertenteil <dwertent@armosec.io>
* code refactor
Signed-off-by: Amir Malka <amirm@armosec.io>
* use scaninfo object in resource handler
Signed-off-by: Amir Malka <amirm@armosec.io>
---------
Signed-off-by: Amir Malka <amirm@armosec.io>
This commit adds a CLI command and an associated package that scan
images for vulnerabilities.
Signed-off-by: Vlad Klokun <vklokun@protonmail.ch>
feat(imagescan): fail on exceeding the severity threshold
Signed-off-by: Vlad Klokun <vklokun@protonmail.ch>
* add cmd
Signed-off-by: Daniel Grunberger <danielgrunberger@armosec.io>
* support single workload scan
Signed-off-by: Amir Malka <amirm@armosec.io>
* fix conflict
Signed-off-by: Amir Malka <amirm@armosec.io>
* added unit tests
Signed-off-by: Amir Malka <amirm@armosec.io>
* added unit tests
Signed-off-by: Amir Malka <amirm@armosec.io>
* more refactoring
Signed-off-by: Amir Malka <amirm@armosec.io>
* add scanned workload reference to opasessionobj
Signed-off-by: Amir Malka <amirm@armosec.io>
* fix GetWorkloadParentKind
Signed-off-by: Amir Malka <amirm@armosec.io>
* remove namespace argument from pullSingleResource, using field selector instead
Signed-off-by: Amir Malka <amirm@armosec.io>
* removed designators (unused) field from PolicyIdentifier, and designators argument from GetResources function
Signed-off-by: Amir Malka <amirm@armosec.io>
* fix tests
Signed-off-by: Amir Malka <amirm@armosec.io>
* use ScanObject instead of workload identifier
Signed-off-by: Amir Malka <amirm@armosec.io>
* refactor logic after CR
Signed-off-by: Amir Malka <amirm@armosec.io>
---------
Signed-off-by: Daniel Grunberger <danielgrunberger@armosec.io>
Signed-off-by: Amir Malka <amirm@armosec.io>
Co-authored-by: Daniel Grunberger <danielgrunberger@armosec.io>
* add print in the cli to which version the kubescape was update
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
* update will suggest to our user to update by following kubescape installation guide
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
---------
Signed-off-by: rcohencyberarmor <rcohen@armosec.io>
Co-authored-by: rcohencyberarmor <rcohen@armosec.io>
External observers don’t need to be aware of the fact we need to
sanitize leading document separators in YAML files. This should be
hidden inside our public function - `ApplyFixToContent()`.
Signed-off-by: Vlad Klokun <vklokun@protonmail.ch>
Previously when there was a typo in a test file name, we silently
failed. This commit makes the test explicitly fail if a test data file
was not found.
Signed-off-by: Vlad Klokun <vklokun@protonmail.ch>
* control parallelism of opa rule processing by env var
Signed-off-by: Amir Malka <amirm@armosec.io>
* go 1.20
Signed-off-by: Amir Malka <amirm@armosec.io>
* update go.mod go.sum
Signed-off-by: Amir Malka <amirm@armosec.io>
---------
Signed-off-by: Amir Malka <amirm@armosec.io>
Also:
* declared scanner resources as an enum type
* replaced stdlib json, added uit tests for skipped resources
* unexported worker pool
* more unexported methods (i.e. everything that is not part of the interface)
* refact(core): clarified mock injection logic and added a few unit tests at the caller's (CLI init utils)
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
This PR factorizes the list of calls to the host-scanner API in a loop.
More godoc-friendly doc strings are added.
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
This parallelize the Process() portion of the OPA processor.
The main change is that called methods to evaluate a rule no longer
mutate the internal state of the opaprocessor and allocate maps (less
often, in larger chunks) that are merged at the end of the processing.
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* Interfaces are unchanged
* Deprecated: low-level API funcs marked for deprecation:
HttpPost, HttpGetter, HttpDelete (an augmented version of the KS Cloud
client will expose the post report API, which is currently the sole
use-case of low-level API)
* Doc: the package is now godoc-friendly
* Style & code layout:
* listed all exposed types via aliases, for clarity/less confusing
imports
* unexported private types
* factorized query param logic
* factorized type <-> JSON using generic func & io.Reader
* "utils" are now limited to a few common utility functions
* centralized hard-coded strings as (unexported) constants
* concision: use higher-level http definitions such as constants,
cookie methods, etc
* included type-safety guards to verify that interfaces are
actually implemented by the exported types
* Tests: existing test assertions are unchanged
* tests are beefed-up to assert proper authentication flow (token & cookie).
* added unit tests for utility methods
* Perf:
* unmarshalling API responses is now flowing without extraneous memory allocation via string representation
* request headers are now passed withot extraneous map allocation
* JSON operations are now fully supported by jsoniter (no longer use encoding/json)
* Changes in functionality:
* the client is now fully extensible with KSCloudOption
* use the option functor idiom to keep constructors short
* methods that used to mute errors (i.e. return nil, nil) now bubble up errors
* the captured cookie is now captured in full, not just its value
(other cookie parameters returned are stored)
* added a request/response dump option, for debugging
* added support for SubmitReport and retrieval of UI url's
* backported utm changes (reports use case)
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
* adding ks version
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* Initialize scanInfo
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* print if logger level is lower than warning
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* wip: scan default frameworks when scanning files
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* change print to log
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* wip: Add end-line after last log
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* wip: silent spinner when logger is warn
Signed-off-by: David Wertenteil <dwertent@armosec.io>
---------
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* Fixed HTML template
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* Adding HTML output format example
Signed-off-by: David Wertenteil <dwertent@armosec.io>
---------
Signed-off-by: David Wertenteil <dwertent@armosec.io>
* GitRegoStore moved to Regolibrary
* httphandler go mod
* update go.mod
* test old regostorlibrary
* restore gitRegoStore from regolibrary
* Update github.com/kubescape/regolibrary to ver 249
Signed-off-by: kooomix <eranm@armosec.io>
* update go mod
Signed-off-by: kooomix <eranm@armosec.io>
* print scan_control_id mesg
Signed-off-by: kooomix <eranm@armosec.io>
* Update regolibrary version - windows host fix
Signed-off-by: kooomix <eranm@armosec.io>
---------
Signed-off-by: kooomix <eranm@armosec.io>
Co-authored-by: David Wertenteil <dwertent@armosec.io>
This change refactors the TestApplyFixKeepsFormatting test to use
assert.Equalf so it will display a convenient diff between the expected
and actual fixing result.
This change:
- Changes test data naming convention to be lexicographically sortable
and have input and expected data side-by-side.
- Executes each test case in a separate run.
* feat: added support for ListControls and GetFrameworks
* perf: introduced jsoniter unmarshalling for faster decoding
* introduced stricted error handling & predefined errors:
* suppressed edge cases when a flaky value is returned instead of an error
* added full unit tests of LoadPolicy
Signed-off-by: Frederic BIDON <fredbi@yahoo.com>
* fixed flaky loop(cautils): loadpolicy getter
We should not inject pointers to the variable iterated over by the
"range" operator.
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* fixed more flaky pointers in loops (registryadaptors, opaprocessor)
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* fixed more flaky pointers in loops (resultshandling)
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* enabled golangci linter in CI
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* fixed linting issues with minimal linters config
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
* bump go version to 1.19
* English and typos
* Support AKS parser (#994)
* support GKE parser
* update go mod
* support GKE parser
* update go mod
* update k8s-interface pkg
* Added KS desgin.drawio
* revert k8s.io to v0.25.3
* ran go mod tidy
* update sign-up url
* [wip] Adding CreateAccount support
* revert to docs URL
* update opa-utils pkg
* Print attack tree (optional, with argument) (#997)
* Print attack tree with the argument
Signed-off-by: Frédéric BIDON <fredbi@yahoo.com>
Co-authored-by: Frédéric BIDON <frederic@oneconcern.com>
Co-authored-by: Frédéric BIDON <fredbi@yahoo.com>
Co-authored-by: Oshrat Nir <45561829+Oshratn@users.noreply.github.com>
Co-authored-by: Amir Malka <amirm@armosec.io>
Co-authored-by: David Wertenteil <dwertent@armosec.io>
Kubescape's main branch is `main`, any PR will be opened against the main branch.
### Opening a PR
When a user opens a PR, this will trigger some basic tests (units, license, etc.)
### Reviewing a PR
The reviewer/maintainer of a PR will decide whether the PR introduces changes that require running the E2E system tests. If so, the reviewer will add the `trigger-integration-test` label.
### Approving a PR
Once a maintainer approves the PR, if the `trigger-integration-test` label was added to the PR, the GitHub actions will trigger the system test. The PR will be merged only after the system tests passed successfully. If the label was not added, the PR can be merged.
### Merging a PR
The code is merged, no other actions are needed
## Release process
Every two weeks, we will create a new tag by bumping the minor version, this will create the release and publish the artifacts.
If we are introducing breaking changes, we will update the `major` version instead.
When we wish to push a hot-fix/feature within the two weeks, we will bump the `patch`.
### Creating a new tag
Every two weeks or upon the decision of the maintainers, a maintainer can create a tag.
The tag should look as follows: `v<A>.<B>.<C>-rc.D` (release candidate).
When creating a tag, GitHub will trigger the following actions:
1. Basic tests - unit tests, license, etc.
2. System tests (integration tests). If the tests fail, the actions will stop here.
3. Create a new tag: `v<A>.<B>.<C>` (same tag just without the `rc` suffix)
4. Create a release
5. Publish artifacts
6. Build and publish the docker image (this is meanwhile until we separate the microservice code from the LCI codebase)
## Additional Information
The "callers" have the alphabetic prefix and the "executes" have the numeric prefix
First, it is awesome that you are considering contributing to Kubescape! Contributing is important and fun and we welcome your efforts.
The Kubescape project manages this document in the central project repository.
When contributing, we categorize contributions into two:
* Small code changes or fixes, whose scope is limited to a single or two files
* Complex features and improvements, that are not limited
If you have a small change, feel free to fire up a Pull Request.
When planning a bigger change, please first discuss the change you wish to make via issue,
email, or any other method with the owners of this repository before making a change. Most likely your changes or features are great, but sometimes we might be already going in this direction (or the exact opposite ;-) ) and we don't want to waste your time.
Please note we have a code of conduct, please follow it in all your interactions with the project.
## Pull Request Process
1. Ensure any install or build dependencies are removed before the end of the layer when doing a
build.
2. Update the README.md with details of changes to the interface, this includes new environment
variables, exposed ports, useful file locations and container parameters.
3. Open Pull Request to `dev` branch - we test the component before merging into the `master` branch
4. We will merge the Pull Request once you have the sign-off.
## Code of Conduct
### Our Pledge
In the interest of fostering an open and welcoming environment, we as
contributors and maintainers pledge to make participation in our project and
our community a harassment-free experience for everyone, regardless of age, body
size, disability, ethnicity, gender identity and expression, level of experience,
nationality, personal appearance, race, religion, or sexual identity and
orientation.
### Our Standards
Examples of behavior that contributes to creating a positive environment
include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or
advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic
address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
We will distance those who constantly adhere to unacceptable behavior.
### Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable
behavior and are expected to take appropriate and fair corrective actions in
response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or
reject comments, commits, code, wiki edits, issues, and other contributions
that are not aligned to this Code of Conduct, or to ban temporarily or
permanently any contributor for other behaviors that they deem inappropriate,
threatening, offensive, or harmful.
### Scope
This Code of Conduct applies both within project spaces and in public spaces
when an individual is representing the project or its community. Examples of
representing a project or community include using an official project e-mail
address, posting via an official social media account, or acting as an appointed
representative at an online or offline event. Representation of a project may be
further defined and clarified by project maintainers.
### Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported by contacting the project team at [INSERT EMAIL ADDRESS]. All
complaints will be reviewed and investigated and will result in a response that
is deemed necessary and appropriate to the circumstances. The project team is
obligated to maintain confidentiality with regard to the reporter of an incident.
Further details of specific enforcement policies may be posted separately.
Project maintainers who do not follow or enforce the Code of Conduct in good
faith may face temporary or permanent repercussions as determined by other
members of the project's leadership.
### Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
available at [http://contributor-covenant.org/version/1/4][version]
Kubescape is an open-source Kubernetes security platform. A single pane of glass access to view risk analysis, security compliance, RBAC visualization, and image vulnerability scanning.
Kubescape scans Kubernetes clusters, YAML files, and Helm charts. It detects misconfigurations according to multiple frameworks (such as [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo/?utm_source=github&utm_medium=repository), [MITRE ATT&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/) and [CIS Benchmark](https://www.armosec.io/blog/cis-kubernetes-benchmark-framework-scanning-tools-comparison/?utm_source=github&utm_medium=repository)). Kubescape also helps you find software vulnerabilities, and RBAC (role-based-access-control) violations at early stages of the CI/CD pipeline. It calculates your risk score instantly and shows risk trends over time.
_Comprehensive Kubernetes Security from Development to Runtime_
Kubescape is one of the fastest-growing Kubernetes security tools among developers. It saves Kubernetes users and admins precious time, effort, and resources with its easy-to-use CLI interface, flexible output formats, and automated scanning capabilities.
Kubescape integrates natively with other DevOps tools, including Jenkins, CircleCI, Github workflows, Prometheus, and Slack. It supports multi-cloud Kubernetes deployments like EKS, GKE, and AKS.
Kubescape is an open-source Kubernetes security platform that provides comprehensive security coverage, from left to right across the entire development and deployment lifecycle. It offers hardening, posture management, and runtime security capabilities to ensure robust protection for Kubernetes environments. It saves Kubernetes users and admins precious time, effort, and resources.
</br>
Kubescape scans clusters, YAML files, and Helm charts. It detects misconfigurations according to multiple frameworks (including [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo/?utm_source=github&utm_medium=repository), [MITRE ATT&CK®](https://www.armosec.io/glossary/mitre-attck-framework/?utm_source=github&utm_medium=repository) and the [CIS Benchmark](https://www.armosec.io/blog/cis-kubernetes-benchmark-framework-scanning-tools-comparison/?utm_source=github&utm_medium=repository)).
# Kubescape CLI:
<img src="docs/demo.gif">
Kubescape was created by [ARMO](https://www.armosec.io/?utm_source=github&utm_medium=repository) and is a [Cloud Native Computing Foundation (CNCF) incubating project](https://www.cncf.io/projects/).
</br>
_Please [star ⭐](https://github.com/kubescape/kubescape/stargazers) the repo if you want us to continue developing and improving Kubescape! 😀_
## Demo
Kubescape has a command line tool that you can use to quickly get a report on the security posture of a Kubernetes cluster:
This script will automatically download the latest Kubescape CLI release and scan the Kubernetes cluster in your current kubectl context.
[Install on windows](#install-on-windows)
Learn more about:
[Install on macOS](#install-on-macos)
*[Installing the Kubescape CLI](https://kubescape.io/docs/install-cli/)
* [Running your first scan](https://kubescape.io/docs/scanning/)
* [Accepting risk with exceptions](https://kubescape.io/docs/accepting-risk/)
[Install on NixOS or Linux/macOS via nix](#install-on-nixos-or-with-nix-community)
_Did you know you can use Kubescape in all these places?_
## Run:
```sh
kubescape scan --enable-host-scan --verbose
```
<img src="docs/summary.png">
</br>
> Kubescape is an open source project. We welcome your feedback and ideas for improvement. We’re also aiming to collaborate with the Kubernetes community to help make the tests more robust and complete as Kubernetes develops.
### Continuous security monitoring with the Kubescape Operator
### Please [star ⭐](https://github.com/kubescape/kubescape/stargazers) the repo if you want us to continue developing and improving Kubescape 😀
As well as a CLI, Kubescape provides an in-cluster mode, which is installed via a Helm chart. Kubescape in-cluster provides extensive features such as continuous scanning, image vulnerability scanning, runtime analysis, network policy generation, and more. [Learn more about the Kubescape operator](https://kubescape.io/docs/operator/).
</br>
### Using Kubescape as a GitHub Action
# Being a part of the team
Kubescape can be used as a GitHub Action. This is a great way to integrate Kubescape into your CI/CD pipeline. You can find the Kubescape GitHub Action in the [GitHub Action marketplace](https://github.com/marketplace/actions/kubescape).
## Under the hood
Kubescape uses [Open Policy Agent](https://github.com/open-policy-agent/opa) to verify Kubernetes objects against [a library of posture controls](https://github.com/kubescape/regolibrary).
For image scanning, it uses [Grype](https://github.com/anchore/grype).
For image patching, it uses [Copacetic](https://github.com/project-copacetic/copacetic).
For eBPF, it uses [Inspektor Gadget](https://github.com/inspektor-gadget)
By default, CLI scan results are printed in a console-friendly manner, but they can be:
* exported to JSON, junit XML or SARIF
* rendered to HTML or PDF
* submitted to a [cloud service](docs/providers.md)
You are in vited to our community! We are excited about this project and want to return the love we get.
We hold community meetings on [Zoom](https://us02web.zoom.us/j/84020231442) on the first Tuesday of every month at 14:00 GMT! :sunglasses:
Kubescape is an open source project. We welcome your feedback and ideas for improvement. We are part of the CNCF community and are evolving Kubescape in sync with the security needs of Kubernetes users. To learn more about where Kubescape is heading, please check out our [ROADMAP](https://github.com/kubescape/project-governance/blob/main/ROADMAP.md).
Please make sure that you follow our [Code Of Conduct](https://github.com/kubescape/kubescape/blob/master/CODE_OF_CONDUCT.md).
If you feel inspired to contribute to Kubescape, check out our [CONTRIBUTING](https://github.com/kubescape/project-governance/blob/main/CONTRIBUTING.md) file to learn how. You can find the issues we are working on (triage to development) on the [Kubescaping board](https://github.com/orgs/kubescape/projects/4/views/1)
## Contributions
Want to discuss something? Have an issue? [Want to contribute?](https://github.com/kubescape/kubescape/blob/master/CONTRIBUTING.md)
* Feel free to pick a task from the [board](https://github.com/orgs/kubescape/projects/4) or suggest a feature of your own.
* Open an issue on the board. We aim to respond to all issues within 48 hours.
* [Join the CNCF Slack](https://slack.cncf.io/) and then our [users](https://cloud-native.slack.com/archives/C04EY3ZF9GE) or [developers](https://cloud-native.slack.com/archives/C04GY6H082K) channel.
* Feel free to pick a task from the [issues](https://github.com/kubescape/kubescape/issues?q=is%3Aissue+is%3Aopen+label%3A%22open+for+contribution%22), [roadmap](docs/roadmap.md) or suggest a feature of your own. [Contact us](MAINTAINERS.md) directly for more information :)
* [Open an issue](https://github.com/kubescape/kubescape/issues/new/choose) , we are trying to respond within 48 hours
* [Join us](https://discord.com/invite/WKZRaCtBxN) in the discussion on our discord server!
The Kubescape project follows the [CNCF Code of Conduct](https://github.com/cncf/foundation/blob/master/code-of-conduct.md).
Direct issues installing `kubescape` via `nix` through the channels mentioned [here](https://nixos.wiki/wiki/Support)
You can use `nix` on Linux or macOS and on other platforms unofficially.
Try it out in an ephemeral shell: `nix-shell -p kubescape`
Install declarative as usual
NixOS:
```nix
# your other config ...
environment.systemPackages = with pkgs; [
# your other packages ...
kubescape
];
```
home-manager:
```nix
# your other config ...
home.packages = with pkgs; [
# your other packages ...
kubescape
];
```
Or to your profile (not preferred): `nix-env --install -A nixpkgs.kubescape`
</details>
## Usage & Examples
### Examples
#### Scan a running Kubernetes cluster
```
kubescape scan --enable-host-scan --verbose
```
> Read [here](https://hub.armosec.io/docs/host-sensor?utm_source=github&utm_medium=repository) more about the `enable-host-scan` flag
#### Scan a running Kubernetes cluster with [`nsa`](https://www.nsa.gov/Press-Room/News-Highlights/Article/Article/2716980/nsa-cisa-release-kubernetes-hardening-guidance/) framework
```
kubescape scan framework nsa
```
#### Scan a running Kubernetes cluster with [`MITRE ATT&CK®`](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/) framework
```
kubescape scan framework mitre
```
#### Scan a running Kubernetes cluster with a specific control using the control name or control ID. [List of controls](https://hub.armosec.io/docs/controls?utm_source=github&utm_medium=repository)
<details><summary> Pre-programmed actions executed by the playground </summary>
* Clone the official GitHub repository of `Kubescape`.
* [Automate the build process on Linux](https://github.com/kubescape/kubescape#build-on-linuxmacos)
* The entire process involves executing multiple commands in order and it takes around 5-6 minutes to execute them all.
</details>
<details>
<summary>Instructions to use the playground</summary>
* Apply changes you wish to make to the Kubescape directory using text editors like `Vim`.
* [Build on Linux](https://github.com/kubescape/kubescape#build-on-linuxmacos)
* Now, you can use Kubescape like a regular user. Instead of using `kubescape`, use `./kubescape`. Make sure you are in the Kubescape directory because the command will execute the binary named `kubescape` in `kubescape directory`)
</details>
## VS Code configuration samples
You can use the sample files below to setup your VS Code environment for building and debugging purposes.
<details><summary>.vscode/settings.json</summary>
```json5
// .vscode/settings.json
{
"go.testTags": "static",
"go.buildTags": "static",
"go.toolsEnvVars": {
"CGO_ENABLED": "1"
}
}
```
</details>
<details><summary>.vscode/launch.json</summary>
```json5
// .vscode/launch.json
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Package",
"type": "go",
"request": "launch",
"mode": "auto",
"program": "${workspaceFolder}/main.go",
"args": [
"scan",
"--logger",
"debug"
],
"buildFlags": "-tags=static"
}
]
}
```
</details>
# Under the hood
## Technology
Kubescape is based on the [OPA engine](https://github.com/open-policy-agent/opa) and ARMO's posture controls.
The tools retrieve Kubernetes objects from the API server and runs a set of [Rego snippets](https://www.openpolicyagent.org/docs/latest/policy-language/) developed by [ARMO](https://www.armosec.io?utm_source=github&utm_medium=repository).
The results by default are printed in a "console friendly" manner, but they can be retrieved in JSON format for further processing.
Kubescape is an open source project, we welcome your feedback and ideas for improvement. We are part of the Kubernetes community and aim to make the tests more robust and complete as Kubernetes develops.
Kubescape changes are tracked on the [release](https://github.com/kubescape/kubescape/releases) page.
## License
Copyright 2021-2024, the Kubescape Authors. All rights reserved. Kubescape is released under the Apache 2.0 license. See the [LICENSE](LICENSE) file for details.
Kubescape is a [Cloud Native Computing Foundation (CNCF) incubating project](https://www.cncf.io/projects/kubescape/) and was contributed by [ARMO](https://www.armosec.io/?utm_source=github&utm_medium=repository).
Short:"Delete configurations in Kubescape SaaS version",
Long:``,
Run:func(cmd*cobra.Command,args[]string){
},
}
deleteCmd.PersistentFlags().StringVarP(&deleteInfo.Credentials.Account,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
deleteCmd.PersistentFlags().StringVarP(&deleteInfo.Credentials.ClientID,"client-id","","","Kubescape SaaS client ID. Default will load client ID from cache, read more - https://hub.armosec.io/docs/authentication")
deleteCmd.PersistentFlags().StringVarP(&deleteInfo.Credentials.SecretKey,"secret-key","","","Kubescape SaaS secret key. Default will load secret key from cache, read more - https://hub.armosec.io/docs/authentication")
downloadCmd.PersistentFlags().StringVarP(&downloadInfo.Credentials.Account,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
downloadCmd.PersistentFlags().StringVarP(&downloadInfo.Credentials.ClientID,"client-id","","","Kubescape SaaS client ID. Default will load client ID from cache, read more - https://hub.armosec.io/docs/authentication")
downloadCmd.PersistentFlags().StringVarP(&downloadInfo.Credentials.SecretKey,"secret-key","","","Kubescape SaaS secret key. Default will load secret key from cache, read more - https://hub.armosec.io/docs/authentication")
downloadCmd.PersistentFlags().StringVarP(&downloadInfo.AccountID,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
downloadCmd.PersistentFlags().StringVarP(&downloadInfo.AccessKey,"access-key","","","Kubescape SaaS access key. Default will load access key from cache")
downloadCmd.Flags().StringVarP(&downloadInfo.Path,"output","o","","Output file. If not specified, will save in `~/.kubescape/<policy name>.json`")
Short:"Propose a fix for the misconfiguration found when scanning Kubernetes manifest files",
Long:``,
Example:fixCmdExamples,
RunE:func(cmd*cobra.Command,args[]string)error{
iflen(args)<1{
returnerrors.New("report output file is required")
}
fixInfo.ReportFile=args[0]
returnks.Fix(&fixInfo)
},
}
fixCmd.PersistentFlags().BoolVar(&fixInfo.NoConfirm,"no-confirm",false,"No confirmation will be given to the user before applying the fix (default false)")
fixCmd.PersistentFlags().BoolVar(&fixInfo.DryRun,"dry-run",false,"No changes will be applied (default false)")
fixCmd.PersistentFlags().BoolVar(&fixInfo.SkipUserValues,"skip-user-values",true,"Changes which involve user-defined values will be skipped")
listCmd.PersistentFlags().StringVarP(&listPolicies.Credentials.Account,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
listCmd.PersistentFlags().StringVarP(&listPolicies.Credentials.ClientID,"client-id","","","Kubescape SaaS client ID. Default will load client ID from cache, read more - https://hub.armosec.io/docs/authentication")
listCmd.PersistentFlags().StringVarP(&listPolicies.Credentials.SecretKey,"secret-key","","","Kubescape SaaS secret key. Default will load secret key from cache, read more - https://hub.armosec.io/docs/authentication")
listCmd.PersistentFlags().StringVarP(&listPolicies.AccountID,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
listCmd.PersistentFlags().StringVarP(&listPolicies.AccessKey,"access-key","","","Kubescape SaaS access key. Default will load access key from cache")
logger.L().Start("Kubescape Operator Triggering for configuration scanning")
_,err=operatorAdapter.OperatorScan()
iferr!=nil{
logger.L().StopError("Failed to triggering Kubescape Operator for configuration scanning",helpers.Error(err))
returnerr
}
logger.L().StopSuccess("Triggered Kubescape Operator for configuration scanning")
returnnil
},
}
configScanInfo:=&cautils.ConfigScanInfo{}
operatorInfo.OperatorScanInfo=configScanInfo
configCmd.PersistentFlags().StringSliceVar(&configScanInfo.IncludedNamespaces,"include-namespaces",nil,"scan specific namespaces. e.g: --include-namespaces ns-a,ns-b")
configCmd.PersistentFlags().StringSliceVar(&configScanInfo.ExcludedNamespaces,"exclude-namespaces",nil,"Namespaces to exclude from scanning. e.g: --exclude-namespaces ns-a,ns-b. Notice, when running with `exclude-namespace` kubescape does not scan cluster-scoped objects.")
configCmd.PersistentFlags().StringSliceVar(&configScanInfo.Frameworks,"frameworks",nil,"Load frameworks for configuration scanning")
configCmd.PersistentFlags().BoolVarP(&configScanInfo.HostScanner,"enable-host-scan","",false,"Deploy Kubescape host-sensor daemonset in the scanned cluster. Deleting it right after we collecting the data. Required to collect valuable data from cluster nodes for certain controls. Yaml file: https://github.com/kubescape/kubescape/blob/master/core/pkg/hostsensorutils/hostsensor.yaml")
returnerrors.New(fmt.Sprintf("For the operator sub-command, only %s and %s are supported. Refer to the examples above.",vulnerabilitiesSubCommand,configurationsSubCommand))
}
returnnil
},
}
operatorCmd.PersistentFlags().StringVar(&operatorInfo.Namespace,"namespace","kubescape","namespace of the Kubescape Operator")
expectedErrorMessage="For the operator sub-command, only "+vulnerabilitiesSubCommand+" and "+configurationsSubCommand+" are supported. Refer to the examples above."
logger.L().Start("Triggering the Kubescape Operator for vulnerability scanning")
_,err=operatorAdapter.OperatorScan()
iferr!=nil{
logger.L().StopError("Failed to trigger the Kubescape Operator for vulnerability scanning",helpers.Error(err))
returnerr
}
logger.L().StopSuccess("Triggered Kubescape Operator for vulnerability scanning. View the scanning results once they are ready using the following command: \"kubectl get vulnerabilitysummaries\"")
The patch command is used for patching container images with vulnerabilities.
It uses [copa](https://github.com/project-copacetic/copacetic) and [buildkit](https://github.com/moby/buildkit) under the hood for patching the container images, and [grype](https://github.com/anchore/grype) as the engine for scanning the images (at the moment).
## Usage
```bash
kubescape patch --image <image-name> [flags]
```
The patch command can be run in 2 ways:
1.**With sudo privileges**
You will need to start `buildkitd` if it is not already running
* Run with '--verbose'/'-v' flag for detailed vulnerabilities view
* Install Kubescape in your cluster for continuous monitoring and a full vulnerability report: https://github.com/kubescape/helm-charts/tree/main/charts/kubescape-cloud-operator
```
## Limitations
- The patch command can only fix OS-level vulnerability. It cannot fix application-level vulnerabilities. This is a limitation of copa. The reason behind this is that application level vulnerabilities are best suited to be fixed by the developers of the application.
Hence, this is not really a limitation but a design decision.
- No support for windows containers given the dependency on buildkit.
patchCmd.PersistentFlags().StringVarP(&patchInfo.Image,"image","i","","Application image name and tag to patch")
patchCmd.PersistentFlags().StringVarP(&patchInfo.PatchedImageTag,"tag","t","","Tag for the patched image. Defaults to '<image-tag>-patched' ")
patchCmd.PersistentFlags().StringVarP(&patchInfo.BuildkitAddress,"address","a","unix:///run/buildkit/buildkitd.sock","Address of buildkitd service, defaults to local buildkitd.sock")
patchCmd.PersistentFlags().DurationVar(&patchInfo.Timeout,"timeout",5*time.Minute,"Timeout for the operation, defaults to '5m'")
patchCmd.PersistentFlags().BoolVar(&patchInfo.IgnoreError,"ignore-errors",false,"Ignore errors and continue patching other images. Default to false")
patchCmd.PersistentFlags().StringVarP(&patchInfo.Username,"username","u","","Username for registry login")
patchCmd.PersistentFlags().StringVarP(&patchInfo.Password,"password","p","","Password for registry login")
patchCmd.PersistentFlags().StringVarP(&scanInfo.Output,"output","o","","Output file. Print output to file and not stdout")
patchCmd.PersistentFlags().BoolVarP(&scanInfo.VerboseMode,"verbose","v",false,"Display full report. Default to false")
patchCmd.PersistentFlags().StringVarP(&scanInfo.FailThresholdSeverity,"severity-threshold","s","","Severity threshold is the severity of a vulnerability at which the command fails and returns exit code 1")
returnpatchCmd
}
// validateImagePatchInfo validates the image patch info for the `patch` command
rootCmd.PersistentFlags().StringVar(&rootInfo.DiscoveryServerURL,"server","","Backend discovery server URL")
rootCmd.PersistentFlags().MarkDeprecated("environment","'environment' is no longer supported, Use 'server' instead. Feel free to contact the Kubescape maintainers for more information.")
rootCmd.PersistentFlags().MarkDeprecated("env","'env' is no longer supported, Use 'server' instead. Feel free to contact the Kubescape maintainers for more information.")
constenvFlagUsage="Send report results to specific URL. Format:<ReportReceiver>,<Backend>,<Frontend>.\n\t\tExample:report.armo.cloud,api.armo.cloud,portal.armo.cloud"
funcinitLogger(){
logger.DisableColor(rootInfo.DisableColor)
logger.EnableColor(rootInfo.EnableColor)
ifrootInfo.LoggerName==""{
ifl:=os.Getenv("KS_LOGGER_NAME");l!=""{
rootInfo.LoggerName=l
}else{
ifisatty.IsTerminal(os.Stdout.Fd()){
rootInfo.LoggerName="pretty"
rootInfo.LoggerName=iconlogger.LoggerName
}else{
rootInfo.LoggerName="zap"
rootInfo.LoggerName=zaplogger.LoggerName
}
}
}
logger.InitLogger(rootInfo.LoggerName)
}
funcinitLoggerLevel(){
ifrootInfo.Logger==helpers.InfoLevel.String(){
}elseifl:=os.Getenv("KS_LOGGER");l!=""{
@@ -56,35 +56,51 @@ func initCacheDir() {
logger.L().Debug("cache dir updated",helpers.String("path",getter.DefaultLocalStore))
logger.L().Fatal("failed to get services from server",helpers.Error(err),helpers.String("server",rootInfo.DiscoveryServerURL))
return
}
logger.L().Debug("configuring service discovery URLs",helpers.String("cloudAPIURL",services.GetApiServerUrl()),helpers.String("cloudReportURL",services.GetReportReceiverHttpUrl()))
assert.Equal(t,fmt.Sprintf("The framework you wish to use. Run '%[1]s list frameworks' for the list of supported frameworks",cautils.ExecName()),cmd.Short)
assert.Equal(t,frameworkExample,cmd.Example)
err:=cmd.Args(&cobra.Command{},[]string{})
expectedErrorMessage:="requires at least one framework name"
scanCmd.PersistentFlags().StringVarP(&scanInfo.Credentials.Account,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
// scanCmd.PersistentFlags().BoolVar(&scanInfo.CreateAccount, "create-account", false, "Create a Kubescape SaaS account ID account ID is not found in cache. After creating the account, the account ID will be saved in cache. In addition, the scanning results will be uploaded to the Kubescape SaaS")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Credentials.ClientID,"client-id","","","Kubescape SaaS client ID. Default will load client ID from cache, read more - https://hub.armosec.io/docs/authentication")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Credentials.SecretKey,"secret-key","","","Kubescape SaaS secret key. Default will load secret key from cache, read more - https://hub.armosec.io/docs/authentication")
scanCmd.PersistentFlags().StringVarP(&scanInfo.KubeContext,"kube-context","","","Kube context. Default will use the current-context")
scanInfo.TriggeredByCLI=true
scanCmd.PersistentFlags().StringVarP(&scanInfo.AccountID,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
scanCmd.PersistentFlags().StringVarP(&scanInfo.AccessKey,"access-key","","","Kubescape SaaS access key. Default will load access key from cache")
scanCmd.PersistentFlags().StringVar(&scanInfo.ControlsInputs,"controls-config","","Path to an controls-config obj. If not set will download controls-config from ARMO management portal")
scanCmd.PersistentFlags().StringVar(&scanInfo.UseExceptions,"exceptions","","Path to an exceptions obj. If not set will download exceptions from ARMO management portal")
scanCmd.PersistentFlags().StringVar(&scanInfo.UseArtifactsFrom,"use-artifacts-from","","Load artifacts from local directory. If not used will download them")
scanCmd.PersistentFlags().StringVarP(&scanInfo.ExcludedNamespaces,"exclude-namespaces","e","","Namespaces to exclude from scanning. Notice, when running with `exclude-namespace` kubescape does not scan cluster-scoped objects.")
scanCmd.PersistentFlags().StringVarP(&scanInfo.ExcludedNamespaces,"exclude-namespaces","e","","Namespaces to exclude from scanning. e.g: --exclude-namespaces ns-a,ns-b. Notice, when running with `exclude-namespace` kubescape does not scan cluster-scoped objects.")
scanCmd.PersistentFlags().Float32VarP(&scanInfo.FailThreshold,"fail-threshold","t",100,"Failure threshold is the percent above which the command fails and returns exit code 1")
scanCmd.PersistentFlags().Float32VarP(&scanInfo.ComplianceThreshold,"compliance-threshold","",0,"Compliance threshold is the percent below which the command fails and returns exit code 1")
scanCmd.PersistentFlags().StringVar(&scanInfo.FailThresholdSeverity,"severity-threshold","","Severity threshold is the severity of failed controls at which the command fails and returns exit code 1")
scanCmd.PersistentFlags().StringVar(&scanInfo.IncludeNamespaces,"include-namespaces","","scan specific namespaces. e.g: --include-namespaces ns-a,ns-b")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.Local,"keep-local","",false,"If you do not want your Kubescape results reported to configured backend.")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Output,"output","o","","Output file. Print output to file and not stdout")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.VerboseMode,"verbose","v",false,"Display all of the input resources and not only failed resources")
scanCmd.PersistentFlags().StringVar(&scanInfo.View,"view",string(cautils.ResourceViewType),fmt.Sprintf("View results based on the %s/%s. default is --view=%s",cautils.ResourceViewType,cautils.ControlViewType,cautils.ResourceViewType))
scanCmd.PersistentFlags().StringVar(&scanInfo.View,"view",string(cautils.SecurityViewType),fmt.Sprintf("View results based on the %s/%s/%s. default is --view=%s",cautils.ResourceViewType,cautils.ControlViewType,cautils.SecurityViewType,cautils.SecurityViewType))
scanCmd.PersistentFlags().BoolVar(&scanInfo.UseDefault,"use-default",false,"Load local policy object from default path. If not used will download latest")
scanCmd.PersistentFlags().StringSliceVar(&scanInfo.UseFrom,"use-from",nil,"Load local policy object from specified path. If not used will download latest")
scanCmd.PersistentFlags().StringVar(&scanInfo.HostSensorYamlPath,"host-scan-yaml","","Override default host scanner DaemonSet. Use this flag cautiously")
scanCmd.PersistentFlags().StringVar(&scanInfo.FormatVersion,"format-version","v1","Output object can be different between versions, this is for maintaining backward and forward compatibility. Supported:'v1'/'v2'")
scanCmd.PersistentFlags().StringVar(&scanInfo.FormatVersion,"format-version","v2","Output object can be different between versions, this is for maintaining backward and forward compatibility. Supported:'v1'/'v2'")
scanCmd.PersistentFlags().StringVar(&scanInfo.CustomClusterName,"cluster-name","","Set the custom name of the cluster. Not same as the kube-context flag")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.Submit,"submit","",false,"Submit the scan results to Kubescape SaaS where you can see the results in a user-friendly UI, choose your preferred compliance framework, check risk results history and trends, manage exceptions, get remediation recommendations and much more. By default the results are not submitted")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.OmitRawResources,"omit-raw-resources","",false,"Omit raw resources from the output. By default the raw resources are included in the output")
scanCmd.PersistentFlags().BoolVarP(&scanInfo.EnableRegoPrint,"enable-rego-prints","",false,"Enable sending to rego prints to the logs (use with debug log level: -l debug)")
scanCmd.PersistentFlags().MarkDeprecated("silent","use '--logger' flag instead. Flag will be removed at 1.May.2022")
scanCmd.PersistentFlags().MarkDeprecated("fail-threshold","use '--compliance-threshold' flag instead. Flag will be removed at 1.Dec.2023")
scanCmd.PersistentFlags().MarkDeprecated("create-account","Create account is no longer supported. In case of a missing Account ID and a configured backend server, a new account id will be generated automatically by Kubescape. Feel free to contact the Kubescape maintainers for more information.")
// hidden flags
scanCmd.PersistentFlags().MarkHidden("host-scan-yaml")// this flag should be used very cautiously. We prefer users will not use it at all unless the DaemonSet can not run pods on the nodes
hostF:=scanCmd.PersistentFlags().VarPF(&scanInfo.HostSensorEnabled,"enable-host-scan","","Deploy Kubescape host-sensor daemonset in the scanned cluster. Deleting it right after we collecting the data. Required to collect valuable data from cluster nodes for certain controls. Yaml file: https://github.com/kubescape/kubescape/blob/master/core/pkg/hostsensorutils/hostsensor.yaml")
scanCmd.PersistentFlags().MarkDeprecated("enable-host-scan","To activate the host scanner capability, proceed with the installation of the kubescape operator chart found here: https://github.com/kubescape/helm-charts/tree/main/charts/kubescape-operator. The flag will be removed at 1.Dec.2023")
scanCmd.PersistentFlags().MarkHidden("host-scan-yaml")// this flag should be used very cautiously. We prefer users will not use it at all unless the DaemonSet can not run pods on the nodes
scanCmd.PersistentFlags().MarkDeprecated("host-scan-yaml","To activate the host scanner capability, proceed with the installation of the kubescape operator chart found here: https://github.com/kubescape/helm-charts/tree/main/charts/kubescape-operator. The flag will be removed at 1.Dec.2023")
workloadCmd.PersistentFlags().StringVarP(&namespace,"namespace","n","","Namespace of the workload. Default will be empty.")
workloadCmd.PersistentFlags().StringVar(&scanInfo.FilePath,"file-path","","Path to the workload file.")
workloadCmd.PersistentFlags().StringVar(&scanInfo.ChartPath,"chart-path","","Path to the helm chart the workload is part of. Must be used with --file-path.")
resultsCmd.PersistentFlags().StringVar(&formatVersion,"format-version","v1","Output object can be differnet between versions, this is for maintaining backward and forward compatibility. Supported:'v1'/'v2'")
Short:"Submit an object to the Kubescape SaaS version",
Long:``,
Example:submitCmdExamples,
Run:func(cmd*cobra.Command,args[]string){
},
}
submitCmd.PersistentFlags().StringVarP(&submitInfo.Credentials.Account,"account","","","Kubescape SaaS account ID. Default will load account ID from cache")
submitCmd.PersistentFlags().StringVarP(&submitInfo.Credentials.ClientID,"client-id","","","Kubescape SaaS client ID. Default will load client ID from cache, read more - https://hub.armosec.io/docs/authentication")
submitCmd.PersistentFlags().StringVarP(&submitInfo.Credentials.SecretKey,"secret-key","","","Kubescape SaaS secret key. Default will load secret key from cache, read more - https://hub.armosec.io/docs/authentication")
fmt.Printf("Version %s is available. Please refer to our installation documentation: %s\n",versioncheck.LatestReleaseVersion,installationLink)
}
returnnil
},
Some files were not shown because too many files have changed in this diff
Show More
Reference in New Issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.