Ejemplo n.º 1
0
 def get_config_ips():
     if ConfigService.get_config_value(
         ['basic_network', 'network_range', 'range_class'],
             True) != 'FixedRange':
         return []
     return ConfigService.get_config_value(
         ['basic_network', 'network_range', 'range_fixed'], True)
Ejemplo n.º 2
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url
    mongo.init_app(app)

    with app.app_context():
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file', serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/', '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/', '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration', '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download', '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')

    return app
Ejemplo n.º 3
0
    def get(self, action=None):
        if not action:
            action = request.args.get('action')

        if not action:
            return jsonify(ip_addresses=local_ip_addresses(),
                           mongo=str(mongo.db),
                           completed_steps=self.get_completed_steps())

        elif action == "reset":
            mongo.db.config.drop()
            mongo.db.monkey.drop()
            mongo.db.telemetry.drop()
            mongo.db.node.drop()
            mongo.db.edge.drop()
            ConfigService.init_config()
            return jsonify(status='OK')
        elif action == "killall":
            mongo.db.monkey.update({'dead': False}, {
                '$set': {
                    'config.alive': False,
                    'modifytime': datetime.now()
                }
            },
                                   upsert=False,
                                   multi=True)
            return jsonify(status='OK')
        else:
            return make_response(400, {'error': 'unknown action'})
Ejemplo n.º 4
0
 def post(self):
     config_json = json.loads(request.data)
     if config_json.has_key('reset'):
         ConfigService.reset_config()
     else:
         ConfigService.update_config(config_json, should_encrypt=True)
     return self.get()
Ejemplo n.º 5
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url
    mongo.init_app(app)

    with app.app_context():
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file', serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/', '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/', '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration', '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download', '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')
    api.add_resource(Report, '/api/report', '/api/report/')
    api.add_resource(TelemetryFeed, '/api/telemetry-feed', '/api/telemetry-feed/')

    return app
Ejemplo n.º 6
0
 def post(self):
     config_json = json.loads(request.data)
     if config_json.has_key('reset'):
         ConfigService.reset_config()
     else:
         ConfigService.update_config(config_json, should_encrypt=True)
     return self.get()
Ejemplo n.º 7
0
 def reset_db():
     [
         mongo.db[x].drop() for x in
         ['config', 'monkey', 'telemetry', 'node', 'edge', 'report']
     ]
     ConfigService.init_config()
     return jsonify(status='OK')
Ejemplo n.º 8
0
 def add_system_info_ssh_keys_to_config(ssh_info):
     for user in ssh_info:
         ConfigService.creds_add_username(user['name'])
         # Public key is useless without private key
         if user['public_key'] and user['private_key']:
             ConfigService.ssh_add_keys(user['public_key'], user['private_key'],
                                        user['name'], user['ip'])
Ejemplo n.º 9
0
 def post(self):
     config_json = json.loads(request.data)
     if 'reset' in config_json:
         ConfigService.reset_config()
     else:
         if not ConfigService.update_config(config_json, should_encrypt=True):
             abort(400)
     return self.get()
Ejemplo n.º 10
0
 def reset_db():
     # We can't drop system collections.
     [
         mongo.db[x].drop() for x in mongo.db.collection_names()
         if not x.startswith('system.')
     ]
     ConfigService.init_config()
     return jsonify(status='OK')
Ejemplo n.º 11
0
    def get_config_exploits():
        exploits_config_value = ['exploits', 'general', 'exploiter_classes']
        default_exploits = ConfigService.get_default_config()
        for namespace in exploits_config_value:
            default_exploits = default_exploits[namespace]
        exploits = ConfigService.get_config_value(exploits_config_value, True)

        if exploits == default_exploits:
            return ['default']

        return [ReportService.EXPLOIT_DISPLAY_DICT[exploit] for exploit in
                exploits]
Ejemplo n.º 12
0
    def get_config_exploits():
        exploits_config_value = ['exploits', 'general', 'exploiter_classes']
        default_exploits = ConfigService.get_default_config()
        for namespace in exploits_config_value:
            default_exploits = default_exploits[namespace]
        exploits = ConfigService.get_config_value(exploits_config_value, True)

        if exploits == default_exploits:
            return ['default']

        return [
            ReportService.EXPLOIT_DISPLAY_DICT[exploit] for exploit in exploits
        ]
