diff --git a/.travis.yml b/.travis.yml index 34f49efe0..880825671 100644 --- a/.travis.yml +++ b/.travis.yml @@ -15,7 +15,7 @@ install: # Python - pip install -r monkey/monkey_island/requirements.txt # for unit tests - pip install flake8 pytest dlint # for next stages -- pip install -r monkey/infection_monkey/requirements_linux.txt # for unit tests +- pip install -r monkey/infection_monkey/requirements.txt # for unit tests before_script: # Set the server config to `testing`. This is required for for the UTs to pass. diff --git a/deployment_scripts/deploy_linux.sh b/deployment_scripts/deploy_linux.sh old mode 100644 new mode 100755 index 488911f15..4e641407e --- a/deployment_scripts/deploy_linux.sh +++ b/deployment_scripts/deploy_linux.sh @@ -70,6 +70,7 @@ fi if [[ ${python_cmd} == "" ]]; then log_message "Python 3.7 command not found. Installing python 3.7." sudo add-apt-repository ppa:deadsnakes/ppa + sudo apt-get update sudo apt install python3.7 log_message "Python 3.7 is now available with command 'python3.7'." python_cmd="python3.7" @@ -92,7 +93,7 @@ ${python_cmd} -m pip install --user --upgrade -r ${requirements} || handle_error log_message "Installing monkey requirements" sudo apt-get install libffi-dev upx libssl-dev libc++1 cd ${monkey_home}/monkey/infection_monkey || handle_error -${python_cmd} -m pip install -r requirements_linux.txt --user --upgrade || handle_error +${python_cmd} -m pip install -r requirements.txt --user --upgrade || handle_error # Download binaries log_message "Downloading binaries" @@ -126,6 +127,7 @@ openssl x509 -req -days 366 -in cc/server.csr -signkey cc/server.key -out cc/ser # Update node log_message "Installing nodejs" cd "$ISLAND_PATH/cc/ui" || handle_error +sudo apt-get install curl curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash - sudo apt-get install -y nodejs npm install sass-loader node-sass webpack --save-dev diff --git a/deployment_scripts/deploy_windows.ps1 b/deployment_scripts/deploy_windows.ps1 index 5a21c4daa..dd602e199 100644 --- a/deployment_scripts/deploy_windows.ps1 +++ b/deployment_scripts/deploy_windows.ps1 @@ -78,7 +78,7 @@ function Deploy-Windows([String] $monkey_home = (Get-Item -Path ".\").FullName, $islandRequirements = Join-Path -Path $monkey_home -ChildPath $MONKEY_ISLAND_DIR | Join-Path -ChildPath "\requirements.txt" -ErrorAction Stop & python -m pip install --user -r $islandRequirements "Installing python packages for monkey" - $monkeyRequirements = Join-Path -Path $monkey_home -ChildPath $MONKEY_DIR | Join-Path -ChildPath "\requirements_windows.txt" + $monkeyRequirements = Join-Path -Path $monkey_home -ChildPath $MONKEY_DIR | Join-Path -ChildPath "\requirements.txt" & python -m pip install --user -r $monkeyRequirements $user_python_dir = cmd.exe /c 'py -m site --user-site' diff --git a/envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py b/envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py index 8ac53996b..388115463 100644 --- a/envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py +++ b/envs/monkey_zoo/blackbox/island_client/monkey_island_requests.py @@ -27,35 +27,36 @@ class MonkeyIslandRequests(object): @classmethod def refresh_jwt_token(cls, request_function): @functools.wraps(request_function) - def request_function_wrapper(self, *args,**kwargs): + def request_function_wrapper(self, *args, **kwargs): self.token = self.try_get_jwt_from_server() # noinspection PyArgumentList return request_function(self, *args, **kwargs) + return request_function_wrapper def get_jwt_from_server(self): - resp = requests.post(self.addr + "api/auth", + resp = requests.post(self.addr + "api/auth", # noqa: DUO123 json={"username": NO_AUTH_CREDS, "password": NO_AUTH_CREDS}, verify=False) return resp.json()["access_token"] @_Decorators.refresh_jwt_token def get(self, url, data=None): - return requests.get(self.addr + url, + return requests.get(self.addr + url, # noqa: DUO123 headers=self.get_jwt_header(), params=data, verify=False) @_Decorators.refresh_jwt_token def post(self, url, data): - return requests.post(self.addr + url, + return requests.post(self.addr + url, # noqa: DUO123 data=data, headers=self.get_jwt_header(), verify=False) @_Decorators.refresh_jwt_token def post_json(self, url, dict_data): - return requests.post(self.addr + url, + return requests.post(self.addr + url, # noqa: DUO123 json=dict_data, headers=self.get_jwt_header(), verify=False) diff --git a/envs/monkey_zoo/terraform/config.tf b/envs/monkey_zoo/terraform/config.tf index 3a2bf0fc4..5396f424c 100644 --- a/envs/monkey_zoo/terraform/config.tf +++ b/envs/monkey_zoo/terraform/config.tf @@ -2,7 +2,7 @@ provider "google" { project = "test-000000" region = "europe-west3" zone = "europe-west3-b" - credentials = "${file("../gcp_keys/gcp_key.json")}" + credentials = file("../gcp_keys/gcp_key.json") } locals { resource_prefix = "" diff --git a/envs/monkey_zoo/terraform/firewalls.tf b/envs/monkey_zoo/terraform/firewalls.tf index afd99a347..a331125c4 100644 --- a/envs/monkey_zoo/terraform/firewalls.tf +++ b/envs/monkey_zoo/terraform/firewalls.tf @@ -1,6 +1,6 @@ resource "google_compute_firewall" "islands-in" { name = "${local.resource_prefix}islands-in" - network = "${google_compute_network.monkeyzoo.name}" + network = google_compute_network.monkeyzoo.name allow { protocol = "tcp" @@ -14,7 +14,7 @@ resource "google_compute_firewall" "islands-in" { resource "google_compute_firewall" "islands-out" { name = "${local.resource_prefix}islands-out" - network = "${google_compute_network.monkeyzoo.name}" + network = google_compute_network.monkeyzoo.name allow { protocol = "tcp" @@ -27,7 +27,7 @@ resource "google_compute_firewall" "islands-out" { resource "google_compute_firewall" "monkeyzoo-in" { name = "${local.resource_prefix}monkeyzoo-in" - network = "${google_compute_network.monkeyzoo.name}" + network = google_compute_network.monkeyzoo.name allow { protocol = "all" @@ -40,7 +40,7 @@ resource "google_compute_firewall" "monkeyzoo-in" { resource "google_compute_firewall" "monkeyzoo-out" { name = "${local.resource_prefix}monkeyzoo-out" - network = "${google_compute_network.monkeyzoo.name}" + network = google_compute_network.monkeyzoo.name allow { protocol = "all" @@ -53,7 +53,7 @@ resource "google_compute_firewall" "monkeyzoo-out" { resource "google_compute_firewall" "tunneling-in" { name = "${local.resource_prefix}tunneling-in" - network = "${google_compute_network.tunneling.name}" + network = google_compute_network.tunneling.name allow { protocol = "all" @@ -65,7 +65,7 @@ resource "google_compute_firewall" "tunneling-in" { resource "google_compute_firewall" "tunneling-out" { name = "${local.resource_prefix}tunneling-out" - network = "${google_compute_network.tunneling.name}" + network = google_compute_network.tunneling.name allow { protocol = "all" @@ -77,7 +77,7 @@ resource "google_compute_firewall" "tunneling-out" { resource "google_compute_firewall" "tunneling2-in" { name = "${local.resource_prefix}tunneling2-in" - network = "${google_compute_network.tunneling2.name}" + network = google_compute_network.tunneling2.name allow { protocol = "all" @@ -89,7 +89,7 @@ resource "google_compute_firewall" "tunneling2-in" { resource "google_compute_firewall" "tunneling2-out" { name = "${local.resource_prefix}tunneling2-out" - network = "${google_compute_network.tunneling2.name}" + network = google_compute_network.tunneling2.name allow { protocol = "all" diff --git a/envs/monkey_zoo/terraform/images.tf b/envs/monkey_zoo/terraform/images.tf index dccbe16dd..4c01ff4d2 100644 --- a/envs/monkey_zoo/terraform/images.tf +++ b/envs/monkey_zoo/terraform/images.tf @@ -1,19 +1,19 @@ //Custom cloud images data "google_compute_image" "hadoop-2" { name = "hadoop-2" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "hadoop-3" { name = "hadoop-3" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "elastic-4" { name = "elastic-4" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "elastic-5" { name = "elastic-5" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } /* @@ -23,73 +23,73 @@ data "google_compute_image" "sambacry-6" { */ data "google_compute_image" "shellshock-8" { name = "shellshock-8" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "tunneling-9" { name = "tunneling-9" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "tunneling-10" { name = "tunneling-10" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "tunneling-11" { name = "tunneling-11" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "sshkeys-11" { name = "sshkeys-11" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "sshkeys-12" { name = "sshkeys-12" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "mimikatz-14" { name = "mimikatz-14" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "mimikatz-15" { name = "mimikatz-15" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "mssql-16" { name = "mssql-16" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "weblogic-18" { name = "weblogic-18" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "weblogic-19" { name = "weblogic-19" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "smb-20" { name = "smb-20" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "scan-21" { name = "scan-21" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "scan-22" { name = "scan-22" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "struts2-23" { name = "struts2-23" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "struts2-24" { name = "struts2-24" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "island-linux-250" { name = "island-linux-250" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } data "google_compute_image" "island-windows-251" { name = "island-windows-251" - project = "${local.monkeyzoo_project}" + project = local.monkeyzoo_project } diff --git a/envs/monkey_zoo/terraform/monkey_zoo.tf b/envs/monkey_zoo/terraform/monkey_zoo.tf index cf45d93e0..30602f237 100644 --- a/envs/monkey_zoo/terraform/monkey_zoo.tf +++ b/envs/monkey_zoo/terraform/monkey_zoo.tf @@ -1,8 +1,8 @@ // Local variables locals { - default_ubuntu="${google_compute_instance_template.ubuntu16.self_link}" - default_windows="${google_compute_instance_template.windows2016.self_link}" + default_ubuntu=google_compute_instance_template.ubuntu16.self_link + default_windows=google_compute_instance_template.windows2016.self_link } resource "google_compute_network" "monkeyzoo" { @@ -23,27 +23,27 @@ resource "google_compute_network" "tunneling2" { resource "google_compute_subnetwork" "monkeyzoo-main" { name = "${local.resource_prefix}monkeyzoo-main" ip_cidr_range = "10.2.2.0/24" - network = "${google_compute_network.monkeyzoo.self_link}" + network = google_compute_network.monkeyzoo.self_link } resource "google_compute_subnetwork" "tunneling-main" { name = "${local.resource_prefix}tunneling-main" ip_cidr_range = "10.2.1.0/28" - network = "${google_compute_network.tunneling.self_link}" + network = google_compute_network.tunneling.self_link } resource "google_compute_subnetwork" "tunneling2-main" { name = "${local.resource_prefix}tunneling2-main" ip_cidr_range = "10.2.0.0/27" - network = "${google_compute_network.tunneling2.self_link}" + network = google_compute_network.tunneling2.self_link } resource "google_compute_instance_from_template" "hadoop-2" { name = "${local.resource_prefix}hadoop-2" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.hadoop-2.self_link}" + image = data.google_compute_image.hadoop-2.self_link } auto_delete = true } @@ -57,10 +57,10 @@ resource "google_compute_instance_from_template" "hadoop-2" { resource "google_compute_instance_from_template" "hadoop-3" { name = "${local.resource_prefix}hadoop-3" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.hadoop-3.self_link}" + image = data.google_compute_image.hadoop-3.self_link } auto_delete = true } @@ -72,10 +72,10 @@ resource "google_compute_instance_from_template" "hadoop-3" { resource "google_compute_instance_from_template" "elastic-4" { name = "${local.resource_prefix}elastic-4" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.elastic-4.self_link}" + image = data.google_compute_image.elastic-4.self_link } auto_delete = true } @@ -87,10 +87,10 @@ resource "google_compute_instance_from_template" "elastic-4" { resource "google_compute_instance_from_template" "elastic-5" { name = "${local.resource_prefix}elastic-5" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.elastic-5.self_link}" + image = data.google_compute_image.elastic-5.self_link } auto_delete = true } @@ -135,10 +135,10 @@ resource "google_compute_instance_from_template" "sambacry-7" { resource "google_compute_instance_from_template" "shellshock-8" { name = "${local.resource_prefix}shellshock-8" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.shellshock-8.self_link}" + image = data.google_compute_image.shellshock-8.self_link } auto_delete = true } @@ -150,10 +150,10 @@ resource "google_compute_instance_from_template" "shellshock-8" { resource "google_compute_instance_from_template" "tunneling-9" { name = "${local.resource_prefix}tunneling-9" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.tunneling-9.self_link}" + image = data.google_compute_image.tunneling-9.self_link } auto_delete = true } @@ -169,10 +169,10 @@ resource "google_compute_instance_from_template" "tunneling-9" { resource "google_compute_instance_from_template" "tunneling-10" { name = "${local.resource_prefix}tunneling-10" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.tunneling-10.self_link}" + image = data.google_compute_image.tunneling-10.self_link } auto_delete = true } @@ -188,10 +188,10 @@ resource "google_compute_instance_from_template" "tunneling-10" { resource "google_compute_instance_from_template" "tunneling-11" { name = "${local.resource_prefix}tunneling-11" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.tunneling-11.self_link}" + image = data.google_compute_image.tunneling-11.self_link } auto_delete = true } @@ -203,10 +203,10 @@ resource "google_compute_instance_from_template" "tunneling-11" { resource "google_compute_instance_from_template" "sshkeys-11" { name = "${local.resource_prefix}sshkeys-11" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.sshkeys-11.self_link}" + image = data.google_compute_image.sshkeys-11.self_link } auto_delete = true } @@ -218,10 +218,10 @@ resource "google_compute_instance_from_template" "sshkeys-11" { resource "google_compute_instance_from_template" "sshkeys-12" { name = "${local.resource_prefix}sshkeys-12" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.sshkeys-12.self_link}" + image = data.google_compute_image.sshkeys-12.self_link } auto_delete = true } @@ -249,10 +249,10 @@ resource "google_compute_instance_from_template" "rdpgrinder-13" { resource "google_compute_instance_from_template" "mimikatz-14" { name = "${local.resource_prefix}mimikatz-14" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.mimikatz-14.self_link}" + image = data.google_compute_image.mimikatz-14.self_link } auto_delete = true } @@ -264,10 +264,10 @@ resource "google_compute_instance_from_template" "mimikatz-14" { resource "google_compute_instance_from_template" "mimikatz-15" { name = "${local.resource_prefix}mimikatz-15" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.mimikatz-15.self_link}" + image = data.google_compute_image.mimikatz-15.self_link } auto_delete = true } @@ -279,10 +279,10 @@ resource "google_compute_instance_from_template" "mimikatz-15" { resource "google_compute_instance_from_template" "mssql-16" { name = "${local.resource_prefix}mssql-16" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.mssql-16.self_link}" + image = data.google_compute_image.mssql-16.self_link } auto_delete = true } @@ -314,10 +314,10 @@ resource "google_compute_instance_from_template" "upgrader-17" { resource "google_compute_instance_from_template" "weblogic-18" { name = "${local.resource_prefix}weblogic-18" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.weblogic-18.self_link}" + image = data.google_compute_image.weblogic-18.self_link } auto_delete = true } @@ -329,10 +329,10 @@ resource "google_compute_instance_from_template" "weblogic-18" { resource "google_compute_instance_from_template" "weblogic-19" { name = "${local.resource_prefix}weblogic-19" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.weblogic-19.self_link}" + image = data.google_compute_image.weblogic-19.self_link } auto_delete = true } @@ -344,10 +344,10 @@ resource "google_compute_instance_from_template" "weblogic-19" { resource "google_compute_instance_from_template" "smb-20" { name = "${local.resource_prefix}smb-20" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.smb-20.self_link}" + image = data.google_compute_image.smb-20.self_link } auto_delete = true } @@ -359,10 +359,10 @@ resource "google_compute_instance_from_template" "smb-20" { resource "google_compute_instance_from_template" "scan-21" { name = "${local.resource_prefix}scan-21" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.scan-21.self_link}" + image = data.google_compute_image.scan-21.self_link } auto_delete = true } @@ -374,10 +374,10 @@ resource "google_compute_instance_from_template" "scan-21" { resource "google_compute_instance_from_template" "scan-22" { name = "${local.resource_prefix}scan-22" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.scan-22.self_link}" + image = data.google_compute_image.scan-22.self_link } auto_delete = true } @@ -389,10 +389,10 @@ resource "google_compute_instance_from_template" "scan-22" { resource "google_compute_instance_from_template" "struts2-23" { name = "${local.resource_prefix}struts2-23" - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.struts2-23.self_link}" + image = data.google_compute_image.struts2-23.self_link } auto_delete = true } @@ -404,10 +404,10 @@ resource "google_compute_instance_from_template" "struts2-23" { resource "google_compute_instance_from_template" "struts2-24" { name = "${local.resource_prefix}struts2-24" - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.struts2-24.self_link}" + image = data.google_compute_image.struts2-24.self_link } auto_delete = true } @@ -421,10 +421,10 @@ resource "google_compute_instance_from_template" "island-linux-250" { name = "${local.resource_prefix}island-linux-250" machine_type = "n1-standard-2" tags = ["island", "linux", "ubuntu16"] - source_instance_template = "${local.default_ubuntu}" + source_instance_template = local.default_ubuntu boot_disk{ initialize_params { - image = "${data.google_compute_image.island-linux-250.self_link}" + image = data.google_compute_image.island-linux-250.self_link } auto_delete = true } @@ -442,10 +442,10 @@ resource "google_compute_instance_from_template" "island-windows-251" { name = "${local.resource_prefix}island-windows-251" machine_type = "n1-standard-2" tags = ["island", "windows", "windowsserver2016"] - source_instance_template = "${local.default_windows}" + source_instance_template = local.default_windows boot_disk{ initialize_params { - image = "${data.google_compute_image.island-windows-251.self_link}" + image = data.google_compute_image.island-windows-251.self_link } auto_delete = true } diff --git a/envs/monkey_zoo/terraform/templates.tf b/envs/monkey_zoo/terraform/templates.tf index 6ae6dafdc..2659c31be 100644 --- a/envs/monkey_zoo/terraform/templates.tf +++ b/envs/monkey_zoo/terraform/templates.tf @@ -18,7 +18,7 @@ resource "google_compute_instance_template" "ubuntu16" { } } service_account { - email ="${local.service_account_email}" + email =local.service_account_email scopes=["cloud-platform"] } } @@ -39,7 +39,7 @@ resource "google_compute_instance_template" "windows2016" { subnetwork="monkeyzoo-main" } service_account { - email="${local.service_account_email}" + email=local.service_account_email scopes=["cloud-platform"] } } diff --git a/monkey/infection_monkey/config.py b/monkey/infection_monkey/config.py index 5e52022cd..2d2a93939 100644 --- a/monkey/infection_monkey/config.py +++ b/monkey/infection_monkey/config.py @@ -2,11 +2,9 @@ import hashlib import os import json import sys -import types import uuid from abc import ABCMeta from itertools import product -import importlib __author__ = 'itamar' @@ -20,10 +18,6 @@ HIDDEN_FIELD_REPLACEMENT_CONTENT = "hidden" class Configuration(object): def from_kv(self, formatted_data): - # now we won't work at <2.7 for sure - network_import = importlib.import_module('infection_monkey.network') - exploit_import = importlib.import_module('infection_monkey.exploit') - unknown_items = [] for key, value in list(formatted_data.items()): if key.startswith('_'): @@ -32,15 +26,10 @@ class Configuration(object): continue if self._depth_from_commandline and key == "depth": continue - # handle in cases - elif key == 'exploiter_classes': - class_objects = [getattr(exploit_import, val) for val in value] - setattr(self, key, class_objects) + if hasattr(self, key): + setattr(self, key, value) else: - if hasattr(self, key): - setattr(self, key, value) - else: - unknown_items.append(key) + unknown_items.append(key) return unknown_items def from_json(self, json_data): diff --git a/monkey/infection_monkey/control.py b/monkey/infection_monkey/control.py index b063744ad..8b45bab2c 100644 --- a/monkey/infection_monkey/control.py +++ b/monkey/infection_monkey/control.py @@ -53,7 +53,7 @@ class ControlClient(object): if ControlClient.proxies: monkey['tunnel'] = ControlClient.proxies.get('https') - requests.post("https://%s/api/monkey" % (WormConfiguration.current_server,), + requests.post("https://%s/api/monkey" % (WormConfiguration.current_server,), # noqa: DUO123 data=json.dumps(monkey), headers={'content-type': 'application/json'}, verify=False, @@ -76,7 +76,7 @@ class ControlClient(object): if ControlClient.proxies: debug_message += " through proxies: %s" % ControlClient.proxies LOG.debug(debug_message) - requests.get("https://%s/api?action=is-up" % (server,), + requests.get("https://%s/api?action=is-up" % (server,), # noqa: DUO123 verify=False, proxies=ControlClient.proxies, timeout=TIMEOUT_IN_SECONDS) @@ -112,7 +112,7 @@ class ControlClient(object): monkey = {} if ControlClient.proxies: monkey['tunnel'] = ControlClient.proxies.get('https') - requests.patch("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), + requests.patch("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), # noqa: DUO123 data=json.dumps(monkey), headers={'content-type': 'application/json'}, verify=False, @@ -129,7 +129,7 @@ class ControlClient(object): return try: telemetry = {'monkey_guid': GUID, 'telem_category': telem_category, 'data': data} - requests.post("https://%s/api/telemetry" % (WormConfiguration.current_server,), + requests.post("https://%s/api/telemetry" % (WormConfiguration.current_server,), # noqa: DUO123 data=json.dumps(telemetry), headers={'content-type': 'application/json'}, verify=False, @@ -144,7 +144,7 @@ class ControlClient(object): return try: telemetry = {'monkey_guid': GUID, 'log': json.dumps(log)} - requests.post("https://%s/api/log" % (WormConfiguration.current_server,), + requests.post("https://%s/api/log" % (WormConfiguration.current_server,), # noqa: DUO123 data=json.dumps(telemetry), headers={'content-type': 'application/json'}, verify=False, @@ -158,7 +158,7 @@ class ControlClient(object): if not WormConfiguration.current_server: return try: - reply = requests.get("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), + reply = requests.get("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), # noqa: DUO123 verify=False, proxies=ControlClient.proxies) @@ -185,7 +185,7 @@ class ControlClient(object): if not WormConfiguration.current_server: return try: - requests.patch("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), + requests.patch("https://%s/api/monkey/%s" % (WormConfiguration.current_server, GUID), # noqa: DUO123 data=json.dumps({'config_error': True}), headers={'content-type': 'application/json'}, verify=False, @@ -247,7 +247,7 @@ class ControlClient(object): if (monkeyfs.isfile(dest_file)) and (size == monkeyfs.getsize(dest_file)): return dest_file else: - download = requests.get("https://%s/api/monkey/download/%s" % + download = requests.get("https://%s/api/monkey/download/%s" % # noqa: DUO123 (WormConfiguration.current_server, filename), verify=False, proxies=ControlClient.proxies) @@ -273,7 +273,7 @@ class ControlClient(object): if not WormConfiguration.current_server: return None, None try: - reply = requests.post("https://%s/api/monkey/download" % (WormConfiguration.current_server,), + reply = requests.post("https://%s/api/monkey/download" % (WormConfiguration.current_server,), # noqa: DUO123 data=json.dumps(host_dict), headers={'content-type': 'application/json'}, verify=False, proxies=ControlClient.proxies) @@ -315,7 +315,7 @@ class ControlClient(object): @staticmethod def get_pba_file(filename): try: - return requests.get(PBA_FILE_DOWNLOAD % + return requests.get(PBA_FILE_DOWNLOAD % # noqa: DUO123 (WormConfiguration.current_server, filename), verify=False, proxies=ControlClient.proxies) diff --git a/monkey/infection_monkey/exploit/HostExploiter.py b/monkey/infection_monkey/exploit/HostExploiter.py new file mode 100644 index 000000000..50f4167d8 --- /dev/null +++ b/monkey/infection_monkey/exploit/HostExploiter.py @@ -0,0 +1,98 @@ +from abc import abstractmethod + +from infection_monkey.config import WormConfiguration +from common.utils.exploit_enum import ExploitType +from datetime import datetime + +from infection_monkey.utils.plugins.plugin import Plugin +import infection_monkey.exploit + +__author__ = 'itamar' + + +class HostExploiter(Plugin): + @staticmethod + def should_run(class_name): + """ + Decides if post breach action is enabled in config + :return: True if it needs to be ran, false otherwise + """ + return class_name in WormConfiguration.exploiter_classes + + @staticmethod + def base_package_file(): + return infection_monkey.exploit.__file__ + + @staticmethod + def base_package_name(): + return infection_monkey.exploit.__package__ + + _TARGET_OS_TYPE = [] + + # Usual values are 'vulnerability' or 'brute_force' + EXPLOIT_TYPE = ExploitType.VULNERABILITY + + @property + @abstractmethod + def _EXPLOITED_SERVICE(self): + pass + + def __init__(self, host): + self._config = WormConfiguration + self.exploit_info = {'display_name': self._EXPLOITED_SERVICE, + 'started': '', + 'finished': '', + 'vulnerable_urls': [], + 'vulnerable_ports': [], + 'executed_cmds': []} + self.exploit_attempts = [] + self.host = host + + def set_start_time(self): + self.exploit_info['started'] = datetime.now().isoformat() + + def set_finish_time(self): + self.exploit_info['finished'] = datetime.now().isoformat() + + def is_os_supported(self): + return self.host.os.get('type') in self._TARGET_OS_TYPE + + def send_exploit_telemetry(self, result): + from infection_monkey.telemetry.exploit_telem import ExploitTelem + ExploitTelem(self, result).send() + + def report_login_attempt(self, result, user, password='', lm_hash='', ntlm_hash='', ssh_key=''): + self.exploit_attempts.append({'result': result, 'user': user, 'password': password, + 'lm_hash': lm_hash, 'ntlm_hash': ntlm_hash, 'ssh_key': ssh_key}) + + def exploit_host(self): + self.pre_exploit() + try: + result = self._exploit_host() + finally: + self.post_exploit() + return result + + def pre_exploit(self): + self.set_start_time() + + def post_exploit(self): + self.set_finish_time() + + @abstractmethod + def _exploit_host(self): + raise NotImplementedError() + + def add_vuln_url(self, url): + self.exploit_info['vulnerable_urls'].append(url) + + def add_vuln_port(self, port): + self.exploit_info['vulnerable_ports'].append(port) + + def add_executed_cmd(self, cmd): + """ + Appends command to exploiter's info. + :param cmd: String of executed command. e.g. 'echo Example' + """ + powershell = True if "powershell" in cmd.lower() else False + self.exploit_info['executed_cmds'].append({'cmd': cmd, 'powershell': powershell}) diff --git a/monkey/infection_monkey/exploit/__init__.py b/monkey/infection_monkey/exploit/__init__.py index 306350437..e69de29bb 100644 --- a/monkey/infection_monkey/exploit/__init__.py +++ b/monkey/infection_monkey/exploit/__init__.py @@ -1,92 +0,0 @@ -from abc import ABCMeta, abstractmethod, abstractproperty -import infection_monkey.config -from common.utils.exploit_enum import ExploitType -from datetime import datetime - -__author__ = 'itamar' - - -class HostExploiter(object, metaclass=ABCMeta): - _TARGET_OS_TYPE = [] - - # Usual values are 'vulnerability' or 'brute_force' - EXPLOIT_TYPE = ExploitType.VULNERABILITY - - @property - @abstractmethod - def _EXPLOITED_SERVICE(self): - pass - - def __init__(self, host): - self._config = infection_monkey.config.WormConfiguration - self.exploit_info = {'display_name': self._EXPLOITED_SERVICE, - 'started': '', - 'finished': '', - 'vulnerable_urls': [], - 'vulnerable_ports': [], - 'executed_cmds': []} - self.exploit_attempts = [] - self.host = host - - def set_start_time(self): - self.exploit_info['started'] = datetime.now().isoformat() - - def set_finish_time(self): - self.exploit_info['finished'] = datetime.now().isoformat() - - def is_os_supported(self): - return self.host.os.get('type') in self._TARGET_OS_TYPE - - def send_exploit_telemetry(self, result): - from infection_monkey.telemetry.exploit_telem import ExploitTelem - ExploitTelem(self, result).send() - - def report_login_attempt(self, result, user, password='', lm_hash='', ntlm_hash='', ssh_key=''): - self.exploit_attempts.append({'result': result, 'user': user, 'password': password, - 'lm_hash': lm_hash, 'ntlm_hash': ntlm_hash, 'ssh_key': ssh_key}) - - def exploit_host(self): - self.pre_exploit() - try: - result = self._exploit_host() - finally: - self.post_exploit() - return result - - def pre_exploit(self): - self.set_start_time() - - def post_exploit(self): - self.set_finish_time() - - @abstractmethod - def _exploit_host(self): - raise NotImplementedError() - - def add_vuln_url(self, url): - self.exploit_info['vulnerable_urls'].append(url) - - def add_vuln_port(self, port): - self.exploit_info['vulnerable_ports'].append(port) - - def add_executed_cmd(self, cmd): - """ - Appends command to exploiter's info. - :param cmd: String of executed command. e.g. 'echo Example' - """ - powershell = True if "powershell" in cmd.lower() else False - self.exploit_info['executed_cmds'].append({'cmd': cmd, 'powershell': powershell}) - - -from infection_monkey.exploit.win_ms08_067 import Ms08_067_Exploiter -from infection_monkey.exploit.wmiexec import WmiExploiter -from infection_monkey.exploit.smbexec import SmbExploiter -from infection_monkey.exploit.sshexec import SSHExploiter -from infection_monkey.exploit.shellshock import ShellShockExploiter -from infection_monkey.exploit.sambacry import SambaCryExploiter -from infection_monkey.exploit.elasticgroovy import ElasticGroovyExploiter -from infection_monkey.exploit.struts2 import Struts2Exploiter -from infection_monkey.exploit.weblogic import WebLogicExploiter -from infection_monkey.exploit.hadoop import HadoopExploiter -from infection_monkey.exploit.mssqlexec import MSSQLExploiter -from infection_monkey.exploit.vsftpd import VSFTPDExploiter diff --git a/monkey/infection_monkey/exploit/mssqlexec.py b/monkey/infection_monkey/exploit/mssqlexec.py index 16e69dff0..9d2aff5b0 100644 --- a/monkey/infection_monkey/exploit/mssqlexec.py +++ b/monkey/infection_monkey/exploit/mssqlexec.py @@ -6,7 +6,7 @@ from time import sleep import pymssql from common.utils.exploit_enum import ExploitType -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.http_tools import MonkeyHTTPServer from infection_monkey.exploit.tools.helpers import get_monkey_dest_path, build_monkey_commandline, get_monkey_depth from infection_monkey.model import DROPPER_ARG diff --git a/monkey/infection_monkey/exploit/sambacry.py b/monkey/infection_monkey/exploit/sambacry.py index 4e1d71fd9..4820d0f05 100644 --- a/monkey/infection_monkey/exploit/sambacry.py +++ b/monkey/infection_monkey/exploit/sambacry.py @@ -16,7 +16,7 @@ from impacket.smb3structs import SMB2_IL_IMPERSONATION, SMB2_CREATE, SMB2_FLAGS_ from impacket.smbconnection import SMBConnection import infection_monkey.monkeyfs as monkeyfs -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.model import DROPPER_ARG from infection_monkey.network.smbfinger import SMB_SERVICE from infection_monkey.exploit.tools.helpers import build_monkey_commandline, get_target_monkey_by_os, get_monkey_depth diff --git a/monkey/infection_monkey/exploit/shellshock.py b/monkey/infection_monkey/exploit/shellshock.py index f65974dbd..718e10617 100644 --- a/monkey/infection_monkey/exploit/shellshock.py +++ b/monkey/infection_monkey/exploit/shellshock.py @@ -7,7 +7,7 @@ from random import choice import requests from common.utils.attack_utils import ScanStatus -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, get_monkey_depth, build_monkey_commandline from infection_monkey.model import DROPPER_ARG from infection_monkey.exploit.shellshock_resources import CGI_FILES @@ -172,10 +172,13 @@ class ShellShockExploiter(HostExploiter): LOG.info("File %s exists on remote host" % file_path) return resp - def attempt_exploit(self, url, attacks=_attacks): + def attempt_exploit(self, url, attacks=None): # Flag used to identify whether the exploit has successfully caused the # server to return a useful response + if not attacks: + attacks = self._attacks + LOG.debug("Attack Flag is: %s" % self.success_flag) LOG.debug("Trying exploit for %s" % url) @@ -206,7 +209,7 @@ class ShellShockExploiter(HostExploiter): try: LOG.debug("Header is: %s" % header) LOG.debug("Attack is: %s" % attack) - r = requests.get(url, headers={header: attack}, verify=False, timeout=TIMEOUT) + r = requests.get(url, headers={header: attack}, verify=False, timeout=TIMEOUT) # noqa: DUO123 result = r.content.decode() return result except requests.exceptions.RequestException as exc: @@ -229,7 +232,7 @@ class ShellShockExploiter(HostExploiter): attack_urls = [attack_path + url for url in url_list] for u in attack_urls: try: - reqs.append(requests.head(u, verify=False, timeout=TIMEOUT)) + reqs.append(requests.head(u, verify=False, timeout=TIMEOUT)) # noqa: DUO123 except requests.Timeout: timeout = True break diff --git a/monkey/infection_monkey/exploit/smbexec.py b/monkey/infection_monkey/exploit/smbexec.py index fef8dad05..f53e1ac38 100644 --- a/monkey/infection_monkey/exploit/smbexec.py +++ b/monkey/infection_monkey/exploit/smbexec.py @@ -3,7 +3,7 @@ from logging import getLogger from impacket.dcerpc.v5 import transport, scmr from impacket.smbconnection import SMB_DIALECT -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, get_monkey_depth, build_monkey_commandline from infection_monkey.exploit.tools.smb_tools import SmbTools from infection_monkey.model import MONKEY_CMDLINE_DETACHED_WINDOWS, DROPPER_CMDLINE_DETACHED_WINDOWS diff --git a/monkey/infection_monkey/exploit/sshexec.py b/monkey/infection_monkey/exploit/sshexec.py index a7e9571b5..4fbc484eb 100644 --- a/monkey/infection_monkey/exploit/sshexec.py +++ b/monkey/infection_monkey/exploit/sshexec.py @@ -5,7 +5,7 @@ import time import paramiko import infection_monkey.monkeyfs as monkeyfs -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, get_monkey_depth, build_monkey_commandline from infection_monkey.model import MONKEY_ARG from infection_monkey.network.tools import check_tcp_port, get_interface_to_target diff --git a/monkey/infection_monkey/exploit/vsftpd.py b/monkey/infection_monkey/exploit/vsftpd.py index d4116c96c..82954b99b 100644 --- a/monkey/infection_monkey/exploit/vsftpd.py +++ b/monkey/infection_monkey/exploit/vsftpd.py @@ -8,7 +8,7 @@ import socket import time from common.utils.attack_utils import ScanStatus -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, build_monkey_commandline, get_monkey_depth from infection_monkey.exploit.tools.http_tools import HTTPTools from infection_monkey.model import MONKEY_ARG, CHMOD_MONKEY, RUN_MONKEY, WGET_HTTP_UPLOAD, DOWNLOAD_TIMEOUT diff --git a/monkey/infection_monkey/exploit/web_rce.py b/monkey/infection_monkey/exploit/web_rce.py index b894acf43..bef428f4d 100644 --- a/monkey/infection_monkey/exploit/web_rce.py +++ b/monkey/infection_monkey/exploit/web_rce.py @@ -3,7 +3,7 @@ import re from posixpath import join from abc import abstractmethod -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, get_monkey_depth, build_monkey_commandline from infection_monkey.exploit.tools.http_tools import HTTPTools from infection_monkey.model import CHECK_COMMAND, ID_STRING, GET_ARCH_LINUX, GET_ARCH_WINDOWS, BITSADMIN_CMDLINE_HTTP, \ diff --git a/monkey/infection_monkey/exploit/weblogic.py b/monkey/infection_monkey/exploit/weblogic.py index 08b642942..04eb43c79 100644 --- a/monkey/infection_monkey/exploit/weblogic.py +++ b/monkey/infection_monkey/exploit/weblogic.py @@ -7,7 +7,7 @@ from requests import post, exceptions from http.server import BaseHTTPRequestHandler, HTTPServer from infection_monkey.exploit.web_rce import WebRCE -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.network.tools import get_interface_to_target from infection_monkey.network.info import get_free_tcp_port from http.server import BaseHTTPRequestHandler, HTTPServer @@ -80,7 +80,7 @@ class WebLogic201710271(WebRCE): else: payload = self.get_exploit_payload('cmd', '/c', command + ' 1> NUL 2> NUL') try: - post(url, data=payload, headers=HEADERS, timeout=EXECUTION_TIMEOUT, verify=False) + post(url, data=payload, headers=HEADERS, timeout=EXECUTION_TIMEOUT, verify=False) # noqa: DUO123 except Exception as e: LOG.error("Connection error: %s" % e) return False @@ -116,7 +116,7 @@ class WebLogic201710271(WebRCE): def check_if_exploitable_weblogic(self, url, httpd): payload = self.get_test_payload(ip=httpd.local_ip, port=httpd.local_port) try: - post(url, data=payload, headers=HEADERS, timeout=REQUEST_DELAY, verify=False) + post(url, data=payload, headers=HEADERS, timeout=REQUEST_DELAY, verify=False) # noqa: DUO123 except exceptions.ReadTimeout: # Our request will not get response thus we get ReadTimeout error pass @@ -299,7 +299,7 @@ class WebLogic20192725(WebRCE): :return: Formatted payload """ empty_payload = ''' - xx diff --git a/monkey/infection_monkey/exploit/win_ms08_067.py b/monkey/infection_monkey/exploit/win_ms08_067.py index b84cf3391..f296091d6 100644 --- a/monkey/infection_monkey/exploit/win_ms08_067.py +++ b/monkey/infection_monkey/exploit/win_ms08_067.py @@ -19,7 +19,7 @@ from infection_monkey.exploit.tools.smb_tools import SmbTools from infection_monkey.model import DROPPER_CMDLINE_WINDOWS, MONKEY_CMDLINE_WINDOWS from infection_monkey.network.smbfinger import SMBFinger from infection_monkey.network.tools import check_tcp_port -from . import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter LOG = getLogger(__name__) diff --git a/monkey/infection_monkey/exploit/wmiexec.py b/monkey/infection_monkey/exploit/wmiexec.py index cc286bfcd..adaf524e2 100644 --- a/monkey/infection_monkey/exploit/wmiexec.py +++ b/monkey/infection_monkey/exploit/wmiexec.py @@ -5,7 +5,7 @@ import traceback from impacket.dcerpc.v5.rpcrt import DCERPCException -from infection_monkey.exploit import HostExploiter +from infection_monkey.exploit.HostExploiter import HostExploiter from infection_monkey.exploit.tools.helpers import get_target_monkey, \ get_monkey_depth, build_monkey_commandline from infection_monkey.exploit.tools.wmi_tools import AccessDeniedException diff --git a/monkey/infection_monkey/monkey.py b/monkey/infection_monkey/monkey.py index 3d0b9d3d7..80d2d8642 100644 --- a/monkey/infection_monkey/monkey.py +++ b/monkey/infection_monkey/monkey.py @@ -30,6 +30,7 @@ from infection_monkey.network.tools import get_interface_to_target from infection_monkey.exploit.tools.exceptions import ExploitingVulnerableMachineError, FailedExploitationError from infection_monkey.telemetry.attack.t1106_telem import T1106Telem from common.utils.attack_utils import ScanStatus, UsageEnum +from infection_monkey.exploit.HostExploiter import HostExploiter __author__ = 'itamar' @@ -144,10 +145,10 @@ class InfectionMonkey(object): self._network.initialize() - self._exploiters = WormConfiguration.exploiter_classes - self._fingerprint = HostFinger.get_instances() + self._exploiters = HostExploiter.get_classes() + if not self._keep_running or not WormConfiguration.alive: break diff --git a/monkey/infection_monkey/network/HostScanner.py b/monkey/infection_monkey/network/HostScanner.py index c6e730c3f..4f7b850c1 100644 --- a/monkey/infection_monkey/network/HostScanner.py +++ b/monkey/infection_monkey/network/HostScanner.py @@ -2,7 +2,6 @@ from abc import ABCMeta, abstractmethod class HostScanner(metaclass=ABCMeta): - @property @abstractmethod def is_host_alive(self, host): raise NotImplementedError() diff --git a/monkey/infection_monkey/network/httpfinger.py b/monkey/infection_monkey/network/httpfinger.py index c6590b9db..ec9f619da 100644 --- a/monkey/infection_monkey/network/httpfinger.py +++ b/monkey/infection_monkey/network/httpfinger.py @@ -32,7 +32,7 @@ class HTTPFinger(HostFinger): # try http, we don't optimise for 443 for url in (https, http): # start with https and downgrade try: - with closing(head(url, verify=False, timeout=1)) as req: + with closing(head(url, verify=False, timeout=1)) as req: # noqa: DUO123 server = req.headers.get('Server') ssl = True if 'https://' in url else False self.init_service(host.services, ('tcp-' + port[1]), port[0]) diff --git a/monkey/infection_monkey/network/info.py b/monkey/infection_monkey/network/info.py index 6b9c5811e..15d9b0d73 100644 --- a/monkey/infection_monkey/network/info.py +++ b/monkey/infection_monkey/network/info.py @@ -51,15 +51,18 @@ if is_windows_os(): local_hostname = socket.gethostname() return socket.gethostbyname_ex(local_hostname)[2] + def get_routes(): raise NotImplementedError() else: from fcntl import ioctl + def local_ips(): valid_ips = [network['addr'] for network in get_host_subnets()] return valid_ips + def get_routes(): # based on scapy implementation for route parsing try: f = open("/proc/net/route", "r") @@ -125,7 +128,7 @@ def check_internet_access(services): """ for host in services: try: - requests.get("https://%s" % (host,), timeout=TIMEOUT, verify=False) + requests.get("https://%s" % (host,), timeout=TIMEOUT, verify=False) # noqa: DUO123 return True except ConnectionError: # Failed connecting diff --git a/monkey/infection_monkey/network/tools.py b/monkey/infection_monkey/network/tools.py index 7a029e5dd..5e95e20be 100644 --- a/monkey/infection_monkey/network/tools.py +++ b/monkey/infection_monkey/network/tools.py @@ -308,4 +308,4 @@ def get_interface_to_target(dst): return None paths.sort() ret = paths[-1][1] - return ret[1] \ No newline at end of file + return ret[1] diff --git a/monkey/infection_monkey/pyinstaller_hooks/hook-infection_monkey.exploit.py b/monkey/infection_monkey/pyinstaller_hooks/hook-infection_monkey.exploit.py new file mode 100644 index 000000000..e759a4116 --- /dev/null +++ b/monkey/infection_monkey/pyinstaller_hooks/hook-infection_monkey.exploit.py @@ -0,0 +1,4 @@ +from PyInstaller.utils.hooks import collect_submodules, collect_data_files + +hiddenimports = collect_submodules('infection_monkey.exploit') +datas = (collect_data_files('infection_monkey.exploit', include_py_files=True)) diff --git a/monkey/infection_monkey/readme.md b/monkey/infection_monkey/readme.md new file mode 100644 index 000000000..d6e17acdb --- /dev/null +++ b/monkey/infection_monkey/readme.md @@ -0,0 +1,115 @@ +# Monkey island dev. env. setup guide + +>To easily setup development environment for Monkey Island and the Monkey look into [deployment scripts](../../deployment_scripts) folder. +>If you want to setup dev. env. for the Monkey manually, refer to the instructions below. + +The monkey is composed of three separate parts. + +- The Infection Monkey itself - PyInstaller compressed python archives +- Sambacry binaries - Two linux binaries, 32/64 bit. +- Mimikatz binaries - Two windows binaries, 32/64 bit. +- Traceroute binaries - Two linux binaries, 32/64bit. + +## Windows + +1. Install python 3.7.4 and choose **ADD to PATH** option when installing. + + Download and install from: + + In case you still need to add python directories to path: + - Run the following command on a cmd console (Replace C:\Python37 with your python directory if it's different) + `setx /M PATH "%PATH%;C:\Python37;C:\Python37\Scripts` + - Close the console, make sure you execute all commands in a new cmd console from now on. +2. Install further dependencies + - if not installed, install Microsoft Visual C++ 2017 SP1 Redistributable Package + - 32bit: + - 64bit: +3. Download the dependent python packages using + `pip install -r requirements.txt` +4. Download and extract UPX binary to monkey\infection_monkey\bin\upx.exe: + +5. Build/Download Sambacry and Mimikatz binaries + - Build/Download according to sections at the end of this readme. + - Place the binaries under monkey\infection_monkey\bin +6. To build the final exe: + - `cd monkey\infection_monkey` + - `build_windows.bat` + - `output is placed under dist\monkey.exe` + +## Linux + +Tested on Ubuntu 16.04. +0. On older distributions of Ubuntu (16.04) you'll need to download python3.7 via ppa: + - `sudo add-apt-repository ppa:deadsnakes/ppa` + - `sudo apt-get update` + - `sudo apt install python3.7` + +1. Install dependencies by running: + - `sudo apt install python3-pip` + - `python3.7 -m pip install pip` + - `sudo apt-get install python3.7-dev libffi-dev upx libssl-dev libc++1` + +2. Install the python packages listed in requirements.txt using pip + - `cd [code location]/infection_monkey` + - `python3.7 -m pip install -r requirements.txt` + +3. Build Sambacry binaries + - Build/Download according to sections at the end of this readme. + - Place the binaries under [code location]\infection_monkey\bin, under the names 'sc_monkey_runner32.so', 'sc_monkey_runner64.so' + +4. Build Traceroute binaries + - Build/Download according to sections at the end of this readme. + - Place the binaries under [code location]\infection_monkey\bin, under the names 'traceroute32', 'traceroute64' + +5. To build, run in terminal: + - `cd [code location]/infection_monkey` + - `chmod +x build_linux.sh` + - `./build_linux.sh` + + output is placed under dist/monkey + +### Sambacry + +Sambacry requires two standalone binaries to execute remotely. + +1. Build sambacry binaries yourself + - Install gcc-multilib if it's not installed `sudo apt-get install gcc-multilib` + - Build the binaries + 1. `cd [code location]/infection_monkey/exploit/sambacry_monkey_runner` + 2. `./build.sh` + +2. Download our pre-built sambacry binaries + - Available here: + - 32bit: + - 64bit: + +### Mimikatz + +Mimikatz is required for the Monkey to be able to steal credentials on Windows. It's possible to either compile binaries from source (requires Visual Studio 2013 and up) or download them from our repository. + +1. Build Mimikatz yourself + - Building mimikatz requires Visual Studio 2013 and up + - Clone our version of mimikatz from + - Build using Visual Studio. + - Put each version in a zip file + 1. The zip should contain only the Mimikatz DLL named tmpzipfile123456.dll + 2. It should be protected using the password 'VTQpsJPXgZuXhX6x3V84G'. + 3. The zip file should be named mk32.zip/mk64.zip accordingly. + 4. Zipping with 7zip has been tested. Other zipping software may not work. + +2. Download our pre-built mimikatz binaries + - Download both 32 and 64 bit zipped DLLs from + - Place them under [code location]\infection_monkey\bin + +### Traceroute + +Traceroute requires two standalone binaries to execute remotely. +The monkey carries the standalone binaries since traceroute isn't built in all Linux distributions. +You can either build them yourself or download pre-built binaries. + +1. Build traceroute yourself + - The sources of traceroute are available here with building instructions: +1. Download our pre-built traceroute binaries + - Available here: + - 32bit: + - 64bit: diff --git a/monkey/infection_monkey/readme.txt b/monkey/infection_monkey/readme.txt deleted file mode 100644 index 06bf449da..000000000 --- a/monkey/infection_monkey/readme.txt +++ /dev/null @@ -1,101 +0,0 @@ -To get development versions of Monkey Island and Monkey look into deployment scripts folder. -If you only want to build monkey from scratch you may reference instructions below. - -The monkey is composed of three separate parts. -* The Infection Monkey itself - PyInstaller compressed python archives -* Sambacry binaries - Two linux binaries, 32/64 bit. -* Mimikatz binaries - Two windows binaries, 32/64 bit. -* Traceroute binaries - Two linux binaries, 32/64bit. - ---- Windows --- - -1. Install python 2.7.15 - Download and install from: https://www.python.org/downloads/release/python-2715/ -2. Add python directories to PATH environment variable (if you didn't install ActiveState Python) - a. Run the following command on a cmd console (Replace C:\Python27 with your python directory if it's different) - setx /M PATH "%PATH%;C:\Python27;C:\Python27\Scripts - b. Close the console, make sure you execute all commands in a new cmd console from now on. -3. Install further dependencies - a. install VCForPython27.msi - https://aka.ms/vcpython27 - b. if not installed, install Microsoft Visual C++ 2010 SP1 Redistributable Package - 32bit: http://www.microsoft.com/en-us/download/details.aspx?id=8328 - 64bit: http://www.microsoft.com/en-us/download/details.aspx?id=13523 -4. Download the dependent python packages using - pip install -r requirements_windows.txt -5. Download and extract UPX binary to [source-path]\monkey\infection_monkey\bin\upx.exe: - https://github.com/upx/upx/releases/download/v3.94/upx394w.zip -6. Build/Download Sambacry and Mimikatz binaries - a. Build/Download according to sections at the end of this readme. - b. Place the binaries under [code location]\infection_monkey\bin -7. To build the final exe: - cd [code location]/infection_monkey - build_windows.bat - output is placed under dist\monkey.exe - ---- Linux --- - -Tested on Ubuntu 16.04 and 17.04. - -1. Install dependencies by running: - sudo apt-get update - sudo apt-get install python-pip python-dev libffi-dev upx libssl-dev libc++1 - Install the python packages listed in requirements.txt using pip - cd [code location]/infection_monkey - pip install -r requirements_linux.txt -2. Build Sambacry binaries - a. Build/Download according to sections at the end of this readme. - b. Place the binaries under [code location]\infection_monkey\bin, under the names 'sc_monkey_runner32.so', 'sc_monkey_runner64.so' -3. Build Traceroute binaries - a. Build/Download according to sections at the end of this readme. - b. Place the binaries under [code location]\infection_monkey\bin, under the names 'traceroute32', 'traceroute64' -4. To build, run in terminal: - cd [code location]/infection_monkey - chmod +x build_linux.sh - ./build_linux.sh - output is placed under dist/monkey - --- Sambacry -- - -Sambacry requires two standalone binaries to execute remotely. -a. Build sambacry binaries yourself - a.1. Install gcc-multilib if it's not installed - sudo apt-get install gcc-multilib - a.2. Build the binaries - cd [code location]/infection_monkey/exploit/sambacry_monkey_runner - ./build.sh - -b. Download our pre-built sambacry binaries - b.1. Available here: - 32bit: https://github.com/guardicore/monkey/releases/download/1.6/sc_monkey_runner32.so - 64bit: https://github.com/guardicore/monkey/releases/download/1.6/sc_monkey_runner64.so - --- Mimikatz -- - -Mimikatz is required for the Monkey to be able to steal credentials on Windows. It's possible to either compile binaries from source (requires Visual Studio 2013 and up) or download them from our repository. -a. Build Mimikatz yourself - a.0. Building mimikatz requires Visual Studio 2013 and up - a.1. Clone our version of mimikatz from https://github.com/guardicore/mimikatz/tree/1.1.0 - a.2. Build using Visual Studio. - a.3. Put each version in a zip file - a.3.1. The zip should contain only the Mimikatz DLL named tmpzipfile123456.dll - a.3.2. It should be protected using the password 'VTQpsJPXgZuXhX6x3V84G'. - a.3.3. The zip file should be named mk32.zip/mk64.zip accordingly. - a.3.4. Zipping with 7zip has been tested. Other zipping software may not work. - -b. Download our pre-built mimikatz binaries - b.1. Download both 32 and 64 bit zipped DLLs from https://github.com/guardicore/mimikatz/releases/tag/1.1.0 - b.2. Place them under [code location]\infection_monkey\bin - --- Traceroute -- - -Traceroute requires two standalone binaries to execute remotely. -The monkey carries the standalone binaries since traceroute isn't built in all Linux distributions. -You can either build them yourself or download pre-built binaries. - -a. Build traceroute yourself - a.1. The sources of traceroute are available here with building instructions: http://traceroute.sourceforge.net -b. Download our pre-built traceroute binaries - b.1. Available here: - 32bit: https://github.com/guardicore/monkey/releases/download/1.6/traceroute32 - 64bit: https://github.com/guardicore/monkey/releases/download/1.6/traceroute64 diff --git a/monkey/infection_monkey/requirements_linux.txt b/monkey/infection_monkey/requirements.txt similarity index 78% rename from monkey/infection_monkey/requirements_linux.txt rename to monkey/infection_monkey/requirements.txt index b32cbc883..93b3b4ca3 100644 --- a/monkey/infection_monkey/requirements_linux.txt +++ b/monkey/infection_monkey/requirements.txt @@ -10,5 +10,6 @@ ecdsa netifaces ipaddress wmi +pywin32 ; sys_platform == 'win32' pymssql<3.0 pyftpdlib diff --git a/monkey/infection_monkey/requirements_windows.txt b/monkey/infection_monkey/requirements_windows.txt deleted file mode 100644 index ceb298160..000000000 --- a/monkey/infection_monkey/requirements_windows.txt +++ /dev/null @@ -1,15 +0,0 @@ -impacket -pycryptodome -cffi -requests -odict -paramiko -psutil -PyInstaller -ecdsa -netifaces -ipaddress -wmi -pywin32 -pymssql<3.0 -pyftpdlib diff --git a/monkey/infection_monkey/system_info/windows_info_collector.py b/monkey/infection_monkey/system_info/windows_info_collector.py index 1419478db..857b42303 100644 --- a/monkey/infection_monkey/system_info/windows_info_collector.py +++ b/monkey/infection_monkey/system_info/windows_info_collector.py @@ -3,11 +3,15 @@ import logging import sys sys.coinit_flags = 0 # needed for proper destruction of the wmi python module - +# noinspection PyPep8 import infection_monkey.config +# noinspection PyPep8 from infection_monkey.system_info.mimikatz_collector import MimikatzCollector +# noinspection PyPep8 from infection_monkey.system_info import InfoCollector +# noinspection PyPep8 from infection_monkey.system_info.wmi_consts import WMI_CLASSES +# noinspection PyPep8 from common.utils.wmi_utils import WMIUtils LOG = logging.getLogger(__name__) diff --git a/monkey/infection_monkey/transport/tcp.py b/monkey/infection_monkey/transport/tcp.py index 22cff5d4a..9b017aa41 100644 --- a/monkey/infection_monkey/transport/tcp.py +++ b/monkey/infection_monkey/transport/tcp.py @@ -61,8 +61,8 @@ class TcpProxy(TransportProxyBase): except socket.timeout: continue + dest = socket.socket(socket.AF_INET, socket.SOCK_STREAM) try: - dest = socket.socket(socket.AF_INET, socket.SOCK_STREAM) dest.connect((self.dest_host, self.dest_port)) except socket.error as ex: source.close() diff --git a/monkey/infection_monkey/utils/plugins/plugin.py b/monkey/infection_monkey/utils/plugins/plugin.py index 21d3134bf..d80ebccc1 100644 --- a/monkey/infection_monkey/utils/plugins/plugin.py +++ b/monkey/infection_monkey/utils/plugins/plugin.py @@ -4,7 +4,7 @@ import logging from abc import ABCMeta, abstractmethod from os.path import dirname, basename, isfile, join import glob -from typing import Sequence, TypeVar, Type +from typing import Sequence, TypeVar, Type, Callable LOG = logging.getLogger(__name__) @@ -14,7 +14,7 @@ def _get_candidate_files(base_package_file): return [basename(f)[:-3] for f in files if isfile(f) and not f.endswith('__init__.py')] -Plugin_type = TypeVar('Plugin_type', bound='Plugin') +PluginType = TypeVar('PluginType', bound='Plugin') class Plugin(metaclass=ABCMeta): @@ -25,11 +25,11 @@ class Plugin(metaclass=ABCMeta): raise NotImplementedError() @classmethod - def get_instances(cls) -> Sequence[Type[Plugin_type]]: + def get_classes(cls) -> Sequence[Callable]: """ - Returns the type objects from base_package_spec. + Returns the class objects from base_package_spec base_package name and file must refer to the same package otherwise bad results - :return: A list of parent_class objects. + :return: A list of parent_class classes. """ objects = [] candidate_files = _get_candidate_files(cls.base_package_file()) @@ -47,13 +47,29 @@ class Plugin(metaclass=ABCMeta): LOG.debug("Checking if should run object {}".format(class_object.__name__)) try: if class_object.should_run(class_object.__name__): - instance = class_object() - objects.append(instance) + objects.append(class_object) LOG.debug("Added {} to list".format(class_object.__name__)) except Exception as e: LOG.warning("Exception {} when checking if {} should run".format(str(e), class_object.__name__)) return objects + @classmethod + def get_instances(cls) -> Sequence[Type[PluginType]]: + """ + Returns the type objects from base_package_spec. + base_package name and file must refer to the same package otherwise bad results + :return: A list of parent_class objects. + """ + class_objects = cls.get_classes() + instances = [] + for class_object in class_objects: + try: + instance = class_object() + instances.append(instance) + except Exception as e: + LOG.warning("Exception {} when initializing {}".format(str(e), class_object.__name__)) + return instances + @staticmethod @abstractmethod def base_package_file(): diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/BadImport.py b/monkey/infection_monkey/utils/plugins/pluginTests/BadImport.py new file mode 100644 index 000000000..ffd3ebb2d --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/pluginTests/BadImport.py @@ -0,0 +1,5 @@ +from infection_monkey.utils.plugins.pluginTests.PluginTestClass import TestPlugin # noqa: F401 + + +class SomeDummyPlugin: + pass diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/BadInit.py b/monkey/infection_monkey/utils/plugins/pluginTests/BadInit.py new file mode 100644 index 000000000..18e83c052 --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/pluginTests/BadInit.py @@ -0,0 +1,7 @@ +from infection_monkey.utils.plugins.pluginTests.PluginTestClass import TestPlugin + + +class BadPluginInit(TestPlugin): + + def __init__(self): + raise Exception("TestException") diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/ComboFile.py b/monkey/infection_monkey/utils/plugins/pluginTests/ComboFile.py new file mode 100644 index 000000000..2d73cd65b --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/pluginTests/ComboFile.py @@ -0,0 +1,15 @@ +from infection_monkey.utils.plugins.pluginTests.PluginTestClass import TestPlugin + + +class NoInheritance: + pass + + +class BadInit(TestPlugin): + + def __init__(self): + raise Exception("TestException") + + +class ProperClass(TestPlugin): + pass diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/PluginTestClass.py b/monkey/infection_monkey/utils/plugins/pluginTests/PluginTestClass.py new file mode 100644 index 000000000..a3785e875 --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/pluginTests/PluginTestClass.py @@ -0,0 +1,22 @@ +from infection_monkey.utils.plugins.plugin import Plugin +import infection_monkey.utils.plugins.pluginTests + + +class TestPlugin(Plugin): + classes_to_load = [] + + @staticmethod + def should_run(class_name): + """ + Decides if post breach action is enabled in config + :return: True if it needs to be ran, false otherwise + """ + return class_name in TestPlugin.classes_to_load + + @staticmethod + def base_package_file(): + return infection_monkey.utils.plugins.pluginTests.__file__ + + @staticmethod + def base_package_name(): + return infection_monkey.utils.plugins.pluginTests.__package__ diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/PluginWorking.py b/monkey/infection_monkey/utils/plugins/pluginTests/PluginWorking.py new file mode 100644 index 000000000..a3fe237b6 --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/pluginTests/PluginWorking.py @@ -0,0 +1,5 @@ +from infection_monkey.utils.plugins.pluginTests.PluginTestClass import TestPlugin + + +class PluginWorking(TestPlugin): + pass diff --git a/monkey/infection_monkey/utils/plugins/pluginTests/__init__.py b/monkey/infection_monkey/utils/plugins/pluginTests/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/monkey/infection_monkey/utils/plugins/plugin_test.py b/monkey/infection_monkey/utils/plugins/plugin_test.py new file mode 100644 index 000000000..7841c6c6a --- /dev/null +++ b/monkey/infection_monkey/utils/plugins/plugin_test.py @@ -0,0 +1,36 @@ +from unittest import TestCase + +from infection_monkey.utils.plugins.pluginTests.ComboFile import BadInit, ProperClass +from infection_monkey.utils.plugins.pluginTests.PluginWorking import PluginWorking +from infection_monkey.utils.plugins.pluginTests.BadImport import SomeDummyPlugin +from infection_monkey.utils.plugins.pluginTests.BadInit import BadPluginInit +from infection_monkey.utils.plugins.pluginTests.PluginTestClass import TestPlugin + + +class PluginTester(TestCase): + + def test_combo_file(self): + TestPlugin.classes_to_load = [BadInit.__name__, ProperClass.__name__] + to_init = TestPlugin.get_classes() + self.assertEqual(len(to_init), 2) + objects = TestPlugin.get_instances() + self.assertEqual(len(objects), 1) + + def test_bad_init(self): + TestPlugin.classes_to_load = [BadPluginInit.__name__] + to_init = TestPlugin.get_classes() + self.assertEqual(len(to_init), 1) + objects = TestPlugin.get_instances() + self.assertEqual(len(objects), 0) + + def test_bad_import(self): + TestPlugin.classes_to_load = [SomeDummyPlugin.__name__] + to_init = TestPlugin.get_classes() + self.assertEqual(len(to_init), 0) + + def test_flow(self): + TestPlugin.classes_to_load = [PluginWorking.__name__] + to_init = TestPlugin.get_classes() + self.assertEqual(len(to_init), 1) + objects = TestPlugin.get_instances() + self.assertEqual(len(objects), 1) diff --git a/monkey/monkey_island/cc/models/zero_trust/segmentation_finding.py b/monkey/monkey_island/cc/models/zero_trust/segmentation_finding.py index 7633ed31f..60262fbfd 100644 --- a/monkey/monkey_island/cc/models/zero_trust/segmentation_finding.py +++ b/monkey/monkey_island/cc/models/zero_trust/segmentation_finding.py @@ -17,7 +17,7 @@ class SegmentationFinding(Finding): """ Creates a segmentation finding. If a segmentation finding with the relevant subnets already exists, adds the event to the existing finding, and the "worst" status is chosen (i.e. if the existing one is "Failed" it will - remain so). + remain so). :param subnets: the 2 subnets of this finding. :param status: STATUS_PASSED or STATUS_FAILED diff --git a/monkey/monkey_island/cc/services/attack/attack_config.py b/monkey/monkey_island/cc/services/attack/attack_config.py index f834f259b..2830a2dc9 100644 --- a/monkey/monkey_island/cc/services/attack/attack_config.py +++ b/monkey/monkey_island/cc/services/attack/attack_config.py @@ -26,9 +26,9 @@ class AttackConfig(object): :return: Technique object or None if technique is not found """ attack_config = AttackConfig.get_config() - for key, attack_type in list(attack_config.items()): - for key, technique in list(attack_type['properties'].items()): - if key == technique_id: + for config_key, attack_type in list(attack_config.items()): + for type_key, technique in list(attack_type['properties'].items()): + if type_key == technique_id: return technique return None diff --git a/monkey/monkey_island/cc/services/telemetry/processing/system_info.py b/monkey/monkey_island/cc/services/telemetry/processing/system_info.py index ed1ea4e86..9ab0b45f0 100644 --- a/monkey/monkey_island/cc/services/telemetry/processing/system_info.py +++ b/monkey/monkey_island/cc/services/telemetry/processing/system_info.py @@ -33,8 +33,9 @@ def safe_process_telemetry(processing_function, telemetry_json): try: processing_function(telemetry_json) except Exception as err: - logger.error("Error while in {} stage of processing telemetry.".format(processing_function.func_name), - exc_info=True) + logger.error( + "Error {} while in {} stage of processing telemetry.".format(str(err), processing_function.func_name), + exc_info=True) def process_ssh_info(telemetry_json): diff --git a/monkey/monkey_island/linux/create_certificate.sh b/monkey/monkey_island/linux/create_certificate.sh index 0aae17558..72aace118 100644 --- a/monkey/monkey_island/linux/create_certificate.sh +++ b/monkey/monkey_island/linux/create_certificate.sh @@ -1,6 +1,6 @@ #!/bin/bash -cd /var/monkey/monkey_island -openssl genrsa -out cc/server.key 2048 -openssl req -new -key cc/server.key -out cc/server.csr -subj "/C=GB/ST=London/L=London/O=Global Security/OU=Monkey Department/CN=monkey.com" -openssl x509 -req -days 366 -in cc/server.csr -signkey cc/server.key -out cc/server.crt +openssl genrsa -out ./cc/server.key 2048 +openssl req -new -key ./cc/server.key -out ./cc/server.csr -subj "/OU=Monkey Department/CN=monkey.com" +openssl x509 -req -days 366 -in ./cc/server.csr -signkey ./cc/server.key -out ./cc/server.crt + diff --git a/monkey/monkey_island/readme.md b/monkey/monkey_island/readme.md new file mode 100644 index 000000000..e0c04e0bb --- /dev/null +++ b/monkey/monkey_island/readme.md @@ -0,0 +1,106 @@ +# Monkey island dev. env. setup guide + +>To easily setup development environment for Monkey Island and the Monkey look into [deployment scripts](../../deployment_scripts) folder. +>If you want to setup dev. env. for Island manually, refer to the instructions below. + +## How to set up the Monkey Island server + +### On Windows + +1. Exclude the folder you are planning to install the Monkey in from your AV software, as it might block or delete files from the installation. +2. Create folder "bin" under monkey\monkey_island +3. Place portable version of Python 3.7.4 + - Download and install from: +4. Install Island's requirements + - `python -m pip install -r monkey\monkey_island\requirements.txt` +4. Setup mongodb (Use one of the following two options): + - Place portable version of mongodb + 1. Download from: + 2. Extract contents of bin folder to \monkey\monkey_island\bin\mongodb. + 3. Create monkey_island\db folder. + + OR + - Use already running instance of mongodb + 1. Run 'set MONKEY_MONGO_URL="mongodb://:27017/monkeyisland"'. Replace '' with address of mongo server + +5. Place portable version of OpenSSL + - Download from: + - Extract contents to monkey_island\bin\openssl +6. Download and install Microsoft Visual C++ redistributable for Visual Studio 2017 + - Download and install from: +7. Generate SSL Certificate + - run `./windows/create_certificate.bat` when your current working directory is monkey_island +8. Put Infection Monkey binaries inside monkey_island/cc/binaries (binaries can be found in releases on github or build from source) + monkey-linux-64 - monkey binary for linux 64bit + monkey-linux-32 - monkey binary for linux 32bit + monkey-windows-32.exe - monkey binary for windows 32bit + monkey-windows-64.exe - monkey binary for windows 64bit +9. Install npm + - Download and install from: +10. Build Monkey Island frontend + - cd to 'monkey_island\cc\ui' + - run 'npm update' + - run 'npm run dist' + +#### How to run + +1. When your current working directory is monkey_island, run monkey_island\windows\run_server_py.bat + +### On Linux + +1. Get python 3.7 and pip if your linux distribution doesn't have it built in (following steps are for Ubuntu 16): + - `sudo add-apt-repository ppa:deadsnakes/ppa` + - `sudo apt-get update` + - `sudo apt install python3.7 python3-pip python3.7-dev` + - `python3.7 -m pip install pip` +2. Install required packages: + - `sudo apt-get install libffi-dev upx libssl-dev libc++1 openssl` +3. Create the following directories in monkey island folder (execute from ./monkey): + - `mkdir -p ./monkey_island/bin/mongodb` + - `mkdir -p ./monkey_island/db` + - `mkdir -p ./monkey_island/cc/binaries` + +4. Install the packages from monkey_island/requirements.txt: + - `sudo python3.7 -m pip install -r ./monkey_island/requirements.txt` + +5. Put monkey binaries in /monkey_island/cc/binaries (binaries can be found in releases on github). + + monkey-linux-64 - monkey binary for linux 64bit + + monkey-linux-32 - monkey binary for linux 32bit + + monkey-windows-32.exe - monkey binary for windows 32bit + + monkey-windows-64.exe - monkey binary for windows 64bit + + Also, if you're going to run monkeys on local machine execute: + - `chmod 755 ./monkey_island/cc/binaries/monkey-linux-64` + - `chmod 755 ./monkey_island/cc/binaries/monkey-linux-32` + +6. Setup MongoDB (Use one of the two following options): + - Download MongoDB and extract it to monkey/monkey_island/bin/mongodb: + 1. Run `./monkey_island/linux/install_mongo.sh ./monkey_island/bin/mongodb`. This will download and extract the relevant mongoDB for your OS. + + OR + - Use already running instance of mongodb + 1. Run `set MONKEY_MONGO_URL="mongodb://:27017/monkeyisland"`. Replace '' with address of mongo server + +7. Generate SSL Certificate: + - `cd ./monkey_island` + - `chmod 755 ./linux/create_certificate.sh` + - `./linux/create_certificate.sh` + +8. Install npm and node by running: + - `sudo apt-get install curl` + - `curl -sL https://deb.nodesource.com/setup_12.x | sudo -E bash -` + - `sudo apt-get install -y nodejs` + +9. Build Monkey Island frontend + - cd to 'monkey_island/cc/ui' + - `npm install sass-loader node-sass webpack --save-dev` + - `npm update` + - `npm run dist` + +#### How to run + +1. When your current working directory is monkey, run ./monkey_island/linux/run.sh (located under /linux) diff --git a/monkey/monkey_island/readme.txt b/monkey/monkey_island/readme.txt deleted file mode 100644 index 87b2f8c40..000000000 --- a/monkey/monkey_island/readme.txt +++ /dev/null @@ -1,91 +0,0 @@ -To get development versions of Monkey Island and Monkey look into deployment scripts folder. -If you only want to run the software from source you may refer to the instructions below. - -How to set up the Monkey Island server: - ----------------- On Windows ----------------: -0. Exclude the folder you are planning to install the Monkey in from your AV software, as it might block or delete files from the installation. -1. Create folder "bin" under monkey_island -2. Place portable version of Python 2.7.15 - 2.1. Download and install from: https://www.python.org/downloads/release/python-2715/ - 2.2. Install virtualenv using "python -m pip install virtualenv" - 2.3. Create a virtualenv using "python -m virtualenv --always-copy \Python27" Where is the path to the bin folder created on step 1. - 2.4. Run "python -m virtualenv --relocatable \Python27" - 2.5. Install the required python libraries using "\Python27\Scripts\python -m pip install -r monkey_island\requirements.txt" - 2.6. Copy DLLs from installation path (Usually C:\Python27\DLLs) to \Python27\DLLs - 2.7. (Optional) You may uninstall Python27 if you like. -3. Setup mongodb (Use one of the following two options): - 3.a Place portable version of mongodb - 3.a.1. Download from: https://downloads.mongodb.org/win32/mongodb-win32-x86_64-2008plus-ssl-latest.zip - 3.a.2. Extract contents from bin folder to monkey_island\bin\mongodb. - 3.a.3. Create monkey_island\db folder. - OR - 3.b. Use already running instance of mongodb - 3.b.1. Run 'set MONKEY_MONGO_URL="mongodb://:27017/monkeyisland"'. Replace '' with address of mongo server - -4. Place portable version of OpenSSL - 4.1. Download from: https://indy.fulgan.com/SSL/Archive/openssl-1.0.2l-i386-win32.zip - 4.2. Extract content from bin folder to monkey_island\bin\openssl -5. Download and install Microsoft Visual C++ redistributable for Visual Studio 2017 - 5.1. Download and install from: https://go.microsoft.com/fwlink/?LinkId=746572 -6. Generate SSL Certificate - 6.1. run create_certificate.bat when your current working directory is monkey_island -7. Create the monkey_island\cc\binaries folder and put Infection Monkey binaries inside - monkey-linux-64 - monkey binary for linux 64bit - monkey-linux-32 - monkey binary for linux 32bit - monkey-windows-32.exe - monkey binary for windows 32bit - monkey-windows-64.exe - monkey binary for windows 64bit -8. Install npm - 8.1. Download and install from: https://www.npmjs.com/get-npm -9. Build Monkey Island frontend - 9.1. cd to 'monkey_island\cc\ui' - 9.2. run 'npm update' - 9.3. run 'npm run dist' - -How to run: -1. When your current working directory is monkey_island, run monkey_island\windows\run_server.bat - ----------------- On Linux ----------------: -1. Create the following directories: - sudo mkdir /var/monkey_island - sudo chmod 777 /var/monkey_island - mkdir -p /var/monkey_island/bin/mongodb - mkdir -p /var/monkey_island/db - mkdir -p /var/monkey_island/cc/binaries - -2. Install the packages from monkey_island/requirements.txt: - sudo python -m pip install -r /var/monkey_island/requirements.txt - If pip is not installed, install the python-pip package. Make sure the server is running Python 2.7 and not Python 3+. - -3. put monkey binaries in /var/monkey_island/cc/binaries - monkey-linux-64 - monkey binary for linux 64bit - monkey-linux-32 - monkey binary for linux 32bit - monkey-windows-32.exe - monkey binary for windows 32bit - monkey-windows-64.exe - monkey binary for windows 64bi - -4. Setup MongoDB (Use one of the two following options): - 4.a. Download MongoDB and extract it to /var/monkey_island/bin/mongodb - 4.a.1. Run '/var/monkey_island/linux/install_mongo.sh /var/monkey_island/bin/mongodb' - This will download and extract the relevant mongoDB for your OS. - OR - 4.b. Use already running instance of mongodb - 4.b.1. Run 'set MONKEY_MONGO_URL="mongodb://:27017/monkeyisland"'. Replace '' with address of mongo server - -5. install OpenSSL - sudo apt-get install openssl - -6. Generate SSL Certificate, Run create_certificate.sh (located under /linux) - -7. Copy monkey island server to /var/monkey_island: - cp -r [monkey_island_source]/cc /var/monkey_island/ - -8. Install npm - 8.1. Download and install from: https://www.npmjs.com/get-npm - -9. Build Monkey Island frontend - 9.1. cd to 'monkey_island/cc/ui' - 9.2. run 'npm update' - 9.3. run 'npm run dist' - -How to run: -1. When your current working directory is monkey, run ./monkey_island/linux/run.sh (located under /linux) diff --git a/monkey/monkey_island/windows/create_certificate.bat b/monkey/monkey_island/windows/create_certificate.bat index 0af3e9960..645c6fa25 100644 --- a/monkey/monkey_island/windows/create_certificate.bat +++ b/monkey/monkey_island/windows/create_certificate.bat @@ -14,5 +14,5 @@ copy "%mydir%windows\openssl.cfg" "%mydir%bin\openssl\openssl.cfg" @echo on "%mydir%bin\openssl\openssl.exe" genrsa -out "%mydir%cc\server.key" 1024 -"%mydir%bin\openssl\openssl.exe" req -new -config "%mydir%bin\openssl\openssl.cfg" -key "%mydir%cc\server.key" -out "%mydir%cc\server.csr" -subj "/C=GB/ST=London/L=London/O=Global Security/OU=Monkey Department/CN=monkey.com" -"%mydir%bin\openssl\openssl.exe" x509 -req -days 366 -in "%mydir%cc\server.csr" -signkey "%mydir%cc\server.key" -out "%mydir%cc\server.crt" \ No newline at end of file +"%mydir%bin\openssl\openssl.exe" req -new -config "%mydir%bin\openssl\openssl.cfg" -key "%mydir%cc\server.key" -out "%mydir%cc\server.csr" -subj "/OU=Monkey Department/CN=monkey.com" +"%mydir%bin\openssl\openssl.exe" x509 -req -days 366 -in "%mydir%cc\server.csr" -signkey "%mydir%cc\server.key" -out "%mydir%cc\server.crt" diff --git a/monkey/monkey_island/windows/run_cc.bat b/monkey/monkey_island/windows/run_cc.bat index c1a2fd88e..c87f04cec 100644 --- a/monkey/monkey_island/windows/run_cc.bat +++ b/monkey/monkey_island/windows/run_cc.bat @@ -1,5 +1,5 @@ REM - Runs Monkey Island Server using python - @title C^&C Server @pushd .. -@monkey_island\bin\Python27\Scripts\python monkey_island.py -@popd \ No newline at end of file +@python monkey_island.py +@popd