Compare commits

..

8 Commits

Author SHA1 Message Date
Daniel Sagi
c16c997e47 removed cache and changed to only use ubuntu-latest 2021-09-30 16:32:04 +03:00
Daniel Sagi
a22debaa4e removed unsupported ubuntu16 machines 2021-09-30 16:07:22 +03:00
danielsagi
83b19d4208 Feature: Changed vulnerability categories to support MITRE ATT&CK (#474)
* Refactored all categories to the new MITRE attack matrix format

* Changed format of vulnerabilities table to display the mitre technique related to the vulnerability
2021-09-30 15:25:30 +03:00
danielsagi
473e4fe2b5 Make gateway discovery always run when running as pod #471 2021-07-23 21:09:28 +03:00
danielsagi
f67f08225c changed exception logs to debug logs in kubernetes_client nodes discovery (#470) 2021-07-22 15:57:25 +03:00
danielsagi
c96312b91e updated gemfile (#464) 2021-06-24 21:15:18 +03:00
danielsagi
a7d26452fb Feature: New Service Account Token Flag (#463)
* added service account token flag to use in hunting

* added flag to main parsing config creation

* fixed linting issues

* added documentation on the service-account-token flag

* minor readme change
2021-06-24 20:58:43 +03:00
danielsagi
e63efddf9f Support multiple subscription on ProveVarLogMount active hunter (#461)
* removed redundant call for /pods again from /var/log mount hunter, by using multiple subscription

* fixed new linting

* fixed linting with exceptions
2021-06-24 18:43:14 +03:00
46 changed files with 523 additions and 705 deletions

View File

@@ -10,7 +10,7 @@ name: Release
jobs:
build:
name: Upload Release Asset
runs-on: ubuntu-16.04
runs-on: ubuntu-latest
steps:
- name: Checkout code
uses: actions/checkout@v2

View File

@@ -13,7 +13,7 @@ jobs:
fail-fast: false
matrix:
python-version: ["3.6", "3.7", "3.8", "3.9"]
os: [ubuntu-20.04, ubuntu-18.04, ubuntu-16.04]
os: [ubuntu-latest]
steps:
- uses: actions/checkout@v2
@@ -23,26 +23,10 @@ jobs:
with:
python-version: ${{ matrix.python-version }}
- name: Get pip cache dir
id: pip-cache
run: |
echo "::set-output name=dir::$(pip cache dir)"
- name: Cache
uses: actions/cache@v2
with:
path: ${{ steps.pip-cache.outputs.dir }}
key:
${{ matrix.os }}-${{ matrix.python-version }}-${{ hashFiles('requirements-dev.txt') }}
restore-keys: |
${{ matrix.os }}-${{ matrix.python-version }}-
- name: Install dependencies
run: |
python -m pip install -U pip
python -m pip install -U wheel
python -m pip install -r requirements.txt
python -m pip install -r requirements-dev.txt
python -m pip install -e .
- name: Test
shell: bash

1
.gitignore vendored
View File

@@ -9,7 +9,6 @@ venv/
# Distribution / packaging
.Python
env/
!kube_hunter/console/env/
build/
develop-eggs/
dist/

View File

@@ -27,21 +27,27 @@ kube-hunter hunts for security weaknesses in Kubernetes clusters. The tool was d
Table of Contents
=================
* [Hunting](#hunting)
* [Where should I run kube-hunter?](#where-should-i-run-kube-hunter)
* [Scanning options](#scanning-options)
* [Active Hunting](#active-hunting)
* [List of tests](#list-of-tests)
* [Nodes Mapping](#nodes-mapping)
* [Output](#output)
* [Dispatching](#dispatching)
* [Advanced Usage](#advanced-usage)
* [Deployment](#deployment)
* [On Machine](#on-machine)
* [Prerequisites](#prerequisites)
* [Container](#container)
* [Pod](#pod)
* [Contribution](#contribution)
- [Table of Contents](#table-of-contents)
- [Hunting](#hunting)
- [Where should I run kube-hunter?](#where-should-i-run-kube-hunter)
- [Scanning options](#scanning-options)
- [Authentication](#authentication)
- [Active Hunting](#active-hunting)
- [List of tests](#list-of-tests)
- [Nodes Mapping](#nodes-mapping)
- [Output](#output)
- [Dispatching](#dispatching)
- [Advanced Usage](#advanced-usage)
- [Azure Quick Scanning](#azure-quick-scanning)
- [Deployment](#deployment)
- [On Machine](#on-machine)
- [Prerequisites](#prerequisites)
- [Install with pip](#install-with-pip)
- [Run from source](#run-from-source)
- [Container](#container)
- [Pod](#pod)
- [Contribution](#contribution)
- [License](#license)
## Hunting
@@ -53,7 +59,7 @@ Run kube-hunter on any machine (including your laptop), select Remote scanning a
You can run kube-hunter directly on a machine in the cluster, and select the option to probe all the local network interfaces.
You can also run kube-hunter in a pod within the cluster. This indicates how exposed your cluster would be if one of your application pods is compromised (through a software vulnerability, for example).
You can also run kube-hunter in a pod within the cluster. This indicates how exposed your cluster would be if one of your application pods is compromised (through a software vulnerability, for example). (_`--pod` flag_)
### Scanning options
@@ -82,6 +88,20 @@ Set `--k8s-auto-discover-nodes` flag to query Kubernetes for all nodes in the cl
Also note, that this is always done when using `--pod` mode.
### Authentication
In order to mimic an attacker in it's early stages, kube-hunter requires no authentication for the hunt.
* **Impersonate** - You can provide kube-hunter with a specific service account token to use when hunting by manually passing the JWT Bearer token of the service-account secret with the `--service-account-token` flag.
Example:
```bash
$ kube-hunter --active --service-account-token eyJhbGciOiJSUzI1Ni...
```
* When runing with `--pod` flag, kube-hunter uses the service account token [mounted inside the pod](https://kubernetes.io/docs/reference/access-authn-authz/service-accounts-admin/) to authenticate to services it finds during the hunt.
* if specified, `--service-account-token` flag takes priority when running as a pod
### Active Hunting
Active hunting is an option in which kube-hunter will exploit vulnerabilities it finds, to explore for further vulnerabilities.
@@ -121,7 +141,7 @@ Available dispatch methods are:
* KUBEHUNTER_HTTP_DISPATCH_URL (defaults to: https://localhost)
* KUBEHUNTER_HTTP_DISPATCH_METHOD (defaults to: POST)
### Advanced Usage
### Advanced Usage
#### Azure Quick Scanning
When running **as a Pod in an Azure or AWS environment**, kube-hunter will fetch subnets from the Instance Metadata Service. Naturally this makes the discovery process take longer.
To hardlimit subnet scanning to a `/24` CIDR, use the `--quick` option.

View File

@@ -197,9 +197,9 @@ GEM
html-pipeline (~> 2.2)
jekyll (>= 3.0, < 5.0)
kramdown (2.3.0)
rexml
rexml (>= 3.2.5)
kramdown-parser-gfm (1.1.0)
kramdown (~> 2.0)
kramdown (>= 2.3.1)
liquid (4.0.3)
listen (3.4.0)
rb-fsevent (~> 0.10, >= 0.10.3)
@@ -212,7 +212,7 @@ GEM
jekyll-seo-tag (~> 2.1)
minitest (5.14.3)
multipart-post (2.1.1)
nokogiri (1.11.1)
nokogiri (>= 1.11.4)
mini_portile2 (~> 2.5.0)
racc (~> 1.4)
octokit (4.20.0)

View File

@@ -26,6 +26,7 @@ config = Config(
remote=args.remote,
statistics=args.statistics,
k8s_auto_discover_nodes=args.k8s_auto_discover_nodes,
service_account_token=args.service_account_token,
kubeconfig=args.kubeconfig,
)
setup_logger(args.log, args.log_file)
@@ -34,7 +35,6 @@ set_config(config)
# Running all other registered plugins before execution
pm.hook.load_plugin(args=args)
from kube_hunter.console.manager import start_console
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import HuntFinished, HuntStarted
from kube_hunter.modules.discovery.hosts import RunningAsPodEvent, HostScanEvent
@@ -93,15 +93,11 @@ def main():
global hunt_started
scan_options = [config.pod, config.cidr, config.remote, config.interface, config.k8s_auto_discover_nodes]
try:
if args.console:
start_console()
return
elif args.list:
if args.list:
list_hunters()
return
elif not any(scan_options):
if not any(scan_options):
if not interactive_set_config():
return

View File

@@ -37,6 +37,7 @@ class Config:
reporter: Optional[Any] = None
statistics: bool = False
k8s_auto_discover_nodes: bool = False
service_account_token: Optional[str] = None
kubeconfig: Optional[str] = None

View File

@@ -1,6 +1,6 @@
from argparse import ArgumentParser
from kube_hunter.plugins import hookimpl
from colorama import init, Fore, Style
@hookimpl
def parser_add_arguments(parser):
@@ -8,15 +8,6 @@ def parser_add_arguments(parser):
This is the default hook implementation for parse_add_argument
Contains initialization for all default arguments
"""
# Initializes colorma
init()
parser.add_argument(
"-c", "--console",
action="store_true",
help=f"Starts kube-hunter's {Fore.GREEN}Immersed Console{Style.RESET_ALL}"
)
parser.add_argument(
"--list",
action="store_true",
@@ -63,7 +54,15 @@ def parser_add_arguments(parser):
"It supports both in-cluster config (when running as a pod), "
"and a specific kubectl config file (use --kubeconfig to set this). "
"By default, when this flag is set, it will use in-cluster config. "
"NOTE: this is automatically switched on in --pod mode."
"NOTE: this is automatically switched on in --pod mode.",
)
parser.add_argument(
"--service-account-token",
type=str,
metavar="JWT_TOKEN",
help="Manually specify the service account jwt token to use for authenticating in the hunting process "
"NOTE: This overrides the loading of the pod's bounded authentication when running in --pod mode",
)
parser.add_argument(
@@ -72,7 +71,7 @@ def parser_add_arguments(parser):
metavar="KUBECONFIG",
default=None,
help="Specify the kubeconfig file to use for Kubernetes nodes auto discovery "
" (to be used in conjuction with the --k8s-auto-discover-nodes flag."
" (to be used in conjuction with the --k8s-auto-discover-nodes flag.",
)
parser.add_argument("--active", action="store_true", help="Enables active hunting")

View File

@@ -1,4 +0,0 @@
from . import general
from . import manager
from . import env
from . import auth

View File

@@ -1 +0,0 @@
from .auth import AuthSubConsole

View File

@@ -1,62 +0,0 @@
import argparse
from cmd2 import with_argparser
from kube_hunter.console.general import BaseKubeHunterCmd
class AuthSubConsole(BaseKubeHunterCmd):
"""
Manages the underlying AuthStore database
Implementes 3 methods to manage the db
delete - Removes an auth entry by an index
create - creates a new entry in the db,
select - select the auth to use in the environment
"""
def __init__(self, env):
super(AuthSubConsole, self).__init__()
self.env = env
self.sub_console_name = "env/auth"
delete_parser = argparse.ArgumentParser()
delete_parser.add_argument("index", type=int, help="index of the auth entry for deletion")
@with_argparser(delete_parser)
def do_delete(self, opts):
"""Creates a new entry in the auth database based on a given raw jwt token"""
if opts.index:
if self.env.current_auth.get_auths_count() > opts.index:
self.env.current_auth.delete_auth(opts.jwt_token.strip())
else:
self.perror("Index too large")
create_parser = argparse.ArgumentParser()
create_parser.add_argument("jwt_token", help="A raw jwt_token of the new auth entry")
@with_argparser(create_parser)
def do_create(self, opts):
"""Creates a new entry in the auth database based on a given raw jwt token"""
if opts.jwt_token:
self.env.current_auth.new_auth(opts.jwt_token.strip())
show_parser = argparse.ArgumentParser()
show_parser.add_argument("-i", "--index", type=int, help="set index to print raw data for a specific auth entry")
@with_argparser(show_parser)
def do_show(self, opts):
"""Show current collected auths"""
if opts.index is not None:
if self.env.current_auth.get_auths_count() > opts.index:
self.poutput(f"Token:\n{self.env.current_auth.get_auth(opts.index).raw_token}")
else:
self.perror("Index too large")
else:
self.poutput(self.env.current_auth.get_table())
select_parser = argparse.ArgumentParser()
select_parser.add_argument("index", type=int, help="index of auth entry to set for environment")
@with_argparser(select_parser)
def do_select(self, opts):
"""Sets the auth entry for the environment"""
if opts.index is not None:
if self.env.current_auth.get_auths_count() > opts.index:
self.env.current_auth.set_select_auth(opts.index)
else:
self.perror("Index too large")

View File

@@ -1,76 +0,0 @@
import json
import base64
from prettytable import PrettyTable, ALL
""" Auth models"""
class Auth:
def parse_token(self, token):
""" Extracting data from token file """
# adding maximum base64 padding to parse correctly
self.raw_token = token
token_json = base64.b64decode(f"{token.split('.')[1]}==")
token_data = json.loads(token_json)
self.iss = token_data.get("iss")
self.namespace = token_data.get("kubernetes.io/serviceaccount/namespace")
self.name = token_data.get("kubernetes.io/serviceaccount/secret.name")
self.service_account_name = token_data.get("kubernetes.io/serviceaccount/service-account.name")
self.uid = token_data.get("kubernetes.io/serviceaccount/service-account.uid")
self.sub = token_data.get("sub")
def __init__(self, token=None):
if token:
self.parse_token(token)
class AuthStore:
auths = []
selected_auth = None
def new_auth(self, token):
""" Initializes new Auth object and adds it to the auth db """
new_auth = Auth(token)
if not self.is_exists(new_auth):
self.auths.append(new_auth)
# if it's the only auth, selecting it
if not self.selected_auth:
self.selected_auth = 0
def get_auths_count(self):
return len(self.auths)
def delete_auth(self, index):
return self.auths.pop(index)
def is_exists(self, check_auth):
""" Checks for uniques auth in auth_store """
for auth in self.auths:
if auth.sub == check_auth.sub:
return True
return False
def get_current_auth(self):
return self.auths[self.selected_auth]
def get_auth(self, index):
return self.auths[index]
def set_select_auth(self, index):
self.selected_auth = index
def get_table(self):
auth_table = PrettyTable(["index", "Name", "Selected"], hrules=ALL)
auth_table.align = "l"
auth_table.padding_width = 1
auth_table.header_style = "upper"
# building auth token table, showing selected auths
for i, auth in enumerate(self.auths):
selected_mark = ""
if i == self.selected_auth:
selected_mark = "*"
auth_table.add_row([i, auth.sub, selected_mark])
return auth_table

View File

@@ -1,67 +0,0 @@
from kube_hunter.console.auth import AuthSubConsole
from kube_hunter.console.general import BaseKubeHunterCmd
from kube_hunter.conf import Config, set_config
from kube_hunter.conf.logging import setup_logger
from kube_hunter.core.events import handler
from kube_hunter.modules.discovery.hosts import RunningAsPodEvent, HostScanEvent
from kube_hunter.modules.report import get_reporter, get_dispatcher
from kube_hunter.core.events.types import HuntFinished, HuntStarted
import time
from cmd2 import ansi
from progressbar import FormatLabel, RotatingMarker, UnknownLength, ProgressBar, Timer
class HuntSubConsole(BaseKubeHunterCmd):
"""DiscoverSubConsole
In charge of managing and running kube-hunter's discover modules
"""
def __init__(self, env):
super(HuntSubConsole, self).__init__()
self.env = env
self.sub_console_name = "hunt"
@staticmethod
def progress_bar():
"""Displays animated progress bar
Integrates with handler object, to properly block until hunt finish
"""
# Logger
widgets = ['[', Timer(), ']', ': ', FormatLabel(''), ' ', RotatingMarker()]
bar = ProgressBar(max_value=UnknownLength, widgets=widgets)
while handler.unfinished_tasks > 0:
widgets[4] = FormatLabel(f'Tasks Left To Process: {handler.unfinished_tasks}')
bar.update(handler.unfinished_tasks)
time.sleep(0.1)
bar.finish()
def do_everything(self, arg):
"""Wraps running of kube-hunter's hunting
Uses the current environment to specify data to start_event when starting a scan
"""
# TODO: display output
current_auth = self.env.current_auth.get_current_auth()
start_event = None
if self.env.is_inside_pod:
self.pfeedback(ansi.style(f"Hunting Started (as {current_auth.sub})", fg="green"))
start_event = RunningAsPodEvent()
start_event.auth_token = current_auth.raw_token
# setting basic stuff for output methods
setup_logger("none", None)
config = Config()
config.dispatcher = get_dispatcher("stdout")
config.reporter = get_reporter("plain")
set_config(config)
# trigger hunting
handler.publish_event(start_event)
handler.publish_event(HuntStarted())
self.progress_bar()
self.pfeedback(ansi.style(f"Finished hunting. found {0} services and {0} vulnerabilities", fg="green"))
handler.join()
handler.publish_event(HuntFinished())
handler.free()

View File

@@ -1,2 +0,0 @@
from .env import EnvSubConsole
from .types import ImmersedEnvironment

View File

@@ -1,17 +0,0 @@
from kube_hunter.console.auth import AuthSubConsole
from kube_hunter.console.general import BaseKubeHunterCmd
class EnvSubConsole(BaseKubeHunterCmd):
"""EnvSubConsole
In charge of managing and viewing the entire current environment state
Includes: Auth database..
"""
def __init__(self, env):
super(EnvSubConsole, self).__init__()
self.env = env
self.sub_console_name = "env"
# self.prompt = self.env.get_prompt(sub_console="env")
def do_auth(self, arg):
AuthSubConsole(self.env).cmdloop()

View File

@@ -1,55 +0,0 @@
from colorama import init, Fore, Style
from kube_hunter.console.general import types as GeneralTypes
from kube_hunter.console.auth import types as AuthTypes
# initializes colorma
init()
class ImmersedEnvironment:
"""
ImmersedEnvironment keeps track of the current console run state.
"""
auths = []
pods = []
is_inside_cloud = False
is_inside_container = False
is_inside_pod = False
current_cloud = GeneralTypes.UnknownCloud()
current_pod = GeneralTypes.Pod()
current_container = GeneralTypes.Container()
current_auth = AuthTypes.AuthStore()
def get_prompt(self, sub_console=""):
"""
Parses current env state to picture a short description of where we are right now
General format is `(cloud) -> (run_unit) kube-hunter $`
"""
arrow = "->"
prompt_prefix = f" kube-hunter{' [' + sub_console + ']' if sub_console else ''} $ "
# add colores unly
cloud = f"({Fore.BLUE}{self.current_cloud}{Style.RESET_ALL})"
pod = f"({Fore.MAGENTA}{self.current_pod}{Style.RESET_ALL})"
container = f"(container: {Fore.CYAN}{self.current_container}{Style.RESET_ALL})"
container_in_pod = f"({Fore.MAGENTA}{self.current_pod}/{{}}{Style.RESET_ALL})"
env_description = ""
if self.current_auth.get_auths_count():
auth = self.current_auth.get_current_auth()
env_description += f" {Fore.LIGHTRED_EX}[Impersonating {auth.sub}]{Style.RESET_ALL}\n"
env_description += cloud
if self.is_inside_pod:
if len(self.current_pod.containers):
env_description += f" {arrow} {container_in_pod.format(self.current_pod.containers[0])}"
else:
env_description += f" {arrow} {pod}"
elif self.is_inside_container:
env_description += f" {arrow} {container}"
return f"{env_description}{prompt_prefix}"

View File

@@ -1 +0,0 @@
from .console import BaseKubeHunterCmd

View File

@@ -1,16 +0,0 @@
import cmd2
class BaseKubeHunterCmd(cmd2.Cmd):
sub_console_name = ""
def postcmd(self, stop, line):
self.prompt = self.env.get_prompt(self.sub_console_name)
if stop:
return True
def do_exit(self, arg):
'exists shell'
return True
def emptyline(self):
pass

View File

@@ -1,38 +0,0 @@
import socket
""" General Types """
class Container:
""" Basic model for Container objects """
name = ""
def __str__(self):
return self.name
class Pod:
""" Basic model for Pod objects """
ip_address = ""
name = ""
namespace = ""
containers = []
def __str__(self):
return f"{self.namespace}/{self.name}"
def incluster_update(self, pod_event):
"""
uses pod_event and other techniques to get full data on the incluster pod env data
"""
self.namespace = pod_event.namespace
# hostname will almost always will be the pod's name
self.name = socket.gethostname()
class Cloud:
def __init__(self, name):
self.name = name
def __str__(self):
return self.name
class UnknownCloud(Cloud):
def __init__(self):
super(UnknownCloud, self).__init__("Unknown Cloud")

View File

@@ -1,59 +0,0 @@
from kube_hunter.console.discover.discover import HuntSubConsole
from kube_hunter.console.general import BaseKubeHunterCmd
from kube_hunter.console.env import EnvSubConsole, ImmersedEnvironment
from kube_hunter.modules.discovery.hosts import RunningAsPodEvent
from colorama import (
Back,
Fore,
Style,
)
from cmd2 import ansi
class KubeHunterMainConsole(BaseKubeHunterCmd):
def __init__(self, env):
super(KubeHunterMainConsole, self).__init__()
kube_hunter_logo = r"""
_ __ __ __
/\ \ /\ \ /\ \ /\ \__
\ \ \/'\ __ _\ \ \____ __ \ \ \___ __ __ ___\ \ ,_\ __ _ __
\ \ , < /\ \/\ \ \ '__`\ /'__`\ ______\ \ _ `\/\ \/\ \/' _ `\ \ \/ /'__`/\`'__\
\ \ \\`\\ \ \_\ \ \ \L\ /\ __//\______\ \ \ \ \ \ \_\ /\ \/\ \ \ \_/\ __\ \ \/
\ \_\ \_\ \____/\ \_,__\ \____\/______/\ \_\ \_\ \____\ \_\ \_\ \__\ \____\ \_\
\/_/\/_/\/___/ \/___/ \/____/ \/_/\/_/\/___/ \/_/\/_/\/__/\/____/\/_/
"""
self.intro = f'{kube_hunter_logo}\n\nWelcome to kube-hunter Immeresed Console. Type help or ? to list commands.\n'
self.env = env
def do_hunt(self, arg):
'hunt using specified environment'
HuntSubConsole(self.env).cmdloop()
def do_env(self, arg):
'Show your environment data collected so far'
EnvSubConsole(self.env).cmdloop()
def do_interactive(self, arg):
"""Start interactive ipython session"""
environment = self.env
self.poutput("\n\tStarted an interactive python session. use `environment` to manage the populated environment object")
import ipdb
ipdb.set_trace()
def do_whereami(self, arg):
"""Try to determine you are based on local files and mounts"""
self.pfeedback("Trying to find out where you are...")
pod_event = RunningAsPodEvent()
if pod_event.auth_token:
self.pfeedback(ansi.style("Found running inside a kubernetes pod", fg="green"))
self.env.current_auth.new_auth(pod_event.auth_token)
self.pfeedback(ansi.style("Loaded a new auth entry: (hint: env/auth/show)", fg="green"))
self.env.current_pod.incluster_update(pod_event)
self.env.is_inside_pod = True
self.pfeedback("Updated environment with locally found data")
def start_console():
environment = ImmersedEnvironment()
a = KubeHunterMainConsole(environment)
a.cmdloop()

View File

@@ -3,15 +3,32 @@ import threading
import requests
from kube_hunter.conf import get_config
from kube_hunter.core.types import (
InformationDisclosure,
DenialOfService,
RemoteCodeExec,
IdentityTheft,
PrivilegeEscalation,
AccessRisk,
UnauthenticatedAccess,
KubernetesCluster,
from kube_hunter.core.types import KubernetesCluster
from kube_hunter.core.types.vulnerabilities import (
GeneralSensitiveInformationTechnique,
ExposedSensitiveInterfacesTechnique,
MountServicePrincipalTechnique,
ListK8sSecretsTechnique,
AccessContainerServiceAccountTechnique,
AccessK8sApiServerTechnique,
AccessKubeletAPITechnique,
AccessK8sDashboardTechnique,
InstanceMetadataApiTechnique,
ExecIntoContainerTechnique,
SidecarInjectionTechnique,
NewContainerTechnique,
GeneralPersistenceTechnique,
HostPathMountPrivilegeEscalationTechnique,
PrivilegedContainerTechnique,
ClusterAdminBindingTechnique,
ARPPoisoningTechnique,
CoreDNSPoisoningTechnique,
DataDestructionTechnique,
GeneralDefenseEvasionTechnique,
ConnectFromProxyServerTechnique,
CVERemoteCodeExecutionCategory,
CVEPrivilegeEscalationCategory,
CVEDenialOfServiceTechnique,
)
logger = logging.getLogger(__name__)
@@ -83,6 +100,12 @@ class Service:
self.path = path
self.role = "Node"
# if a service account token was specified, we load it to the Service class
# We load it here because generally all kuberentes services could be authenticated with the token
config = get_config()
if config.service_account_token:
self.auth_token = config.service_account_token
def get_name(self):
return self.name
@@ -96,13 +119,30 @@ class Service:
class Vulnerability:
severity = dict(
{
InformationDisclosure: "medium",
DenialOfService: "medium",
RemoteCodeExec: "high",
IdentityTheft: "high",
PrivilegeEscalation: "high",
AccessRisk: "low",
UnauthenticatedAccess: "low",
GeneralSensitiveInformationTechnique: "low",
ExposedSensitiveInterfacesTechnique: "high",
MountServicePrincipalTechnique: "high",
ListK8sSecretsTechnique: "high",
AccessContainerServiceAccountTechnique: "low",
AccessK8sApiServerTechnique: "medium",
AccessKubeletAPITechnique: "medium",
AccessK8sDashboardTechnique: "medium",
InstanceMetadataApiTechnique: "high",
ExecIntoContainerTechnique: "high",
SidecarInjectionTechnique: "high",
NewContainerTechnique: "high",
GeneralPersistenceTechnique: "high",
HostPathMountPrivilegeEscalationTechnique: "high",
PrivilegedContainerTechnique: "high",
ClusterAdminBindingTechnique: "high",
ARPPoisoningTechnique: "medium",
CoreDNSPoisoningTechnique: "high",
DataDestructionTechnique: "high",
GeneralDefenseEvasionTechnique: "high",
ConnectFromProxyServerTechnique: "low",
CVERemoteCodeExecutionCategory: "high",
CVEPrivilegeEscalationCategory: "high",
CVEDenialOfServiceTechnique: "medium",
}
)
@@ -207,18 +247,21 @@ class ReportDispatched(Event):
class K8sVersionDisclosure(Vulnerability, Event):
"""The kubernetes version could be obtained from the {} endpoint"""
def __init__(self, version, from_endpoint, extra_info=""):
def __init__(self, version, from_endpoint, extra_info="", category=None):
Vulnerability.__init__(
self,
KubernetesCluster,
"K8s Version Disclosure",
category=InformationDisclosure,
category=ExposedSensitiveInterfacesTechnique,
vid="KHV002",
)
self.version = version
self.from_endpoint = from_endpoint
self.extra_info = extra_info
self.evidence = version
# depending from where the version came from, we might want to also override the category
if category:
self.category = category
def explain(self):
return self.__doc__.format(self.from_endpoint) + self.extra_info

View File

@@ -1,94 +0,0 @@
class HunterBase:
publishedVulnerabilities = 0
@staticmethod
def parse_docs(docs):
"""returns tuple of (name, docs)"""
if not docs:
return __name__, "<no documentation>"
docs = docs.strip().split("\n")
for i, line in enumerate(docs):
docs[i] = line.strip()
return docs[0], " ".join(docs[1:]) if len(docs[1:]) else "<no documentation>"
@classmethod
def get_name(cls):
name, _ = cls.parse_docs(cls.__doc__)
return name
def publish_event(self, event):
handler.publish_event(event, caller=self)
class ActiveHunter(HunterBase):
pass
class Hunter(HunterBase):
pass
class Discovery(HunterBase):
pass
class KubernetesCluster:
"""Kubernetes Cluster"""
name = "Kubernetes Cluster"
class KubectlClient:
"""The kubectl client binary is used by the user to interact with the cluster"""
name = "Kubectl Client"
class Kubelet(KubernetesCluster):
"""The kubelet is the primary "node agent" that runs on each node"""
name = "Kubelet"
class AWS(KubernetesCluster):
"""AWS Cluster"""
name = "AWS"
class Azure(KubernetesCluster):
"""Azure Cluster"""
name = "Azure"
class InformationDisclosure:
name = "Information Disclosure"
class RemoteCodeExec:
name = "Remote Code Execution"
class IdentityTheft:
name = "Identity Theft"
class UnauthenticatedAccess:
name = "Unauthenticated Access"
class AccessRisk:
name = "Access Risk"
class PrivilegeEscalation(KubernetesCluster):
name = "Privilege Escalation"
class DenialOfService:
name = "Denial of Service"
# import is in the bottom to break import loops
from .events import handler # noqa

View File

@@ -0,0 +1,4 @@
# flake8: noqa: E402
from .hunters import *
from .components import *
from .vulnerabilities import *

View File

@@ -0,0 +1,28 @@
class KubernetesCluster:
"""Kubernetes Cluster"""
name = "Kubernetes Cluster"
class KubectlClient:
"""The kubectl client binary is used by the user to interact with the cluster"""
name = "Kubectl Client"
class Kubelet(KubernetesCluster):
"""The kubelet is the primary "node agent" that runs on each node"""
name = "Kubelet"
class AWS(KubernetesCluster):
"""AWS Cluster"""
name = "AWS"
class Azure(KubernetesCluster):
"""Azure Cluster"""
name = "Azure"

View File

@@ -0,0 +1,36 @@
class HunterBase:
publishedVulnerabilities = 0
@staticmethod
def parse_docs(docs):
"""returns tuple of (name, docs)"""
if not docs:
return __name__, "<no documentation>"
docs = docs.strip().split("\n")
for i, line in enumerate(docs):
docs[i] = line.strip()
return docs[0], " ".join(docs[1:]) if len(docs[1:]) else "<no documentation>"
@classmethod
def get_name(cls):
name, _ = cls.parse_docs(cls.__doc__)
return name
def publish_event(self, event):
# Import here to avoid circular import from events package.
# imports are cached in python so this should not affect runtime
from ..events import handler # noqa
handler.publish_event(event, caller=self)
class ActiveHunter(HunterBase):
pass
class Hunter(HunterBase):
pass
class Discovery(HunterBase):
pass

View File

@@ -0,0 +1,188 @@
"""
Vulnerabilities are divided into 2 main categories.
MITRE Category
--------------
Vulnerability that correlates to a method in the official MITRE ATT&CK matrix for kubernetes
CVE Category
-------------
"General" category definition. The category is usually determined by the severity of the CVE
"""
class MITRECategory:
@classmethod
def get_name(cls):
"""
Returns the full name of MITRE technique: <MITRE CATEGORY> // <MITRE TECHNIQUE>
Should only be used on a direct technique class at the end of the MITRE inheritance chain.
Example inheritance:
MITRECategory -> InitialAccessCategory -> ExposedSensitiveInterfacesTechnique
"""
inheritance_chain = cls.__mro__
if len(inheritance_chain) >= 4:
# -3 == index of mitreCategory class. (object class is first)
mitre_category_class = inheritance_chain[-3]
return f"{mitre_category_class.name} // {cls.name}"
class CVECategory:
@classmethod
def get_name(cls):
"""
Returns the full name of the category: CVE // <CVE Category name>
"""
return f"CVE // {cls.name}"
"""
MITRE ATT&CK Technique Categories
"""
class InitialAccessCategory(MITRECategory):
name = "Initial Access"
class ExecutionCategory(MITRECategory):
name = "Execution"
class PersistenceCategory(MITRECategory):
name = "Persistence"
class PrivilegeEscalationCategory(MITRECategory):
name = "Privilege Escalation"
class DefenseEvasionCategory(MITRECategory):
name = "Defense Evasion"
class CredentialAccessCategory(MITRECategory):
name = "Credential Access"
class DiscoveryCategory(MITRECategory):
name = "Discovery"
class LateralMovementCategory(MITRECategory):
name = "Lateral Movement"
class CollectionCategory(MITRECategory):
name = "Collection"
class ImpactCategory(MITRECategory):
name = "Impact"
"""
MITRE ATT&CK Techniques
"""
class GeneralSensitiveInformationTechnique(InitialAccessCategory):
name = "General Sensitive Information"
class ExposedSensitiveInterfacesTechnique(InitialAccessCategory):
name = "Exposed sensitive interfaces"
class MountServicePrincipalTechnique(CredentialAccessCategory):
name = "Mount service principal"
class ListK8sSecretsTechnique(CredentialAccessCategory):
name = "List K8S secrets"
class AccessContainerServiceAccountTechnique(CredentialAccessCategory):
name = "Access container service account"
class AccessK8sApiServerTechnique(DiscoveryCategory):
name = "Access the K8S API Server"
class AccessKubeletAPITechnique(DiscoveryCategory):
name = "Access Kubelet API"
class AccessK8sDashboardTechnique(DiscoveryCategory):
name = "Access Kubernetes Dashboard"
class InstanceMetadataApiTechnique(DiscoveryCategory):
name = "Instance Metadata API"
class ExecIntoContainerTechnique(ExecutionCategory):
name = "Exec into container"
class SidecarInjectionTechnique(ExecutionCategory):
name = "Sidecar injection"
class NewContainerTechnique(ExecutionCategory):
name = "New container"
class GeneralPersistenceTechnique(PersistenceCategory):
name = "General Peristence"
class HostPathMountPrivilegeEscalationTechnique(PrivilegeEscalationCategory):
name = "hostPath mount"
class PrivilegedContainerTechnique(PrivilegeEscalationCategory):
name = "Privileged container"
class ClusterAdminBindingTechnique(PrivilegeEscalationCategory):
name = "Cluser-admin binding"
class ARPPoisoningTechnique(LateralMovementCategory):
name = "ARP poisoning and IP spoofing"
class CoreDNSPoisoningTechnique(LateralMovementCategory):
name = "CoreDNS poisoning"
class DataDestructionTechnique(ImpactCategory):
name = "Data Destruction"
class GeneralDefenseEvasionTechnique(DefenseEvasionCategory):
name = "General Defense Evasion"
class ConnectFromProxyServerTechnique(DefenseEvasionCategory):
name = "Connect from Proxy server"
"""
CVE Categories
"""
class CVERemoteCodeExecutionCategory(CVECategory):
name = "Remote Code Execution (CVE)"
class CVEPrivilegeEscalationCategory(CVECategory):
name = "Privilege Escalation (CVE)"
class CVEDenialOfServiceTechnique(CVECategory):
name = "Denial Of Service (CVE)"

View File

@@ -11,7 +11,7 @@ from kube_hunter.conf import get_config
from kube_hunter.modules.discovery.kubernetes_client import list_all_k8s_cluster_nodes
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, NewHostEvent, Vulnerability
from kube_hunter.core.types import Discovery, InformationDisclosure, AWS, Azure
from kube_hunter.core.types import Discovery, AWS, Azure, InstanceMetadataApiTechnique
logger = logging.getLogger(__name__)
@@ -19,11 +19,17 @@ logger = logging.getLogger(__name__)
class RunningAsPodEvent(Event):
def __init__(self):
self.name = "Running from within a pod"
self.auth_token = self.get_service_account_file("token")
self.client_cert = self.get_service_account_file("ca.crt")
self.namespace = self.get_service_account_file("namespace")
self.kubeservicehost = os.environ.get("KUBERNETES_SERVICE_HOST", None)
# if service account token was manually specified, we don't load the token file
config = get_config()
if config.service_account_token:
self.auth_token = config.service_account_token
else:
self.auth_token = self.get_service_account_file("token")
# Event's logical location to be used mainly for reports.
def location(self):
location = "Local to Pod"
@@ -49,7 +55,7 @@ class AWSMetadataApi(Vulnerability, Event):
self,
AWS,
"AWS Metadata Exposure",
category=InformationDisclosure,
category=InstanceMetadataApiTechnique,
vid="KHV053",
)
self.cidr = cidr
@@ -64,7 +70,7 @@ class AzureMetadataApi(Vulnerability, Event):
self,
Azure,
"Azure Metadata Exposure",
category=InformationDisclosure,
category=InstanceMetadataApiTechnique,
vid="KHV003",
)
self.cidr = cidr
@@ -123,15 +129,15 @@ class FromPodHostDiscovery(Discovery):
self.publish_event(HostScanEvent())
else:
# Discover cluster subnets, we'll scan all these hosts
cloud = None
cloud, subnets = None, list()
if self.is_azure_pod():
subnets, cloud = self.azure_metadata_discovery()
elif self.is_aws_pod_v1():
subnets, cloud = self.aws_metadata_v1_discovery()
elif self.is_aws_pod_v2():
subnets, cloud = self.aws_metadata_v2_discovery()
else:
subnets = self.gateway_discovery()
subnets += self.gateway_discovery()
should_scan_apiserver = False
if self.event.kubeservicehost:
@@ -215,19 +221,27 @@ class FromPodHostDiscovery(Discovery):
"http://169.254.169.254/latest/meta-data/mac",
timeout=config.network_timeout,
).text
logger.debug(f"Extracted mac from aws's metadata v1: {mac_address}")
cidr = requests.get(
f"http://169.254.169.254/latest/meta-data/network/interfaces/macs/{mac_address}/subnet-ipv4-cidr-block",
timeout=config.network_timeout,
).text.split("/")
).text
logger.debug(f"Trying to extract cidr from aws's metadata v1: {cidr}")
address, subnet = (cidr[0], cidr[1])
subnet = subnet if not config.quick else "24"
cidr = f"{address}/{subnet}"
logger.debug(f"From pod discovered subnet {cidr}")
try:
cidr = cidr.split("/")
address, subnet = (cidr[0], cidr[1])
subnet = subnet if not config.quick else "24"
cidr = f"{address}/{subnet}"
logger.debug(f"From pod discovered subnet {cidr}")
self.publish_event(AWSMetadataApi(cidr=cidr))
self.publish_event(AWSMetadataApi(cidr=cidr))
return [(address, subnet)], "AWS"
except Exception as x:
logger.debug(f"ERROR: could not parse cidr from aws metadata api: {cidr} - {x}")
return [(address, subnet)], "AWS"
return [], "AWS"
# querying AWS's interface metadata api v2 | works only from a pod
def aws_metadata_v2_discovery(self):
@@ -249,14 +263,19 @@ class FromPodHostDiscovery(Discovery):
timeout=config.network_timeout,
).text.split("/")
address, subnet = (cidr[0], cidr[1])
subnet = subnet if not config.quick else "24"
cidr = f"{address}/{subnet}"
logger.debug(f"From pod discovered subnet {cidr}")
try:
address, subnet = (cidr[0], cidr[1])
subnet = subnet if not config.quick else "24"
cidr = f"{address}/{subnet}"
logger.debug(f"From pod discovered subnet {cidr}")
self.publish_event(AWSMetadataApi(cidr=cidr))
self.publish_event(AWSMetadataApi(cidr=cidr))
return [(address, subnet)], "AWS"
return [(address, subnet)], "AWS"
except Exception as x:
logger.debug(f"ERROR: could not parse cidr from aws metadata api: {cidr} - {x}")
return [], "AWS"
# querying azure's interface metadata api | works only from a pod
def azure_metadata_discovery(self):

View File

@@ -6,13 +6,13 @@ def list_all_k8s_cluster_nodes(kube_config=None, client=None):
logger = logging.getLogger(__name__)
try:
if kube_config:
logger.info("Attempting to use kubeconfig file: %s", kube_config)
logger.debug("Attempting to use kubeconfig file: %s", kube_config)
kubernetes.config.load_kube_config(config_file=kube_config)
else:
logger.info("Attempting to use in cluster Kubernetes config")
logger.debug("Attempting to use in cluster Kubernetes config")
kubernetes.config.load_incluster_config()
except kubernetes.config.config_exception.ConfigException:
logger.exception("Failed to initiate Kubernetes client")
except kubernetes.config.config_exception.ConfigException as ex:
logger.debug(f"Failed to initiate Kubernetes client: {ex}")
return
try:
@@ -23,5 +23,5 @@ def list_all_k8s_cluster_nodes(kube_config=None, client=None):
for item in ret.items:
for addr in item.status.addresses:
yield addr.address
except:
logger.exception("Failed to list nodes from Kubernetes")
except Exception as ex:
logger.debug(f"Failed to list nodes from Kubernetes: {ex}")

View File

@@ -7,7 +7,7 @@ from kube_hunter.conf import get_config
from kube_hunter.modules.hunting.kubelet import ExposedPodsHandler, SecureKubeletPortHunter
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, Vulnerability
from kube_hunter.core.types import Hunter, ActiveHunter, IdentityTheft, Azure
from kube_hunter.core.types import Hunter, ActiveHunter, MountServicePrincipalTechnique, Azure
logger = logging.getLogger(__name__)
@@ -20,7 +20,7 @@ class AzureSpnExposure(Vulnerability, Event):
self,
Azure,
"Azure SPN Exposure",
category=IdentityTheft,
category=MountServicePrincipalTechnique,
vid="KHV004",
)
self.container = container

View File

@@ -8,10 +8,15 @@ from kube_hunter.modules.discovery.apiserver import ApiServer
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event, K8sVersionDisclosure
from kube_hunter.core.types import Hunter, ActiveHunter, KubernetesCluster
from kube_hunter.core.types import (
AccessRisk,
InformationDisclosure,
UnauthenticatedAccess,
from kube_hunter.core.types.vulnerabilities import (
AccessK8sApiServerTechnique,
ExposedSensitiveInterfacesTechnique,
GeneralDefenseEvasionTechnique,
DataDestructionTechnique,
ClusterAdminBindingTechnique,
NewContainerTechnique,
PrivilegedContainerTechnique,
SidecarInjectionTechnique,
)
logger = logging.getLogger(__name__)
@@ -24,10 +29,10 @@ class ServerApiAccess(Vulnerability, Event):
def __init__(self, evidence, using_token):
if using_token:
name = "Access to API using service account token"
category = InformationDisclosure
category = AccessK8sApiServerTechnique
else:
name = "Unauthenticated access to API"
category = UnauthenticatedAccess
category = ExposedSensitiveInterfacesTechnique
Vulnerability.__init__(
self,
KubernetesCluster,
@@ -44,7 +49,7 @@ class ServerApiHTTPAccess(Vulnerability, Event):
def __init__(self, evidence):
name = "Insecure (HTTP) access to API"
category = UnauthenticatedAccess
category = ExposedSensitiveInterfacesTechnique
Vulnerability.__init__(
self,
KubernetesCluster,
@@ -59,7 +64,7 @@ class ApiInfoDisclosure(Vulnerability, Event):
"""Information Disclosure depending upon RBAC permissions and Kube-Cluster Setup"""
def __init__(self, evidence, using_token, name):
category = InformationDisclosure
category = AccessK8sApiServerTechnique
if using_token:
name += " using default service account token"
else:
@@ -111,7 +116,7 @@ class CreateANamespace(Vulnerability, Event):
self,
KubernetesCluster,
name="Created a namespace",
category=AccessRisk,
category=GeneralDefenseEvasionTechnique,
)
self.evidence = evidence
@@ -125,7 +130,7 @@ class DeleteANamespace(Vulnerability, Event):
self,
KubernetesCluster,
name="Delete a namespace",
category=AccessRisk,
category=DataDestructionTechnique,
)
self.evidence = evidence
@@ -136,7 +141,7 @@ class CreateARole(Vulnerability, Event):
"""
def __init__(self, evidence):
Vulnerability.__init__(self, KubernetesCluster, name="Created a role", category=AccessRisk)
Vulnerability.__init__(self, KubernetesCluster, name="Created a role", category=GeneralDefenseEvasionTechnique)
self.evidence = evidence
@@ -150,7 +155,7 @@ class CreateAClusterRole(Vulnerability, Event):
self,
KubernetesCluster,
name="Created a cluster role",
category=AccessRisk,
category=ClusterAdminBindingTechnique,
)
self.evidence = evidence
@@ -165,7 +170,7 @@ class PatchARole(Vulnerability, Event):
self,
KubernetesCluster,
name="Patched a role",
category=AccessRisk,
category=ClusterAdminBindingTechnique,
)
self.evidence = evidence
@@ -180,7 +185,7 @@ class PatchAClusterRole(Vulnerability, Event):
self,
KubernetesCluster,
name="Patched a cluster role",
category=AccessRisk,
category=ClusterAdminBindingTechnique,
)
self.evidence = evidence
@@ -193,7 +198,7 @@ class DeleteARole(Vulnerability, Event):
self,
KubernetesCluster,
name="Deleted a role",
category=AccessRisk,
category=DataDestructionTechnique,
)
self.evidence = evidence
@@ -206,7 +211,7 @@ class DeleteAClusterRole(Vulnerability, Event):
self,
KubernetesCluster,
name="Deleted a cluster role",
category=AccessRisk,
category=DataDestructionTechnique,
)
self.evidence = evidence
@@ -219,7 +224,7 @@ class CreateAPod(Vulnerability, Event):
self,
KubernetesCluster,
name="Created A Pod",
category=AccessRisk,
category=NewContainerTechnique,
)
self.evidence = evidence
@@ -232,7 +237,7 @@ class CreateAPrivilegedPod(Vulnerability, Event):
self,
KubernetesCluster,
name="Created A PRIVILEGED Pod",
category=AccessRisk,
category=PrivilegedContainerTechnique,
)
self.evidence = evidence
@@ -245,7 +250,7 @@ class PatchAPod(Vulnerability, Event):
self,
KubernetesCluster,
name="Patched A Pod",
category=AccessRisk,
category=SidecarInjectionTechnique,
)
self.evidence = evidence
@@ -258,7 +263,7 @@ class DeleteAPod(Vulnerability, Event):
self,
KubernetesCluster,
name="Deleted A Pod",
category=AccessRisk,
category=DataDestructionTechnique,
)
self.evidence = evidence
@@ -377,7 +382,7 @@ class AccessApiServerWithToken(AccessApiServer):
super().__init__(event)
assert self.event.auth_token
self.headers = {"Authorization": f"Bearer {self.event.auth_token}"}
self.category = InformationDisclosure
self.category = AccessK8sApiServerTechnique
self.with_token = True

View File

@@ -5,7 +5,7 @@ from scapy.all import ARP, IP, ICMP, Ether, sr1, srp
from kube_hunter.conf import get_config
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, Vulnerability
from kube_hunter.core.types import ActiveHunter, KubernetesCluster, IdentityTheft
from kube_hunter.core.types import ActiveHunter, KubernetesCluster, ARPPoisoningTechnique
from kube_hunter.modules.hunting.capabilities import CapNetRawEnabled
logger = logging.getLogger(__name__)
@@ -20,7 +20,7 @@ class PossibleArpSpoofing(Vulnerability, Event):
self,
KubernetesCluster,
"Possible Arp Spoof",
category=IdentityTheft,
category=ARPPoisoningTechnique,
vid="KHV020",
)

View File

@@ -4,7 +4,7 @@ import logging
from kube_hunter.modules.discovery.hosts import RunningAsPodEvent
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, Vulnerability
from kube_hunter.core.types import Hunter, AccessRisk, KubernetesCluster
from kube_hunter.core.types import Hunter, ARPPoisoningTechnique, KubernetesCluster
logger = logging.getLogger(__name__)
@@ -20,7 +20,7 @@ class CapNetRawEnabled(Event, Vulnerability):
self,
KubernetesCluster,
name="CAP_NET_RAW Enabled",
category=AccessRisk,
category=ARPPoisoningTechnique,
)

View File

@@ -3,7 +3,7 @@ import logging
import base64
import re
from kube_hunter.core.types import Hunter, KubernetesCluster, InformationDisclosure
from kube_hunter.core.types import Hunter, KubernetesCluster, GeneralSensitiveInformationTechnique
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event, Service
@@ -21,7 +21,7 @@ class CertificateEmail(Vulnerability, Event):
self,
KubernetesCluster,
"Certificate Includes Email Address",
category=InformationDisclosure,
category=GeneralSensitiveInformationTechnique,
vid="KHV021",
)
self.email = email

View File

@@ -6,11 +6,11 @@ from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event, K8sVersionDisclosure
from kube_hunter.core.types import (
Hunter,
KubernetesCluster,
RemoteCodeExec,
PrivilegeEscalation,
DenialOfService,
KubectlClient,
KubernetesCluster,
CVERemoteCodeExecutionCategory,
CVEPrivilegeEscalationCategory,
CVEDenialOfServiceTechnique,
)
from kube_hunter.modules.discovery.kubectl import KubectlClientEvent
@@ -25,7 +25,7 @@ class ServerApiVersionEndPointAccessPE(Vulnerability, Event):
self,
KubernetesCluster,
name="Critical Privilege Escalation CVE",
category=PrivilegeEscalation,
category=CVEPrivilegeEscalationCategory,
vid="KHV022",
)
self.evidence = evidence
@@ -40,7 +40,7 @@ class ServerApiVersionEndPointAccessDos(Vulnerability, Event):
self,
KubernetesCluster,
name="Denial of Service to Kubernetes API Server",
category=DenialOfService,
category=CVEDenialOfServiceTechnique,
vid="KHV023",
)
self.evidence = evidence
@@ -55,7 +55,7 @@ class PingFloodHttp2Implementation(Vulnerability, Event):
self,
KubernetesCluster,
name="Possible Ping Flood Attack",
category=DenialOfService,
category=CVEDenialOfServiceTechnique,
vid="KHV024",
)
self.evidence = evidence
@@ -70,7 +70,7 @@ class ResetFloodHttp2Implementation(Vulnerability, Event):
self,
KubernetesCluster,
name="Possible Reset Flood Attack",
category=DenialOfService,
category=CVEDenialOfServiceTechnique,
vid="KHV025",
)
self.evidence = evidence
@@ -85,7 +85,7 @@ class ServerApiClusterScopedResourcesAccess(Vulnerability, Event):
self,
KubernetesCluster,
name="Arbitrary Access To Cluster Scoped Resources",
category=PrivilegeEscalation,
category=CVEPrivilegeEscalationCategory,
vid="KHV026",
)
self.evidence = evidence
@@ -100,7 +100,7 @@ class IncompleteFixToKubectlCpVulnerability(Vulnerability, Event):
self,
KubectlClient,
"Kubectl Vulnerable To CVE-2019-11246",
category=RemoteCodeExec,
category=CVERemoteCodeExecutionCategory,
vid="KHV027",
)
self.binary_version = binary_version
@@ -116,7 +116,7 @@ class KubectlCpVulnerability(Vulnerability, Event):
self,
KubectlClient,
"Kubectl Vulnerable To CVE-2019-1002101",
category=RemoteCodeExec,
category=CVERemoteCodeExecutionCategory,
vid="KHV028",
)
self.binary_version = binary_version

View File

@@ -3,7 +3,7 @@ import json
import requests
from kube_hunter.conf import get_config
from kube_hunter.core.types import Hunter, RemoteCodeExec, KubernetesCluster
from kube_hunter.core.types import Hunter, AccessK8sDashboardTechnique, KubernetesCluster
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event
from kube_hunter.modules.discovery.dashboard import KubeDashboardEvent
@@ -19,7 +19,7 @@ class DashboardExposed(Vulnerability, Event):
self,
KubernetesCluster,
"Dashboard Exposed",
category=RemoteCodeExec,
category=AccessK8sDashboardTechnique,
vid="KHV029",
)
self.evidence = "nodes: {}".format(" ".join(nodes)) if nodes else None

View File

@@ -6,7 +6,7 @@ from scapy.all import IP, ICMP, UDP, DNS, DNSQR, ARP, Ether, sr1, srp1, srp
from kube_hunter.conf import get_config
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, Vulnerability
from kube_hunter.core.types import ActiveHunter, KubernetesCluster, IdentityTheft
from kube_hunter.core.types import ActiveHunter, KubernetesCluster, CoreDNSPoisoningTechnique
from kube_hunter.modules.hunting.arp import PossibleArpSpoofing
logger = logging.getLogger(__name__)
@@ -21,7 +21,7 @@ class PossibleDnsSpoofing(Vulnerability, Event):
self,
KubernetesCluster,
"Possible DNS Spoof",
category=IdentityTheft,
category=CoreDNSPoisoningTechnique,
vid="KHV030",
)
self.kubedns_pod_ip = kubedns_pod_ip

View File

@@ -8,10 +8,10 @@ from kube_hunter.core.types import (
ActiveHunter,
Hunter,
KubernetesCluster,
InformationDisclosure,
RemoteCodeExec,
UnauthenticatedAccess,
AccessRisk,
GeneralSensitiveInformationTechnique,
GeneralPersistenceTechnique,
ListK8sSecretsTechnique,
ExposedSensitiveInterfacesTechnique,
)
logger = logging.getLogger(__name__)
@@ -29,7 +29,7 @@ class EtcdRemoteWriteAccessEvent(Vulnerability, Event):
self,
KubernetesCluster,
name="Etcd Remote Write Access Event",
category=RemoteCodeExec,
category=GeneralPersistenceTechnique,
vid="KHV031",
)
self.evidence = write_res
@@ -43,7 +43,7 @@ class EtcdRemoteReadAccessEvent(Vulnerability, Event):
self,
KubernetesCluster,
name="Etcd Remote Read Access Event",
category=AccessRisk,
category=ListK8sSecretsTechnique,
vid="KHV032",
)
self.evidence = keys
@@ -58,7 +58,7 @@ class EtcdRemoteVersionDisclosureEvent(Vulnerability, Event):
self,
KubernetesCluster,
name="Etcd Remote version disclosure",
category=InformationDisclosure,
category=GeneralSensitiveInformationTechnique,
vid="KHV033",
)
self.evidence = version
@@ -74,7 +74,7 @@ class EtcdAccessEnabledWithoutAuthEvent(Vulnerability, Event):
self,
KubernetesCluster,
name="Etcd is accessible using insecure connection (HTTP)",
category=UnauthenticatedAccess,
category=ExposedSensitiveInterfacesTechnique,
vid="KHV034",
)
self.evidence = version

View File

@@ -16,9 +16,12 @@ from kube_hunter.core.types import (
ActiveHunter,
KubernetesCluster,
Kubelet,
InformationDisclosure,
RemoteCodeExec,
AccessRisk,
ExposedSensitiveInterfacesTechnique,
ExecIntoContainerTechnique,
GeneralDefenseEvasionTechnique,
GeneralSensitiveInformationTechnique,
PrivilegedContainerTechnique,
AccessKubeletAPITechnique,
)
from kube_hunter.modules.discovery.kubelet import (
ReadOnlyKubeletEvent,
@@ -35,7 +38,7 @@ class ExposedPodsHandler(Vulnerability, Event):
def __init__(self, pods):
Vulnerability.__init__(
self, component=Kubelet, name="Exposed Pods", category=InformationDisclosure, vid="KHV052"
self, component=Kubelet, name="Exposed Pods", category=AccessKubeletAPITechnique, vid="KHV052"
)
self.pods = pods
self.evidence = f"count: {len(self.pods)}"
@@ -50,7 +53,7 @@ class AnonymousAuthEnabled(Vulnerability, Event):
self,
component=Kubelet,
name="Anonymous Authentication",
category=RemoteCodeExec,
category=ExposedSensitiveInterfacesTechnique,
vid="KHV036",
)
@@ -63,7 +66,7 @@ class ExposedContainerLogsHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Container Logs",
category=InformationDisclosure,
category=AccessKubeletAPITechnique,
vid="KHV037",
)
@@ -77,7 +80,7 @@ class ExposedRunningPodsHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Running Pods",
category=InformationDisclosure,
category=AccessKubeletAPITechnique,
vid="KHV038",
)
self.count = count
@@ -92,7 +95,7 @@ class ExposedExecHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Exec On Container",
category=RemoteCodeExec,
category=ExecIntoContainerTechnique,
vid="KHV039",
)
@@ -105,7 +108,7 @@ class ExposedRunHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Run Inside Container",
category=RemoteCodeExec,
category=ExecIntoContainerTechnique,
vid="KHV040",
)
@@ -118,7 +121,7 @@ class ExposedPortForwardHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Port Forward",
category=RemoteCodeExec,
category=GeneralDefenseEvasionTechnique,
vid="KHV041",
)
@@ -132,7 +135,7 @@ class ExposedAttachHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Attaching To Container",
category=RemoteCodeExec,
category=ExecIntoContainerTechnique,
vid="KHV042",
)
@@ -146,7 +149,7 @@ class ExposedHealthzHandler(Vulnerability, Event):
self,
component=Kubelet,
name="Cluster Health Disclosure",
category=InformationDisclosure,
category=GeneralSensitiveInformationTechnique,
vid="KHV043",
)
self.status = status
@@ -163,7 +166,7 @@ the whole cluster"""
self,
component=KubernetesCluster,
name="Exposed Existing Privileged Container(s) Via Secure Kubelet Port",
category=AccessRisk,
category=PrivilegedContainerTechnique,
vid="KHV051",
)
self.exposed_existing_privileged_containers = exposed_existing_privileged_containers
@@ -178,7 +181,7 @@ class PrivilegedContainers(Vulnerability, Event):
self,
component=KubernetesCluster,
name="Privileged Container",
category=AccessRisk,
category=PrivilegedContainerTechnique,
vid="KHV044",
)
self.containers = containers
@@ -193,7 +196,7 @@ class ExposedSystemLogs(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed System Logs",
category=InformationDisclosure,
category=AccessKubeletAPITechnique,
vid="KHV045",
)
@@ -206,7 +209,7 @@ class ExposedKubeletCmdline(Vulnerability, Event):
self,
component=Kubelet,
name="Exposed Kubelet Cmdline",
category=InformationDisclosure,
category=AccessKubeletAPITechnique,
vid="KHV046",
)
self.cmdline = cmdline

View File

@@ -5,12 +5,7 @@ import uuid
from kube_hunter.conf import get_config
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Event, Vulnerability
from kube_hunter.core.types import (
ActiveHunter,
Hunter,
KubernetesCluster,
PrivilegeEscalation,
)
from kube_hunter.core.types import ActiveHunter, Hunter, KubernetesCluster, HostPathMountPrivilegeEscalationTechnique
from kube_hunter.modules.hunting.kubelet import (
ExposedPodsHandler,
ExposedRunHandler,
@@ -28,7 +23,7 @@ class WriteMountToVarLog(Vulnerability, Event):
self,
KubernetesCluster,
"Pod With Mount To /var/log",
category=PrivilegeEscalation,
category=HostPathMountPrivilegeEscalationTechnique,
vid="KHV047",
)
self.pods = pods
@@ -44,7 +39,7 @@ class DirectoryTraversalWithKubelet(Vulnerability, Event):
self,
KubernetesCluster,
"Root Traversal Read On The Kubelet",
category=PrivilegeEscalation,
category=HostPathMountPrivilegeEscalationTechnique,
)
self.output = output
self.evidence = f"output: {self.output}"
@@ -77,15 +72,17 @@ class VarLogMountHunter(Hunter):
self.publish_event(WriteMountToVarLog(pods=pe_pods))
@handler.subscribe(ExposedRunHandler)
@handler.subscribe_many([ExposedRunHandler, WriteMountToVarLog])
class ProveVarLogMount(ActiveHunter):
"""Prove /var/log Mount Hunter
Tries to read /etc/shadow on the host by running commands inside a pod with host mount to /var/log
"""
def __init__(self, event):
self.event = event
self.base_path = f"https://{self.event.host}:{self.event.port}"
self.write_mount_event = self.event.get_by_class(WriteMountToVarLog)
self.event = self.write_mount_event
self.base_path = f"https://{self.write_mount_event.host}:{self.write_mount_event.port}"
def run(self, command, container):
run_url = KubeletHandlers.RUN.value.format(
@@ -96,20 +93,6 @@ class ProveVarLogMount(ActiveHunter):
)
return self.event.session.post(f"{self.base_path}/{run_url}", verify=False).text
# TODO: replace with multiple subscription to WriteMountToVarLog as well
def get_varlog_mounters(self):
config = get_config()
logger.debug("accessing /pods manually on ProveVarLogMount")
pods = self.event.session.get(
f"{self.base_path}/" + KubeletHandlers.PODS.value,
verify=False,
timeout=config.network_timeout,
).json()["items"]
for pod in pods:
volume = VarLogMountHunter(ExposedPodsHandler(pods=pods)).has_write_mount_to(pod, "/var/log")
if volume:
yield pod, volume
def mount_path_from_mountname(self, pod, mount_name):
"""returns container name, and container mount path correlated to mount_name"""
for container in pod["spec"]["containers"]:
@@ -138,7 +121,7 @@ class ProveVarLogMount(ActiveHunter):
return content
def execute(self):
for pod, volume in self.get_varlog_mounters():
for pod, volume in self.write_mount_event.pe_pods():
for container, mount_path in self.mount_path_from_mountname(pod, volume["name"]):
logger.debug("Correlated container to mount_name")
cont = {

View File

@@ -10,7 +10,7 @@ from kube_hunter.core.types import (
ActiveHunter,
Hunter,
KubernetesCluster,
InformationDisclosure,
ConnectFromProxyServerTechnique,
)
from kube_hunter.modules.discovery.dashboard import KubeDashboardEvent
from kube_hunter.modules.discovery.proxy import KubeProxyEvent
@@ -26,7 +26,7 @@ class KubeProxyExposed(Vulnerability, Event):
self,
KubernetesCluster,
"Proxy Exposed",
category=InformationDisclosure,
category=ConnectFromProxyServerTechnique,
vid="KHV049",
)
@@ -123,5 +123,6 @@ class K8sVersionDisclosureProve(ActiveHunter):
version=version_metadata["gitVersion"],
from_endpoint="/version",
extra_info="on kube-proxy",
category=ConnectFromProxyServerTechnique,
)
)

View File

@@ -3,7 +3,7 @@ import os
from kube_hunter.core.events import handler
from kube_hunter.core.events.types import Vulnerability, Event
from kube_hunter.core.types import Hunter, KubernetesCluster, AccessRisk
from kube_hunter.core.types import Hunter, KubernetesCluster, AccessContainerServiceAccountTechnique
from kube_hunter.modules.discovery.hosts import RunningAsPodEvent
logger = logging.getLogger(__name__)
@@ -17,7 +17,7 @@ class ServiceAccountTokenAccess(Vulnerability, Event):
self,
KubernetesCluster,
name="Read access to pod's service account token",
category=AccessRisk,
category=AccessContainerServiceAccountTechnique,
vid="KHV050",
)
self.evidence = evidence
@@ -31,7 +31,7 @@ class SecretsAccess(Vulnerability, Event):
self,
component=KubernetesCluster,
name="Access to pod's secrets",
category=AccessRisk,
category=AccessContainerServiceAccountTechnique,
)
self.evidence = evidence

View File

@@ -36,7 +36,7 @@ class BaseReporter:
{
"location": vuln.location(),
"vid": vuln.get_vid(),
"category": vuln.category.name,
"category": vuln.category.get_name(),
"severity": vuln.get_severity(),
"vulnerability": vuln.get_name(),
"description": vuln.explain(),

View File

@@ -83,7 +83,7 @@ class PlainReporter(BaseReporter):
column_names = [
"ID",
"Location",
"Category",
"MITRE Category",
"Vulnerability",
"Description",
"Evidence",
@@ -91,7 +91,7 @@ class PlainReporter(BaseReporter):
vuln_table = PrettyTable(column_names, hrules=ALL)
vuln_table.align = "l"
vuln_table.max_width = MAX_TABLE_WIDTH
vuln_table.sortby = "Category"
vuln_table.sortby = "MITRE Category"
vuln_table.reversesort = True
vuln_table.padding_width = 1
vuln_table.header_style = "upper"
@@ -101,10 +101,11 @@ class PlainReporter(BaseReporter):
evidence = str(vuln.evidence)
if len(evidence) > EVIDENCE_PREVIEW:
evidence = evidence[:EVIDENCE_PREVIEW] + "..."
row = [
vuln.get_vid(),
vuln.location(),
vuln.category.name,
vuln.category.get_name(),
vuln.get_name(),
vuln.explain(),
evidence,

View File

@@ -1,10 +1,9 @@
from kube_hunter.conf import Config, set_config
set_config(Config())
from kube_hunter.modules.discovery.kubernetes_client import list_all_k8s_cluster_nodes
from unittest.mock import MagicMock, patch
set_config(Config())
def test_client_yields_ips():
@@ -18,7 +17,7 @@ def test_client_yields_ips():
response.items[1].status.addresses = [MagicMock()]
response.items[1].status.addresses[0].address = "127.0.0.3"
with patch('kubernetes.config.load_incluster_config') as m:
with patch("kubernetes.config.load_incluster_config") as m:
output = list(list_all_k8s_cluster_nodes(client=client))
m.assert_called_once()
@@ -26,6 +25,6 @@ def test_client_yields_ips():
def test_client_uses_kubeconfig():
with patch('kubernetes.config.load_kube_config') as m:
with patch("kubernetes.config.load_kube_config") as m:
list(list_all_k8s_cluster_nodes(kube_config="/location", client=MagicMock()))
m.assert_called_once_with(config_file="/location")

View File

@@ -1,4 +1,5 @@
# flake8: noqa: E402
from kube_hunter.core.types.vulnerabilities import AccessK8sApiServerTechnique
import requests_mock
import time
@@ -21,7 +22,7 @@ from kube_hunter.modules.hunting.apiserver import (
from kube_hunter.modules.hunting.apiserver import ApiServerPassiveHunterFinished
from kube_hunter.modules.hunting.apiserver import CreateANamespace, DeleteANamespace
from kube_hunter.modules.discovery.apiserver import ApiServer
from kube_hunter.core.types import UnauthenticatedAccess, InformationDisclosure
from kube_hunter.core.types import ExposedSensitiveInterfacesTechnique, AccessK8sApiServerTechnique
from kube_hunter.core.events import handler
counter = 0
@@ -181,10 +182,10 @@ class test_ListClusterRoles:
class test_ServerApiAccess:
def __init__(self, event):
print("ServerApiAccess")
if event.category == UnauthenticatedAccess:
if event.category == ExposedSensitiveInterfacesTechnique:
assert event.auth_token is None
else:
assert event.category == InformationDisclosure
assert event.category == AccessK8sApiServerTechnique
assert event.auth_token == "so-secret"
global counter
counter += 1