Compare commits

..

57 Commits

Author SHA1 Message Date
Rotem Refael
033e8f6b44 Merge pull request #346 from armosec/dev
returning rbac submit code + fix crash
2022-01-24 12:40:33 +02:00
Ben Hirschberg
bef40f0e6c Merge pull request #344 from slashben/dev
returning RBAC submit table
2022-01-24 09:13:28 +02:00
Ben Hirschberg
aa2f69125f returning rbac submit code 2022-01-24 09:12:13 +02:00
Ben Hirschberg
d30f3960a7 Merge pull request #341 from slashben/dev
fixing the crash around submit rbac
2022-01-23 21:28:10 +02:00
Ben Hirschberg
5f43da94ba fixing the crash around submit rbac 2022-01-23 20:17:03 +02:00
Rotem Refael
2aa8a0c935 Merge pull request #340 from Anthirian/dev
Fix typo in namespace
2022-01-23 13:43:42 +02:00
Ben Hirschberg
c02f8c6cb5 Merge pull request #338 from vfarcic/dev
Video
2022-01-23 08:18:44 +02:00
Geert Smelt
aa0be474e2 Fix typo in namespace 2022-01-21 15:40:00 +01:00
Viktor Farcic
c0161c9b33 Video 2022-01-20 19:54:57 +01:00
Rotem Refael
514da1e2db Merge pull request #332 from armosec/dev
Emergency fix: checking kube context before use
2022-01-19 16:53:14 +02:00
Ben Hirschberg
75dfceb5da Merge pull request #331 from slashben/dev
checking if local context exists before using
2022-01-19 16:38:22 +02:00
Ben Hirschberg
1ae76b4377 checking if context exists 2022-01-19 16:37:32 +02:00
Rotem Refael
b6f90cba8e Merge pull request #330 from armosec/dev
New kubescape major version
2022-01-19 15:21:52 +02:00
rrefael
62af441a1d Increase release & tag to major 2022-01-19 09:19:16 +02:00
Rotem Refael
228b8957d3 Merge pull request #317 from armosec/report-refactor
- Support report v2 (pagination)
- Scan control only once
- Support download of exceptions,control-configuration,artifacts -> kubescape download
- Support listing frameworks and controls -> kubescape list
- Adding scan framework all for scanning yaml files
- Scan other kubernetes contexts by adding the --kube-context flag
2022-01-18 21:02:56 +02:00
YiscahLevySilas1
b4ce999ab3 Merge pull request #324 from YiscahLevySilas1/dev
added download + load artifacts to readme
2022-01-18 18:02:34 +02:00
yiscah
cc06a414fe added examples of download + load artifacts 2022-01-18 17:50:28 +02:00
YiscahLevySilas1
d3c37c4e5f Merge branch 'armosec:dev' into dev 2022-01-18 17:30:36 +02:00
YiscahLevySilas1
3b448b62b1 Merge pull request #323 from YiscahLevySilas1/dev
support load artifacts from local path
2022-01-18 17:28:08 +02:00
YiscahLevySilas1
6a3f5658b1 Merge branch 'report-refactor' into dev 2022-01-18 17:19:03 +02:00
yiscah
f65e791522 fix parsing local path to artifacts 2022-01-18 17:01:53 +02:00
yiscah
d91304f9ad setUseArtifactsFrom only when flag is set 2022-01-18 16:32:01 +02:00
yiscah
61ce00108e fixed download to local path 2022-01-18 15:29:35 +02:00
Ben Hirschberg
a4eb773eee Merge pull request #322 from slashben/dev
Adding examples for cloud integrations
2022-01-18 15:05:47 +02:00
Ben Hirschberg
cfc69f5a0f adding access to container registry 2022-01-18 14:41:07 +02:00
Ben Hirschberg
a44823c3ed example cloud integration scripts 2022-01-17 13:55:43 +02:00
Ben Hirschberg
8a166e5ba5 typo fix 2022-01-17 11:54:02 +02:00
rrefael
9a7aeff870 update overview text- README 2022-01-16 15:40:34 +02:00
Lior Alafi
cb3bdb9df2 supporting both structures for score calculation 2022-01-14 17:54:39 +02:00
rrefael
0be8d57eaa add --enable-host-scan flag 2022-01-13 15:44:21 +02:00
dwertent
79b9cbf1d6 Merge branch 'report-refactor' 2022-01-13 15:16:15 +02:00
dwertent
500df8737e send small clusters once 2022-01-13 15:03:23 +02:00
David Wertenteil
b8acbd1bee fixed flag and cloud env support 2022-01-13 14:19:26 +02:00
dwertent
0bde8a65ba fixed context flag 2022-01-13 14:16:36 +02:00
dwertent
d2884b8936 update failure message 2022-01-13 13:07:29 +02:00
dwertent
e692359b47 Merge remote-tracking branch 'dwertent/master' into report-refactor 2022-01-13 12:52:34 +02:00
dwertent
473746eab0 merged with Daniels branch 2022-01-13 12:50:50 +02:00
dwertent
050878cbd6 Merge remote-tracking branch 'dwertent/master' into report-refactor 2022-01-13 11:48:13 +02:00
dwertent
e100f18bb0 fixed tests 2022-01-13 11:44:46 +02:00
dwertent
05c82fc166 Merge remote-tracking branch 'dwertent/master' into dev 2022-01-13 11:36:15 +02:00
dwertent
839c3e261f swap result and resource 2022-01-13 11:04:09 +02:00
Bezbran
8656715753 Merge pull request #314 from alegrey91/master
move kube-host-sensor manifest to indipendent yaml file with embed capability
2022-01-12 09:39:26 +02:00
Rotem Refael
d3bdbf31ac Merge pull request #315 from armosec/dev
Typo fixes
Update Kubescape logo
Adding contributors

Issues:
- Closes Spelling error Namescape should be Namespace #296
- Closes Add contributors to Readme #307
2022-01-11 09:58:36 +02:00
yiscah
995f615b10 support load artifacts from local path 2022-01-10 20:00:42 +02:00
alegrey91
392625b774 style(host-sensor): move kube-host-sensor manifest to indipendent yaml file 2022-01-10 18:39:06 +01:00
Ben Hirschberg
3f6cbd57b2 Merge pull request #311 from saiyam1814/patch-1
Adding Kubescape katacoda playground
2022-01-08 18:16:50 +02:00
Saiyam Pathak
2c9524ed45 Adding Kubescape katacoda playground 2022-01-08 19:21:33 +05:30
Ben Hirschberg
384922680a Merge pull request #309 from saiyam1814/master
Adding Contributors
2022-01-07 15:41:53 +02:00
David Wertenteil
d2e9f8f4f8 Fixes #296 Spelling error Namescape should be Namespace 2022-01-07 14:25:24 +02:00
Saiyam Pathak
b4f10f854e Adding contributors 2022-01-07 11:27:32 +05:30
Clint Modien
8ce64d2a7f Fixes #296 Spelling error Namescape should be Namespace 2022-01-06 09:45:11 -08:00
Ben Hirschberg
2bb612ca3f Merge pull request #303 from armosec/slashben-roadmap-branch
Create roadmap.md
2022-01-06 11:12:48 +02:00
Ben Hirschberg
35534112c6 Create MAINTAINERS.md 2022-01-06 11:10:21 +02:00
Ben Hirschberg
f51e531f3a fixing typos 2022-01-06 11:04:28 +02:00
Ben Hirschberg
2490856ccb Update roadmap.md 2022-01-06 11:02:37 +02:00
Ben Hirschberg
9a5a87b027 Create CODE_OF_CONDUCT.md 2022-01-06 10:44:28 +02:00
Ben Hirschberg
45b8c89865 Create roadmap.md 2022-01-06 10:30:08 +02:00
33 changed files with 918 additions and 106 deletions