Ejemplo n.º 13
0
 def add_system_info_creds_to_config(creds):
     for user in creds:
         ConfigService.creds_add_username(user)
         if 'password' in creds[user]:
             ConfigService.creds_add_password(creds[user]['password'])
         if 'lm_hash' in creds[user]:
             ConfigService.creds_add_lm_hash(creds[user]['lm_hash'])
         if 'ntlm_hash' in creds[user]:
             ConfigService.creds_add_ntlm_hash(creds[user]['ntlm_hash'])
Ejemplo n.º 14
0
 def add_system_info_creds_to_config(creds):
     for user in creds:
         ConfigService.creds_add_username(user)
         if 'password' in creds[user]:
             ConfigService.creds_add_password(creds[user]['password'])
         if 'lm_hash' in creds[user]:
             ConfigService.creds_add_lm_hash(creds[user]['lm_hash'])
         if 'ntlm_hash' in creds[user]:
             ConfigService.creds_add_ntlm_hash(creds[user]['ntlm_hash'])
Ejemplo n.º 15
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url

    app.config['SECRET_KEY'] = os.urandom(32)
    app.config['JWT_AUTH_URL_RULE'] = '/api/auth'
    app.config['JWT_EXPIRATION_DELTA'] = env.get_auth_expiration_time()

    init_jwt(app)
    mongo.init_app(app)

    with app.app_context():
        database.init()
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file',
                     serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/',
                     '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/',
                     '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration',
                     '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download',
                     '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')
    api.add_resource(Report, '/api/report', '/api/report/')
    api.add_resource(TelemetryFeed, '/api/telemetry-feed',
                     '/api/telemetry-feed/')
    api.add_resource(Log, '/api/log', '/api/log/')
    api.add_resource(IslandLog, '/api/log/island/download',
                     '/api/log/island/download/')

    return app
Ejemplo n.º 16
0
    def update_aws_auth_params():
        """
        Updates the AWS authentication parameters according to config
        :return: True if new params allow successful authentication. False otherwise
        """
        access_key_id = ConfigService.get_config_value(
            ['cnc', 'aws_config', 'aws_access_key_id'], False, True)
        secret_access_key = ConfigService.get_config_value(
            ['cnc', 'aws_config', 'aws_secret_access_key'], False, True)

        if (access_key_id != AwsService.access_key_id) or (
                secret_access_key != AwsService.secret_access_key):
            AwsService.set_auth_params(access_key_id, secret_access_key)
            RemoteRunAwsService.is_auth = AwsService.test_client()

        AwsService.set_region(RemoteRunAwsService.aws_instance.region)

        return RemoteRunAwsService.is_auth
Ejemplo n.º 17
0
 def process_system_info_telemetry(telemetry_json):
     if 'credentials' in telemetry_json['data']:
         creds = telemetry_json['data']['credentials']
         for user in creds:
             ConfigService.creds_add_username(user)
             if 'password' in creds[user]:
                 ConfigService.creds_add_password(creds[user]['password'])
             if 'lm_hash' in creds[user]:
                 ConfigService.creds_add_lm_hash(creds[user]['lm_hash'])
             if 'ntlm_hash' in creds[user]:
                 ConfigService.creds_add_ntlm_hash(creds[user]['ntlm_hash'])
Ejemplo n.º 18
0
    def get(self, guid=None, **kw):
        NodeService.update_dead_monkeys()  # refresh monkeys status
        if not guid:
            guid = request.args.get('guid')

        if guid:
            monkey_json = mongo.db.monkey.find_one_or_404({"guid": guid})
            monkey_json['config'] = ConfigService.decrypt_flat_config(monkey_json['config'])
            return monkey_json

        return {}
