index
int64
0
50.7k
project_path
stringclasses
279 values
completion_path
stringlengths
57
199
signature_postion
stringlengths
3
11
class_position
stringlengths
3
11
function_name
stringlengths
1
62
class_name
stringlengths
0
55
body_position
stringlengths
3
11
body_position_with_comments
stringlengths
3
11
masked_class
stringlengths
14
8.32k
masked_class_with_comment
stringlengths
14
8.32k
func_body
stringlengths
9
6.72k
func_body_with_comment
stringlengths
9
6.72k
len_func_body
int64
1
643
len_input
int64
10
2.02k
len_output
int64
4
1.9k
total
int64
20
2.05k
file_code
stringlengths
14
442k
file_code_with_comment
stringlengths
14
442k
38,047
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/obfuscator_api.py
21,28
10,47
get_obfuscators
ObfuscatorApi
28,31
28,31
class ObfuscatorApi(BaseObjectApi): def __init__(self, services): super().__init__(description='obfuscator', obj_class=Obfuscator, schema=ObfuscatorSchema, ram_key='obfuscators', id_property='name', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=s...
class ObfuscatorApi(BaseObjectApi): def __init__(self, services): super().__init__(description='obfuscator', obj_class=Obfuscator, schema=ObfuscatorSchema, ram_key='obfuscators', id_property='name', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=s...
sources = await self.get_all_objects(request) return web.json_response(sources)
sources = await self.get_all_objects(request) return web.json_response(sources)
6
582
30
612
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_obfuscator import Obfuscator, Obfuscat...
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_obfuscator import Obfuscator, Obfuscat...
38,048
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/objective_api.py
61,76
10,98
update_objective
ObjectiveApi
76,79
76,79
class ObjectiveApi(BaseObjectApi): def __init__(self, services): super().__init__(description='objective', obj_class=Objective, schema=ObjectiveSchema, ram_key='objectives', id_property='id', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services...
class ObjectiveApi(BaseObjectApi): def __init__(self, services): super().__init__(description='objective', obj_class=Objective, schema=ObjectiveSchema, ram_key='objectives', id_property='id', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services...
objective = await self.update_on_disk_object(request) return web.json_response(objective.display)
objective = await self.update_on_disk_object(request) return web.json_response(objective.display)
6
1,299
35
1,334
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_objective import Objective, ObjectiveS...
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_objective import Objective, ObjectiveS...
38,050
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/planner_api.py
33,50
10,52
get_planner_by_id
PlannerApi
50,52
50,52
class PlannerApi(BaseObjectApi): def __init__(self, services): super().__init__(description='planner', obj_class=Planner, schema=PlannerSchema, ram_key='planners', id_property='planner_id', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services['...
class PlannerApi(BaseObjectApi): def __init__(self, services): super().__init__(description='planner', obj_class=Planner, schema=PlannerSchema, ram_key='planners', id_property='planner_id', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services['...
planner = await self.get_object(request) return web.json_response(planner)
planner = await self.get_object(request) return web.json_response(planner)
6
667
28
695
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_planner import Planner, PlannerSchema ...
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_planner import Planner, PlannerSchema ...
38,051
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/handlers/plugins_api.py
16,17
10,49
add_routes
PluginApi
17,21
17,21
class PluginApi(BaseObjectApi): def __init__(self, services): super().__init__(description='plugins', obj_class=Plugin, schema=PluginSchema, ram_key='plugins', id_property='name', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services['data_svc']...
class PluginApi(BaseObjectApi): def __init__(self, services): super().__init__(description='plugins', obj_class=Plugin, schema=PluginSchema, ram_key='plugins', id_property='name', auth_svc=services['auth_svc']) self._api_manager = BaseApiManager(data_svc=services['data_svc']...
router = app.router router.add_get('/plugins', self.get_plugins) router.add_get('/plugins/{name}', self.get_plugin_by_name)
router = app.router router.add_get('/plugins', self.get_plugins) router.add_get('/plugins/{name}', self.get_plugin_by_name)
7
562
51
613
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_plugin import Plugin, PluginSchema c...
import aiohttp_apispec from aiohttp import web from app.api.v2.handlers.base_object_api import BaseObjectApi from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.schemas.base_schemas import BaseGetAllQuerySchema, BaseGetOneQuerySchema from app.objects.c_plugin import Plugin, PluginSchema c...
38,052
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/managers/ability_api_manager.py
53,54
14,98
_validate_ability_data
AbilityApiManager
54,87
54,87
class AbilityApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def create_on_disk_object(self, data: dict, access: dict, ram_key: str, id_property: str, obj_class: type): self._validate_ability_data(create=True, data...
class AbilityApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def create_on_disk_object(self, data: dict, access: dict, ram_key: str, id_property: str, obj_class: type): self._validate_ability_data(create=True, data...
# Correct ability_id key for ability file saving. data['id'] = data.pop('ability_id', '') # If a new ability is being created, ensure required fields present. if create: # Set ability ID if undefined if not data['id']: data['id'] = str(uuid.uuid4(...
# Correct ability_id key for ability file saving. data['id'] = data.pop('ability_id', '') # If a new ability is being created, ensure required fields present. if create: # Set ability ID if undefined if not data['id']: data['id'] = str(uuid.uuid4(...
178
1,054
520
1,574
import re import uuid import os import yaml from typing import Any from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.responses import JsonHttpBadRequest from app.objects.c_ability import AbilitySchema from app.utility.base_world import BaseWorld class AbilityApiManager(BaseApiManager):...
import re import uuid import os import yaml from typing import Any from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.responses import JsonHttpBadRequest from app.objects.c_ability import AbilitySchema from app.utility.base_world import BaseWorld class AbilityApiManager(BaseApiManager):...
38,053
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/managers/adversary_api_manager.py
9,10
5,13
verify_adversary
AdversaryApiManager
10,13
10,13
class AdversaryApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def verify_adversary(self, adversary: Adversary): FILL_FUNC_BODY
class AdversaryApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def verify_adversary(self, adversary: Adversary): FILL_FUNC_BODY
adversary.verify(log=self.log, abilities=self._data_svc.ram['abilities'], objectives=self._data_svc.ram['objectives']) return adversary
adversary.verify(log=self.log, abilities=self._data_svc.ram['abilities'], objectives=self._data_svc.ram['objectives']) return adversary
5
87
51
138
from app.api.v2.managers.base_api_manager import BaseApiManager from app.objects.c_adversary import Adversary class AdversaryApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def verify_adversary(self, adversary: Adversary...
from app.api.v2.managers.base_api_manager import BaseApiManager from app.objects.c_adversary import Adversary class AdversaryApiManager(BaseApiManager): def __init__(self, data_svc, file_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) async def verify_adversary(self, adversary: Adversary...
38,055
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/managers/contact_api_manager.py
10,11
5,18
get_contact_report
ContactApiManager
11,16
11,16
class ContactApiManager(BaseApiManager): def __init__(self, data_svc, file_svc, contact_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) self.contact_svc = contact_svc def get_contact_report(self, contact: str = None): FILL_FUNC_BODY def get_available_contact_reports(self): ...
class ContactApiManager(BaseApiManager): def __init__(self, data_svc, file_svc, contact_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) self.contact_svc = contact_svc def get_contact_report(self, contact: str = None): FILL_FUNC_BODY def get_available_contact_reports(self): ...
contact = contact.upper() if contact in self.contact_svc.report: return self.contact_svc.report.get(contact) raise JsonHttpNotFound(f'Contact not found: {contact}')
contact = contact.upper() if contact in self.contact_svc.report: return self.contact_svc.report.get(contact) raise JsonHttpNotFound(f'Contact not found: {contact}')
14
131
61
192
from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.responses import JsonHttpNotFound class ContactApiManager(BaseApiManager): def __init__(self, data_svc, file_svc, contact_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) self.contact_svc = contact_svc ...
from app.api.v2.managers.base_api_manager import BaseApiManager from app.api.v2.responses import JsonHttpNotFound class ContactApiManager(BaseApiManager): def __init__(self, data_svc, file_svc, contact_svc): super().__init__(data_svc=data_svc, file_svc=file_svc) self.contact_svc = contact_svc ...
38,056
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/managers/schedule_api_manager.py
29,30
8,36
_merge_dictionaries
ScheduleApiManager
30,36
30,36
class ScheduleApiManager(OperationApiManager): def __init__(self, services): super().__init__(services) self.services = services def find_and_update_object(self, ram_key: str, data: dict, search: dict = None): return super(OperationApiManager, self).find_and_update_object(ram_key, data,...
class ScheduleApiManager(OperationApiManager): def __init__(self, services): super().__init__(services) self.services = services def find_and_update_object(self, ram_key: str, data: dict, search: dict = None): return super(OperationApiManager, self).find_and_update_object(ram_key, data,...
for key in dict1.keys(): if key not in dict2: dict2[key] = dict1[key] elif isinstance(dict1[key], dict): self._merge_dictionaries(dict1[key], dict2[key]) return dict2
for key in dict1.keys(): if key not in dict2: dict2[key] = dict1[key] elif isinstance(dict1[key], dict): self._merge_dictionaries(dict1[key], dict2[key]) return dict2
19
307
75
382
from marshmallow.schema import SchemaMeta from typing import Any from app.api.v2.managers.operation_api_manager import OperationApiManager from app.utility.base_world import BaseWorld class ScheduleApiManager(OperationApiManager): def __init__(self, services): super().__init__(services) self.serv...
from marshmallow.schema import SchemaMeta from typing import Any from app.api.v2.managers.operation_api_manager import OperationApiManager from app.utility.base_world import BaseWorld class ScheduleApiManager(OperationApiManager): def __init__(self, services): super().__init__(services) self.serv...
38,057
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/responses.py
31,33
1,81
apispec_request_validation_middleware
36,65
33,65
from aiohttp import web from json import JSONDecodeError from marshmallow.exceptions import ValidationError from app.api.v2 import errors from app.api.v2.schemas.error_schemas import JsonHttpErrorSchema class JsonHttpErrorResponse: """Base class for json formatted versions of aiohttp responses.""" def __ini...
from aiohttp import web from json import JSONDecodeError from marshmallow.exceptions import ValidationError from app.api.v2 import errors from app.api.v2.schemas.error_schemas import JsonHttpErrorSchema class JsonHttpErrorResponse: """Base class for json formatted versions of aiohttp responses.""" def __ini...
try: return await handler(request) except TypeError as ex: # ex: Schema `post_load()` instantiates an object, but required # argument is missing raise JsonHttpBadRequest( error='Error parsing JSON', details=str(ex) ) except AttributeError as ...
"""Middleware to handle errors thrown by schema validation Must be added before `validation_middleware`""" try: return await handler(request) except TypeError as ex: # ex: Schema `post_load()` instantiates an object, but required # argument is missing raise JsonHttpBad...
92
494
270
764
from aiohttp import web from json import JSONDecodeError from marshmallow.exceptions import ValidationError from app.api.v2 import errors from app.api.v2.schemas.error_schemas import JsonHttpErrorSchema class JsonHttpErrorResponse: """Base class for json formatted versions of aiohttp responses.""" def __ini...
from aiohttp import web from json import JSONDecodeError from marshmallow.exceptions import ValidationError from app.api.v2 import errors from app.api.v2.schemas.error_schemas import JsonHttpErrorSchema class JsonHttpErrorResponse: """Base class for json formatted versions of aiohttp responses.""" def __ini...
38,058
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/schemas/error_schemas.py
12,14
5,25
make_dict
JsonHttpErrorSchema
14,21
14,21
class JsonHttpErrorSchema(schema.Schema): error = fields.String(required=True) details = fields.Dict() class Meta: ordered = True @classmethod def make_dict(cls, error, details=None): FILL_FUNC_BODY @classmethod def serialize(cls, error, details=None): mapping = cls.make_dic...
class JsonHttpErrorSchema(schema.Schema): error = fields.String(required=True) details = fields.Dict() class Meta: ordered = True @classmethod def make_dict(cls, error, details=None): FILL_FUNC_BODY @classmethod def serialize(cls, error, details=None): mapping = cls.make_dic...
obj = {'error': error} if details: obj['details'] = details return obj
obj = {'error': error} if details: obj['details'] = details return obj
11
120
36
156
from marshmallow import fields from marshmallow import schema class JsonHttpErrorSchema(schema.Schema): error = fields.String(required=True) details = fields.Dict() class Meta: ordered = True @classmethod def make_dict(cls, error, details=None): FILL_FUNC_BODY @classmethod def ser...
from marshmallow import fields from marshmallow import schema class JsonHttpErrorSchema(schema.Schema): error = fields.String(required=True) details = fields.Dict() class Meta: ordered = True @classmethod def make_dict(cls, error, details=None): FILL_FUNC_BODY @classmethod def ser...
38,059
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/security.py
8,9
1,80
is_handler_authentication_exempt
10,20
9,20
import inspect import functools import types from aiohttp import web def is_handler_authentication_exempt(handler): FILL_FUNC_BODYdef _wrap_async_method(method: types.MethodType): """Wrap the input bound async method in an async function.""" async def wrapper(*args, **kwargs): return await method(*ar...
import inspect import functools import types from aiohttp import web def is_handler_authentication_exempt(handler): """Return True if the endpoint handler is authentication exempt.""" FILL_FUNC_BODYdef _wrap_async_method(method: types.MethodType): """Wrap the input bound async method in an async function."""...
try: if hasattr(handler, '__caldera_unauthenticated__'): is_unauthenticated = handler.__caldera_unauthenticated__ else: is_unauthenticated = handler.keywords.get('handler').__caldera_unauthenticated__ except AttributeError: is_unauthenticated = False return is...
"""Return True if the endpoint handler is authentication exempt.""" try: if hasattr(handler, '__caldera_unauthenticated__'): is_unauthenticated = handler.__caldera_unauthenticated__ else: is_unauthenticated = handler.keywords.get('handler').__caldera_unauthenticated__ ...
18
611
115
726
import inspect import functools import types from aiohttp import web def is_handler_authentication_exempt(handler): FILL_FUNC_BODYdef _wrap_async_method(method: types.MethodType): """Wrap the input bound async method in an async function.""" async def wrapper(*args, **kwargs): return await method(*ar...
import inspect import functools import types from aiohttp import web def is_handler_authentication_exempt(handler): """Return True if the endpoint handler is authentication exempt.""" FILL_FUNC_BODYdef _wrap_async_method(method: types.MethodType): """Wrap the input bound async method in an async function."""...
38,060
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/api/v2/validation.py
21,22
1,28
check_not_empty_string
22,28
22,28
from app.api.v2.errors import DataValidationError def _is_integer(value): return isinstance(value, int) def _is_string(value): return isinstance(value, (str, bytes)) def check_positive_integer(value, name=None): if not _is_integer(value) or value < 0: raise DataValidationError( mes...
from app.api.v2.errors import DataValidationError def _is_integer(value): return isinstance(value, int) def _is_string(value): return isinstance(value, (str, bytes)) def check_positive_integer(value, name=None): if not _is_integer(value) or value < 0: raise DataValidationError( mes...
if not _is_string(value) or len(value) == 0: raise DataValidationError( message='Value must be a non-empty string', name=name, value=value )
if not _is_string(value) or len(value) == 0: raise DataValidationError( message='Value must be a non-empty string', name=name, value=value )
18
153
60
213
from app.api.v2.errors import DataValidationError def _is_integer(value): return isinstance(value, int) def _is_string(value): return isinstance(value, (str, bytes)) def check_positive_integer(value, name=None): if not _is_integer(value) or value < 0: raise DataValidationError( mes...
from app.api.v2.errors import DataValidationError def _is_integer(value): return isinstance(value, int) def _is_string(value): return isinstance(value, (str, bytes)) def check_positive_integer(value, name=None): if not _is_integer(value) or value < 0: raise DataValidationError( mes...
38,061
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/ascii_banner.py
55,56
1,63
print_rich_banner
57,63
56,63
import os from rich import print as rich_print RED = "\33[1m" DARK_RED = "\x1b[38;5;1m" BLUE = "\33[94m" DARK_BLUE = "\x1b[38;5;20m" GREEN = "\033[32m" YELLOW = "\033[93m" PURPLE = "\033[0;35m" DARK_PURPLE = "\x1b[38;5;92m" CYAN = "\033[36m" END = "\033[0m" _BANNER = """ ██████╗ █████╗ ██╗ ██████╗ ███████╗████...
import os from rich import print as rich_print RED = "\33[1m" DARK_RED = "\x1b[38;5;1m" BLUE = "\33[94m" DARK_BLUE = "\x1b[38;5;20m" GREEN = "\033[32m" YELLOW = "\033[93m" PURPLE = "\033[0;35m" DARK_PURPLE = "\x1b[38;5;92m" CYAN = "\033[36m" END = "\033[0m" _BANNER = """ ██████╗ █████╗ ██╗ ██████╗ ███████╗████...
if no_color(): rich_print(f"{_BANNER_SECTION_1}{_BANNER_SECTION_2}{BANNER_SECTION_3}") else: rich_print( f"[blue]{_BANNER_SECTION_1}[/blue][purple]{_BANNER_SECTION_2}[/purple][red]{BANNER_SECTION_3}[/red]" )
"""Print banner using Python Rich library""" if no_color(): rich_print(f"{_BANNER_SECTION_1}{_BANNER_SECTION_2}{BANNER_SECTION_3}") else: rich_print( f"[blue]{_BANNER_SECTION_1}[/blue][purple]{_BANNER_SECTION_2}[/purple][red]{BANNER_SECTION_3}[/red]" )
7
1,369
116
1,485
import os from rich import print as rich_print RED = "\33[1m" DARK_RED = "\x1b[38;5;1m" BLUE = "\33[94m" DARK_BLUE = "\x1b[38;5;20m" GREEN = "\033[32m" YELLOW = "\033[93m" PURPLE = "\033[0;35m" DARK_PURPLE = "\x1b[38;5;92m" CYAN = "\033[36m" END = "\033[0m" _BANNER = """ ██████╗ █████╗ ██╗ ██████╗ ███████╗████...
import os from rich import print as rich_print RED = "\33[1m" DARK_RED = "\x1b[38;5;1m" BLUE = "\33[94m" DARK_BLUE = "\x1b[38;5;20m" GREEN = "\033[32m" YELLOW = "\033[93m" PURPLE = "\033[0;35m" DARK_PURPLE = "\x1b[38;5;92m" CYAN = "\033[36m" END = "\033[0m" _BANNER = """ ██████╗ █████╗ ██╗ ██████╗ ███████╗████...
38,062
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/contacts/contact_udp.py
18,19
8,29
start
Contact
19,24
19,24
class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact_udp') self.contact_svc = services.get('contact_svc') self.handler = Handler(services) self.transpor...
class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact_udp') self.contact_svc = services.get('contact_svc') self.handler = Handler(services) self.transpor...
loop = asyncio.get_event_loop() udp = self.get_config('app.contact.udp') addr, port = udp.split(':') self.transport, _ = await loop.create_task(loop.create_datagram_endpoint(lambda: self.handler, local_addr=(addr, port)))
loop = asyncio.get_event_loop() udp = self.get_config('app.contact.udp') addr, port = udp.split(':') self.transport, _ = await loop.create_task(loop.create_datagram_endpoint(lambda: self.handler, local_addr=(addr, port)))
18
139
92
231
import asyncio import json from app.contacts.handles.h_beacon import Handle from app.utility.base_world import BaseWorld class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact...
import asyncio import json from app.contacts.handles.h_beacon import Handle from app.utility.base_world import BaseWorld class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact...
38,063
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/contacts/contact_udp.py
40,41
29,48
handle_msg
Handler
41,47
41,47
class Handler(asyncio.DatagramProtocol): def __init__(self, services): super().__init__() self.services = services self.handles = [ Handle(tag='beacon') ] self.log = BaseWorld.create_logger('udp_handler') def datagram_received(self, data, addr): asyn...
class Handler(asyncio.DatagramProtocol): def __init__(self, services): super().__init__() self.services = services self.handles = [ Handle(tag='beacon') ] self.log = BaseWorld.create_logger('udp_handler') def datagram_received(self, data, addr): asyn...
try: message = json.loads(data.decode()) for handle in [h for h in self.handles if h.tag == message.pop('tag')]: await handle.run(message, self.services, addr[0]) except Exception as e: self.log.debug(e)
try: message = json.loads(data.decode()) for handle in [h for h in self.handles if h.tag == message.pop('tag')]: await handle.run(message, self.services, addr[0]) except Exception as e: self.log.debug(e)
25
129
83
212
import asyncio import json from app.contacts.handles.h_beacon import Handle from app.utility.base_world import BaseWorld class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact...
import asyncio import json from app.contacts.handles.h_beacon import Handle from app.utility.base_world import BaseWorld class Contact(BaseWorld): def __init__(self, services): self.name = 'udp' self.description = 'Accept streaming messages via UDP' self.log = self.create_logger('contact...
38,064
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/contacts/handles/h_beacon.py
9,11
4,19
run
Handle
11,19
11,19
class Handle: def __init__(self, tag): self.tag = tag @staticmethod async def run(message, services, caller): FILL_FUNC_BODY
class Handle: def __init__(self, tag): self.tag = tag @staticmethod async def run(message, services, caller): FILL_FUNC_BODY
callback = message.pop('callback', None) message['executors'] = [e for e in message.get('executors', '').split(',') if e] message['contact'] = 'udp' await services.get('contact_svc').handle_heartbeat(**message) if callback: sock = socket.socket(family=socket.AF_INET,...
callback = message.pop('callback', None) message['executors'] = [e for e in message.get('executors', '').split(',') if e] message['contact'] = 'udp' await services.get('contact_svc').handle_heartbeat(**message) if callback: sock = socket.socket(family=socket.AF_INET,...
28
51
136
187
import socket class Handle: def __init__(self, tag): self.tag = tag @staticmethod async def run(message, services, caller): FILL_FUNC_BODY
import socket class Handle: def __init__(self, tag): self.tag = tag @staticmethod async def run(message, services, caller): FILL_FUNC_BODY
38,065
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/contacts/tunnels/tunnel_ssh.py
60,61
38,70
begin_auth
SSHServerTunnel
61,64
61,64
class SSHServerTunnel(asyncssh.SSHServer): def __init__(self, services, user_name, user_password): super().__init__() self.services = services self.log = BaseWorld.create_logger('ssh_server') self.valid_user_credentials = { user_name: user_password } def conn...
class SSHServerTunnel(asyncssh.SSHServer): def __init__(self, services, user_name, user_password): super().__init__() self.services = services self.log = BaseWorld.create_logger('ssh_server') self.valid_user_credentials = { user_name: user_password } def conn...
# If the user's password is the empty string, no auth is required return self.valid_user_credentials.get(username) != ''
# If the user's password is the empty string, no auth is required return self.valid_user_credentials.get(username) != ''
17
340
41
381
import os import asyncssh from app.utility.base_world import BaseWorld class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services ...
import os import asyncssh from app.utility.base_world import BaseWorld class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services ...
38,066
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/contacts/tunnels/tunnel_ssh.py
17,18
8,38
start
Tunnel
18,34
18,34
class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services self._user_name = self.get_config('app.contact.tunnel.ssh.user_name') ...
class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services self._user_name = self.get_config('app.contact.tunnel.ssh.user_name') ...
ssh_endpoint = self.get_config('app.contact.tunnel.ssh.socket') addr, port = ssh_endpoint.split(':') host_key_filename = self.get_config('app.contact.tunnel.ssh.host_key_file') host_key_filepath = os.path.join('conf', 'ssh_keys', host_key_filename) host_key_passphrase = self.get_...
ssh_endpoint = self.get_config('app.contact.tunnel.ssh.socket') addr, port = ssh_endpoint.split(':') host_key_filename = self.get_config('app.contact.tunnel.ssh.host_key_file') host_key_filepath = os.path.join('conf', 'ssh_keys', host_key_filename) host_key_passphrase = self.get_...
60
181
304
485
import os import asyncssh from app.utility.base_world import BaseWorld class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services ...
import os import asyncssh from app.utility.base_world import BaseWorld class Tunnel(BaseWorld): def __init__(self, services): self.name = 'ssh_tunneling' self.description = 'Accept tunneled SSH messages' self.log = self.create_logger('tunnel_ssh') self.services = services ...
38,067
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/data_encoders/base64_basic.py
6,7
1,21
load
7,10
7,10
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns base64 encoded d...
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns base64 encoded d...
return Base64Encoder()
return Base64Encoder()
2
165
14
179
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns base64 encoded d...
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns base64 encoded d...
38,068
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/data_encoders/base64_basic.py
14,15
10,21
encode
Base64Encoder
16,18
15,18
class Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): FILL_FUNC_BODY def decode(self, encoded_data, **_): """Returns b64 decoded bytes.""" return b64decode(encoded_data)
class Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns base64 encoded data.""" FILL_FUNC_BODY def decode(self, encoded_data, **_): """Returns b64 decoded bytes.""" return b...
return b64encode(data)
"""Returns base64 encoded data.""" return b64encode(data)
2
116
13
129
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): return Base64Encoder() class Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): FILL_FUNC_BODY de...
from base64 import b64encode, b64decode from app.objects.c_data_encoder import DataEncoder def load(): return Base64Encoder() class Base64Encoder(DataEncoder): def __init__(self): super().__init__('base64', 'Encodes and decodes data in base64') def encode(self, data, **_): """Returns b...
38,069
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/data_encoders/plain_text.py
4,5
1,18
load
5,8
5,8
from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): ...
from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): ...
return PlainTextEncoder()
return PlainTextEncoder()
2
124
14
138
from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): ...
from app.objects.c_data_encoder import DataEncoder def load(): FILL_FUNC_BODYclass PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): ...
38,070
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/data_encoders/plain_text.py
16,17
8,18
decode
PlainTextEncoder
17,18
17,18
class PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): return data def decode(self, encoded_data, **_): FILL_FUNC_BODY
class PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self, data, **_): return data def decode(self, encoded_data, **_): FILL_FUNC_BODY
return encoded_data
return encoded_data
2
96
7
103
from app.objects.c_data_encoder import DataEncoder def load(): return PlainTextEncoder() class PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self...
from app.objects.c_data_encoder import DataEncoder def load(): return PlainTextEncoder() class PlainTextEncoder(DataEncoder): def __init__(self): super().__init__('plain-text', 'Does not encode or decode data at all, instead keeps it in plain text form') def encode(self...
38,071
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/learning/p_ip.py
18,20
8,28
_is_valid_ip
Parser
20,28
20,28
class Parser: def __init__(self): self.trait = 'host.ip.address' def parse(self, blob): for ip in re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', blob): if self._is_valid_ip(ip): yield Fact.load(dict(trait=self.trait, value=ip)) @staticmethod def _is_...
class Parser: def __init__(self): self.trait = 'host.ip.address' def parse(self, blob): for ip in re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', blob): if self._is_valid_ip(ip): yield Fact.load(dict(trait=self.trait, value=ip)) @staticmethod def _is_...
try: # The following hardcoded addresses are not used to bind to an interface. if raw_ip in ['0.0.0.0', '127.0.0.1']: # nosec return False ip_address(raw_ip) except ValueError: return False return True
try: # The following hardcoded addresses are not used to bind to an interface. if raw_ip in ['0.0.0.0', '127.0.0.1']: # nosec return False ip_address(raw_ip) except ValueError: return False return True
30
149
90
239
import re from ipaddress import ip_address from app.objects.secondclass.c_fact import Fact class Parser: def __init__(self): self.trait = 'host.ip.address' def parse(self, blob): for ip in re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', blob): if self._is_valid_ip(ip): ...
import re from ipaddress import ip_address from app.objects.secondclass.c_fact import Fact class Parser: def __init__(self): self.trait = 'host.ip.address' def parse(self, blob): for ip in re.findall(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b', blob): if self._is_valid_ip(ip): ...
38,072
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/learning/p_path.py
11,12
6,16
parse
Parser
12,16
12,16
class Parser: def __init__(self): self.trait = 'host.file.path' def parse(self, blob): FILL_FUNC_BODY
class Parser: def __init__(self): self.trait = 'host.file.path' def parse(self, blob): FILL_FUNC_BODY
for p in re.findall(r'(\/.*?\.[\w:]+[^\s]+)', blob): yield Fact.load(dict(trait=self.trait, value=p)) for p in re.findall(r'(C:\\.*?\.[\w:]+)', blob): yield Fact.load(dict(trait=self.trait, value=p))
for p in re.findall(r'(\/.*?\.[\w:]+[^\s]+)', blob): yield Fact.load(dict(trait=self.trait, value=p)) for p in re.findall(r'(C:\\.*?\.[\w:]+)', blob): yield Fact.load(dict(trait=self.trait, value=p))
16
49
107
156
import re from app.objects.secondclass.c_fact import Fact class Parser: def __init__(self): self.trait = 'host.file.path' def parse(self, blob): FILL_FUNC_BODY
import re from app.objects.secondclass.c_fact import Fact class Parser: def __init__(self): self.trait = 'host.file.path' def parse(self, blob): FILL_FUNC_BODY
38,073
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_ability.py
97,98
49,181
store
Ability
98,122
98,122
class Ability(FirstClassObjectInterface, BaseObject): schema = AbilitySchema() display_schema = AbilitySchema() HOOKS = dict() @property def unique(self): return self.ability_id @property def executors(self): yield from self._executor_map.values() def __init__(self, ...
class Ability(FirstClassObjectInterface, BaseObject): schema = AbilitySchema() display_schema = AbilitySchema() HOOKS = dict() @property def unique(self): return self.ability_id @property def executors(self): yield from self._executor_map.values() def __init__(self, ...
existing = self.retrieve(ram['abilities'], self.unique) if not existing: name_match = [x for x in ram['abilities'] if x.name == self.name] if name_match: self.name = self.name + " (2)" logging.debug(f"Collision in ability name detected for {self.ab...
existing = self.retrieve(ram['abilities'], self.unique) if not existing: name_match = [x for x in ram['abilities'] if x.name == self.name] if name_match: self.name = self.name + " (2)" logging.debug(f"Collision in ability name detected for {self.ab...
77
1,062
381
1,443
import collections import logging import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_executor import ExecutorSchema from app.objects.secondclass.c_requirement import RequirementSchema from app.utility.base_object import BaseObject ...
import collections import logging import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_executor import ExecutorSchema from app.objects.secondclass.c_requirement import RequirementSchema from app.utility.base_object import BaseObject ...
38,074
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_ability.py
42,44
14,49
build_ability
AbilitySchema
44,49
44,49
class AbilitySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE ability_id = ma.fields.String() tactic = ma.fields.String(load_default=None) technique_name = ma.fields.String(load_default=None) technique_id = ma.fields.String(load_default=None) name = ma.fields.String(load_default=Non...
class AbilitySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE ability_id = ma.fields.String() tactic = ma.fields.String(load_default=None) technique_name = ma.fields.String(load_default=None) technique_id = ma.fields.String(load_default=None) name = ma.fields.String(load_default=Non...
if 'technique' in data: data['technique_name'] = data.pop('technique') return None if kwargs.get('partial') is True else Ability(**data)
if 'technique' in data: data['technique_name'] = data.pop('technique') return None if kwargs.get('partial') is True else Ability(**data)
15
414
56
470
import collections import logging import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_executor import ExecutorSchema from app.objects.secondclass.c_requirement import RequirementSchema from app.utility.base_object import BaseObject ...
import collections import logging import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_executor import ExecutorSchema from app.objects.secondclass.c_requirement import RequirementSchema from app.utility.base_object import BaseObject ...
38,075
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_adversary.py
101,102
54,112
has_ability
Adversary
102,107
102,107
class Adversary(FirstClassObjectInterface, BaseObject): schema = AdversarySchema() @property def unique(self): return self.hash('%s' % self.adversary_id) def __init__(self, name='', adversary_id='', description='', atomic_ordering=(), objective='', tags=None, plugin=''): super().__ini...
class Adversary(FirstClassObjectInterface, BaseObject): schema = AdversarySchema() @property def unique(self): return self.hash('%s' % self.adversary_id) def __init__(self, name='', adversary_id='', description='', atomic_ordering=(), objective='', tags=None, plugin=''): super().__ini...
for a in self.atomic_ordering: if ability == a: return True return False
for a in self.atomic_ordering: if ability == a: return True return False
12
684
33
717
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject DEFAULT_OBJECTIVE_ID = '495a9828-cab1-44dd-a0ca-66e58177d8cc' class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id ...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject DEFAULT_OBJECTIVE_ID = '495a9828-cab1-44dd-a0ca-66e58177d8cc' class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id ...
38,076
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_adversary.py
49,51
12,54
build_adversary
AdversarySchema
51,54
51,54
class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id = ma.fields.String() name = ma.fields.String() description = ma.fields.String() atomic_ordering = ma.fields.List(ma.fields.String()) objective = ma.fields.String() tags = ma.fields.List(ma.fields.String...
class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id = ma.fields.String() name = ma.fields.String() description = ma.fields.String() atomic_ordering = ma.fields.List(ma.fields.String()) objective = ma.fields.String() tags = ma.fields.List(ma.fields.String...
return None if kwargs.get('partial') is True else Adversary(**data)
return None if kwargs.get('partial') is True else Adversary(**data)
8
442
28
470
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject DEFAULT_OBJECTIVE_ID = '495a9828-cab1-44dd-a0ca-66e58177d8cc' class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id ...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject DEFAULT_OBJECTIVE_ID = '495a9828-cab1-44dd-a0ca-66e58177d8cc' class AdversarySchema(ma.Schema): class Meta: unknown = ma.EXCLUDE adversary_id ...
38,078
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_agent.py
55,57
16,64
remove_properties
AgentFieldsSchema
57,64
57,64
class AgentFieldsSchema(ma.Schema): paw = ma.fields.String(allow_none=True) sleep_min = ma.fields.Integer() sleep_max = ma.fields.Integer() watchdog = ma.fields.Integer() group = ma.fields.String() architecture = ma.fields.String() platform = ma.fields.String() server = ma.fields.String...
class AgentFieldsSchema(ma.Schema): paw = ma.fields.String(allow_none=True) sleep_min = ma.fields.Integer() sleep_max = ma.fields.Integer() watchdog = ma.fields.Integer() group = ma.fields.String() architecture = ma.fields.String() platform = ma.fields.String() server = ma.fields.String...
data.pop('display_name', None) data.pop('created', None) data.pop('last_seen', None) data.pop('links', None) return data
data.pop('display_name', None) data.pop('created', None) data.pop('last_seen', None) data.pop('links', None) return data
10
585
57
642
import re from base64 import b64decode from datetime import datetime, timezone from urllib.parse import urlparse import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_link import Link, LinkSchema from app.objects.secondclass.c_fact import OriginT...
import re from base64 import b64decode from datetime import datetime, timezone from urllib.parse import urlparse import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_link import Link, LinkSchema from app.objects.secondclass.c_fact import OriginT...
38,079
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_agent.py
66,68
64,71
build_agent
AgentSchema
68,71
68,71
class AgentSchema(AgentFieldsSchema): @ma.post_load def build_agent(self, data, **kwargs): FILL_FUNC_BODY
class AgentSchema(AgentFieldsSchema): @ma.post_load def build_agent(self, data, **kwargs): FILL_FUNC_BODY
return None if kwargs.get('partial') is True else Agent(**data)
return None if kwargs.get('partial') is True else Agent(**data)
8
42
26
68
import re from base64 import b64decode from datetime import datetime, timezone from urllib.parse import urlparse import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_link import Link, LinkSchema from app.objects.secondclass.c_fact import OriginT...
import re from base64 import b64decode from datetime import datetime, timezone from urllib.parse import urlparse import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_link import Link, LinkSchema from app.objects.secondclass.c_fact import OriginT...
38,080
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_data_encoder.py
28,29
15,42
store
DataEncoder
29,35
29,35
class DataEncoder(FirstClassObjectInterface, BaseObject): schema = DataEncoderSchema() display_schema = DataEncoderSchema(exclude=['module']) @property def unique(self): return self.hash('%s' % self.name) def __init__(self, name, description): super().__init__() self.name =...
class DataEncoder(FirstClassObjectInterface, BaseObject): schema = DataEncoderSchema() display_schema = DataEncoderSchema(exclude=['module']) @property def unique(self): return self.hash('%s' % self.name) def __init__(self, name, description): super().__init__() self.name =...
existing = self.retrieve(ram['data_encoders'], self.unique) if not existing: ram['data_encoders'].append(self) return self.retrieve(ram['data_encoders'], self.unique) return existing
existing = self.retrieve(ram['data_encoders'], self.unique) if not existing: ram['data_encoders'].append(self) return self.retrieve(ram['data_encoders'], self.unique) return existing
13
176
72
248
from abc import abstractmethod import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class DataEncoderSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fields.String() class ...
from abc import abstractmethod import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class DataEncoderSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fields.String() class ...
38,081
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_obfuscator.py
35,36
21,48
store
Obfuscator
36,42
36,42
class Obfuscator(FirstClassObjectInterface, BaseObject): schema = ObfuscatorSchema() display_schema = ObfuscatorSchema(exclude=['module']) @property def unique(self): return self.hash('%s' % self.name) def __init__(self, name, description, module): super().__init__() self.n...
class Obfuscator(FirstClassObjectInterface, BaseObject): schema = ObfuscatorSchema() display_schema = ObfuscatorSchema(exclude=['module']) @property def unique(self): return self.hash('%s' % self.name) def __init__(self, name, description, module): super().__init__() self.n...
existing = self.retrieve(ram['obfuscators'], self.unique) if not existing: ram['obfuscators'].append(self) return self.retrieve(ram['obfuscators'], self.unique) return existing
existing = self.retrieve(ram['obfuscators'], self.unique) if not existing: ram['obfuscators'].append(self) return self.retrieve(ram['obfuscators'], self.unique) return existing
13
206
69
275
import logging from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fiel...
import logging from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fiel...
38,082
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_obfuscator.py
16,18
10,21
build_obfuscator
ObfuscatorSchema
18,21
18,21
class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fields.String() @ma.post_load def build_obfuscator(self, data, **kwargs): FILL_FUNC_BODY
class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fields.String() @ma.post_load def build_obfuscator(self, data, **kwargs): FILL_FUNC_BODY
return None if kwargs.get('partial') is True else Obfuscator(**data)
return None if kwargs.get('partial') is True else Obfuscator(**data)
8
79
29
108
import logging from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fiel...
import logging from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class ObfuscatorSchema(ma.Schema): name = ma.fields.String() description = ma.fields.String() module = ma.fiel...
38,083
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_objective.py
55,56
31,64
store
Objective
56,64
56,64
class Objective(FirstClassObjectInterface, BaseObject): schema = ObjectiveSchema() @property def unique(self): return self.hash('%s' % self.id) @property def percentage(self): if len(self.goals) > 0: return 100 * (len([g for g in self.goals if g.satisfied() is True])/l...
class Objective(FirstClassObjectInterface, BaseObject): schema = ObjectiveSchema() @property def unique(self): return self.hash('%s' % self.id) @property def percentage(self): if len(self.goals) > 0: return 100 * (len([g for g in self.goals if g.satisfied() is True])/l...
existing = self.retrieve(ram['objectives'], self.unique) if not existing: ram['objectives'].append(self) return self.retrieve(ram['objectives'], self.unique) existing.update('name', self.name) existing.update('description', self.description) existing.updat...
existing = self.retrieve(ram['objectives'], self.unique) if not existing: ram['objectives'].append(self) return self.retrieve(ram['objectives'], self.unique) existing.update('name', self.name) existing.update('description', self.description) existing.updat...
19
244
102
346
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_goal import GoalSchema from app.utility.base_object import BaseObject class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String()...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_goal import GoalSchema from app.utility.base_object import BaseObject class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String()...
38,084
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_objective.py
26,28
10,31
build_objective
ObjectiveSchema
28,31
28,31
class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() name = ma.fields.String() description = ma.fields.String() goals = ma.fields.List(ma.fields.Nested(GoalSchema)) percentage = ma.fields.Float(dump_only=True) @ma.pre_load def remove_prope...
class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() name = ma.fields.String() description = ma.fields.String() goals = ma.fields.List(ma.fields.Nested(GoalSchema)) percentage = ma.fields.Float(dump_only=True) @ma.pre_load def remove_prope...
return None if kwargs.get('partial') is True else Objective(**data)
return None if kwargs.get('partial') is True else Objective(**data)
8
167
27
194
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_goal import GoalSchema from app.utility.base_object import BaseObject class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String()...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_goal import GoalSchema from app.utility.base_object import BaseObject class ObjectiveSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String()...
38,085
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_planner.py
62,64
26,67
_set_stopping_conditions
Planner
64,67
64,67
class Planner(FirstClassObjectInterface, BaseObject): schema = PlannerSchema() display_schema = PlannerSchema(exclude=['module', 'ignore_enforcement_modules']) @property def unique(self): return self.hash(self.name) def __init__(self, name='', planner_id='', module='', params=None, stoppi...
class Planner(FirstClassObjectInterface, BaseObject): schema = PlannerSchema() display_schema = PlannerSchema(exclude=['module', 'ignore_enforcement_modules']) @property def unique(self): return self.hash(self.name) def __init__(self, name='', planner_id='', module='', params=None, stoppi...
if conditions: return [Fact.load(dict(trait=trait, value=value)) for sc in conditions for trait, value in sc.items()] return []
if conditions: return [Fact.load(dict(trait=trait, value=value)) for sc in conditions for trait, value in sc.items()] return []
16
419
47
466
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject from app.objects.secondclass.c_fact import Fact, FactSchema class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields....
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject from app.objects.secondclass.c_fact import Fact, FactSchema class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields....
38,086
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_planner.py
21,23
10,26
build_planner
PlannerSchema
23,26
23,26
class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields.String() module = ma.fields.String() params = ma.fields.Dict() description = ma.fields.String() stopping_conditions = ma.fields.List(ma.fields.Nested(FactSchema())) ignore_enforcement_modules = ma.f...
class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields.String() module = ma.fields.String() params = ma.fields.Dict() description = ma.fields.String() stopping_conditions = ma.fields.List(ma.fields.Nested(FactSchema())) ignore_enforcement_modules = ma.f...
return None if kwargs.get('partial') is True else Planner(**data)
return None if kwargs.get('partial') is True else Planner(**data)
8
181
27
208
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject from app.objects.secondclass.c_fact import Fact, FactSchema class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields....
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject from app.objects.secondclass.c_fact import Fact, FactSchema class PlannerSchema(ma.Schema): planner_id = ma.fields.String(data_key='id') name = ma.fields....
38,087
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_plugin.py
51,52
24,92
load_plugin
Plugin
52,62
52,62
class Plugin(FirstClassObjectInterface, BaseObject): schema = PluginSchema() display_schema = PluginSchema(only=['name', 'description', 'enabled', 'address']) @property def unique(self): return self.hash(self.name) def __init__(self, name='virtual', description=None, address=None, enabled...
class Plugin(FirstClassObjectInterface, BaseObject): schema = PluginSchema() display_schema = PluginSchema(only=['name', 'description', 'enabled', 'address']) @property def unique(self): return self.hash(self.name) def __init__(self, name='virtual', description=None, address=None, enabled...
try: plugin = self._load_module() self.description = plugin.description self.address = plugin.address self.access = getattr(self._load_module(), 'access', self.Access.APP) return True except Exception as e: logging.error('Error load...
try: plugin = self._load_module() self.description = plugin.description self.address = plugin.address self.access = getattr(self._load_module(), 'access', self.Access.APP) return True except Exception as e: logging.error('Error load...
30
584
106
690
import logging import os from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() a...
import logging import os from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() a...
38,088
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_plugin.py
19,21
11,24
build_plugin
PluginSchema
21,24
21,24
class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() address = ma.fields.String() description = ma.fields.String() data_dir = ma.fields.String() access = ma.fields.Integer() @ma.post_load def build_plugin(self, data, **kwargs): FILL_FUNC_BO...
class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() address = ma.fields.String() description = ma.fields.String() data_dir = ma.fields.String() access = ma.fields.Integer() @ma.post_load def build_plugin(self, data, **kwargs): FILL_FUNC_BO...
return None if kwargs.get('partial') is True else Plugin(**data)
return None if kwargs.get('partial') is True else Plugin(**data)
8
109
27
136
import logging import os from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() a...
import logging import os from importlib import import_module import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.utility.base_object import BaseObject class PluginSchema(ma.Schema): name = ma.fields.String(required=True) enabled = ma.fields.Boolean() a...
38,089
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_schedule.py
37,38
24,47
store
Schedule
38,47
38,47
class Schedule(FirstClassObjectInterface, BaseObject): schema = ScheduleSchema() @property def unique(self): return self.hash('%s' % self.id) def __init__(self, schedule, task, id=''): super().__init__() self.id = str(id) if id else str(uuid.uuid4()) self.schedule = sch...
class Schedule(FirstClassObjectInterface, BaseObject): schema = ScheduleSchema() @property def unique(self): return self.hash('%s' % self.id) def __init__(self, schedule, task, id=''): super().__init__() self.id = str(id) if id else str(uuid.uuid4()) self.schedule = sch...
existing = self.retrieve(ram['schedules'], self.unique) if not existing: ram['schedules'].append(self) return self.retrieve(ram['schedules'], self.unique) existing.update('schedule', self.schedule) existing.task.update('state', self.task.state) existing.ta...
existing = self.retrieve(ram['schedules'], self.unique) if not existing: ram['schedules'].append(self) return self.retrieve(ram['schedules'], self.unique) existing.update('schedule', self.schedule) existing.task.update('state', self.task.state) existing.ta...
21
128
137
265
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.c_operation import OperationSchema from app.utility.base_object import BaseObject class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() ...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.c_operation import OperationSchema from app.utility.base_object import BaseObject class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() ...
38,090
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_schedule.py
19,21
10,24
build_schedule
ScheduleSchema
21,24
21,24
class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() schedule = ma.fields.Time(required=True) task = ma.fields.Nested(OperationSchema()) @ma.post_load def build_schedule(self, data, **kwargs): FILL_FUNC_BODY
class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() schedule = ma.fields.Time(required=True) task = ma.fields.Nested(OperationSchema()) @ma.post_load def build_schedule(self, data, **kwargs): FILL_FUNC_BODY
return None if kwargs.get('partial') is True else Schedule(**data)
return None if kwargs.get('partial') is True else Schedule(**data)
8
100
27
127
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.c_operation import OperationSchema from app.utility.base_object import BaseObject class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() ...
import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.c_operation import OperationSchema from app.utility.base_object import BaseObject class ScheduleSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE id = ma.fields.String() ...
38,091
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_source.py
20,22
13,25
build_adjustment
AdjustmentSchema
22,25
22,25
class AdjustmentSchema(ma.Schema): ability_id = ma.fields.String() trait = ma.fields.String() value = ma.fields.String() offset = ma.fields.Integer() @ma.post_load() def build_adjustment(self, data, **_): FILL_FUNC_BODY
class AdjustmentSchema(ma.Schema): ability_id = ma.fields.String() trait = ma.fields.String() value = ma.fields.String() offset = ma.fields.Integer() @ma.post_load() def build_adjustment(self, data, **_): FILL_FUNC_BODY
return Adjustment(**data)
return Adjustment(**data)
2
91
15
106
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
38,092
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_source.py
93,94
74,104
store
Source
94,104
94,104
class Source(FirstClassObjectInterface, BaseObject): schema = SourceSchema() display_schema = SourceSchema(exclude=('adjustments',)) @property def unique(self): return self.hash('%s' % self.id) def __init__(self, name='', id='', facts=(), relationships=(), rules=(), adjustments=(), plugin...
class Source(FirstClassObjectInterface, BaseObject): schema = SourceSchema() display_schema = SourceSchema(exclude=('adjustments',)) @property def unique(self): return self.hash('%s' % self.id) def __init__(self, name='', id='', facts=(), relationships=(), rules=(), adjustments=(), plugin...
existing = self.retrieve(ram['sources'], self.unique) if not existing: ram['sources'].append(self) return self.retrieve(ram['sources'], self.unique) existing.update('name', self.name) existing.update('facts', self.facts) existing.update('rules', self.rules...
existing = self.retrieve(ram['sources'], self.unique) if not existing: ram['sources'].append(self) return self.retrieve(ram['sources'], self.unique) existing.update('name', self.name) existing.update('facts', self.facts) existing.update('rules', self.rules...
23
189
127
316
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
38,093
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/c_source.py
56,58
28,74
_fix_loaded_object_origins
SourceSchema
63,74
58,74
class SourceSchema(ma.Schema): id = ma.fields.String() name = ma.fields.String() facts = ma.fields.List(ma.fields.Nested(FactSchema)) rules = ma.fields.List(ma.fields.Nested(RuleSchema)) adjustments = ma.fields.List(ma.fields.Nested(AdjustmentSchema)) relationships = ma.fields.List(ma.fields.Ne...
class SourceSchema(ma.Schema): id = ma.fields.String() name = ma.fields.String() facts = ma.fields.List(ma.fields.Nested(FactSchema)) rules = ma.fields.List(ma.fields.Nested(RuleSchema)) adjustments = ma.fields.List(ma.fields.Nested(AdjustmentSchema)) relationships = ma.fields.List(ma.fields.Ne...
for y in input_data.get('facts', []): y['origin_type'] = OriginType.IMPORTED.name y['source'] = input_data['id'] for y in input_data.get('relationships', []): y['source']['origin_type'] = OriginType.IMPORTED.name y['source']['source'] = input_data['id'] ...
""" Sort through input_data's facts and relationships, and patch them to include origin and references :param input_data: A 'source' dictionary :return: input_data with updated facts/relationships (patched in place) """ for y in input_data.get('facts', []): y[...
30
455
153
608
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
from collections import namedtuple import uuid import marshmallow as ma from app.objects.interfaces.i_object import FirstClassObjectInterface from app.objects.secondclass.c_fact import FactSchema, OriginType from app.objects.secondclass.c_rule import RuleSchema from app.objects.secondclass.c_relationship import Relat...
38,094
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/interfaces/i_object.py
11,13
4,14
store
FirstClassObjectInterface
13,14
13,14
class FirstClassObjectInterface(abc.ABC): @property @abc.abstractmethod def unique(self): raise NotImplementedError @abc.abstractmethod def store(self, ram): FILL_FUNC_BODY
class FirstClassObjectInterface(abc.ABC): @property @abc.abstractmethod def unique(self): raise NotImplementedError @abc.abstractmethod def store(self, ram): FILL_FUNC_BODY
raise NotImplementedError
raise NotImplementedError
2
68
9
77
import abc class FirstClassObjectInterface(abc.ABC): @property @abc.abstractmethod def unique(self): raise NotImplementedError @abc.abstractmethod def store(self, ram): FILL_FUNC_BODY
import abc class FirstClassObjectInterface(abc.ABC): @property @abc.abstractmethod def unique(self): raise NotImplementedError @abc.abstractmethod def store(self, ram): FILL_FUNC_BODY
38,095
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_executor.py
87,88
1,100
get_variations
88,100
88,100
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
variations = [] if not data: return [] for v in data: if isinstance(v, Variation): description = v.description command = v.command else: description = v['description'] command = v['command'] variations.append(Variation.load(dict...
variations = [] if not data: return [] for v in data: if isinstance(v, Variation): description = v.description command = v.command else: description = v['description'] command = v['command'] variations.append(Variation.load(dict...
32
870
104
974
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
38,096
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_executor.py
38,40
29,87
is_global_variable
Executor
40,42
40,42
class Executor(BaseObject): schema = ExecutorSchema() display_schema = ExecutorSchema() RESERVED = dict(payload='#{payload}') HOOKS = dict() @classmethod def is_global_variable(cls, variable): FILL_FUNC_BODY @property def test(self): """Get command with app property variables ...
class Executor(BaseObject): schema = ExecutorSchema() display_schema = ExecutorSchema() RESERVED = dict(payload='#{payload}') HOOKS = dict() @classmethod def is_global_variable(cls, variable): FILL_FUNC_BODY @property def test(self): """Get command with app property variables ...
return variable in cls.RESERVED
return variable in cls.RESERVED
4
504
15
519
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
38,097
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_executor.py
24,26
9,29
build_executor
ExecutorSchema
26,29
26,29
class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String(load_default=None) command = ma.fields.String(load_default=None) code = ma.fields.String(load_default=None) language = ma.fields.String(load_default=None) build_target = ma.fields.String(load_...
class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String(load_default=None) command = ma.fields.String(load_default=None) code = ma.fields.String(load_default=None) language = ma.fields.String(load_default=None) build_target = ma.fields.String(load_...
return Executor(**data)
return Executor(**data)
2
282
14
296
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
import marshmallow as ma from app.utility.base_object import BaseObject from app.objects.secondclass.c_parser import ParserSchema from app.objects.secondclass.c_variation import Variation, VariationSchema class ExecutorSchema(ma.Schema): name = ma.fields.String(load_default=None) platform = ma.fields.String...
38,098
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_fact.py
89,91
67,121
trait
Fact
91,94
91,94
class Fact(BaseObject): schema = FactSchema() load_schema = FactSchema(exclude=['unique']) @property def unique(self): return self.hash('%s%s' % (self.trait, self.value)) @property def name(self): return self._trait @name.setter def name(self, value): # Keep b...
class Fact(BaseObject): schema = FactSchema() load_schema = FactSchema(exclude=['unique']) @property def unique(self): return self.hash('%s%s' % (self.trait, self.value)) @property def name(self): return self._trait @name.setter def name(self, value): # Keep b...
# Keep both values in sync if changed. (backwards compatibility) self._trait = value
# Keep both values in sync if changed. (backwards compatibility) self._trait = value
13
488
28
516
from datetime import datetime, timezone from enum import Enum import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject escape_ref = { 'sh': { 'special': ['\\', ' ', '$', '#', '^', '&', '*', '|', '`', '>', '<', '"', '\'', '[', ']', '{',...
from datetime import datetime, timezone from enum import Enum import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject escape_ref = { 'sh': { 'special': ['\\', ' ', '$', '#', '^', '&', '*', '|', '`', '>', '<', '"', '\'', '[', ']', '{',...
38,099
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_fact.py
57,59
38,62
build_fact
FactSchema
59,62
59,62
class FactSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE unique = ma.fields.String(dump_only=True) trait = ma.fields.String(required=True) name = ma.fields.String(dump_only=True) value = ma.fields.Function(lambda x: x.value, deserialize=lambda x: str(x), allow_none=True) created =...
class FactSchema(ma.Schema): class Meta: unknown = ma.EXCLUDE unique = ma.fields.String(dump_only=True) trait = ma.fields.String(required=True) name = ma.fields.String(dump_only=True) value = ma.fields.Function(lambda x: x.value, deserialize=lambda x: str(x), allow_none=True) created =...
return None if kwargs.get('partial') is True else Fact(**data)
return None if kwargs.get('partial') is True else Fact(**data)
8
295
26
321
from datetime import datetime, timezone from enum import Enum import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject escape_ref = { 'sh': { 'special': ['\\', ' ', '$', '#', '^', '&', '*', '|', '`', '>', '<', '"', '\'', '[', ']', '{',...
from datetime import datetime, timezone from enum import Enum import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject escape_ref = { 'sh': { 'special': ['\\', ' ', '$', '#', '^', '&', '*', '|', '`', '>', '<', '"', '\'', '[', ']', '{',...
38,100
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_goal.py
29,31
24,61
parse_operator
Goal
31,45
31,45
class Goal(BaseObject): schema = GoalSchema() MAX_GOAL_COUNT = 2**20 @staticmethod def parse_operator(operator): FILL_FUNC_BODY def satisfied(self, all_facts=None): temp_count = 0 for fact in (all_facts or []): if self.target == fact.trait and self.parse_operator(self.op...
class Goal(BaseObject): schema = GoalSchema() MAX_GOAL_COUNT = 2**20 @staticmethod def parse_operator(operator): FILL_FUNC_BODY def satisfied(self, all_facts=None): temp_count = 0 for fact in (all_facts or []): if self.target == fact.trait and self.parse_operator(self.op...
if operator == '<': return lambda x, y: x < y if operator == '>': return lambda x, y: x > y if operator == '<=': return lambda x, y: x <= y if operator == '>=': return lambda x, y: x >= y if operator == 'in': return lamb...
if operator == '<': return lambda x, y: x < y if operator == '>': return lambda x, y: x > y if operator == '<=': return lambda x, y: x <= y if operator == '>=': return lambda x, y: x >= y if operator == 'in': return lamb...
71
242
146
388
import marshmallow as ma from app.utility.base_object import BaseObject class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_prop...
import marshmallow as ma from app.utility.base_object import BaseObject class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_prop...
38,101
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_goal.py
14,16
6,24
remove_properties
GoalSchema
16,19
16,19
class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_properties(self, data, **_): FILL_FUNC_BODY @ma.post_load def build_goal...
class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_properties(self, data, **_): FILL_FUNC_BODY @ma.post_load def build_goal...
data.pop('achieved', None) return data
data.pop('achieved', None) return data
4
134
19
153
import marshmallow as ma from app.utility.base_object import BaseObject class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_prop...
import marshmallow as ma from app.utility.base_object import BaseObject class GoalSchema(ma.Schema): target = ma.fields.String() value = ma.fields.String() count = ma.fields.Integer() operator = ma.fields.String() achieved = ma.fields.Boolean(dump_only=True) @ma.pre_load def remove_prop...
38,102
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_instruction.py
26,28
22,43
display
Instruction
28,32
28,32
class Instruction(BaseObject): schema = InstructionSchema() @property def display(self): FILL_FUNC_BODY def __init__(self, id, command, executor, payloads=None, uploads=None, sleep=0, timeout=60, deadman=False, delete_payload=True): super().__init__() self.id = id self.sleep = s...
class Instruction(BaseObject): schema = InstructionSchema() @property def display(self): FILL_FUNC_BODY def __init__(self, id, command, executor, payloads=None, uploads=None, sleep=0, timeout=60, deadman=False, delete_payload=True): super().__init__() self.id = id self.sleep = s...
return self.clean(dict(id=self.id, sleep=self.sleep, command=self.command, executor=self.executor, timeout=self.timeout, payloads=self.payloads, uploads=self.uploads, deadman=self.deadman, delete_payload=self.delete_payload))
return self.clean(dict(id=self.id, sleep=self.sleep, command=self.command, executor=self.executor, timeout=self.timeout, payloads=self.payloads, uploads=self.uploads, deadman=self.deadman, delete_payload=self.delete_payload))
10
181
87
268
import marshmallow as ma from app.utility.base_object import BaseObject class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) de...
import marshmallow as ma from app.utility.base_object import BaseObject class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) de...
38,103
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_instruction.py
17,19
6,22
build_instruction
InstructionSchema
19,22
19,22
class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) deadman = ma.fields.Boolean() uploads = ma.fields.List(ma.fields.Dict(key...
class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) deadman = ma.fields.Boolean() uploads = ma.fields.List(ma.fields.Dict(key...
return Instruction(**data)
return Instruction(**data)
2
176
14
190
import marshmallow as ma from app.utility.base_object import BaseObject class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) de...
import marshmallow as ma from app.utility.base_object import BaseObject class InstructionSchema(ma.Schema): id = ma.fields.String() sleep = ma.fields.Int() command = ma.fields.String() executor = ma.fields.String() timeout = ma.fields.Int() payloads = ma.fields.List(ma.fields.String()) de...
38,104
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_parser.py
28,30
24,36
unique
Parser
30,32
30,32
class Parser(BaseObject): schema = ParserSchema() @property def unique(self): FILL_FUNC_BODY def __init__(self, module, parserconfigs): super().__init__() self.module = module self.parserconfigs = parserconfigs
class Parser(BaseObject): schema = ParserSchema() @property def unique(self): FILL_FUNC_BODY def __init__(self, module, parserconfigs): super().__init__() self.module = module self.parserconfigs = parserconfigs
return self.module
return self.module
2
79
9
88
import marshmallow as ma from app.objects.secondclass.c_parserconfig import ParserConfig, ParserConfigSchema from app.utility.base_object import BaseObject class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() ...
import marshmallow as ma from app.objects.secondclass.c_parserconfig import ParserConfig, ParserConfigSchema from app.utility.base_object import BaseObject class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() ...
38,105
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_parser.py
16,18
7,24
prepare_parser
ParserSchema
18,24
18,24
class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() def build_parser(self, data, **_): return Parser(**data) @ma.post_dump() def prepare_parser(self, data, **_): FILL_FUNC_BODY
class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() def build_parser(self, data, **_): return Parser(**data) @ma.post_dump() def prepare_parser(self, data, **_): FILL_FUNC_BODY
for pc, index in enumerate(data['parserconfigs']): if isinstance(pc, ParserConfig): data['parserconfigs'][index] = pc.display return data
for pc, index in enumerate(data['parserconfigs']): if isinstance(pc, ParserConfig): data['parserconfigs'][index] = pc.display return data
13
111
56
167
import marshmallow as ma from app.objects.secondclass.c_parserconfig import ParserConfig, ParserConfigSchema from app.utility.base_object import BaseObject class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() ...
import marshmallow as ma from app.objects.secondclass.c_parserconfig import ParserConfig, ParserConfigSchema from app.utility.base_object import BaseObject class ParserSchema(ma.Schema): module = ma.fields.String() parserconfigs = ma.fields.List(ma.fields.Nested(ParserConfigSchema())) @ma.post_load() ...
38,106
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_parserconfig.py
16,18
6,36
check_edge_target
ParserConfigSchema
18,23
18,23
class ParserConfigSchema(ma.Schema): class Meta: unknown = ma.INCLUDE source = ma.fields.String() edge = ma.fields.String(load_default=None) target = ma.fields.String(load_default=None) custom_parser_vals = ma.fields.Dict(keys=ma.fields.String(), values=ma.fields.String()) @ma.pre_loa...
class ParserConfigSchema(ma.Schema): class Meta: unknown = ma.INCLUDE source = ma.fields.String() edge = ma.fields.String(load_default=None) target = ma.fields.String(load_default=None) custom_parser_vals = ma.fields.Dict(keys=ma.fields.String(), values=ma.fields.String()) @ma.pre_loa...
if all(k in in_data.keys() for k in ['edge', 'target']) \ and (in_data['edge'] is None) and (in_data['target'] is not None): raise ma.ValidationError('Target provided without an edge.') return in_data
if all(k in in_data.keys() for k in ['edge', 'target']) \ and (in_data['edge'] is None) and (in_data['target'] is not None): raise ma.ValidationError('Target provided without an edge.') return in_data
27
256
75
331
import marshmallow as ma from app.utility.base_object import BaseObject class ParserConfigSchema(ma.Schema): class Meta: unknown = ma.INCLUDE source = ma.fields.String() edge = ma.fields.String(load_default=None) target = ma.fields.String(load_default=None) custom_parser_vals = ma.field...
import marshmallow as ma from app.utility.base_object import BaseObject class ParserConfigSchema(ma.Schema): class Meta: unknown = ma.INCLUDE source = ma.fields.String() edge = ma.fields.String(load_default=None) target = ma.fields.String(load_default=None) custom_parser_vals = ma.field...
38,107
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_requirement.py
20,22
16,28
unique
Requirement
22,24
22,24
class Requirement(BaseObject): schema = RequirementSchema() @property def unique(self): FILL_FUNC_BODY def __init__(self, module, relationship_match): super().__init__() self.module = module self.relationship_match = relationship_match
class Requirement(BaseObject): schema = RequirementSchema() @property def unique(self): FILL_FUNC_BODY def __init__(self, module, relationship_match): super().__init__() self.module = module self.relationship_match = relationship_match
return self.module
return self.module
2
82
9
91
import marshmallow as ma from app.utility.base_object import BaseObject class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): return Requirement(**data) class Requiremen...
import marshmallow as ma from app.utility.base_object import BaseObject class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): return Requirement(**data) class Requiremen...
38,108
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_requirement.py
11,13
6,16
build_requirement
RequirementSchema
13,16
13,16
class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): FILL_FUNC_BODY
class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): FILL_FUNC_BODY
return Requirement(**data)
return Requirement(**data)
2
76
15
91
import marshmallow as ma from app.utility.base_object import BaseObject class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): FILL_FUNC_BODYclass Requirement(BaseObject): sch...
import marshmallow as ma from app.utility.base_object import BaseObject class RequirementSchema(ma.Schema): module = ma.fields.String() relationship_match = ma.fields.List(ma.fields.Dict()) @ma.post_load() def build_requirement(self, data, **_): FILL_FUNC_BODYclass Requirement(BaseObject): sch...
38,109
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_result.py
19,21
6,26
prepare_dump
ResultSchema
21,26
21,26
class ResultSchema(ma.Schema): id = ma.fields.String() output = ma.fields.String() stderr = ma.fields.String() exit_code = ma.fields.String() pid = ma.fields.String() status = ma.fields.String() agent_reported_time = ma.fields.DateTime(format=BaseObject.TIME_FORMAT, load_default=None) @...
class ResultSchema(ma.Schema): id = ma.fields.String() output = ma.fields.String() stderr = ma.fields.String() exit_code = ma.fields.String() pid = ma.fields.String() status = ma.fields.String() agent_reported_time = ma.fields.DateTime(format=BaseObject.TIME_FORMAT, load_default=None) @...
if data.get('agent_reported_time', None) is None: data.pop('agent_reported_time', None) return data
if data.get('agent_reported_time', None) is None: data.pop('agent_reported_time', None) return data
9
167
45
212
import marshmallow as ma from app.utility.base_object import BaseObject class ResultSchema(ma.Schema): id = ma.fields.String() output = ma.fields.String() stderr = ma.fields.String() exit_code = ma.fields.String() pid = ma.fields.String() status = ma.fields.String() agent_reported_time = ...
import marshmallow as ma from app.utility.base_object import BaseObject class ResultSchema(ma.Schema): id = ma.fields.String() output = ma.fields.String() stderr = ma.fields.String() exit_code = ma.fields.String() pid = ma.fields.String() status = ma.fields.String() agent_reported_time = ...
38,110
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_rule.py
14,16
8,19
build_rule
RuleSchema
16,19
16,19
class RuleSchema(ma.Schema): action = ma_enum.EnumField(RuleAction, required=True) trait = ma.fields.String(required=True) match = ma.fields.String() @ma.post_load def build_rule(self, data, **_): FILL_FUNC_BODY
class RuleSchema(ma.Schema): action = ma_enum.EnumField(RuleAction, required=True) trait = ma.fields.String(required=True) match = ma.fields.String() @ma.post_load def build_rule(self, data, **_): FILL_FUNC_BODY
return Rule(**data)
return Rule(**data)
2
86
13
99
import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject from app.utility.rule_set import RuleAction class RuleSchema(ma.Schema): action = ma_enum.EnumField(RuleAction, required=True) trait = ma.fields.String(required=True) match = ma.fields.String() ...
import marshmallow as ma import marshmallow_enum as ma_enum from app.utility.base_object import BaseObject from app.utility.rule_set import RuleAction class RuleSchema(ma.Schema): action = ma_enum.EnumField(RuleAction, required=True) trait = ma.fields.String(required=True) match = ma.fields.String() ...
38,111
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_variation.py
24,26
16,32
raw_command
Variation
26,28
26,28
class Variation(BaseObject): schema = VariationSchema() @property def command(self): return self.replace_app_props(self._command) @property def raw_command(self): FILL_FUNC_BODY def __init__(self, description, command): super().__init__() self.description = description ...
class Variation(BaseObject): schema = VariationSchema() @property def command(self): return self.replace_app_props(self._command) @property def raw_command(self): FILL_FUNC_BODY def __init__(self, description, command): super().__init__() self.description = description ...
return self.decode_bytes(self._command)
return self.decode_bytes(self._command)
2
109
16
125
import marshmallow as ma from app.utility.base_object import BaseObject class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): return Variation(**data) class Variation(BaseObject): schema = V...
import marshmallow as ma from app.utility.base_object import BaseObject class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): return Variation(**data) class Variation(BaseObject): schema = V...
38,112
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_variation.py
11,13
6,16
build_variation
VariationSchema
13,16
13,16
class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): FILL_FUNC_BODY
class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): FILL_FUNC_BODY
return Variation(**data)
return Variation(**data)
2
65
14
79
import marshmallow as ma from app.utility.base_object import BaseObject class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): FILL_FUNC_BODYclass Variation(BaseObject): schema = VariationSchema() ...
import marshmallow as ma from app.utility.base_object import BaseObject class VariationSchema(ma.Schema): description = ma.fields.String() command = ma.fields.String() @ma.post_load def build_variation(self, data, **_): FILL_FUNC_BODYclass Variation(BaseObject): schema = VariationSchema() ...
38,113
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_visibility.py
27,29
16,43
score
Visibility
29,36
29,36
class Visibility(BaseObject): MIN_SCORE = 1 MAX_SCORE = 100 schema = VisibilitySchema() @property def display(self): return self.clean(dict(score=self.score)) @property def score(self): FILL_FUNC_BODY def __init__(self): super().__init__() self._score = 50 ...
class Visibility(BaseObject): MIN_SCORE = 1 MAX_SCORE = 100 schema = VisibilitySchema() @property def display(self): return self.clean(dict(score=self.score)) @property def score(self): FILL_FUNC_BODY def __init__(self): super().__init__() self._score = 50 ...
total_score = self._score + sum([a.offset for a in self.adjustments]) if total_score > self.MAX_SCORE: return self.MAX_SCORE elif total_score < self.MIN_SCORE: return self.MIN_SCORE return total_score
total_score = self._score + sum([a.offset for a in self.adjustments]) if total_score > self.MAX_SCORE: return self.MAX_SCORE elif total_score < self.MIN_SCORE: return self.MIN_SCORE return total_score
23
144
88
232
import marshmallow as ma from app.utility.base_object import BaseObject class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): return Visibility(**data) class Visibility(BaseObje...
import marshmallow as ma from app.utility.base_object import BaseObject class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): return Visibility(**data) class Visibility(BaseObje...
38,114
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/objects/secondclass/c_visibility.py
11,13
6,16
build_visibility
VisibilitySchema
13,16
13,16
class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): FILL_FUNC_BODY
class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): FILL_FUNC_BODY
return Visibility(**data)
return Visibility(**data)
2
72
14
86
import marshmallow as ma from app.utility.base_object import BaseObject class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): FILL_FUNC_BODYclass Visibility(BaseObject): MIN_SCORE = ...
import marshmallow as ma from app.utility.base_object import BaseObject class VisibilitySchema(ma.Schema): score = ma.fields.Integer() adjustments = ma.fields.List(ma.fields.Integer()) @ma.post_load def build_visibility(self, data, **_): FILL_FUNC_BODYclass Visibility(BaseObject): MIN_SCORE = ...
38,117
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/auth_svc.py
229,230
223,246
authorized_userid
DictionaryAuthorizationPolicy
234,237
230,237
class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, user_map): super().__init__() self.user_map = user_map async def authorized_userid(self, identity): FILL_FUNC_BODY async def permits(self, identity, permission, context=None): """Check user permissi...
class DictionaryAuthorizationPolicy(AbstractAuthorizationPolicy): def __init__(self, user_map): super().__init__() self.user_map = user_map async def authorized_userid(self, identity): """Retrieve authorized user id. Return the user_id of the user identified by the identity ...
if identity in self.user_map: return identity
"""Retrieve authorized user id. Return the user_id of the user identified by the identity or 'None' if no user exists related to the identity. """ if identity in self.user_map: return identity
6
190
19
209
import base64 from collections import namedtuple from hmac import compare_digest from importlib import import_module from aiohttp import web, web_request from aiohttp.web_exceptions import HTTPUnauthorized, HTTPForbidden from aiohttp_security import api as aiohttp_security_api from aiohttp_security import SessionIdent...
import base64 from collections import namedtuple from hmac import compare_digest from importlib import import_module from aiohttp import web, web_request from aiohttp.web_exceptions import HTTPUnauthorized, HTTPForbidden from aiohttp_security import api as aiohttp_security_api from aiohttp_security import SessionIdent...
38,118
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_app_svc.py
14,16
4,71
find_link
AppServiceInterface
21,23
16,23
class AppServiceInterface(abc.ABC): @abc.abstractmethod def start_sniffer_untrusted_agents(self): """ Cyclic function that repeatedly checks if there are agents to be marked as untrusted :return: None """ raise NotImplementedError @abc.abstractmethod def find_li...
class AppServiceInterface(abc.ABC): @abc.abstractmethod def start_sniffer_untrusted_agents(self): """ Cyclic function that repeatedly checks if there are agents to be marked as untrusted :return: None """ raise NotImplementedError @abc.abstractmethod def find_li...
raise NotImplementedError
""" Locate a given link by its unique property :param unique: :return: """ raise NotImplementedError
2
470
11
481
import abc class AppServiceInterface(abc.ABC): @abc.abstractmethod def start_sniffer_untrusted_agents(self): """ Cyclic function that repeatedly checks if there are agents to be marked as untrusted :return: None """ raise NotImplementedError @abc.abstractmethod ...
import abc class AppServiceInterface(abc.ABC): @abc.abstractmethod def start_sniffer_untrusted_agents(self): """ Cyclic function that repeatedly checks if there are agents to be marked as untrusted :return: None """ raise NotImplementedError @abc.abstractmethod ...
38,119
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_auth_svc.py
26,28
4,47
login_user
AuthServiceInterface
32,34
28,34
class AuthServiceInterface(abc.ABC): @abc.abstractmethod def apply(self, app, users): """ Set up security on server boot :param app: :param users: :return: None """ raise NotImplementedError @staticmethod @abc.abstractmethod def logout_user(r...
class AuthServiceInterface(abc.ABC): @abc.abstractmethod def apply(self, app, users): """ Set up security on server boot :param app: :param users: :return: None """ raise NotImplementedError @staticmethod @abc.abstractmethod def logout_user(r...
raise NotImplementedError
""" Kick off all scheduled jobs, as their schedule determines :return: """ raise NotImplementedError
2
277
11
288
import abc class AuthServiceInterface(abc.ABC): @abc.abstractmethod def apply(self, app, users): """ Set up security on server boot :param app: :param users: :return: None """ raise NotImplementedError @staticmethod @abc.abstractmethod def ...
import abc class AuthServiceInterface(abc.ABC): @abc.abstractmethod def apply(self, app, users): """ Set up security on server boot :param app: :param users: :return: None """ raise NotImplementedError @staticmethod @abc.abstractmethod def ...
38,120
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_contact_svc.py
22,24
4,25
build_filename
ContactServiceInterface
24,25
24,25
class ContactServiceInterface(abc.ABC): @abc.abstractmethod def register_contact(self, contact): raise NotImplementedError @abc.abstractmethod def register_tunnel(self, tunnel): raise NotImplementedError @abc.abstractmethod def handle_heartbeat(self): """ Accep...
class ContactServiceInterface(abc.ABC): @abc.abstractmethod def register_contact(self, contact): raise NotImplementedError @abc.abstractmethod def register_tunnel(self, tunnel): raise NotImplementedError @abc.abstractmethod def handle_heartbeat(self): """ Accep...
raise NotImplementedError
raise NotImplementedError
2
164
9
173
import abc class ContactServiceInterface(abc.ABC): @abc.abstractmethod def register_contact(self, contact): raise NotImplementedError @abc.abstractmethod def register_tunnel(self, tunnel): raise NotImplementedError @abc.abstractmethod def handle_heartbeat(self): """ ...
import abc class ContactServiceInterface(abc.ABC): @abc.abstractmethod def register_contact(self, contact): raise NotImplementedError @abc.abstractmethod def register_tunnel(self, tunnel): raise NotImplementedError @abc.abstractmethod def handle_heartbeat(self): """ ...
38,121
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_data_svc.py
26,28
5,66
reload_data
DataServiceInterface
33,35
28,35
class DataServiceInterface(ObjectServiceInterface): @abc.abstractmethod def apply(self, collection): """ Add a new collection to RAM :param collection: :return: """ raise NotImplementedError @abc.abstractmethod def load_data(self, plugins): """ ...
class DataServiceInterface(ObjectServiceInterface): @abc.abstractmethod def apply(self, collection): """ Add a new collection to RAM :param collection: :return: """ raise NotImplementedError @abc.abstractmethod def load_data(self, plugins): """ ...
raise NotImplementedError
""" Blocking read all the data sources to populate the object store :return: None """ raise NotImplementedError
2
405
11
416
import abc from app.service.interfaces.i_object_svc import ObjectServiceInterface class DataServiceInterface(ObjectServiceInterface): @abc.abstractmethod def apply(self, collection): """ Add a new collection to RAM :param collection: :return: """ raise NotImpl...
import abc from app.service.interfaces.i_object_svc import ObjectServiceInterface class DataServiceInterface(ObjectServiceInterface): @abc.abstractmethod def apply(self, collection): """ Add a new collection to RAM :param collection: :return: """ raise NotImpl...
38,122
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_event_svc.py
6,8
4,26
observe_event
EventServiceInterface
8,17
8,17
class EventServiceInterface(abc.ABC): @abc.abstractmethod def observe_event(self, event, callback): FILL_FUNC_BODY @abc.abstractmethod def fire_event(self, event, **callback_kwargs): """ Fire an event :param event: The event topic and (optional) subtopic, separated by a '/' ...
class EventServiceInterface(abc.ABC): @abc.abstractmethod def observe_event(self, event, callback): FILL_FUNC_BODY @abc.abstractmethod def fire_event(self, event, **callback_kwargs): """ Fire an event :param event: The event topic and (optional) subtopic, separated by a '/' ...
""" Register an event handler :param event: The event topic and (optional) subtopic, separated by a '/' :param callback: The function that will handle the event :return: None """ raise NotImplementedError
""" Register an event handler :param event: The event topic and (optional) subtopic, separated by a '/' :param callback: The function that will handle the event :return: None """ raise NotImplementedError
31
130
71
201
import abc class EventServiceInterface(abc.ABC): @abc.abstractmethod def observe_event(self, event, callback): FILL_FUNC_BODY @abc.abstractmethod def fire_event(self, event, **callback_kwargs): """ Fire an event :param event: The event topic and (optional) subtopic, separated b...
import abc class EventServiceInterface(abc.ABC): @abc.abstractmethod def observe_event(self, event, callback): FILL_FUNC_BODY @abc.abstractmethod def fire_event(self, event, **callback_kwargs): """ Fire an event :param event: The event topic and (optional) subtopic, separated b...
38,123
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_file_svc.py
65,67
4,106
write_result_file
FileServiceInterface
75,77
67,77
class FileServiceInterface(abc.ABC): @abc.abstractmethod def get_file(self, headers): """ Retrieve file :param headers: headers dictionary. The `file` key is REQUIRED. :type headers: dict or dict-equivalent :return: File contents and optionally a display_name if the payl...
class FileServiceInterface(abc.ABC): @abc.abstractmethod def get_file(self, headers): """ Retrieve file :param headers: headers dictionary. The `file` key is REQUIRED. :type headers: dict or dict-equivalent :return: File contents and optionally a display_name if the payl...
raise NotImplementedError
""" Writes the results of a link execution to disk. If file encryption is enabled, the results file will contain ciphertext. :param link_id: The link id of the result being written. :param output: The content of the link's output. :param location: The path to the results ...
2
948
11
959
import abc class FileServiceInterface(abc.ABC): @abc.abstractmethod def get_file(self, headers): """ Retrieve file :param headers: headers dictionary. The `file` key is REQUIRED. :type headers: dict or dict-equivalent :return: File contents and optionally a display_nam...
import abc class FileServiceInterface(abc.ABC): @abc.abstractmethod def get_file(self, headers): """ Retrieve file :param headers: headers dictionary. The `file` key is REQUIRED. :type headers: dict or dict-equivalent :return: File contents and optionally a display_nam...
38,124
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_knowledge_svc.py
122,124
5,140
get_rules
KnowledgeServiceInterface
130,132
124,132
class KnowledgeServiceInterface(ObjectServiceInterface): @abc.abstractmethod async def add_fact(self, fact, constraints=None): """ Add a fact to the internal store :param fact: Fact to add :param constraints: any potential constraints """ raise NotImplementedErr...
class KnowledgeServiceInterface(ObjectServiceInterface): @abc.abstractmethod async def add_fact(self, fact, constraints=None): """ Add a fact to the internal store :param fact: Fact to add :param constraints: any potential constraints """ raise NotImplementedErr...
raise NotImplementedError
""" Retrieve rules from the internal store :param criteria: dictionary containing fields to match on :return: list of matching rules """ raise NotImplementedError
2
1,044
11
1,055
import abc from app.service.interfaces.i_object_svc import ObjectServiceInterface class KnowledgeServiceInterface(ObjectServiceInterface): @abc.abstractmethod async def add_fact(self, fact, constraints=None): """ Add a fact to the internal store :param fact: Fact to add :para...
import abc from app.service.interfaces.i_object_svc import ObjectServiceInterface class KnowledgeServiceInterface(ObjectServiceInterface): @abc.abstractmethod async def add_fact(self, fact, constraints=None): """ Add a fact to the internal store :param fact: Fact to add :para...
38,125
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_learning_svc.py
6,9
4,23
add_parsers
LearningServiceInterface
9,11
9,11
class LearningServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def add_parsers(directory): FILL_FUNC_BODY @abc.abstractmethod def build_model(self): """ The model is a static set of all variables used inside all ability commands This can be used to determine which...
class LearningServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def add_parsers(directory): FILL_FUNC_BODY @abc.abstractmethod def build_model(self): """ The model is a static set of all variables used inside all ability commands This can be used to determine which...
raise NotImplementedError
raise NotImplementedError
2
151
11
162
import abc class LearningServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def add_parsers(directory): FILL_FUNC_BODY @abc.abstractmethod def build_model(self): """ The model is a static set of all variables used inside all ability commands This can be used to de...
import abc class LearningServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def add_parsers(directory): FILL_FUNC_BODY @abc.abstractmethod def build_model(self): """ The model is a static set of all variables used inside all ability commands This can be used to de...
38,126
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_login_handler.py
11,13
6,34
handle_login
LoginHandlerInterface
19,21
13,21
class LoginHandlerInterface(abc.ABC, BaseObject): def __init__(self, services, name): self.services = services self._name = name @abc.abstractmethod async def handle_login(self, request, **kwargs): FILL_FUNC_BODY @abc.abstractmethod async def handle_login_redirect(self, request, **kw...
class LoginHandlerInterface(abc.ABC, BaseObject): def __init__(self, services, name): self.services = services self._name = name @abc.abstractmethod async def handle_login(self, request, **kwargs): """Handle login request :param request: :return: the response/locati...
raise NotImplementedError
"""Handle login request :param request: :return: the response/location of where the user is trying to navigate :raises: HTTP exception, such as HTTPFound for redirect, or HTTPUnauthorized """ raise NotImplementedError
2
235
11
246
import abc from app.utility.base_object import BaseObject class LoginHandlerInterface(abc.ABC, BaseObject): def __init__(self, services, name): self.services = services self._name = name @abc.abstractmethod async def handle_login(self, request, **kwargs): FILL_FUNC_BODY @abc.abstractm...
import abc from app.utility.base_object import BaseObject class LoginHandlerInterface(abc.ABC, BaseObject): def __init__(self, services, name): self.services = services self._name = name @abc.abstractmethod async def handle_login(self, request, **kwargs): """Handle login request ...
38,127
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_object_svc.py
6,9
4,30
destroy
ObjectServiceInterface
13,15
9,15
class ObjectServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def destroy(): FILL_FUNC_BODY @abc.abstractmethod def save_state(self): """ Save stored data to disk :return: """ raise NotImplementedError @abc.abstractmethod def restore_state(...
class ObjectServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def destroy(): """ Clear out all data :return: """ FILL_FUNC_BODY @abc.abstractmethod def save_state(self): """ Save stored data to disk :return: """ raise...
raise NotImplementedError
""" Clear out all data :return: """ raise NotImplementedError
2
143
11
154
import abc class ObjectServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def destroy(): FILL_FUNC_BODY @abc.abstractmethod def save_state(self): """ Save stored data to disk :return: """ raise NotImplementedError @abc.abstractmethod def r...
import abc class ObjectServiceInterface(abc.ABC): @staticmethod @abc.abstractmethod def destroy(): """ Clear out all data :return: """ FILL_FUNC_BODY @abc.abstractmethod def save_state(self): """ Save stored data to disk :return: """ ...
38,128
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_planning_svc.py
6,8
4,41
get_links
PlanningServiceInterface
17,19
8,19
class PlanningServiceInterface(abc.ABC): @abc.abstractmethod def get_links(self, operation, buckets, agent, trim): FILL_FUNC_BODY @abc.abstractmethod def get_cleanup_links(self, operation, agent): """ For a given operation, create all cleanup links. If agent is supplied, only ret...
class PlanningServiceInterface(abc.ABC): @abc.abstractmethod def get_links(self, operation, buckets, agent, trim): """ For an operation and agent combination, create links (that can be executed). When no agent is supplied, links for all agents are returned :param operation: ...
raise NotImplementedError
""" For an operation and agent combination, create links (that can be executed). When no agent is supplied, links for all agents are returned :param operation: :param buckets: :param agent: :param trim: call trim_links() on list of links before returning :...
2
311
11
322
import abc class PlanningServiceInterface(abc.ABC): @abc.abstractmethod def get_links(self, operation, buckets, agent, trim): FILL_FUNC_BODY @abc.abstractmethod def get_cleanup_links(self, operation, agent): """ For a given operation, create all cleanup links. If agent is suppl...
import abc class PlanningServiceInterface(abc.ABC): @abc.abstractmethod def get_links(self, operation, buckets, agent, trim): """ For an operation and agent combination, create links (that can be executed). When no agent is supplied, links for all agents are returned :param op...
38,129
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/interfaces/i_rest_svc.py
46,48
4,117
delete_operation
RestServiceInterface
48,50
48,50
class RestServiceInterface(abc.ABC): @abc.abstractmethod def persist_adversary(self, access, data): """ Save a new adversary from either the GUI or REST API. This writes a new YML file into the core data/ directory. :param access :param data: :return: the ID of the creat...
class RestServiceInterface(abc.ABC): @abc.abstractmethod def persist_adversary(self, access, data): """ Save a new adversary from either the GUI or REST API. This writes a new YML file into the core data/ directory. :param access :param data: :return: the ID of the creat...
raise NotImplementedError
raise NotImplementedError
2
899
11
910
import abc class RestServiceInterface(abc.ABC): @abc.abstractmethod def persist_adversary(self, access, data): """ Save a new adversary from either the GUI or REST API. This writes a new YML file into the core data/ directory. :param access :param data: :return: the ID...
import abc class RestServiceInterface(abc.ABC): @abc.abstractmethod def persist_adversary(self, access, data): """ Save a new adversary from either the GUI or REST API. This writes a new YML file into the core data/ directory. :param access :param data: :return: the ID...
38,130
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/knowledge_svc.py
27,28
11,87
update_fact
KnowledgeService
28,31
28,31
class KnowledgeService(KnowledgeServiceInterface, BaseService): def __init__(self): self.log = self.add_service('knowledge_svc', self) self.__loaded_knowledge_module = BaseKnowledgeService() @staticmethod def _load_module(module_type, module_info): module = import_module(module_inf...
class KnowledgeService(KnowledgeServiceInterface, BaseService): def __init__(self): self.log = self.add_service('knowledge_svc', self) self.__loaded_knowledge_module = BaseKnowledgeService() @staticmethod def _load_module(module_type, module_info): module = import_module(module_inf...
await self.get_service('event_svc').fire_event(exchange='fact', queue='updated', criteria=criteria, updates=updates) return await self.__loaded_knowledge_module._update_fact(criteria, updates)
await self.get_service('event_svc').fire_event(exchange='fact', queue='updated', criteria=criteria, updates=updates) return await self.__loaded_knowledge_module._update_fact(criteria, updates)
9
851
64
915
from importlib import import_module from app.objects.secondclass.c_fact import Fact from app.objects.secondclass.c_relationship import Relationship from app.objects.secondclass.c_rule import Rule from app.service.interfaces.i_knowledge_svc import KnowledgeServiceInterface from app.utility.base_knowledge_svc import Bas...
from importlib import import_module from app.objects.secondclass.c_fact import Fact from app.objects.secondclass.c_relationship import Relationship from app.objects.secondclass.c_rule import Rule from app.service.interfaces.i_knowledge_svc import KnowledgeServiceInterface from app.utility.base_knowledge_svc import Bas...
38,131
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/learning_svc.py
39,40
13,66
learn
LearningService
40,52
40,52
class LearningService(LearningServiceInterface, BaseService): def __init__(self): self.log = self.add_service('learning_svc', self) self.model = set() self.parsers = self.add_parsers('app/learning') self.re_variable = re.compile(r'#{(.*?)}', flags=re.DOTALL) self.log.debug('...
class LearningService(LearningServiceInterface, BaseService): def __init__(self): self.log = self.add_service('learning_svc', self) self.model = set() self.parsers = self.add_parsers('app/learning') self.re_variable = re.compile(r'#{(.*?)}', flags=re.DOTALL) self.log.debug('...
decoded_blob = b64decode(blob).decode('utf-8') found_facts = [] for parser in self.parsers: try: for fact in parser.parse(decoded_blob): found_facts.append(fact) except Exception as e: self.log.error(e) await up...
decoded_blob = b64decode(blob).decode('utf-8') found_facts = [] for parser in self.parsers: try: for fact in parser.parse(decoded_blob): found_facts.append(fact) except Exception as e: self.log.error(e) await up...
30
563
150
713
import itertools import glob import re from base64 import b64decode from importlib import import_module from app.objects.secondclass.c_relationship import Relationship from app.objects.secondclass.c_link import update_scores from app.service.interfaces.i_learning_svc import LearningServiceInterface from app.utility.ba...
import itertools import glob import re from base64 import b64decode from importlib import import_module from app.objects.secondclass.c_relationship import Relationship from app.objects.secondclass.c_link import update_scores from app.service.interfaces.i_learning_svc import LearningServiceInterface from app.utility.ba...
38,132
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/service/login_handlers/default.py
37,38
13,91
handle_login_redirect
DefaultLoginHandler
44,49
38,49
class DefaultLoginHandler(LoginHandlerInterface): def __init__(self, services): super().__init__(services, HANDLER_NAME) self.log = logging.getLogger('default_login_handler') self._ldap_config = self.get_config('ldap') async def handle_login(self, request, **kwargs): data = awai...
class DefaultLoginHandler(LoginHandlerInterface): def __init__(self, services): super().__init__(services, HANDLER_NAME) self.log = logging.getLogger('default_login_handler') self._ldap_config = self.get_config('ldap') async def handle_login(self, request, **kwargs): data = awai...
if kwargs.get('use_template'): return render_template('login.html', request, dict()) else: raise web.HTTPFound('/login')
"""Handle login redirect. :return: login.html template if use_template is set to True in kwargs. :raises web.HTTPFound: HTTPFound exception to redirect to the '/login' page if use_template is set to False or not included in kwargs. """ if kwargs.get('use_template'): ...
9
892
49
941
import logging import ldap3 from aiohttp import web from aiohttp_jinja2 import render_template from ldap3.core.exceptions import LDAPAttributeError, LDAPException from app.service.interfaces.i_login_handler import LoginHandlerInterface HANDLER_NAME = 'Default Login Handler' class DefaultLoginHandler(LoginHandlerIn...
import logging import ldap3 from aiohttp import web from aiohttp_jinja2 import render_template from ldap3.core.exceptions import LDAPAttributeError, LDAPException from app.service.interfaces.i_login_handler import LoginHandlerInterface HANDLER_NAME = 'Default Login Handler' class DefaultLoginHandler(LoginHandlerIn...
38,133
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_obfuscator.py
12,13
7,24
run
BaseObfuscator
13,24
13,24
class BaseObfuscator(BaseWorld): def __init__(self, agent): self.agent = agent def run(self, link, **kwargs): FILL_FUNC_BODY
class BaseObfuscator(BaseWorld): def __init__(self, agent): self.agent = agent def run(self, link, **kwargs): FILL_FUNC_BODY
agent = self.__getattribute__('agent') supported_platforms = self.__getattribute__('supported_platforms') try: if agent.platform in supported_platforms and link.executor.name in agent.executors: link.command_hash = hashlib.sha256(str.encode(link.command)).hexdigest() ...
agent = self.__getattribute__('agent') supported_platforms = self.__getattribute__('supported_platforms') try: if agent.platform in supported_platforms and link.executor.name in agent.executors: link.command_hash = hashlib.sha256(str.encode(link.command)).hexdigest() ...
36
52
163
215
import logging import hashlib from app.utility.base_world import BaseWorld class BaseObfuscator(BaseWorld): def __init__(self, agent): self.agent = agent def run(self, link, **kwargs): FILL_FUNC_BODY
import logging import hashlib from app.utility.base_world import BaseWorld class BaseObfuscator(BaseWorld): def __init__(self, agent): self.agent = agent def run(self, link, **kwargs): FILL_FUNC_BODY
38,134
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_object.py
107,109
106,112
is_global_variable
AppConfigGlobalVariableIdentifier
109,112
109,112
class AppConfigGlobalVariableIdentifier: @classmethod def is_global_variable(cls, variable): FILL_FUNC_BODY
class AppConfigGlobalVariableIdentifier: @classmethod def is_global_variable(cls, variable): FILL_FUNC_BODY
if variable.startswith('app.'): return variable in BaseWorld.get_config() return False
if variable.startswith('app.'): return variable in BaseWorld.get_config() return False
8
36
31
67
from app.utility.base_world import BaseWorld class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): if not criteria: ...
from app.utility.base_world import BaseWorld class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): if not criteria: ...
38,135
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_object.py
14,15
4,106
match
BaseObject
15,29
15,29
class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): FILL_FUNC_BODY def update(self, field, value): """ Upda...
class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): FILL_FUNC_BODY def update(self, field, value): """ Upda...
if not criteria: return self criteria_matches = [] for k, v in criteria.items(): if type(v) is tuple: for val in v: if getattr(self, k) == val: criteria_matches.append(True) else: if g...
if not criteria: return self criteria_matches = [] for k, v in criteria.items(): if type(v) is tuple: for val in v: if getattr(self, k) == val: criteria_matches.append(True) else: if g...
42
708
143
851
from app.utility.base_world import BaseWorld class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): FILL_FUNC_BODY def updat...
from app.utility.base_world import BaseWorld class BaseObject(BaseWorld): schema = None display_schema = None load_schema = None def __init__(self): self._access = self.Access.APP self._created = self.get_current_timestamp() def match(self, criteria): FILL_FUNC_BODY def updat...
38,136
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_parser.py
30,32
7,71
email
BaseParser
37,39
32,39
class BaseParser: def __init__(self, parser_info): self.mappers = parser_info['mappers'] self.used_facts = parser_info['used_facts'] self.source_facts = parser_info['source_facts'] @staticmethod def set_value(search, match, used_facts): """ Determine the value of a ...
class BaseParser: def __init__(self, parser_info): self.mappers = parser_info['mappers'] self.used_facts = parser_info['used_facts'] self.source_facts = parser_info['source_facts'] @staticmethod def set_value(search, match, used_facts): """ Determine the value of a ...
return re.findall(r'[\w\.-]+@[\w\.-]+', blob)
""" Parse out email addresses :param blob: :return: """ return re.findall(r'[\w\.-]+@[\w\.-]+', blob)
3
531
30
561
import json import re PARSER_SIGNALS_FAILURE = 418 # Universal Teapot error code class BaseParser: def __init__(self, parser_info): self.mappers = parser_info['mappers'] self.used_facts = parser_info['used_facts'] self.source_facts = parser_info['source_facts'] @staticmethod de...
import json import re PARSER_SIGNALS_FAILURE = 418 # Universal Teapot error code class BaseParser: def __init__(self, parser_info): self.mappers = parser_info['mappers'] self.used_facts = parser_info['used_facts'] self.source_facts = parser_info['source_facts'] @staticmethod de...
38,137
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_service.py
8,9
4,23
add_service
BaseService
9,12
9,12
class BaseService(BaseWorld): _services = dict() def add_service(self, name, svc): FILL_FUNC_BODY @classmethod def remove_service(cls, name): del cls._services[name] @classmethod def get_service(cls, name): return cls._services.get(name) @classmethod def get_services(c...
class BaseService(BaseWorld): _services = dict() def add_service(self, name, svc): FILL_FUNC_BODY @classmethod def remove_service(cls, name): del cls._services[name] @classmethod def get_service(cls, name): return cls._services.get(name) @classmethod def get_services(c...
self.__class__._services[name] = svc return self.create_logger(name)
self.__class__._services[name] = svc return self.create_logger(name)
5
118
29
147
from app.utility.base_world import BaseWorld class BaseService(BaseWorld): _services = dict() def add_service(self, name, svc): FILL_FUNC_BODY @classmethod def remove_service(cls, name): del cls._services[name] @classmethod def get_service(cls, name): return cls._services.get...
from app.utility.base_world import BaseWorld class BaseService(BaseWorld): _services = dict() def add_service(self, name, svc): FILL_FUNC_BODY @classmethod def remove_service(cls, name): del cls._services[name] @classmethod def get_service(cls, name): return cls._services.get...
38,138
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/base_world.py
114,116
18,166
is_uuid4
BaseWorld
116,120
116,120
class BaseWorld: """ A collection of base static functions for service & object module usage """ _app_configuration = dict() re_base64 = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', flags=re.DOTALL) TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' @staticmethod def app...
class BaseWorld: """ A collection of base static functions for service & object module usage """ _app_configuration = dict() re_base64 = re.compile('[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', flags=re.DOTALL) TIME_FORMAT = '%Y-%m-%dT%H:%M:%SZ' @staticmethod def app...
if BaseWorld.re_base64.match(s): return True return False
if BaseWorld.re_base64.match(s): return True return False
6
1,455
29
1,484
import binascii import string import re import yaml import logging import subprocess import packaging.version from base64 import b64encode, b64decode from datetime import datetime, timezone from importlib import import_module from random import randint, choice from enum import Enum import marshmallow as ma import mars...
import binascii import string import re import yaml import logging import subprocess import packaging.version from base64 import b64encode, b64decode from datetime import datetime, timezone from importlib import import_module from random import randint, choice from enum import Enum import marshmallow as ma import mars...
38,139
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/config_generator.py
47,48
1,60
ensure_local_config
51,60
48,60
import logging import pathlib import secrets import jinja2 import yaml CONFIG_MSG_TEMPLATE = jinja2.Template(""" Log into Caldera with the following admin credentials: Red: {%- if users.red.red %} USERNAME: red PASSWORD: {{ users.red.red }} {%- endif %} API_TOKEN: {{ api_key_red }...
import logging import pathlib import secrets import jinja2 import yaml CONFIG_MSG_TEMPLATE = jinja2.Template(""" Log into Caldera with the following admin credentials: Red: {%- if users.red.red %} USERNAME: red PASSWORD: {{ users.red.red }} {%- endif %} API_TOKEN: {{ api_key_red }...
local_conf_path = pathlib.Path('conf/local.yml') if local_conf_path.exists(): return logging.info('Creating new secure config in %s' % local_conf_path) with local_conf_path.open('w') as fle: yaml.safe_dump(make_secure_config(), fle, default_flow_style=False) log_config_message(loca...
""" Checks if a local.yml config file exists. If not, generates a new local.yml file using secure random values. """ local_conf_path = pathlib.Path('conf/local.yml') if local_conf_path.exists(): return logging.info('Creating new secure config in %s' % local_conf_path) with local_con...
22
468
122
590
import logging import pathlib import secrets import jinja2 import yaml CONFIG_MSG_TEMPLATE = jinja2.Template(""" Log into Caldera with the following admin credentials: Red: {%- if users.red.red %} USERNAME: red PASSWORD: {{ users.red.red }} {%- endif %} API_TOKEN: {{ api_key_red }...
import logging import pathlib import secrets import jinja2 import yaml CONFIG_MSG_TEMPLATE = jinja2.Template(""" Log into Caldera with the following admin credentials: Red: {%- if users.red.red %} USERNAME: red PASSWORD: {{ users.red.red }} {%- endif %} API_TOKEN: {{ api_key_red }...
38,140
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/file_decryptor.py
45,46
1,77
decrypt
46,57
46,57
import os import yaml import base64 import argparse from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC description = """ This script is for the purpose of dec...
import os import yaml import base64 import argparse from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC description = """ This script is for the purpose of dec...
encryptor = get_encryptor(configuration['crypt_salt'], configuration['encryption_key']) if not output_file: output_file = filename + '_decrypted' with open(output_file, 'wb') as f: if b64decode: f.write(base64.b64decode(read(filename, encryptor))) else: f.writ...
encryptor = get_encryptor(configuration['crypt_salt'], configuration['encryption_key']) if not output_file: output_file = filename + '_decrypted' with open(output_file, 'wb') as f: if b64decode: f.write(base64.b64decode(read(filename, encryptor))) else: f.writ...
30
892
142
1,034
import os import yaml import base64 import argparse from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC description = """ This script is for the purpose of dec...
import os import yaml import base64 import argparse from cryptography.fernet import Fernet from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC description = """ This script is for the purpose of dec...
38,141
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/payload_encoder.py
25,26
1,53
xor_bytes
26,35
26,35
""" This module contains helper functions for encoding and decoding payload files. If AV is running on the server host, then it may sometimes flag, quarantine, or delete Caldera payloads. To help prevent this, encoded payloads can be used to prevent AV from breaking the server. The convention expected by the server is...
""" This module contains helper functions for encoding and decoding payload files. If AV is running on the server host, then it may sometimes flag, quarantine, or delete Caldera payloads. To help prevent this, encoded payloads can be used to prevent AV from breaking the server. The convention expected by the server is...
if not key: key = DEFAULT_KEY arr = array.array('B', in_bytes) for i, val in enumerate(arr): cur_key = key[i % len(key)] arr[i] = val ^ cur_key return bytes(arr)
if not key: key = DEFAULT_KEY arr = array.array('B', in_bytes) for i, val in enumerate(arr): cur_key = key[i % len(key)] arr[i] = val ^ cur_key return bytes(arr)
27
456
83
539
""" This module contains helper functions for encoding and decoding payload files. If AV is running on the server host, then it may sometimes flag, quarantine, or delete Caldera payloads. To help prevent this, encoded payloads can be used to prevent AV from breaking the server. The convention expected by the server is...
""" This module contains helper functions for encoding and decoding payload files. If AV is running on the server host, then it may sometimes flag, quarantine, or delete Caldera payloads. To help prevent this, encoded payloads can be used to prevent AV from breaking the server. The convention expected by the server is...
38,142
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/utility/rule_set.py
73,74
11,102
_is_ip_rule_match
RuleSet
87,102
74,102
class RuleSet: def __init__(self, rules): self.rules = rules async def is_fact_allowed(self, fact): allowed = True for rule in await self._applicable_rules(fact): if await self._is_ip_rule_match(rule, fact): allowed = await self._rule_judgement(rule.action) ...
class RuleSet: def __init__(self, rules): self.rules = rules async def is_fact_allowed(self, fact): allowed = True for rule in await self._applicable_rules(fact): if await self._is_ip_rule_match(rule, fact): allowed = await self._rule_judgement(rule.action) ...
if rule.match != '.*': is_fact_address = await self._is_ip_address(fact.value) is_fact_network = await self._is_ip_network(fact.value) is_rule_address = await self._is_ip_address(rule.match) is_rule_network = await self._is_ip_network(rule.match) if i...
""" We only match string-equivalent IP addresses, string-equivalent subnets in CIDR notation, and IP address facts to the subnet rules where the address is a member of the subnet. Matching non-equivalent subnets is complicated, because of the following general case: ...
52
774
227
1,001
import re from enum import Enum import ipaddress class RuleAction(Enum): ALLOW = 1 DENY = 0 class RuleSet: def __init__(self, rules): self.rules = rules async def is_fact_allowed(self, fact): allowed = True for rule in await self._applicable_rules(fact): if await...
import re from enum import Enum import ipaddress class RuleAction(Enum): ALLOW = 1 DENY = 0 class RuleSet: def __init__(self, rules): self.rules = rules async def is_fact_allowed(self, fact): allowed = True for rule in await self._applicable_rules(fact): if await...
38,143
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera
/home/hieuvd/dung_repo/raw/stars_02/mitre_caldera/caldera/app/version.py
4,5
1,6
get_version
5,6
5,6
__version__ = '5.0.0' def get_version(): FILL_FUNC_BODY
__version__ = '5.0.0' def get_version(): FILL_FUNC_BODY
return __version__
return __version__
2
30
7
37
__version__ = '5.0.0' def get_version(): FILL_FUNC_BODY
__version__ = '5.0.0' def get_version(): FILL_FUNC_BODY
38,185
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/baseline.py
37,38
20,45
is_fitted
BaselineClassifierAlgorithm
38,45
38,45
class BaselineClassifierAlgorithm(SklearnAlgorithm, ClassifierMixin): algorithm_name = "Baseline Classifier" algorithm_short_name = "Baseline" def __init__(self, params): super(BaselineClassifierAlgorithm, self).__init__(params) logger.debug("BaselineClassifierAlgorithm.__init__") ...
class BaselineClassifierAlgorithm(SklearnAlgorithm, ClassifierMixin): algorithm_name = "Baseline Classifier" algorithm_short_name = "Baseline" def __init__(self, params): super(BaselineClassifierAlgorithm, self).__init__(params) logger.debug("BaselineClassifierAlgorithm.__init__") ...
return ( hasattr(self.model, "n_outputs_") and self.model.n_outputs_ is not None and self.model.n_outputs_ > 0 )
return ( hasattr(self.model, "n_outputs_") and self.model.n_outputs_ is not None and self.model.n_outputs_ > 0 )
14
194
61
255
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.dummy import DummyClassifier, DummyRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised.algorithms.s...
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.dummy import DummyClassifier, DummyRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised.algorithms.s...
38,186
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/baseline.py
60,61
45,68
is_fitted
BaselineRegressorAlgorithm
61,68
61,68
class BaselineRegressorAlgorithm(SklearnAlgorithm, RegressorMixin): algorithm_name = "Baseline Regressor" algorithm_short_name = "Baseline" def __init__(self, params): super(BaselineRegressorAlgorithm, self).__init__(params) logger.debug("BaselineRegressorAlgorithm.__init__") self....
class BaselineRegressorAlgorithm(SklearnAlgorithm, RegressorMixin): algorithm_name = "Baseline Regressor" algorithm_short_name = "Baseline" def __init__(self, params): super(BaselineRegressorAlgorithm, self).__init__(params) logger.debug("BaselineRegressorAlgorithm.__init__") self....
return ( hasattr(self.model, "n_outputs_") and self.model.n_outputs_ is not None and self.model.n_outputs_ > 0 )
return ( hasattr(self.model, "n_outputs_") and self.model.n_outputs_ is not None and self.model.n_outputs_ > 0 )
14
183
61
244
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.dummy import DummyClassifier, DummyRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised.algorithms.s...
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.dummy import DummyClassifier, DummyRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised.algorithms.s...
38,189
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/extra_trees.py
48,49
23,52
file_extension
ExtraTreesAlgorithm
49,52
49,52
class ExtraTreesAlgorithm(SklearnTreesEnsembleClassifierAlgorithm, ClassifierMixin): algorithm_name = "Extra Trees Classifier" algorithm_short_name = "Extra Trees" def __init__(self, params): super(ExtraTreesAlgorithm, self).__init__(params) logger.debug("ExtraTreesAlgorithm.__init__") ...
class ExtraTreesAlgorithm(SklearnTreesEnsembleClassifierAlgorithm, ClassifierMixin): algorithm_name = "Extra Trees Classifier" algorithm_short_name = "Extra Trees" def __init__(self, params): super(ExtraTreesAlgorithm, self).__init__(params) logger.debug("ExtraTreesAlgorithm.__init__") ...
return "extra_trees"
return "extra_trees"
2
394
13
407
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised...
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised...
38,190
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/extra_trees.py
81,82
52,86
file_extension
ExtraTreesRegressorAlgorithm
82,86
82,86
class ExtraTreesRegressorAlgorithm( SklearnTreesEnsembleRegressorAlgorithm, RegressorMixin ): algorithm_name = "Extra Trees Regressor" algorithm_short_name = "Extra Trees" def __init__(self, params): super(ExtraTreesRegressorAlgorithm, self).__init__(params) logger.debug("ExtraTreesRegr...
class ExtraTreesRegressorAlgorithm( SklearnTreesEnsembleRegressorAlgorithm, RegressorMixin ): algorithm_name = "Extra Trees Regressor" algorithm_short_name = "Extra Trees" def __init__(self, params): super(ExtraTreesRegressorAlgorithm, self).__init__(params) logger.debug("ExtraTreesRegr...
return "extra_trees" # For binary classification target should be 0, 1. There should be no NaNs in target.
return "extra_trees" # For binary classification target should be 0, 1. There should be no NaNs in target.
18
427
38
465
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised...
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.ensemble import ExtraTreesClassifier, ExtraTreesRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRESSION, AlgorithmsRegistry, ) from supervised...
38,191
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/factory.py
11,13
10,29
get_algorithm
AlgorithmFactory
13,22
13,22
class AlgorithmFactory(object): @classmethod def get_algorithm(cls, params): FILL_FUNC_BODY @classmethod def load(cls, json_desc, learner_path, lazy_load): learner = AlgorithmFactory.get_algorithm(json_desc.get("params")) learner.set_params(json_desc, learner_path) if not lazy_loa...
class AlgorithmFactory(object): @classmethod def get_algorithm(cls, params): FILL_FUNC_BODY @classmethod def load(cls, json_desc, learner_path, lazy_load): learner = AlgorithmFactory.get_algorithm(json_desc.get("params")) learner.set_params(json_desc, learner_path) if not lazy_loa...
alg_type = params.get("model_type", "Xgboost") ml_task = params.get("ml_task", BINARY_CLASSIFICATION) try: Algorithm = AlgorithmsRegistry.get_algorithm_class(ml_task, alg_type) return Algorithm(params) except Exception as e: raise AutoMLException(f"Ca...
alg_type = params.get("model_type", "Xgboost") ml_task = params.get("ml_task", BINARY_CLASSIFICATION) try: Algorithm = AlgorithmsRegistry.get_algorithm_class(ml_task, alg_type) return Algorithm(params) except Exception as e: raise AutoMLException(f"Ca...
25
117
113
230
import logging from supervised.algorithms.registry import BINARY_CLASSIFICATION, AlgorithmsRegistry logger = logging.getLogger(__name__) from supervised.exceptions import AutoMLException class AlgorithmFactory(object): @classmethod def get_algorithm(cls, params): FILL_FUNC_BODY @classmethod def load...
import logging from supervised.algorithms.registry import BINARY_CLASSIFICATION, AlgorithmsRegistry logger = logging.getLogger(__name__) from supervised.exceptions import AutoMLException class AlgorithmFactory(object): @classmethod def get_algorithm(cls, params): FILL_FUNC_BODY @classmethod def load...
38,192
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/knn.py
35,46
24,64
fit
KNNFit
46,55
46,55
class KNNFit(SklearnAlgorithm, ClassifierMixin): def file_extension(self): return "k_neighbors" def is_fitted(self): return ( hasattr(self.model, "n_samples_fit_") and self.model.n_samples_fit_ is not None and self.model.n_samples_fit_ > 0 ) def ...
class KNNFit(SklearnAlgorithm, ClassifierMixin): def file_extension(self): return "k_neighbors" def is_fitted(self): return ( hasattr(self.model, "n_samples_fit_") and self.model.n_samples_fit_ is not None and self.model.n_samples_fit_ > 0 ) def ...
rows_limit = self.params.get("rows_limit", KNN_ROWS_LIMIT) if X.shape[0] > rows_limit: X1, _, y1, _ = train_test_split( X, y, train_size=rows_limit, stratify=y, random_state=1234 ) self.model.fit(X1, y1) else: self.model.fit(X, y)
rows_limit = self.params.get("rows_limit", KNN_ROWS_LIMIT) if X.shape[0] > rows_limit: X1, _, y1, _ = train_test_split( X, y, train_size=rows_limit, stratify=y, random_state=1234 ) self.model.fit(X1, y1) else: self.model.fit(X, y)
25
246
127
373
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, ...
import logging import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.model_selection import train_test_split from sklearn.neighbors import KNeighborsClassifier, KNeighborsRegressor from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, ...
38,195
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/linear.py
46,60
23,107
interpret
LinearAlgorithm
60,107
60,107
class LinearAlgorithm(SklearnAlgorithm, ClassifierMixin): algorithm_name = "Logistic Regression" algorithm_short_name = "Linear" def __init__(self, params): super(LinearAlgorithm, self).__init__(params) logger.debug("LinearAlgorithm.__init__") self.max_iters = 1 self.library...
class LinearAlgorithm(SklearnAlgorithm, ClassifierMixin): algorithm_name = "Logistic Regression" algorithm_short_name = "Linear" def __init__(self, params): super(LinearAlgorithm, self).__init__(params) logger.debug("LinearAlgorithm.__init__") self.max_iters = 1 self.library...
super(LinearAlgorithm, self).interpret( X_train, y_train, X_validation, y_validation, model_file_path, learner_name, target_name, class_names, metric_name, ml_task, explain_level, ...
super(LinearAlgorithm, self).interpret( X_train, y_train, X_validation, y_validation, model_file_path, learner_name, target_name, class_names, metric_name, ml_task, explain_level, ...
105
334
508
842
import logging import os import numpy as np import pandas as pd import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.linear_model import LinearRegression, LogisticRegression from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRE...
import logging import os import numpy as np import pandas as pd import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.linear_model import LinearRegression, LogisticRegression from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRE...
38,196
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised
/home/hieuvd/dung_repo/raw/stars_02/mljar_mljar-supervised/mljar-supervised/supervised/algorithms/linear.py
118,119
107,173
is_fitted
LinearRegressorAlgorithm
119,125
119,125
class LinearRegressorAlgorithm(SklearnAlgorithm, RegressorMixin): algorithm_name = "Linear Regression" algorithm_short_name = "Linear" def __init__(self, params): super(LinearRegressorAlgorithm, self).__init__(params) logger.debug("LinearRegressorAlgorithm.__init__") self.max_iters ...
class LinearRegressorAlgorithm(SklearnAlgorithm, RegressorMixin): algorithm_name = "Linear Regression" algorithm_short_name = "Linear" def __init__(self, params): super(LinearRegressorAlgorithm, self).__init__(params) logger.debug("LinearRegressorAlgorithm.__init__") self.max_iters ...
return ( hasattr(self.model, "coef_") and self.model.coef_ is not None and self.model.coef_.shape[0] > 0 )
return ( hasattr(self.model, "coef_") and self.model.coef_ is not None and self.model.coef_.shape[0] > 0 )
14
526
57
583
import logging import os import numpy as np import pandas as pd import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.linear_model import LinearRegression, LogisticRegression from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRE...
import logging import os import numpy as np import pandas as pd import sklearn from sklearn.base import ClassifierMixin, RegressorMixin from sklearn.linear_model import LinearRegression, LogisticRegression from supervised.algorithms.registry import ( BINARY_CLASSIFICATION, MULTICLASS_CLASSIFICATION, REGRE...