View File

@@ -16,8 +16,8 @@ jobs:
env:
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
with:
tag_name: v1.0.${{ github.run_number }}
release_name: Release v1.0.${{ github.run_number }}
tag_name: v2.0.${{ github.run_number }}
release_name: Release v2.0.${{ github.run_number }}
draft: false
prerelease: false
build:
@@ -39,7 +39,7 @@ jobs:
- name: Build
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
ArmoBEServer: api.armo.cloud
ArmoERServer: report.armo.cloud
ArmoWebsite: portal.armo.cloud
@@ -48,7 +48,7 @@ jobs:
- name: Smoke Testing
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
KUBESCAPE_SKIP_UPDATE_CHECK: "true"
run: python3 smoke_testing/init.py ${PWD}/build/${{ matrix.os }}/kubescape
@@ -74,7 +74,7 @@ jobs:
- uses: actions/checkout@v2
- name: Set name
run: echo quay.io/armosec/kubescape:v1.0.${{ github.run_number }} > build_tag.txt
run: echo quay.io/armosec/kubescape:v2.0.${{ github.run_number }} > build_tag.txt
- name: Build the Docker image
run: docker build . --file build/Dockerfile --tag $(cat build_tag.txt) --build-arg run_number=${{ github.run_number }}

View File

@@ -23,7 +23,7 @@ jobs:
- name: Build
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
ArmoBEServer: api.armo.cloud
ArmoERServer: report.euprod1.cyberarmorsoft.com
ArmoWebsite: portal.armo.cloud
@@ -32,7 +32,7 @@ jobs:
- name: Smoke Testing
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
KUBESCAPE_SKIP_UPDATE_CHECK: "true"
run: python3 smoke_testing/init.py ${PWD}/build/${{ matrix.os }}/kubescape
@@ -53,7 +53,7 @@ jobs:
- uses: actions/checkout@v2
- name: Set name
run: echo quay.io/armosec/kubescape:dev-v1.0.${{ github.run_number }} > build_tag.txt
run: echo quay.io/armosec/kubescape:dev-v2.0.${{ github.run_number }} > build_tag.txt
- name: Build the Docker image
run: docker build . --file build/Dockerfile --tag $(cat build_tag.txt) --build-arg run_number=${{ github.run_number }}

View File

@@ -24,7 +24,7 @@ jobs:
- name: Build
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
ArmoBEServer: api.armo.cloud
ArmoERServer: report.armo.cloud
ArmoWebsite: portal.armo.cloud
@@ -33,7 +33,7 @@ jobs:
- name: Smoke Testing
env:
RELEASE: v1.0.${{ github.run_number }}
RELEASE: v2.0.${{ github.run_number }}
KUBESCAPE_SKIP_UPDATE_CHECK: "true"
run: python3 smoke_testing/init.py ${PWD}/build/${{ matrix.os }}/kubescape

127
CODE_OF_CONDUCT.md Normal file
View File

@@ -0,0 +1,127 @@
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders 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, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement [here](mailto:ben@armosec.io).
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations.

9
MAINTAINERS.md Normal file
View File

@@ -0,0 +1,9 @@
# Maintainers
The following table lists Kubescape project maintainers
| Name | GitHub | Email | Organization | Repositories/Area of Expertise | Added/Renewed On |
| --- | --- | --- | --- | --- | --- |
| Ben Hirschberg | @slashben | ben@armosec.io | ARMO | Kubescape CLI | 2021-09-01 |
| Rotem Refael | @rotemamsa | rrefael@armosec.io | ARMO | Kubescape CLI | 2021-10-11 |
| David Wertenteil | @dwertent | dwertent@armosec.io | ARMO | Kubescape CLI | 2021-09-01 |

View File