Ejemplo n.º 19
0
def init_app(mongo_url):
    app = Flask(__name__)

    api = flask_restful.Api(app)
    api.representations = {'application/json': output_json}

    app.config['MONGO_URI'] = mongo_url

    app.config['SECRET_KEY'] = os.urandom(32)
    app.config['JWT_AUTH_URL_RULE'] = '/api/auth'
    app.config['JWT_EXPIRATION_DELTA'] = env.get_auth_expiration_time()

    init_jwt(app)
    mongo.init_app(app)

    with app.app_context():
        database.init()
        ConfigService.init_config()

    app.add_url_rule('/', 'serve_home', serve_home)
    app.add_url_rule('/<path:static_path>', 'serve_static_file', serve_static_file)

    api.add_resource(Root, '/api')
    api.add_resource(Monkey, '/api/monkey', '/api/monkey/', '/api/monkey/<string:guid>')
    api.add_resource(LocalRun, '/api/local-monkey', '/api/local-monkey/')
    api.add_resource(ClientRun, '/api/client-monkey', '/api/client-monkey/')
    api.add_resource(Telemetry, '/api/telemetry', '/api/telemetry/', '/api/telemetry/<string:monkey_guid>')
    api.add_resource(MonkeyConfiguration, '/api/configuration', '/api/configuration/')
    api.add_resource(MonkeyDownload, '/api/monkey/download', '/api/monkey/download/',
                     '/api/monkey/download/<string:path>')
    api.add_resource(NetMap, '/api/netmap', '/api/netmap/')
    api.add_resource(Edge, '/api/netmap/edge', '/api/netmap/edge/')
    api.add_resource(Node, '/api/netmap/node', '/api/netmap/node/')
    api.add_resource(Report, '/api/report', '/api/report/')
    api.add_resource(TelemetryFeed, '/api/telemetry-feed', '/api/telemetry-feed/')
    api.add_resource(Log, '/api/log', '/api/log/')

    return app
Ejemplo n.º 20
0
    def process_system_info_telemetry(telemetry_json):
        if 'credentials' in telemetry_json['data']:
            creds = telemetry_json['data']['credentials']
            for user in creds:
                ConfigService.creds_add_username(user)
                if 'password' in creds[user]:
                    ConfigService.creds_add_password(creds[user]['password'])
                if 'lm_hash' in creds[user]:
                    ConfigService.creds_add_lm_hash(creds[user]['lm_hash'])
                if 'ntlm_hash' in creds[user]:
                    ConfigService.creds_add_ntlm_hash(creds[user]['ntlm_hash'])

            for user in creds:
                if -1 != user.find('.'):
                    new_user = user.replace('.', ',')
                    creds[new_user] = creds.pop(user)
Ejemplo n.º 21
0
    def get_cross_segment_issues():
        scans = mongo.db.telemetry.find({'telem_type': 'scan'}, {
            'monkey_guid': 1,
            'data.machine.ip_addr': 1,
            'data.machine.services': 1
        })

        cross_segment_issues = []

        # For now the feature is limited to 1 group.
        subnet_groups = [
            ConfigService.get_config_value(
                ['basic_network', 'network_analysis', 'inaccessible_subnets'])
        ]

        for subnet_group in subnet_groups:
            cross_segment_issues += ReportService.get_cross_segment_issues_per_subnet_group(
                scans, subnet_group)

        return cross_segment_issues
Ejemplo n.º 22
0
 def get_config_users():
     return ConfigService.get_config_value(['basic', 'credentials', 'exploit_user_list'], True)
Ejemplo n.º 23
0
 def get_config_passwords():
     return ConfigService.get_config_value(['basic', 'credentials', 'exploit_password_list'], True)
Ejemplo n.º 24
0
    def _get_aws_keys():
        creds_dict = {}
        for key in AWS_CRED_CONFIG_KEYS:
            creds_dict[key[2]] = str(ConfigService.get_config_value(key))

        return creds_dict
Ejemplo n.º 25
0
 def get_config_ips():
     if ConfigService.get_config_value(['basic_network', 'network_range', 'range_class'], True) != 'FixedRange':
         return []
     return ConfigService.get_config_value(['basic_network', 'network_range', 'range_fixed'], True)
Ejemplo n.º 26
0
 def get_config_scan():
     return ConfigService.get_config_value(['basic_network', 'general', 'local_network_scan'], True)
