├── .gitignore ├── CHANGELOG.md ├── CONTRIBUTING.md ├── CVE.json ├── DockerHubDockerfile ├── DockerHubDockerfileAlpine ├── Dockerfile ├── DockerfileAlpine ├── KubiScan.py ├── LICENSE ├── NOTICES.txt ├── README.md ├── __init__.py ├── api ├── __init__.py ├── api_client.py ├── api_client_temp.py ├── base_client_api.py ├── client_factory.py ├── config.py └── static_api_client.py ├── docker_run.sh ├── engine ├── __init__.py ├── capabilities │ └── capabilities.py ├── container.py ├── join_token.sh ├── jwt_token.py ├── pod.py ├── priority.py ├── privleged_containers.py ├── role.py ├── role_binding.py ├── rule.py ├── subject.py └── utils.py ├── examples └── examples.txt ├── misc ├── __init__.py ├── colours.py └── constants.py ├── requirements.txt ├── risky_roles.yaml ├── static_risky_roles.py ├── static_scan.py ├── static_unit_test └── static_scan_test.py ├── unit_test.py └── unit_test ├── kubectl_apply.sh ├── kubiscan-sa ├── kubiscan-sa2 └── readme /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled files 2 | *.pyc 3 | *.pyo 4 | *.pyd 5 | __pycache__/ 6 | 7 | # Virtual environment directories 8 | .venv/ 9 | env/ 10 | venv/ 11 | 12 | # IDE and editor directories 13 | .vscode/ 14 | .idea/ 15 | *.sublime-workspace 16 | *.sublime-project 17 | 18 | # Coverage reports 19 | .coverage 20 | *.coverage 21 | *.coverage.* 22 | nosetests.xml 23 | coverage.xml 24 | 25 | # Test results 26 | *.log 27 | *.tmp 28 | *.swp 29 | *.swo 30 | *.bak 31 | *.orig 32 | 33 | # Jupyter Notebook 34 | .ipynb_checkpoints/ 35 | 36 | # MyPy 37 | .mypy_cache/ 38 | 39 | # Pyre type checker 40 | .pyre/ 41 | 42 | # Python virtual environments 43 | .env/ 44 | .venv/ 45 | 46 | # Sphinx documentation 47 | docs/_build/ 48 | 49 | # Build directories 50 | build/ 51 | dist/ 52 | *.egg-info/ 53 | .eggs/ 54 | 55 | # Package distribution 56 | *.egg 57 | *.egg-info 58 | 59 | # PyInstaller 60 | *.spec 61 | 62 | # PyCharm 63 | *.iml 64 | *.idea/ 65 | *.pyc 66 | __pycache__/ 67 | 68 | # macOS 69 | .DS_Store 70 | 71 | # Windows 72 | Thumbs.db 73 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | All notable changes to this project will be documented in this file. 3 | 4 | The format is based on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/). 5 | 6 | 7 | ## [v1.6] - 2023-01-27 8 | - Replaced Added support to match case match case with if else to support Python versions below 3.10 (#69 by @kamal2222ahmed) 9 | - Failed chmod when not specifying AWS info (#66 & #67 by @elreydetoda) 10 | - Adding support to AKS and options to CVE scan (#65 by @2niknatan) 11 | - Adding CVE scan and unittest (#64 by @2niknatan) 12 | - Adding flags (-o, -q, -j and -nc) to enhance the output (#63 by @2niknatan) 13 | - Changing the risky pods function (#62 by @2niknatan) 14 | - Adding unit tests (#55 by @2niknatan) 15 | - Supporting eks in docker container (#54 by @2niknatan) 16 | - Printing error message when no kind was entered to '-aars' flag (#53 by @2niknatan) 17 | - Fixing duplicates in '-rp' flag (#52 & #50) 18 | - Fix typo in api_client.py (#51 by @AlonBenHorin) 19 | - Fixing '-rp' flag by adding logic so it can print several Service Accounts (#49 by @2niknatan) 20 | - Adding secret creation to support version +1.24 21 | - Fixing hang in some environments (#47 by @2niknatan) 22 | - Fixing the path to '/opt/kubiscan/config_bak' like in the Dockerfile (#46 by @2niknatan) 23 | - Adding an environment variable to docker file, fixing -td flag and catching exceptions and adding tag to docker image (#45 by @2niknatan) 24 | - Update docker_run.sh 25 | - Adding catch exception and fix non existing key bug (#41 by @AlonBenHorin) 26 | - Fixing pull request #18 and adding bash script to run a container (#40 by @AlonBenHorin) 27 | - Minor change in the check for running inside a container 28 | - Added support to kubeconfig in the API client (by @g3rzi) 29 | - Simplify dockerfile + Parameterize paths (#18 by @vidbina) 30 | 31 | ## [v1.5] - 2022-09-21 32 | - Fix 'NoneType' object is not iterable and always connection to localhost (#24) 33 | - Resolve errors encountered running kubiscan in openshift and from a container image (#23) 34 | - Handle pod.spec.volumes with None (#20) 35 | - Fix TLS warnings when using a token (#19) 36 | - Fix SyntaxWarning for 'is not' with literals 37 | - Fix missing namespace for service account (#10) 38 | - Fix --pods-secrets-env example (#17) 39 | - Support Py version where async is keyword: fix #11 (#14) 40 | - Added fix for container check in MacOS (#15) 41 | - Use yaml.safe_load instead of yaml.load (#16) 42 | 43 | ## [v1.4] - 2020-01-14 44 | - Added check for hostPID and hostIPC 45 | - Added parsing for pod's spec for hostPID nad hostIPC 46 | - Added support on hostNetwork nad hostPorts 47 | - Added printing of hostPorts and hostNetwork information 48 | - Removed debug printing for pod name 49 | - Fixed wrong indents in risk YAML file 50 | - Added support on hostPaths in containers 51 | - Added support to printing volumes with hostPaths mounted to container 52 | - Added the mounted path inside the container 53 | 54 | ## [v1.3] - 2019-07-24 55 | - Fix checking if inside a docker container 56 | - Fix bug to get RoleBindings of "User" subjects 57 | - Added catch for error 404 in function get_roles_associated_to_subject 58 | 59 | ## [v1.2] - 2019-04-10 60 | - New switch (-pp\--privileged-pods) to get privileged pods\containers 61 | - Added pod's namespace to risky pods 62 | 63 | ## [v1.1] - 2019-03-28 64 | - New switch (-d\--deep) to read tokens from containers 65 | - Added option to read token from ETCD 66 | - Added missing verb in kubiscan-sa token permissions 67 | - Fixed wrong resource name in kubiscan-sa token permissions 68 | - New switch for priority filtering 69 | - Support for different contexts 70 | - Dockerfile support for lightweight alpine image 71 | - Strip newline from files 72 | 73 | ## [v1.0] - 2019-03-28 74 | - Initial version 75 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | # Contributing 2 | Thank you for considering contributing to KubiScan! We welcome contributions to improve this project. 3 | For general contribution and community guidelines, please see the [community repo](https://github.com/cyberark/community). 4 | 5 | ## Contributing 6 | 7 | 1. [Fork the project](https://help.github.com/en/github/getting-started-with-github/fork-a-repo) 8 | 2. [Clone your fork](https://help.github.com/en/github/creating-cloning-and-archiving-repositories/cloning-a-repository) 9 | 3. Make local changes to your fork by editing files 10 | 3. [Commit your changes](https://help.github.com/en/github/managing-files-in-a-repository/adding-a-file-to-a-repository-using-the-command-line) 11 | 4. [Push your local changes to the remote server](https://help.github.com/en/github/using-git/pushing-commits-to-a-remote-repository) 12 | 5. [Create new Pull Request](https://help.github.com/en/github/collaborating-with-issues-and-pull-requests/creating-a-pull-request-from-a-fork) 13 | 14 | From here your pull request will be reviewed and once you've responded to all 15 | feedback it will be merged into the project. Congratulations, you're a 16 | contributor! 17 | 18 | ## Development 19 | To start developing and testing using our development scripts , 20 | the following tools need to be installed: 21 | - Docker 22 | - Minikube (or any other local Kubernetes setup) 23 | 24 | ### Running tests 25 | ```shell 26 | [1] Commit and push your changes to your repository. 27 | [2] Make sure docker is installed on the host. 28 | [3] Start MiniKube. 29 | [4] Type the following commands: 30 | "cd /tmp" 31 | "git clone " 32 | "cd KubiScan/unit_test/" 33 | "./kubectl_apply.sh" 34 | [5] For the unit-test run the following command: 35 | python3 -m pytest -v unit_test.py 36 | ``` 37 | 38 | ## Releases 39 | Maintainers only should create releases. Follow these steps to prepare for a release. 40 | 41 | ### Pre-requisites 42 | 43 | 1. Review recent commits and ensure the [changelog](CHANGELOG.md) includes all relevant changes, with references to GitHub issues or PRs when applicable. 44 | 2. Verify that any updated dependencies are accurately reflected in the [NOTICES](NOTICES.txt). 45 | 3. Confirm that required documentation is complete and has been approved. 46 | 4. Scan the project for vulnerabilities 47 | 48 | ### Release and Promote 49 | 50 | 1. Merging to the main branch will trigger an automated release build. Successful builds can be promoted at a later time. 51 | 2. Use build parameters in CI/CD tools to promote a release or manually trigger additional builds if needed. 52 | ### 53 | Thank you for contributing to KubiScan! 54 | 55 | 56 | 57 | 58 | 59 | 60 | -------------------------------------------------------------------------------- /DockerHubDockerfile: -------------------------------------------------------------------------------- 1 | FROM ubuntu:latest 2 | RUN apt-get update 3 | RUN apt-get install -y python3 python3-pip 4 | RUN pip3 install kubernetes 5 | RUN pip3 install PTable 6 | RUN echo "alias kubiscan='python3 /KubiScan/KubiScan.py'" > /root/.bash_aliases 7 | RUN . /root/.bash_aliases 8 | RUN apt-get remove -y python3-pip 9 | RUN apt-get install -y git 10 | ENTRYPOINT git clone https://github.com/cyberark/KubiScan.git /KubiScan && bash -------------------------------------------------------------------------------- /DockerHubDockerfileAlpine: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | RUN apk update && apk upgrade && apk add bash && apk add python3 && apk add cmd:pip3 && pip3 install requests && pip3 install PTable 3 | RUN apk add git && git clone --recursive https://github.com/kubernetes-client/python.git && cd python/ && python3 setup.py install 4 | RUN echo "alias kubiscan='python3 /KubiScan/KubiScan.py'" > /root/.bash_aliases && echo "alias kubiscan='python3 /KubiScan/KubiScan.py'" > /root/.bashrc 5 | RUN . /root/.bash_aliases 6 | ENTRYPOINT git clone https://github.com/cyberark/KubiScan.git /KubiScan && bash 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # Default to the Docker Hub container registry 2 | ARG DOCKER_REGISTRY=index.docker.io 3 | 4 | # Default to the official Python Debian image 5 | ARG PYTHON_IMAGE=${DOCKER_REGISTRY}/python:3.8.0-slim-buster 6 | 7 | 8 | FROM ${PYTHON_IMAGE} AS build-image 9 | 10 | WORKDIR /tmp/build-kubiscan 11 | COPY requirements.txt requirements.txt 12 | 13 | # The default image provides `pip`, `pip3`, `python` and `python3` commands and 14 | # for portability's sake, the `pip3` and `python3` names will be used in this 15 | # configuration. 16 | 17 | # Install Python dependencies from requirements.txt 18 | # As customary with Python projects, the requirements.txt, when provided, 19 | # should contain all packages necessary to run the Python source for the 20 | # project. As such changes to the dependencies would merely warrant a change to 21 | # the requirements.txt file, while the Dockerfile files remain unaffected. 22 | RUN pip3 install -r requirements.txt 23 | 24 | 25 | FROM ${PYTHON_IMAGE} AS run-image 26 | # Copy Python packages installed in the build stage 27 | COPY --from=build-image /usr/local /usr/local 28 | 29 | # Copy source 30 | COPY . /opt/kubiscan 31 | 32 | # Create kubiscan executable shortcut for all users 33 | # NOTE that this image does not default to using this shortcut but rather 34 | # resorts to directly starting the KubiScan Python script. It may prove useful 35 | # to remove this shortcut altogether unless end-users are expected to spawn a 36 | # Bash inside the resulting container in which case the `kubiscan` shortcut 37 | # will come in handy. 38 | RUN set -ex \ 39 | && echo 'python3 /opt/kubiscan/KubiScan.py $@' > /usr/local/bin/kubiscan \ 40 | && chmod a+x /usr/local/bin/kubiscan \ 41 | && which kubiscan 42 | 43 | # Create a non-root user and group 44 | RUN set -ex \ 45 | && addgroup kubiscan \ 46 | && adduser \ 47 | --no-create-home \ 48 | --disabled-password \ 49 | --gecos ',,,,' \ 50 | --ingroup kubiscan \ 51 | --disabled-login \ 52 | kubiscan \ 53 | && > /var/log/faillog \ 54 | && > /var/log/lastlog 55 | 56 | # Environment variable to know if running in a container 57 | ENV RUNNING_IN_A_CONTAINER=true -------------------------------------------------------------------------------- /DockerfileAlpine: -------------------------------------------------------------------------------- 1 | FROM alpine:latest 2 | RUN apk update && apk upgrade && apk add bash && apk add python3 && apk add cmd:pip3 && pip3 install requests && pip3 install PTable 3 | RUN apk add git && git clone --recursive https://github.com/kubernetes-client/python.git && cd python/ && python3 setup.py install 4 | RUN echo "alias kubiscan='python3 /KubiScan/KubiScan.py'" > /root/.bash_aliases && echo "alias kubiscan='python3 /KubiScan/KubiScan.py'" > /root/.bashrc 5 | RUN . /root/.bash_aliases 6 | COPY . /KubiScan 7 | ENTRYPOINT bash 8 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | KubiScan Copyright (c) 2020 CyberArk Software Ltd. All rights reserved. 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | -------------------------------------------------------------------------------- /NOTICES.txt: -------------------------------------------------------------------------------- 1 | Copyright (c) 2020 CyberArk Software Ltd. All rights reserved 2 | 3 | KubiScan is using the following open source components: 4 | 5 | Official Python client library for kubernetes (https://github.com/kubernetes-client/python) : Apache-2.0 License 6 | Copyright 2014 The Kubernetes Authors. All rights reserved. 7 | * Two files were modified, see the footnote at the end of this file. 8 | 9 | PTable (https://github.com/kxxoling/PTable/blob/master/COPYING) : PTable License 10 | Copyright (c) 2009-2014 Luke Maurits . All rights reserved. 11 | 12 | Two licenses: 13 | 14 | 1. Apache-2.0 license 15 | ====================== 16 | Apache License 17 | Version 2.0, January 2004 18 | http://www.apache.org/licenses/ 19 | 20 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 21 | 22 | 1. Definitions. 23 | 24 | "License" shall mean the terms and conditions for use, reproduction, 25 | and distribution as defined by Sections 1 through 9 of this document. 26 | 27 | "Licensor" shall mean the copyright owner or entity authorized by 28 | the copyright owner that is granting the License. 29 | 30 | "Legal Entity" shall mean the union of the acting entity and all 31 | other entities that control, are controlled by, or are under common 32 | control with that entity. For the purposes of this definition, 33 | "control" means (i) the power, direct or indirect, to cause the 34 | direction or management of such entity, whether by contract or 35 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 36 | outstanding shares, or (iii) beneficial ownership of such entity. 37 | 38 | "You" (or "Your") shall mean an individual or Legal Entity 39 | exercising permissions granted by this License. 40 | 41 | "Source" form shall mean the preferred form for making modifications, 42 | including but not limited to software source code, documentation 43 | source, and configuration files. 44 | 45 | "Object" form shall mean any form resulting from mechanical 46 | transformation or translation of a Source form, including but 47 | not limited to compiled object code, generated documentation, 48 | and conversions to other media types. 49 | 50 | "Work" shall mean the work of authorship, whether in Source or 51 | Object form, made available under the License, as indicated by a 52 | copyright notice that is included in or attached to the work 53 | (an example is provided in the Appendix below). 54 | 55 | "Derivative Works" shall mean any work, whether in Source or Object 56 | form, that is based on (or derived from) the Work and for which the 57 | editorial revisions, annotations, elaborations, or other modifications 58 | represent, as a whole, an original work of authorship. For the purposes 59 | of this License, Derivative Works shall not include works that remain 60 | separable from, or merely link (or bind by name) to the interfaces of, 61 | the Work and Derivative Works thereof. 62 | 63 | "Contribution" shall mean any work of authorship, including 64 | the original version of the Work and any modifications or additions 65 | to that Work or Derivative Works thereof, that is intentionally 66 | submitted to Licensor for inclusion in the Work by the copyright owner 67 | or by an individual or Legal Entity authorized to submit on behalf of 68 | the copyright owner. For the purposes of this definition, "submitted" 69 | means any form of electronic, verbal, or written communication sent 70 | to the Licensor or its representatives, including but not limited to 71 | communication on electronic mailing lists, source code control systems, 72 | and issue tracking systems that are managed by, or on behalf of, the 73 | Licensor for the purpose of discussing and improving the Work, but 74 | excluding communication that is conspicuously marked or otherwise 75 | designated in writing by the copyright owner as "Not a Contribution." 76 | 77 | "Contributor" shall mean Licensor and any individual or Legal Entity 78 | on behalf of whom a Contribution has been received by Licensor and 79 | subsequently incorporated within the Work. 80 | 81 | 2. Grant of Copyright License. Subject to the terms and conditions of 82 | this License, each Contributor hereby grants to You a perpetual, 83 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 84 | copyright license to reproduce, prepare Derivative Works of, 85 | publicly display, publicly perform, sublicense, and distribute the 86 | Work and such Derivative Works in Source or Object form. 87 | 88 | 3. Grant of Patent License. Subject to the terms and conditions of 89 | this License, each Contributor hereby grants to You a perpetual, 90 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 91 | (except as stated in this section) patent license to make, have made, 92 | use, offer to sell, sell, import, and otherwise transfer the Work, 93 | where such license applies only to those patent claims licensable 94 | by such Contributor that are necessarily infringed by their 95 | Contribution(s) alone or by combination of their Contribution(s) 96 | with the Work to which such Contribution(s) was submitted. If You 97 | institute patent litigation against any entity (including a 98 | cross-claim or counterclaim in a lawsuit) alleging that the Work 99 | or a Contribution incorporated within the Work constitutes direct 100 | or contributory patent infringement, then any patent licenses 101 | granted to You under this License for that Work shall terminate 102 | as of the date such litigation is filed. 103 | 104 | 4. Redistribution. You may reproduce and distribute copies of the 105 | Work or Derivative Works thereof in any medium, with or without 106 | modifications, and in Source or Object form, provided that You 107 | meet the following conditions: 108 | 109 | (a) You must give any other recipients of the Work or 110 | Derivative Works a copy of this License; and 111 | 112 | (b) You must cause any modified files to carry prominent notices 113 | stating that You changed the files; and 114 | 115 | (c) You must retain, in the Source form of any Derivative Works 116 | that You distribute, all copyright, patent, trademark, and 117 | attribution notices from the Source form of the Work, 118 | excluding those notices that do not pertain to any part of 119 | the Derivative Works; and 120 | 121 | (d) If the Work includes a "NOTICE" text file as part of its 122 | distribution, then any Derivative Works that You distribute must 123 | include a readable copy of the attribution notices contained 124 | within such NOTICE file, excluding those notices that do not 125 | pertain to any part of the Derivative Works, in at least one 126 | of the following places: within a NOTICE text file distributed 127 | as part of the Derivative Works; within the Source form or 128 | documentation, if provided along with the Derivative Works; or, 129 | within a display generated by the Derivative Works, if and 130 | wherever such third-party notices normally appear. The contents 131 | of the NOTICE file are for informational purposes only and 132 | do not modify the License. You may add Your own attribution 133 | notices within Derivative Works that You distribute, alongside 134 | or as an addendum to the NOTICE text from the Work, provided 135 | that such additional attribution notices cannot be construed 136 | as modifying the License. 137 | 138 | You may add Your own copyright statement to Your modifications and 139 | may provide additional or different license terms and conditions 140 | for use, reproduction, or distribution of Your modifications, or 141 | for any such Derivative Works as a whole, provided Your use, 142 | reproduction, and distribution of the Work otherwise complies with 143 | the conditions stated in this License. 144 | 145 | 5. Submission of Contributions. Unless You explicitly state otherwise, 146 | any Contribution intentionally submitted for inclusion in the Work 147 | by You to the Licensor shall be under the terms and conditions of 148 | this License, without any additional terms or conditions. 149 | Notwithstanding the above, nothing herein shall supersede or modify 150 | the terms of any separate license agreement you may have executed 151 | with Licensor regarding such Contributions. 152 | 153 | 6. Trademarks. This License does not grant permission to use the trade 154 | names, trademarks, service marks, or product names of the Licensor, 155 | except as required for reasonable and customary use in describing the 156 | origin of the Work and reproducing the content of the NOTICE file. 157 | 158 | 7. Disclaimer of Warranty. Unless required by applicable law or 159 | agreed to in writing, Licensor provides the Work (and each 160 | Contributor provides its Contributions) on an "AS IS" BASIS, 161 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 162 | implied, including, without limitation, any warranties or conditions 163 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 164 | PARTICULAR PURPOSE. You are solely responsible for determining the 165 | appropriateness of using or redistributing the Work and assume any 166 | risks associated with Your exercise of permissions under this License. 167 | 168 | 8. Limitation of Liability. In no event and under no legal theory, 169 | whether in tort (including negligence), contract, or otherwise, 170 | unless required by applicable law (such as deliberate and grossly 171 | negligent acts) or agreed to in writing, shall any Contributor be 172 | liable to You for damages, including any direct, indirect, special, 173 | incidental, or consequential damages of any character arising as a 174 | result of this License or out of the use or inability to use the 175 | Work (including but not limited to damages for loss of goodwill, 176 | work stoppage, computer failure or malfunction, or any and all 177 | other commercial damages or losses), even if such Contributor 178 | has been advised of the possibility of such damages. 179 | 180 | 9. Accepting Warranty or Additional Liability. While redistributing 181 | the Work or Derivative Works thereof, You may choose to offer, 182 | and charge a fee for, acceptance of support, warranty, indemnity, 183 | or other liability obligations and/or rights consistent with this 184 | License. However, in accepting such obligations, You may act only 185 | on Your own behalf and on Your sole responsibility, not on behalf 186 | of any other Contributor, and only if You agree to indemnify, 187 | defend, and hold each Contributor harmless for any liability 188 | incurred by, or claims asserted against, such Contributor by reason 189 | of your accepting any such warranty or additional liability. 190 | 191 | END OF TERMS AND CONDITIONS 192 | 193 | APPENDIX: How to apply the Apache License to your work. 194 | 195 | To apply the Apache License to your work, attach the following 196 | boilerplate notice, with the fields enclosed by brackets "[]" 197 | replaced with your own identifying information. (Don't include 198 | the brackets!) The text should be enclosed in the appropriate 199 | comment syntax for the file format. We also recommend that a 200 | file or class name and description of purpose be included on the 201 | same "printed page" as the copyright notice for easier 202 | identification within third-party archives. 203 | 204 | Copyright 2014 The Kubernetes Authors. 205 | 206 | Licensed under the Apache License, Version 2.0 (the "License"); 207 | you may not use this file except in compliance with the License. 208 | You may obtain a copy of the License at 209 | 210 | http://www.apache.org/licenses/LICENSE-2.0 211 | 212 | Unless required by applicable law or agreed to in writing, software 213 | distributed under the License is distributed on an "AS IS" BASIS, 214 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 215 | See the License for the specific language governing permissions and 216 | limitations under the License. 217 | 218 | --- 219 | 220 | 2. PTable License 221 | ================= 222 | 223 | # Copyright (c) 2009-2014 Luke Maurits 224 | # All rights reserved. 225 | # With contributions from: 226 | # * Chris Clark 227 | # * Klein Stephane 228 | # * John Filleau 229 | # 230 | # Redistribution and use in source and binary forms, with or without 231 | # modification, are permitted provided that the following conditions are met: 232 | # 233 | # * Redistributions of source code must retain the above copyright notice, 234 | # this list of conditions and the following disclaimer. 235 | # * Redistributions in binary form must reproduce the above copyright notice, 236 | # this list of conditions and the following disclaimer in the documentation 237 | # and/or other materials provided with the distribution. 238 | # * The name of the author may not be used to endorse or promote products 239 | # derived from this software without specific prior written permission. 240 | # 241 | # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 242 | # AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 243 | # IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 244 | # ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 245 | # LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 246 | # CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 247 | # SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 248 | # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 249 | # CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 250 | # ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 251 | # POSSIBILITY OF SUCH DAMAGE. 252 | 253 | Footnote: 254 | 1. Part of the code was copied and modified to the file (/api/api_client_temp.py) from: 255 | https://github.com/kubernetes-client/python/blob/71b5abce5a4e2d747c0bb26d4eaa17eeb08f8ac5/kubernetes/client/api_client.py 256 | This is due to a known bug (https://github.com/kubernetes-client/gen/issues/52) which caused exception and exit the program when there is a query to objects with None rules. 257 | Once this code will be fixed, it can be removed and do the relevant changes. 258 | 2. Some of the code from: 259 | https://github.com/kubernetes-client/python-base/blob/07ef6263685802ee5a8532662bf589adaa07b592/config/incluster_config.py#L36 260 | Was used (with some modifications) in: 261 | https://github.com/cyberark/KubiScan/blob/aee973487cb50164a734c2f4d72fa2f7ea331147/api/api_client.py#L75 262 | 263 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![GitHub release][release-img]][release] 2 | [![License][license-img]][license] 3 | ![Stars](https://img.shields.io/github/stars/cyberark/KubiScan) 4 | 5 | 6 | A tool for scanning Kubernetes cluster for risky permissions in Kubernetes's Role-based access control (RBAC) authorization model. 7 | The tool was published as part of the "Securing Kubernetes Clusters by Eliminating Risky Permissions" research https://www.cyberark.com/threat-research-blog/securing-kubernetes-clusters-by-eliminating-risky-permissions/. 8 | 9 | --- 10 | 11 | ## Table of Contents 12 | - [Overview](#overview) 13 | - [What can it do?](#what-can-it-do) 14 | - [Usage](#usage) 15 | - [Container](#container) 16 | - [Directly with Python3](#directly-with-python3) 17 | - [Prerequisites](#prerequisites) 18 | - [Example for installation on Ubuntu](#example-for-installation-on-ubuntu) 19 | - [With KubeConfig file](#with-kubeconfig-file) 20 | - [From a remote with ServiceAccount token](#from-a-remote-with-serviceaccount-token) 21 | - [Examples](#examples) 22 | - [Demo](#demo) 23 | - [Risky Roles YAML](#risky-roles-yaml) 24 | - [Showcase](#%EF%B8%8F-showcase) 25 | - [License](#license) 26 | - [References](#references) 27 | 28 | --- 29 | 30 | ## Overview 31 | KubiScan helps cluster administrators identify permissions that attackers could potentially exploit to compromise the clusters. 32 | This can be especially helpful on large environments where there are lots of permissions that can be challenging to track. 33 | KubiScan gathers information about risky roles\clusterroles, rolebindings\clusterrolebindings, users and pods, automating traditional manual processes and giving administrators the visibility they need to reduce risk. 34 | 35 | ## What can it do? 36 | - Identify risky Roles\ClusterRoles 37 | - Identify risky RoleBindings\ClusterRoleBindings 38 | - Identify risky Subjects (Users, Groups and ServiceAccounts) 39 | - Identify risky Pods\Containers 40 | - Dump tokens from pods (all or by namespace) 41 | - Get associated RoleBindings\ClusterRoleBindings to Role, ClusterRole or Subject (user, group or service account) 42 | - List Subjects with specific kind ('User', 'Group' or 'ServiceAccount') 43 | - List rules of RoleBinding or ClusterRoleBinding 44 | - Show Pods that have access to secret data through a volume or environment variables 45 | - Get bootstrap tokens for the cluster 46 | - CVE scan 47 | - EKS\AKS\GKE support 48 | 49 | ## Usage 50 | ### Container 51 | 52 | You can run it like that: 53 | ``` 54 | ./docker_run.sh 55 | # For example: ./docker_run.sh ~/.kube/config 56 | ``` 57 | 58 | It will copy all the files linked inside the config file into the container and spwan a shell into the container. 59 | 60 | To build the Docker image run: 61 | ``` 62 | docker build -t kubiscan . 63 | ``` 64 | 65 | ### Directly with Python3 66 | #### Prerequisites: 67 | - __Python 3.6+__ 68 | - __Pip3__ 69 | - [__Kubernetes Python Client__](https://github.com/kubernetes-client/python) 70 | - [__Prettytable__](https://pypi.org/project/PTable) 71 | - __openssl__ (built-in in ubuntu) - used only for join token 72 | 73 | #### Example for installation on Ubuntu: 74 | ``` 75 | apt-get update 76 | apt-get install -y python3 python3-pip 77 | pip3 install -r requirements.txt 78 | ``` 79 | 80 | Run `alias kubiscan='python3 //KubiScan.py'` to use `kubiscan`. 81 | 82 | After installing all of the above requirements you can run it in two different ways: 83 | #### With KubeConfig file: 84 | Make sure you have access to `~/.kube/config` file and all the relevant certificates, simply run: 85 | `kubiscan ` 86 | For example: `kubiscan -rs` will show all the risky subjects (users, service accounts and groups). 87 | 88 | #### From a remote with ServiceAccount token 89 | Some functionality requires a **privileged** service account with the following permissions: 90 | - **resources**: `["roles", "clusterroles", "rolebindings", "clusterrolebindings", "pods", "secrets"]` 91 | **verbs**: `["get", "list"]` 92 | - **resources**: `["pods/exec"]` 93 | **verbs**: `["create", "get"]` 94 | 95 | But most of the functionalities are not, so you can use this settings for limited service account: 96 | It can be created by running: 97 | ``` 98 | kubectl apply -f - << EOF 99 | apiVersion: v1 100 | kind: ServiceAccount 101 | metadata: 102 | name: kubiscan-sa 103 | namespace: default 104 | --- 105 | apiVersion: v1 106 | kind: Secret 107 | type: kubernetes.io/service-account-token 108 | metadata: 109 | name: kubiscan-sa-secret 110 | annotations: 111 | kubernetes.io/service-account.name: kubiscan-sa 112 | --- 113 | kind: ClusterRoleBinding 114 | apiVersion: rbac.authorization.k8s.io/v1 115 | metadata: 116 | name: kubiscan-clusterrolebinding 117 | subjects: 118 | - kind: ServiceAccount 119 | name: kubiscan-sa 120 | namespace: default 121 | apiGroup: "" 122 | roleRef: 123 | kind: ClusterRole 124 | name: kubiscan-clusterrole 125 | apiGroup: "" 126 | --- 127 | kind: ClusterRole 128 | apiVersion: rbac.authorization.k8s.io/v1 129 | metadata: 130 | name: kubiscan-clusterrole 131 | rules: 132 | - apiGroups: ["*"] 133 | resources: ["roles", "clusterroles", "rolebindings", "clusterrolebindings", "pods"] 134 | verbs: ["get", "list"] 135 | EOF 136 | ``` 137 | 138 | Note that from Kubernetes 1.24, the creation of service account doesn't create a secret. This means that we need to create the secret. 139 | Before 1.24, you can remove the `Secret` object from the above commands and save the service account's token to a file: 140 | `kubectl get secrets $(kubectl get sa kubiscan-sa -o=jsonpath='{.secrets[0].name}') -o=jsonpath='{.data.token}' | base64 -d > token` 141 | 142 | From 1.24, you don't need to change anything and save the token like that: 143 | ``` 144 | kubectl get secrets kubiscan-sa-secret -o=jsonpath='{.data.token}' | base64 -d > token 145 | ``` 146 | 147 | After saving the token into the file, you can use it like that: 148 | `python3 ./KubiScan.py -ho -t /token ` 149 | 150 | For example: 151 | ``` 152 | alias kubiscan='python3 //KubiScan.py 153 | kubiscan -ho 192.168.21.129:8443 -t /token -rs 154 | ``` 155 | 156 | Notice that you can also use the certificate authority (ca.crt) to verify the SSL connection: 157 | ``` 158 | kubiscan -ho -t /token -c /ca.crt 159 | ``` 160 | 161 | To remove the privileged service account, run the following commands: 162 | ``` 163 | kubectl delete clusterroles kubiscan-clusterrole 164 | kubectl delete clusterrolebindings kubiscan-clusterrolebinding 165 | kubectl delete sa kubiscan-sa 166 | kubectl delete secrets kubiscan-sa-secret 167 | ``` 168 | 169 | ## Examples 170 | To see all the examples, run `python3 KubiScan.py -e` or from within the container `kubiscan -e`. 171 | 172 | ## Demo 173 | A small example of KubiScan usage: 174 |