@@ -3,10 +3,10 @@
[![build](https://github.com/armosec/kubescape/actions/workflows/build.yaml/badge.svg)](https://github.com/armosec/kubescape/actions/workflows/build.yaml)
[![Go Report Card](https://goreportcard.com/badge/github.com/armosec/kubescape)](https://goreportcard.com/report/github.com/armosec/kubescape)
Kubescape is the first open-source tool for testing if Kubernetes is deployed securely according to multiple frameworks:
regulatory, customized company policies and DevSecOps best practices, such as the [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo) and the [MITRE ATT&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/) .
Kubescape scans K8s clusters, YAML files, and HELM charts, and detect misconfigurations and software vulnerabilities at early stages of the CI/CD pipeline and provides a risk score instantly and risk trends over time.
Kubescape integrates natively with other DevOps tools, including Jenkins, CircleCI and Github workflows.
Kubescape is a K8s open-source tool providing a multi-cloud K8s single pane of glass, including risk analysis, security compliance, RBAC visualizer and image vulnerabilities scanning.
Kubescape scans K8s clusters, YAML files, and HELM charts, detecting misconfigurations according to multiple frameworks (such as the [NSA-CISA](https://www.armosec.io/blog/kubernetes-hardening-guidance-summary-by-armo) , [MITRE ATT&CK®](https://www.microsoft.com/security/blog/2021/03/23/secure-containerized-environments-with-updated-threat-matrix-for-kubernetes/)), software vulnerabilities, and RBAC (role-based-access-control) violations at early stages of the CI/CD pipeline, calculates risk score instantly and shows risk trends over time.
It became one of the fastest-growing Kubernetes tools among developers due to its easy-to-use CLI interface, flexible output formats, and automated scanning capabilities, saving Kubernetes users and admins precious time, effort, and resources.
Kubescape integrates natively with other DevOps tools, including Jenkins, CircleCI, Github workflows, Prometheus, and Slack, and supports multi-cloud K8s deployments like EKS, GKE, and AKS.
</br>
@@ -24,7 +24,7 @@ curl -s https://raw.githubusercontent.com/armosec/kubescape/master/install.sh |
## Run:
```
kubescape scan --submit
kubescape scan --submit --enable-host-scan
```
<img src="docs/summary.png">
@@ -54,9 +54,13 @@ Want to contribute? Want to discuss something? Have an issue?
# Options and examples
## Playground
* [Kubescape playground](https://www.katacoda.com/pathaksaiyam/scenarios/kubescape)
## Tutorials
* [Overview](https://youtu.be/wdBkt_0Qhbg)
* [How To Secure Kubernetes Clusters With Kubescape And Armo](https://youtu.be/ZATGiDIDBQk)
* [Scanning Kubernetes YAML files](https://youtu.be/Ox6DaR7_4ZI)
* [Scan Kubescape on an air-gapped environment (offline support)](https://youtu.be/IGXL9s37smM)
* [Managing exceptions in the Kubescape SaaS version](https://youtu.be/OzpvxGmCR80)
@@ -94,9 +98,11 @@ Set-ExecutionPolicy RemoteSigned -scope CurrentUser
| `-t`/`--fail-threshold` | `100` (do not fail) | fail command (return exit code 1) if result is above threshold | `0` -> `100` |
| `-f`/`--format` | `pretty-printer` | Output format | `pretty-printer`/`json`/`junit`/`prometheus` |
| `-o`/`--output` | print to stdout | Save scan result in file | |
| `--use-from` | | Load local framework object from specified path. If not used will download latest | |
| `--use-from` | | Load local framework object from specified path. If not used will download latest |
| `--use-artifacts-from` | | Load artifacts (frameworks, control-config, exceptions) from local directory. If not used will download them | |
| `--use-default` | `false` | Load local framework object from default path. If not used will download latest | `true`/`false` |
| `--exceptions` | | Path to an [exceptions obj](examples/exceptions.json). If not set will download exceptions from Armo management portal | |
| `--exceptions` | | Path to an [exceptions obj](examples/exceptions.json). If not set will download exceptions from Armo management portal |
| `--controls-config` | | Path to a controls-config obj. If not set will download controls-config from ARMO management portal | |
| `--submit` | `false` | If set, Kubescape will send the scan results to Armo management portal 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 sent | `true`/`false` |
| `--keep-local` | `false` | Kubescape will not send scan results to Armo management portal. Use this flag if you ran with the `--submit` flag in the past and you do not want to submit your current scan results | `true`/`false` |
| `--account` | | Armo portal account ID. Default will load account ID from configMap or config file | |
@@ -190,7 +196,7 @@ It is possible to run Kubescape offline!
First download the framework and then scan with `--use-from` flag
1. Download and save in file, if file name not specified, will store save to `~/.kubescape/<framework name>.json`
1. Download and save in file, if file name not specified, will save in `~/.kubescape/<framework name>.json`
```
kubescape download framework nsa --output nsa.json
```
@@ -201,6 +207,19 @@ kubescape scan framework nsa --use-from nsa.json
```
You can also download all artifacts to a local path and then load them using `--use-artifacts-from` flag
1. Download and save in local directory, if path not specified, will save all in `~/.kubescape`
```
kubescape download artifacts --output path/to/local/dir
```
2. Scan using the downloaded artifacts
```
kubescape scan framework nsa --use-artifacts-from path/to/local/dir
```
## Scan Periodically using Helm - Contributed by [@yonahd](https://github.com/yonahd)
You can scan your cluster periodically by adding a `CronJob` that will repeatedly trigger kubescape
@@ -264,7 +283,7 @@ go build -o kubescape .
3. Run
```
./kubescape scan framework nsa
./kubescape scan --submit --enable-host-scan
```
4. Enjoy :zany_face:
@@ -320,3 +339,9 @@ The tools retrieves Kubernetes objects from the API server and runs a set of [re
The results by default printed in a pretty "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. Were also aiming to collaborate with the Kubernetes community to help make the tests themselves more robust and complete as Kubernetes develops.
## Thanks to all the contributors ❤️
<a href = "https://github.com/armosec/kubescape/graphs/contributors">
<img src = "https://contrib.rocks/image?repo=armosec/kubescape"/>
</a>

View File

@@ -85,8 +85,19 @@ func (lp *LoadPolicy) GetFrameworks() ([]reporthandling.Framework, error) {
}
func (lp *LoadPolicy) ListFrameworks() ([]string, error) {
// TODO - Support
return []string{}, fmt.Errorf("loading frameworks list from file is not supported")
fwNames := []string{}
framework := &reporthandling.Framework{}
for _, f := range lp.filePaths {
file, err := os.ReadFile(f)
if err == nil {
if err := json.Unmarshal(file, framework); err == nil {
if !contains(fwNames, framework.Name) {
fwNames = append(fwNames, framework.Name)
}
}
}
}
return fwNames, nil
}
func (lp *LoadPolicy) ListControls(listType ListType) ([]string, error) {
@@ -114,7 +125,7 @@ func (lp *LoadPolicy) GetControlsInputs(clusterName string) (map[string][]string
return nil, err
}
if err = json.Unmarshal(f, &accountConfig); err == nil {
if err = json.Unmarshal(f, &accountConfig.Settings.PostureControlInputs); err == nil {
return accountConfig.Settings.PostureControlInputs, nil
}
return nil, err

View File

@@ -51,23 +51,22 @@ func (rbacObjects *RBACObjects) rbacObjectsToResources(resources *rbacutils.Rbac
Should be investigated
************************************************************************************************************************
// wrap rbac aggregated objects in IMetadata and add to allresources
// TODO - DEPRECATE SA2WLIDmap
SA2WLIDmapIMeta, err := rbacutils.SA2WLIDmapIMetadataWrapper(resources.SA2WLIDmap)
if err != nil {
return nil, err
}
allresources[SA2WLIDmapIMeta.GetID()] = SA2WLIDmapIMeta
SAID2WLIDmapIMeta, err := rbacutils.SAID2WLIDmapIMetadataWrapper(resources.SAID2WLIDmap)
if err != nil {
return nil, err
}
allresources[SAID2WLIDmapIMeta.GetID()] = SAID2WLIDmapIMeta
*/
// wrap rbac aggregated objects in IMetadata and add to allresources
// TODO - DEPRECATE SA2WLIDmap
SA2WLIDmapIMeta, err := rbacutils.SA2WLIDmapIMetadataWrapper(resources.SA2WLIDmap)
if err != nil {
return nil, err
}
allresources[SA2WLIDmapIMeta.GetID()] = SA2WLIDmapIMeta
SAID2WLIDmapIMeta, err := rbacutils.SAID2WLIDmapIMetadataWrapper(resources.SAID2WLIDmap)
if err != nil {
return nil, err
}
allresources[SAID2WLIDmapIMeta.GetID()] = SAID2WLIDmapIMeta
// convert rbac k8s resources to IMetadata and add to allresources
for _, cr := range resources.ClusterRoles.Items {
crmap, err := convertToMap(cr)

View File

@@ -1,16 +1,23 @@
package cautils
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"os"
"path/filepath"
"strings"
"github.com/armosec/kubescape/cautils/getter"
"github.com/armosec/opa-utils/reporthandling"
)
const (
ScanCluster string = "cluster"
ScanLocalFiles string = "yaml"
ScanCluster string = "cluster"
ScanLocalFiles string = "yaml"
localControlInputsFilename string = "controls-inputs.json"
localExceptionsFilename string = "exceptions.json"
)
type BoolPtrFlag struct {
@@ -52,6 +59,7 @@ type ScanInfo struct {
ControlsInputs string // Load file with inputs for controls
UseFrom []string // Load framework from local file (instead of download). Use when running offline
UseDefault bool // Load framework from cached file (instead of download). Use when running offline
UseArtifactsFrom string // Load artifacts from local path. Use when running offline
VerboseMode bool // Display all of the input resources and not only failed resources
Format string // Format results (table, json, junit ...)
Output string // Store results in an output file, Output file name
@@ -64,10 +72,9 @@ type ScanInfo struct {
HostSensor BoolPtrFlag // Deploy ARMO K8s host sensor to collect data from certain controls
Local bool // Do not submit results
Account string // account ID
// ClusterName string // cluster name
KubeContext string // context name
FrameworkScan bool // false if scanning control
ScanAll bool // true if scan all frameworks
KubeContext string // context name
FrameworkScan bool // false if scanning control
ScanAll bool // true if scan all frameworks
}
type Getters struct {
@@ -79,7 +86,48 @@ type Getters struct {
func (scanInfo *ScanInfo) Init() {
scanInfo.setUseFrom()
scanInfo.setOutputFile()
scanInfo.setUseArtifactsFrom()
}
func (scanInfo *ScanInfo) setUseArtifactsFrom() {
if scanInfo.UseArtifactsFrom == "" {
return
}
// UseArtifactsFrom must be a path without a filename
dir, file := filepath.Split(scanInfo.UseArtifactsFrom)
if dir == "" {
scanInfo.UseArtifactsFrom = file
} else if strings.Contains(file, ".json") {
scanInfo.UseArtifactsFrom = dir
}
// set frameworks files
files, err := ioutil.ReadDir(scanInfo.UseArtifactsFrom)
if err != nil {
log.Fatal(err)
}
framework := &reporthandling.Framework{}
for _, f := range files {
filePath := filepath.Join(scanInfo.UseArtifactsFrom, f.Name())
file, err := os.ReadFile(filePath)
if err == nil {
if err := json.Unmarshal(file, framework); err == nil {
scanInfo.UseFrom = append(scanInfo.UseFrom, filepath.Join(scanInfo.UseArtifactsFrom, f.Name()))
}
}
}
// set config-inputs file
scanInfo.ControlsInputs = filepath.Join(scanInfo.UseArtifactsFrom, localControlInputsFilename)
// set exceptions
scanInfo.UseExceptions = filepath.Join(scanInfo.UseArtifactsFrom, localExceptionsFilename)
}
func (scanInfo *ScanInfo) setUseExceptions() {
if scanInfo.UseExceptions != "" {
// load exceptions from file
scanInfo.ExceptionsGetter = getter.NewLoadPolicy([]string{scanInfo.UseExceptions})
} else {
scanInfo.ExceptionsGetter = getter.GetArmoAPIConnector()
}
}
func (scanInfo *ScanInfo) setUseFrom() {

View File

@@ -51,7 +51,7 @@ func setPathandFilename(downloadInfo *cautils.DownloadInfo) {
dir, file := filepath.Split(downloadInfo.Path)
if dir == "" {
downloadInfo.Path = file
} else {
} else if strings.Contains(file, ".json") {
downloadInfo.Path = dir
downloadInfo.FileName = file
}

View File

@@ -42,9 +42,10 @@ func init() {
cobra.OnInitialize(frameworkInitConfig)
rootCmd.AddCommand(scanCmd)
rootCmd.PersistentFlags().StringVarP(&scanInfo.KubeContext, "--kube-context", "", "", "Kube context. Default will use the current-context")
rootCmd.PersistentFlags().StringVarP(&scanInfo.KubeContext, "kube-context", "", "", "Kube context. Default will use the current-context")
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. Recommended: kube-system,kube-public")
scanCmd.PersistentFlags().Uint16VarP(&scanInfo.FailThreshold, "fail-threshold", "t", 100, "Failure threshold is the percent above which the command fails and returns exit code 1")
scanCmd.PersistentFlags().StringVarP(&scanInfo.Format, "format", "f", "pretty-printer", `Output format. Supported formats: "pretty-printer"/"json"/"junit"/"prometheus"`)

View File

@@ -11,8 +11,8 @@ import (
"github.com/armosec/kubescape/resourcehandler"
"github.com/armosec/kubescape/resultshandling/reporter"
reporterv1 "github.com/armosec/kubescape/resultshandling/reporter/v1"
reporterv2 "github.com/armosec/kubescape/resultshandling/reporter/v2"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/rbac-utils/rbacscanner"
)

View File

@@ -1,4 +1,4 @@
# Container image vulnerabilty adaptor interface proposal
# Container image vulnerability adaptor interface proposal
## Rationale
@@ -6,7 +6,7 @@ source #287
### Big picture
* Kubescape team planning to create controls which take into account image vulnerabilities, example: looking for public internet facing workloads with critical vulnerabilities. These are seriously effecting the security health of a cluster and therefore we think it is important to cover it. We think that most container registries are/will support image scanning like Harbor and therefore the ability to get information from them is important.
* Kubescape team is planning to create controls which take into account image vulnerabilities, example: looking for public internet facing workloads with critical vulnerabilities. These are seriously effecting the security health of a cluster and therefore we think it is important to cover it. We think that most container registries are/will support image scanning like Harbor and therefore the ability to get information from them is important.
* There are information in the image repository which is important for existing controls as well. They are incomplete without it, example see this issue: Non-root containers check is broken #19 . These are not necessarily image vulnerability related. Can be information in the image manifest (like the issue before), but it can be the image BOM related.
### Relation to this proposal
@@ -114,4 +114,63 @@ type IContainerImageVulnerabilityAdaptor interface {
GetImagesInformation(imageIDs []ContainerImageIdentifier) ([]ContainerImageInformation, error)
}
```
# Integration
# Input
The objects received from the interface will be converted to an Imetadata compatible objects as following
```
{
"apiVersion": "image.vulnscan.com/v1",
"kind": "VulnScan",
"metadata": {
"name": "nginx:latest"
},
"data": {
// returned by the adaptor API (structure like our backend gives for an image
}
}
```
# Output
The rego results will be a combination of the k8s artifact and the list of relevant CVEs for the control
```
{
"apiVersion": "result.vulnscan.com/v1",
"kind": "Pod",
"metadata": {
"name": "nginx"
},
"relatedObjects": [
{
"apiVersion": "v1",
"kind": "Pod",
"metadata": {
"name": "nginx"
},
"spec": {
// podSpec
},
},
{
"apiVersion": "container.vulnscan.com/v1",
"kind": "VulnScan",
"metadata": {
"name": "nginx:latest",
},
"data": {
// returned by the adaptor API (structure like our backend gives for an image
}
}
]
}
```

23
docs/roadmap.md Normal file
View File

@@ -0,0 +1,23 @@
# Kubescape project roadmap
## Proposals
* [Container registry integration](/docs/proposals/container-image-vulnerability-adaptor.md)
## Planed features
* Image vulnerablity scanning based controls
* Assited remidiation (telling where/what to fix)
* Git integration for pull requests
* Integration with container registries
* Custom controls and regos
* API server configuration validation
* Kubelet configuration validation
## Completed features
* Integration with Prometheus
* Confiugration of controls (customizing rules for a given environment)
* Installation in the cluster for continous monitoring
* Host scanner
* Cloud vendor API integration
* Custom exceptions
* Custom frameworks

View File

@@ -0,0 +1,68 @@
#!/bin/bash
# AWS
# Attach the Kubescape service account to an AWS IAM role with the described cluster permission
# Prerequisites:
# eksctl, awscli v2
# Set environment variables
echo 'Set environment variables'
export kubescape_namespace=armo-system
export kubescape_serviceaccount=armo-kubescape-service-account
# Get current context
echo 'Get current context'
export context=$(kubectl config current-context)
# Get cluster arn
echo 'Get cluster arn'
export cluster_arn=$(kubectl config view -o jsonpath="{.contexts[?(@.name == \"$context\")].context.cluster}")
# Get cluster name
echo 'Get cluster name'
export cluster_name=$(echo "$cluster_arn" | awk -F'/' '{print $NF}')
# Get cluster region
echo 'Get cluster region'
export cluster_region=$(echo "$cluster_arn" | awk -F':' '{print $4}')
# First step, Create IAM OIDC provider for the cluster (Not required if the third step runs as is):
echo 'Create IAM OIDC provider for the cluster'
eksctl utils associate-iam-oidc-provider --cluster $cluster_name --approve
# Second step, Create a policy and service account role:
# Create a kubescape policy
echo 'Create a kubescape policy'
export kubescape_policy_arn=$(aws iam create-policy \
--output yaml \
--query 'Policy.Arn' \
--policy-name kubescape \
--policy-document \
"$(cat <<EOF
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "eks:DescribeCluster",
"Resource": "$cluster_arn"
}
]
}
EOF
)")
# Create Kubernetes Kubescape service account, and AWS IAM attachment role
echo 'Create Kubernetes Kubescape service account, and AWS IAM attachment role'
eksctl create iamserviceaccount \
--name $kubescape_serviceaccount \
--namespace $kubescape_namespace \
--cluster $cluster_name \
--attach-policy-arn $kubescape_policy_arn \
--approve \
--override-existing-serviceaccounts
# Install/Upgrade Kubescape chart
echo 'Install/Upgrade Kubescape chart'
helm upgrade --install armo armo-components/ -n armo-system --create-namespace --set clusterName=$cluster_name --set cloud_provider_engine=eks --set createKubescapeServiceAccount=false --set cloudRegion=$cluster_region

View File

@@ -0,0 +1,49 @@
#!/bin/bash
# GCP
# Attach the Kubescape service account to a GCP service account with the get cluster permission
# Prerequisites:
# gcloud
# Workload Identity enabled on the cluster.
# Node pool with --workload-metadata=GKE_METADATA where the pod can run.
# CLUSTER_NAME and CLUSTER_REGION environment variables.
[ -z $CLUSTER_NAME ] && >&2 echo "Please set the CLUSTER_NAME environment variable" && exit 1
[ -z $CLUSTER_REGION ] && >&2 echo "Please set the CLUSTER_REGION environment variable" && exit 1
# Create GCP service account
gcloud iam service-accounts create kubescape --display-name=kubescape
# Set environment variables
echo 'Set environment variables'
export kubescape_namespace=armo-system
export kubescape_serviceaccount=armo-kubescape-service-account
# Get current GCP project
echo 'Get current GCP project'
export gcp_project=$(gcloud config get-value project)
sleep 5
# Get service account email
echo 'Get service account email'
export gcp_service_account=$(gcloud iam service-accounts list --filter="email ~ kubescape@" --format="value(email)")
# Create custome cluster.get role
echo 'Create custome cluster.get role'
export custom_role_name=$(gcloud iam roles create kubescape --project=$gcp_project --title='Armo kubernetes' --description='Allow clusters.get to Kubernetes armo service account' --permissions=container.clusters.get --stage=GA --format='value(name)')
# Attach policies to the service account
echo 'Attach policies to the service account'
gcloud --quiet projects add-iam-policy-binding $gcp_project --member serviceAccount:$gcp_service_account --role $custom_role_name >/dev/null
gcloud --quiet projects add-iam-policy-binding $gcp_project --member serviceAccount:$gcp_service_account --role roles/storage.objectViewer >/dev/null
# If there are missing permissions, use this role instead
# gcloud --quiet projects add-iam-policy-binding $gcp_project --member serviceAccount:$gcp_service_account --role roles/container.clusterViewer
# Bind the GCP kubescape service account to kubescape kubernetes service account
gcloud iam service-accounts add-iam-policy-binding $gcp_service_account --role roles/iam.workloadIdentityUser --member "serviceAccount:${gcp_project}.svc.id.goog[${kubescape_namespace}/${kubescape_serviceaccount}]"
# Install/Upgrade Kubescape chart
echo 'Install/Upgrade Kubescape chart'
helm upgrade --install armo armo-components/ -n armo-system --create-namespace --set cloud_provider_engine=gke --set gke_service_account=$gcp_service_account --set cloudRegion=$CLUSTER_REGION --set clusterName=$CLUSTER_NAME --set gkeProject=$gcp_project

6
go.mod
View File

@@ -4,8 +4,8 @@ go 1.17
require (
github.com/armosec/armoapi-go v0.0.41
github.com/armosec/k8s-interface v0.0.54
github.com/armosec/opa-utils v0.0.97
github.com/armosec/k8s-interface v0.0.56
github.com/armosec/opa-utils v0.0.99
github.com/armosec/rbac-utils v0.0.12
github.com/armosec/utils-go v0.0.3
github.com/briandowns/spinner v1.18.0
@@ -19,6 +19,7 @@ require (
github.com/satori/go.uuid v1.2.0
github.com/spf13/cobra v1.2.1
github.com/stretchr/testify v1.7.0
go.uber.org/zap v1.19.1
gopkg.in/yaml.v2 v2.4.0
k8s.io/api v0.22.2
k8s.io/apimachinery v0.22.2
@@ -77,7 +78,6 @@ require (
go.opencensus.io v0.23.0 // indirect
go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect
go.uber.org/zap v1.19.1 // indirect
golang.org/x/crypto v0.0.0-20210711020723-a769d52b0f97 // indirect
golang.org/x/net v0.0.0-20210825183410-e898025ed96a // indirect
golang.org/x/oauth2 v0.0.0-20211005180243-6b3c2da341f1 // indirect

8
go.sum
View File

@@ -92,11 +92,11 @@ github.com/armosec/armoapi-go v0.0.41/go.mod h1:exk1O3rK6V+X8SSyxc06lwb0j9ILQuKA
github.com/armosec/k8s-interface v0.0.8/go.mod h1:xxS+V5QT3gVQTwZyAMMDrYLWGrfKOpiJ7Jfhfa0w9sM=
github.com/armosec/k8s-interface v0.0.37/go.mod h1:vHxGWqD/uh6+GQb9Sqv7OGMs+Rvc2dsFVc0XtgRh1ZU=
github.com/armosec/k8s-interface v0.0.50/go.mod h1:vHxGWqD/uh6+GQb9Sqv7OGMs+Rvc2dsFVc0XtgRh1ZU=
github.com/armosec/k8s-interface v0.0.54 h1:1sQeoEZA5bgpXVibXhEiTSeLd3GKY5NkTOeewdgR0Bs=
github.com/armosec/k8s-interface v0.0.54/go.mod h1:vHxGWqD/uh6+GQb9Sqv7OGMs+Rvc2dsFVc0XtgRh1ZU=
github.com/armosec/k8s-interface v0.0.56 h1:7dOgc3qZaI7ReLRZcJa2JZKk0rliyYi05l1vuHc6gcE=
github.com/armosec/k8s-interface v0.0.56/go.mod h1:vHxGWqD/uh6+GQb9Sqv7OGMs+Rvc2dsFVc0XtgRh1ZU=
github.com/armosec/opa-utils v0.0.64/go.mod h1:6tQP8UDq2EvEfSqh8vrUdr/9QVSCG4sJfju1SXQOn4c=
github.com/armosec/opa-utils v0.0.97 h1:KPjRZdsAC9EObo17QxiW+s5KWmF6vNFu+VQSOgFv5uk=
github.com/armosec/opa-utils v0.0.97/go.mod h1:BNTjeianyXlflJMz3bZM0GimBWqmzirUf1whWR6Os04=
github.com/armosec/opa-utils v0.0.99 h1:ZuoIPg6vbgO4J09xJZDO/yIRD59odwmK2Bm55uTvkU8=
github.com/armosec/opa-utils v0.0.99/go.mod h1:BNTjeianyXlflJMz3bZM0GimBWqmzirUf1whWR6Os04=
github.com/armosec/rbac-utils v0.0.1/go.mod h1:pQ8CBiij8kSKV7aeZm9FMvtZN28VgA7LZcYyTWimq40=
github.com/armosec/rbac-utils v0.0.12 h1:uJpMGDyLAX129PrKHp6NPNB6lVRhE0OZIwV6ywzSDrs=
github.com/armosec/rbac-utils v0.0.12/go.mod h1:Ex/IdGWhGv9HZq6Hs8N/ApzCKSIvpNe/ETqDfnuyah0=

View File

@@ -1,6 +1,4 @@
package hostsensorutils
const hostSensorYAML = `apiVersion: v1
apiVersion: v1
kind: Namespace
metadata:
labels:
@@ -62,4 +60,4 @@ spec:
name: host-filesystem
hostNetwork: true
hostPID: true
hostIPC: true`
hostIPC: true

View File

@@ -1,6 +1,7 @@
package hostsensorutils
import (
_ "embed"
"fmt"
"io"
"strings"
@@ -18,6 +19,11 @@ import (
coreapplyv1 "k8s.io/client-go/applyconfigurations/core/v1"
)
var (
//go:embed hostsensor.yaml
hostSensorYAML string
)
type HostSensorHandler struct {
HostSensorPort int32
HostSensorPodNames map[string]string //map from pod names to node names

View File

@@ -6,6 +6,7 @@ import (
"time"
"github.com/armosec/kubescape/cautils"
ksscore "github.com/armosec/kubescape/score"
"github.com/armosec/opa-utils/objectsenvelopes"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/reporthandling/apis"
@@ -71,6 +72,9 @@ func (opaHandler *OPAProcessorHandler) ProcessRulesListenner() {
// edit results
opap.updateResults()
//TODO: review this location
scorewrapper := ksscore.NewScoreWrapper(opaSessionObj)
scorewrapper.Calculate(ksscore.EPostureReportV2)
// report
*opaHandler.reportResults <- opaSessionObj
}

View File

@@ -0,0 +1,104 @@
package resourcehandler
import (
"os"
"strings"
"github.com/armosec/k8s-interface/cloudsupport"
"github.com/armosec/k8s-interface/k8sinterface"
)
var (
KS_KUBE_CLUSTER_ENV_VAR = "KS_KUBE_CLUSTER"
KS_CLOUD_PROVIDER_ENV_VAR = "KS_CLOUD_PROVIDER"
KS_CLOUD_REGION_ENV_VAR = "KS_CLOUD_REGION"
KS_GKE_PROJECT_ENV_VAR = "KS_GKE_PROJECT"
)
type ICloudProvider interface {
getKubeCluster() string
getRegion(cluster string, provider string) (string, error)
getProject(cluster string, provider string) (string, error)
getKubeClusterName() string
}
func initCloudProvider() ICloudProvider {
switch getCloudProvider() {
case "gke", "gcp":
return NewGKEProviderContext()
case "eks", "aws":
return NewEKSProviderContext()
}
return NewEmptyCloudProvider()
}
func getCloudProvider() string {
var provider string
if isEnvVars() {
provider = getCloudProviderFromEnvVar()
} else {
provider = getCloudProviderFromContext()
}
return strings.ToLower(provider)
}
func getCloudProviderFromContext() string {
return cloudsupport.GetCloudProvider(getClusterFromContext())
}
func getClusterFromContext() string {
context := k8sinterface.GetCurrentContext()
if context == nil {
return ""
}
cluster := context.Cluster
if cluster != "" {
return cluster
}
return k8sinterface.GetClusterName()
}
func getCloudProviderFromEnvVar() string {
val, present := os.LookupEnv(KS_CLOUD_PROVIDER_ENV_VAR)
if present {
return val
}
return ""
}
func isEnvVars() bool {
_, present := os.LookupEnv(KS_KUBE_CLUSTER_ENV_VAR)
if !present {
return false
}
_, present = os.LookupEnv(KS_CLOUD_PROVIDER_ENV_VAR)
if !present {
return false
}
_, present = os.LookupEnv(KS_CLOUD_REGION_ENV_VAR)
return present
}
type EmptyCloudProvider struct {
}
func NewEmptyCloudProvider() *EmptyCloudProvider {
return &EmptyCloudProvider{}
}
func (emptyCloudProvider *EmptyCloudProvider) getKubeCluster() string {
return getClusterFromContext()
}
func (emptyCloudProvider *EmptyCloudProvider) getKubeClusterName() string {
return emptyCloudProvider.getKubeCluster()
}
func (emptyCloudProvider *EmptyCloudProvider) getRegion(cluster string, provider string) (string, error) {
return "", nil
}
func (emptyCloudProvider *EmptyCloudProvider) getProject(cluster string, provider string) (string, error) {
return "", nil
}

View File

@@ -0,0 +1,95 @@
package resourcehandler
import (
"fmt"
"os"
"strings"
"github.com/armosec/k8s-interface/k8sinterface"
)
type EKSProviderEnvVar struct {
}
func NewEKSProviderEnvVar() *EKSProviderEnvVar {
return &EKSProviderEnvVar{}
}
func (eksProviderEnvVar *EKSProviderEnvVar) getKubeClusterName() string {
return eksProviderEnvVar.getKubeCluster()
}
func (eksProviderEnvVar *EKSProviderEnvVar) getKubeCluster() string {
val, present := os.LookupEnv(KS_KUBE_CLUSTER_ENV_VAR)
if present {
return val
}
return ""
}
func (eksProviderEnvVar *EKSProviderEnvVar) getRegion(cluster string, provider string) (string, error) {
return eksProviderEnvVar.getRegionForEKS(cluster)
}
func (eksProviderEnvVar *EKSProviderEnvVar) getProject(cluster string, provider string) (string, error) {
return "", nil
}
func (eksProviderEnvVar *EKSProviderEnvVar) getRegionForEKS(cluster string) (string, error) {
region, present := os.LookupEnv(KS_CLOUD_REGION_ENV_VAR)
if present {
return region, nil
}
splittedClusterContext := strings.Split(cluster, ".")
if len(splittedClusterContext) < 2 {
return "", fmt.Errorf("error: failed to get region")
}
region = splittedClusterContext[1]
return region, nil
}
// ------------------------------------- EKSProviderContext -------------------------
type EKSProviderContext struct {
}
func NewEKSProviderContext() *EKSProviderContext {
return &EKSProviderContext{}
}
func (eksProviderContext *EKSProviderContext) getKubeClusterName() string {
cluster := k8sinterface.GetCurrentContext().Cluster
var splittedCluster []string
if cluster != "" {
splittedCluster = strings.Split(cluster, ".")
if len(splittedCluster) > 1 {
return splittedCluster[0]
}
}
splittedCluster = strings.Split(k8sinterface.GetClusterName(), ".")
if len(splittedCluster) > 1 {
return splittedCluster[0]
}
return ""
}
func (eksProviderContext *EKSProviderContext) getKubeCluster() string {
cluster := k8sinterface.GetCurrentContext().Cluster
if cluster != "" {
return cluster
}
return k8sinterface.GetClusterName()
}
func (eksProviderContext *EKSProviderContext) getRegion(cluster string, provider string) (string, error) {
splittedClusterContext := strings.Split(cluster, ".")
if len(splittedClusterContext) < 2 {
return "", fmt.Errorf("error: failed to get region")
}
region := splittedClusterContext[1]
return region, nil
}
func (eksProviderContext *EKSProviderContext) getProject(cluster string, provider string) (string, error) {
return "", nil
}

View File

@@ -0,0 +1,125 @@
package resourcehandler
import (
"fmt"
"os"
"strings"
"github.com/armosec/k8s-interface/k8sinterface"
)
type GKEProviderEnvVar struct {
}
func NewGKEProviderEnvVar() *GKEProviderEnvVar {
return &GKEProviderEnvVar{}
}
func (gkeProvider *GKEProviderEnvVar) getKubeClusterName() string {
return gkeProvider.getKubeCluster()
}
func (gkeProvider *GKEProviderEnvVar) getKubeCluster() string {
val, present := os.LookupEnv(KS_KUBE_CLUSTER_ENV_VAR)
if present {
return val
}
return ""
}
func (gkeProvider *GKEProviderEnvVar) getRegion(cluster string, provider string) (string, error) {
return gkeProvider.getRegionForGKE(cluster)
}
func (gkeProvider *GKEProviderEnvVar) getProject(cluster string, provider string) (string, error) {
return gkeProvider.getProjectForGKE(cluster)
}
func (gkeProvider *GKEProviderEnvVar) getProjectForGKE(cluster string) (string, error) {
project, present := os.LookupEnv(KS_GKE_PROJECT_ENV_VAR)
if present {
return project, nil
}
parsedName := strings.Split(cluster, "_")
if len(parsedName) < 3 {
return "", fmt.Errorf("error: failed to parse cluster name")
}
project = parsedName[1]
return project, nil
}
func (gkeProvider *GKEProviderEnvVar) getRegionForGKE(cluster string) (string, error) {
region, present := os.LookupEnv(KS_CLOUD_REGION_ENV_VAR)
if present {
return region, nil
}
parsedName := strings.Split(cluster, "_")
if len(parsedName) < 3 {
return "", fmt.Errorf("error: failed to parse cluster name")
}
region = parsedName[2]
return region, nil
}
// ------------------------------ GKEProviderContext --------------------------------------------------------
type GKEProviderContext struct {
}
func NewGKEProviderContext() *GKEProviderContext {
return &GKEProviderContext{}
}
func (gkeProviderContext *GKEProviderContext) getKubeClusterName() string {
cluster := k8sinterface.GetCurrentContext().Cluster
parsedName := strings.Split(cluster, "_")
if len(parsedName) < 3 {
return ""
}
clusterName := parsedName[3]
if clusterName != "" {
return clusterName
}
cluster = k8sinterface.GetClusterName()
parsedName = strings.Split(cluster, "_")
if len(parsedName) < 3 {
return ""
}
clusterName = parsedName[3]
return clusterName
}
func (gkeProviderContext *GKEProviderContext) getKubeCluster() string {
cluster := k8sinterface.GetCurrentContext().Cluster
if cluster != "" {
return cluster
}
return k8sinterface.GetClusterName()
}
func (gkeProviderContext *GKEProviderContext) getRegion(cluster string, provider string) (string, error) {
return gkeProviderContext.getRegionForGKE(cluster)
}
func (gkeProviderContext *GKEProviderContext) getProject(cluster string, provider string) (string, error) {
return gkeProviderContext.getProjectForGKE(cluster)
}
func (gkeProviderContext *GKEProviderContext) getProjectForGKE(cluster string) (string, error) {
parsedName := strings.Split(cluster, "_")
if len(parsedName) < 3 {
return "", fmt.Errorf("error: failed to parse cluster name")
}
project := parsedName[1]
return project, nil
}
func (gkeProviderContext *GKEProviderContext) getRegionForGKE(cluster string) (string, error) {
parsedName := strings.Split(cluster, "_")
if len(parsedName) < 3 {
return "", fmt.Errorf("error: failed to parse cluster name")
}
region := parsedName[2]
return region, nil
}

View File

@@ -193,11 +193,21 @@ func (k8sHandler *K8sResourceHandler) collectRbacResources(allResources map[stri
}
func getCloudProviderDescription(allResources map[string]workloadinterface.IMetadata, k8sResourcesMap *cautils.K8SResources) error {
if cloudsupport.IsRunningInCloudProvider() {
wl, err := cloudsupport.GetDescriptiveInfoFromCloudProvider()
cloudProvider := initCloudProvider()
cluster := cloudProvider.getKubeCluster()
clusterName := cloudProvider.getKubeClusterName()
provider := getCloudProvider()
region, err := cloudProvider.getRegion(cluster, provider)
if err != nil {
return err
}
project, err := cloudProvider.getProject(cluster, provider)
if err != nil {
return err
}
if provider != "" {
wl, err := cloudsupport.GetDescriptiveInfoFromCloudProvider(clusterName, provider, region, project)
if err != nil {
cluster := k8sinterface.GetCurrentContext().Cluster
provider := cloudsupport.GetCloudProvider(cluster)
// Return error with useful info on how to configure credentials for getting cloud provider info
switch provider {
case "gke":

View File

@@ -22,7 +22,7 @@ func groupByNamespaceOrKind(resources []WorkloadSummary, status func(workloadSum
case workloadinterface.TypeWorkloadObject:
ns := ""
if resources[i].resource.GetNamespace() != "" {
ns = "Namescape " + resources[i].resource.GetNamespace()
ns = "Namespace " + resources[i].resource.GetNamespace()
}
if r, ok := mapResources[ns]; ok {
r = append(r, resources[i])

View File

@@ -40,7 +40,7 @@ func groupByNamespaceOrKind(resources []WorkloadSummary, status func(workloadSum
case workloadinterface.TypeWorkloadObject:
ns := ""
if resources[i].resource.GetNamespace() != "" {
ns = "Namescape " + resources[i].resource.GetNamespace()
ns = "Namespace " + resources[i].resource.GetNamespace()
}
if r, ok := mapResources[ns]; ok {
r = append(r, resources[i])

View File

@@ -38,14 +38,16 @@ func NewReportEventReceiver(tenantConfig *cautils.ConfigObj) *ReportEventReceive
}
func (report *ReportEventReceiver) ActionSendReport(opaSessionObj *cautils.OPASessionObj) error {
cautils.ReportV2ToV1(opaSessionObj)
if opaSessionObj.PostureReport == nil && opaSessionObj.Report != nil {
cautils.ReportV2ToV1(opaSessionObj)
}
if report.customerGUID == "" {
report.message = "WARNING: Failed to publish results. Reason: Unknown accout ID. Run kubescape with the '--account <account ID>' flag. Contact ARMO team for more details"
return nil
}
if report.clusterName == "" {
report.message = "WARNING: Failed to publish results. Reason: Unknown cluster name. Run kubescape with the '--kube-context <cluster name>' flag"
report.message = "WARNING: Failed to publish results because the cluster name is Unknown. If you are scanning YAML files the results are not submitted to the Kubescape SaaS"
return nil
}

View File

@@ -46,7 +46,7 @@ func (report *ReportEventReceiver) ActionSendReport(opaSessionObj *cautils.OPASe
return nil
}
if report.clusterName == "" {
report.message = "WARNING: Failed to publish results. Reason: Unknown cluster name. Run kubescape with the '--kube-context <cluster name>' flag"
report.message = "WARNING: Failed to publish results because the cluster name is Unknown. If you are scanning YAML files the results are not submitted to the Kubescape SaaS"
return nil
}
opaSessionObj.Report.ReportID = uuid.NewV4().String()
@@ -78,27 +78,21 @@ func (report *ReportEventReceiver) prepareReport(postureReport *reporthandlingv2
reportCounter := 0
// send results
if err := report.sendResults(host, postureReport, &reportCounter); err != nil {
return err
}
reportCounter++
// send resources
if err := report.sendResources(host, postureReport, &reportCounter); err != nil {
if err := report.sendResources(host, postureReport, &reportCounter, false); err != nil {
return err
}
// reportCounter++
// // send framework results
// if err := report.sendSummary(host, postureReport, &reportCounter); err != nil {
// // send results
// if err := report.sendResults(host, postureReport, &reportCounter, true); err != nil {
// return err
// }
return nil
}
func (report *ReportEventReceiver) sendResources(host string, postureReport *reporthandlingv2.PostureReport, reportCounter *int) error {
func (report *ReportEventReceiver) sendResources(host string, postureReport *reporthandlingv2.PostureReport, reportCounter *int, isLastReport bool) error {
splittedPostureReport := setSubReport(postureReport)
counter := 0
@@ -118,6 +112,7 @@ func (report *ReportEventReceiver) sendResources(host string, postureReport *rep
// delete resources
splittedPostureReport.Resources = []reporthandling.Resource{}
splittedPostureReport.Results = []resourcesresults.Result{}
// restart counter
counter = 0
@@ -127,20 +122,13 @@ func (report *ReportEventReceiver) sendResources(host string, postureReport *rep
splittedPostureReport.Resources = append(splittedPostureReport.Resources, v)
}
return report.sendReport(host, splittedPostureReport, *reportCounter, true)
}
func (report *ReportEventReceiver) sendResults(host string, postureReport *reporthandlingv2.PostureReport, reportCounter *int) error {
splittedPostureReport := setSubReport(postureReport)
counter := 0
for _, v := range postureReport.Results {
r, err := json.Marshal(v)
if err != nil {
return fmt.Errorf("failed to unmarshal resource '%s', reason: %v", v.GetResourceID(), err)
}
if counter+len(r) >= MAX_REPORT_SIZE && len(splittedPostureReport.Resources) > 0 {
if counter+len(r) >= MAX_REPORT_SIZE && len(splittedPostureReport.Results) > 0 {
// send report
if err := report.sendReport(host, splittedPostureReport, *reportCounter, false); err != nil {
@@ -150,6 +138,7 @@ func (report *ReportEventReceiver) sendResults(host string, postureReport *repor
// delete results
splittedPostureReport.Results = []resourcesresults.Result{}
splittedPostureReport.Resources = []reporthandling.Resource{}
// restart counter
counter = 0
@@ -159,15 +148,41 @@ func (report *ReportEventReceiver) sendResults(host string, postureReport *repor
splittedPostureReport.Results = append(splittedPostureReport.Results, v)
}
return report.sendReport(host, splittedPostureReport, *reportCounter, false)
}
func (report *ReportEventReceiver) sendSummary(host string, postureReport *reporthandlingv2.PostureReport, reportCounter *int) error {
splittedPostureReport := setSubReport(postureReport)
splittedPostureReport.SummaryDetails = postureReport.SummaryDetails
return report.sendReport(host, splittedPostureReport, *reportCounter, true)
}
// func (report *ReportEventReceiver) sendResults(host string, postureReport *reporthandlingv2.PostureReport, reportCounter *int, isLastReport bool) error {
// splittedPostureReport := setSubReport(postureReport)
// counter := 0
// for _, v := range postureReport.Results {
// r, err := json.Marshal(v)
// if err != nil {
// return fmt.Errorf("failed to unmarshal resource '%s', reason: %v", v.GetResourceID(), err)
// }
// if counter+len(r) >= MAX_REPORT_SIZE && len(splittedPostureReport.Resources) > 0 {
// // send report
// if err := report.sendReport(host, splittedPostureReport, *reportCounter, false); err != nil {
// return err
// }
// *reportCounter++
// // delete results
// splittedPostureReport.Results = []resourcesresults.Result{}
// // restart counter
// counter = 0
// }
// counter += len(r)
// splittedPostureReport.Results = append(splittedPostureReport.Results, v)
// }
// return report.sendReport(host, splittedPostureReport, *reportCounter, isLastReport)
// }
func (report *ReportEventReceiver) sendReport(host string, postureReport *reporthandlingv2.PostureReport, counter int, isLastReport bool) error {
postureReport.PaginationInfo = reporthandlingv2.PaginationMarks{
ReportNumber: counter,

View File

@@ -9,10 +9,10 @@ func TestHostToString(t *testing.T) {
host := url.URL{
Scheme: "https",
Host: "report.eudev3.cyberarmorsoft.com",
Path: "k8srestapi/v1/postureReport",
Path: "k8srestapi/v2/postureReport",
RawQuery: "cluster=openrasty_seal-7fvz&customerGUID=5d817063-096f-4d91-b39b-8665240080af",
}
expectedHost := "https://report.eudev3.cyberarmorsoft.com/k8srestapi/v1/postureReport?cluster=openrasty_seal-7fvz&customerGUID=5d817063-096f-4d91-b39b-8665240080af&reportID=ffdd2a00-4dc8-4bf3-b97a-a6d4fd198a41"
expectedHost := "https://report.eudev3.cyberarmorsoft.com/k8srestapi/v2/postureReport?cluster=openrasty_seal-7fvz&customerGUID=5d817063-096f-4d91-b39b-8665240080af&reportGUID=ffdd2a00-4dc8-4bf3-b97a-a6d4fd198a41"
receivedHost := hostToString(&host, "ffdd2a00-4dc8-4bf3-b97a-a6d4fd198a41")
if receivedHost != expectedHost {
t.Errorf("%s != %s", receivedHost, expectedHost)

View File

@@ -33,17 +33,7 @@ func (resultsHandler *ResultsHandler) HandleResults(scanInfo *cautils.ScanInfo)
fmt.Println(err)
}
// TODO - get score from table
var score float32 = 0
if opaSessionObj.PostureReport != nil {
for i := range opaSessionObj.PostureReport.FrameworkReports {
score += opaSessionObj.PostureReport.FrameworkReports[i].Score
}
score /= float32(len(opaSessionObj.PostureReport.FrameworkReports))
resultsHandler.printerObj.Score(score)
}
return score
return opaSessionObj.Report.SummaryDetails.Score
}
// CalculatePostureScore calculate final score

43
score/score.go Normal file
View File

@@ -0,0 +1,43 @@
package score
import (
"fmt"
"github.com/armosec/opa-utils/score"
"github.com/armosec/kubescape/cautils"
)
/* provides a wrapper for scoreUtils, since there's no common interface between postureReportV1 and PostureReportV2
and the need of concrete objects
I've decided to create scoreWrapper that will allow calculating score regardless (as long as opaSessionObj is there)
*/
type ScoreWrapper struct {
scoreUtil *score.ScoreUtil
opaSessionObj *cautils.OPASessionObj
}
type PostureReportVersion string
const (
EPostureReportV1 PostureReportVersion = "v1"
EPostureReportV2 PostureReportVersion = "V2"
)
func (su *ScoreWrapper) Calculate(reportVersion PostureReportVersion) error {
switch reportVersion {
case EPostureReportV1:
return su.scoreUtil.Calculate(su.opaSessionObj.PostureReport.FrameworkReports)
case EPostureReportV2:
return su.scoreUtil.CalculatePostureReportV2(su.opaSessionObj.Report)
}
return fmt.Errorf("unsupported score calculator")
}
func NewScoreWrapper(opaSessionObj *cautils.OPASessionObj) *ScoreWrapper {
return &ScoreWrapper{
scoreUtil: score.NewScore(opaSessionObj.AllResources),
opaSessionObj: opaSessionObj,
}
}

1
score/score_test.go Normal file
View File

@@ -0,0 +1 @@
package score