Ejemplo n.º 27
0
    def post(self, **kw):
        monkey_json = json.loads(request.data)
        monkey_json['creds'] = []
        monkey_json['dead'] = False
        if 'keepalive' in monkey_json:
            monkey_json['keepalive'] = dateutil.parser.parse(
                monkey_json['keepalive'])
        else:
            monkey_json['keepalive'] = datetime.now()

        monkey_json['modifytime'] = datetime.now()

        ConfigService.save_initial_config_if_needed()

        # if new monkey telem, change config according to "new monkeys" config.
        db_monkey = mongo.db.monkey.find_one({"guid": monkey_json["guid"]})
        if not db_monkey:
            new_config = ConfigService.get_flat_config(False, True)
            monkey_json['config'] = monkey_json.get('config', {})
            monkey_json['config'].update(new_config)
        else:
            db_config = db_monkey.get('config', {})
            if 'current_server' in db_config:
                del db_config['current_server']
            monkey_json.get('config', {}).update(db_config)

        # try to find new monkey parent
        parent = monkey_json.get('parent')
        parent_to_add = (monkey_json.get('guid'), None
                         )  # default values in case of manual run
        if parent and parent != monkey_json.get(
                'guid'):  # current parent is known
            exploit_telem = [
                x for x in mongo.db.telemetry.find({
                    'telem_type': {
                        '$eq': 'exploit'
                    },
                    'data.result': {
                        '$eq': True
                    },
                    'data.machine.ip_addr': {
                        '$in': monkey_json['ip_addresses']
                    },
                    'monkey_guid': {
                        '$eq': parent
                    }
                })
            ]
            if 1 == len(exploit_telem):
                parent_to_add = (exploit_telem[0].get('monkey_guid'),
                                 exploit_telem[0].get('data').get('exploiter'))
            else:
                parent_to_add = (parent, None)
        elif (not parent or parent
              == monkey_json.get('guid')) and 'ip_addresses' in monkey_json:
            exploit_telem = [
                x for x in mongo.db.telemetry.find({
                    'telem_type': {
                        '$eq': 'exploit'
                    },
                    'data.result': {
                        '$eq': True
                    },
                    'data.machine.ip_addr': {
                        '$in': monkey_json['ip_addresses']
                    }
                })
            ]

            if 1 == len(exploit_telem):
                parent_to_add = (exploit_telem[0].get('monkey_guid'),
                                 exploit_telem[0].get('data').get('exploiter'))

        if not db_monkey:
            monkey_json['parent'] = [parent_to_add]
        else:
            monkey_json['parent'] = db_monkey.get('parent') + [parent_to_add]

        tunnel_host_ip = None
        if 'tunnel' in monkey_json:
            tunnel_host_ip = monkey_json['tunnel'].split(":")[-2].replace(
                "//", "")
            monkey_json.pop('tunnel')

        mongo.db.monkey.update({"guid": monkey_json["guid"]},
                               {"$set": monkey_json},
                               upsert=True)

        # Merge existing scanned node with new monkey

        new_monkey_id = mongo.db.monkey.find_one({"guid":
                                                  monkey_json["guid"]})["_id"]

        if tunnel_host_ip is not None:
            NodeService.set_monkey_tunnel(new_monkey_id, tunnel_host_ip)

        existing_node = mongo.db.node.find_one(
            {"ip_addresses": {
                "$in": monkey_json["ip_addresses"]
            }})

        if existing_node:
            node_id = existing_node["_id"]
            for edge in mongo.db.edge.find({"to": node_id}):
                mongo.db.edge.update({"_id": edge["_id"]},
                                     {"$set": {
                                         "to": new_monkey_id
                                     }})
            for creds in existing_node['creds']:
                NodeService.add_credentials_to_monkey(new_monkey_id, creds)
            mongo.db.node.remove({"_id": node_id})

        return {"id": new_monkey_id}
Ejemplo n.º 28
0
 def get_config_scan():
     return ConfigService.get_config_value(
         ['basic_network', 'general', 'local_network_scan'], True)
Ejemplo n.º 29
0
 def get(self):
     return jsonify(schema=ConfigService.get_config_schema(), configuration=ConfigService.get_config(False, True))
Ejemplo n.º 30
0
 def reset_db():
     # We can't drop system collections.
     [mongo.db[x].drop() for x in mongo.db.collection_names() if not x.startswith('system.')]
     ConfigService.init_config()
     return jsonify(status='OK')
Ejemplo n.º 31
0
 def get_config_passwords():
     return ConfigService.get_config_value(
         ['basic', 'credentials', 'exploit_password_list'], True)
Ejemplo n.º 32
0
 def get_config_users():
     return ConfigService.get_config_value(
         ['basic', 'credentials', 'exploit_user_list'], True)