175 | 176 | ## Risky Roles YAML 177 | There is a file named `risky_roles.yaml`. This file contains templates for risky roles with priority. 178 | Although the kind in each role is `Role`, these templates will be compared against any Role\ClusterRole in the cluster. 179 | When each of these roles is checked against a role in the cluster, it checks if the role in the cluster contains the rules from the risky role. If it does, it will be marked as risky. 180 | We added all the roles we found to be risky, but because each one can define the term "risky" in a different way, you can modify the file by adding\removing roles you think are more\less risky. 181 | 182 | ## ❤️ Showcase 183 | * Presented at RSA 2020 ["Compromising Kubernetes Cluster by Exploiting RBAC Permissions"](https://www.youtube.com/watch?v=1LMo0CftVC4) 184 | * Presented at RSA 2022 ["Attacking and Defending Kubernetes Cluster: Kubesploit vs KubiScan"](https://www.youtube.com/watch?v=xRqYSDKi6a0) 185 | * Article by PortSwigger ["KubiScan: Open source Kubernetes security tool showcased at Black Hat 2020"](https://portswigger.net/daily-swig/kubiscan-open-source-kubernetes-security-tool-showcased-at-black-hat-2020) 186 | 187 | 188 | ## License 189 | Copyright (c) 2020 CyberArk Software Ltd. All rights reserved 190 | This repository is licensed under GPL-3.0 License - see [`LICENSE`](LICENSE) for more details. 191 | 192 | ## References: 193 | For more comments, suggestions or questions, you can contact Eviatar Gerzi ([@g3rzi](https://twitter.com/g3rzi)) and CyberArk Labs. 194 | 195 | [release-img]: https://img.shields.io/github/release/cyberark/kubiscan.svg 196 | [release]: https://github.com/cyberark/kubiscan/releases 197 | 198 | [license-img]: https://img.shields.io/github/license/cyberark/kubiscan.svg 199 | [license]: https://github.com/cyberark/kubiscan/blob/master/LICENSE 200 | -------------------------------------------------------------------------------- /__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberark/KubiScan/ade56e6762eb88db588d601860e38b339f2e7543/__init__.py -------------------------------------------------------------------------------- /api/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberark/KubiScan/ade56e6762eb88db588d601860e38b339f2e7543/api/__init__.py -------------------------------------------------------------------------------- /api/api_client.py: -------------------------------------------------------------------------------- 1 | from kubernetes import client, config 2 | from shutil import copyfile 3 | import os 4 | from tempfile import mkstemp 5 | from shutil import move 6 | from kubernetes.client.configuration import Configuration 7 | from kubernetes.client.api_client import ApiClient 8 | from .base_client_api import BaseApiClient 9 | 10 | # TODO: Should be removed after the bug will be solved: 11 | # https://github.com/kubernetes-client/python/issues/577 12 | from .api_client_temp import ApiClientTemp 13 | 14 | # The following variables have been commented as it resulted a bug when running `kubiscan -h` 15 | # Exception ignored in: filename, value -> filepath, 306 | for `multipart/form-data`. 307 | :param async_req bool: execute request asynchronously 308 | :param _return_http_data_only: response data without head status code and headers 309 | :param collection_formats: dict of collection formats for path, query, 310 | header, and post parameters. 311 | :param _preload_content: if False, the urllib3.HTTPResponse object will be returned without 312 | reading/decoding response data. Default is True. 313 | :param _request_timeout: timeout setting for this request. If one number provided, it will be total request 314 | timeout. It can also be a pair (tuple) of (connection, read) timeouts. 315 | :return: 316 | If async_req parameter is True, 317 | the request will be called asynchronously. 318 | The method will return the request thread. 319 | If parameter async_req is False or missing, 320 | then the method will return the response directly. 321 | """ 322 | if not async_req: 323 | return self.__call_api(resource_path, method, 324 | path_params, query_params, header_params, 325 | body, post_params, files, 326 | response_type, auth_settings, 327 | _return_http_data_only, collection_formats, _preload_content, _request_timeout) 328 | else: 329 | thread = self.pool.apply_async(self.__call_api, (resource_path, method, 330 | path_params, query_params, 331 | header_params, body, 332 | post_params, files, 333 | response_type, auth_settings, 334 | _return_http_data_only, 335 | collection_formats, _preload_content, _request_timeout)) 336 | return thread 337 | 338 | def request(self, method, url, query_params=None, headers=None, 339 | post_params=None, body=None, _preload_content=True, _request_timeout=None): 340 | """ 341 | Makes the HTTP request using RESTClient. 342 | """ 343 | if method == "GET": 344 | return self.rest_client.GET(url, 345 | query_params=query_params, 346 | _preload_content=_preload_content, 347 | _request_timeout=_request_timeout, 348 | headers=headers) 349 | elif method == "HEAD": 350 | return self.rest_client.HEAD(url, 351 | query_params=query_params, 352 | _preload_content=_preload_content, 353 | _request_timeout=_request_timeout, 354 | headers=headers) 355 | elif method == "OPTIONS": 356 | return self.rest_client.OPTIONS(url, 357 | query_params=query_params, 358 | headers=headers, 359 | post_params=post_params, 360 | _preload_content=_preload_content, 361 | _request_timeout=_request_timeout, 362 | body=body) 363 | elif method == "POST": 364 | return self.rest_client.POST(url, 365 | query_params=query_params, 366 | headers=headers, 367 | post_params=post_params, 368 | _preload_content=_preload_content, 369 | _request_timeout=_request_timeout, 370 | body=body) 371 | elif method == "PUT": 372 | return self.rest_client.PUT(url, 373 | query_params=query_params, 374 | headers=headers, 375 | post_params=post_params, 376 | _preload_content=_preload_content, 377 | _request_timeout=_request_timeout, 378 | body=body) 379 | elif method == "PATCH": 380 | return self.rest_client.PATCH(url, 381 | query_params=query_params, 382 | headers=headers, 383 | post_params=post_params, 384 | _preload_content=_preload_content, 385 | _request_timeout=_request_timeout, 386 | body=body) 387 | elif method == "DELETE": 388 | return self.rest_client.DELETE(url, 389 | query_params=query_params, 390 | headers=headers, 391 | _preload_content=_preload_content, 392 | _request_timeout=_request_timeout, 393 | body=body) 394 | else: 395 | raise ValueError( 396 | "http method must be `GET`, `HEAD`, `OPTIONS`," 397 | " `POST`, `PATCH`, `PUT` or `DELETE`." 398 | ) 399 | 400 | def parameters_to_tuples(self, params, collection_formats): 401 | """ 402 | Get parameters as list of tuples, formatting collections. 403 | 404 | :param params: Parameters as dict or list of two-tuples 405 | :param dict collection_formats: Parameter collection formats 406 | :return: Parameters as list of tuples, collections formatted 407 | """ 408 | new_params = [] 409 | if collection_formats is None: 410 | collection_formats = {} 411 | for k, v in iteritems(params) if isinstance(params, dict) else params: 412 | if k in collection_formats: 413 | collection_format = collection_formats[k] 414 | if collection_format == 'multi': 415 | new_params.extend((k, value) for value in v) 416 | else: 417 | if collection_format == 'ssv': 418 | delimiter = ' ' 419 | elif collection_format == 'tsv': 420 | delimiter = '\t' 421 | elif collection_format == 'pipes': 422 | delimiter = '|' 423 | else: # csv is the default 424 | delimiter = ',' 425 | new_params.append( 426 | (k, delimiter.join(str(value) for value in v))) 427 | else: 428 | new_params.append((k, v)) 429 | return new_params 430 | 431 | def prepare_post_parameters(self, post_params=None, files=None): 432 | """ 433 | Builds form parameters. 434 | 435 | :param post_params: Normal form parameters. 436 | :param files: File parameters. 437 | :return: Form parameters with files. 438 | """ 439 | params = [] 440 | 441 | if post_params: 442 | params = post_params 443 | 444 | if files: 445 | for k, v in iteritems(files): 446 | if not v: 447 | continue 448 | file_names = v if type(v) is list else [v] 449 | for n in file_names: 450 | with open(n, 'rb') as f: 451 | filename = os.path.basename(f.name) 452 | filedata = f.read() 453 | mimetype = mimetypes. \ 454 | guess_type(filename)[0] or 'application/octet-stream' 455 | params.append(tuple([k, tuple([filename, filedata, mimetype])])) 456 | 457 | return params 458 | 459 | def select_header_accept(self, accepts): 460 | """ 461 | Returns `Accept` based on an array of accepts provided. 462 | 463 | :param accepts: List of headers. 464 | :return: Accept (e.g. application/json). 465 | """ 466 | if not accepts: 467 | return 468 | 469 | accepts = [x.lower() for x in accepts] 470 | 471 | if 'application/json' in accepts: 472 | return 'application/json' 473 | else: 474 | return ', '.join(accepts) 475 | 476 | def select_header_content_type(self, content_types): 477 | """ 478 | Returns `Content-Type` based on an array of content_types provided. 479 | 480 | :param content_types: List of content-types. 481 | :return: Content-Type (e.g. application/json). 482 | """ 483 | if not content_types: 484 | return 'application/json' 485 | 486 | content_types = [x.lower() for x in content_types] 487 | 488 | if 'application/json' in content_types or '*/*' in content_types: 489 | return 'application/json' 490 | else: 491 | return content_types[0] 492 | 493 | def update_params_for_auth(self, headers, querys, auth_settings): 494 | """ 495 | Updates header and query params based on authentication setting. 496 | 497 | :param headers: Header parameters dict to be updated. 498 | :param querys: Query parameters tuple list to be updated. 499 | :param auth_settings: Authentication setting identifiers list. 500 | """ 501 | if not auth_settings: 502 | return 503 | 504 | for auth in auth_settings: 505 | auth_setting = self.configuration.auth_settings().get(auth) 506 | if auth_setting: 507 | if not auth_setting['value']: 508 | continue 509 | elif auth_setting['in'] == 'header': 510 | headers[auth_setting['key']] = auth_setting['value'] 511 | elif auth_setting['in'] == 'query': 512 | querys.append((auth_setting['key'], auth_setting['value'])) 513 | else: 514 | raise ValueError( 515 | 'Authentication token must be in `query` or `header`' 516 | ) 517 | 518 | def __deserialize_file(self, response): 519 | """ 520 | Saves response body into a file in a temporary folder, 521 | using the filename from the `Content-Disposition` header if provided. 522 | 523 | :param response: RESTResponse. 524 | :return: file path. 525 | """ 526 | fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path) 527 | os.close(fd) 528 | os.remove(path) 529 | 530 | content_disposition = response.getheader("Content-Disposition") 531 | if content_disposition: 532 | filename = re. \ 533 | search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition). \ 534 | group(1) 535 | path = os.path.join(os.path.dirname(path), filename) 536 | 537 | with open(path, "w") as f: 538 | f.write(response.data) 539 | 540 | return path 541 | 542 | def __deserialize_primitive(self, data, klass): 543 | """ 544 | Deserializes string to primitive type. 545 | 546 | :param data: str. 547 | :param klass: class literal. 548 | 549 | :return: int, long, float, str, bool. 550 | """ 551 | try: 552 | return klass(data) 553 | except UnicodeEncodeError: 554 | return unicode(data) 555 | except TypeError: 556 | return data 557 | 558 | def __deserialize_object(self, value): 559 | """ 560 | Return a original value. 561 | 562 | :return: object. 563 | """ 564 | return value 565 | 566 | def __deserialize_date(self, string): 567 | """ 568 | Deserializes string to date. 569 | 570 | :param string: str. 571 | :return: date. 572 | """ 573 | try: 574 | from dateutil.parser import parse 575 | return parse(string).date() 576 | except ImportError: 577 | return string 578 | except ValueError: 579 | raise ApiException( 580 | status=0, 581 | reason="Failed to parse `{0}` into a date object".format(string) 582 | ) 583 | 584 | def __deserialize_datatime(self, string): 585 | """ 586 | Deserializes string to datetime. 587 | 588 | The string should be in iso8601 datetime format. 589 | 590 | :param string: str. 591 | :return: datetime. 592 | """ 593 | try: 594 | from dateutil.parser import parse 595 | return parse(string) 596 | except ImportError: 597 | return string 598 | except ValueError: 599 | raise ApiException( 600 | status=0, 601 | reason=( 602 | "Failed to parse `{0}` into a datetime object" 603 | .format(string) 604 | ) 605 | ) 606 | 607 | def __deserialize_model(self, data, klass): 608 | """ 609 | Deserializes list or dict to model. 610 | 611 | :param data: dict, list. 612 | :param klass: class literal. 613 | :return: model object. 614 | """ 615 | 616 | if not klass.swagger_types and not hasattr(klass, 'get_real_child_model'): 617 | return data 618 | 619 | kwargs = {} 620 | if klass.swagger_types is not None: 621 | for attr, attr_type in iteritems(klass.swagger_types): 622 | if data is not None \ 623 | and klass.attribute_map[attr] in data \ 624 | and isinstance(data, (list, dict)): 625 | value = data[klass.attribute_map[attr]] 626 | kwargs[attr] = self.__deserialize(value, attr_type) 627 | 628 | instance = klass(**kwargs) 629 | 630 | if hasattr(instance, 'get_real_child_model'): 631 | klass_name = instance.get_real_child_model(data) 632 | if klass_name: 633 | instance = self.__deserialize(data, klass_name) 634 | return instance 635 | 636 | 637 | def list_cluster_role_binding(self): 638 | json_data = self.__call_api(resource_path='/apis/rbac.authorization.k8s.io/v1/clusterrolebindings', method='GET', 639 | path_params={}, query_params=[], 640 | header_params={'Content-Type': 'application/json', 'Accept': 'application/json'}, 641 | body=None, post_params=[], files={}, 642 | response_type='V1ClusterRoleBindingList', auth_settings=['BearerToken'], 643 | _return_http_data_only=None, collection_formats={}, _preload_content=True, 644 | _request_timeout=None) 645 | cluster_role_bindings = [] 646 | for i in json_data[0]['items']: 647 | 648 | metadata = V1ObjectMeta(name=i['metadata']['name'], creation_timestamp=self._ApiClientTemp__deserialize_datatime(i['metadata']['creationTimestamp'])) 649 | role_ref = V1RoleRef(api_group=i['roleRef']['apiGroup'], name=i['roleRef']['name'], kind=i['roleRef']['kind']) 650 | subjects = [] 651 | 652 | if 'subjects' in i and i['subjects'] is not None: 653 | for s in i['subjects']: 654 | namespace = None 655 | if 'namespace' in s.keys(): 656 | namespace = s['namespace'] 657 | subjects.append(V1Subject(kind=s['kind'], name=s['name'], namespace=namespace)) 658 | 659 | cluster_role_binding = V1ClusterRoleBinding(metadata=metadata, role_ref=role_ref, subjects=subjects) 660 | cluster_role_bindings.append(cluster_role_binding) 661 | 662 | return cluster_role_bindings 663 | 664 | def list_cluster_role(self): 665 | json_data = self.__call_api('/apis/rbac.authorization.k8s.io/v1/clusterroles', 'GET', 666 | path_params={}, query_params=[], 667 | header_params={'Content-Type': 'application/json', 'Accept': 'application/json'}, 668 | body=None, post_params=[], files={}, 669 | response_type='V1ClusterRoleList', auth_settings=['BearerToken'], 670 | _return_http_data_only=None, collection_formats={}, _preload_content=True, 671 | _request_timeout=None) 672 | cluster_roles = [] 673 | for i in json_data[0]['items']: 674 | metadata = V1ObjectMeta(name=i['metadata']['name'], 675 | creation_timestamp=self._ApiClientTemp__deserialize_datatime( 676 | i['metadata']['creationTimestamp'])) 677 | 678 | rules = [] 679 | if i['rules'] is not None: 680 | for rule in i['rules']: 681 | resources = None 682 | if 'resources' in rule.keys(): 683 | resources = rule['resources'] 684 | verbs = None 685 | if 'verbs' in rule.keys(): 686 | verbs = rule['verbs'] 687 | 688 | rules.append(V1PolicyRule(resources=resources, verbs=verbs)) 689 | 690 | cluster_role = V1ClusterRole(kind='ClusterRole', metadata=metadata, rules=rules) 691 | cluster_roles.append(cluster_role) 692 | 693 | return V1ClusterRoleList(items=cluster_roles) -------------------------------------------------------------------------------- /api/base_client_api.py: -------------------------------------------------------------------------------- 1 | from abc import ABC, abstractmethod 2 | 3 | 4 | class BaseApiClient(ABC): 5 | 6 | @abstractmethod 7 | def list_roles_for_all_namespaces(self): 8 | pass 9 | 10 | @abstractmethod 11 | def list_cluster_role(self): 12 | pass 13 | 14 | @abstractmethod 15 | def list_role_binding_for_all_namespaces(self): 16 | pass 17 | 18 | @abstractmethod 19 | def list_cluster_role_binding(self): 20 | pass 21 | 22 | @abstractmethod 23 | def read_namespaced_role_binding(self,rolebinding_name, namespace): 24 | pass 25 | 26 | @abstractmethod 27 | def read_namespaced_role(self, role_name, namespace): 28 | pass 29 | 30 | @abstractmethod 31 | def read_cluster_role(self, role_name): 32 | pass 33 | 34 | @abstractmethod 35 | def list_pod_for_all_namespaces(self,watch): 36 | pass 37 | 38 | @abstractmethod 39 | def list_namespaced_pod(self,namespace): 40 | pass -------------------------------------------------------------------------------- /api/client_factory.py: -------------------------------------------------------------------------------- 1 | from .static_api_client import StaticApiClient 2 | from .api_client import RegularApiClient 3 | 4 | class ApiClientFactory: 5 | @staticmethod 6 | def get_client(use_static=False, input_file=None): 7 | if use_static: 8 | return StaticApiClient(input_file=input_file) 9 | else: 10 | return RegularApiClient() 11 | 12 | 13 | #api_client = ApiClientFactory.get_client(use_static=True, input_file="/home/noamr/Documents/KubiScan/combined.json") 14 | #api_client = ApiClientFactory.get_client() 15 | #print(api_client.list_roles_for_all_namespaces()) -------------------------------------------------------------------------------- /api/config.py: -------------------------------------------------------------------------------- 1 | # config.py 2 | 3 | class Config: 4 | api_client = None 5 | 6 | def set_api_client(client): 7 | Config.api_client = client 8 | 9 | def get_api_client(): 10 | return Config.api_client 11 | -------------------------------------------------------------------------------- /api/static_api_client.py: -------------------------------------------------------------------------------- 1 | import json 2 | import yaml 3 | import os 4 | from datetime import datetime 5 | from .base_client_api import BaseApiClient 6 | from kubernetes.client import ( 7 | V1VolumeProjection, V1ServiceAccountTokenProjection, V1SecretProjection, V1DownwardAPIProjection, 8 | V1RoleList, V1Role, V1ObjectMeta, V1PolicyRule, V1RoleBinding, V1RoleRef, V1Subject, 9 | V1RoleBindingList, V1PodList, V1Pod, V1PodSpec, V1Container, V1Volume, V1PodStatus, 10 | V1SecurityContext, V1HostPathVolumeSource, V1ProjectedVolumeSource,V1VolumeMount,V1ConfigMapProjection, 11 | V1DownwardAPIVolumeFile,V1ObjectFieldSelector,V1ContainerStatus,V1Capabilities,V1PodSecurityContext,V1ContainerPort 12 | ) 13 | 14 | class StaticApiClient(BaseApiClient): 15 | def __init__(self, input_file): 16 | self.combined_data = self.load_combined_file(input_file) 17 | self.all_roles = self.construct_v1_role_list("Role", self.get_resources('Role')) 18 | self.all_cluster_roles = self.construct_v1_role_list("ClusterRole", self.get_resources('ClusterRole')) 19 | self.all_role_bindings = self.construct_v1_role_binding_list("RoleBinding", self.get_resources('RoleBinding')) 20 | self.all_cluster_role_bindings = self.construct_v1_role_binding_list("ClusterRoleBinding", self.get_resources('ClusterRoleBinding')) 21 | self.all_pods = self.construct_v1_pod_list("Pod", self.get_resources('Pod')) 22 | 23 | def load_combined_file(self, input_file): 24 | _, file_extension = os.path.splitext(input_file) 25 | file_format = 'json' if file_extension.lower() == '.json' else 'yaml' if file_extension.lower() == '.yaml' else None 26 | 27 | if not file_format: 28 | print("Unsupported file extension. Only '.yaml' and '.json' are supported.") 29 | return None 30 | 31 | try: 32 | with open(input_file, 'r') as file: 33 | if file_format == "yaml": 34 | documents = list(yaml.safe_load_all(file)) 35 | return documents 36 | elif file_format == "json": 37 | return json.load(file) 38 | except FileNotFoundError: 39 | print(f"File not found: {input_file}") 40 | return None 41 | except Exception as e: 42 | print(f"Error reading file: {e}") 43 | return None 44 | 45 | def get_resources(self, kind): 46 | resources = [] 47 | if self.combined_data: 48 | for entry in self.combined_data: 49 | if 'items' in entry and isinstance(entry['items'], list): 50 | resources.extend(item for item in entry['items'] if item.get('kind') == kind) 51 | return resources 52 | 53 | 54 | def parse_metadata(self, metadata_dict): 55 | creation_timestamp_str = metadata_dict.get('creationTimestamp') 56 | creation_timestamp = None 57 | if creation_timestamp_str: 58 | creation_timestamp = datetime.strptime(creation_timestamp_str, "%Y-%m-%dT%H:%M:%SZ") 59 | return V1ObjectMeta( 60 | name=metadata_dict['name'], 61 | namespace=metadata_dict.get('namespace'), 62 | creation_timestamp=creation_timestamp 63 | ) 64 | 65 | def construct_v1_role_list(self, kind, items): 66 | v1_roles = [] 67 | for item in items: 68 | v1_role = V1Role( 69 | api_version=item['apiVersion'], 70 | kind=item['kind'], 71 | metadata =self.parse_metadata(item['metadata']), 72 | rules=[ 73 | V1PolicyRule( 74 | api_groups=rule.get('apiGroups', []), 75 | resources=rule.get('resources', []), 76 | verbs=rule.get('verbs', []), 77 | resource_names=rule.get('resourceNames', []) 78 | ) for rule in item.get('rules', []) 79 | ] 80 | ) 81 | v1_roles.append(v1_role) 82 | 83 | return V1RoleList( 84 | api_version="rbac.authorization.k8s.io/v1", 85 | kind=f"{kind}List", 86 | items=v1_roles, 87 | metadata={'resourceVersion': '1'} 88 | ) 89 | 90 | def construct_v1_role_binding_list(self, kind, items): 91 | v1_role_bindings = [] 92 | for item in items: 93 | 94 | 95 | 96 | v1_role_binding = V1RoleBinding( 97 | api_version=item['apiVersion'], 98 | kind=item['kind'], 99 | metadata =self.parse_metadata(item['metadata']), 100 | subjects=[ 101 | V1Subject( 102 | kind=subject.get('kind'), 103 | name=subject.get('name'), 104 | namespace=subject.get('namespace') 105 | ) for subject in item.get('subjects', []) 106 | ], 107 | role_ref=V1RoleRef( 108 | api_group=item['roleRef'].get('apiGroup'), 109 | kind=item['roleRef'].get('kind'), 110 | name=item['roleRef'].get('name') 111 | ) 112 | ) 113 | v1_role_bindings.append(v1_role_binding) 114 | 115 | return V1RoleBindingList( 116 | api_version="rbac.authorization.k8s.io/v1", 117 | kind=f"{kind}List", 118 | items=v1_role_bindings, 119 | metadata={'resourceVersion': '1'} 120 | ) 121 | 122 | def construct_v1_pod_list(self, kind, items): 123 | v1_pods = [] 124 | for item in items: 125 | metadata = item.get('metadata', {}) 126 | spec = item.get('spec', {}) 127 | status = item.get('status', {}) 128 | pod_security_context = V1PodSecurityContext( 129 | run_as_user=spec.get('securityContext', {}).get('runAsUser', None), 130 | run_as_group=spec.get('securityContext', {}).get('runAsGroup', None), 131 | fs_group=spec.get('securityContext', {}).get('fsGroup', None), 132 | se_linux_options=spec.get('securityContext', {}).get('seLinuxOptions', None) 133 | ) 134 | container_statuses = [ 135 | V1ContainerStatus( 136 | name=container_status.get('name'), 137 | ready=container_status.get('ready', False), 138 | restart_count=container_status.get('restartCount', 0), 139 | image=container_status.get('image'), 140 | image_id=container_status.get('imageID'), 141 | container_id=container_status.get('containerID') 142 | ) for container_status in status.get('containerStatuses', []) 143 | ] 144 | 145 | # Create a V1Pod object without trying to set 'is_risky' 146 | v1_pod = V1Pod( 147 | api_version=item.get('apiVersion', 'v1'), 148 | kind=item.get('kind', 'Pod'), 149 | metadata=V1ObjectMeta( 150 | name=metadata.get('name'), 151 | namespace=metadata.get('namespace', None), 152 | labels=metadata.get('labels', {}), 153 | annotations=metadata.get('annotations', {}), 154 | creation_timestamp=metadata.get('creationTimestamp', None), 155 | uid=metadata.get('uid', None), 156 | resource_version=metadata.get('resourceVersion', None) 157 | ), 158 | spec=V1PodSpec( 159 | security_context=pod_security_context, 160 | service_account=spec.get('serviceAccount', None), 161 | service_account_name=spec.get('serviceAccountName', None), 162 | node_name=spec.get('nodeName', None), 163 | host_ipc=spec.get('hostIpc', False), 164 | host_pid=spec.get('hostPid', False), 165 | host_network=spec.get('hostNetwork', False), 166 | restart_policy=spec.get('restartPolicy', 'Always'), 167 | containers=[ 168 | V1Container( 169 | name=container['name'], 170 | image=container.get('image'), 171 | ports=[ 172 | V1ContainerPort( 173 | container_port=port.get('containerPort'), 174 | host_port=port.get('hostPort'), 175 | protocol=port.get('protocol', 'TCP'), 176 | name=port.get('name', None) 177 | ) for port in container.get('ports', []) 178 | ], 179 | volume_mounts=[ 180 | V1VolumeMount( 181 | mount_path=volume_mount.get('mountPath'), 182 | name=volume_mount.get('name'), 183 | read_only=volume_mount.get('readOnly', False) 184 | ) for volume_mount in container.get('volumeMounts', []) 185 | ], 186 | image_pull_policy=container.get('imagePullPolicy'), 187 | resources=container.get('resources', {}), 188 | security_context=V1SecurityContext( 189 | run_as_user=container.get('securityContext', {}).get('runAsUser', None), 190 | run_as_group=container.get('securityContext', {}).get('runAsGroup', None), 191 | privileged=container.get('securityContext', {}).get('privileged', False), 192 | allow_privilege_escalation=container.get('securityContext', {}).get('allowPrivilegeEscalation', None), 193 | capabilities=V1Capabilities( 194 | add=container.get('securityContext', {}).get('capabilities', {}).get('add', []), 195 | drop=container.get('securityContext', {}).get('capabilities', {}).get('drop', []) 196 | ) if container.get('securityContext', {}).get('capabilities') else None 197 | ) 198 | ) for container in spec.get('containers', []) 199 | ], 200 | volumes=[ 201 | V1Volume( 202 | name=volume.get('name'), 203 | empty_dir=volume.get('emptyDir', {}), 204 | persistent_volume_claim=volume.get('persistentVolumeClaim', {}), 205 | host_path=V1HostPathVolumeSource( 206 | path=volume.get('hostPath', {}).get('path', ''), 207 | type=volume.get('hostPath', {}).get('type', '') 208 | ), 209 | projected=V1ProjectedVolumeSource( 210 | sources=[ 211 | V1VolumeProjection( 212 | service_account_token=V1ServiceAccountTokenProjection( 213 | path=source.get('serviceAccountToken', {}).get('path', ''), 214 | expiration_seconds=source.get('serviceAccountToken', {}).get('expirationSeconds', None) 215 | ), 216 | secret=V1SecretProjection( 217 | name=source.get('secret', {}).get('name', None) 218 | ), 219 | config_map=V1ConfigMapProjection( 220 | name=source.get('configMap', {}).get('name', None) 221 | ), 222 | downward_api=V1DownwardAPIProjection( 223 | items=[ 224 | V1DownwardAPIVolumeFile( 225 | path=item.get('path'), 226 | field_ref=V1ObjectFieldSelector( 227 | api_version=item.get('fieldRef', {}).get('apiVersion', 'v1'), 228 | field_path=item.get('fieldRef', {}).get('fieldPath', '') 229 | ) 230 | ) for item in source.get('downwardAPI', {}).get('items', []) 231 | ] 232 | ) 233 | ) for source in volume.get('projected', {}).get('sources', []) 234 | ] 235 | ) 236 | ) for volume in spec.get('volumes', []) 237 | ] 238 | ), 239 | status=V1PodStatus( 240 | phase=status.get('phase', 'Unknown'), # Default phase to 'Unknown' 241 | conditions=status.get('conditions', []), 242 | container_statuses=container_statuses 243 | ) 244 | ) 245 | v1_pods.append(v1_pod) 246 | 247 | return V1PodList( 248 | api_version="v1", 249 | kind=f"{kind}List", 250 | items=v1_pods, 251 | metadata={'resourceVersion': '1'} 252 | ) 253 | 254 | def list_roles_for_all_namespaces(self): 255 | return self.all_roles 256 | 257 | def list_cluster_role(self): 258 | return self.all_cluster_roles 259 | 260 | def list_role_binding_for_all_namespaces(self): 261 | return self.all_role_bindings 262 | 263 | def list_cluster_role_binding(self): 264 | return self.all_cluster_role_bindings.items 265 | 266 | def read_namespaced_role_binding(self, rolebinding_name, namespace): 267 | for rolebinding in self.all_role_bindings.items: 268 | if rolebinding.metadata.name == rolebinding_name and rolebinding.metadata.namespace == namespace: 269 | return rolebinding 270 | return None 271 | 272 | def read_namespaced_role(self, role_name, namespace): 273 | for role in self.all_roles.items: 274 | if role.metadata.name == role_name and role.metadata.namespace == namespace: 275 | return role 276 | return None 277 | 278 | def read_cluster_role(self, role_name): 279 | for role in self.all_cluster_roles.items: 280 | if role.metadata.name == role_name: 281 | return role 282 | return None 283 | 284 | def list_pod_for_all_namespaces(self, watch): 285 | return self.all_pods 286 | 287 | def list_namespaced_pod(self, namespace): 288 | # Filter the pods based on the namespace 289 | filtered_pods = [pod for pod in self.all_pods.items if pod.metadata.namespace == namespace] 290 | 291 | # Return the filtered pods as a V1PodList 292 | return V1PodList( 293 | api_version="v1", 294 | kind="PodList", 295 | items=filtered_pods, 296 | metadata={'resourceVersion': '1'} 297 | ) -------------------------------------------------------------------------------- /docker_run.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # Getting the kubeconfig path. 4 | kube_config="$1" 5 | aws_dir="$2" 6 | # Check if the file is empty 7 | if [ -z "$kube_config" ]; 8 | then 9 | echo "Please provide kube config path" 10 | exit 1 11 | fi 12 | 13 | # Check if the file exists 14 | if ! test -f "$kube_config"; then 15 | echo "File of directory does not exist" 16 | exit 1 17 | fi 18 | 19 | 20 | # Running the container. 21 | docker run -t -d --rm --name kubiscan_container -e CONF_PATH=/config --network host g3rzi/kubiscan 22 | 23 | # The new container id. 24 | kubiscan_container_id=$( docker ps -a -f "name=kubiscan_container" -q) 25 | 26 | # If the argument is empty, enter. 27 | if [ -n "$aws_dir" ]; 28 | then 29 | echo "Copying aws folder" 30 | docker exec "$kubiscan_container_id" bash -c "mkdir -p /home/kubiscan" 31 | docker cp "$aws_dir" "$kubiscan_container_id":/home/kubiscan/.aws/ 32 | fi 33 | 34 | 35 | # Get the path to the certificate auth file 36 | certificate_auth=$(grep -i "certificate-authority:" "$kube_config" | sed 's/certificate-authority://g' | sed 's/ //g') 37 | # 'certificate_auth%/*' delete everything after the last '/' 38 | if [ -n "$certificate_auth" ]; 39 | then 40 | certificate_auth_path="/tmp${certificate_auth%/*}" 41 | echo "Creating folders: $certificate_auth_path" 42 | docker exec -it "$kubiscan_container_id" bash -c "mkdir -p $certificate_auth_path" 43 | fi 44 | # Get all the paths of the cert files in the kube config file. 45 | cert_array=$(grep -i "client-certificate:" "$kube_config" | sed 's/client-certificate://g' | sed 's/ //g') 46 | # Get all the paths of the key files in the kube config file. 47 | key_array=$(grep -i "client-key:" "$kube_config" | sed 's/client-key://g' | sed 's/ //g') 48 | 49 | #Create all the paths for the 'mkdir' command in the container. 50 | if [ -n "$cert_array" ]; 51 | then 52 | echo "$cert_array" 53 | raw_cert_paths="" 54 | for var in $cert_array: 55 | do 56 | # 'var%/*' delete everything after the last '/' 57 | raw_cert_paths="$raw_cert_paths /tmp${var%/*}" 58 | done 59 | fi 60 | 61 | if [ -n "$key_array" ]; 62 | then 63 | raw_key_paths="" 64 | for path in $key_array: 65 | do 66 | # 'var%/*' delete everything after the last '/' 67 | raw_key_paths="$raw_key_paths /tmp${path%/*}" 68 | done 69 | all_paths="$raw_cert_paths $raw_key_paths" 70 | echo "Creating folders: $all_paths" 71 | docker exec -it "$kubiscan_container_id" bash -c "mkdir -p $all_paths" 72 | fi 73 | 74 | 75 | if [ -n "$cert_array" ]; 76 | then 77 | # Copy all the certificates to the container 78 | for cert_file in $cert_array 79 | do 80 | # Copy them to tmp folder 81 | echo "Copying $cert_file to /tmp$cert_file" 82 | docker cp "$cert_file" "$kubiscan_container_id":/tmp"$cert_file" 83 | done 84 | fi 85 | 86 | if [ -n "$key_array" ]; 87 | then 88 | # Copy all keys to the container 89 | for key_file in $key_array 90 | do 91 | # Copy them to tmp folder 92 | echo "Copying $key_file to /tmp $key_file" 93 | docker cp "$key_file" "$kubiscan_container_id":/tmp"$key_file" 94 | done 95 | fi 96 | 97 | # Copy kube config file 98 | echo "Copying $kube_config to /tmp" 99 | docker cp "$kube_config" "$kubiscan_container_id:/tmp" 100 | 101 | # Copy certificate auth file 102 | 103 | if [ -n "$certificate_auth" ]; 104 | then 105 | echo "Copying $certificate_auth to $certificate_auth" 106 | docker cp "$certificate_auth" "$kubiscan_container_id":/tmp/"$certificate_auth" 107 | fi 108 | # Giving permissions to /tmp and opt/KubiScan 109 | # The "-f" in chmod will suppress the errors 110 | docker exec -it "$kubiscan_container_id" bash -c "chmod -fR 777 /tmp /opt/kubiscan /home/kubiscan" 111 | docker exec -it --user kubiscan "$kubiscan_container_id" bash 112 | 113 | -------------------------------------------------------------------------------- /engine/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberark/KubiScan/ade56e6762eb88db588d601860e38b339f2e7543/engine/__init__.py -------------------------------------------------------------------------------- /engine/capabilities/capabilities.py: -------------------------------------------------------------------------------- 1 | 2 | caps_list = { 3 | "CHOWN": 1, 4 | "DAC_OVERRIDE": 2, 5 | "DAC_READ_SEARCH": 3, 6 | "FOWNER": 4, 7 | "FSETID": 5, 8 | "KILL": 6, 9 | "SETGID": 7, 10 | "SETUID": 8, 11 | "SETPCAP": 9, 12 | "LINUX_IMMUTABLE": 10, 13 | "NET_BIND_SERVICE": 11, 14 | "NET_BROADCAST": 12, 15 | "NET_ADMIN": 13, 16 | "NET_RAW": 14, 17 | "IPC_LOCK": 15, 18 | "IPC_OWNER": 16, 19 | "SYS_MODULE": 17, 20 | "SYS_RAWIO": 18, 21 | "SYS_CHROOT": 19, 22 | "SYS_PTRACE": 20, 23 | "SYS_PACCT": 21, 24 | "SYS_ADMIN": 22, 25 | "SYS_BOOT": 23, 26 | "SYS_NICE": 24, 27 | "SYS_RESOURCE": 25, 28 | "SYS_TIME": 26, 29 | "SYS_TTY_CONFIG": 27, 30 | "MKNOD": 28, 31 | "LEASE": 29, 32 | "AUDIT_WRITE": 30, 33 | "AUDIT_CONTROL": 31, 34 | "SETFCAP": 32, 35 | "MAC_OVERRIDE": 33, 36 | "MAC_ADMIN": 34, 37 | "SYSLOG": 35, 38 | "WAKE_ALARM": 36, 39 | "BLOCK_SUSPEND": 37, 40 | "AUDIT_READ": 38 41 | } 42 | 43 | default_caps = { 44 | "CAP_CHOWN": 1, 45 | "DAC_OVERRIDE": 2, 46 | "FOWNER": 4, 47 | "FSETID": 5, 48 | "KILL": 6, 49 | "SETGID": 7, 50 | "SETUID": 8, 51 | "SETPCAP": 9, 52 | "NET_BIND_SERVICE": 11, 53 | "NET_RAW": 14, 54 | "SYS_CHROOT": 19, 55 | "MKNOD": 28, 56 | "AUDIT_WRITE": 30, 57 | "SETFCAP": 32, 58 | "AUDIT_READ": 38 59 | } 60 | 61 | dangerous_caps = { 62 | "DAC_READ_SEARCH": 3, 63 | "LINUX_IMMUTABLE": 10, 64 | "NET_BROADCAST": 12, 65 | "NET_ADMIN": 13, 66 | "IPC_LOCK": 15, 67 | "IPC_OWNER": 16, 68 | "SYS_MODULE": 17, 69 | "SYS_RAWIO": 18, 70 | "SYS_PTRACE": 20, 71 | "SYS_BOOT": 23, 72 | "SYS_PACCT": 21, 73 | "SYS_ADMIN": 22, 74 | "SYS_NICE": 24, 75 | "SYS_RESOURCE": 25, 76 | "SYS_TIME": 26, 77 | "SYS_TTY_CONFIG": 27, 78 | "LEASE": 29, 79 | "AUDIT_CONTROL": 31, 80 | "MAC_OVERRIDE": 33, 81 | "MAC_ADMIN": 34, 82 | "SYSLOG": 35, 83 | "WAKE_ALARM": 36, 84 | "BLOCK_SUSPEND": 37 85 | } 86 | 87 | 88 | 89 | 90 | 91 | 92 | #indexes = get_indexes_with_one(0x10) 93 | #indexes = get_indexes_with_one(0x3fffffffff) 94 | #print_decoded_capabilities(indexes) -------------------------------------------------------------------------------- /engine/container.py: -------------------------------------------------------------------------------- 1 | class Container: 2 | def __init__(self, name, service_account_name=None, service_account_namespace=None, service_accounts_name_set=None, priority=None, token=None, raw_jwt_token=None): 3 | self.name = name 4 | self.service_account_name = service_account_name 5 | self.service_account_namespace = service_account_namespace 6 | self.service_accounts_name_set = service_accounts_name_set 7 | self.priority = priority 8 | self.token = token 9 | self.raw_jwt_token = raw_jwt_token 10 | -------------------------------------------------------------------------------- /engine/join_token.sh: -------------------------------------------------------------------------------- 1 | MASTER_SERVER_IP="$1" 2 | MASTER_SERVER_PORT="$2" 3 | 4 | #CA_CRT_PATH="/etc/kubernetes/pki/ca.crt" 5 | CA_CRT_PATH="$3" 6 | 7 | TOKEN="$4" 8 | 9 | SHA=`openssl x509 -pubkey -in $CA_CRT_PATH | openssl rsa -pubin -outform der 2>/dev/null | openssl dgst -sha256 -hex | sed 's/^.* //'` 10 | 11 | # Might need `sudo` 12 | #TOKEN_LIST=`kubeadm token list` 13 | 14 | #TOKEN=`echo $TOKEN_LIST | cut -d ' ' -f8` 15 | 16 | echo "kubeadm join --token $TOKEN $MASTER_SERVER_IP:$MASTER_SERVER_PORT --discovery-token-ca-cert-hash sha256:$SHA" -------------------------------------------------------------------------------- /engine/jwt_token.py: -------------------------------------------------------------------------------- 1 | 2 | import base64 3 | 4 | def decode_base64_jwt_token(base64_token): 5 | return decode_jwt_token_data(decode_base64_bytes_to_string(decode_base64(base64_token))) 6 | 7 | def decode_jwt_token_data(jwt_token): 8 | try: 9 | splitted_string = jwt_token.split(".") 10 | decoded_data_base64 = decode_base64(splitted_string[1]) 11 | return decode_base64_bytes_to_string(decoded_data_base64) 12 | except Exception: 13 | return None 14 | 15 | def decode_base64_bytes_to_string(decoded_data_base64): 16 | decoded_data = '' 17 | try: 18 | decoded_data = decoded_data_base64.decode("utf-8") 19 | except Exception as e: 20 | print('[*] An error occured while trying to deocde the JWT token:') 21 | print(str(e)) 22 | print("[*] Decoding the token with latin-1 instead of UTF-8...") 23 | decoded_data = decoded_data_base64.decode("latin-1") 24 | return decoded_data 25 | 26 | 27 | def decode_base64(data): 28 | """Decode base64, padding being optional. 29 | 30 | :param data: Base64 data as an ASCII byte string 31 | :returns: The decoded byte string. 32 | 33 | """ 34 | missing_padding = len(data) % 4 35 | if missing_padding != 0: 36 | data += '='* (4 - missing_padding) 37 | return base64.b64decode(data) 38 | -------------------------------------------------------------------------------- /engine/pod.py: -------------------------------------------------------------------------------- 1 | # TODO: add priority field which will have the highest priority from the containers 2 | class Pod: 3 | def __init__(self, name, namespace, containers): 4 | self.name = name 5 | self.namespace = namespace 6 | self.containers = containers 7 | -------------------------------------------------------------------------------- /engine/priority.py: -------------------------------------------------------------------------------- 1 | 2 | from enum import Enum 3 | 4 | class Priority(Enum): 5 | CRITICAL = 4 6 | HIGH = 3 7 | MEDIUM = 2 8 | LOW = 1 9 | NONE = 0 10 | 11 | 12 | def get_priority_by_name(priority): 13 | return { 14 | Priority.CRITICAL.name: Priority.CRITICAL, 15 | Priority.HIGH.name: Priority.HIGH, 16 | Priority.MEDIUM.name: Priority.MEDIUM, 17 | Priority.LOW.name: Priority.LOW, 18 | Priority.NONE.name: Priority.NONE, 19 | 20 | }[priority] -------------------------------------------------------------------------------- /engine/privleged_containers.py: -------------------------------------------------------------------------------- 1 | import engine.capabilities.capabilities as caps 2 | from api import api_client 3 | from api.config import get_api_client 4 | 5 | def list_pods_for_all_namespaces_or_one_namspace(namespace=None): 6 | api_client=get_api_client() 7 | if namespace is None: 8 | pods = api_client.list_pod_for_all_namespaces(watch=False) 9 | else: 10 | pods = api_client.list_namespaced_pod(namespace) 11 | return pods 12 | 13 | def list_pods(namespace=None): 14 | return list_pods_for_all_namespaces_or_one_namspace(namespace) 15 | 16 | def is_privileged(security_context, is_container=False): 17 | is_privileged = False 18 | if security_context: 19 | # shared to pods and containers 20 | if security_context.run_as_user == 0: 21 | is_privileged = True 22 | elif is_container: 23 | if security_context.privileged: 24 | is_privileged = True 25 | elif security_context.allow_privilege_escalation: 26 | is_privileged = True 27 | elif security_context.capabilities: 28 | if security_context.capabilities.add: 29 | for cap in security_context.capabilities.add: 30 | if cap in caps.dangerous_caps: 31 | is_privileged = True 32 | break 33 | return is_privileged 34 | 35 | def get_privileged_containers(namespace=None): 36 | privileged_pods = [] 37 | pods = list_pods_for_all_namespaces_or_one_namspace(namespace) 38 | for pod in pods.items: 39 | privileged_containers = [] 40 | if pod.spec.host_ipc or pod.spec.host_pid or pod.spec.host_network or is_privileged(pod.spec.security_context, is_container=False): 41 | privileged_containers = pod.spec.containers 42 | else: 43 | for container in pod.spec.containers: 44 | found_privileged_container = False 45 | if is_privileged(container.security_context, is_container=True): 46 | privileged_containers.append(container) 47 | elif container.ports: 48 | for ports in container.ports: 49 | if ports.host_port: 50 | privileged_containers.append(container) 51 | found_privileged_container = True 52 | break 53 | if not found_privileged_container: 54 | if pod.spec.volumes is not None: 55 | for volume in pod.spec.volumes: 56 | if found_privileged_container: 57 | break 58 | if volume.host_path: 59 | for volume_mount in container.volume_mounts: 60 | if volume_mount.name == volume.name: 61 | privileged_containers.append(container) 62 | found_privileged_container = True 63 | break 64 | if privileged_containers: 65 | pod.spec.containers = privileged_containers 66 | privileged_pods.append(pod) 67 | 68 | return privileged_pods 69 | -------------------------------------------------------------------------------- /engine/role.py: -------------------------------------------------------------------------------- 1 | from kubernetes import client, config 2 | 3 | # This class is also for ClusterRole 4 | class Role: 5 | def __init__(self, name, priority, rules=None, namespace=None, kind=None, time=None): 6 | self.name = name 7 | self.priority = priority 8 | self.rules = rules 9 | self.namespace = namespace 10 | self.kind = kind 11 | self.time = time 12 | 13 | def get_rules(self): 14 | config.load_kube_config() 15 | v1 = client.RbacAuthorizationV1Api() 16 | if self.kind.lower() == "role": 17 | return (v1.read_namespaced_role(self.name, self.namespace)).rules 18 | else: # "clusterrole" 19 | return (v1.read_cluster_role(self.name)).rules -------------------------------------------------------------------------------- /engine/role_binding.py: -------------------------------------------------------------------------------- 1 | # This class is also for ClusterRoleBinding 2 | class RoleBinding: 3 | def __init__(self, name, priority, namespace=None, kind=None, subjects=None, time=None): 4 | self.name = name 5 | self.priority = priority 6 | self.namespace = namespace 7 | self.kind = kind 8 | self.subjects = subjects 9 | self.time = time -------------------------------------------------------------------------------- /engine/rule.py: -------------------------------------------------------------------------------- 1 | # It is also possible to use client.V1PolicyRule(api_groups, non_resource_ur_ls, resource_names, resources, verbs) 2 | class Rule: 3 | def __init__(self, verbs, resources, resource_names=None): 4 | self.verbs = verbs 5 | self.resources = resources 6 | self.resource_names = resource_names -------------------------------------------------------------------------------- /engine/subject.py: -------------------------------------------------------------------------------- 1 | # There are three types of subjects: 2 | # 1. User 3 | # 2. Group 4 | # 3. ServiceAccount 5 | # https://github.com/kubernetes-client/python/blob/master/kubernetes/docs/V1Subject.md 6 | class Subject: 7 | def __init__(self, raw_info, priority): 8 | self.user_info = raw_info 9 | self.priority = priority -------------------------------------------------------------------------------- /engine/utils.py: -------------------------------------------------------------------------------- 1 | import requests 2 | 3 | from engine.role import Role 4 | from engine.priority import Priority 5 | from static_risky_roles import STATIC_RISKY_ROLES 6 | from engine.role_binding import RoleBinding 7 | from kubernetes.stream import stream 8 | from engine.pod import Pod 9 | from engine.container import Container 10 | import json 11 | from api import api_client 12 | from engine.subject import Subject 13 | from misc.constants import * 14 | from kubernetes.client.rest import ApiException 15 | import urllib3 16 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) 17 | from api.config import Config 18 | 19 | # region - Roles and ClusteRoles 20 | 21 | list_of_service_accounts = [] 22 | def is_risky_resource_name_exist(source_rolename, source_resourcenames): 23 | is_risky = False 24 | for resource_name in source_resourcenames: 25 | # prevent cycles. 26 | if resource_name != source_rolename: 27 | # TODO: Need to allow this check also for 'roles' resource_name, should consider namespace... 28 | role = get_role_by_name_and_kind(resource_name, CLUSTER_ROLE_KIND) 29 | if role is not None: 30 | is_risky, priority = is_risky_role(role) 31 | if is_risky: 32 | break 33 | 34 | return is_risky 35 | 36 | 37 | def is_rule_contains_risky_rule(source_role_name, source_rule, risky_rule): 38 | is_contains = True 39 | is_bind_verb_found = False 40 | is_role_resource_found = False 41 | 42 | # Optional: uncomment and shift everything bellow till the 'return' to add any rules that have "*" in their verbs or resources. 43 | # currently it is being handled in risky_roles.yaml partially 44 | # if (source_rule.verbs is not None and "*" not in source_rule.verbs) and (source_rule.resources is not None and "*" not in source_rule.resources): 45 | for verb in risky_rule.verbs: 46 | if verb not in source_rule.verbs: 47 | is_contains = False 48 | break 49 | 50 | if verb.lower() == "bind": 51 | is_bind_verb_found = True 52 | 53 | if is_contains and source_rule.resources is not None: 54 | for resource in risky_rule.resources: 55 | if resource not in source_rule.resources: 56 | is_contains = False 57 | break 58 | if resource.lower() == "roles" or resource.lower() == "clusterroles": 59 | is_role_resource_found = True 60 | 61 | if is_contains and risky_rule.resource_names is not None: 62 | is_contains = False 63 | if is_bind_verb_found and is_role_resource_found: 64 | is_risky = is_risky_resource_name_exist(source_role_name, source_rule.resource_names) 65 | if is_risky: 66 | is_contains = True 67 | else: 68 | is_contains = False 69 | 70 | return is_contains 71 | 72 | 73 | def get_current_version(certificate_authority_file=None, client_certificate_file=None, client_key_file=None, host=None): 74 | if host is None: 75 | version = api_client.api_version.get_code().git_version 76 | return version.replace('v', "") 77 | else: 78 | if certificate_authority_file is None and client_certificate_file is None and client_key_file is None: 79 | response = requests.get(host + '/version', verify=False) 80 | if response.status_code != 200: 81 | print(response.text) 82 | return None 83 | else: 84 | return response.json()["gitVersion"].replace('v', "") 85 | if certificate_authority_file is not None and client_certificate_file is not None and client_key_file is not None: 86 | response = requests.get(host + '/version', cert=(client_certificate_file, client_key_file), 87 | verify=certificate_authority_file) 88 | if response.status_code != 200: 89 | print(response.text) 90 | return None 91 | else: 92 | return response.json()["gitVersion"].replace('v', "") 93 | if certificate_authority_file is None or client_certificate_file is None or client_key_file is None or host is None: 94 | print("Please provide certificate authority file path, client certificate file path," 95 | " client key file path and host address") 96 | return None 97 | response = requests.get(host + '/version', cert=(client_certificate_file, client_key_file), 98 | verify=certificate_authority_file) 99 | if response.status_code != 200: 100 | print(response.text) 101 | return None 102 | else: 103 | return response.json()["gitVersion"].replace('v', "") 104 | 105 | 106 | 107 | 108 | def get_role_by_name_and_kind(name, kind, namespace=None): 109 | requested_role = None 110 | roles = get_roles_by_kind(kind) 111 | for role in roles.items: 112 | if role.metadata.name == name: 113 | requested_role = role 114 | break 115 | return requested_role 116 | 117 | 118 | def are_rules_contain_other_rules(source_role_name, source_rules, target_rules): 119 | is_contains = False 120 | matched_rules = 0 121 | if not (target_rules and source_rules): 122 | return is_contains 123 | for target_rule in target_rules: 124 | if source_rules is not None: 125 | for source_rule in source_rules: 126 | if is_rule_contains_risky_rule(source_role_name, source_rule, target_rule): 127 | matched_rules += 1 128 | if matched_rules == len(target_rules): 129 | is_contains = True 130 | return is_contains 131 | 132 | return is_contains 133 | 134 | 135 | def is_risky_role(role): 136 | is_risky = False 137 | priority = Priority.LOW 138 | for risky_role in STATIC_RISKY_ROLES: 139 | if are_rules_contain_other_rules(role.metadata.name, role.rules, risky_role.rules): 140 | is_risky = True 141 | priority = risky_role.priority 142 | break 143 | 144 | return is_risky, priority 145 | 146 | 147 | def find_risky_roles(roles, kind): 148 | risky_roles = [] 149 | for role in roles: 150 | is_risky, priority = is_risky_role(role) 151 | if is_risky: 152 | risky_roles.append( 153 | Role(role.metadata.name, priority, rules=role.rules, namespace=role.metadata.namespace, kind=kind, 154 | time=role.metadata.creation_timestamp)) 155 | 156 | return risky_roles 157 | 158 | 159 | def get_roles_by_kind(kind): 160 | all_roles = [] 161 | if kind == ROLE_KIND: 162 | #all_roles = api_client.RbacAuthorizationV1Api.list_role_for_all_namespaces() 163 | all_roles = Config.api_client.list_roles_for_all_namespaces() 164 | else: 165 | #all_roles = api_client.RbacAuthorizationV1Api.list_cluster_role() 166 | #all_roles = api_client.api_temp.list_cluster_role() 167 | all_roles = Config.api_client.list_cluster_role() 168 | return all_roles 169 | 170 | 171 | def get_risky_role_by_kind(kind): 172 | risky_roles = [] 173 | 174 | all_roles = get_roles_by_kind(kind) 175 | 176 | if all_roles is not None: 177 | risky_roles = find_risky_roles(all_roles.items, kind) 178 | 179 | return risky_roles 180 | 181 | 182 | def get_risky_roles_and_clusterroles(): 183 | risky_roles = get_risky_roles() 184 | risky_clusterroles = get_risky_clusterroles() 185 | 186 | # return risky_roles, risky_clusterroles 187 | all_risky_roles = risky_roles + risky_clusterroles 188 | return all_risky_roles 189 | 190 | 191 | def get_risky_roles(): 192 | return get_risky_role_by_kind('Role') 193 | 194 | 195 | def get_risky_clusterroles(): 196 | return get_risky_role_by_kind('ClusterRole') 197 | 198 | 199 | # endregion - Roles and ClusteRoles 200 | 201 | # region - RoleBindings and ClusterRoleBindings 202 | 203 | def is_risky_rolebinding(risky_roles, rolebinding): 204 | is_risky = False 205 | priority = Priority.LOW 206 | for risky_role in risky_roles: 207 | 208 | # It is also possible to add check for role kind 209 | if rolebinding.role_ref.name == risky_role.name: 210 | is_risky = True 211 | priority = risky_role.priority 212 | break 213 | 214 | return is_risky, priority 215 | 216 | 217 | def find_risky_rolebindings_or_clusterrolebindings(risky_roles, rolebindings, kind): 218 | risky_rolebindings = [] 219 | for rolebinding in rolebindings: 220 | is_risky, priority = is_risky_rolebinding(risky_roles, rolebinding) 221 | if is_risky: 222 | risky_rolebindings.append(RoleBinding(rolebinding.metadata.name, 223 | priority, 224 | namespace=rolebinding.metadata.namespace, 225 | kind=kind, subjects=rolebinding.subjects, 226 | time=rolebinding.metadata.creation_timestamp)) 227 | return risky_rolebindings 228 | 229 | 230 | def get_rolebinding_by_kind_all_namespaces(kind): 231 | all_roles = [] 232 | if kind == ROLE_BINDING_KIND: 233 | all_roles = Config.api_client.list_role_binding_for_all_namespaces() 234 | # else: 235 | # TODO: check if it was fixed 236 | # all_roles = api_client.RbacAuthorizationV1Api.list_cluster_role_binding() 237 | 238 | return all_roles 239 | 240 | 241 | def get_all_risky_rolebinding(): 242 | all_risky_roles = get_risky_roles_and_clusterroles() 243 | 244 | risky_rolebindings = get_risky_rolebindings(all_risky_roles) 245 | risky_clusterrolebindings = get_risky_clusterrolebindings(all_risky_roles) 246 | 247 | risky_rolebindings_and_clusterrolebindings = risky_clusterrolebindings + risky_rolebindings 248 | return risky_rolebindings_and_clusterrolebindings 249 | 250 | 251 | def get_risky_rolebindings(all_risky_roles=None): 252 | if all_risky_roles is None: 253 | all_risky_roles = get_risky_roles_and_clusterroles() 254 | all_rolebindings = get_rolebinding_by_kind_all_namespaces(ROLE_BINDING_KIND) 255 | risky_rolebindings = find_risky_rolebindings_or_clusterrolebindings(all_risky_roles, all_rolebindings.items, 256 | "RoleBinding") 257 | 258 | return risky_rolebindings 259 | 260 | 261 | def get_risky_clusterrolebindings(all_risky_roles=None): 262 | if all_risky_roles is None: 263 | all_risky_roles = get_risky_roles_and_clusterroles() 264 | # Cluster doesn't work. 265 | # https://github.com/kubernetes-client/python/issues/577 - when it will be solve, can remove the comments 266 | # all_clusterrolebindings = api_client.RbacAuthorizationV1Api.list_cluster_role_binding() 267 | all_clusterrolebindings = Config.api_client.list_cluster_role_binding() 268 | # risky_clusterrolebindings = find_risky_rolebindings(all_risky_roles, all_clusterrolebindings.items, "ClusterRoleBinding") 269 | risky_clusterrolebindings = find_risky_rolebindings_or_clusterrolebindings(all_risky_roles, all_clusterrolebindings, 270 | "ClusterRoleBinding") 271 | return risky_clusterrolebindings 272 | 273 | 274 | # endregion - RoleBindings and ClusterRoleBindings 275 | 276 | # region- Risky Users 277 | 278 | def get_all_risky_subjects(): 279 | all_risky_users = [] 280 | all_risky_rolebindings = get_all_risky_rolebinding() 281 | passed_users = {} 282 | for risky_rolebinding in all_risky_rolebindings: 283 | 284 | # In case 'risky_rolebinding.subjects' is 'None', 'or []' will prevent an exception. 285 | for user in risky_rolebinding.subjects or []: 286 | # Removing duplicated users 287 | if ''.join((user.kind, user.name, str(user.namespace))) not in passed_users: 288 | passed_users[''.join((user.kind, user.name, str(user.namespace)))] = True 289 | if user.namespace == None and (user.kind).lower() == "serviceaccount": 290 | user.namespace = risky_rolebinding.namespace 291 | all_risky_users.append(Subject(user, risky_rolebinding.priority)) 292 | 293 | return all_risky_users 294 | 295 | 296 | # endregion - Risky Users 297 | 298 | # region- Risky Pods 299 | 300 | ''' 301 | Example of JWT token decoded: 302 | { 303 | 'kubernetes.io/serviceaccount/service-account.uid': '11a8e2a1-6f07-11e8-8d52-000c2904e34b', 304 | 'iss': 'kubernetes/serviceaccount', 305 | 'sub': 'system:serviceaccount:default:myservice', 306 | 'kubernetes.io/serviceaccount/namespace': 'default', 307 | 'kubernetes.io/serviceaccount/secret.name': 'myservice-token-btwvr', 308 | 'kubernetes.io/serviceaccount/service-account.name': 'myservice' 309 | } 310 | ''' 311 | 312 | 313 | def pod_exec_read_token(pod, container_name, path): 314 | cat_command = 'cat ' + path 315 | exec_command = ['/bin/sh', 316 | '-c', 317 | cat_command] 318 | resp = '' 319 | try: 320 | resp = stream(api_client.CoreV1Api.connect_post_namespaced_pod_exec, pod.metadata.name, pod.metadata.namespace, 321 | command=exec_command, container=container_name, 322 | stderr=False, stdin=False, 323 | stdout=True, tty=False) 324 | except ApiException as e: 325 | print("Exception when calling api_client.CoreV1Api->connect_post_namespaced_pod_exec: %s\n" % e) 326 | print('{0}, {1}'.format(pod.metadata.name, pod.metadata.namespace)) 327 | 328 | return resp 329 | 330 | 331 | def pod_exec_read_token_two_paths(pod, container_name): 332 | result = pod_exec_read_token(pod, container_name, '/run/secrets/kubernetes.io/serviceaccount/token') 333 | if result == '': 334 | result = pod_exec_read_token(pod, container_name, '/var/run/secrets/kubernetes.io/serviceaccount/token') 335 | return result 336 | 337 | 338 | def get_jwt_token_from_container(pod, container_name): 339 | resp = pod_exec_read_token_two_paths(pod, container_name) 340 | 341 | token_body = '' 342 | if resp != '' and not resp.startswith('OCI'): 343 | from engine.jwt_token import decode_jwt_token_data 344 | decoded_data = decode_jwt_token_data(resp) 345 | if decoded_data is not None and decoded_data != '': 346 | try: 347 | token_body = json.loads(decoded_data) 348 | except json.JSONDecodeError as e: 349 | print(f"Error decoding JWT token for container {container_name} in pod {pod.metadata.name}: {e}") 350 | 351 | return token_body, resp 352 | 353 | 354 | def is_same_user(a_username, a_namespace, b_username, b_namespace): 355 | return (a_username == b_username and a_namespace == b_namespace) 356 | 357 | 358 | def get_risky_user_from_container(jwt_body, risky_users): 359 | risky_user_in_container = None 360 | 361 | service_account_info = jwt_body.get('kubernetes.io', {}).get('serviceaccount', {}) 362 | if not service_account_info: 363 | return None 364 | 365 | # Check if the service account information is present in the first structure 366 | service_account_name = service_account_info.get('name') 367 | service_account_namespace = jwt_body.get('kubernetes.io', {}).get('namespace') 368 | 369 | if not service_account_name or not service_account_namespace: 370 | # Fallback to the alternative structure (kubernetes.io/serviceaccount/...) 371 | service_account_name = jwt_body.get('kubernetes.io/serviceaccount/service-account.name') 372 | service_account_namespace = jwt_body.get('kubernetes.io/serviceaccount/namespace') 373 | 374 | if service_account_name and service_account_namespace: 375 | for risky_user in risky_users: 376 | if risky_user.user_info.kind == 'ServiceAccount': 377 | if is_same_user(service_account_name, 378 | service_account_namespace, 379 | risky_user.user_info.name, 380 | risky_user.user_info.namespace): 381 | risky_user_in_container = risky_user 382 | break 383 | 384 | return risky_user_in_container 385 | 386 | 387 | 388 | def get_risky_containers(pod, risky_users, read_token_from_container=False): 389 | risky_containers = [] 390 | if read_token_from_container: 391 | # Skipping terminated and evicted pods 392 | # This will run only on the containers with the "ready" status 393 | if pod.status.container_statuses: 394 | for container in pod.status.container_statuses: 395 | if container.ready and container.state.running: 396 | jwt_body, _ = get_jwt_token_from_container(pod, container.name) 397 | if jwt_body: 398 | risky_user = get_risky_user_from_container(jwt_body, risky_users) 399 | if risky_user: 400 | risky_containers.append( 401 | Container( 402 | container.name, 403 | risky_user.user_info.name, 404 | risky_user.user_info.namespace, 405 | set() if risky_user is None else {risky_user}, 406 | risky_user.priority 407 | ) 408 | ) 409 | 410 | else: 411 | # A dictionary for the volume 412 | volumes_dict = {} 413 | for volume in pod.spec.volumes or []: 414 | volumes_dict[volume.name] = volume 415 | for container in pod.spec.containers: 416 | risky_users_set = get_risky_users_from_container(container, risky_users, pod, volumes_dict) 417 | if not container_exists_in_risky_containers(risky_containers, container.name, 418 | risky_users_set): 419 | if len(risky_users_set) > 0: 420 | priority = get_highest_priority(risky_users_set) 421 | risky_containers.append( 422 | Container(container.name, None, pod.metadata.namespace, risky_users_set, 423 | priority)) 424 | return risky_containers 425 | 426 | 427 | # Get the highest priority user in the list 428 | def get_highest_priority(risky_users_list): 429 | highest_priority = Priority.NONE 430 | for user in risky_users_list: 431 | if user.priority.value > highest_priority.value: 432 | highest_priority = user.priority 433 | return highest_priority 434 | 435 | 436 | def get_risky_users_from_container(container, risky_users, pod, volumes_dict): 437 | risky_users_set = set() 438 | # '[]' for checking if 'container.volume_mounts' is None 439 | for volume_mount in container.volume_mounts or []: 440 | if volume_mount.name in volumes_dict: 441 | if volumes_dict[volume_mount.name].projected is not None: 442 | for source in volumes_dict[volume_mount.name].projected.sources or []: 443 | if source.service_account_token is not None: 444 | risky_user = is_user_risky(risky_users, pod.spec.service_account, pod.metadata.namespace) 445 | if risky_user is not None: 446 | risky_users_set.add(risky_user) 447 | elif volumes_dict[volume_mount.name].secret is not None: 448 | risky_user = get_jwt_and_decode(pod, risky_users, volumes_dict[volume_mount.name]) 449 | if risky_user is not None: 450 | risky_users_set.add(risky_user) 451 | return risky_users_set 452 | 453 | 454 | 455 | def container_exists_in_risky_containers(risky_containers, container_name, risky_users_list): 456 | for risky_container in risky_containers: 457 | if risky_container.name == container_name: 458 | for user_name in risky_users_list: 459 | risky_container.service_account_name.append(user_name) 460 | return True 461 | return False 462 | 463 | 464 | def default_path_exists(volume_mounts): 465 | for volume_mount in volume_mounts: 466 | if volume_mount.mount_path == "/var/run/secrets/kubernetes.io/serviceaccount": 467 | return True 468 | return False 469 | 470 | 471 | def is_user_risky(risky_users, service_account, namespace): 472 | for risky_user in risky_users: 473 | if risky_user.user_info.name == service_account and risky_user.user_info.namespace == namespace: 474 | return risky_user 475 | return None 476 | 477 | 478 | def get_jwt_and_decode(pod, risky_users, volume): 479 | from engine.jwt_token import decode_base64_jwt_token 480 | try: 481 | secret = api_client.CoreV1Api.read_namespaced_secret(name=volume.secret.secret_name, 482 | namespace=pod.metadata.namespace) 483 | except Exception: 484 | secret = None 485 | try: 486 | if secret is not None and secret.data is not None: 487 | if 'token' in secret.data: 488 | decoded_data = decode_base64_jwt_token(secret.data['token']) 489 | token_body = json.loads(decoded_data) 490 | if token_body: 491 | risky_user = get_risky_user_from_container(token_body, risky_users) 492 | return risky_user 493 | raise Exception() 494 | except Exception: 495 | if secret is not None: 496 | return get_risky_user_from_container_secret(secret, risky_users) 497 | 498 | def get_risky_user_from_container_secret(secret, risky_users): 499 | if secret is not None: 500 | global list_of_service_accounts 501 | if not list_of_service_accounts: 502 | list_of_service_accounts = api_client.CoreV1Api.list_service_account_for_all_namespaces() 503 | for sa in list_of_service_accounts.items: 504 | for service_account_secret in sa.secrets or []: 505 | if secret.metadata.name == service_account_secret.name: 506 | for risky_user in risky_users: 507 | if risky_user.user_info.name == sa.metadata.name: 508 | return risky_user 509 | 510 | def get_risky_pods(namespace=None, deep_analysis=False): 511 | risky_pods = [] 512 | pods = list_pods_for_all_namespaces_or_one_namspace(namespace) 513 | risky_users = get_all_risky_subjects() 514 | for pod in pods.items: 515 | risky_containers = get_risky_containers(pod, risky_users, deep_analysis) 516 | if len(risky_containers) > 0: 517 | risky_pods.append(Pod(pod.metadata.name, pod.metadata.namespace, risky_containers)) 518 | 519 | return risky_pods 520 | 521 | 522 | # endregion- Risky Pods 523 | 524 | def get_rolebindings_all_namespaces_and_clusterrolebindings(): 525 | namespaced_rolebindings = Config.api_client.list_role_binding_for_all_namespaces() 526 | 527 | # TODO: check when this bug will be fixed 528 | # cluster_rolebindings = api_client.RbacAuthorizationV1Api.list_cluster_role_binding() 529 | # cluster_rolebindings = api_client.api_temp.list_cluster_role_binding() 530 | cluster_rolebindings = Config.api_client.list_cluster_role_binding() 531 | return namespaced_rolebindings, cluster_rolebindings 532 | 533 | 534 | def get_rolebindings_and_clusterrolebindings_associated_to_subject(subject_name, kind, namespace): 535 | rolebindings_all_namespaces, cluster_rolebindings = get_rolebindings_all_namespaces_and_clusterrolebindings() 536 | associated_rolebindings = [] 537 | 538 | for rolebinding in rolebindings_all_namespaces.items: 539 | # In case 'rolebinding.subjects' is 'None', 'or []' will prevent an exception. 540 | for subject in rolebinding.subjects or []: 541 | if subject.name.lower() == subject_name.lower() and subject.kind.lower() == kind.lower(): 542 | if kind == SERVICEACCOUNT_KIND: 543 | if subject.namespace.lower() == namespace.lower(): 544 | associated_rolebindings.append(rolebinding) 545 | else: 546 | associated_rolebindings.append(rolebinding) 547 | 548 | associated_clusterrolebindings = [] 549 | for clusterrolebinding in cluster_rolebindings: 550 | 551 | # In case 'clusterrolebinding.subjects' is 'None', 'or []' will prevent an exception. 552 | for subject in clusterrolebinding.subjects or []: 553 | if subject.name == subject_name.lower() and subject.kind.lower() == kind.lower(): 554 | if kind == SERVICEACCOUNT_KIND: 555 | if subject.namespace.lower() == namespace.lower(): 556 | associated_clusterrolebindings.append(clusterrolebinding) 557 | else: 558 | associated_clusterrolebindings.append(clusterrolebinding) 559 | 560 | return associated_rolebindings, associated_clusterrolebindings 561 | 562 | 563 | # Role can be only inside RoleBinding 564 | def get_rolebindings_associated_to_role(role_name, namespace): 565 | rolebindings_all_namespaces = Config.api_client.list_role_binding_for_all_namespaces() 566 | associated_rolebindings = [] 567 | 568 | for rolebinding in rolebindings_all_namespaces.items: 569 | if rolebinding.role_ref.name.lower() == role_name.lower() and rolebinding.role_ref.kind == ROLE_KIND and rolebinding.metadata.namespace.lower() == namespace.lower(): 570 | associated_rolebindings.append(rolebinding) 571 | 572 | return associated_rolebindings 573 | 574 | 575 | def get_rolebindings_and_clusterrolebindings_associated_to_clusterrole(role_name): 576 | rolebindings_all_namespaces, cluster_rolebindings = get_rolebindings_all_namespaces_and_clusterrolebindings() 577 | 578 | associated_rolebindings = [] 579 | 580 | for rolebinding in rolebindings_all_namespaces.items: 581 | if rolebinding.role_ref.name.lower() == role_name.lower() and rolebinding.role_ref.kind == CLUSTER_ROLE_KIND: 582 | associated_rolebindings.append(rolebinding) 583 | 584 | associated_clusterrolebindings = [] 585 | 586 | # for clusterrolebinding in cluster_rolebindings.items: 587 | for clusterrolebinding in cluster_rolebindings: 588 | if clusterrolebinding.role_ref.name.lower() == role_name.lower() and clusterrolebinding.role_ref.kind == CLUSTER_ROLE_KIND: 589 | associated_rolebindings.append(clusterrolebinding) 590 | 591 | return associated_rolebindings, associated_clusterrolebindings 592 | 593 | 594 | def dump_containers_tokens_by_pod(pod_name, namespace, read_token_from_container=False): 595 | containers_with_tokens = [] 596 | try: 597 | pod = api_client.CoreV1Api.read_namespaced_pod(name=pod_name, namespace=namespace) 598 | except ApiException: 599 | print(pod_name + " was not found in " + namespace + " namespace") 600 | return None 601 | if read_token_from_container: 602 | if pod.status.container_statuses: 603 | for container in pod.status.container_statuses: 604 | if container.ready: 605 | jwt_body, raw_jwt_token = get_jwt_token_from_container(pod, container.name) 606 | if jwt_body: 607 | containers_with_tokens.append( 608 | Container(container.name, token=jwt_body, raw_jwt_token=raw_jwt_token)) 609 | 610 | else: 611 | fill_container_with_tokens_list(containers_with_tokens, pod) 612 | return containers_with_tokens 613 | 614 | 615 | def fill_container_with_tokens_list(containers_with_tokens, pod): 616 | from engine.jwt_token import decode_base64_jwt_token 617 | for container in pod.spec.containers: 618 | for volume_mount in container.volume_mounts or []: 619 | for volume in pod.spec.volumes or []: 620 | if volume.name == volume_mount.name and volume.secret: 621 | try: 622 | secret = api_client.CoreV1Api.read_namespaced_secret(volume.secret.secret_name, 623 | pod.metadata.namespace) 624 | if secret and secret.data and secret.data['token']: 625 | decoded_data = decode_base64_jwt_token(secret.data['token']) 626 | token_body = json.loads(decoded_data) 627 | containers_with_tokens.append(Container(container.name, token=token_body, 628 | raw_jwt_token=None)) 629 | except ApiException: 630 | print("No secret found.") 631 | 632 | 633 | def dump_all_pods_tokens_or_by_namespace(namespace=None, read_token_from_container=False): 634 | pods_with_tokens = [] 635 | pods = list_pods_for_all_namespaces_or_one_namspace(namespace) 636 | for pod in pods.items: 637 | containers = dump_containers_tokens_by_pod(pod.metadata.name, pod.metadata.namespace, read_token_from_container) 638 | if containers is not None: 639 | pods_with_tokens.append(Pod(pod.metadata.name, pod.metadata.namespace, containers)) 640 | 641 | return pods_with_tokens 642 | 643 | 644 | def dump_pod_tokens(name, namespace, read_token_from_container=False): 645 | pod_with_tokens = [] 646 | containers = dump_containers_tokens_by_pod(name, namespace, read_token_from_container) 647 | pod_with_tokens.append(Pod(name, namespace, containers)) 648 | 649 | return pod_with_tokens 650 | 651 | 652 | def search_subject_in_subjects_by_kind(subjects, kind): 653 | subjects_found = [] 654 | for subject in subjects: 655 | if subject.kind.lower() == kind.lower(): 656 | subjects_found.append(subject) 657 | return subjects_found 658 | 659 | 660 | # It get subjects by kind for all rolebindings. 661 | def get_subjects_by_kind(kind): 662 | subjects_found = [] 663 | rolebindings = Config.api_client.list_role_binding_for_all_namespaces() 664 | clusterrolebindings = Config.api_client.list_cluster_role_binding() 665 | for rolebinding in rolebindings.items: 666 | if rolebinding.subjects is not None: 667 | subjects_found += search_subject_in_subjects_by_kind(rolebinding.subjects, kind) 668 | 669 | for clusterrolebinding in clusterrolebindings: 670 | if clusterrolebinding.subjects is not None: 671 | subjects_found += search_subject_in_subjects_by_kind(clusterrolebinding.subjects, kind) 672 | 673 | return remove_duplicated_subjects(subjects_found) 674 | 675 | 676 | def remove_duplicated_subjects(subjects): 677 | seen_subjects = set() 678 | new_subjects = [] 679 | for s1 in subjects: 680 | if s1.namespace == None: 681 | s1_unique_name = ''.join([s1.name, s1.kind]) 682 | else: 683 | s1_unique_name = ''.join([s1.name, s1.namespace, s1.kind]) 684 | if s1_unique_name not in seen_subjects: 685 | new_subjects.append(s1) 686 | seen_subjects.add(s1_unique_name) 687 | 688 | return new_subjects 689 | 690 | 691 | def get_rolebinding_role(rolebinding_name, namespace): 692 | rolebinding = None 693 | role = None 694 | try: 695 | rolebinding = Config.api_client.read_namespaced_role_binding(rolebinding_name, namespace) 696 | if rolebinding.role_ref.kind == ROLE_KIND: 697 | role = Config.api_client.read_namespaced_role(rolebinding.role_ref.name, 698 | rolebinding.metadata.namespace) 699 | else: 700 | role = Config.api_client.read_cluster_role(rolebinding.role_ref.name) 701 | 702 | return role 703 | except ApiException: 704 | if rolebinding is None: 705 | print("Could not find " + rolebinding_name + " rolebinding in " + namespace + " namespace") 706 | elif role is None: 707 | print( 708 | "Could not find " + rolebinding.role_ref.name + " role in " + rolebinding.role_ref.name + " rolebinding") 709 | return None 710 | 711 | 712 | def get_clusterrolebinding_role(cluster_rolebinding_name): 713 | cluster_role = '' 714 | try: 715 | cluster_rolebinding = api_client.RbacAuthorizationV1Api.read_cluster_role_binding(cluster_rolebinding_name) 716 | cluster_role = api_client.RbacAuthorizationV1Api.read_cluster_role(cluster_rolebinding.role_ref.name) 717 | except ApiException as e: 718 | print(e) 719 | exit() 720 | 721 | return cluster_role 722 | 723 | 724 | def get_roles_associated_to_subject(subject_name, kind, namespace): 725 | associated_rolebindings, associated_clusterrolebindings = get_rolebindings_and_clusterrolebindings_associated_to_subject( 726 | subject_name, kind, namespace) 727 | 728 | associated_roles = [] 729 | for rolebind in associated_rolebindings: 730 | try: 731 | role = get_rolebinding_role(rolebind.metadata.name, rolebind.metadata.namespace) 732 | associated_roles.append(role) 733 | except ApiException as e: 734 | # 404 not found 735 | continue 736 | 737 | for clusterrolebinding in associated_clusterrolebindings: 738 | role = get_clusterrolebinding_role(clusterrolebinding.metadata.name) 739 | associated_roles.append(role) 740 | 741 | return associated_roles 742 | 743 | 744 | def list_pods_for_all_namespaces_or_one_namspace(namespace=None): 745 | try: 746 | if namespace is None: 747 | pods = Config.api_client.list_pod_for_all_namespaces(watch=False) 748 | else: 749 | pods = Config.api_client.list_namespaced_pod(namespace) 750 | return pods 751 | except ApiException: 752 | return None 753 | 754 | 755 | # https://:/api/v1/namespaces/kube-system/secrets?fieldSelector=type=bootstrap.kubernetes.io/token 756 | def list_boostrap_tokens_decoded(): 757 | tokens = [] 758 | secrets = api_client.CoreV1Api.list_namespaced_secret(namespace='kube-system', 759 | field_selector='type=bootstrap.kubernetes.io/token') 760 | import base64 761 | 762 | for secret in secrets.items: 763 | tokens.append('.'.join((base64.b64decode(secret.data['token-id']).decode('utf-8'), 764 | base64.b64decode(secret.data['token-secret']).decode('utf-8')))) 765 | 766 | return tokens 767 | -------------------------------------------------------------------------------- /examples/examples.txt: -------------------------------------------------------------------------------- 1 | 2 | Use 'python3 /KubiScan.py' or run alias kubiscan='python3 /KubiScan.py' and use 'kubiscan' to run. 3 | 4 | # Get all risky Roles 5 | python3 KubiScan.py --risky-roles 6 | python3 KubiScan.py -rr 7 | # all risky roles exist less than 100 days 8 | python3 KubiScan.py -rr -lt 100 9 | 10 | # With rules 11 | python3 KubiScan.py -rr -r 12 | 13 | # From remote 14 | # kubiscan -ho -t -c -rr 15 | SERVICE_TOKEN_FILENAME="/var/run/secrets/kubernetes.io/serviceaccount/token" 16 | SERVICE_CERT_FILENAME="/var/run/secrets/kubernetes.io/serviceaccount/ca.crt" 17 | kubiscan -ho 192.168.190.143:8443 -t $SERVICE_TOKEN_FILENAME -c $SERVICE_CERT_FILENAME -rr 18 | It is possible to use only the token (without the certificate) and the SSL communication won't be verified: 19 | kubiscan -ho 192.168.190.143:8443 -t $SERVICE_TOKEN_FILENAME -rr 20 | 21 | # Get all risky ClusterRoles 22 | python3 KubiScan.py --risky-clusterroles 23 | python3 KubiScan.py -rcr 24 | python3 KubiScan.py -rcr -lt 100 25 | 26 | # With Rules 27 | python3 KubiScan.py -rcr -r 28 | 29 | # Get all risky Roles and ClusterRoles 30 | python3 KubiScan.py --risky-any-roles 31 | python3 KubiScan.py -rar 32 | python3 KubiScan.py -rar -lt 100 33 | 34 | # Get all risky RoleBindings 35 | python3 KubiScan.py --risky-rolebindings 36 | python3 KubiScan.py -rb 37 | python3 KubiScan.py -rb -lt 100 38 | 39 | # Get all risky ClusterRoleBindings 40 | python3 KubiScan.py --risky-clusterrolebindings 41 | python3 KubiScan.py -rcb 42 | python3 KubiScan.py -rcb -lt 100 43 | 44 | # Get all risky RoleBindings and ClusterRoleBindings 45 | python3 KubiScan.py --risky-any-rolebindings 46 | python3 KubiScan.py -rab 47 | python3 KubiScan.py -rab -lt 100 48 | 49 | # Get all risky Subjects (Users, Groups or Service Accounts) 50 | python3 KubiScan.py --risky-subjects 51 | python3 KubiScan.py -rs 52 | 53 | # Get all risky Pods\Containers 54 | python3 KubiScan.py --risky-pods 55 | python3 KubiScan.py -rp 56 | 57 | # Get all risky Roles\ClusterRoles, RoleBindings\ClusterRoleBindings, users and pods\containers 58 | python3 KubiScan.py --all 59 | python3 KubiScan.py -a 60 | python3 KubiScan.py -a -lt 100 61 | 62 | # Dump tokens from pod\pods 63 | python3 KubiScan.py --dump-tokens 64 | python3 KubiScan.py -dt 65 | python3 KubiScan.py -dt -ns "kube-system" 66 | python3 KubiScan.py -dt -n "nginx1" -ns "kube-system" 67 | 68 | # Get associated RoleBindings\ClusterRoleBindings to a specific Role 69 | python3 KubiScan.py --associated-any-rolebindings-role "system:controller:token-cleaner" -ns "kube-system" 70 | python3 KubiScan.py -aarbr "system:controller:token-cleaner" -ns "kube-system" 71 | 72 | # Get associated RoleBindings\ClusterRoleBindings to a specific ClusterRole 73 | python3 KubiScan.py --associated-any-rolebindings-clusterrole "cluster-admin" 74 | python3 KubiScan.py -aarbcr "cluster-admin" 75 | 76 | # Get associated RoleBindings\ClusterRoleBindings to a specific Subject (user, group or service account) 77 | python3 KubiScan.py --associated-any-rolebindings-subject "system:masters" -k "Group" 78 | python3 KubiScan.py -aarbs "system:masters" -k "Group" 79 | 80 | # Get associated Roles\ClusterRoles to a specific Subject (user, group or service account) 81 | python3 KubiScan.py --associated-any-roles-subject "generic-garbage-collector" -k "ServiceAccount" -ns "kube-system" 82 | python3 KubiScan.py -aars "generic-garbage-collector" -k "ServiceAccount" -ns "kube-system" 83 | 84 | python3 KubiScan.py -aars "system:authenticated" -k "Group" 85 | 86 | # List Subject (kind=Users) 87 | python3 KubiScan.py --subject-users 88 | python3 KubiScan.py -su 89 | 90 | # List Subject (kind=Groups) 91 | python3 KubiScan.py --subject-groups 92 | python3 KubiScan.py -sg 93 | 94 | # List Subject (kind=ServiceAccounts) 95 | python3 KubiScan.py --subject-serviceaccounts 96 | python3 KubiScan.py -ss 97 | 98 | # List rules of RoleBinding 99 | python3 KubiScan.py --rolebinding-rules "system:controller:token-cleaner" -ns "kube-system" 100 | python3 KubiScan.py -rru "system:controller:token-cleaner" -ns "kube-system" 101 | 102 | # List rules of ClusterRoleBinding 103 | python3 KubiScan.py --clusterrolebinding-rules -crru "cluster-admin" 104 | python3 KubiScan.py -crru "cluster-admin" 105 | 106 | # Show Pods that has access to the secret data through a Volume 107 | python3 KubiScan.py --pods-secrets-volume 108 | python3 KubiScan.py -psv 109 | python3 KubiScan.py -psv -ns "kube-system" 110 | 111 | # Show Pods that has access to the secret data through environment variables 112 | python3 KubiScan.py --pods-secrets-env 113 | python3 KubiScan.py -pse 114 | python3 KubiScan.py -pse -ns "kube-system" 115 | 116 | # Get all risky Subjects and export to json 117 | python3 KubiScan.py -rs -j risky_subjects.json 118 | 119 | # Get all risky Subjects, printing it to a file with no logo and no color 120 | python3 KubiScan.py -rs -o risky_subjects_table -nc 121 | 122 | -------------------------------------------------------------------------------- /misc/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/cyberark/KubiScan/ade56e6762eb88db588d601860e38b339f2e7543/misc/__init__.py -------------------------------------------------------------------------------- /misc/colours.py: -------------------------------------------------------------------------------- 1 | 2 | # It is possible to use colorama module but it will require to install this module 3 | ''' 4 | \033[ Escape code, this is always the same 5 | 0 = Style, 0 for normal. 6 | 32 = Text colour, 32 for bright green. 7 | 40m = Background colour, 40 is for black. 8 | 9 | 10 | TEXT COLOUR CODE TEXT STYLE CODE BACKGROUND COLOUR CODE 11 | Black 30 No effect 0 Black 40 12 | Red 31 Bold 1 Red 41 13 | Green 32 Underline 2 Green 42 14 | Yellow 33 Negative1 3 Yellow 43 15 | Blue 34 Negative2 5 Blue 44 16 | Purple 35 Purple 45 17 | Cyan 36 Cyan 46 18 | White 37 White 47 19 | ''' 20 | 21 | 22 | RED = '\033[0;31;49m' 23 | LIGHTRED = '\033[0;91;49m' 24 | YELLOW = '\033[0;33;49m' 25 | LIGHTYELLOW = '\033[0;93;49m' 26 | 27 | WHITE = '\033[0;47;49m' 28 | 29 | """Provide RGB color constants and a colors dictionary with 30 | elements formatted: colors[colorname] = CONSTANT""" 31 | 32 | from collections import namedtuple, OrderedDict 33 | 34 | Color = namedtuple('RGB', 'red, green, blue') 35 | colors = {} # dict of colors 36 | 37 | 38 | class RGB(Color): 39 | def hex_format(self): 40 | '''Returns color in hex format''' 41 | return '#{:02X}{:02X}{:02X}'.format(self.red, self.green, self.blue) 42 | 43 | 44 | RED1 = RGB(255, 0, 0) 45 | RED2 = RGB(238, 0, 0) 46 | RED3 = RGB(205, 0, 0) 47 | RED4 = RGB(139, 0, 0) 48 | 49 | colors['red1'] = RED1 50 | colors['red2'] = RED2 51 | colors['red3'] = RED3 52 | colors['red4'] = RED4 53 | 54 | colors = OrderedDict(sorted(colors.items(), key=lambda t: t[0])) 55 | -------------------------------------------------------------------------------- /misc/constants.py: -------------------------------------------------------------------------------- 1 | RISKY_NAMESPACE = 'risky-namespace' 2 | ROLE_KIND = 'Role' 3 | CLUSTER_ROLE_KIND = 'ClusterRole' 4 | ROLE_BINDING_KIND = 'RoleBinding' 5 | CLUSTER_ROLE_BINDING_KIND = 'ClusterRoleBinding' 6 | USER_KIND = 'User' 7 | GROUP_KIND = 'Group' 8 | SERVICEACCOUNT_KIND = 'ServiceAccount' 9 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | kubernetes==11.0.0 2 | PTable==0.9.2 3 | -------------------------------------------------------------------------------- /risky_roles.yaml: -------------------------------------------------------------------------------- 1 | 2 | 3 | ######################### REGION - Risky permissions combinations ######################### 4 | 5 | # The order is important ! 6 | 7 | ######################### REGION - CRITICAL Roles ######################### 8 | 9 | # Risk: Viewing specific secrets 10 | # Verb: get 11 | # Resources: secrets 12 | # Example: kubectl get secrets 13 | 14 | items: 15 | 16 | - kind: Role 17 | metadata: 18 | namespace: default 19 | name: risky-get-secrets 20 | priority: CRITICAL 21 | rules: 22 | - apiGroups: ["*"] 23 | resources: ["secrets"] 24 | verbs: ["get"] 25 | 26 | # Risk: Viewing all secrets 27 | # Verb: list 28 | # Resources: secrets 29 | # Example: kubectl get secrets -o yaml 30 | 31 | - kind: Role 32 | metadata: 33 | namespace: default 34 | name: risky-list-secrets 35 | priority: CRITICAL 36 | rules: 37 | - apiGroups: ["*"] 38 | resources: ["secrets"] 39 | verbs: ["list"] 40 | 41 | # Risk: Impersonate privileged groups (like "system:masters") 42 | # Verb: list 43 | # Resources: secrets 44 | # Example: kubectl get secrets -o yaml 45 | - kind: Role 46 | metadata: 47 | namespace: default 48 | name: risky-impersonate-groups 49 | priority: CRITICAL 50 | rules: 51 | - apiGroups: ["*"] 52 | resources: ["groups"] 53 | verbs: ["impersonate"] 54 | 55 | ######################### REGION - Any Any Roles ######################### 56 | 57 | - kind: Role 58 | metadata: 59 | namespace: default 60 | name: risky-any-verb 61 | priority: CRITICAL 62 | rules: 63 | - apiGroups: ["*"] 64 | resources: ["*"] 65 | verbs: ["*"] 66 | 67 | ######################### END REGION - Any Any Roles ######################### 68 | 69 | ######################### REGION - Any verb Roles ######################### 70 | 71 | - kind: Role 72 | metadata: 73 | namespace: default 74 | name: risky-any-verb-secrets 75 | priority: CRITICAL 76 | rules: 77 | - apiGroups: ["*"] 78 | resources: ["secrets"] 79 | verbs: ["*"] 80 | 81 | - kind: Role 82 | metadata: 83 | namespace: default 84 | name: risky-any-verb-pods 85 | priority: CRITICAL 86 | rules: 87 | - apiGroups: ["*"] 88 | resources: ["pods"] 89 | verbs: ["*"] 90 | 91 | - kind: Role 92 | metadata: 93 | namespace: default 94 | name: risky-any-verb-deployments 95 | priority: CRITICAL 96 | rules: 97 | - apiGroups: ["*"] 98 | resources: ["deployments"] 99 | verbs: ["*"] 100 | 101 | - kind: Role 102 | metadata: 103 | namespace: default 104 | name: risky-any-verb-daemonsets 105 | priority: CRITICAL 106 | rules: 107 | - apiGroups: ["*"] 108 | resources: ["daemonsets"] 109 | verbs: ["*"] 110 | 111 | - kind: Role 112 | metadata: 113 | namespace: default 114 | name: risky-any-verb-statefulsets 115 | priority: CRITICAL 116 | rules: 117 | - apiGroups: ["*"] 118 | resources: ["statefulsets"] 119 | verbs: ["*"] 120 | 121 | - kind: Role 122 | metadata: 123 | namespace: default 124 | name: risky-any-verb-replicationcontrollers 125 | priority: CRITICAL 126 | rules: 127 | - apiGroups: ["*"] 128 | resources: ["replicationcontrollers"] 129 | verbs: ["*"] 130 | 131 | - kind: Role 132 | metadata: 133 | namespace: default 134 | name: risky-any-verb-replicasets 135 | priority: CRITICAL 136 | rules: 137 | - apiGroups: ["*"] 138 | resources: ["replicasets"] 139 | verbs: ["*"] 140 | 141 | - kind: Role 142 | metadata: 143 | namespace: default 144 | name: risky-any-verb-cronjobs 145 | priority: CRITICAL 146 | rules: 147 | - apiGroups: ["*"] 148 | resources: ["cronjobs"] 149 | verbs: ["*"] 150 | 151 | - kind: Role 152 | metadata: 153 | namespace: default 154 | name: risky-any-verb-jobs 155 | priority: CRITICAL 156 | rules: 157 | - apiGroups: ["*"] 158 | resources: ["jobs"] 159 | verbs: ["*"] 160 | 161 | - kind: Role 162 | metadata: 163 | namespace: default 164 | name: risky-any-verb-roles 165 | priority: CRITICAL 166 | rules: 167 | - apiGroups: ["*"] 168 | resources: ["roles"] 169 | verbs: ["*"] 170 | 171 | - kind: Role 172 | metadata: 173 | namespace: default 174 | name: risky-any-verb-clusterroles 175 | priority: CRITICAL 176 | rules: 177 | - apiGroups: ["*"] 178 | resources: ["clusterroles"] 179 | verbs: ["*"] 180 | 181 | - kind: Role 182 | metadata: 183 | namespace: default 184 | name: risky-any-verb-rolebindings 185 | priority: CRITICAL 186 | rules: 187 | - apiGroups: ["*"] 188 | resources: ["rolebindings"] 189 | verbs: ["*"] 190 | 191 | - kind: Role 192 | metadata: 193 | namespace: default 194 | name: risky-any-verb-clusterrolebindings 195 | priority: CRITICAL 196 | rules: 197 | - apiGroups: ["*"] 198 | resources: ["clusterrolebindings"] 199 | verbs: ["*"] 200 | 201 | - kind: Role 202 | metadata: 203 | namespace: default 204 | name: risky-any-verb-users 205 | priority: CRITICAL 206 | rules: 207 | - apiGroups: ["*"] 208 | resources: ["users"] 209 | verbs: ["*"] 210 | 211 | - kind: Role 212 | metadata: 213 | namespace: default 214 | name: risky-any-verb-groups 215 | priority: CRITICAL 216 | rules: 217 | - apiGroups: ["*"] 218 | resources: ["groups"] 219 | verbs: ["*"] 220 | 221 | ######################### END REGION - Any verb Roles ######################### 222 | 223 | 224 | ######################### REGION - Any resource Roles ######################### 225 | - kind: Role 226 | metadata: 227 | namespace: default 228 | name: risky-any-resource-delete 229 | priority: CRITICAL 230 | rules: 231 | - apiGroups: ["*"] 232 | resources: ["*"] 233 | verbs: ["delete"] 234 | 235 | - kind: Role 236 | metadata: 237 | namespace: default 238 | name: risky-any-resource-delete 239 | priority: CRITICAL 240 | rules: 241 | - apiGroups: ["*"] 242 | resources: ["*"] 243 | verbs: ["deletecollection"] 244 | 245 | - kind: Role 246 | metadata: 247 | namespace: default 248 | name: risky-any-resource-create 249 | priority: CRITICAL 250 | rules: 251 | - apiGroups: ["*"] 252 | resources: ["*"] 253 | verbs: ["create"] 254 | 255 | - kind: Role 256 | metadata: 257 | namespace: default 258 | name: risky-any-resource-list 259 | priority: CRITICAL 260 | rules: 261 | - apiGroups: ["*"] 262 | resources: ["*"] 263 | verbs: ["list"] 264 | 265 | - kind: Role 266 | metadata: 267 | namespace: default 268 | name: risky-any-resource-get 269 | priority: CRITICAL 270 | rules: 271 | - apiGroups: ["*"] 272 | resources: ["*"] 273 | verbs: ["get"] 274 | 275 | - kind: Role 276 | metadata: 277 | namespace: default 278 | name: risky-any-resource-impersonate 279 | priority: CRITICAL 280 | rules: 281 | - apiGroups: ["*"] 282 | resources: ["*"] 283 | verbs: ["impersonate"] 284 | 285 | ######################### END REGION - Any resource Roles ######################### 286 | 287 | 288 | ######################### END REGION - CRITICAL Roles ######################### 289 | 290 | ######################### REGION - HIGH Roles ######################### 291 | 292 | # Risk: Privilege Escalation from Node/Proxy 293 | # Verb: get, create 294 | # Resources: nodes/proxy 295 | 296 | - kind: Role 297 | metadata: 298 | namespace: default 299 | name: risky-execute-command-node-proxy 300 | priority: HIGH 301 | rules: 302 | - apiGroups: ["*"] 303 | resources: ["nodes/proxy"] 304 | verbs: ["get", "create"] 305 | 306 | # Risk: Allowing to create a malicious pod 307 | # Verb: create 308 | # Resources: deployments 309 | 310 | - kind: Role 311 | metadata: 312 | namespace: default 313 | name: risky-create-deployments 314 | priority: HIGH 315 | rules: 316 | - apiGroups: ["*"] 317 | resources: ["deployments"] 318 | verbs: ["create"] 319 | 320 | # Risk: Allowing to update a malicious pod 321 | # Verb: update 322 | # Resources: deployments 323 | 324 | - kind: Role 325 | metadata: 326 | namespace: default 327 | name: risky-update-deployments 328 | priority: HIGH 329 | rules: 330 | - apiGroups: ["*"] 331 | resources: ["deployments"] 332 | verbs: ["update"] 333 | 334 | # Risk: Allowing to create a malicious pod 335 | # Verb: create 336 | # Resources: daemonsets 337 | 338 | - kind: Role 339 | metadata: 340 | namespace: default 341 | name: risky-create-daemonsets 342 | priority: HIGH 343 | rules: 344 | - apiGroups: ["*"] 345 | resources: ["daemonsets"] 346 | verbs: ["create"] 347 | 348 | # Risk: Allowing to update a malicious pod 349 | # Verb: update 350 | # Resources: daemonsets 351 | 352 | - kind: Role 353 | metadata: 354 | namespace: default 355 | name: risky-update-daemonsets 356 | priority: HIGH 357 | rules: 358 | - apiGroups: ["*"] 359 | resources: ["daemonsets"] 360 | verbs: ["update"] 361 | 362 | # Risk: Allowing to create a malicious pod 363 | # Verb: create 364 | # Resources: statefulsets 365 | 366 | - kind: Role 367 | metadata: 368 | namespace: default 369 | name: risky-create-statefulsets 370 | priority: HIGH 371 | rules: 372 | - apiGroups: ["*"] 373 | resources: ["statefulsets"] 374 | verbs: ["create"] 375 | 376 | # Risk: Allowing to update a malicious pod 377 | # Verb: update 378 | # Resources: statefulsets 379 | 380 | - kind: Role 381 | metadata: 382 | namespace: default 383 | name: risky-update-statefulsets 384 | priority: HIGH 385 | rules: 386 | - apiGroups: ["*"] 387 | resources: ["statefulsets"] 388 | verbs: ["update"] 389 | 390 | # Risk: Allowing to create a malicious pod 391 | # Verb: create 392 | # Resources: replicationcontrollers 393 | 394 | - kind: Role 395 | metadata: 396 | namespace: default 397 | name: risky-create-replicationcontrollers 398 | priority: HIGH 399 | rules: 400 | - apiGroups: ["*"] 401 | resources: ["replicationcontrollers"] 402 | verbs: ["create"] 403 | 404 | # Risk: Allowing to update a malicious pod 405 | # Verb: update 406 | # Resources: replicationcontrollers 407 | 408 | - kind: Role 409 | metadata: 410 | namespace: default 411 | name: risky-update-replicationcontrollers 412 | priority: HIGH 413 | rules: 414 | - apiGroups: ["*"] 415 | resources: ["replicationcontrollers"] 416 | verbs: ["update"] 417 | 418 | # Risk: Allowing to create a malicious pod 419 | # Verb: create 420 | # Resources: replicasets 421 | 422 | - kind: Role 423 | metadata: 424 | namespace: default 425 | name: risky-create-replicasets 426 | priority: HIGH 427 | rules: 428 | - apiGroups: ["*"] 429 | resources: ["replicasets"] 430 | verbs: ["create"] 431 | 432 | # Risk: Allowing to update a malicious pod 433 | # Verb: update 434 | # Resources: replicasets 435 | 436 | - kind: Role 437 | metadata: 438 | namespace: default 439 | name: risky-update-replicasets 440 | priority: HIGH 441 | rules: 442 | - apiGroups: ["*"] 443 | resources: ["replicasets"] 444 | verbs: ["update"] 445 | 446 | # Risk: Allowing to create a malicious pod 447 | # Verb: create 448 | # Resources: jobs 449 | 450 | - kind: Role 451 | metadata: 452 | namespace: default 453 | name: risky-create-jobs 454 | priority: HIGH 455 | rules: 456 | - apiGroups: ["*"] 457 | resources: ["jobs"] 458 | verbs: ["create"] 459 | 460 | 461 | # Risk: Allowing to update a malicious pod 462 | # Verb: update 463 | # Resources: jobs 464 | 465 | - kind: Role 466 | metadata: 467 | namespace: default 468 | name: risky-update-jobs 469 | priority: HIGH 470 | rules: 471 | - apiGroups: ["*"] 472 | resources: ["jobs"] 473 | verbs: ["update"] 474 | 475 | # Risk: Allowing to create a malicious pod 476 | # Verb: create 477 | # Resources: cronjobs 478 | 479 | - kind: Role 480 | metadata: 481 | namespace: default 482 | name: risky-create-jobs 483 | priority: HIGH 484 | rules: 485 | - apiGroups: ["*"] 486 | resources: ["cronjobs"] 487 | verbs: ["create"] 488 | 489 | 490 | # Risk: Allowing to update a malicious pod 491 | # Verb: update 492 | # Resources: cronjobs 493 | 494 | - kind: Role 495 | metadata: 496 | namespace: default 497 | name: risky-update-jobs 498 | priority: HIGH 499 | rules: 500 | - apiGroups: ["*"] 501 | resources: ["cronjobs"] 502 | verbs: ["update"] 503 | 504 | # Risk: Allowing creation of rolebinding and associate privileged role to itself 505 | # GroupA: 506 | # Verb: create 507 | # Resource: rolebindings 508 | # GroupB: 509 | # Verb: bind 510 | # Resource: roles 511 | # resourceNames: privilegedRoles 512 | 513 | - kind: Role 514 | metadata: 515 | namespace: default 516 | name: risky-create-rolebinding-role 517 | priority: HIGH 518 | rules: 519 | - apiGroups: ["rbac.authorization.k8s.io"] 520 | resources: ["rolebindings"] 521 | verbs: ["create"] 522 | - apiGroups: ["rbac.authorization.k8s.io"] 523 | resources: ["roles"] 524 | verbs: ["bind"] 525 | resourceNames: ["*"] 526 | 527 | # Risk: Allowing creation of rolebinding and associate privileged clusterrole to itself 528 | # GroupA: 529 | # Verb: create 530 | # Resource: rolebindings 531 | # GroupB: 532 | # Verb: bind 533 | # Resource: clusterroles 534 | # resourceNames: privilegedRoles 535 | 536 | 537 | - kind: Role 538 | metadata: 539 | namespace: default 540 | name: risky-create-rolebinding-clusterrole 541 | priority: HIGH 542 | rules: 543 | - apiGroups: ["rbac.authorization.k8s.io"] 544 | resources: ["rolebindings"] 545 | verbs: ["create"] 546 | - apiGroups: ["rbac.authorization.k8s.io"] 547 | resources: ["clusterroles"] 548 | verbs: ["bind"] 549 | resourceNames: ["*"] 550 | 551 | # Risk: Allowing creation of clusterrolebinding and associate privileged clusterrole to itself 552 | # GroupA: 553 | # Verb: create 554 | # Resource: clusterrolebinding 555 | # GroupB: 556 | # Verb: bind 557 | # Resource: clusterroles 558 | # resourceNames: privilegedRoles 559 | 560 | 561 | - kind: Role 562 | metadata: 563 | namespace: default 564 | name: risky-create-clusterrolebinding-clusterrole 565 | priority: HIGH 566 | rules: 567 | - apiGroups: ["rbac.authorization.k8s.io"] 568 | resources: ["clusterrolebindings"] 569 | verbs: ["create"] 570 | - apiGroups: ["rbac.authorization.k8s.io"] 571 | resources: ["clusterroles"] 572 | verbs: ["bind"] 573 | resourceNames: ["*"] 574 | 575 | # Risk: Allowing update of a malicious pod 576 | # Verb: create 577 | # Resources: pods 578 | # Example: kubectl create -f malicious-pod.yaml 579 | 580 | - kind: Role 581 | metadata: 582 | namespace: default 583 | name: risky-create-pod 584 | priority: HIGH 585 | rules: 586 | - apiGroups: ["*"] 587 | resources: ["pods"] 588 | verbs: ["create"] 589 | 590 | 591 | # Risk: Getting shell on pods 592 | # GroupA: 593 | # Verb: create 594 | # Resource: pods/exec 595 | # GroupB: 596 | # Verb: get 597 | # Resource: pods 598 | # Example: kubectl exec podname -it sh 599 | 600 | - kind: Role 601 | metadata: 602 | namespace: default 603 | name: risky-exec-pods 604 | priority: HIGH 605 | rules: 606 | - apiGroups: ["*"] 607 | resources: ["pods/exec"] 608 | verbs: ["create"] 609 | - apiGroups: ["*"] 610 | resources: ["pods"] 611 | verbs: ["get"] 612 | 613 | 614 | # Risk: Attaching pod and view all its logs in realtime 615 | # GroupA: 616 | # Verb: create 617 | # Resource: pods/attach 618 | # GroupB: 619 | # Verb: get 620 | # Resource: pods 621 | # Example: kubectl attach podname -it sh 622 | 623 | 624 | - kind: Role 625 | metadata: 626 | namespace: default 627 | name: risky-attach-pods 628 | priority: HIGH 629 | rules: 630 | - apiGroups: ["*"] 631 | resources: ["pods/attach"] 632 | verbs: ["create"] 633 | - apiGroups: ["*"] 634 | resources: ["pods"] 635 | verbs: ["get"] 636 | 637 | 638 | 639 | ######################### END REGION - HIGH Roles ######################### 640 | 641 | ######################### REGION - LOW Roles ######################### 642 | 643 | # Risk: Allowing users in a rolebinding to add other users to their rolebindings 644 | # Verb: get, patch 645 | # Resources: rolebindings 646 | 647 | - kind: Role 648 | metadata: 649 | namespace: default 650 | name: risky-add-rolebinding 651 | priority: LOW 652 | rules: 653 | - apiGroups: ["*"] 654 | resources: ["rolebindings"] 655 | verbs: ["get", "patch"] 656 | 657 | ######################### END REGION - LOW Roles ######################### 658 | 659 | ######################### END REGION - Risky permissions combinations ######################### 660 | -------------------------------------------------------------------------------- /static_risky_roles.py: -------------------------------------------------------------------------------- 1 | from engine.role import Role 2 | from engine.rule import Rule 3 | from engine.priority import get_priority_by_name 4 | from misc.constants import * 5 | import yaml 6 | import os 7 | 8 | STATIC_RISKY_ROLES = [] 9 | 10 | def set_risky_roles_from_yaml(items): 11 | for role in items: 12 | rules = [] 13 | for rule in role['rules']: 14 | rule_obj = Rule(resources=rule['resources'], verbs=rule['verbs']) 15 | rules.append(rule_obj) 16 | 17 | STATIC_RISKY_ROLES.append(Role(role['metadata']['name'], 18 | get_priority_by_name(role['metadata']['priority']), 19 | rules, 20 | namespace=RISKY_NAMESPACE) 21 | ) 22 | 23 | with open(os.path.dirname(os.path.realpath(__file__)) + '/risky_roles.yaml', 'r') as stream: 24 | try: 25 | loaded_yaml = yaml.safe_load(stream) 26 | set_risky_roles_from_yaml(loaded_yaml['items']) 27 | except yaml.YAMLError as exc: 28 | print(exc) 29 | -------------------------------------------------------------------------------- /static_scan.py: -------------------------------------------------------------------------------- 1 | import yaml 2 | from engine import utils 3 | 4 | ROLE_KIND = "Role" 5 | 6 | def load_roles_from_yaml(file_path): 7 | with open(file_path, 'r') as file: 8 | documents = yaml.safe_load(file) 9 | roles_dict = [doc for doc in documents.get('items', []) if doc.get('kind') == ROLE_KIND] 10 | roles = [Role( 11 | apiVersion=role.get('apiVersion'), 12 | kind=role.get('kind'), 13 | metadata=role.get('metadata'), 14 | rules=role.get('rules') 15 | ) for role in roles_dict] 16 | return roles 17 | 18 | def get_risky_roles_from_file(file_path): 19 | roles = load_roles_from_yaml(file_path) 20 | # Use the find_risky_roles function to identify risky roles 21 | risky_roles = utils.find_risky_roles(roles, ROLE_KIND) 22 | return risky_roles 23 | 24 | def get_risky_roles(file_path): 25 | risky_roles = get_risky_roles_from_file(file_path) 26 | return risky_roles 27 | 28 | # Path to your roles.yaml file 29 | file_path = r'/home/noamr/Documents/KubiScan/roles.yaml' 30 | # Get all risky roles 31 | all_risky_roles = get_risky_roles(file_path) 32 | 33 | # Print out all the risky roles 34 | print("All Risky Roles:") 35 | for role in all_risky_roles: 36 | print(f"Kind: {role.kind}, Name: {role.metadata['name']}, Namespace: {role.metadata['namespace']}") 37 | -------------------------------------------------------------------------------- /static_unit_test/static_scan_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | import subprocess 3 | import difflib 4 | import os 5 | 6 | class TestKubiScan(unittest.TestCase): 7 | 8 | def setUp(self): 9 | """Set up the environment for each test.""" 10 | self.current_directory = os.getcwd() 11 | 12 | #CHANGE combined.yaml to the json/yaml file you created for the static scan. 13 | self.json_file_path = os.path.join(self.current_directory, "combined.yaml") 14 | print(f"Setting up for test in {self.current_directory}") 15 | 16 | def tearDown(self): 17 | """Clean up after each test.""" 18 | print("Tearing down test environment...") 19 | 20 | def run_command(self, cmd): 21 | """Helper function to run shell commands and capture output.""" 22 | result = subprocess.run(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) 23 | return result.stdout, result.stderr 24 | 25 | def filter_output(self, output): 26 | """Helper function to filter out non-essential lines from the output.""" 27 | filtered_lines = [line for line in output.splitlines() 28 | if "KubiScan version" not in line 29 | and "Author" not in line 30 | and "Using kube config file" not in line] 31 | return "\n".join(filtered_lines) 32 | 33 | def compare_outputs(self, output1, output2): 34 | """Helper function to compare two outputs and show differences.""" 35 | output1_filtered = self.filter_output(output1) 36 | output2_filtered = self.filter_output(output2) 37 | 38 | diff = difflib.unified_diff( 39 | output1_filtered.splitlines(), output2_filtered.splitlines(), lineterm='', 40 | fromfile='Regular API Scan', tofile='Static JSON Scan' 41 | ) 42 | diff_output = '\n'.join(diff) 43 | if diff_output: 44 | print(f"Differences found:\n{diff_output}") 45 | return diff_output 46 | 47 | def run_and_compare_scans(self, regular_args, static_args, description): 48 | """Helper function to run and compare regular API scan with static JSON scan.""" 49 | regular_cmd = ["python3", "./KubiScan.py"] + regular_args 50 | static_cmd = ["python3", "./KubiScan.py", "-f", self.json_file_path] + static_args 51 | 52 | regular_output, regular_error = self.run_command(regular_cmd) 53 | static_output, static_error = self.run_command(static_cmd) 54 | 55 | # Ensure both commands ran without errors 56 | self.assertEqual(regular_error, '', f"Error in regular API scan: {regular_error}") 57 | self.assertEqual(static_error, '', f"Error in static JSON scan: {static_error}") 58 | 59 | # Compare outputs and assert no differences 60 | diff = self.compare_outputs(regular_output, static_output) 61 | self.assertEqual(diff, '', f"Outputs differ between regular API scan and static JSON scan for {description}.") 62 | print(f"✅ Test passed: {description} scan comparison is identical.") 63 | 64 | def test_risky_roles(self): 65 | self.run_and_compare_scans(["-rr"], ["-rr"], "Risky Roles") 66 | 67 | def test_risky_clusterroles(self): 68 | self.run_and_compare_scans(["-rcr"], ["-rcr"], "Risky ClusterRoles") 69 | 70 | def test_risky_any_roles(self): 71 | self.run_and_compare_scans(["-rar"], ["-rar"], "Risky Roles and ClusterRoles") 72 | 73 | def test_risky_rolebindings(self): 74 | self.run_and_compare_scans(["-rb"], ["-rb"], "Risky RoleBindings") 75 | 76 | def test_risky_clusterrolebindings(self): 77 | self.run_and_compare_scans(["-rcb"], ["-rcb"], "Risky ClusterRoleBindings") 78 | 79 | def test_risky_any_rolebindings(self): 80 | self.run_and_compare_scans(["-rab"], ["-rab"], "Risky RoleBindings and ClusterRoleBindings") 81 | 82 | def test_risky_subjects(self): 83 | self.run_and_compare_scans(["-rs"], ["-rs"], "Risky Subjects") 84 | 85 | def test_risky_pods(self): 86 | self.run_and_compare_scans(["-rp"], ["-rp"], "Risky Pods") 87 | 88 | 89 | #def test_risky_pods(self): ## There is a bug in KubiScan need to fix. 90 | #self.run_and_compare_scans(["-rp" , "-d"], ["-rp", "-d"], "Risky Pods Deep!") 91 | 92 | #def test_privleged_pods(self): 93 | #self.run_and_compare_scans(["-pp"], ["-pp"], "Privleged Pods") 94 | 95 | def test_risky_rolebindings_namespace(self): 96 | self.run_and_compare_scans(["-rb", "-ns", "kube-system"], ["-rb", "-ns", "kube-system"], "Risky RoleBindings with namespace!") 97 | 98 | def test_risky_all(self): 99 | self.run_and_compare_scans(["-a"], ["-a"], "All risky Roles\ClusterRoles, RoleBindings\ClusterRoleBindings, users and pods\containers.") 100 | 101 | 102 | if __name__ == "__main__": 103 | unittest.main(verbosity=2) 104 | -------------------------------------------------------------------------------- /unit_test.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | from engine import utils, privleged_containers 3 | from engine.privleged_containers import get_privileged_containers 4 | from api import api_client 5 | from .KubiScan import get_all_affecting_cves_table_by_version 6 | import json 7 | from api.config import set_api_client 8 | from api.api_client import api_init 9 | from api.client_factory import ApiClientFactory 10 | from api.config import set_api_client 11 | 12 | list_of_risky_containers = ["test1-yes", "test3-yes", "test5ac2-yes", "test6a-yes", "test6b-yes", 13 | "test7c2-yes", "test8c-yes"] 14 | list_of_not_risky_containers = ["test5ac1-no", "test1-no", "test2b-no", "test7c1-no"] 15 | 16 | list_of_risky_users = ["kubiscan-sa"] 17 | list_of_not_risky_users = ["kubiscan-sa2", "default"] 18 | 19 | list_of_privileged_pods = ["etcd-minikube", "kube-apiserver-minikube", "kube-controller-manager-minikube", 20 | "kube-scheduler-minikube", "storage-provisioner"] 21 | 22 | 23 | version_dict = {"mid_version": "1.19.14", 24 | "above_all_version": "1.200.0", 25 | "under_all_version": "1.0.0"} 26 | 27 | mid_version_cve = ["CVE-2021-25741", "CVE-2021-25749", "CVE-2022-3172"] 28 | 29 | 30 | def get_containers_by_names(): 31 | 32 | risky_pods = utils.get_risky_pods() 33 | risky_containers_by_name = [] 34 | for risky_pod in risky_pods or []: 35 | for container in risky_pod.containers: 36 | risky_containers_by_name.append(container.name) 37 | return risky_containers_by_name 38 | 39 | 40 | def get_risky_users_by_name(): 41 | risky_users = utils.get_all_risky_subjects() 42 | risky_users_by_name = [] 43 | for risky_user in risky_users: 44 | risky_users_by_name.append(risky_user.user_info.name) 45 | return risky_users_by_name 46 | 47 | 48 | def get_cve_list(version_status): 49 | version_table = get_all_affecting_cves_table_by_version(version_dict[version_status]) 50 | cve_list = [] 51 | for row in version_table: 52 | row.border = False 53 | row.header = False 54 | cve_list.append(row.get_string(fields=['CVE']).strip()) 55 | return sorted(cve_list) 56 | 57 | 58 | def get_all_cve_from_json(): 59 | with open('CVE.json', 'r') as f: 60 | data = json.load(f) 61 | all_cves = [] 62 | for cve in data["CVES"]: 63 | all_cves.append(cve["CVENumber"]) 64 | return all_cves 65 | 66 | 67 | class TestKubiScan(unittest.TestCase): 68 | api_client = ApiClientFactory.get_client(use_static=False) 69 | api_init() 70 | set_api_client(api_client) 71 | 72 | def test_get_risky_pods(self): 73 | risky_containers_by_name = get_containers_by_names() 74 | for container in list_of_risky_containers: 75 | self.assertIn(container, risky_containers_by_name) 76 | for container in list_of_not_risky_containers: 77 | self.assertNotIn(container, risky_containers_by_name) 78 | 79 | def test_get_all_risky_roles(self): 80 | risky_users_by_name = get_risky_users_by_name() 81 | for user in list_of_risky_users: 82 | self.assertIn(user, risky_users_by_name) 83 | for user in list_of_not_risky_users: 84 | self.assertNotIn(user, risky_users_by_name) 85 | 86 | def test_get_privileged_containers(self): 87 | pods = get_privileged_containers() 88 | string_list_of_privileged_pods = [] 89 | for pod in pods: 90 | string_list_of_privileged_pods.append(pod.metadata.name) 91 | for pod_name in list_of_privileged_pods: 92 | self.assertIn(pod_name, string_list_of_privileged_pods) 93 | 94 | def test_get_all_affecting_cves_table_by_version(self): 95 | empty_table = get_all_affecting_cves_table_by_version(version_dict["above_all_version"]) 96 | self.assertTrue(len(empty_table._rows) == 0) 97 | 98 | mid_cve_list_sorted = get_cve_list("mid_version") 99 | hard_coded_mid_version_cve_sorted = sorted(mid_version_cve) 100 | self.assertListEqual(hard_coded_mid_version_cve_sorted, mid_cve_list_sorted) 101 | 102 | all_cve_list_sorted = get_cve_list("under_all_version") 103 | all_cve_from_json = sorted(get_all_cve_from_json()) 104 | self.assertListEqual(all_cve_list_sorted, all_cve_from_json) 105 | 106 | 107 | if __name__ == '__main__': 108 | unittest.main() 109 | 110 | 111 | -------------------------------------------------------------------------------- /unit_test/kubectl_apply.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | GREEN='\033[3;92m' 3 | BCYAN='\033[1;96m' 4 | UCYAN='\033[4;96m' 5 | NO_COLOR='\033[0m' 6 | 7 | 8 | if [ "$1" = "-h" ]; 9 | then 10 | echo -e "${UCYAN}How to run unit-test:${NO_COLOR}" 11 | echo -e "${BCYAN}$(cat readme)${NO_COLOR}" 12 | exit 0 13 | fi 14 | 15 | DEFAULT_SECRET=$(kubectl get sa default -o=jsonpath='{.secrets[0].name}') 16 | echo -e "${GREEN}Creating kubiscan-sa...${NO_COLOR}" 17 | kubectl apply -f kubiscan-sa 18 | echo -e "${GREEN}Creating kubiscan-sa2...${NO_COLOR}" 19 | kubectl apply -f kubiscan-sa2 20 | KUBISCAN_SA_SECRET=$(kubectl get sa kubiscan-sa -o=jsonpath='{.secrets[0].name}') 21 | KUBISCAN_SA2_SECRET=$(kubectl get sa kubiscan-sa2 -o=jsonpath='{.secrets[0].name}') 22 | echo -e "${BCYAN}kubiscan-sa secret: "$KUBISCAN_SA_SECRET", kubiscan-sa2 secret: "$KUBISCAN_SA2_SECRET ${NO_COLOR}"" 23 | 24 | echo -e "${GREEN}Creating test1-yes pod...${NO_COLOR}" 25 | kubectl apply -f - << EOF 26 | apiVersion: v1 27 | kind: Pod 28 | metadata: 29 | name: test1-yes 30 | spec: 31 | serviceAccountName: kubiscan-sa 32 | containers: 33 | - name: test1-yes 34 | image: nginx 35 | EOF 36 | 37 | echo -e "${GREEN}Creating test5-yes pod...${NO_COLOR}" 38 | kubectl apply -f - << EOF 39 | apiVersion: v1 40 | kind: Pod 41 | metadata: 42 | name: test5a-yes 43 | namespace: default 44 | spec: 45 | serviceAccountName: kubiscan-sa 46 | containers: 47 | - image: nginx 48 | name: test5ac1-no 49 | volumeMounts: 50 | - name: secret-volume 51 | readOnly: true 52 | mountPath: "/var/run/secrets/kubernetes.io/serviceaccount" 53 | - image: nginx 54 | name: test5ac2-yes 55 | volumes: 56 | - name: secret-volume 57 | secret: 58 | secretName: "$DEFAULT_SECRET" 59 | EOF 60 | 61 | echo -e "${GREEN}Creating test8-yes pod...${NO_COLOR}" 62 | kubectl apply -f - << EOF 63 | apiVersion: v1 64 | kind: Pod 65 | metadata: 66 | name: test8-yes 67 | namespace: default 68 | spec: 69 | serviceAccountName: kubiscan-sa 70 | containers: 71 | - image: nginx 72 | name: test8c-yes 73 | volumeMounts: 74 | - name: secret-volume 75 | readOnly: true 76 | mountPath: "/var/run/secrets/kubernetes.io/serviceaccount" 77 | - name: secret-volume2 78 | mountPath: "/var/run/secrets/tokens" 79 | volumes: 80 | - name: secret-volume 81 | secret: 82 | secretName: "$KUBISCAN_SA_SECRET" 83 | - name: secret-volume2 84 | secret: 85 | secretName: "$KUBISCAN_SA2_SECRET" 86 | EOF 87 | 88 | echo -e "${GREEN}Creating test1-no pod...${NO_COLOR}" 89 | kubectl apply -f - <" 11 | "cd KubiScan/for_unit_test/" 12 | "./kubectl_apply.sh" 13 | [6] For the unit-test run the following command: 14 | python3 -m pytest -v unit_test.py 15 | --------------------------------------------------------------------------------