Compare commits

..

189 Commits

Author SHA1 Message Date
David Wertenteil
46073e0a6c update scanner image 2022-09-05 10:12:28 +03:00
David Wertenteil
93a44f494d Merge remote-tracking branch 'armosec/dev' 2022-09-05 09:33:59 +03:00
Aditya Pratap Singh
5c96f877ed Option to force enable color output (closes #560) (#767)
* Option to force enable color output (closes #560)

(cherry picked from commit 4f951781ee8dd6bb451ac7d159787f47e4b07379)

* Update go.mod
2022-09-05 09:03:38 +03:00
Amir Malka
23ea7e0511 bump opa-utils to 181 2022-09-04 15:32:42 +03:00
Suhas Gumma
137b3d7b5d Fixed: Kubescape fails to authenticate remote private Github repo (#721)
* grammar error fixer in CONTRIBUTING.md

* scanning private git repository is available

* giturl to gitapi

* NO TOKEN error functionality added

* Used GetToken method of giturl.IGitAPPI for auth

Co-authored-by: satyam kale <satyamkale271@gmail.com>
Co-authored-by: Ben Hirschberg <59160382+slashben@users.noreply.github.com>
2022-09-04 15:17:15 +03:00
David Wertenteil
13ffd92210 update logger version (#773) 2022-09-04 15:13:16 +03:00
David Wertenteil
4725f8b3ca update logger version 2022-09-04 15:02:04 +03:00
David Wertenteil
6d65a90de9 Merging typo fixes from master (#772)
* greetings

* Update aws.sh

simplified the comment

* typo: In the title and h1 element

Their was a typo in index.html file.

* punctuation changes

* docs : added gitpod badge in readme.md

* fixed typos

* ƒ some grammar mistake is corrected inPULL_REQUEST_TEMPLATE.md file

* Updated README.md file

Added link to CONTRIBUTING.md file in a line in README.

* Added link to code of conduct file

I have added link to the code of conduct file and fixed some problems in the Readme file.

* Fixed readme

* Added alpine tag

Adding alpine tag instead of latest and removing repeating commands

* roadmap.md file is modified

* Automatically Close "Typo" labelled Issue

* build.py is modified

* modified PR template

* Fixed some typos in feature_request.md

"." at the end of the headings were missing and all the text were in same line.
Now this gives a clear and concise view of the texts.

* fixed the typo in docs/index.html

Found and fixed typo in the 'alt' attribute of img tag

* Update PULL_REQUEST_TEMPLATE.md

Co-authored-by: Krishna Agarwal <dmkrishna.agarwal@gmail.com>
Co-authored-by: Saswata Senapati <74651639+saswat16@users.noreply.github.com>
Co-authored-by: Rahul Singh <110548934+rahuldhirendersingh@users.noreply.github.com>
Co-authored-by: deepuyadav004 <deepuyadavze@gmail.com>
Co-authored-by: kartik <97971066+kartikgajjar7@users.noreply.github.com>
Co-authored-by: Rounak-28 <95576871+Rounak-28@users.noreply.github.com>
Co-authored-by: pwnb0y <vickykr07@yahoo.com>
Co-authored-by: Ben Hirschberg <59160382+slashben@users.noreply.github.com>
Co-authored-by: Saptarshi Sarkar <saptarshi.programmer@gmail.com>
Co-authored-by: Rahul Surwade <93492791+RahulSurwade08@users.noreply.github.com>
Co-authored-by: Suhas Gumma <43647369+suhasgumma@users.noreply.github.com>
Co-authored-by: Kamal Nayan <95926324+legendarykamal@users.noreply.github.com>
Co-authored-by: TarangVerma <90996971+TarangVerma@users.noreply.github.com>
Co-authored-by: avikittu <65793296+avikittu@users.noreply.github.com>
2022-09-04 14:50:22 +03:00
David Wertenteil
faf928527d Merge pull request #770 from amirmalka/dev
Resources Prioritization
2022-09-04 14:17:19 +03:00
Amir Malka
18c6e80c3c Added resource prioritization information, raw resource will be sent on the result object 2022-09-04 13:38:48 +03:00
David Wertenteil
b103e817ed Merge pull request #745 from Moshe-Rappaport-CA/dev
Print chart name log when fail to generate
2022-09-04 12:59:30 +03:00
Moshe Rappaport
2db2f55d16 Change formatting to %s 2022-09-01 14:28:18 +03:00
David Wertenteil
b38ce5e812 Merge pull request #734 from Chirag8023/patch-3
Patch 3
2022-09-01 08:44:26 +03:00
David Wertenteil
d03806aea2 Merge pull request #738 from shm12/dev
Adding fixed control input
2022-09-01 08:32:26 +03:00
Moshe-Rappaport-CA
fc3912ca7d Print chart name log when fail to generate 2022-08-31 15:26:24 +03:00
shm12
a76228c1e1 update go.mod 2022-08-30 11:39:54 +03:00
shm12
9447f2933a Added fixed control input 2022-08-30 11:33:19 +03:00
David Wertenteil
26d4664cc5 Merge pull request #694 from Moshe-Rappaport-CA/support-scanning-several-files
Support scanning several files
2022-08-30 10:01:44 +03:00
Chirag Arora
acdad028a3 Update completion.go 2022-08-30 00:59:00 +05:30
Moshe Rappaport
de78615038 Update core/pkg/resourcehandler/filesloader.go
Co-authored-by: Vlad Klokun <vladklokun@users.noreply.github.com>
2022-08-29 18:10:21 +03:00
David Wertenteil
1c215c36af Merge pull request #682 from MaruthiKo/patch-1
Fixed Typos in examples/exceptions/README.md
2022-08-29 14:53:49 +03:00
David Wertenteil
2e8f64b20a Merge pull request #675 from MrKrishnaAgarwal/patch-3
fix typos
2022-08-29 14:53:16 +03:00
Moshe-Rappaport-CA
9c764c90e3 Fix scanning ListObj following reviews 2022-08-29 10:29:25 +03:00
Moshe-Rappaport-CA
95a4c19dc6 Handle with issues caused by updating opa-utils 2022-08-29 10:17:31 +03:00
Moshe-Rappaport-CA
e3352f90e1 Merge remote-tracking branch 'armo/dev' into support-scanning-several-files 2022-08-28 12:03:09 +03:00
Moshe-Rappaport-CA
677a9da80a Fix issues according to review 2022-08-28 12:02:21 +03:00
Ben Hirschberg
c7e1e251ba Merge pull request #693 from satyamkale27/Gramma-Mistakes
grammar error fixer in CONTRIBUTING.md
2022-08-28 09:41:03 +03:00
Vlad Klokun
9a7eb4b9a5 Merge pull request #690 from legendarykamal/master
docs: center the icon, reword starring call to action
2022-08-26 14:47:24 +03:00
Vlad Klokun
903b5f39df docs(readme): Star → star 2022-08-25 23:00:10 +03:00
Kamal Nayan
55f0ca3e9e gramatical improvements 2022-08-26 00:57:56 +05:30
David Wertenteil
3387e677ba Merge pull request #636 from Moshe-Rappaport-CA/dev
Fix scanning list obj
2022-08-25 17:33:38 +03:00
Moshe-Rappaport-CA
5774acfc81 Merge remote-tracking branch 'armo/dev' into support-scanning-several-files 2022-08-25 15:25:58 +03:00
Moshe-Rappaport-CA
0eee2d1d0a Support scanning several files 2022-08-25 15:20:26 +03:00
satyam kale
0c624cc576 grammar error fixer in CONTRIBUTING.md 2022-08-25 15:21:51 +05:30
Kamal Nayan
aade1008c4 improved icon of kubescape in readme 2022-08-25 14:54:03 +05:30
Konjeti Maruthi
786092bdaf Fixed Typos in examples/exceptions/README.md
Fixed a few typos and grammatical mistakes in the readme.md
2022-08-24 22:12:57 +05:30
David Wertenteil
80adf03926 Merge branch 'master' into dev 2022-08-24 17:23:28 +03:00
David Wertenteil
4b9c35d53b Merge branch 'master' of https://github.com/kubescape/kubescape 2022-08-24 17:23:10 +03:00
David Wertenteil
f3623dccf6 Merge pull request #678 from RohitYandigeri/patch-5
Update container-image-vulnerability-adaptor.md

Resolves #673
2022-08-24 17:20:28 +03:00
David Wertenteil
b936c3f857 Merge branch 'master' into dev 2022-08-24 17:11:38 +03:00
David Wertenteil
600b9a6fb0 Merge branch 'master' of https://github.com/kubescape/kubescape 2022-08-24 17:11:13 +03:00
David Wertenteil
3bec2ef0b7 override infoMap only if it's not nil 2022-08-24 17:10:18 +03:00
Rohit Yandigeri
3d8344f23c Update container-image-vulnerability-adaptor.md 2022-08-24 19:07:54 +05:30
Krishna Agarwal
d87836d0a9 fix typos 2022-08-24 18:25:06 +05:30
David Wertenteil
70288c94c3 Merge pull request #665 from rahuldhirendersingh/patch-1
Fixed typo: for better code readability
2022-08-24 15:39:24 +03:00
David Wertenteil
2bc63c2ab6 Merge pull request #659 from RohitYandigeri/patch-4
Update README.md
2022-08-24 15:35:21 +03:00
David Wertenteil
609cbff2da Merge pull request #655 from om2137/om2
Broken links fix in roadmap.md
2022-08-24 15:29:50 +03:00
David Wertenteil
3cf0931fb8 Merge pull request #652 from Polokghosh53/patch-2
Update CONTRIBUTING.md
2022-08-24 15:28:46 +03:00
David Wertenteil
a42d2452fd Merge branch 'master' into patch-2 2022-08-24 15:28:32 +03:00
David Wertenteil
7dd79874cc Merge pull request #645 from Hirdey-1999/patch-2
Updated roadmap.md : Typo Error
2022-08-24 15:21:50 +03:00
David Wertenteil
d1a75f076e Merge pull request #640 from Yh010/patch-3
Corrected grammatical errors
2022-08-24 15:20:42 +03:00
David Wertenteil
08fa833f82 Merge branch 'master' into patch-3 2022-08-24 15:20:34 +03:00
David Wertenteil
45e869e0d6 Merge pull request #634 from asim-bhatta/document
Edited few words
2022-08-24 15:15:28 +03:00
David Wertenteil
46cfc882c2 Merge pull request #667 from dwertent/master
Adding close `typo` issues workflow
2022-08-24 14:40:16 +03:00
Ben Hirschberg
10583a4b9b Merge pull request #661 from slashben/master
Updates to roadmap and readme
2022-08-24 14:12:47 +03:00
Ben Hirschberg
da2adf3059 Update close-typos-issues.yaml 2022-08-24 14:01:43 +03:00
David Wertenteil
da24c9164a auto close typo issues 2022-08-24 13:27:24 +03:00
Rahul Singh
8ac41533b6 typo correction: for better code readability
There was some spelling mistakes at multiple places, so I've made those changes to increase the better code readability
2022-08-24 14:07:49 +05:30
David Wertenteil
76958f285c Merge branch 'master' into master 2022-08-24 11:06:05 +03:00
David Wertenteil
93f6f3aecf Update README.md 2022-08-24 11:04:17 +03:00
Benyamin Hirschberg
971f0c06e7 Adding "open for contribution" tickets in the team intro section 2022-08-24 09:36:12 +03:00
Benyamin Hirschberg
bd4e0483d4 small reame changes 2022-08-24 09:31:16 +03:00
Ben Hirschberg
838eff3037 Merge pull request #637 from kubescape/dev
Replacing `armosec` by `kubescape`
2022-08-24 09:28:09 +03:00
Benyamin Hirschberg
1ee1c11700 removing ARMO from Kubescape logo 2022-08-24 09:15:33 +03:00
Benyamin Hirschberg
daa6db164a Updating high level roadmap 2022-08-24 09:11:01 +03:00
Rohit Yandigeri
eb33542e4a Update README.md 2022-08-24 10:40:48 +05:30
Om Raut
a03b0c94c4 Broken links fix in roadmap.md
Planning, backlog, and wishlist links were not taking to the required section.
2022-08-24 02:18:56 +05:30
David Wertenteil
402aea1493 Merge remote-tracking branch 'armosec/dev' 2022-08-23 22:34:03 +03:00
David Wertenteil
26c0baefe7 Fixing building section links 2022-08-23 22:33:04 +03:00
David Wertenteil
057d22adc1 Merge branch 'master' into dev 2022-08-23 22:29:24 +03:00
Polok-Ghosh
77f3806abf Update CONTRIBUTING.md
Some minute changes in the contributing.md
2022-08-24 00:38:31 +05:30
David Wertenteil
5f6689adc1 Merge pull request #651 from dwertent/master
Fixed links in readme
2022-08-23 21:48:31 +03:00
David Wertenteil
051ec71263 Merge remote-tracking branch 'armosec/dev' 2022-08-23 21:43:43 +03:00
David Wertenteil
c3434814c1 Fixed readme links 2022-08-23 21:43:02 +03:00
Hirdey-1999
38325c5af4 Update roadmap.md 2022-08-23 21:33:05 +05:30
Moshe-Rappaport-CA
589d0545cb Merge branch 'dev' of github.com:Moshe-Rappaport-CA/kubescape into dev 2022-08-23 17:41:01 +03:00
Moshe-Rappaport-CA
32b74608bf Merge remote-tracking branch 'armo/dev' into dev 2022-08-23 17:02:15 +03:00
Yash Hegde
98c0be147b Corrected grammatical errors 2022-08-23 19:07:36 +05:30
David Wertenteil
6442e8c891 fixed test deps pkg 2022-08-23 16:31:19 +03:00
Moshe-Rappaport-CA
9454924b9f Merge remote-tracking branch 'armo/dev' into dev 2022-08-23 16:11:07 +03:00
Moshe Rappaport
7233f00c32 Merge branch 'dev' into dev 2022-08-23 15:51:57 +03:00
Moshe-Rappaport-CA
905db42625 Fix go mod in httphandler pkg 2022-08-23 15:49:06 +03:00
David Wertenteil
40e02899bb Merge pull request #604 from kubescape/send-num-of-resources
Send num of resources
2022-08-23 15:26:23 +03:00
Asim Bhatta
bfdf24afb4 Edited few words 2022-08-23 18:02:38 +05:45
Asim Bhatta
588269f1a0 Merge branch 'document' of https://github.com/asim-bhatta/kubescape into document 2022-08-23 17:57:38 +05:45
David Wertenteil
040b965be2 Merge pull request #633 from dwertent/master
Replacing `armo` organization by `kubescape` organization
2022-08-23 15:10:16 +03:00
Daniel-GrunbergerCA
363951eb94 pr fixes 2022-08-23 15:07:51 +03:00
Asim Bhatta
a45283b128 Edited here as well 2022-08-23 17:39:43 +05:45
Moshe-Rappaport-CA
05d5ad47f2 Merge remote-tracking branch 'armo/dev' into dev 2022-08-23 14:42:38 +03:00
Moshe-Rappaport-CA
5ccb858d7f Fix issue for scanning list obj 2022-08-23 14:42:12 +03:00
Asim Bhatta
c49c808730 Merge branch 'kubescape:master' into document 2022-08-23 17:16:59 +05:45
Asim Bhatta
23d44aef7e Edited few words 2022-08-23 16:22:06 +05:45
David Wertenteil
657beea858 Merge pull request #632 from SaptarshiSarkar12/patch-2
Fixed typo
2022-08-23 13:29:06 +03:00
David Wertenteil
4becfc6b88 Update PULL_REQUEST_TEMPLATE.md 2022-08-23 13:28:40 +03:00
Saptarshi Sarkar
b2763b1f4f Fixed typo 2022-08-23 15:54:22 +05:30
David Wertenteil
cbd4fc1a80 replace armo by kubescape mentioned in urls 2022-08-23 12:33:48 +03:00
David Wertenteil
6a17eb1e86 Merge pull request #631 from slashben/dev
Removing mention of ARMO in the initi log print
2022-08-23 12:29:38 +03:00
Ben Hirschberg
4e847b4293 Removing mention of ARMO in the initi log print 2022-08-23 11:25:28 +03:00
Daniel-GrunbergerCA
e81d8ffa3c use setters 2022-08-23 10:34:05 +03:00
David Wertenteil
2e1de8a48f Merge pull request #622 from OmAximani0/pr-template
Added simple PR template
2022-08-23 08:29:10 +03:00
David Wertenteil
240971172d Requesting PRs should be opened against the dev branch 2022-08-23 08:28:04 +03:00
David Wertenteil
1b54f3b87c Merge pull request #628 from rakshitgondwal/changes
Update README.md
2022-08-23 08:21:10 +03:00
David Wertenteil
cf6ae51f76 Update README.md 2022-08-23 08:20:15 +03:00
David Wertenteil
12619f4f3b Update README.md 2022-08-23 08:19:01 +03:00
Rakshit Gondwal
4b96ce4a54 Update README.md 2022-08-23 02:36:21 +05:30
David Wertenteil
86c1f57128 Merge pull request #626 from Yh010/patch-2
Correction of grammatical errors
2022-08-22 23:47:17 +03:00
Yash Hegde
7a51b46178 Correction of grammatical errors 2022-08-23 00:29:18 +05:30
OmAxiani0
eeb1d8bff7 Added simple PR template 2022-08-22 22:05:43 +05:30
David Wertenteil
04f757913a Merge pull request #616 from NirmitSawant/patch-2
Updated the correct link on the discord button
2022-08-22 19:18:55 +03:00
NirmitSawant
307b7be28d Updated the correct link on the discord button 2022-08-22 21:06:26 +05:30
David Wertenteil
c3d188bde4 Merge pull request #615 from prajapatiomkar/master
Made changes in README file by adding discord link correctly
2022-08-22 18:27:09 +03:00
Prajapati omkar
52c2b4e854 Made changes in Readme file by adding discord link 2022-08-22 20:53:31 +05:30
David Wertenteil
bd970eff83 update to kubescape org 2022-08-22 18:22:28 +03:00
David Wertenteil
7bba5fafe0 Merge pull request #607 from vladklokun/template-bug-report
chore: Add a Bug Report issue template
2022-08-22 17:32:32 +03:00
David Wertenteil
d25c69abbf Merge pull request #606 from vladklokun/feature-request-template
Add a feature request template
2022-08-22 17:30:23 +03:00
vladklokun
22e1e8a82f chore: Add a Bug Report issue template 2022-08-22 17:28:56 +03:00
vladklokun
c8c3ab76d6 Add a feature request template 2022-08-22 17:19:45 +03:00
Daniel-GrunbergerCA
ad1c39a7e5 go mod tidy 2022-08-22 16:03:10 +03:00
Daniel-GrunbergerCA
e6398872cd change if order 2022-08-22 15:58:09 +03:00
Daniel-GrunbergerCA
811d27529c log error 2022-08-22 15:56:25 +03:00
Daniel-GrunbergerCA
a1efafc871 send mapNamespace to nuimber of resources in report 2022-08-22 15:51:53 +03:00
David Wertenteil
7f2a4bdfd8 use ks namespace 2022-08-21 10:20:29 +03:00
David Wertenteil
8381b2d348 Merge pull request #602 from dwertent/master
Updated dependencies packages
2022-08-18 22:44:51 +03:00
David Wertenteil
a95c2ec42b removing unused function 2022-08-18 22:41:00 +03:00
David Wertenteil
ad91178ef7 updated dependencies pkgs 2022-08-18 17:41:03 +03:00
David Wertenteil
db179d7b67 Merge pull request #601 from vladklokun/refactor-rename-entities
refactor: Rename branded entities to Kubescape
2022-08-18 16:35:21 +03:00
Vlad Klokun
f6e2651f88 refactor!: httphandler: use Kubescape’s updated exported functions 2022-08-18 15:19:36 +03:00
Vlad Klokun
6a52945e5a chore: summeryhelpers.go → summaryhelpers.go
Fixed a typo in filename (summEry → summAry)
2022-08-18 15:19:29 +03:00
Vlad Klokun
f8a66b0f9b refactor!: resourcehandler: rename armoResources to ksResources 2022-08-18 15:19:27 +03:00
Vlad Klokun
bfc3b0cc43 refactor!: resourcehandler: rename armoResources to ksResources 2022-08-18 15:19:25 +03:00
Vlad Klokun
2432378a57 refactor!: resourcehandler: rename armoResources to ksResources 2022-08-18 15:19:22 +03:00
Vlad Klokun
2f1ae9418a chore!: registryadaptors: rename armosec/v1 Go files 2022-08-18 15:19:19 +03:00
Vlad Klokun
619eeb3f02 refactor!: registryadaptors: rename adaptor Armo to KS 2022-08-18 15:19:16 +03:00
Vlad Klokun
ed1862cf72 refactor!: policyhandler/handlenotification.go: rename armoResources to ksResources 2022-08-18 15:19:12 +03:00
Vlad Klokun
40d5b08f39 refactor!: opaprocessor/processorhandlerutils.go: rename getArmoObjects to getKSObjects 2022-08-18 15:19:10 +03:00
Vlad Klokun
fcfccd18dc refactor!: core/submit.go: rename armoAPI to ksCloudAPI 2022-08-18 15:19:07 +03:00
Vlad Klokun
0be1acfe72 refactor!: core/list: rename armoAPI to ksCloudAPI 2022-08-18 15:19:04 +03:00
Vlad Klokun
7407cbb4fb refactor!: core/initutils.go: rename Armo to Kubescape Cloud 2022-08-18 15:19:02 +03:00
Vlad Klokun
79158aa3e5 refactor!: core/delete.go: rename Armo to Kubescape 2022-08-18 15:19:00 +03:00
Vlad Klokun
e7d212fb8c style: format ArmoResource comment 2022-08-18 15:18:56 +03:00
Vlad Klokun
4d6f75a65a refactor!: rename MapArmoResource to MapKSResource 2022-08-18 15:18:54 +03:00
Vlad Klokun
17445ee8b9 refactor!: rename "ArmoResources" to "KSResources" 2022-08-18 15:18:51 +03:00
Vlad Klokun
2de950cce7 chore!: scaninfo_test.go: remove commented out code 2022-08-18 15:18:48 +03:00
Vlad Klokun
326dd096fd docs!: scaninfo.go: remove Armo mentions 2022-08-18 15:18:46 +03:00
Vlad Klokun
416b5e691e chore!: remove commented out code from reportv2tov1 2022-08-18 15:18:45 +03:00
Vlad Klokun
f7d91f1b48 docs: rename CA in comments to Kubescape Cloud 2022-08-18 15:18:43 +03:00
Vlad Klokun
46f823eb89 refactor!: rename "ruleWithArmoOpaDependency" to "ruleWithKSOpaDependency" 2022-08-18 15:18:41 +03:00
Vlad Klokun
e54bfec4c1 refactor!: rename "ArmoResources" to "KSCloudResources" 2022-08-18 15:18:39 +03:00
Vlad Klokun
e95a09dbff docs: "armo" to "kubescape cloud" in customerloader comments 2022-08-18 15:18:35 +03:00
Vlad Klokun
e1f01f963f chore!: rename "armoapi.go" to "kscloudapi.go" 2022-08-18 15:18:32 +03:00
Vlad Klokun
a397f681b3 refactor(armoapiutils)!: rename "armoAPI" to "api" 2022-08-18 15:18:21 +03:00
Vlad Klokun
0b52c498da refactor!: rename "armoAPI" receivers to "api" 2022-08-18 15:18:19 +03:00
Vlad Klokun
5141d82e49 refactor!: rename NewArmoAPICustomized to NewKSCloudCustomized 2022-08-18 15:18:17 +03:00
Vlad Klokun
262c014cfe refactor!: rename "NewARMOAPIStaging" to "NewKSCloudAPIStaging" 2022-08-18 15:18:14 +03:00
Vlad Klokun
dcd4ac9703 refactor!: rename top-level global vars from "armo" to "ksCloud" 2022-08-18 15:18:12 +03:00
Vlad Klokun
566457308f refactor!: rename "NewARMOAPIProd" to "NewKSCloudAPIProd" (Github tests
ratelimit fails here)
2022-08-18 15:18:09 +03:00
Vlad Klokun
c967dbeefc refactor!: rename "NewArmoAPIDev" to "NewKSCloudAPIDev" 2022-08-18 15:18:03 +03:00
Vlad Klokun
0bcef1be3b refactor!: rename "globalArmoAPIConnector" to "globalKSCloudAPIConnector" 2022-08-18 15:18:00 +03:00
Vlad Klokun
11037f1071 refactor!: rename "GetArmoAPIConnector" to "etKSCloudAPIConnector" 2022-08-18 15:17:56 +03:00
Vlad Klokun
bec9fc9c80 refactor!: rename SetArmoAPIConnector to SetKSCloudAPIConnector 2022-08-18 15:17:53 +03:00
Vlad Klokun
7e1cf051e8 refactor!: rename ArmoAPI to KSCloudAPI 2022-08-18 15:17:51 +03:00
Vlad Klokun
7ea8e89766 refactor!: rename "armo" to "kscloud" in RootInfo 2022-08-18 15:17:47 +03:00
Vlad Klokun
4fc20964b3 refactor!: rename armo to kubescape in rootutils 2022-08-18 15:17:43 +03:00
Amir Malka
cbc14a8c83 Merge pull request #595 from armosec/dev 2022-08-16 08:48:42 +03:00
David Wertenteil
355be63b6f Merge pull request #593 from amirmalka/dev
Updated brew commands, ignore markdown in workflows
2022-08-15 18:32:45 +03:00
Amir Malka
29b431009c Ignore markdown changes in workflows 2022-08-15 14:16:41 +03:00
Amir Malka
4114730d91 Updated brew commands 2022-08-15 14:12:43 +03:00
David Wertenteil
b1731531b1 Merge pull request #586 from armosec/dev
Hot fix: fixed url repo displayed
2022-08-08 17:15:27 +03:00
David Wertenteil
d2a092d032 Merge pull request #585 from dwertent/master
Hot fix: fixed url repo displayed
2022-08-08 17:13:37 +03:00
David Wertenteil
5b450be094 Merge pull request #584 from armosec/dev
Microservice swagger support
2022-08-08 10:07:31 +03:00
Lior Alafi
9c80f4d9cb Merge pull request #583 from dwertent/master
Fixed RBAC submit support
2022-08-07 13:13:14 +03:00
David Wertenteil
9f450ef0cb Merge pull request #580 from dwertent/master
Adding heap
2022-08-04 15:06:31 +03:00
David Wertenteil
17f48a9bc1 Merge pull request #575 from armosec/fix-for-homebrew
Update Makefile
2022-07-25 15:50:02 +03:00
Amir Malka
57874f399b Update Makefile
To support the new build process in homebrew, we are not using the submodules, hence, adding a dash to ignore an error when git submodule command fails
2022-07-25 12:31:34 +03:00
David Wertenteil
ba2e4fe16e Merge pull request #570 from armosec/dev
Hot fix - removing URLs from the python build file
2022-07-19 11:42:23 +03:00
David Wertenteil
ef8565b67f Merge pull request #567 from armosec/dev
Support last commit info
2022-07-18 20:21:24 +03:00
Ben Hirschberg
2fb2ab02c4 Merge pull request #558 from armosec/dev
Support helm chart scanning and reporting
2022-07-06 10:37:14 +03:00
David Wertenteil
f7445d1777 Merge pull request #554 from armosec/dev
Handling edge cases when scanning files
2022-06-30 20:36:54 +03:00
Bezbran
2ce6c1840b Merge pull request #543 from armosec/dev
Adding repository scanning support
2022-06-30 15:21:19 +03:00
Rotem Refael
54020d317e Merge pull request #528 from armosec/rotemamsa-patch-1
Update README.md
2022-06-06 13:45:35 +03:00
Rotem Refael
91d1ec6c2f Update README.md 2022-06-06 13:30:22 +03:00
Rotem Refael
1d3fd0dc9d Merge pull request #527 from vladklokun/add-maintenance-message 2022-06-03 19:43:27 +03:00
Vlad Klokun
8a7511cecb chore: add maintenance message 2022-06-03 19:35:33 +03:00
David Wertenteil
0af0c01ec0 Merge pull request #524 from armosec/dev
Quick fix
2022-05-26 12:21:29 +03:00
David Wertenteil
4f1971a63d Merge pull request #520 from armosec/dev
Extend microservice support
2022-05-24 11:07:24 +03:00
Rotem Refael
afb6ea1d9c Merge pull request #507 from armosec/dev
- Adding Lens extension to readme
- Supporting --view flag
2022-05-12 10:26:14 +03:00
David Wertenteil
b3d16875d6 Merge pull request #493 from armosec/dev
Microservice support
2022-05-03 15:14:24 +03:00
Rotem Refael
cf086e6614 Merge pull request #487 from armosec/dev
Remove binary from repo
2022-04-11 17:20:18 +03:00
Rotem Refael
a27d2d41f2 Merge pull request #484 from armosec/dev
CLI improvement release
2022-04-11 15:48:10 +03:00
171 changed files with 2155 additions and 1727 deletions

34
.github/ISSUE_TEMPLATE/bug_report.md vendored Normal file
View File

@@ -0,0 +1,34 @@
---
name: Bug report
about: Create a report to help us improve
title: ''
labels: ''
assignees: ''
---
# Describe the bug
A clear and concise description of what the bug is.
# Environment
OS: the OS + version youre running Kubescape on, e.g Ubuntu 22.04 LTS
Version: the version that Kubescape reports when you run `kubescape version`
```
Your current version is:
```
# Steps To Reproduce
Steps to reproduce the behavior:
1. Go to '...'
2. Click on '....'
3. Scroll down to '....'
4. See error
# Expected behavior
A clear and concise description of what you expected to happen.
# Actual Behavior
A clear and concise description of what happened. If applicable, add screenshots to help explain your problem.
# Additional context
Add any other context about the problem here.

View File

@@ -0,0 +1,19 @@
---
name: Feature request
about: Suggest an idea for this project
title: ''
labels: ''
assignees: ''
---
**Is your feature request related to a problem? Please describe.**</br>
> A clear and concise description of what the problem is. Ex. I'm always frustrated when [...]
**Describe the solution you'd like.**</br>
> A clear and concise description of what you want to happen.
**Describe alternatives you've considered.**</br>
> A clear and concise description of any alternative solutions or features you've considered.
**Additional context.**</br>
> Add any other context or screenshots about the feature request here.

18
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,18 @@
## Describe your changes
## Screenshots - If Any (Optional)
## This PR fixes:
* Resolved #
## Checklist before requesting a review
<!-- put an [x] in the box to get it checked -->
- [ ] My code follows the style guidelines of this project
- [ ] I have commented on my code, particularly in hard-to-understand areas
- [ ] I have performed a self-review of my code
- [ ] If it is a core feature, I have added thorough tests.
- [ ] New and existing unit tests pass locally with my changes
**Please open the PR against the `dev` branch (Unless the PR contains only documentation changes)**

View File

@@ -3,6 +3,9 @@ name: build
on:
push:
branches: [ master ]
paths-ignore:
# Do not run the pipeline if only Markdown files changed
- '**.md'
jobs:
once:
name: Create release
@@ -93,10 +96,6 @@ jobs:
env:
RELEASE: v2.0.${{ github.run_number }}
CLIENT: release
ArmoBEServer: api.armo.cloud
ArmoAuthServer: auth.armo.cloud
ArmoERServer: report.armo.cloud
ArmoWebsite: portal.armo.cloud
CGO_ENABLED: 1
run: python3 --version && python3 build.py
@@ -131,7 +130,7 @@ jobs:
name: Build docker container, tag and upload to registry
needs: build
runs-on: ubuntu-latest
if: ${{ github.repository == 'armosec/kubescape' }} # TODO
if: ${{ github.repository == 'kubescape/kubescape' }} # TODO
permissions:
id-token: write
packages: write

View File

@@ -3,6 +3,9 @@ name: build-dev
on:
push:
branches: [ dev ]
paths-ignore:
# Do not run the pipeline if only Markdown files changed
- '**.md'
jobs:
build:
name: Create cross-platform dev build
@@ -85,10 +88,6 @@ jobs:
env:
RELEASE: v2.0.${{ github.run_number }}
CLIENT: release-dev
ArmoBEServer: api.armo.cloud
ArmoAuthServer: auth.armo.cloud
ArmoERServer: report.armo.cloud
ArmoWebsite: portal.armo.cloud
CGO_ENABLED: 1
run: python3 --version && python3 build.py
@@ -107,7 +106,7 @@ jobs:
build-docker:
name: Build docker container, tag and upload to registry
needs: build
if: ${{ github.repository == 'armosec/kubescape' }} # TODO
if: ${{ github.repository == 'kubescape/kubescape' }} # TODO
runs-on: ubuntu-latest
permissions:
id-token: write

View File

@@ -0,0 +1,23 @@
on:
issues:
types: [opened, labeled]
jobs:
open_PR_message:
if: github.event.label.name == 'typo'
runs-on: ubuntu-latest
steps:
- uses: ben-z/actions-comment-on-issue@1.0.2
with:
message: "Hello! :wave:\n\nThis issue is being automatically closed, Please open a PR with a relevant fix."
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
auto_close_issues:
runs-on: ubuntu-latest
steps:
- uses: lee-dohm/close-matching-issues@v2
with:
query: 'label:typo'
token: ${{ secrets.GITHUB_TOKEN }}

22
.github/workflows/community.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
on:
fork:
issues:
types: [opened]
issue_comment:
types: [created]
pull_request_target:
types: [opened]
pull_request_review_comment:
types: [created]
jobs:
welcome:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v1
- uses: EddieHubCommunity/gh-action-community/src/welcome@main
with:
github-token: ${{ secrets.GITHUB_TOKEN }}
issue-message: '<h3>Hey, Welcome to this repo, Congratulations on opening your issue. Keep Contributing to Kubescape</h3>'
pr-message: '<h3>Hey, Welcome to this repo, Congratulations on opening your Pull Request. Keep Contributing to Kubescape</h3>'
footer: '<h4>We''ll try to review and add you work as soon as possible and a maintainer will get back to you soon!</h4>'

View File

@@ -4,6 +4,9 @@ on:
pull_request:
branches: [ master, dev ]
types: [ edited, opened, synchronize, reopened ]
paths-ignore:
# Do not run the pipeline if only Markdown files changed
- '**.md'
jobs:
build:
name: Create cross-platform build
@@ -78,10 +81,6 @@ jobs:
env:
RELEASE: v2.0.${{ github.run_number }}
CLIENT: test
ArmoBEServer: api.armo.cloud
ArmoAuthServer: auth.armo.cloud
ArmoERServer: report.armo.cloud
ArmoWebsite: portal.armo.cloud
CGO_ENABLED: 1
run: python3 --version && python3 build.py
@@ -90,4 +89,4 @@ jobs:
RELEASE: v2.0.${{ github.run_number }}
KUBESCAPE_SKIP_UPDATE_CHECK: "true"
run: python3 smoke_testing/init.py ${PWD}/build/${{ matrix.os }}/kubescape

View File

@@ -3,13 +3,13 @@
First, it is awesome that you are considering contributing to Kubescape! Contributing is important and fun and we welcome your efforts.
When contributing, we categorize contributions into two:
* Small code changes or fixes, whose scope are limited to a single or two files
* Complex features and improvements, whose are not limited
* 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 already going to this direction (or the exact opposite ;-) ) and we don't want to waste your time.
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.
@@ -20,14 +20,14 @@ Please note we have a code of conduct, please follow it in all your interactions
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 in once you have the sign-off.
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 making participation in our project and
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
@@ -55,12 +55,12 @@ advances
* Other conduct which could reasonably be considered inappropriate in a
professional setting
We will distance those who are constantly adhere to unacceptable behavior.
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 action in
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
@@ -97,4 +97,4 @@ This Code of Conduct is adapted from the [Contributor Covenant][homepage], versi
available at [http://contributor-covenant.org/version/1/4][version]
[homepage]: http://contributor-covenant.org
[version]: http://contributor-covenant.org/version/1/4/
[version]: http://contributor-covenant.org/version/1/4/

View File

@@ -7,7 +7,7 @@ export CGO_ENABLED=1
# build and install libgit2
libgit2:
git submodule update --init --recursive
-git submodule update --init --recursive
cd git2go; make install-static
# go build tags

106
README.md
View File

@@ -1,35 +1,33 @@
<img src="docs/kubescape.png" width="300" alt="logo" align="center">
<div align="center">
<img src="docs/kubescape.png" width="300" alt="logo">
</div>
[![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)
---
[![build](https://github.com/kubescape/kubescape/actions/workflows/build.yaml/badge.svg)](https://github.com/kubescape/kubescape/actions/workflows/build.yaml)
[![Go Report Card](https://goreportcard.com/badge/github.com/kubescape/kubescape)](https://goreportcard.com/report/github.com/kubescape/kubescape)
[![Gitpod Ready-to-Code](https://img.shields.io/badge/Gitpod-Ready--to--Code-blue?logo=gitpod)](https://gitpod.io/#https://github.com/kubescape/kubescape)
:sunglasses: [Want to contribute?](#being-a-part-of-the-team) :innocent:
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 is a K8s open-source tool providing a Kubernetes 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/?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/)), 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.
It has become 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>
<!-- # Kubescape Coverage
<img src="docs/ksfromcodetodeploy.png">
</br> -->
# Kubescape CLI:
<img src="docs/demo.gif">
</br>
<!-- # Kubescape overview:
<img src="docs/ARMO-header-2022.gif"> -->
# TL;DR
## Install:
```sh
curl -s https://raw.githubusercontent.com/armosec/kubescape/master/install.sh | /bin/bash
curl -s https://raw.githubusercontent.com/kubescape/kubescape/master/install.sh | /bin/bash
```
[Install on windows](#install-on-windows)
@@ -49,26 +47,25 @@ kubescape scan --submit --enable-host-scan --verbose
</br>
> 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.
> 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 more robust and complete as Kubernetes develops.
</br>
### Click [👍](https://github.com/armosec/kubescape/stargazers) if you want us to continue to develop and improve Kubescape 😀
### Please [star ⭐](https://github.com/kubescape/kubescape/stargazers) the repo if you want us to continue developing and improving Kubescape 😀
</br>
# Being part of the team
# Being a part of the team
We invite you to our team! We are excited about this project and want to return the love we get.
Want to contribute? Want to discuss something? Have an issue?
[Want to contribute?](https://github.com/kubescape/kubescape/blob/master/CONTRIBUTING.md) Want to discuss something? Have an issue? Please make sure that you follow our [Code Of Conduct](https://github.com/kubescape/kubescape/blob/master/CODE_OF_CONDUCT.md) .
* Feel free to pick a task from the [roadmap](docs/roadmap.md) or suggest a feature of your own. [Contact us](MAINTAINERS.md) directly for more information :)
* Open a issue, we are trying to respond within 48 hours
* [Join us](https://armosec.github.io/kubescape) in a discussion on our discord server!
* 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!
[<img src="docs/discord-banner.png" width="100" alt="logo" align="center">](https://armosec.github.io/kubescape/)
[<img src="docs/discord-banner.png" width="100" alt="logo" align="center">](https://discord.com/invite/WKZRaCtBxN)
![discord](https://img.shields.io/discord/893048809884643379)
@@ -87,16 +84,18 @@ Want to contribute? Want to discuss something? Have an issue?
* [Scan Kubescape on an air-gapped environment (offline support)](https://youtu.be/IGXL9s37smM)
* [Managing exceptions in the Kubescape SaaS version](https://youtu.be/OzpvxGmCR80)
* [Configure and run customized frameworks](https://youtu.be/12Sanq_rEhs)
* Customize controls configurations. [Kubescape CLI](https://youtu.be/955psg6TVu4), [Kubescape SaaS](https://youtu.be/lIMVSVhH33o)
<details><summary>Windows</summary>
* Customize control configurations:
- [Kubescape CLI](https://youtu.be/955psg6TVu4)
- [Kubescape SaaS](https://youtu.be/lIMVSVhH33o)
## Install on Windows
<details><summary>Windows</summary>
**Requires powershell v5.0+**
``` powershell
iwr -useb https://raw.githubusercontent.com/armosec/kubescape/master/install.ps1 | iex
iwr -useb https://raw.githubusercontent.com/kubescape/kubescape/master/install.ps1 | iex
```
Note: if you get an error you might need to change the execution policy (i.e. enable Powershell) with
@@ -106,22 +105,23 @@ Set-ExecutionPolicy RemoteSigned -scope CurrentUser
```
</details>
<details><summary>MacOS</summary>
## Install on macOS
<details><summary>MacOS</summary>
1. ```sh
brew tap armosec/kubescape
brew tap kubescape/tap
```
2. ```sh
brew install kubescape
brew install kubescape-cli
```
</details>
<details><summary>Nix/NixOS</summary>
## Install on NixOS or with nix (Community)
<details><summary>Nix/NixOS</summary>
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.
@@ -193,17 +193,17 @@ kubescape scan --include-namespaces development,staging,production
kubescape scan --exclude-namespaces kube-system,kube-public
```
#### Scan local `yaml`/`json` files before deploying. [Take a look at the demonstration](https://youtu.be/Ox6DaR7_4ZI) Submit the results in case the directory is a git repo. [docs](https://hub.armosec.io/docs/repository-scanning?utm_source=github&utm_medium=repository)
#### Scan local `yaml`/`json` files before deploying. [Take a look at the demonstration](https://youtu.be/Ox6DaR7_4ZI). Submit the results in case the directory is a git repo. [docs](https://hub.armosec.io/docs/repository-scanning?utm_source=github&utm_medium=repository)
```
kubescape scan *.yaml --submit
```
#### Scan kubernetes manifest files from a git repository [and submit the results](https://hub.armosec.io/docs/repository-scanning?utm_source=github&utm_medium=repository)
#### Scan Kubernetes manifest files from a git repository [and submit the results](https://hub.armosec.io/docs/repository-scanning?utm_source=github&utm_medium=repository)
```
kubescape scan https://github.com/armosec/kubescape --submit
kubescape scan https://github.com/kubescape/kubescape --submit
```
#### Display all scanned resources (including the resources who passed)
#### Display all scanned resources (including the resources which passed)
```
kubescape scan --verbose
```
@@ -243,7 +243,7 @@ kubescape scan --exceptions examples/exceptions/exclude-kube-namespaces.json
```
kubescape scan </path/to/directory> --submit
```
> Kubescape will load the default values file
> Kubescape will load the default value file
### Offline/Air-gaped Environment Support
@@ -263,11 +263,11 @@ kubescape download artifacts --output path/to/local/dir
kubescape scan --use-artifacts-from path/to/local/dir
```
#### Download a single artifacts
#### Download a single artifact
You can also download a single artifacts and scan with the `--use-from` flag
You can also download a single artifact and scan with the `--use-from` flag
1. Download and save in file, if file name not specified, will save in `~/.kubescape/<framework name>.json`
1. Download and save in a file, if the file name is not specified, will save in `~/.kubescape/<framework name>.json`
```
kubescape download framework nsa --output /path/nsa.json
```
@@ -298,9 +298,9 @@ View Kubescape scan results directly in [Lens IDE](https://k8slens.dev/) using k
# Building Kubescape
<details><summary>Windows</summary>
## Build on Windows
## Windows
<details><summary>Windows</summary>
1. Install MSYS2 & build libgit _(needed only for the first time)_
@@ -323,9 +323,9 @@ View Kubescape scan results directly in [Lens IDE](https://k8slens.dev/) using k
```
</details>
<details><summary>Linux / MacOS</summary>
## Build on Linux/MacOS
## Linux / MacOS
<details><summary>Linux / MacOS</summary>
1. Install libgit2 dependency _(needed only for the first time)_
@@ -357,7 +357,7 @@ View Kubescape scan results directly in [Lens IDE](https://k8slens.dev/) using k
## VS code configuration samples
You can use the samples files below to setup your VS code environment for building and debugging purposes.
You can use the sample files below to setup your VS code environment for building and debugging purposes.
<details><summary>.vscode/settings.json</summary>
@@ -402,16 +402,16 @@ You can use the samples files below to setup your VS code environment for buildi
# Under the hood
## Technology
Kubescape based on [OPA engine](https://github.com/open-policy-agent/opa) and ARMO's posture controls.
Kubescape is based on the [OPA engine](https://github.com/open-policy-agent/opa) and ARMO's posture controls.
The tools retrieves Kubernetes objects from the API server and runs a set of [rego's snippets](https://www.openpolicyagent.org/docs/latest/policy-language/) developed by [ARMO](https://www.armosec.io?utm_source=github&utm_medium=repository).
The tools retrieve Kubernetes objects from the API server and run a set of [rego's 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 printed in a pretty "console friendly" manner, but they can be retrieved in JSON format for further processing.
The results by default are 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.
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 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 href = "https://github.com/kubescape/kubescape/graphs/contributors">
<img src = "https://contrib.rocks/image?repo=kubescape/kubescape"/>
</a>

View File

@@ -4,7 +4,7 @@ import hashlib
import platform
import subprocess
BASE_GETTER_CONST = "github.com/armosec/kubescape/v2/core/cautils/getter"
BASE_GETTER_CONST = "github.com/kubescape/kubescape/v2/core/cautils/getter"
def check_status(status, msg):
if status != 0:
@@ -25,7 +25,7 @@ def get_build_dir():
def get_package_name():
package_name = "kubescape"
# if platform.system() == "Windows": package_name += ".exe"
if platform.system() == "Windows": package_name += ".exe"
return package_name
@@ -35,10 +35,10 @@ def main():
# Set some variables
package_name = get_package_name()
build_url = "github.com/armosec/kubescape/v2/core/cautils.BuildNumber"
build_url = "github.com/kubescape/kubescape/v2/core/cautils.BuildNumber"
release_version = os.getenv("RELEASE")
client_var = "github.com/armosec/kubescape/v2/core/cautils.Client"
client_var = "github.com/kubescape/kubescape/v2/core/cautils.Client"
client_name = os.getenv("CLIENT")
# Create build directory

View File

@@ -20,7 +20,6 @@ WORKDIR /work
ADD . .
# install libgit2
WORKDIR /work
RUN rm -rf git2go && make libgit2
# build kubescape server
@@ -34,16 +33,16 @@ RUN python build.py
RUN /work/build/ubuntu-latest/kubescape download artifacts -o /work/artifacts
FROM alpine
FROM alpine:3.16.2
RUN addgroup -S armo && adduser -S armo -G armo
RUN mkdir /home/armo/.kubescape
COPY --from=builder /work/artifacts/ /home/armo/.kubescape
RUN chown -R armo:armo /home/armo/.kubescape
USER armo
WORKDIR /home/armo
COPY --from=builder /work/httphandler/build/ubuntu-latest/kubescape /usr/bin/ksserver

View File

@@ -4,7 +4,7 @@
1. Clone Project
```
git clone https://github.com/armosec/kubescape.git kubescape && cd "$_"
git clone https://github.com/kubescape/kubescape.git kubescape && cd "$_"
```
2. Build

View File

@@ -43,7 +43,3 @@ func GetCompletionCmd() *cobra.Command {
}
return completionCmd
}
// func init() {
// rootCmd.AddCommand(completionCmd)
// }

View File

@@ -1,7 +1,7 @@
package config
import (
"github.com/armosec/kubescape/v2/core/meta"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/spf13/cobra"
)

View File

@@ -1,9 +1,9 @@
package config
import (
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -4,9 +4,9 @@ import (
"fmt"
"strings"
"github.com/armosec/kubescape/v2/core/meta"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/meta"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -3,9 +3,9 @@ package config
import (
"os"
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -1,8 +1,8 @@
package delete
import (
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -4,9 +4,9 @@ import (
"fmt"
"strings"
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -5,11 +5,11 @@ import (
"path/filepath"
"strings"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/core"
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/core"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -4,11 +4,11 @@ import (
"fmt"
"strings"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/core"
"github.com/armosec/kubescape/v2/core/meta"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/core"
"github.com/kubescape/kubescape/v2/core/meta"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -4,20 +4,20 @@ import (
"fmt"
"strings"
"github.com/armosec/kubescape/v2/cmd/completion"
"github.com/armosec/kubescape/v2/cmd/config"
"github.com/armosec/kubescape/v2/cmd/delete"
"github.com/armosec/kubescape/v2/cmd/download"
"github.com/armosec/kubescape/v2/cmd/list"
"github.com/armosec/kubescape/v2/cmd/scan"
"github.com/armosec/kubescape/v2/cmd/submit"
"github.com/armosec/kubescape/v2/cmd/version"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/core"
"github.com/armosec/kubescape/v2/core/meta"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/cmd/completion"
"github.com/kubescape/kubescape/v2/cmd/config"
"github.com/kubescape/kubescape/v2/cmd/delete"
"github.com/kubescape/kubescape/v2/cmd/download"
"github.com/kubescape/kubescape/v2/cmd/list"
"github.com/kubescape/kubescape/v2/cmd/scan"
"github.com/kubescape/kubescape/v2/cmd/submit"
"github.com/kubescape/kubescape/v2/cmd/version"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/core"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/spf13/cobra"
)
@@ -51,8 +51,8 @@ func getRootCmd(ks meta.IKubescape) *cobra.Command {
Example: ksExamples,
}
rootCmd.PersistentFlags().StringVar(&rootInfo.ArmoBEURLsDep, "environment", "", envFlagUsage)
rootCmd.PersistentFlags().StringVar(&rootInfo.ArmoBEURLs, "env", "", envFlagUsage)
rootCmd.PersistentFlags().StringVar(&rootInfo.KSCloudBEURLsDep, "environment", "", envFlagUsage)
rootCmd.PersistentFlags().StringVar(&rootInfo.KSCloudBEURLs, "env", "", envFlagUsage)
rootCmd.PersistentFlags().MarkDeprecated("environment", "use 'env' instead")
rootCmd.PersistentFlags().MarkHidden("environment")
rootCmd.PersistentFlags().MarkHidden("env")
@@ -63,6 +63,7 @@ func getRootCmd(ks meta.IKubescape) *cobra.Command {
rootCmd.PersistentFlags().StringVarP(&rootInfo.Logger, "logger", "l", helpers.InfoLevel.String(), fmt.Sprintf("Logger level. Supported: %s [$KS_LOGGER]", strings.Join(helpers.SupportedLevels(), "/")))
rootCmd.PersistentFlags().StringVar(&rootInfo.CacheDir, "cache-dir", getter.DefaultLocalStore, "Cache directory [$KS_CACHE_DIR]")
rootCmd.PersistentFlags().BoolVarP(&rootInfo.DisableColor, "disable-color", "", false, "Disable Color output for logging")
rootCmd.PersistentFlags().BoolVarP(&rootInfo.EnableColor, "enable-color", "", false, "Force enable Color output for logging")
cobra.OnInitialize(initLogger, initLoggerLevel, initEnvironment, initCacheDir)

View File

@@ -5,9 +5,9 @@ import (
"os"
"strings"
"github.com/armosec/kubescape/v2/core/cautils/getter"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/mattn/go-isatty"
)
@@ -16,6 +16,7 @@ const envFlagUsage = "Send report results to specific URL. Format:<ReportReceive
func initLogger() {
logger.DisableColor(rootInfo.DisableColor)
logger.EnableColor(rootInfo.EnableColor)
if rootInfo.LoggerName == "" {
if l := os.Getenv("KS_LOGGER_NAME"); l != "" {
@@ -55,10 +56,10 @@ func initCacheDir() {
logger.L().Debug("cache dir updated", helpers.String("path", getter.DefaultLocalStore))
}
func initEnvironment() {
if rootInfo.ArmoBEURLs == "" {
rootInfo.ArmoBEURLs = rootInfo.ArmoBEURLsDep
if rootInfo.KSCloudBEURLs == "" {
rootInfo.KSCloudBEURLs = rootInfo.KSCloudBEURLsDep
}
urlSlices := strings.Split(rootInfo.ArmoBEURLs, ",")
urlSlices := strings.Split(rootInfo.KSCloudBEURLs, ",")
if len(urlSlices) != 1 && len(urlSlices) < 3 {
logger.L().Fatal("expected at least 3 URLs (report, api, frontend, auth)")
}
@@ -66,24 +67,24 @@ func initEnvironment() {
case 1:
switch urlSlices[0] {
case "dev", "development":
getter.SetARMOAPIConnector(getter.NewARMOAPIDev())
getter.SetKSCloudAPIConnector(getter.NewKSCloudAPIDev())
case "stage", "staging":
getter.SetARMOAPIConnector(getter.NewARMOAPIStaging())
getter.SetKSCloudAPIConnector(getter.NewKSCloudAPIStaging())
case "":
getter.SetARMOAPIConnector(getter.NewARMOAPIProd())
getter.SetKSCloudAPIConnector(getter.NewKSCloudAPIProd())
default:
logger.L().Fatal("--environment flag usage: " + envFlagUsage)
}
case 2:
logger.L().Fatal("--environment flag usage: " + envFlagUsage)
case 3, 4:
var armoAUTHURL string
armoERURL := urlSlices[0] // mandatory
armoBEURL := urlSlices[1] // mandatory
armoFEURL := urlSlices[2] // mandatory
var ksAuthURL string
ksEventReceiverURL := urlSlices[0] // mandatory
ksBackendURL := urlSlices[1] // mandatory
ksFrontendURL := urlSlices[2] // mandatory
if len(urlSlices) >= 4 {
armoAUTHURL = urlSlices[3]
ksAuthURL = urlSlices[3]
}
getter.SetARMOAPIConnector(getter.NewARMOAPICustomized(armoERURL, armoBEURL, armoFEURL, armoAUTHURL))
getter.SetKSCloudAPIConnector(getter.NewKSCloudAPICustomized(ksEventReceiverURL, ksBackendURL, ksFrontendURL, ksAuthURL))
}
}

View File

@@ -6,12 +6,12 @@ import (
"os"
"strings"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/meta"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/enescakir/emoji"
"github.com/spf13/cobra"
@@ -70,7 +70,7 @@ func getControlCmd(ks meta.IKubescape, scanInfo *cautils.ScanInfo) *cobra.Comman
if len(args) > 1 {
if len(args[1:]) == 0 || args[1] != "-" {
scanInfo.InputPatterns = []string{args[1]}
scanInfo.InputPatterns = args[1:]
} else { // store stdin to file - do NOT move to separate function !!
tempFile, err := os.CreateTemp(".", "tmp-kubescape*.yaml")
if err != nil {

View File

@@ -6,12 +6,12 @@ import (
"os"
"strings"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/meta"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/enescakir/emoji"
"github.com/spf13/cobra"
@@ -80,7 +80,7 @@ func getFrameworkCmd(ks meta.IKubescape, scanInfo *cautils.ScanInfo) *cobra.Comm
}
if len(args) > 1 {
if len(args[1:]) == 0 || args[1] != "-" {
scanInfo.InputPatterns = []string{args[1]}
scanInfo.InputPatterns = args[1:]
} else { // store stdin to file - do NOT move to separate function !!
tempFile, err := os.CreateTemp(".", "tmp-kubescape*.yaml")
if err != nil {

View File

@@ -3,9 +3,9 @@ package scan
import (
"fmt"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/meta"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/spf13/cobra"
)
@@ -93,7 +93,7 @@ func GetScanCommand(ks meta.IKubescape) *cobra.Command {
scanCmd.PersistentFlags().MarkHidden("silent") // this flag should be deprecated since we added the --logger support
// scanCmd.PersistentFlags().MarkHidden("format-version") // meant for testing different output approaches and not for common use
hostF := scanCmd.PersistentFlags().VarPF(&scanInfo.HostSensorEnabled, "enable-host-scan", "", "Deploy ARMO K8s 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/armosec/kubescape/blob/master/core/pkg/hostsensorutils/hostsensor.yaml")
hostF := scanCmd.PersistentFlags().VarPF(&scanInfo.HostSensorEnabled, "enable-host-scan", "", "Deploy ARMO K8s 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")
hostF.NoOptDefVal = "true"
hostF.DefValue = "false, for no TTY in stdin"

View File

@@ -3,9 +3,9 @@ package submit
import (
"fmt"
"github.com/armosec/kubescape/v2/core/meta"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/meta"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -3,18 +3,18 @@ package submit
import (
"fmt"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/meta"
"github.com/armosec/kubescape/v2/core/meta/cliinterfaces"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
reporterv2 "github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter/v2"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
"github.com/google/uuid"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/kubescape/kubescape/v2/core/meta/cliinterfaces"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
reporterv2 "github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter/v2"
"github.com/armosec/rbac-utils/rbacscanner"
"github.com/kubescape/rbac-utils/rbacscanner"
"github.com/spf13/cobra"
)
@@ -79,7 +79,7 @@ func getKubernetesApi() *k8sinterface.KubernetesApi {
}
func getTenantConfig(credentials *cautils.Credentials, clusterName string, k8s *k8sinterface.KubernetesApi) cautils.ITenantConfig {
if !k8sinterface.IsConnectedToCluster() || k8s == nil {
return cautils.NewLocalConfig(getter.GetArmoAPIConnector(), credentials, clusterName)
return cautils.NewLocalConfig(getter.GetKSCloudAPIConnector(), credentials, clusterName)
}
return cautils.NewClusterConfig(k8s, getter.GetArmoAPIConnector(), credentials, clusterName)
return cautils.NewClusterConfig(k8s, getter.GetKSCloudAPIConnector(), credentials, clusterName)
}

View File

@@ -5,16 +5,16 @@ import (
"fmt"
"os"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
"github.com/google/uuid"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/kubescape/v2/core/meta"
"github.com/armosec/kubescape/v2/core/meta/cliinterfaces"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
reporterv2 "github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter/v2"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/kubescape/v2/core/meta"
"github.com/kubescape/kubescape/v2/core/meta/cliinterfaces"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
reporterv2 "github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter/v2"
"github.com/spf13/cobra"
)

View File

@@ -1,8 +1,8 @@
package submit
import (
"github.com/armosec/kubescape/v2/core/meta"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
"github.com/kubescape/kubescape/v2/core/meta"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/spf13/cobra"
)

View File

@@ -4,7 +4,7 @@ import (
"fmt"
"os"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/spf13/cobra"
)

View File

@@ -9,9 +9,9 @@ import (
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils/getter"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
corev1 "k8s.io/api/core/v1"
)
@@ -124,7 +124,7 @@ func (lc *LocalConfig) GetToken() string { return lc.configObj.Token }
func (lc *LocalConfig) IsConfigFound() bool { return existsConfigFile() }
func (lc *LocalConfig) SetTenant() error {
// ARMO tenant GUID
// Kubescape Cloud tenant GUID
if err := getTenantConfigFromBE(lc.backendAPI, lc.configObj); err != nil {
return err
}
@@ -145,7 +145,7 @@ func (lc *LocalConfig) DeleteCachedConfig() error {
func getTenantConfigFromBE(backendAPI getter.IBackend, configObj *ConfigObj) error {
// get from armoBE
// get from Kubescape Cloud API
tenantResponse, err := backendAPI.GetTenant()
if err == nil && tenantResponse != nil {
if tenantResponse.AdminMail != "" { // registered tenant
@@ -182,11 +182,11 @@ TODO - supprot:
KS_CACHE // path to cached files
*/
type ClusterConfig struct {
backendAPI getter.IBackend
k8s *k8sinterface.KubernetesApi
configObj *ConfigObj
configMapName string
configMapNamespace string
backendAPI getter.IBackend
configObj *ConfigObj
}
func NewClusterConfig(k8s *k8sinterface.KubernetesApi, backendAPI getter.IBackend, credentials *Credentials, clusterName string) *ClusterConfig {

View File

@@ -2,27 +2,29 @@ package cautils
import (
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/reporthandling"
apis "github.com/armosec/opa-utils/reporthandling/apis"
"github.com/armosec/opa-utils/reporthandling/results/v1/resourcesresults"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/reporthandling"
apis "github.com/kubescape/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/reporthandling/results/v1/prioritization"
"github.com/kubescape/opa-utils/reporthandling/results/v1/resourcesresults"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
)
// K8SResources map[<api group>/<api version>/<resource>][]<resourceID>
type K8SResources map[string][]string
type ArmoResources map[string][]string
type KSResources map[string][]string
type OPASessionObj struct {
K8SResources *K8SResources // input k8s objects
ArmoResource *ArmoResources // input ARMO objects
Policies []reporthandling.Framework // list of frameworks to scan
AllResources map[string]workloadinterface.IMetadata // all scanned resources, map[<rtesource ID>]<resource>
ResourcesResult map[string]resourcesresults.Result // resources scan results, map[<rtesource ID>]<resource result>
ResourceSource map[string]reporthandling.Source // resources sources, map[<rtesource ID>]<resource result>
Report *reporthandlingv2.PostureReport // scan results v2 - Remove
Exceptions []armotypes.PostureExceptionPolicy // list of exceptions to apply on scan results
RegoInputData RegoInputData // input passed to rgo for scanning. map[<control name>][<input arguments>]
K8SResources *K8SResources // input k8s objects
ArmoResource *KSResources // input ARMO objects
Policies []reporthandling.Framework // list of frameworks to scan
AllResources map[string]workloadinterface.IMetadata // all scanned resources, map[<resource ID>]<resource>
ResourcesResult map[string]resourcesresults.Result // resources scan results, map[<resource ID>]<resource result>
ResourceSource map[string]reporthandling.Source // resources sources, map[<resource ID>]<resource result>
ResourcesPrioritized map[string]prioritization.PrioritizedResource // resources prioritization information, map[<resource ID>]<prioritized resource>
Report *reporthandlingv2.PostureReport // scan results v2 - Remove
Exceptions []armotypes.PostureExceptionPolicy // list of exceptions to apply on scan results
RegoInputData RegoInputData // input passed to rgo for scanning. map[<control name>][<input arguments>]
Metadata *reporthandlingv2.Metadata
InfoMap map[string]apis.StatusInfo // Map errors of resources to StatusInfo
ResourceToControlsMap map[string][]string // map[<apigroup/apiversion/resource>] = [<control_IDs>]
@@ -36,6 +38,7 @@ func NewOPASessionObj(frameworks []reporthandling.Framework, k8sResources *K8SRe
K8SResources: k8sResources,
AllResources: make(map[string]workloadinterface.IMetadata),
ResourcesResult: make(map[string]resourcesresults.Result),
ResourcesPrioritized: make(map[string]prioritization.PrioritizedResource),
InfoMap: make(map[string]apis.StatusInfo),
ResourceToControlsMap: make(map[string][]string),
ResourceSource: make(map[string]reporthandling.Source),
@@ -44,13 +47,31 @@ func NewOPASessionObj(frameworks []reporthandling.Framework, k8sResources *K8SRe
}
}
func (sessionObj *OPASessionObj) SetMapNamespaceToNumberOfResources(mapNamespaceToNumberOfResources map[string]int) {
if sessionObj.Metadata.ContextMetadata.ClusterContextMetadata == nil {
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata = &reporthandlingv2.ClusterMetadata{}
}
if sessionObj.Metadata.ContextMetadata.ClusterContextMetadata.MapNamespaceToNumberOfResources == nil {
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata.MapNamespaceToNumberOfResources = make(map[string]int)
}
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata.MapNamespaceToNumberOfResources = mapNamespaceToNumberOfResources
}
func (sessionObj *OPASessionObj) SetNumberOfWorkerNodes(n int) {
if sessionObj.Metadata.ContextMetadata.ClusterContextMetadata == nil {
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata = &reporthandlingv2.ClusterMetadata{}
}
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata.NumberOfWorkerNodes = n
}
func NewOPASessionObjMock() *OPASessionObj {
return &OPASessionObj{
Policies: nil,
K8SResources: nil,
AllResources: make(map[string]workloadinterface.IMetadata),
ResourcesResult: make(map[string]resourcesresults.Result),
Report: &reporthandlingv2.PostureReport{},
Policies: nil,
K8SResources: nil,
AllResources: make(map[string]workloadinterface.IMetadata),
ResourcesResult: make(map[string]resourcesresults.Result),
ResourcesPrioritized: make(map[string]prioritization.PrioritizedResource),
Report: &reporthandlingv2.PostureReport{},
Metadata: &reporthandlingv2.Metadata{
ScanMetadata: reporthandlingv2.ScanMetadata{
ScanningTarget: 0,
@@ -77,6 +98,6 @@ type RegoInputData struct {
}
type Policies struct {
Frameworks []string
Controls map[string]reporthandling.Control // map[<control ID>]<control>
Frameworks []string
}

View File

@@ -3,8 +3,8 @@ package cautils
import (
"golang.org/x/mod/semver"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/utils-go/boolutils"
"github.com/kubescape/opa-utils/reporthandling"
)
func NewPolicies() *Policies {
@@ -22,7 +22,7 @@ func (policies *Policies) Set(frameworks []reporthandling.Framework, version str
for j := range frameworks[i].Controls {
compatibleRules := []reporthandling.PolicyRule{}
for r := range frameworks[i].Controls[j].Rules {
if !ruleWithArmoOpaDependency(frameworks[i].Controls[j].Rules[r].Attributes) && isRuleKubescapeVersionCompatible(frameworks[i].Controls[j].Rules[r].Attributes, version) {
if !ruleWithKSOpaDependency(frameworks[i].Controls[j].Rules[r].Attributes) && isRuleKubescapeVersionCompatible(frameworks[i].Controls[j].Rules[r].Attributes, version) {
compatibleRules = append(compatibleRules, frameworks[i].Controls[j].Rules[r])
}
}
@@ -35,7 +35,7 @@ func (policies *Policies) Set(frameworks []reporthandling.Framework, version str
}
}
func ruleWithArmoOpaDependency(attributes map[string]interface{}) bool {
func ruleWithKSOpaDependency(attributes map[string]interface{}) bool {
if attributes == nil {
return false
}

View File

@@ -1,6 +1,6 @@
package cautils
// CA environment vars
// Kubescape Cloud environment vars
var (
CustomerGUID = ""
ClusterName = ""

View File

@@ -8,12 +8,12 @@ import (
"path/filepath"
"strings"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/dwertent/go-logger/helpers"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/objectsenvelopes"
"github.com/armosec/opa-utils/objectsenvelopes/localworkload"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/opa-utils/objectsenvelopes"
"github.com/kubescape/opa-utils/objectsenvelopes/localworkload"
"gopkg.in/yaml.v2"
)
@@ -47,7 +47,7 @@ func LoadResourcesFromHelmCharts(basePath string) (map[string][]workloadinterfac
if err == nil {
wls, errs := chart.GetWorkloadsWithDefaultValues()
if len(errs) > 0 {
logger.L().Error(fmt.Sprintf("Rendering of Helm chart template failed: %v", errs))
logger.L().Error(fmt.Sprintf("Rendering of Helm chart template '%s', failed: %v", chart.GetName(), errs))
continue
}
@@ -190,8 +190,10 @@ func readYamlFile(yamlFile []byte) ([]workloadinterface.IMetadata, error) {
}
if obj, ok := j.(map[string]interface{}); ok {
if o := objectsenvelopes.NewObject(obj); o != nil {
if o.GetKind() == "List" {
yamlObjs = append(yamlObjs, handleListObject(o)...)
if o.GetObjectType() == workloadinterface.TypeListWorkloads {
if list := workloadinterface.NewListWorkloadsObj(o.GetObject()); list != nil {
yamlObjs = append(yamlObjs, list.GetItems()...)
}
} else {
yamlObjs = append(yamlObjs, o)
}
@@ -323,20 +325,3 @@ func GetFileFormat(filePath string) FileFormat {
return FileFormat(filePath)
}
}
// handleListObject handle a List manifest
func handleListObject(obj workloadinterface.IMetadata) []workloadinterface.IMetadata {
yamlObjs := []workloadinterface.IMetadata{}
if i, ok := workloadinterface.InspectMap(obj.GetObject(), "items"); ok && i != nil {
if items, ok := i.([]interface{}); ok && items != nil {
for item := range items {
if m, ok := items[item].(map[string]interface{}); ok && m != nil {
if o := objectsenvelopes.NewObject(m); o != nil {
yamlObjs = append(yamlObjs, o)
}
}
}
}
}
return yamlObjs
}

View File

@@ -6,7 +6,7 @@ import (
"strings"
"testing"
"github.com/armosec/opa-utils/objectsenvelopes/localworkload"
"github.com/kubescape/opa-utils/objectsenvelopes/localworkload"
"github.com/stretchr/testify/assert"
)

View File

@@ -1,371 +0,0 @@
package getter
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/opa-utils/reporthandling"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
)
// =======================================================================================================================
// =============================================== ArmoAPI ===============================================================
// =======================================================================================================================
var (
// ATTENTION!!!
// Changes in this URLs variable names, or in the usage is affecting the build process! BE CAREFUL
armoERURL = "report.armo.cloud"
armoBEURL = "api.armosec.io"
armoFEURL = "cloud.armosec.io"
armoAUTHURL = "auth.armosec.io"
armoStageERURL = "report-ks.eustage2.cyberarmorsoft.com"
armoStageBEURL = "api-stage.armosec.io"
armoStageFEURL = "armoui-stage.armosec.io"
armoStageAUTHURL = "eggauth-stage.armosec.io"
armoDevERURL = "report.eudev3.cyberarmorsoft.com"
armoDevBEURL = "api-dev.armosec.io"
armoDevFEURL = "cloud-dev.armosec.io"
armoDevAUTHURL = "eggauth-dev.armosec.io"
)
// Armo API for downloading policies
type ArmoAPI struct {
httpClient *http.Client
apiURL string
authURL string
erURL string
feURL string
accountID string
clientID string
secretKey string
feToken FeLoginResponse
authCookie string
loggedIn bool
}
var globalArmoAPIConnector *ArmoAPI
func SetARMOAPIConnector(armoAPI *ArmoAPI) {
logger.L().Debug("Armo URLs", helpers.String("api", armoAPI.apiURL), helpers.String("auth", armoAPI.authURL), helpers.String("report", armoAPI.erURL), helpers.String("UI", armoAPI.feURL))
globalArmoAPIConnector = armoAPI
}
func GetArmoAPIConnector() *ArmoAPI {
if globalArmoAPIConnector == nil {
// logger.L().Error("returning nil API connector")
SetARMOAPIConnector(NewARMOAPIProd())
}
return globalArmoAPIConnector
}
func NewARMOAPIDev() *ArmoAPI {
apiObj := newArmoAPI()
apiObj.apiURL = armoDevBEURL
apiObj.authURL = armoDevAUTHURL
apiObj.erURL = armoDevERURL
apiObj.feURL = armoDevFEURL
return apiObj
}
func NewARMOAPIProd() *ArmoAPI {
apiObj := newArmoAPI()
apiObj.apiURL = armoBEURL
apiObj.erURL = armoERURL
apiObj.feURL = armoFEURL
apiObj.authURL = armoAUTHURL
return apiObj
}
func NewARMOAPIStaging() *ArmoAPI {
apiObj := newArmoAPI()
apiObj.apiURL = armoStageBEURL
apiObj.erURL = armoStageERURL
apiObj.feURL = armoStageFEURL
apiObj.authURL = armoStageAUTHURL
return apiObj
}
func NewARMOAPICustomized(armoERURL, armoBEURL, armoFEURL, armoAUTHURL string) *ArmoAPI {
apiObj := newArmoAPI()
apiObj.erURL = armoERURL
apiObj.apiURL = armoBEURL
apiObj.feURL = armoFEURL
apiObj.authURL = armoAUTHURL
return apiObj
}
func newArmoAPI() *ArmoAPI {
return &ArmoAPI{
httpClient: &http.Client{Timeout: time.Duration(61) * time.Second},
loggedIn: false,
}
}
func (armoAPI *ArmoAPI) Post(fullURL string, headers map[string]string, body []byte) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
armoAPI.appendAuthHeaders(headers)
return HttpPost(armoAPI.httpClient, fullURL, headers, body)
}
func (armoAPI *ArmoAPI) Delete(fullURL string, headers map[string]string) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
armoAPI.appendAuthHeaders(headers)
return HttpDelete(armoAPI.httpClient, fullURL, headers)
}
func (armoAPI *ArmoAPI) Get(fullURL string, headers map[string]string) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
armoAPI.appendAuthHeaders(headers)
return HttpGetter(armoAPI.httpClient, fullURL, headers)
}
func (armoAPI *ArmoAPI) GetAccountID() string { return armoAPI.accountID }
func (armoAPI *ArmoAPI) IsLoggedIn() bool { return armoAPI.loggedIn }
func (armoAPI *ArmoAPI) GetClientID() string { return armoAPI.clientID }
func (armoAPI *ArmoAPI) GetSecretKey() string { return armoAPI.secretKey }
func (armoAPI *ArmoAPI) GetFrontendURL() string { return armoAPI.feURL }
func (armoAPI *ArmoAPI) GetApiURL() string { return armoAPI.apiURL }
func (armoAPI *ArmoAPI) GetAuthURL() string { return armoAPI.authURL }
func (armoAPI *ArmoAPI) GetReportReceiverURL() string { return armoAPI.erURL }
func (armoAPI *ArmoAPI) SetAccountID(accountID string) { armoAPI.accountID = accountID }
func (armoAPI *ArmoAPI) SetClientID(clientID string) { armoAPI.clientID = clientID }
func (armoAPI *ArmoAPI) SetSecretKey(secretKey string) { armoAPI.secretKey = secretKey }
func (armoAPI *ArmoAPI) GetFramework(name string) (*reporthandling.Framework, error) {
respStr, err := armoAPI.Get(armoAPI.getFrameworkURL(name), nil)
if err != nil {
return nil, nil
}
framework := &reporthandling.Framework{}
if err = JSONDecoder(respStr).Decode(framework); err != nil {
return nil, err
}
return framework, err
}
func (armoAPI *ArmoAPI) GetFrameworks() ([]reporthandling.Framework, error) {
respStr, err := armoAPI.Get(armoAPI.getListFrameworkURL(), nil)
if err != nil {
return nil, nil
}
frameworks := []reporthandling.Framework{}
if err = JSONDecoder(respStr).Decode(&frameworks); err != nil {
return nil, err
}
// SaveInFile(framework, GetDefaultPath(name+".json"))
return frameworks, err
}
func (armoAPI *ArmoAPI) GetControl(policyName string) (*reporthandling.Control, error) {
return nil, fmt.Errorf("control api is not public")
}
func (armoAPI *ArmoAPI) GetExceptions(clusterName string) ([]armotypes.PostureExceptionPolicy, error) {
exceptions := []armotypes.PostureExceptionPolicy{}
respStr, err := armoAPI.Get(armoAPI.getExceptionsURL(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&exceptions); err != nil {
return nil, err
}
return exceptions, nil
}
func (armoAPI *ArmoAPI) GetTenant() (*TenantResponse, error) {
url := armoAPI.getAccountURL()
if armoAPI.accountID != "" {
url = fmt.Sprintf("%s?customerGUID=%s", url, armoAPI.accountID)
}
respStr, err := armoAPI.Get(url, nil)
if err != nil {
return nil, err
}
tenant := &TenantResponse{}
if err = JSONDecoder(respStr).Decode(tenant); err != nil {
return nil, err
}
if tenant.TenantID != "" {
armoAPI.accountID = tenant.TenantID
}
return tenant, nil
}
// ControlsInputs // map[<control name>][<input arguments>]
func (armoAPI *ArmoAPI) GetAccountConfig(clusterName string) (*armotypes.CustomerConfig, error) {
accountConfig := &armotypes.CustomerConfig{}
if armoAPI.accountID == "" {
return accountConfig, nil
}
respStr, err := armoAPI.Get(armoAPI.getAccountConfig(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&accountConfig); err != nil {
// try with default scope
respStr, err = armoAPI.Get(armoAPI.getAccountConfigDefault(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&accountConfig); err != nil {
return nil, err
}
}
return accountConfig, nil
}
// ControlsInputs // map[<control name>][<input arguments>]
func (armoAPI *ArmoAPI) GetControlsInputs(clusterName string) (map[string][]string, error) {
accountConfig, err := armoAPI.GetAccountConfig(clusterName)
if err == nil {
return accountConfig.Settings.PostureControlInputs, nil
}
return nil, err
}
func (armoAPI *ArmoAPI) ListCustomFrameworks() ([]string, error) {
respStr, err := armoAPI.Get(armoAPI.getListFrameworkURL(), nil)
if err != nil {
return nil, err
}
frs := []reporthandling.Framework{}
if err = json.Unmarshal([]byte(respStr), &frs); err != nil {
return nil, err
}
frameworkList := []string{}
for _, fr := range frs {
if !isNativeFramework(fr.Name) {
frameworkList = append(frameworkList, fr.Name)
}
}
return frameworkList, nil
}
func (armoAPI *ArmoAPI) ListFrameworks() ([]string, error) {
respStr, err := armoAPI.Get(armoAPI.getListFrameworkURL(), nil)
if err != nil {
return nil, err
}
frs := []reporthandling.Framework{}
if err = json.Unmarshal([]byte(respStr), &frs); err != nil {
return nil, err
}
frameworkList := []string{}
for _, fr := range frs {
if isNativeFramework(fr.Name) {
frameworkList = append(frameworkList, strings.ToLower(fr.Name))
} else {
frameworkList = append(frameworkList, fr.Name)
}
}
return frameworkList, nil
}
func (armoAPI *ArmoAPI) ListControls(l ListType) ([]string, error) {
return nil, fmt.Errorf("control api is not public")
}
func (armoAPI *ArmoAPI) PostExceptions(exceptions []armotypes.PostureExceptionPolicy) error {
for i := range exceptions {
ex, err := json.Marshal(exceptions[i])
if err != nil {
return err
}
_, err = armoAPI.Post(armoAPI.exceptionsURL(""), map[string]string{"Content-Type": "application/json"}, ex)
if err != nil {
return err
}
}
return nil
}
func (armoAPI *ArmoAPI) DeleteException(exceptionName string) error {
_, err := armoAPI.Delete(armoAPI.exceptionsURL(exceptionName), nil)
if err != nil {
return err
}
return nil
}
func (armoAPI *ArmoAPI) Login() error {
if armoAPI.accountID == "" {
return fmt.Errorf("failed to login, missing accountID")
}
if armoAPI.clientID == "" {
return fmt.Errorf("failed to login, missing clientID")
}
if armoAPI.secretKey == "" {
return fmt.Errorf("failed to login, missing secretKey")
}
// init URLs
feLoginData := FeLoginData{ClientId: armoAPI.clientID, Secret: armoAPI.secretKey}
body, _ := json.Marshal(feLoginData)
resp, err := http.Post(armoAPI.getApiToken(), "application/json", bytes.NewBuffer(body))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("error authenticating: %d", resp.StatusCode)
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var feLoginResponse FeLoginResponse
if err = json.Unmarshal(responseBody, &feLoginResponse); err != nil {
return err
}
armoAPI.feToken = feLoginResponse
/* Now we have JWT */
armoAPI.authCookie, err = armoAPI.getAuthCookie()
if err != nil {
return err
}
armoAPI.loggedIn = true
return nil
}

View File

@@ -8,11 +8,11 @@ type FeLoginData struct {
type FeLoginResponse struct {
Token string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresIn int32 `json:"expiresIn"`
Expires string `json:"expires"`
ExpiresIn int32 `json:"expiresIn"`
}
type ArmoSelectCustomer struct {
type KSCloudSelectCustomer struct {
SelectedCustomerGuid string `json:"selectedCustomer"`
}

View File

@@ -3,8 +3,8 @@ package getter
import (
"strings"
"github.com/armosec/opa-utils/gitregostore"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/gitregostore"
"github.com/kubescape/opa-utils/reporthandling"
)
// =======================================================================================================================

View File

@@ -2,7 +2,7 @@ package getter
import (
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling"
)
// supported listing

View File

@@ -0,0 +1,363 @@
package getter
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strings"
"time"
"github.com/armosec/armoapi-go/armotypes"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/opa-utils/reporthandling"
)
var (
ksCloudERURL = "report.armo.cloud"
ksCloudBEURL = "api.armosec.io"
ksCloudFEURL = "cloud.armosec.io"
ksCloudAUTHURL = "auth.armosec.io"
ksCloudStageERURL = "report-ks.eustage2.cyberarmorsoft.com"
ksCloudStageBEURL = "api-stage.armosec.io"
ksCloudStageFEURL = "armoui-stage.armosec.io"
ksCloudStageAUTHURL = "eggauth-stage.armosec.io"
ksCloudDevERURL = "report.eudev3.cyberarmorsoft.com"
ksCloudDevBEURL = "api-dev.armosec.io"
ksCloudDevFEURL = "cloud-dev.armosec.io"
ksCloudDevAUTHURL = "eggauth-dev.armosec.io"
)
// KSCloudAPI allows accessing the API of the Kubescape Cloud offering
type KSCloudAPI struct {
httpClient *http.Client
apiURL string
authURL string
erURL string
feURL string
accountID string
clientID string
secretKey string
authCookie string
feToken FeLoginResponse
loggedIn bool
}
var globalKSCloudAPIConnector *KSCloudAPI
func SetKSCloudAPIConnector(ksCloudAPI *KSCloudAPI) {
logger.L().Debug("Kubescape Cloud URLs", helpers.String("api", ksCloudAPI.apiURL), helpers.String("auth", ksCloudAPI.authURL), helpers.String("report", ksCloudAPI.erURL), helpers.String("UI", ksCloudAPI.feURL))
globalKSCloudAPIConnector = ksCloudAPI
}
func GetKSCloudAPIConnector() *KSCloudAPI {
if globalKSCloudAPIConnector == nil {
SetKSCloudAPIConnector(NewKSCloudAPIProd())
}
return globalKSCloudAPIConnector
}
func NewKSCloudAPIDev() *KSCloudAPI {
apiObj := newKSCloudAPI()
apiObj.apiURL = ksCloudDevBEURL
apiObj.authURL = ksCloudDevAUTHURL
apiObj.erURL = ksCloudDevERURL
apiObj.feURL = ksCloudDevFEURL
return apiObj
}
func NewKSCloudAPIProd() *KSCloudAPI {
apiObj := newKSCloudAPI()
apiObj.apiURL = ksCloudBEURL
apiObj.erURL = ksCloudERURL
apiObj.feURL = ksCloudFEURL
apiObj.authURL = ksCloudAUTHURL
return apiObj
}
func NewKSCloudAPIStaging() *KSCloudAPI {
apiObj := newKSCloudAPI()
apiObj.apiURL = ksCloudStageBEURL
apiObj.erURL = ksCloudStageERURL
apiObj.feURL = ksCloudStageFEURL
apiObj.authURL = ksCloudStageAUTHURL
return apiObj
}
func NewKSCloudAPICustomized(ksCloudERURL, ksCloudBEURL, ksCloudFEURL, ksCloudAUTHURL string) *KSCloudAPI {
apiObj := newKSCloudAPI()
apiObj.erURL = ksCloudERURL
apiObj.apiURL = ksCloudBEURL
apiObj.feURL = ksCloudFEURL
apiObj.authURL = ksCloudAUTHURL
return apiObj
}
func newKSCloudAPI() *KSCloudAPI {
return &KSCloudAPI{
httpClient: &http.Client{Timeout: time.Duration(61) * time.Second},
loggedIn: false,
}
}
func (api *KSCloudAPI) Post(fullURL string, headers map[string]string, body []byte) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
api.appendAuthHeaders(headers)
return HttpPost(api.httpClient, fullURL, headers, body)
}
func (api *KSCloudAPI) Delete(fullURL string, headers map[string]string) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
api.appendAuthHeaders(headers)
return HttpDelete(api.httpClient, fullURL, headers)
}
func (api *KSCloudAPI) Get(fullURL string, headers map[string]string) (string, error) {
if headers == nil {
headers = make(map[string]string)
}
api.appendAuthHeaders(headers)
return HttpGetter(api.httpClient, fullURL, headers)
}
func (api *KSCloudAPI) GetAccountID() string { return api.accountID }
func (api *KSCloudAPI) IsLoggedIn() bool { return api.loggedIn }
func (api *KSCloudAPI) GetClientID() string { return api.clientID }
func (api *KSCloudAPI) GetSecretKey() string { return api.secretKey }
func (api *KSCloudAPI) GetFrontendURL() string { return api.feURL }
func (api *KSCloudAPI) GetApiURL() string { return api.apiURL }
func (api *KSCloudAPI) GetAuthURL() string { return api.authURL }
func (api *KSCloudAPI) GetReportReceiverURL() string { return api.erURL }
func (api *KSCloudAPI) SetAccountID(accountID string) { api.accountID = accountID }
func (api *KSCloudAPI) SetClientID(clientID string) { api.clientID = clientID }
func (api *KSCloudAPI) SetSecretKey(secretKey string) { api.secretKey = secretKey }
func (api *KSCloudAPI) GetFramework(name string) (*reporthandling.Framework, error) {
respStr, err := api.Get(api.getFrameworkURL(name), nil)
if err != nil {
return nil, nil
}
framework := &reporthandling.Framework{}
if err = JSONDecoder(respStr).Decode(framework); err != nil {
return nil, err
}
return framework, err
}
func (api *KSCloudAPI) GetFrameworks() ([]reporthandling.Framework, error) {
respStr, err := api.Get(api.getListFrameworkURL(), nil)
if err != nil {
return nil, nil
}
frameworks := []reporthandling.Framework{}
if err = JSONDecoder(respStr).Decode(&frameworks); err != nil {
return nil, err
}
return frameworks, err
}
func (api *KSCloudAPI) GetControl(policyName string) (*reporthandling.Control, error) {
return nil, fmt.Errorf("control api is not public")
}
func (api *KSCloudAPI) GetExceptions(clusterName string) ([]armotypes.PostureExceptionPolicy, error) {
exceptions := []armotypes.PostureExceptionPolicy{}
respStr, err := api.Get(api.getExceptionsURL(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&exceptions); err != nil {
return nil, err
}
return exceptions, nil
}
func (api *KSCloudAPI) GetTenant() (*TenantResponse, error) {
url := api.getAccountURL()
if api.accountID != "" {
url = fmt.Sprintf("%s?customerGUID=%s", url, api.accountID)
}
respStr, err := api.Get(url, nil)
if err != nil {
return nil, err
}
tenant := &TenantResponse{}
if err = JSONDecoder(respStr).Decode(tenant); err != nil {
return nil, err
}
if tenant.TenantID != "" {
api.accountID = tenant.TenantID
}
return tenant, nil
}
// ControlsInputs // map[<control name>][<input arguments>]
func (api *KSCloudAPI) GetAccountConfig(clusterName string) (*armotypes.CustomerConfig, error) {
accountConfig := &armotypes.CustomerConfig{}
if api.accountID == "" {
return accountConfig, nil
}
respStr, err := api.Get(api.getAccountConfig(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&accountConfig); err != nil {
// try with default scope
respStr, err = api.Get(api.getAccountConfigDefault(clusterName), nil)
if err != nil {
return nil, err
}
if err = JSONDecoder(respStr).Decode(&accountConfig); err != nil {
return nil, err
}
}
return accountConfig, nil
}
// ControlsInputs // map[<control name>][<input arguments>]
func (api *KSCloudAPI) GetControlsInputs(clusterName string) (map[string][]string, error) {
accountConfig, err := api.GetAccountConfig(clusterName)
if err == nil {
return accountConfig.Settings.PostureControlInputs, nil
}
return nil, err
}
func (api *KSCloudAPI) ListCustomFrameworks() ([]string, error) {
respStr, err := api.Get(api.getListFrameworkURL(), nil)
if err != nil {
return nil, err
}
frs := []reporthandling.Framework{}
if err = json.Unmarshal([]byte(respStr), &frs); err != nil {
return nil, err
}
frameworkList := []string{}
for _, fr := range frs {
if !isNativeFramework(fr.Name) {
frameworkList = append(frameworkList, fr.Name)
}
}
return frameworkList, nil
}
func (api *KSCloudAPI) ListFrameworks() ([]string, error) {
respStr, err := api.Get(api.getListFrameworkURL(), nil)
if err != nil {
return nil, err
}
frs := []reporthandling.Framework{}
if err = json.Unmarshal([]byte(respStr), &frs); err != nil {
return nil, err
}
frameworkList := []string{}
for _, fr := range frs {
if isNativeFramework(fr.Name) {
frameworkList = append(frameworkList, strings.ToLower(fr.Name))
} else {
frameworkList = append(frameworkList, fr.Name)
}
}
return frameworkList, nil
}
func (api *KSCloudAPI) ListControls(l ListType) ([]string, error) {
return nil, fmt.Errorf("control api is not public")
}
func (api *KSCloudAPI) PostExceptions(exceptions []armotypes.PostureExceptionPolicy) error {
for i := range exceptions {
ex, err := json.Marshal(exceptions[i])
if err != nil {
return err
}
_, err = api.Post(api.exceptionsURL(""), map[string]string{"Content-Type": "application/json"}, ex)
if err != nil {
return err
}
}
return nil
}
func (api *KSCloudAPI) DeleteException(exceptionName string) error {
_, err := api.Delete(api.exceptionsURL(exceptionName), nil)
if err != nil {
return err
}
return nil
}
func (api *KSCloudAPI) Login() error {
if api.accountID == "" {
return fmt.Errorf("failed to login, missing accountID")
}
if api.clientID == "" {
return fmt.Errorf("failed to login, missing clientID")
}
if api.secretKey == "" {
return fmt.Errorf("failed to login, missing secretKey")
}
// init URLs
feLoginData := FeLoginData{ClientId: api.clientID, Secret: api.secretKey}
body, _ := json.Marshal(feLoginData)
resp, err := http.Post(api.getApiToken(), "application/json", bytes.NewBuffer(body))
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return fmt.Errorf("error authenticating: %d", resp.StatusCode)
}
responseBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
return err
}
var feLoginResponse FeLoginResponse
if err = json.Unmarshal(responseBody, &feLoginResponse); err != nil {
return err
}
api.feToken = feLoginResponse
/* Now we have JWT */
api.authCookie, err = api.getAuthCookie()
if err != nil {
return err
}
api.loggedIn = true
return nil
}

View File

@@ -11,12 +11,12 @@ import (
var NativeFrameworks = []string{"nsa", "mitre", "armobest", "devopsbest"}
func (armoAPI *ArmoAPI) getFrameworkURL(frameworkName string) string {
func (api *KSCloudAPI) getFrameworkURL(frameworkName string) string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/armoFrameworks"
q := u.Query()
q.Add("customerGUID", armoAPI.getCustomerGUIDFallBack())
q.Add("customerGUID", api.getCustomerGUIDFallBack())
if isNativeFramework(frameworkName) {
q.Add("frameworkName", strings.ToUpper(frameworkName))
} else {
@@ -28,23 +28,23 @@ func (armoAPI *ArmoAPI) getFrameworkURL(frameworkName string) string {
return u.String()
}
func (armoAPI *ArmoAPI) getListFrameworkURL() string {
func (api *KSCloudAPI) getListFrameworkURL() string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/armoFrameworks"
q := u.Query()
q.Add("customerGUID", armoAPI.getCustomerGUIDFallBack())
q.Add("customerGUID", api.getCustomerGUIDFallBack())
u.RawQuery = q.Encode()
return u.String()
}
func (armoAPI *ArmoAPI) getExceptionsURL(clusterName string) string {
func (api *KSCloudAPI) getExceptionsURL(clusterName string) string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/armoPostureExceptions"
q := u.Query()
q.Add("customerGUID", armoAPI.getCustomerGUIDFallBack())
q.Add("customerGUID", api.getCustomerGUIDFallBack())
// if clusterName != "" { // TODO - fix customer name support in Armo BE
// q.Add("clusterName", clusterName)
// }
@@ -53,13 +53,13 @@ func (armoAPI *ArmoAPI) getExceptionsURL(clusterName string) string {
return u.String()
}
func (armoAPI *ArmoAPI) exceptionsURL(exceptionsPolicyName string) string {
func (api *KSCloudAPI) exceptionsURL(exceptionsPolicyName string) string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/postureExceptionPolicy"
q := u.Query()
q.Add("customerGUID", armoAPI.getCustomerGUIDFallBack())
q.Add("customerGUID", api.getCustomerGUIDFallBack())
if exceptionsPolicyName != "" { // for delete
q.Add("policyName", exceptionsPolicyName)
}
@@ -69,19 +69,19 @@ func (armoAPI *ArmoAPI) exceptionsURL(exceptionsPolicyName string) string {
return u.String()
}
func (armoAPI *ArmoAPI) getAccountConfigDefault(clusterName string) string {
config := armoAPI.getAccountConfig(clusterName)
func (api *KSCloudAPI) getAccountConfigDefault(clusterName string) string {
config := api.getAccountConfig(clusterName)
url := config + "&scope=customer"
return url
}
func (armoAPI *ArmoAPI) getAccountConfig(clusterName string) string {
func (api *KSCloudAPI) getAccountConfig(clusterName string) string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/armoCustomerConfiguration"
q := u.Query()
q.Add("customerGUID", armoAPI.getCustomerGUIDFallBack())
q.Add("customerGUID", api.getCustomerGUIDFallBack())
if clusterName != "" { // TODO - fix customer name support in Armo BE
q.Add("clusterName", clusterName)
}
@@ -90,49 +90,49 @@ func (armoAPI *ArmoAPI) getAccountConfig(clusterName string) string {
return u.String()
}
func (armoAPI *ArmoAPI) getAccountURL() string {
func (api *KSCloudAPI) getAccountURL() string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/createTenant"
return u.String()
}
func (armoAPI *ArmoAPI) getApiToken() string {
func (api *KSCloudAPI) getApiToken() string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetAuthURL())
u.Scheme, u.Host = parseHost(api.GetAuthURL())
u.Path = "identity/resources/auth/v1/api-token"
return u.String()
}
func (armoAPI *ArmoAPI) getOpenidCustomers() string {
func (api *KSCloudAPI) getOpenidCustomers() string {
u := url.URL{}
u.Scheme, u.Host = parseHost(armoAPI.GetApiURL())
u.Scheme, u.Host = parseHost(api.GetApiURL())
u.Path = "api/v1/openid_customers"
return u.String()
}
func (armoAPI *ArmoAPI) getAuthCookie() (string, error) {
selectCustomer := ArmoSelectCustomer{SelectedCustomerGuid: armoAPI.accountID}
func (api *KSCloudAPI) getAuthCookie() (string, error) {
selectCustomer := KSCloudSelectCustomer{SelectedCustomerGuid: api.accountID}
requestBody, _ := json.Marshal(selectCustomer)
client := &http.Client{}
httpRequest, err := http.NewRequest(http.MethodPost, armoAPI.getOpenidCustomers(), bytes.NewBuffer(requestBody))
httpRequest, err := http.NewRequest(http.MethodPost, api.getOpenidCustomers(), bytes.NewBuffer(requestBody))
if err != nil {
return "", err
}
httpRequest.Header.Set("Content-Type", "application/json")
httpRequest.Header.Set("Authorization", fmt.Sprintf("Bearer %s", armoAPI.feToken.Token))
httpRequest.Header.Set("Authorization", fmt.Sprintf("Bearer %s", api.feToken.Token))
httpResponse, err := client.Do(httpRequest)
if err != nil {
return "", err
}
defer httpResponse.Body.Close()
if httpResponse.StatusCode != http.StatusOK {
return "", fmt.Errorf("failed to get cookie from %s: status %d", armoAPI.getOpenidCustomers(), httpResponse.StatusCode)
return "", fmt.Errorf("failed to get cookie from %s: status %d", api.getOpenidCustomers(), httpResponse.StatusCode)
}
cookies := httpResponse.Header.Get("set-cookie")
if len(cookies) == 0 {
return "", fmt.Errorf("no cookie field in response from %s", armoAPI.getOpenidCustomers())
return "", fmt.Errorf("no cookie field in response from %s", api.getOpenidCustomers())
}
authCookie := ""
@@ -144,24 +144,24 @@ func (armoAPI *ArmoAPI) getAuthCookie() (string, error) {
}
if len(authCookie) == 0 {
return "", fmt.Errorf("no auth cookie field in response from %s", armoAPI.getOpenidCustomers())
return "", fmt.Errorf("no auth cookie field in response from %s", api.getOpenidCustomers())
}
return authCookie, nil
}
func (armoAPI *ArmoAPI) appendAuthHeaders(headers map[string]string) {
func (api *KSCloudAPI) appendAuthHeaders(headers map[string]string) {
if armoAPI.feToken.Token != "" {
headers["Authorization"] = fmt.Sprintf("Bearer %s", armoAPI.feToken.Token)
if api.feToken.Token != "" {
headers["Authorization"] = fmt.Sprintf("Bearer %s", api.feToken.Token)
}
if armoAPI.authCookie != "" {
headers["Cookie"] = fmt.Sprintf("auth=%s", armoAPI.authCookie)
if api.authCookie != "" {
headers["Cookie"] = fmt.Sprintf("auth=%s", api.authCookie)
}
}
func (armoAPI *ArmoAPI) getCustomerGUIDFallBack() string {
if armoAPI.accountID != "" {
return armoAPI.accountID
func (api *KSCloudAPI) getCustomerGUIDFallBack() string {
if api.accountID != "" {
return api.accountID
}
return "11111111-1111-1111-1111-111111111111"
}

View File

@@ -8,7 +8,7 @@ import (
"strings"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling"
)
// =======================================================================================================================

View File

@@ -4,10 +4,10 @@ import (
"path/filepath"
"strings"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/objectsenvelopes/localworkload"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/objectsenvelopes/localworkload"
helmchart "helm.sh/helm/v3/pkg/chart"
helmloader "helm.sh/helm/v3/pkg/chart/loader"

View File

@@ -9,7 +9,7 @@ import (
"strings"
"testing"
"github.com/armosec/opa-utils/objectsenvelopes/localworkload"
"github.com/kubescape/opa-utils/objectsenvelopes/localworkload"
"github.com/stretchr/testify/suite"
)

View File

@@ -4,12 +4,12 @@ import (
"encoding/json"
"time"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/rbac-utils/rbacscanner"
"github.com/armosec/rbac-utils/rbacutils"
"github.com/google/uuid"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/rbac-utils/rbacscanner"
"github.com/kubescape/rbac-utils/rbacutils"
)
type RBACObjects struct {
@@ -54,8 +54,8 @@ func (rbacObjects *RBACObjects) rbacObjectsToResources(resources *rbacutils.Rbac
/*
************************************************************************************************************************
This code is adding a non valid ID ->
(github.com/armosec/rbac-utils v0.0.11): "//SA2WLIDmap/SA2WLIDmap"
(github.com/armosec/rbac-utils v0.0.12): "armo.rbac.com/v0beta1//SAID2WLIDmap/SAID2WLIDmap"
(github.com/kubescape/opa-utils v0.0.11): "//SA2WLIDmap/SA2WLIDmap"
(github.com/kubescape/opa-utils v0.0.12): "armo.rbac.com/v0beta1//SAID2WLIDmap/SAID2WLIDmap"
Should be investigated
************************************************************************************************************************
@@ -63,17 +63,21 @@ func (rbacObjects *RBACObjects) rbacObjectsToResources(resources *rbacutils.Rbac
// wrap rbac aggregated objects in IMetadata and add to AllResources
// TODO - DEPRECATE SA2WLIDmap
SA2WLIDmapIMeta, err := rbacutils.SA2WLIDmapIMetadataWrapper(resources.SA2WLIDmap)
m, err := rbacutils.SA2WLIDmapIMetadataWrapper(resources.SA2WLIDmap)
if err != nil {
return nil, err
}
allresources[SA2WLIDmapIMeta.GetID()] = SA2WLIDmapIMeta
SAID2WLIDmapIMeta, err := rbacutils.SAID2WLIDmapIMetadataWrapper(resources.SAID2WLIDmap)
sa2WLIDmapIMeta := workloadinterface.NewBaseObject(m)
allresources[sa2WLIDmapIMeta.GetID()] = sa2WLIDmapIMeta
m2, err := rbacutils.SAID2WLIDmapIMetadataWrapper(resources.SAID2WLIDmap)
if err != nil {
return nil, err
}
allresources[SAID2WLIDmapIMeta.GetID()] = SAID2WLIDmapIMeta
saID2WLIDmapIMeta := workloadinterface.NewBaseObject(m2)
allresources[saID2WLIDmapIMeta.GetID()] = saID2WLIDmapIMeta
// convert rbac k8s resources to IMetadata and add to allresources
for _, cr := range resources.ClusterRoles.Items {

View File

@@ -1,15 +1,14 @@
package cautils
import (
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/reporthandling"
helpersv1 "github.com/armosec/opa-utils/reporthandling/helpers/v1"
"github.com/armosec/opa-utils/reporthandling/results/v1/reportsummary"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/reporthandling"
helpersv1 "github.com/kubescape/opa-utils/reporthandling/helpers/v1"
"github.com/kubescape/opa-utils/reporthandling/results/v1/reportsummary"
)
func ReportV2ToV1(opaSessionObj *OPASessionObj) *reporthandling.PostureReport {
report := &reporthandling.PostureReport{}
// opaSessionObj.PostureReport.ClusterCloudProvider = opaSessionObj.Report.ClusterCloudProvider
frameworks := []reporthandling.FrameworkReport{}
@@ -31,26 +30,12 @@ func ReportV2ToV1(opaSessionObj *OPASessionObj) *reporthandling.PostureReport {
fwv1.Score = opaSessionObj.Report.SummaryDetails.Score
}
// // remove unused data
// opaSessionObj.Report = nil
// opaSessionObj.ResourcesResult = nil
// setup counters and score
for f := range frameworks {
// // set exceptions
// exceptions.SetFrameworkExceptions(frameworks, opap.Exceptions, cautils.ClusterName)
// set counters
reporthandling.SetUniqueResourcesCounter(&frameworks[f])
// set default score
// reporthandling.SetDefaultScore(&frameworks[f])
}
// // update score
// scoreutil := score.NewScore(opaSessionObj.AllResources)
// scoreutil.Calculate(frameworks)
report.FrameworkReports = frameworks
return report
}
@@ -64,7 +49,6 @@ func controlReportV2ToV1(opaSessionObj *OPASessionObj, frameworkName string, con
crv1.Name = crv2.GetName()
crv1.Score = crv2.GetScore()
crv1.Control_ID = controlID
// crv1.Attributes = crv2.
// TODO - add fields
crv1.Description = crv2.Description
@@ -72,7 +56,9 @@ func controlReportV2ToV1(opaSessionObj *OPASessionObj, frameworkName string, con
rulesv1 := map[string]reporthandling.RuleReport{}
for _, resourceID := range crv2.ListResourcesIDs().All() {
iter := crv2.ListResourcesIDs().All()
for iter.HasNext() {
resourceID := iter.Next()
if result, ok := opaSessionObj.ResourcesResult[resourceID]; ok {
for _, rulev2 := range result.ListRulesOfControl(crv2.GetID(), "") {

View File

@@ -5,9 +5,10 @@ type RootInfo struct {
LoggerName string // logger name ("pretty"/"zap"/"none")
CacheDir string // cached dir
DisableColor bool // Disable Color
EnableColor bool // Force enable Color
ArmoBEURLs string // armo url
ArmoBEURLsDep string // armo url
KSCloudBEURLs string // Kubescape Cloud URL
KSCloudBEURLsDep string // Kubescape Cloud URL
}
@@ -16,81 +17,3 @@ type Credentials struct {
ClientID string
SecretKey string
}
// func (rootInfo *RootInfo) InitLogger() {
// logger.DisableColor(rootInfo.DisableColor)
// if rootInfo.LoggerName == "" {
// if l := os.Getenv("KS_LOGGER_NAME"); l != "" {
// rootInfo.LoggerName = l
// } else {
// if isatty.IsTerminal(os.Stdout.Fd()) {
// rootInfo.LoggerName = "pretty"
// } else {
// rootInfo.LoggerName = "zap"
// }
// }
// }
// logger.InitLogger(rootInfo.LoggerName)
// }
// func (rootInfo *RootInfo) InitLoggerLevel() error {
// if rootInfo.Logger == helpers.InfoLevel.String() {
// } else if l := os.Getenv("KS_LOGGER"); l != "" {
// rootInfo.Logger = l
// }
// if err := logger.L().SetLevel(rootInfo.Logger); err != nil {
// return fmt.Errorf("supported levels: %s", strings.Join(helpers.SupportedLevels(), "/"))
// }
// return nil
// }
// func (rootInfo *RootInfo) InitCacheDir() error {
// if rootInfo.CacheDir == getter.DefaultLocalStore {
// getter.DefaultLocalStore = rootInfo.CacheDir
// } else if cacheDir := os.Getenv("KS_CACHE_DIR"); cacheDir != "" {
// getter.DefaultLocalStore = cacheDir
// } else {
// return nil // using default cache dir location
// }
// // TODO create dir if not found exist
// // logger.L().Debug("cache dir updated", helpers.String("path", getter.DefaultLocalStore))
// return nil
// }
// func (rootInfo *RootInfo) InitEnvironment() error {
// urlSlices := strings.Split(rootInfo.ArmoBEURLs, ",")
// if len(urlSlices) != 1 && len(urlSlices) < 3 {
// return fmt.Errorf("expected at least 2 URLs (report,api,frontend,auth)")
// }
// switch len(urlSlices) {
// case 1:
// switch urlSlices[0] {
// case "dev", "development":
// getter.SetARMOAPIConnector(getter.NewARMOAPIDev())
// case "stage", "staging":
// getter.SetARMOAPIConnector(getter.NewARMOAPIStaging())
// case "":
// getter.SetARMOAPIConnector(getter.NewARMOAPIProd())
// default:
// return fmt.Errorf("unknown environment")
// }
// case 2:
// armoERURL := urlSlices[0] // mandatory
// armoBEURL := urlSlices[1] // mandatory
// getter.SetARMOAPIConnector(getter.NewARMOAPICustomized(armoERURL, armoBEURL, "", ""))
// case 3, 4:
// var armoAUTHURL string
// armoERURL := urlSlices[0] // mandatory
// armoBEURL := urlSlices[1] // mandatory
// armoFEURL := urlSlices[2] // mandatory
// if len(urlSlices) <= 4 {
// armoAUTHURL = urlSlices[3]
// }
// getter.SetARMOAPIConnector(getter.NewARMOAPICustomized(armoERURL, armoBEURL, armoFEURL, armoAUTHURL))
// }
// return nil
// }

View File

@@ -9,15 +9,15 @@ import (
"strings"
"github.com/armosec/armoapi-go/armotypes"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
giturl "github.com/armosec/go-git-url"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/opa-utils/reporthandling"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/opa-utils/reporthandling"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/google/uuid"
)
@@ -117,9 +117,9 @@ type ScanInfo struct {
InputPatterns []string // Yaml files input patterns
Silent bool // Silent mode - Do not print progress logs
FailThreshold float32 // Failure score threshold
Submit bool // Submit results to Armo BE
Submit bool // Submit results to Kubescape Cloud BE
ScanID string // Report id of the current scan
HostSensorEnabled BoolPtrFlag // Deploy ARMO K8s host scanner to collect data from certain controls
HostSensorEnabled BoolPtrFlag // Deploy Kubescape K8s host scanner to collect data from certain controls
HostSensorYamlPath string // Path to hostsensor file
Local bool // Do not submit results
Credentials Credentials // account ID

View File

@@ -3,7 +3,7 @@ package cautils
import (
"testing"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/stretchr/testify/assert"
)
@@ -20,7 +20,7 @@ func TestSetContextMetadata(t *testing.T) {
}
{
ctx := reporthandlingv2.ContextMetadata{}
setContextMetadata(&ctx, "https://github.com/armosec/kubescape")
setContextMetadata(&ctx, "https://github.com/kubescape/kubescape")
assert.Nil(t, ctx.ClusterContextMetadata)
assert.Nil(t, ctx.DirectoryContextMetadata)
@@ -29,7 +29,7 @@ func TestSetContextMetadata(t *testing.T) {
assert.NotNil(t, ctx.RepoContextMetadata)
assert.Equal(t, "kubescape", ctx.RepoContextMetadata.Repo)
assert.Equal(t, "armosec", ctx.RepoContextMetadata.Owner)
assert.Equal(t, "kubescape", ctx.RepoContextMetadata.Owner)
assert.Equal(t, "master", ctx.RepoContextMetadata.Branch)
}
}
@@ -40,8 +40,5 @@ func TestGetHostname(t *testing.T) {
func TestGetScanningContext(t *testing.T) {
assert.Equal(t, ContextCluster, GetScanningContext(""))
// assert.Equal(t, ContextDir, GetScanningContext("/"))
assert.Equal(t, ContextGitURL, GetScanningContext("https://github.com/armosec/kubescape"))
// assert.Equal(t, ContextFile, GetScanningContext(path.Join(".", "testdata", "localrepo.git")))
// assert.Equal(t, ContextGitLocal, GetScanningContext(path.Join(".", "testdata")))
assert.Equal(t, ContextGitURL, GetScanningContext("https://github.com/kubescape/kubescape"))
}

View File

@@ -6,10 +6,10 @@ import (
"net/http"
"os"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/utils-go/boolutils"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"golang.org/x/mod/semver"
)

View File

@@ -4,7 +4,7 @@ import (
"testing"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/stretchr/testify/assert"
"golang.org/x/mod/semver"
)

View File

@@ -3,7 +3,7 @@ package cautils
import (
"strings"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/reporthandling/apis"
)
var (
@@ -21,9 +21,9 @@ var (
CloudResources = []string{"ClusterDescribe"}
)
func MapArmoResource(armoResourceMap *ArmoResources, resources []string) []string {
func MapKSResource(ksResourceMap *KSResources, resources []string) []string {
var hostResources []string
for k := range *armoResourceMap {
for k := range *ksResourceMap {
for _, resource := range resources {
if strings.Contains(k, resource) {
hostResources = append(hostResources, k)
@@ -33,16 +33,16 @@ func MapArmoResource(armoResourceMap *ArmoResources, resources []string) []strin
return hostResources
}
func MapHostResources(armoResourceMap *ArmoResources) []string {
return MapArmoResource(armoResourceMap, HostSensorResources)
func MapHostResources(ksResourceMap *KSResources) []string {
return MapKSResource(ksResourceMap, HostSensorResources)
}
func MapImageVulnResources(armoResourceMap *ArmoResources) []string {
return MapArmoResource(armoResourceMap, ImageVulnResources)
func MapImageVulnResources(ksResourceMap *KSResources) []string {
return MapKSResource(ksResourceMap, ImageVulnResources)
}
func MapCloudResources(armoResourceMap *ArmoResources) []string {
return MapArmoResource(armoResourceMap, CloudResources)
func MapCloudResources(ksResourceMap *KSResources) []string {
return MapKSResource(ksResourceMap, CloudResources)
}
func SetInfoMapForResources(info string, resources []string, errorMap map[string]apis.StatusInfo) {

View File

@@ -3,7 +3,7 @@ package core
import (
"fmt"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
)
func (ks *Kubescape) SetCachedConfig(setConfig *metav1.SetConfig) error {

View File

@@ -3,10 +3,10 @@ package core
import (
"fmt"
"github.com/armosec/kubescape/v2/core/cautils/getter"
v1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
v1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
)
func (ks *Kubescape) DeleteExceptions(delExceptions *v1.DeleteExceptions) error {
@@ -15,8 +15,8 @@ func (ks *Kubescape) DeleteExceptions(delExceptions *v1.DeleteExceptions) error
getTenantConfig(&delExceptions.Credentials, "", getKubernetesApi())
// login kubescape SaaS
armoAPI := getter.GetArmoAPIConnector()
if err := armoAPI.Login(); err != nil {
ksCloudAPI := getter.GetKSCloudAPIConnector()
if err := ksCloudAPI.Login(); err != nil {
return err
}
@@ -26,7 +26,7 @@ func (ks *Kubescape) DeleteExceptions(delExceptions *v1.DeleteExceptions) error
continue
}
logger.L().Info("Deleting exception", helpers.String("name", exceptionName))
if err := armoAPI.DeleteException(exceptionName); err != nil {
if err := ksCloudAPI.DeleteException(exceptionName); err != nil {
return fmt.Errorf("failed to delete exception '%s', reason: %s", exceptionName, err.Error())
}
logger.L().Success("Exception deleted successfully")

View File

@@ -7,10 +7,10 @@ import (
"strings"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/kubescape/v2/core/cautils/getter"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
)
var downloadFunc = map[string]func(*metav1.DownloadInfo) error{

View File

@@ -3,19 +3,19 @@ package core
import (
"fmt"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/pkg/hostsensorutils"
"github.com/armosec/kubescape/v2/core/pkg/resourcehandler"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter"
reporterv2 "github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter/v2"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/pkg/hostsensorutils"
"github.com/kubescape/kubescape/v2/core/pkg/resourcehandler"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter"
reporterv2 "github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter/v2"
"github.com/google/uuid"
"github.com/armosec/rbac-utils/rbacscanner"
"github.com/kubescape/rbac-utils/rbacscanner"
)
// getKubernetesApi
@@ -27,9 +27,9 @@ func getKubernetesApi() *k8sinterface.KubernetesApi {
}
func getTenantConfig(credentials *cautils.Credentials, clusterName string, k8s *k8sinterface.KubernetesApi) cautils.ITenantConfig {
if !k8sinterface.IsConnectedToCluster() || k8s == nil {
return cautils.NewLocalConfig(getter.GetArmoAPIConnector(), credentials, clusterName)
return cautils.NewLocalConfig(getter.GetKSCloudAPIConnector(), credentials, clusterName)
}
return cautils.NewClusterConfig(k8s, getter.GetArmoAPIConnector(), credentials, clusterName)
return cautils.NewClusterConfig(k8s, getter.GetKSCloudAPIConnector(), credentials, clusterName)
}
func getExceptionsGetter(useExceptions string) getter.IExceptionsGetter {
@@ -37,7 +37,7 @@ func getExceptionsGetter(useExceptions string) getter.IExceptionsGetter {
// load exceptions from file
return getter.NewLoadPolicy([]string{useExceptions})
} else {
return getter.GetArmoAPIConnector()
return getter.GetKSCloudAPIConnector()
}
}
@@ -73,7 +73,7 @@ func getResourceHandler(scanInfo *cautils.ScanInfo, tenantConfig cautils.ITenant
// scanInfo.HostSensor.SetBool(false)
return resourcehandler.NewFileResourceHandler(scanInfo.InputPatterns, registryAdaptors)
}
getter.GetArmoAPIConnector()
getter.GetKSCloudAPIConnector()
rbacObjects := getRBACHandler(tenantConfig, k8s, scanInfo.Submit)
return resourcehandler.NewK8sResourceHandler(k8s, getFieldSelector(scanInfo), hostSensorHandler, rbacObjects, registryAdaptors)
}
@@ -124,7 +124,7 @@ func policyIdentifierNames(pi []cautils.PolicyIdentifier) string {
return policiesNames
}
// setSubmitBehavior - Setup the desired cluster behavior regarding submitting to the Armo BE
// setSubmitBehavior - Setup the desired cluster behavior regarding submitting to the Kubescape Cloud BE
func setSubmitBehavior(scanInfo *cautils.ScanInfo, tenantConfig cautils.ITenantConfig) {
/*
@@ -165,13 +165,13 @@ func setSubmitBehavior(scanInfo *cautils.ScanInfo, tenantConfig cautils.ITenantC
}
// setPolicyGetter set the policy getter - local file/github release/ArmoAPI
// setPolicyGetter set the policy getter - local file/github release/Kubescape Cloud API
func getPolicyGetter(loadPoliciesFromFile []string, tennatEmail string, frameworkScope bool, downloadReleasedPolicy *getter.DownloadReleasedPolicy) getter.IPolicyGetter {
if len(loadPoliciesFromFile) > 0 {
return getter.NewLoadPolicy(loadPoliciesFromFile)
}
if tennatEmail != "" && frameworkScope {
g := getter.GetArmoAPIConnector() // download policy from ARMO backend
g := getter.GetKSCloudAPIConnector() // download policy from Kubescape Cloud backend
return g
}
if downloadReleasedPolicy == nil {
@@ -181,13 +181,13 @@ func getPolicyGetter(loadPoliciesFromFile []string, tennatEmail string, framewor
}
// setConfigInputsGetter sets the config input getter - local file/github release/ArmoAPI
// setConfigInputsGetter sets the config input getter - local file/github release/Kubescape Cloud API
func getConfigInputsGetter(ControlsInputs string, accountID string, downloadReleasedPolicy *getter.DownloadReleasedPolicy) getter.IControlsInputsGetter {
if len(ControlsInputs) > 0 {
return getter.NewLoadPolicy([]string{ControlsInputs})
}
if accountID != "" {
g := getter.GetArmoAPIConnector() // download config from ARMO backend
g := getter.GetKSCloudAPIConnector() // download config from Kubescape Cloud backend
return g
}
if downloadReleasedPolicy == nil {

View File

@@ -6,8 +6,8 @@ import (
"sort"
"strings"
"github.com/armosec/kubescape/v2/core/cautils/getter"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
)
var listFunc = map[string]func(*metav1.ListPolicies) ([]string, error){
@@ -66,8 +66,8 @@ func listExceptions(listPolicies *metav1.ListPolicies) ([]string, error) {
getTenantConfig(&listPolicies.Credentials, "", getKubernetesApi())
var exceptionsNames []string
armoAPI := getExceptionsGetter("")
exceptions, err := armoAPI.GetExceptions("")
ksCloudAPI := getExceptionsGetter("")
exceptions, err := ksCloudAPI.GetExceptions("")
if err != nil {
return exceptionsNames, err
}

View File

@@ -3,23 +3,24 @@ package core
import (
"fmt"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/pkg/hostsensorutils"
"github.com/armosec/kubescape/v2/core/pkg/opaprocessor"
"github.com/armosec/kubescape/v2/core/pkg/policyhandler"
"github.com/armosec/kubescape/v2/core/pkg/resourcehandler"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling/printer"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/pkg/hostsensorutils"
"github.com/kubescape/kubescape/v2/core/pkg/opaprocessor"
"github.com/kubescape/kubescape/v2/core/pkg/policyhandler"
"github.com/kubescape/kubescape/v2/core/pkg/resourcehandler"
"github.com/kubescape/kubescape/v2/core/pkg/resourcesprioritization"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/printer"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter"
"github.com/armosec/opa-utils/resources"
"github.com/kubescape/opa-utils/resources"
)
type componentInterfaces struct {
@@ -104,7 +105,7 @@ func getInterfaces(scanInfo *cautils.ScanInfo) componentInterfaces {
}
func (ks *Kubescape) Scan(scanInfo *cautils.ScanInfo) (*resultshandling.ResultsHandler, error) {
logger.L().Info("ARMO security scanner starting")
logger.L().Info("Kubescape scanner starting")
// ===================== Initialization =====================
scanInfo.Init() // initialize scan info
@@ -152,6 +153,12 @@ func (ks *Kubescape) Scan(scanInfo *cautils.ScanInfo) (*resultshandling.ResultsH
return resultsHandling, fmt.Errorf("%w", err)
}
// ======================== prioritization ===================
priotizationHandler := resourcesprioritization.NewResourcesPrioritizationHandler(true)
if err := priotizationHandler.PrioritizeResources(scanData); err != nil {
return resultsHandling, fmt.Errorf("%w", err)
}
// ========================= results handling =====================
resultsHandling.SetData(scanData)

View File

@@ -1,12 +1,12 @@
package core
import (
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/meta/cliinterfaces"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/meta/cliinterfaces"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
)
func (ks *Kubescape) Submit(submitInterfaces cliinterfaces.SubmitInterfaces) error {
@@ -52,12 +52,12 @@ func (ks *Kubescape) SubmitExceptions(credentials *cautils.Credentials, excPath
}
// login kubescape SaaS
armoAPI := getter.GetArmoAPIConnector()
if err := armoAPI.Login(); err != nil {
ksCloudAPI := getter.GetKSCloudAPIConnector()
if err := ksCloudAPI.Login(); err != nil {
return err
}
if err := armoAPI.PostExceptions(exceptions); err != nil {
if err := ksCloudAPI.PostExceptions(exceptions); err != nil {
return err
}
logger.L().Success("Exceptions submitted successfully")

View File

@@ -1,10 +1,10 @@
package cliinterfaces
import (
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling/reporter"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling/reporter"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
)
type ISubmitObjects interface {

View File

@@ -1,6 +1,6 @@
package v1
import "github.com/armosec/kubescape/v2/core/cautils"
import "github.com/kubescape/kubescape/v2/core/cautils"
type DeleteExceptions struct {
Credentials cautils.Credentials

View File

@@ -1,6 +1,6 @@
package v1
import "github.com/armosec/kubescape/v2/core/cautils"
import "github.com/kubescape/kubescape/v2/core/cautils"
type DownloadInfo struct {
Path string // directory to save artifact. Default is "~/.kubescape/"

View File

@@ -1,6 +1,6 @@
package v1
import "github.com/armosec/kubescape/v2/core/cautils"
import "github.com/kubescape/kubescape/v2/core/cautils"
type ListPolicies struct {
Target string

View File

@@ -1,6 +1,6 @@
package v1
import "github.com/armosec/kubescape/v2/core/cautils"
import "github.com/kubescape/kubescape/v2/core/cautils"
type Submit struct {
Credentials cautils.Credentials

View File

@@ -1,10 +1,10 @@
package meta
import (
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/meta/cliinterfaces"
metav1 "github.com/armosec/kubescape/v2/core/meta/datastructures/v1"
"github.com/armosec/kubescape/v2/core/pkg/resultshandling"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/meta/cliinterfaces"
metav1 "github.com/kubescape/kubescape/v2/core/meta/datastructures/v1"
"github.com/kubescape/kubescape/v2/core/pkg/resultshandling"
)
type IKubescape interface {

View File

@@ -4,8 +4,8 @@ import (
"encoding/json"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/reporthandling"
)
var mockControl_0006 = `{"guid":"","name":"Allowed hostPath","attributes":{"armoBuiltin":true},"id":"C-0006","controlID":"C-0006","creationTime":"","description":"Mounting host directory to the container can be abused to get access to sensitive data and gain persistence on the host machine.","remediation":"Refrain from using host path mount.","rules":[{"guid":"","name":"alert-rw-hostpath","attributes":{"armoBuiltin":true,"m$K8sThreatMatrix":"Persistence::Writable hostPath mount, Lateral Movement::Writable volume mounts on the host"},"creationTime":"","rule":"package armo_builtins\n\n# input: pod\n# apiversion: v1\n# does: returns hostPath volumes\n\ndeny[msga] {\n pod := input[_]\n pod.kind == \"Pod\"\n volumes := pod.spec.volumes\n volume := volumes[_]\n volume.hostPath\n\tcontainer := pod.spec.containers[i]\n\tvolumeMount := container.volumeMounts[k]\n\tvolumeMount.name == volume.name\n\tbegginingOfPath := \"spec.\"\n\tresult := isRWMount(volumeMount, begginingOfPath, i, k)\n\n podname := pod.metadata.name\n\n\tmsga := {\n\t\t\"alertMessage\": sprintf(\"pod: %v has: %v as hostPath volume\", [podname, volume.name]),\n\t\t\"packagename\": \"armo_builtins\",\n\t\t\"alertScore\": 7,\n\t\t\"failedPaths\": [result],\n\t\t\"alertObject\": {\n\t\t\t\"k8sApiObjects\": [pod]\n\t\t}\n\t}\n}\n\n#handles majority of workload resources\ndeny[msga] {\n\twl := input[_]\n\tspec_template_spec_patterns := {\"Deployment\",\"ReplicaSet\",\"DaemonSet\",\"StatefulSet\",\"Job\"}\n\tspec_template_spec_patterns[wl.kind]\n volumes := wl.spec.template.spec.volumes\n volume := volumes[_]\n volume.hostPath\n\tcontainer := wl.spec.template.spec.containers[i]\n\tvolumeMount := container.volumeMounts[k]\n\tvolumeMount.name == volume.name\n\tbegginingOfPath := \"spec.template.spec.\"\n\tresult := isRWMount(volumeMount, begginingOfPath, i, k)\n\n\tmsga := {\n\t\t\"alertMessage\": sprintf(\"%v: %v has: %v as hostPath volume\", [wl.kind, wl.metadata.name, volume.name]),\n\t\t\"packagename\": \"armo_builtins\",\n\t\t\"alertScore\": 7,\n\t\t\"failedPaths\": [result],\n\t\t\"alertObject\": {\n\t\t\t\"k8sApiObjects\": [wl]\n\t\t}\n\t\n\t}\n}\n\n#handles CronJobs\ndeny[msga] {\n\twl := input[_]\n\twl.kind == \"CronJob\"\n volumes := wl.spec.jobTemplate.spec.template.spec.volumes\n volume := volumes[_]\n volume.hostPath\n\n\tcontainer = wl.spec.jobTemplate.spec.template.spec.containers[i]\n\tvolumeMount := container.volumeMounts[k]\n\tvolumeMount.name == volume.name\n\tbegginingOfPath := \"spec.jobTemplate.spec.template.spec.\"\n\tresult := isRWMount(volumeMount, begginingOfPath, i, k)\n\n\tmsga := {\n\t\"alertMessage\": sprintf(\"%v: %v has: %v as hostPath volume\", [wl.kind, wl.metadata.name, volume.name]),\n\t\"packagename\": \"armo_builtins\",\n\t\"alertScore\": 7,\n\t\"failedPaths\": [result],\n\t\"alertObject\": {\n\t\t\t\"k8sApiObjects\": [wl]\n\t\t}\n\t}\n}\n\nisRWMount(mount, begginingOfPath, i, k) = path {\n not mount.readOnly == true\n not mount.readOnly == false\n path = \"\"\n}\nisRWMount(mount, begginingOfPath, i, k) = path {\n mount.readOnly == false\n path = sprintf(\"%vcontainers[%v].volumeMounts[%v].readOnly\", [begginingOfPath, format_int(i, 10), format_int(k, 10)])\n} ","resourceEnumerator":"","ruleLanguage":"Rego","match":[{"apiGroups":["*"],"apiVersions":["*"],"resources":["Deployment","ReplicaSet","DaemonSet","StatefulSet","Job","CronJob","Pod"]}],"ruleDependencies":[{"packageName":"cautils"},{"packageName":"kubernetes.api.client"}],"configInputs":null,"controlConfigInputs":null,"description":"determines if any workload contains a hostPath volume with rw permissions","remediation":"Set the readOnly field of the mount to true","ruleQuery":""}],"rulesIDs":[""],"baseScore":6}`

View File

@@ -33,7 +33,7 @@ spec:
effect: NoSchedule
containers:
- name: host-sensor
image: quay.io/armosec/kube-host-sensor:latest
image: quay.io/kubescape/host-scanner:latest
securityContext:
privileged: true
readOnlyRootFilesystem: true

View File

@@ -8,11 +8,11 @@ import (
"sync"
"time"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/kubescape/v2/core/cautils"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
appsv1 "k8s.io/api/apps/v1"
corev1 "k8s.io/api/core/v1"

View File

@@ -5,11 +5,11 @@ import (
"fmt"
"sync"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/opa-utils/objectsenvelopes/hostsensor"
"github.com/armosec/opa-utils/reporthandling/apis"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/opa-utils/objectsenvelopes/hostsensor"
"github.com/kubescape/opa-utils/reporthandling/apis"
"sigs.k8s.io/yaml"
)

View File

@@ -1,8 +1,8 @@
package hostsensorutils
import (
"github.com/armosec/opa-utils/objectsenvelopes/hostsensor"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/objectsenvelopes/hostsensor"
"github.com/kubescape/opa-utils/reporthandling/apis"
)
type IHostSensor interface {

View File

@@ -1,8 +1,8 @@
package hostsensorutils
import (
"github.com/armosec/opa-utils/objectsenvelopes/hostsensor"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/objectsenvelopes/hostsensor"
"github.com/kubescape/opa-utils/reporthandling/apis"
)
type HostSensorHandlerMock struct {

View File

@@ -3,9 +3,9 @@ package hostsensorutils
import (
"sync"
"github.com/armosec/opa-utils/objectsenvelopes/hostsensor"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/opa-utils/objectsenvelopes/hostsensor"
)
const noOfWorkers int = 10

View File

@@ -1,8 +1,8 @@
package hostsensorutils
import (
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/opa-utils/reporthandling/apis"
)
var (

View File

@@ -6,21 +6,21 @@ import (
"time"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/pkg/score"
"github.com/armosec/opa-utils/objectsenvelopes"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/armosec/opa-utils/reporthandling/results/v1/resourcesresults"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/score"
"github.com/kubescape/opa-utils/objectsenvelopes"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/reporthandling/results/v1/resourcesresults"
"github.com/open-policy-agent/opa/storage"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
reporthandlingv2 "github.com/armosec/opa-utils/reporthandling/v2"
"github.com/armosec/opa-utils/resources"
reporthandlingv2 "github.com/kubescape/opa-utils/reporthandling/v2"
"github.com/kubescape/opa-utils/resources"
"github.com/open-policy-agent/opa/ast"
"github.com/open-policy-agent/opa/rego"
)
@@ -122,7 +122,7 @@ func (opap *OPAProcessor) processControl(control *reporthandling.Control) (map[s
// ruleResults := make(map[string][]resourcesresults.ResourceAssociatedRule)
for i := range control.Rules {
resourceAssociatedRule, err := opap.processRule(&control.Rules[i])
resourceAssociatedRule, err := opap.processRule(&control.Rules[i], control.FixedInput)
if err != nil {
logger.L().Error(err.Error())
continue
@@ -150,10 +150,15 @@ func (opap *OPAProcessor) processControl(control *reporthandling.Control) (map[s
return resourcesAssociatedControl, errs
}
func (opap *OPAProcessor) processRule(rule *reporthandling.PolicyRule) (map[string]*resourcesresults.ResourceAssociatedRule, error) {
func (opap *OPAProcessor) processRule(rule *reporthandling.PolicyRule, fixedControlInputs map[string][]string) (map[string]*resourcesresults.ResourceAssociatedRule, error) {
postureControlInputs := opap.regoDependenciesData.GetFilteredPostureControlInputs(rule.ConfigInputs) // get store
// Merge configurable control input and fixed control input
for k, v := range fixedControlInputs {
postureControlInputs[k] = v
}
inputResources, err := reporthandling.RegoResourcesAggregator(rule, getAllSupportedObjects(opap.K8SResources, opap.ArmoResource, opap.AllResources, rule))
if err != nil {
return nil, fmt.Errorf("error getting aggregated k8sObjects: %s", err.Error())

View File

@@ -4,13 +4,13 @@ import (
"testing"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/mocks"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/resources"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/mocks"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/resources"
"github.com/stretchr/testify/assert"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
// _ "k8s.io/client-go/plugin/pkg/client/auth"
)
@@ -42,7 +42,7 @@ func TestProcessResourcesResult(t *testing.T) {
assert.Equal(t, 1, len(opaSessionObj.ResourcesResult))
res := opaSessionObj.ResourcesResult[deployment.GetID()]
assert.Equal(t, 2, len(res.ListControlsIDs(nil).All()))
assert.Equal(t, 2, res.ListControlsIDs(nil).All().Len())
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Failed()))
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Passed()))
assert.True(t, res.GetStatus(nil).IsFailed())
@@ -51,8 +51,8 @@ func TestProcessResourcesResult(t *testing.T) {
opap.updateResults()
res = opaSessionObj.ResourcesResult[deployment.GetID()]
assert.Equal(t, 2, len(res.ListControlsIDs(nil).All()))
assert.Equal(t, 2, len(res.ListControlsIDs(nil).All()))
assert.Equal(t, 2, res.ListControlsIDs(nil).All().Len())
assert.Equal(t, 2, res.ListControlsIDs(nil).All().Len())
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Failed()))
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Passed()))
assert.True(t, res.GetStatus(nil).IsFailed())
@@ -67,13 +67,13 @@ func TestProcessResourcesResult(t *testing.T) {
assert.Equal(t, 0, summaryDetails.NumberOfResources().Passed())
// test resource listing
assert.Equal(t, 1, len(summaryDetails.ListResourcesIDs().All()))
assert.Equal(t, 1, summaryDetails.ListResourcesIDs().All().Len())
assert.Equal(t, 1, len(summaryDetails.ListResourcesIDs().Failed()))
assert.Equal(t, 0, len(summaryDetails.ListResourcesIDs().Excluded()))
assert.Equal(t, 0, len(summaryDetails.ListResourcesIDs().Passed()))
// test control listing
assert.Equal(t, len(res.ListControlsIDs(nil).All()), summaryDetails.NumberOfControls().All())
assert.Equal(t, res.ListControlsIDs(nil).All().Len(), summaryDetails.NumberOfControls().All())
assert.Equal(t, len(res.ListControlsIDs(nil).Passed()), summaryDetails.NumberOfControls().Passed())
assert.Equal(t, len(res.ListControlsIDs(nil).Failed()), summaryDetails.NumberOfControls().Failed())
assert.Equal(t, len(res.ListControlsIDs(nil).Excluded()), summaryDetails.NumberOfControls().Excluded())
@@ -83,7 +83,7 @@ func TestProcessResourcesResult(t *testing.T) {
opap.updateResults()
res = opaSessionObj.ResourcesResult[deployment.GetID()]
assert.Equal(t, 2, len(res.ListControlsIDs(nil).All()))
assert.Equal(t, 2, res.ListControlsIDs(nil).All().Len())
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Excluded()))
assert.Equal(t, 1, len(res.ListControlsIDs(nil).Passed()))
assert.True(t, res.GetStatus(nil).IsExcluded())
@@ -93,7 +93,7 @@ func TestProcessResourcesResult(t *testing.T) {
// test resource listing
summaryDetails = opaSessionObj.Report.SummaryDetails
assert.Equal(t, 1, len(summaryDetails.ListResourcesIDs().All()))
assert.Equal(t, 1, summaryDetails.ListResourcesIDs().All().Len())
assert.Equal(t, 1, len(summaryDetails.ListResourcesIDs().Failed()))
assert.Equal(t, 0, len(summaryDetails.ListResourcesIDs().Excluded()))
assert.Equal(t, 0, len(summaryDetails.ListResourcesIDs().Passed()))

View File

@@ -1,15 +1,15 @@
package opaprocessor
import (
"github.com/armosec/kubescape/v2/core/cautils"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/reporthandling/apis"
"github.com/armosec/opa-utils/reporthandling/results/v1/reportsummary"
resources "github.com/armosec/opa-utils/resources"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling/apis"
"github.com/kubescape/opa-utils/reporthandling/results/v1/reportsummary"
resources "github.com/kubescape/opa-utils/resources"
)
// updateResults update the results objects and report objects. This is a critical function - DO NOT CHANGE
@@ -84,14 +84,14 @@ func isEmptyResources(counters reportsummary.ICounters) bool {
return counters.Failed() == 0 && counters.Excluded() == 0 && counters.Passed() == 0
}
func getAllSupportedObjects(k8sResources *cautils.K8SResources, armoResources *cautils.ArmoResources, allResources map[string]workloadinterface.IMetadata, rule *reporthandling.PolicyRule) []workloadinterface.IMetadata {
func getAllSupportedObjects(k8sResources *cautils.K8SResources, ksResources *cautils.KSResources, allResources map[string]workloadinterface.IMetadata, rule *reporthandling.PolicyRule) []workloadinterface.IMetadata {
k8sObjects := []workloadinterface.IMetadata{}
k8sObjects = append(k8sObjects, getKubernetesObjects(k8sResources, allResources, rule.Match)...)
k8sObjects = append(k8sObjects, getArmoObjects(armoResources, allResources, rule.DynamicMatch)...)
k8sObjects = append(k8sObjects, getKSObjects(ksResources, allResources, rule.DynamicMatch)...)
return k8sObjects
}
func getArmoObjects(k8sResources *cautils.ArmoResources, allResources map[string]workloadinterface.IMetadata, match []reporthandling.RuleMatchObjects) []workloadinterface.IMetadata {
func getKSObjects(k8sResources *cautils.KSResources, allResources map[string]workloadinterface.IMetadata, match []reporthandling.RuleMatchObjects) []workloadinterface.IMetadata {
k8sObjects := []workloadinterface.IMetadata{}
for m := range match {

View File

@@ -5,7 +5,7 @@ import (
"github.com/stretchr/testify/assert"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
)
func TestRemoveData(t *testing.T) {

View File

@@ -1,9 +1,9 @@
package opaprocessor
import (
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/reporthandling/results/v1/reportsummary"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling/results/v1/reportsummary"
)
// ConvertFrameworksToPolicies convert list of frameworks to list of policies

View File

@@ -5,9 +5,9 @@ import (
"github.com/stretchr/testify/assert"
"github.com/armosec/kubescape/v2/core/mocks"
"github.com/armosec/opa-utils/reporthandling"
"github.com/armosec/opa-utils/reporthandling/results/v1/reportsummary"
"github.com/kubescape/kubescape/v2/core/mocks"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/kubescape/opa-utils/reporthandling/results/v1/reportsummary"
)
func TestConvertFrameworksToPolicies(t *testing.T) {

View File

@@ -4,8 +4,8 @@ import (
"fmt"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/pkg/resourcehandler"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/resourcehandler"
)
// PolicyHandler -
@@ -49,14 +49,14 @@ func (policyHandler *PolicyHandler) CollectResources(policyIdentifier []cautils.
func (policyHandler *PolicyHandler) getResources(policyIdentifier []cautils.PolicyIdentifier, opaSessionObj *cautils.OPASessionObj, scanInfo *cautils.ScanInfo) error {
opaSessionObj.Report.ClusterAPIServerInfo = policyHandler.resourceHandler.GetClusterAPIServerInfo()
resourcesMap, allResources, armoResources, err := policyHandler.resourceHandler.GetResources(opaSessionObj, &policyIdentifier[0].Designators)
resourcesMap, allResources, ksResources, err := policyHandler.resourceHandler.GetResources(opaSessionObj, &policyIdentifier[0].Designators)
if err != nil {
return err
}
opaSessionObj.K8SResources = resourcesMap
opaSessionObj.AllResources = allResources
opaSessionObj.ArmoResource = armoResources
opaSessionObj.ArmoResource = ksResources
return nil
}

View File

@@ -4,13 +4,13 @@ import (
"fmt"
"strings"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/opa-utils/reporthandling"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/opa-utils/reporthandling"
)
func (policyHandler *PolicyHandler) getPolicies(policyIdentifier []cautils.PolicyIdentifier, policiesAndResources *cautils.OPASessionObj) error {

View File

@@ -4,9 +4,9 @@ import (
"fmt"
"strings"
apisv1 "github.com/armosec/opa-utils/httpserver/apis/v1"
apisv1 "github.com/kubescape/opa-utils/httpserver/apis/v1"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils"
)
func getScanKind(policyIdentifier []cautils.PolicyIdentifier) apisv1.NotificationPolicyKind {

View File

@@ -4,29 +4,29 @@ import (
"encoding/json"
"fmt"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/armosec/kubescape/v2/core/pkg/containerscan"
"github.com/armosec/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/pkg/containerscan"
"github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
)
func NewArmoAdaptor(armoAPI *getter.ArmoAPI) *ArmoCivAdaptor {
return &ArmoCivAdaptor{
armoAPI: armoAPI,
func NewKSAdaptor(api *getter.KSCloudAPI) *KSCivAdaptor {
return &KSCivAdaptor{
ksCloudAPI: api,
}
}
func (armoCivAdaptor *ArmoCivAdaptor) Login() error {
if armoCivAdaptor.armoAPI.IsLoggedIn() {
func (ksCivAdaptor *KSCivAdaptor) Login() error {
if ksCivAdaptor.ksCloudAPI.IsLoggedIn() {
return nil
}
return armoCivAdaptor.armoAPI.Login()
return ksCivAdaptor.ksCloudAPI.Login()
}
func (armoCivAdaptor *ArmoCivAdaptor) GetImagesVulnerabilities(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageVulnerabilityReport, error) {
func (ksCivAdaptor *KSCivAdaptor) GetImagesVulnerabilities(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageVulnerabilityReport, error) {
resultList := make([]registryvulnerabilities.ContainerImageVulnerabilityReport, 0)
for _, imageID := range imageIDs {
result, err := armoCivAdaptor.GetImageVulnerability(&imageID)
result, err := ksCivAdaptor.GetImageVulnerability(&imageID)
if err == nil {
resultList = append(resultList, *result)
} else {
@@ -36,9 +36,9 @@ func (armoCivAdaptor *ArmoCivAdaptor) GetImagesVulnerabilities(imageIDs []regist
return resultList, nil
}
func (armoCivAdaptor *ArmoCivAdaptor) GetImageVulnerability(imageID *registryvulnerabilities.ContainerImageIdentifier) (*registryvulnerabilities.ContainerImageVulnerabilityReport, error) {
func (ksCivAdaptor *KSCivAdaptor) GetImageVulnerability(imageID *registryvulnerabilities.ContainerImageIdentifier) (*registryvulnerabilities.ContainerImageVulnerabilityReport, error) {
// First
containerScanId, err := armoCivAdaptor.getImageLastScanId(imageID)
containerScanId, err := ksCivAdaptor.getImageLastScanId(imageID)
if err != nil {
return nil, err
}
@@ -51,9 +51,9 @@ func (armoCivAdaptor *ArmoCivAdaptor) GetImageVulnerability(imageID *registryvul
pageNumber := 1
request := V2ListRequest{PageSize: &pageSize, PageNum: &pageNumber, InnerFilters: filter, OrderBy: "timestamp:desc"}
requestBody, _ := json.Marshal(request)
requestUrl := fmt.Sprintf("https://%s/api/v1/vulnerability/scanResultsDetails?customerGUID=%s", armoCivAdaptor.armoAPI.GetApiURL(), armoCivAdaptor.armoAPI.GetAccountID())
requestUrl := fmt.Sprintf("https://%s/api/v1/vulnerability/scanResultsDetails?customerGUID=%s", ksCivAdaptor.ksCloudAPI.GetApiURL(), ksCivAdaptor.ksCloudAPI.GetAccountID())
resp, err := armoCivAdaptor.armoAPI.Post(requestUrl, map[string]string{"Content-Type": "application/json"}, requestBody)
resp, err := ksCivAdaptor.ksCloudAPI.Post(requestUrl, map[string]string{"Content-Type": "application/json"}, requestBody)
if err != nil {
return nil, err
}
@@ -82,16 +82,16 @@ func (armoCivAdaptor *ArmoCivAdaptor) GetImageVulnerability(imageID *registryvul
return &resultImageVulnerabilityReport, nil
}
func (armoCivAdaptor *ArmoCivAdaptor) DescribeAdaptor() string {
func (ksCivAdaptor *KSCivAdaptor) DescribeAdaptor() string {
return "armo image vulnerabilities scanner, docs: https://hub.armosec.io/docs/configuration-of-image-vulnerabilities"
}
func (armoCivAdaptor *ArmoCivAdaptor) GetImagesInformation(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageInformation, error) {
func (ksCivAdaptor *KSCivAdaptor) GetImagesInformation(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageInformation, error) {
// TODO
return []registryvulnerabilities.ContainerImageInformation{}, nil
}
func (armoCivAdaptor *ArmoCivAdaptor) GetImagesScanStatus(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageScanStatus, error) {
func (ksCivAdaptor *KSCivAdaptor) GetImagesScanStatus(imageIDs []registryvulnerabilities.ContainerImageIdentifier) ([]registryvulnerabilities.ContainerImageScanStatus, error) {
// TODO
return []registryvulnerabilities.ContainerImageScanStatus{}, nil
}

View File

@@ -3,7 +3,7 @@ package v1
import (
"testing"
"github.com/armosec/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
"github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
"github.com/stretchr/testify/assert"
)

View File

@@ -3,8 +3,8 @@ package v1
import (
"encoding/json"
"github.com/armosec/kubescape/v2/core/pkg/containerscan"
"github.com/armosec/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
"github.com/kubescape/kubescape/v2/core/pkg/containerscan"
"github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
)
type ArmoCivAdaptorMock struct {

View File

@@ -4,19 +4,19 @@ import (
"encoding/json"
"fmt"
"github.com/armosec/kubescape/v2/core/pkg/containerscan"
"github.com/armosec/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
"github.com/kubescape/kubescape/v2/core/pkg/containerscan"
"github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
)
func (armoCivAdaptor *ArmoCivAdaptor) getImageLastScanId(imageID *registryvulnerabilities.ContainerImageIdentifier) (string, error) {
func (armoCivAdaptor *KSCivAdaptor) getImageLastScanId(imageID *registryvulnerabilities.ContainerImageIdentifier) (string, error) {
filter := []map[string]string{{"imageTag": imageID.Tag, "status": "Success"}}
pageSize := 1
pageNumber := 1
request := V2ListRequest{PageSize: &pageSize, PageNum: &pageNumber, InnerFilters: filter, OrderBy: "timestamp:desc"}
requestBody, _ := json.Marshal(request)
requestUrl := fmt.Sprintf("https://%s/api/v1/vulnerability/scanResultsSumSummary?customerGUID=%s", armoCivAdaptor.armoAPI.GetApiURL(), armoCivAdaptor.armoAPI.GetAccountID())
requestUrl := fmt.Sprintf("https://%s/api/v1/vulnerability/scanResultsSumSummary?customerGUID=%s", armoCivAdaptor.ksCloudAPI.GetApiURL(), armoCivAdaptor.ksCloudAPI.GetAccountID())
resp, err := armoCivAdaptor.armoAPI.Post(requestUrl, map[string]string{"Content-Type": "application/json"}, requestBody)
resp, err := armoCivAdaptor.ksCloudAPI.Post(requestUrl, map[string]string{"Content-Type": "application/json"}, requestBody)
if err != nil {
return "", err
}

View File

@@ -3,7 +3,7 @@ package v1
import (
"time"
"github.com/armosec/kubescape/v2/core/cautils/getter"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
)
type V2ListRequest struct {
@@ -30,6 +30,7 @@ type V2ListRequest struct {
FieldsList []string `json:"includeFields,omitempty"`
FieldsReverseKeywordMap map[string]string `json:"-,omitempty"`
}
type ArmoCivAdaptor struct {
armoAPI *getter.ArmoAPI
type KSCivAdaptor struct {
ksCloudAPI *getter.KSCloudAPI
}

View File

@@ -4,7 +4,7 @@ import (
"fmt"
"strings"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/k8sinterface"
"k8s.io/apimachinery/pkg/runtime/schema"
)

View File

@@ -3,7 +3,7 @@ package resourcehandler
import (
"testing"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/stretchr/testify/assert"
"k8s.io/apimachinery/pkg/runtime/schema"
)

View File

@@ -6,14 +6,14 @@ import (
"path/filepath"
"github.com/armosec/armoapi-go/armotypes"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/opa-utils/reporthandling"
"k8s.io/apimachinery/pkg/version"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
)
// FileResourceHandler handle resources from files and URLs
@@ -30,26 +30,69 @@ func NewFileResourceHandler(inputPatterns []string, registryAdaptors *RegistryAd
}
}
func (fileHandler *FileResourceHandler) GetResources(sessionObj *cautils.OPASessionObj, designator *armotypes.PortalDesignator) (*cautils.K8SResources, map[string]workloadinterface.IMetadata, *cautils.ArmoResources, error) {
func (fileHandler *FileResourceHandler) GetResources(sessionObj *cautils.OPASessionObj, designator *armotypes.PortalDesignator) (*cautils.K8SResources, map[string]workloadinterface.IMetadata, *cautils.KSResources, error) {
//
// build resources map
// map resources based on framework required resources: map["/group/version/kind"][]<k8s workloads ids>
k8sResources := setK8sResourceMap(sessionObj.Policies)
allResources := map[string]workloadinterface.IMetadata{}
workloadIDToSource := make(map[string]reporthandling.Source, 0)
armoResources := &cautils.ArmoResources{}
workloads := []workloadinterface.IMetadata{}
ksResources := &cautils.KSResources{}
if len(fileHandler.inputPatterns) == 0 {
return nil, nil, nil, fmt.Errorf("missing input")
}
path := fileHandler.inputPatterns[0]
logger.L().Info("Accessing local objects")
cautils.StartSpinner()
for path := range fileHandler.inputPatterns {
workloadIDToSource, workloads, err := getResourcesFromPath(fileHandler.inputPatterns[path])
if err != nil {
return nil, allResources, nil, err
}
if len(workloads) == 0 {
logger.L().Debug("path ignored because contains only a non-kubernetes file", helpers.String("path", fileHandler.inputPatterns[path]))
}
for k, v := range workloadIDToSource {
sessionObj.ResourceSource[k] = v
}
// map all resources: map["/apiVersion/version/kind"][]<k8s workloads>
mappedResources := mapResources(workloads)
// save only relevant resources
for i := range mappedResources {
if _, ok := (*k8sResources)[i]; ok {
ids := []string{}
for j := range mappedResources[i] {
ids = append(ids, mappedResources[i][j].GetID())
allResources[mappedResources[i][j].GetID()] = mappedResources[i][j]
}
(*k8sResources)[i] = append((*k8sResources)[i], ids...)
}
}
}
if err := fileHandler.registryAdaptors.collectImagesVulnerabilities(k8sResources, allResources, ksResources); err != nil {
logger.L().Warning("failed to collect images vulnerabilities", helpers.Error(err))
}
cautils.StopSpinner()
logger.L().Success("Done accessing local objects")
return k8sResources, allResources, ksResources, nil
}
func getResourcesFromPath(path string) (map[string]reporthandling.Source, []workloadinterface.IMetadata, error) {
workloadIDToSource := make(map[string]reporthandling.Source, 0)
workloads := []workloadinterface.IMetadata{}
clonedRepo, err := cloneGitRepo(&path)
if err != nil {
return nil, allResources, nil, err
return nil, nil, err
}
if clonedRepo != "" {
defer os.RemoveAll(clonedRepo)
@@ -63,9 +106,6 @@ func (fileHandler *FileResourceHandler) GetResources(sessionObj *cautils.OPASess
}
// load resource from local file system
logger.L().Info("Accessing local objects")
cautils.StartSpinner()
sourceToWorkloads := cautils.LoadResourcesFromFiles(path, repoRoot)
// update workloads and workloadIDToSource
@@ -156,37 +196,7 @@ func (fileHandler *FileResourceHandler) GetResources(sessionObj *cautils.OPASess
logger.L().Debug("helm templates found in local storage", helpers.Int("helmTemplates", len(helmSourceToWorkloads)), helpers.Int("workloads", len(workloads)))
}
// addCommitData(fileHandler.inputPatterns[0], workloadIDToSource)
if len(workloads) == 0 {
return nil, allResources, nil, fmt.Errorf("empty list of workloads - no workloads found")
}
sessionObj.ResourceSource = workloadIDToSource
// map all resources: map["/apiVersion/version/kind"][]<k8s workloads>
mappedResources := mapResources(workloads)
// save only relevant resources
for i := range mappedResources {
if _, ok := (*k8sResources)[i]; ok {
ids := []string{}
for j := range mappedResources[i] {
ids = append(ids, mappedResources[i][j].GetID())
allResources[mappedResources[i][j].GetID()] = mappedResources[i][j]
}
(*k8sResources)[i] = ids
}
}
if err := fileHandler.registryAdaptors.collectImagesVulnerabilities(k8sResources, allResources, armoResources); err != nil {
logger.L().Warning("failed to collect images vulnerabilities", helpers.Error(err))
}
cautils.StopSpinner()
logger.L().Success("Accessed to local objects")
return k8sResources, allResources, armoResources, nil
return workloadIDToSource, workloads, nil
}
func (fileHandler *FileResourceHandler) GetClusterAPIServerInfo() *version.Info {

View File

@@ -5,12 +5,12 @@ import (
"path/filepath"
giturl "github.com/armosec/go-git-url"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/opa-utils/reporthandling"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/opa-utils/reporthandling"
)
// Clone git repository
@@ -18,7 +18,7 @@ func cloneGitRepo(path *string) (string, error) {
var clonedDir string
// Clone git repository if needed
gitURL, err := giturl.NewGitURL(*path)
gitURL, err := giturl.NewGitAPI(*path)
if err == nil {
logger.L().Info("cloning", helpers.String("repository url", gitURL.GetURL().String()))
cautils.StartSpinner()

View File

@@ -5,16 +5,16 @@ import (
"fmt"
"strings"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/pkg/hostsensorutils"
"github.com/armosec/opa-utils/objectsenvelopes"
"github.com/armosec/opa-utils/reporthandling/apis"
logger "github.com/dwertent/go-logger"
"github.com/dwertent/go-logger/helpers"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/go-logger/helpers"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/pkg/hostsensorutils"
"github.com/kubescape/opa-utils/objectsenvelopes"
"github.com/kubescape/opa-utils/reporthandling/apis"
"github.com/armosec/k8s-interface/cloudsupport"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/kubescape/k8s-interface/cloudsupport"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/armosec/armoapi-go/armotypes"
@@ -45,7 +45,7 @@ func NewK8sResourceHandler(k8s *k8sinterface.KubernetesApi, fieldSelector IField
}
}
func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessionObj, designator *armotypes.PortalDesignator) (*cautils.K8SResources, map[string]workloadinterface.IMetadata, *cautils.ArmoResources, error) {
func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessionObj, designator *armotypes.PortalDesignator) (*cautils.K8SResources, map[string]workloadinterface.IMetadata, *cautils.KSResources, error) {
allResources := map[string]workloadinterface.IMetadata{}
// get k8s resources
@@ -61,14 +61,14 @@ func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessio
_, namespace, labels := armotypes.DigestPortalDesignator(designator)
// pull k8s recourses
armoResourceMap := setArmoResourceMap(sessionObj.Policies, resourceToControl)
ksResourceMap := setKSResourceMap(sessionObj.Policies, resourceToControl)
// map of armo resources to control_ids
// map of Kubescape resources to control_ids
sessionObj.ResourceToControlsMap = resourceToControl
if err := k8sHandler.pullResources(k8sResourcesMap, allResources, namespace, labels); err != nil {
cautils.StopSpinner()
return k8sResourcesMap, allResources, armoResourceMap, err
return k8sResourcesMap, allResources, ksResourceMap, err
}
numberOfWorkerNodes, err := k8sHandler.pullWorkerNodesNumber()
@@ -76,29 +76,27 @@ func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessio
if err != nil {
logger.L().Debug("failed to collect worker nodes number", helpers.Error(err))
} else {
if sessionObj.Metadata != nil && sessionObj.Metadata.ContextMetadata.ClusterContextMetadata != nil {
sessionObj.Metadata.ContextMetadata.ClusterContextMetadata.NumberOfWorkerNodes = numberOfWorkerNodes
}
sessionObj.SetNumberOfWorkerNodes(numberOfWorkerNodes)
}
imgVulnResources := cautils.MapImageVulnResources(armoResourceMap)
imgVulnResources := cautils.MapImageVulnResources(ksResourceMap)
// check that controls use image vulnerability resources
if len(imgVulnResources) > 0 {
if err := k8sHandler.registryAdaptors.collectImagesVulnerabilities(k8sResourcesMap, allResources, armoResourceMap); err != nil {
if err := k8sHandler.registryAdaptors.collectImagesVulnerabilities(k8sResourcesMap, allResources, ksResourceMap); err != nil {
logger.L().Warning("failed to collect image vulnerabilities", helpers.Error(err))
cautils.SetInfoMapForResources(fmt.Sprintf("failed to pull image scanning data: %s. for more information: https://hub.armosec.io/docs/configuration-of-image-vulnerabilities", err.Error()), imgVulnResources, sessionObj.InfoMap)
} else {
if isEmptyImgVulns(*armoResourceMap) {
if isEmptyImgVulns(*ksResourceMap) {
cautils.SetInfoMapForResources("image scanning is not configured. for more information: https://hub.armosec.io/docs/configuration-of-image-vulnerabilities", imgVulnResources, sessionObj.InfoMap)
}
}
}
hostResources := cautils.MapHostResources(armoResourceMap)
hostResources := cautils.MapHostResources(ksResourceMap)
// check that controls use host sensor resources
if len(hostResources) > 0 {
if sessionObj.Metadata.ScanMetadata.HostScanner {
infoMap, err := k8sHandler.collectHostResources(allResources, armoResourceMap)
infoMap, err := k8sHandler.collectHostResources(allResources, ksResourceMap)
if err != nil {
logger.L().Warning("failed to collect host scanner resources", helpers.Error(err))
cautils.SetInfoMapForResources(err.Error(), hostResources, sessionObj.InfoMap)
@@ -106,7 +104,9 @@ func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessio
// using hostSensor mock
cautils.SetInfoMapForResources("failed to init host scanner", hostResources, sessionObj.InfoMap)
} else {
sessionObj.InfoMap = infoMap
if len(infoMap) > 0 {
sessionObj.InfoMap = infoMap
}
}
} else {
cautils.SetInfoMapForResources("enable-host-scan flag not used. For more information: https://hub.armosec.io/docs/host-sensor", hostResources, sessionObj.InfoMap)
@@ -117,10 +117,13 @@ func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessio
logger.L().Warning("failed to collect rbac resources", helpers.Error(err))
}
cloudResources := cautils.MapCloudResources(armoResourceMap)
cloudResources := cautils.MapCloudResources(ksResourceMap)
setMapNamespaceToNumOfResources(allResources, sessionObj)
// check that controls use cloud resources
if len(cloudResources) > 0 {
provider, err := getCloudProviderDescription(allResources, armoResourceMap)
provider, err := getCloudProviderDescription(allResources, ksResourceMap)
if err != nil {
cautils.SetInfoMapForResources(err.Error(), cloudResources, sessionObj.InfoMap)
logger.L().Warning("failed to collect cloud data", helpers.Error(err))
@@ -135,7 +138,7 @@ func (k8sHandler *K8sResourceHandler) GetResources(sessionObj *cautils.OPASessio
cautils.StopSpinner()
logger.L().Success("Accessed to Kubernetes objects")
return k8sResourcesMap, allResources, armoResourceMap, nil
return k8sResourcesMap, allResources, ksResourceMap, nil
}
func (k8sHandler *K8sResourceHandler) GetClusterAPIServerInfo() *version.Info {
@@ -147,6 +150,30 @@ func (k8sHandler *K8sResourceHandler) GetClusterAPIServerInfo() *version.Info {
return clusterAPIServerInfo
}
// set namespaceToNumOfResources map in report
func setMapNamespaceToNumOfResources(allResources map[string]workloadinterface.IMetadata, sessionObj *cautils.OPASessionObj) {
mapNamespaceToNumberOfResources := make(map[string]int)
for _, resource := range allResources {
if obj := workloadinterface.NewWorkloadObj(resource.GetObject()); obj != nil {
ownerReferences, err := obj.GetOwnerReferences()
if err == nil {
// Add an object to the map if the object does not have a parent but is contained within a namespace (except Job)
if len(ownerReferences) == 0 {
if ns := resource.GetNamespace(); ns != "" {
if obj.GetKind() != "Job" {
mapNamespaceToNumberOfResources[ns]++
}
}
}
} else {
logger.L().Warning(fmt.Sprintf("failed to get owner references. Resource %s will not be counted", obj.GetName()), helpers.Error(err))
}
}
}
sessionObj.SetMapNamespaceToNumberOfResources(mapNamespaceToNumberOfResources)
}
func (k8sHandler *K8sResourceHandler) pullResources(k8sResources *cautils.K8SResources, allResources map[string]workloadinterface.IMetadata, namespace string, labels map[string]string) error {
var errs error
@@ -220,19 +247,7 @@ func ConvertMapListToMeta(resourceMap []map[string]interface{}) []workloadinterf
return workloads
}
// func (k8sHandler *K8sResourceHandler) collectHostResourcesAPI(allResources map[string]workloadinterface.IMetadata, resourcesMap *cautils.K8SResources) error {
// HostSensorAPI := map[string]string{
// "bla/v1": "",
// }
// for apiVersion := range allResources {
// if HostSensorAPI == apiVersion {
// k8sHandler.collectHostResources()
// }
// }
// return nil
// }
func (k8sHandler *K8sResourceHandler) collectHostResources(allResources map[string]workloadinterface.IMetadata, armoResourceMap *cautils.ArmoResources) (map[string]apis.StatusInfo, error) {
func (k8sHandler *K8sResourceHandler) collectHostResources(allResources map[string]workloadinterface.IMetadata, ksResourceMap *cautils.KSResources) (map[string]apis.StatusInfo, error) {
logger.L().Debug("Collecting host scanner resources")
hostResources, infoMap, err := k8sHandler.hostSensorHandler.CollectResources()
if err != nil {
@@ -244,11 +259,11 @@ func (k8sHandler *K8sResourceHandler) collectHostResources(allResources map[stri
groupResource := k8sinterface.JoinResourceTriplets(group, version, hostResources[rscIdx].GetKind())
allResources[hostResources[rscIdx].GetID()] = &hostResources[rscIdx]
grpResourceList, ok := (*armoResourceMap)[groupResource]
grpResourceList, ok := (*ksResourceMap)[groupResource]
if !ok {
grpResourceList = make([]string, 0)
}
(*armoResourceMap)[groupResource] = append(grpResourceList, hostResources[rscIdx].GetID())
(*ksResourceMap)[groupResource] = append(grpResourceList, hostResources[rscIdx].GetID())
}
return infoMap, nil
}
@@ -269,7 +284,7 @@ func (k8sHandler *K8sResourceHandler) collectRbacResources(allResources map[stri
return nil
}
func getCloudProviderDescription(allResources map[string]workloadinterface.IMetadata, armoResourceMap *cautils.ArmoResources) (string, error) {
func getCloudProviderDescription(allResources map[string]workloadinterface.IMetadata, ksResourceMap *cautils.KSResources) (string, error) {
logger.L().Debug("Collecting cloud data")
clusterName := cautils.ClusterName
@@ -286,7 +301,7 @@ func getCloudProviderDescription(allResources map[string]workloadinterface.IMeta
return provider, fmt.Errorf("failed to get %s descriptive information. Read more: https://hub.armosec.io/docs/kubescape-integration-with-cloud-providers", strings.ToUpper(provider))
}
allResources[wl.GetID()] = wl
(*armoResourceMap)[fmt.Sprintf("%s/%s", wl.GetApiVersion(), wl.GetKind())] = []string{wl.GetID()}
(*ksResourceMap)[fmt.Sprintf("%s/%s", wl.GetApiVersion(), wl.GetKind())] = []string{wl.GetID()}
}
return provider, nil

File diff suppressed because one or more lines are too long

View File

@@ -3,11 +3,11 @@ package resourcehandler
import (
"strings"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/opa-utils/reporthandling"
"k8s.io/utils/strings/slices"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/k8sinterface"
)
var (
@@ -40,10 +40,10 @@ var (
ClusterDescribe: {"container.googleapis.com/v1", "eks.amazonaws.com/v1", "management.azure.com/v1"}}
)
func isEmptyImgVulns(armoResourcesMap cautils.ArmoResources) bool {
imgVulnResources := cautils.MapImageVulnResources(&armoResourcesMap)
func isEmptyImgVulns(ksResourcesMap cautils.KSResources) bool {
imgVulnResources := cautils.MapImageVulnResources(&ksResourcesMap)
for _, resource := range imgVulnResources {
if val, ok := armoResourcesMap[resource]; ok {
if val, ok := ksResourcesMap[resource]; ok {
if len(val) > 0 {
return false
}
@@ -68,20 +68,20 @@ func setK8sResourceMap(frameworks []reporthandling.Framework) *cautils.K8SResour
return &k8sResources
}
func setArmoResourceMap(frameworks []reporthandling.Framework, resourceToControl map[string][]string) *cautils.ArmoResources {
armoResources := make(cautils.ArmoResources)
complexMap := setComplexArmoResourceMap(frameworks, resourceToControl)
func setKSResourceMap(frameworks []reporthandling.Framework, resourceToControl map[string][]string) *cautils.KSResources {
ksResources := make(cautils.KSResources)
complexMap := setComplexKSResourceMap(frameworks, resourceToControl)
for group := range complexMap {
for version := range complexMap[group] {
for resource := range complexMap[group][version] {
groupResources := k8sinterface.ResourceGroupToString(group, version, resource)
for _, groupResource := range groupResources {
armoResources[groupResource] = nil
ksResources[groupResource] = nil
}
}
}
}
return &armoResources
return &ksResources
}
func setComplexK8sResourceMap(frameworks []reporthandling.Framework) map[string]map[string]map[string]interface{} {
@@ -99,13 +99,13 @@ func setComplexK8sResourceMap(frameworks []reporthandling.Framework) map[string]
}
// [group][versionn][resource]
func setComplexArmoResourceMap(frameworks []reporthandling.Framework, resourceToControls map[string][]string) map[string]map[string]map[string]interface{} {
func setComplexKSResourceMap(frameworks []reporthandling.Framework, resourceToControls map[string][]string) map[string]map[string]map[string]interface{} {
k8sResources := make(map[string]map[string]map[string]interface{})
for _, framework := range frameworks {
for _, control := range framework.Controls {
for _, rule := range control.Rules {
for _, match := range rule.DynamicMatch {
insertArmoResourcesAndControls(k8sResources, match, resourceToControls, control)
insertKSResourcesAndControls(k8sResources, match, resourceToControls, control)
}
}
}
@@ -113,7 +113,7 @@ func setComplexArmoResourceMap(frameworks []reporthandling.Framework, resourceTo
return k8sResources
}
func mapArmoResourceToApiGroup(resource string) []string {
func mapKSResourceToApiGroup(resource string) []string {
if val, ok := MapResourceToApiGroup[resource]; ok {
return []string{val}
}
@@ -127,9 +127,9 @@ func mapArmoResourceToApiGroup(resource string) []string {
}
func insertControls(resource string, resourceToControl map[string][]string, control reporthandling.Control) {
armoResources := mapArmoResourceToApiGroup(resource)
for _, armoResource := range armoResources {
group, version := k8sinterface.SplitApiVersion(armoResource)
ksResources := mapKSResourceToApiGroup(resource)
for _, ksResource := range ksResources {
group, version := k8sinterface.SplitApiVersion(ksResource)
r := k8sinterface.JoinResourceTriplets(group, version, resource)
if _, ok := resourceToControl[r]; !ok {
resourceToControl[r] = append(resourceToControl[r], control.ControlID)
@@ -159,7 +159,7 @@ func insertResources(k8sResources map[string]map[string]map[string]interface{},
}
}
func insertArmoResourcesAndControls(k8sResources map[string]map[string]map[string]interface{}, match reporthandling.RuleMatchObjects, resourceToControl map[string][]string, control reporthandling.Control) {
func insertKSResourcesAndControls(k8sResources map[string]map[string]map[string]interface{}, match reporthandling.RuleMatchObjects, resourceToControl map[string][]string, control reporthandling.Control) {
for _, apiGroup := range match.APIGroups {
if v, ok := k8sResources[apiGroup]; !ok || v == nil {
k8sResources[apiGroup] = make(map[string]map[string]interface{})

View File

@@ -1,9 +1,9 @@
package resourcehandler
import (
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/opa-utils/reporthandling"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/opa-utils/reporthandling"
"github.com/stretchr/testify/assert"
"testing"
@@ -27,16 +27,16 @@ func TestSetResourceMap(t *testing.T) {
}
func TestSsEmptyImgVulns(t *testing.T) {
armoResourcesMap := make(cautils.ArmoResources, 0)
armoResourcesMap["container.googleapis.com/v1"] = []string{"fsdfds"}
assert.Equal(t, true, isEmptyImgVulns(armoResourcesMap))
ksResourcesMap := make(cautils.KSResources, 0)
ksResourcesMap["container.googleapis.com/v1"] = []string{"fsdfds"}
assert.Equal(t, true, isEmptyImgVulns(ksResourcesMap))
armoResourcesMap["armo.vuln.images/v1/ImageVulnerabilities"] = []string{"dada"}
assert.Equal(t, false, isEmptyImgVulns(armoResourcesMap))
ksResourcesMap["armo.vuln.images/v1/ImageVulnerabilities"] = []string{"dada"}
assert.Equal(t, false, isEmptyImgVulns(ksResourcesMap))
armoResourcesMap["armo.vuln.images/v1/ImageVulnerabilities"] = []string{}
armoResourcesMap["bla"] = []string{"blu"}
assert.Equal(t, true, isEmptyImgVulns(armoResourcesMap))
ksResourcesMap["armo.vuln.images/v1/ImageVulnerabilities"] = []string{}
ksResourcesMap["bla"] = []string{"blu"}
assert.Equal(t, true, isEmptyImgVulns(ksResourcesMap))
}
func TestInsertK8sResources(t *testing.T) {

View File

@@ -3,15 +3,15 @@ package resourcehandler
import (
"fmt"
"github.com/armosec/k8s-interface/k8sinterface"
"github.com/armosec/k8s-interface/workloadinterface"
"github.com/armosec/kubescape/v2/core/cautils"
"github.com/armosec/kubescape/v2/core/cautils/getter"
armosecadaptorv1 "github.com/armosec/kubescape/v2/core/pkg/registryadaptors/armosec/v1"
"github.com/armosec/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
logger "github.com/dwertent/go-logger"
logger "github.com/kubescape/go-logger"
"github.com/kubescape/k8s-interface/k8sinterface"
"github.com/kubescape/k8s-interface/workloadinterface"
"github.com/kubescape/kubescape/v2/core/cautils"
"github.com/kubescape/kubescape/v2/core/cautils/getter"
armosecadaptorv1 "github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/armosec/v1"
"github.com/kubescape/kubescape/v2/core/pkg/registryadaptors/registryvulnerabilities"
"github.com/armosec/opa-utils/shared"
"github.com/kubescape/opa-utils/shared"
)
const (
@@ -35,7 +35,7 @@ func NewRegistryAdaptors() (*RegistryAdaptors, error) {
return registryAdaptors, nil
}
func (registryAdaptors *RegistryAdaptors) collectImagesVulnerabilities(k8sResourcesMap *cautils.K8SResources, allResources map[string]workloadinterface.IMetadata, armoResourceMap *cautils.ArmoResources) error {
func (registryAdaptors *RegistryAdaptors) collectImagesVulnerabilities(k8sResourcesMap *cautils.K8SResources, allResources map[string]workloadinterface.IMetadata, ksResourceMap *cautils.KSResources) error {
logger.L().Debug("Collecting images vulnerabilities")
if len(registryAdaptors.adaptors) == 0 {
@@ -75,7 +75,7 @@ func (registryAdaptors *RegistryAdaptors) collectImagesVulnerabilities(k8sResour
for i := range metaObjs {
allResources[metaObjs[i].GetID()] = metaObjs[i]
}
(*armoResourceMap)[k8sinterface.JoinResourceTriplets(ImagevulnerabilitiesObjectGroup, ImagevulnerabilitiesObjectVersion, ImagevulnerabilitiesObjectKind)] = workloadinterface.ListMetaIDs(metaObjs)
(*ksResourceMap)[k8sinterface.JoinResourceTriplets(ImagevulnerabilitiesObjectGroup, ImagevulnerabilitiesObjectVersion, ImagevulnerabilitiesObjectKind)] = workloadinterface.ListMetaIDs(metaObjs)
return nil
}
@@ -151,10 +151,10 @@ func listAdaptores() ([]registryvulnerabilities.IContainerImageVulnerabilityAdap
adaptors := []registryvulnerabilities.IContainerImageVulnerabilityAdaptor{}
armoAPI := getter.GetArmoAPIConnector()
if armoAPI != nil {
if armoAPI.GetSecretKey() != "" && armoAPI.GetClientID() != "" && armoAPI.GetAccountID() != "" {
adaptors = append(adaptors, armosecadaptorv1.NewArmoAdaptor(getter.GetArmoAPIConnector()))
ksCloudAPI := getter.GetKSCloudAPIConnector()
if ksCloudAPI != nil {
if ksCloudAPI.GetSecretKey() != "" && ksCloudAPI.GetClientID() != "" && ksCloudAPI.GetAccountID() != "" {
adaptors = append(adaptors, armosecadaptorv1.NewKSAdaptor(getter.GetKSCloudAPIConnector()))
}
}

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