Ejemplo n.º 33
0
 def get_config_ips():
     return ConfigService.get_config_value(
         ['basic_network', 'general', 'subnet_scan_list'], True, True)
Ejemplo n.º 34
0
    def post(self, **kw):
        monkey_json = json.loads(request.data)
        monkey_json['creds'] = []
        monkey_json['dead'] = False
        if 'keepalive' in monkey_json:
            monkey_json['keepalive'] = dateutil.parser.parse(monkey_json['keepalive'])
        else:
            monkey_json['keepalive'] = datetime.now()

        monkey_json['modifytime'] = datetime.now()

        ConfigService.save_initial_config_if_needed()

        # if new monkey telem, change config according to "new monkeys" config.
        db_monkey = mongo.db.monkey.find_one({"guid": monkey_json["guid"]})
        if not db_monkey:
            # we pull it encrypted because we then decrypt it for the monkey in get
            new_config = ConfigService.get_flat_config(False, False)
            monkey_json['config'] = monkey_json.get('config', {})
            monkey_json['config'].update(new_config)
        else:
            db_config = db_monkey.get('config', {})
            if 'current_server' in db_config:
                del db_config['current_server']
            monkey_json.get('config', {}).update(db_config)

        # try to find new monkey parent
        parent = monkey_json.get('parent')
        parent_to_add = (monkey_json.get('guid'), None)  # default values in case of manual run
        if parent and parent != monkey_json.get('guid'):  # current parent is known
            exploit_telem = [x for x in
                             mongo.db.telemetry.find({'telem_type': {'$eq': 'exploit'}, 'data.result': {'$eq': True},
                                                      'data.machine.ip_addr': {'$in': monkey_json['ip_addresses']},
                                                      'monkey_guid': {'$eq': parent}})]
            if 1 == len(exploit_telem):
                parent_to_add = (exploit_telem[0].get('monkey_guid'), exploit_telem[0].get('data').get('exploiter'))
            else:
                parent_to_add = (parent, None)
        elif (not parent or parent == monkey_json.get('guid')) and 'ip_addresses' in  monkey_json:
            exploit_telem = [x for x in
                             mongo.db.telemetry.find({'telem_type': {'$eq': 'exploit'}, 'data.result': {'$eq': True},
                                                      'data.machine.ip_addr': {'$in': monkey_json['ip_addresses']}})]

            if 1 == len(exploit_telem):
                parent_to_add = (exploit_telem[0].get('monkey_guid'), exploit_telem[0].get('data').get('exploiter'))

        if not db_monkey:
            monkey_json['parent'] = [parent_to_add]
        else:
            monkey_json['parent'] = db_monkey.get('parent') + [parent_to_add]

        tunnel_host_ip = None
        if 'tunnel' in monkey_json:
            tunnel_host_ip = monkey_json['tunnel'].split(":")[-2].replace("//", "")
            monkey_json.pop('tunnel')

        mongo.db.monkey.update({"guid": monkey_json["guid"]},
                               {"$set": monkey_json},
                               upsert=True)

        # Merge existing scanned node with new monkey

        new_monkey_id = mongo.db.monkey.find_one({"guid": monkey_json["guid"]})["_id"]

        if tunnel_host_ip is not None:
            NodeService.set_monkey_tunnel(new_monkey_id, tunnel_host_ip)

        existing_node = mongo.db.node.find_one({"ip_addresses": {"$in": monkey_json["ip_addresses"]}})

        if existing_node:
            node_id = existing_node["_id"]
            for edge in mongo.db.edge.find({"to": node_id}):
                mongo.db.edge.update({"_id": edge["_id"]}, {"$set": {"to": new_monkey_id}})
            for creds in existing_node['creds']:
                NodeService.add_credentials_to_monkey(new_monkey_id, creds)
            mongo.db.node.remove({"_id": node_id})

        return {"id": new_monkey_id}
Ejemplo n.º 35
0
 def get(self):
     return jsonify(schema=ConfigService.get_config_schema(),
                    configuration=ConfigService.get_config(False, True))
Ejemplo n.º 36
0
 def reset_db():
     [mongo.db[x].drop() for x in ['config', 'monkey', 'telemetry', 'node', 'edge', 'report']]
     ConfigService.init_config()
     return jsonify(status='OK')