path
stringlengths
9
117
type
stringclasses
2 values
project
stringclasses
10 values
commit_hash
stringlengths
40
40
commit_message
stringlengths
1
137
ground_truth
stringlengths
0
2.74k
main_code
stringlengths
102
3.37k
context
stringlengths
0
14.7k
cloudtracker.datasources.athena/Athena.query_athena
Modified
duo-labs~cloudtracker
48ce243f9f44cf62ec943a466bcaa97a8ea6bfe1
Creates partitions for every day
<0>:<add> logging.debug('Making query {}'.format(query)) <add> <12>:<add> <add> if do_not_wait: <add> return response['QueryExecutionId'] <15>:<add> # Paginate results and combine them <add> rows = [] <add> paginator = self.athena.get_paginator('get_query_results') <add> response_iterator = paginator.paginate(QueryExecutionId=response['QueryExecutionId']) <del> response = self.athena.get_query_results(QueryExecutionId=response['QueryExecutionId']) <16>:<add> for response in response_iterator: <add> rows.extend(response['ResultSet']['Rows']) <del> return response['ResultSet']['Rows'] <17>:<add> return rows
<s> - # TODO Delete result objects from S3 - # TODO Create partitions - # TODO Create views based on unions of partions - # TODO Add ability to skip setup - # TODO Add teardown to remove all the athena tables, partitions, and views - # TODO Use named parameters for string formatting - class Athena(object): + def query_athena(self, query, context={'Database': database}, do_not_wait=False): - def query_athena(self, query, context={'Database': database}): <0> # Make query request dependent on whether the context is None or not <1> if context is None: <2> response = self.athena.start_query_execution( <3> QueryString = query, <4> ResultConfiguration = {'OutputLocation': self.output_bucket} <5> ) <6> else: <7> response = self.athena.start_query_execution( <8> QueryString = query, <9> QueryExecutionContext = context, <10> ResultConfiguration = {'OutputLocation': self.output_bucket} <11> ) <12> <13> self.wait_for_query_to_complete(response['QueryExecutionId']) <14> <15> response = self.athena.get_query_results(QueryExecutionId=response['QueryExecutionId']) <16> return response['ResultSet']['Rows'] <17>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena.__init__ self.output_bucket = config['output_s3_bucket'] self.output_bucket = 's3://aws-athena-query-results-{}-{}'.format(current_account_id, region) self.athena = boto3.client('athena') at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
cloudtracker.datasources.athena/Athena.wait_for_query_to_complete
Modified
duo-labs~cloudtracker
48ce243f9f44cf62ec943a466bcaa97a8ea6bfe1
Creates partitions for every day
<12>:<add> logging.debug('Sleeping 1 second while query {} completes'.format(queryExecutionId)) <del> logging.info('Sleeping 1 second while query {} completes'.format(queryExecutionId))
<s>://medium.com/@alsmola/partitioning-cloudtrail-logs-in-athena-29add93ee070 - - # TODO Delete result objects from S3 - # TODO Create partitions - # TODO Create views based on unions of partions - # TODO Add ability to skip setup - # TODO Add teardown to remove all the athena tables, partitions, and views - # TODO Use named parameters for string formatting - class Athena(object): def wait_for_query_to_complete(self, queryExecutionId): <0> """ <1> Returns when the query completes successfully, or raises an exception if it fails or is canceled. <2> Waits until the query finishes running. <3> """ <4> <5> while True: <6> response = self.athena.get_query_execution(QueryExecutionId=queryExecutionId) <7> state = response['QueryExecution']['Status']['State'] <8> if state == 'SUCCEEDED': <9> return True <10> if state == 'FAILED' or state == 'CANCELLED': <11> raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason'])) <12> logging.info('Sleeping 1 second while query {} completes'.format(queryExecutionId)) <13> time.sleep(1) <14>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena wait_for_query_to_complete(queryExecutionId) at: cloudtracker.datasources.athena.Athena.__init__ self.athena = boto3.client('athena') ===========changed ref 0=========== <s> - # TODO Delete result objects from S3 - # TODO Create partitions - # TODO Create views based on unions of partions - # TODO Add ability to skip setup - # TODO Add teardown to remove all the athena tables, partitions, and views - # TODO Use named parameters for string formatting - class Athena(object): + def query_athena(self, query, context={'Database': database}, do_not_wait=False): - def query_athena(self, query, context={'Database': database}): + logging.debug('Making query {}'.format(query)) + # Make query request dependent on whether the context is None or not if context is None: response = self.athena.start_query_execution( QueryString = query, ResultConfiguration = {'OutputLocation': self.output_bucket} ) else: response = self.athena.start_query_execution( QueryString = query, QueryExecutionContext = context, ResultConfiguration = {'OutputLocation': self.output_bucket} ) + + if do_not_wait: + return response['QueryExecutionId'] self.wait_for_query_to_complete(response['QueryExecutionId']) + # Paginate results and combine them + rows = [] + paginator = self.athena.get_paginator('get_query_results') + response_iterator = paginator.paginate(QueryExecutionId=response['QueryExecutionId']) - response = self.athena.get_query_results(QueryExecutionId=response['QueryExecutionId']) + for response in response_iterator: + rows.extend(response['ResultSet']['Rows']) - return response['ResultSet']['Rows'] + return rows
cloudtracker.datasources.athena/Athena.wait_for_query_to_complete
Modified
duo-labs~cloudtracker
e99c609e358840134637abe8498f2454f6461365
Linting
<0>:<add> """ <del> """ <11>:<add> raise Exception('Query entered state {state} with reason {reason}'.format( <add> state=state, <add> reason=response['QueryExecution']['Status']['StateChangeReason'])) <del> raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason']))
# module: cloudtracker.datasources.athena class Athena(object): def wait_for_query_to_complete(self, queryExecutionId): <0> """ <1> Returns when the query completes successfully, or raises an exception if it fails or is canceled. <2> Waits until the query finishes running. <3> """ <4> <5> while True: <6> response = self.athena.get_query_execution(QueryExecutionId=queryExecutionId) <7> state = response['QueryExecution']['Status']['State'] <8> if state == 'SUCCEEDED': <9> return True <10> if state == 'FAILED' or state == 'CANCELLED': <11> raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason'])) <12> logging.debug('Sleeping 1 second while query {} completes'.format(queryExecutionId)) <13> time.sleep(1) <14>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' at: cloudtracker.datasources.athena.Athena.__init__ self.athena = boto3.client('athena') at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: time sleep(secs: float) -> None ===========changed ref 0=========== # module: cloudtracker.datasources.athena + # Much thanks to Alex Smolen (https://twitter.com/alsmola) - # Much thanks to Alex Smolen (https://twitter.com/alsmola) + # for his post "Partitioning CloudTrail Logs in Athena" - # for his post "Partitioning CloudTrail Logs in Athena" # https://medium.com/@alsmola/partitioning-cloudtrail-logs-in-athena-29add93ee070 # TODO Delete result objects from S3 - # TODO Create partitions - # TODO Create views based on unions of partions # TODO Add ability to skip setup # TODO Add teardown to remove all the athena tables, partitions, and views - # TODO Use named parameters for string formatting - # TODO Run queries, especially the partition creation, concurrently. - # You can run up to 20 at a time, or more with limit increases. - # You can also get the status of multiple queries with BatchGetQueryExecution. + NUM_MONTHS_FOR_PARTITIONS = 12 - NUM_DAYS_FOR_PARTITIONS = 365
cloudtracker.datasources.athena/Athena.wait_for_query_batch_to_complete
Modified
duo-labs~cloudtracker
e99c609e358840134637abe8498f2454f6461365
Linting
<0>:<add> """ <del> """ <12>:<add> raise Exception('Query entered state {state} with reason {reason}'.format( <add> state=state, <add> reason=response['QueryExecution']['Status']['StateChangeReason'])) <add> <del> raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason'])) <13>:<del>
# module: cloudtracker.datasources.athena class Athena(object): - def wait_for_query_batch_to_complete(self, queryExecutionIds): <0> """ <1> Returns when the query completes successfully, or raises an exception if it fails or is canceled. <2> Waits until the query finishes running. <3> """ <4> <5> while len(queryExecutionIds) > 0: <6> response = self.athena.batch_get_query_execution(QueryExecutionIds=list(queryExecutionIds)) <7> for query_execution in response['QueryExecutions']: <8> state = query_execution['Status']['State'] <9> if state == 'SUCCEEDED': <10> queryExecutionIds.remove(query_execution['QueryExecutionId']) <11> if state == 'FAILED' or state == 'CANCELLED': <12> raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason'])) <13> <14> if len(queryExecutionIds) == 0: <15> return <16> logging.debug('Sleeping 1 second while {} queries complete'.format(len(queryExecutionIds))) <17> time.sleep(1) <18>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena.__init__ self.athena = boto3.client('athena') at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: time sleep(secs: float) -> None ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): def wait_for_query_to_complete(self, queryExecutionId): + """ - """ Returns when the query completes successfully, or raises an exception if it fails or is canceled. Waits until the query finishes running. """ while True: response = self.athena.get_query_execution(QueryExecutionId=queryExecutionId) state = response['QueryExecution']['Status']['State'] if state == 'SUCCEEDED': return True if state == 'FAILED' or state == 'CANCELLED': + raise Exception('Query entered state {state} with reason {reason}'.format( + state=state, + reason=response['QueryExecution']['Status']['StateChangeReason'])) - raise Exception('Query entered state {} with reason {}'.format(state, response['QueryExecution']['Status']['StateChangeReason'])) logging.debug('Sleeping 1 second while query {} completes'.format(queryExecutionId)) time.sleep(1) ===========changed ref 1=========== # module: cloudtracker.datasources.athena + # Much thanks to Alex Smolen (https://twitter.com/alsmola) - # Much thanks to Alex Smolen (https://twitter.com/alsmola) + # for his post "Partitioning CloudTrail Logs in Athena" - # for his post "Partitioning CloudTrail Logs in Athena" # https://medium.com/@alsmola/partitioning-cloudtrail-logs-in-athena-29add93ee070 # TODO Delete result objects from S3 - # TODO Create partitions - # TODO Create views based on unions of partions # TODO Add ability to skip setup # TODO Add teardown to remove all the athena tables, partitions, and views - # TODO Use named parameters for string formatting - # TODO Run queries, especially the partition creation, concurrently. - # You can run up to 20 at a time, or more with limit increases. - # You can also get the status of multiple queries with BatchGetQueryExecution. + NUM_MONTHS_FOR_PARTITIONS = 12 - NUM_DAYS_FOR_PARTITIONS = 365
cloudtracker/run
Modified
duo-labs~cloudtracker
55fdadc389c64ee8e6e5f6c380ea59e4dde28fd1
Added ability to skip the setup
<11>:<add> datasource = Athena(config['athena'], account, start, end, args) <del> datasource = Athena(config['athena'], account, start, end)
# module: cloudtracker def run(args, config, start, end): <0> """Perform the requested command""" <1> use_color = args.use_color <2> <3> account = get_account(config['accounts'], args.account) <4> <5> if 'elasticsearch' in config: <6> from cloudtracker.datasources.es import ElasticSearch <7> datasource = ElasticSearch(config['elasticsearch'], start, end) <8> else: <9> logging.debug("Using Athena") <10> from cloudtracker.datasources.athena import Athena <11> datasource = Athena(config['athena'], account, start, end) <12> <13> # Read AWS actions <14> aws_api_list = read_aws_api_list() <15> <16> # Read cloudtrail_supported_events <17> global cloudtrail_supported_actions <18> cloudtrail_supported_actions = {} <19> with open("cloudtrail_supported_actions.txt") as f: <20> lines = f.readlines() <21> for line in lines: <22> (service, event) = line.rstrip().split(":") <23> cloudtrail_supported_actions[normalize_api_call(service, event)] = True <24> <25> account_iam = get_account_iam(account) <26> <27> if args.list: <28> actor_type = args.list <29> <30> if actor_type == 'users': <31> allowed_actors = get_allowed_users(account_iam) <32> performed_actors = datasource.get_performed_users() <33> elif actor_type == 'roles': <34> allowed_actors = get_allowed_roles(account_iam) <35> performed_actors = datasource.get_performed_roles() <36> else: <37> exit("ERROR: --list argument must be one of 'users' or 'roles'") <38> <39> print_actor_diff(performed_actors, allowed_actors, use_color) <40> <41> else: <42> if args.destaccount: <43> destination_account = get_account(config['accounts'], args.destaccount) </s>
===========below chunk 0=========== # module: cloudtracker def run(args, config, start, end): # offset: 1 destination_account = account destination_iam = get_account_iam(destination_account) search_query = datasource.get_search_query() if args.user: username = args.user user_iam = get_user_iam(username, account_iam) print("Getting info on {}, user created {}".format(args.user, user_iam['CreateDate'])) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_user_in_role( search_query, user_iam, dest_role_iam) else: allowed_actions = get_user_allowed_actions(aws_api_list, user_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_user( search_query, user_iam) elif args.role: rolename = args.role role_iam = get_role_iam(rolename, account_iam) print("Getting info for role {}".format(rolename)) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_role_in_role( search_query, role_iam, dest_role_iam) else: allowed_actions = get_role_allowed_actions(aws_api_list, role_iam, account_iam)</s> ===========below chunk 1=========== # module: cloudtracker def run(args, config, start, end): # offset: 2 <s> else: allowed_actions = get_role_allowed_actions(aws_api_list, role_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_role( search_query, role_iam) else: exit("ERROR: Must specify a user or a role") printfilter = {} printfilter['show_unknown'] = args.show_unknown printfilter['show_benign'] = args.show_benign printfilter['show_used'] = args.show_used print_diff(performed_actions, allowed_actions, printfilter, use_color) ===========unchanged ref 0=========== at: cloudtracker normalize_api_call(service, eventName) get_account_iam(account) get_allowed_users(account_iam) get_allowed_roles(account_iam) print_actor_diff(performed_actors, allowed_actors, use_color) get_user_iam(username, account_iam) get_role_iam(rolename, account_iam) get_user_allowed_actions(aws_api_list, user_iam, account_iam) get_role_allowed_actions(aws_api_list, role_iam, account_iam) print_diff(performed_actions, allowed_actions, printfilter, use_color) get_account(accounts, account_name) read_aws_api_list(aws_api_list_file='aws_api_list.txt') at: cloudtracker.datasources.athena Athena(config, account, start, end) at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' get_performed_users() get_performed_roles() get_search_query() get_performed_event_names_by_user(searchquery, user_iam) get_performed_event_names_by_role(searchquery, role_iam) get_performed_event_names_by_user_in_role(searchquery, user_iam, role_iam) at: io.TextIOWrapper readlines(self, hint: int=..., /) -> List[str] at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========unchanged ref 1=========== at: typing.IO __slots__ = () readlines(hint: int=...) -> list[AnyStr]
cloudtracker/print_actor_diff
Modified
duo-labs~cloudtracker
cff2a5df1c81f71796b048ff2bec6ce1b9153f90
User search works
<19>:<add> for actor in sorted(actors.keys()): <del> for actor in sorted(actors.iterkeys()):
# module: cloudtracker def print_actor_diff(performed_actors, allowed_actors, use_color): <0> """ <1> Given a list of actors that have performed actions, and a list that exist in the account, <2> print the actors and whether they are still active. <3> """ <4> PERFORMED_AND_ALLOWED = 1 <5> PERFORMED_BUT_NOT_ALLOWED = 2 <6> ALLOWED_BUT_NOT_PERFORMED = 3 <7> <8> actors = {} <9> for actor in performed_actors: <10> if actor in allowed_actors: <11> actors[actor] = PERFORMED_AND_ALLOWED <12> else: <13> actors[actor] = PERFORMED_BUT_NOT_ALLOWED <14> <15> for actor in allowed_actors: <16> if actor not in actors: <17> actors[actor] = ALLOWED_BUT_NOT_PERFORMED <18> <19> for actor in sorted(actors.iterkeys()): <20> if actors[actor] == PERFORMED_AND_ALLOWED: <21> colored_print(" {}".format(actor), use_color, 'white') <22> elif actors[actor] == PERFORMED_BUT_NOT_ALLOWED: <23> # Don't show users that existed but have since been deleted <24> continue <25> elif actors[actor] == ALLOWED_BUT_NOT_PERFORMED: <26> colored_print("- {}".format(actor), use_color, 'red') <27> else: <28> raise Exception("Unknown constant") <29>
===========unchanged ref 0=========== at: cloudtracker colored_print(text, use_color=True, color_name='white')
cloudtracker/print_diff
Modified
duo-labs~cloudtracker
cff2a5df1c81f71796b048ff2bec6ce1b9153f90
User search works
<35>:<add> for action in sorted(actions.keys()): <del> for action in sorted(actions.iterkeys()):
# module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): <0> """ <1> For an actor, given the actions they performed, and the privileges they were granted, <2> print what they were allowed to do but did not, and other differences. <3> """ <4> PERFORMED_AND_ALLOWED = 1 <5> PERFORMED_BUT_NOT_ALLOWED = 2 <6> ALLOWED_BUT_NOT_PERFORMED = 3 <7> ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 <8> <9> actions = {} <10> <11> for action in performed_actions: <12> # Convert to IAM names <13> for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): <14> if action == cloudtrail_name: <15> action = iam_name <16> <17> # See if this was allowed or not <18> if action in allowed_actions: <19> actions[action] = PERFORMED_AND_ALLOWED <20> else: <21> if action in NO_IAM: <22> # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed <23> # whether or not they are in IAM <24> continue <25> actions[action] = PERFORMED_BUT_NOT_ALLOWED <26> <27> # Find actions that were allowed, but there is no record of them being used <28> for action in allowed_actions: <29> if action not in actions: <30> if not is_recorded_by_cloudtrail(action): <31> actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED <32> else: <33> actions[action] = ALLOWED_BUT_NOT_PERFORMED <34> <35> for action in sorted(actions.iterkeys()): <36> # Convert CloudTrail name back to IAM name <37> display_name = action <38> <39> if not printfilter.get('show_benign', True): <40> # Ignore actions that won't exfil or modify resources <41> if ":list" in display_name or ":describe" in display_name: <42> continue <43> <44> </s>
===========below chunk 0=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant") ===========unchanged ref 0=========== at: cloudtracker EVENT_RENAMES = { 's3:listallmybuckets': 's3:listbuckets', 's3:getbucketaccesscontrolpolicy': 's3:getbucketacl', 's3:setbucketaccesscontrolpolicy': 's3:putbucketacl', 's3:getbucketloggingstatus': 's3:getbucketlogging', 's3:setbucketloggingstatus': 's3:putbucketlogging' } NO_IAM = { 'sts:getcalleridentity': True, 'sts:getsessiontoken': True, 'signin:consolelogin': True, 'signin:checkmfa': True, "signin:exitrole": True, "signin:renewrole": True, "signin:switchrole": True } is_recorded_by_cloudtrail(action) colored_print(text, use_color=True, color_name='white') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: cloudtracker def print_actor_diff(performed_actors, allowed_actors, use_color): """ Given a list of actors that have performed actions, and a list that exist in the account, print the actors and whether they are still active. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 actors = {} for actor in performed_actors: if actor in allowed_actors: actors[actor] = PERFORMED_AND_ALLOWED else: actors[actor] = PERFORMED_BUT_NOT_ALLOWED for actor in allowed_actors: if actor not in actors: actors[actor] = ALLOWED_BUT_NOT_PERFORMED + for actor in sorted(actors.keys()): - for actor in sorted(actors.iterkeys()): if actors[actor] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(actor), use_color, 'white') elif actors[actor] == PERFORMED_BUT_NOT_ALLOWED: # Don't show users that existed but have since been deleted continue elif actors[actor] == ALLOWED_BUT_NOT_PERFORMED: colored_print("- {}".format(actor), use_color, 'red') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.query_athena
Modified
duo-labs~cloudtracker
cff2a5df1c81f71796b048ff2bec6ce1b9153f90
User search works
<24>:<add> row_count = 0 <25>:<add> for row in response['ResultSet']['Rows']: <del> rows.extend(response['ResultSet']['Rows']) <26>:<add> row_count +=1 <add> if row_count == 1: <add> # Skip header <add> continue <add> rows.append(self.extract_response_values(row))
# module: cloudtracker.datasources.athena class Athena(object): def query_athena(self, query, context={'Database': database}, do_not_wait=False): <0> logging.debug('Making query {}'.format(query)) <1> <2> # Make query request dependent on whether the context is None or not <3> if context is None: <4> response = self.athena.start_query_execution( <5> QueryString=query, <6> ResultConfiguration={'OutputLocation': self.output_bucket} <7> ) <8> else: <9> response = self.athena.start_query_execution( <10> QueryString=query, <11> QueryExecutionContext=context, <12> ResultConfiguration={'OutputLocation': self.output_bucket} <13> ) <14> <15> if do_not_wait: <16> return response['QueryExecutionId'] <17> <18> self.wait_for_query_to_complete(response['QueryExecutionId']) <19> <20> # Paginate results and combine them <21> rows = [] <22> paginator = self.athena.get_paginator('get_query_results') <23> response_iterator = paginator.paginate(QueryExecutionId=response['QueryExecutionId']) <24> for response in response_iterator: <25> rows.extend(response['ResultSet']['Rows']) <26> return rows <27>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' wait_for_query_to_complete(queryExecutionId) at: cloudtracker.datasources.athena.Athena.__init__ self.output_bucket = config['output_s3_bucket'] self.output_bucket = 's3://aws-athena-query-results-{}-{}'.format(current_account_id, region) self.athena = boto3.client('athena') at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' + search_filter = '' + table_name = '' ===========changed ref 1=========== # module: cloudtracker def print_actor_diff(performed_actors, allowed_actors, use_color): """ Given a list of actors that have performed actions, and a list that exist in the account, print the actors and whether they are still active. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 actors = {} for actor in performed_actors: if actor in allowed_actors: actors[actor] = PERFORMED_AND_ALLOWED else: actors[actor] = PERFORMED_BUT_NOT_ALLOWED for actor in allowed_actors: if actor not in actors: actors[actor] = ALLOWED_BUT_NOT_PERFORMED + for actor in sorted(actors.keys()): - for actor in sorted(actors.iterkeys()): if actors[actor] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(actor), use_color, 'white') elif actors[actor] == PERFORMED_BUT_NOT_ALLOWED: # Don't show users that existed but have since been deleted continue elif actors[actor] == ALLOWED_BUT_NOT_PERFORMED: colored_print("- {}".format(actor), use_color, 'red') else: raise Exception("Unknown constant") ===========changed ref 2=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): """ For an actor, given the actions they performed, and the privileges they were granted, print what they were allowed to do but did not, and other differences. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 actions = {} for action in performed_actions: # Convert to IAM names for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if action == cloudtrail_name: action = iam_name # See if this was allowed or not if action in allowed_actions: actions[action] = PERFORMED_AND_ALLOWED else: if action in NO_IAM: # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed # whether or not they are in IAM continue actions[action] = PERFORMED_BUT_NOT_ALLOWED # Find actions that were allowed, but there is no record of them being used for action in allowed_actions: if action not in actions: if not is_recorded_by_cloudtrail(action): actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED else: actions[action] = ALLOWED_BUT_NOT_PERFORMED + for action in sorted(actions.keys()): - for action in sorted(actions.iterkeys()): # Convert CloudTrail name back to IAM name display_name = action if not printfilter.get('show_benign', True): # Ignore actions that won't exfil or modify resources if ":list" in display_name or ":describe" in display_name: continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use</s> ===========changed ref 3=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 <s> if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.get_performed_users
Modified
duo-labs~cloudtracker
cff2a5df1c81f71796b048ff2bec6ce1b9153f90
User search works
<3>:<del> raise Exception("Not implemented") <4>:<del> search = Search(using=self.es, index=self.index) <5>:<del> for query in self.searchfilter.values(): <6>:<del> search = search.query(query) <7>:<del> <8>:<del> search.aggs.bucket('user_names', 'terms', field=self.get_field_name('userIdentity.userName'), size=5000) <9>:<del> response = search.execute() <10>:<del> <11>:<add> query = 'select distinct userIdentity.userName from {table_name} where {search_filter}'.format( <add> table_name=self.table_name, <add> search_filter=self.search_filter) <add> response = self.query_athena(query) <add> <12>:<add> for row in response: <add> user_name = row[0] <del> for user in response.aggregations.user_names.buckets: <13>:<add> if user_name == 'HIDDEN_DUE_TO_SECURITY_REASONS': <del> if user.key == 'HIDDEN_DUE_TO_SECURITY_REASONS': <16>:<add> user_names[user_name] = True <del> user_names[user.key] = True
# module: cloudtracker.datasources.athena class Athena(object): def get_performed_users(self): <0> """ <1> Returns the users that performed actions within the search filters <2> """ <3> raise Exception("Not implemented") <4> search = Search(using=self.es, index=self.index) <5> for query in self.searchfilter.values(): <6> search = search.query(query) <7> <8> search.aggs.bucket('user_names', 'terms', field=self.get_field_name('userIdentity.userName'), size=5000) <9> response = search.execute() <10> <11> user_names = {} <12> for user in response.aggregations.user_names.buckets: <13> if user.key == 'HIDDEN_DUE_TO_SECURITY_REASONS': <14> # This happens when a user logs in with the wrong username <15> continue <16> user_names[user.key] = True <17> return user_names <18>
===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): + def extract_response_values(self, row): + result = [] + for column in row['Data']: + result.append(column.get('VarCharValue', '')) + return result + ===========changed ref 1=========== # module: cloudtracker.datasources.athena class Athena(object): athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' + search_filter = '' + table_name = '' ===========changed ref 2=========== # module: cloudtracker.datasources.athena class Athena(object): def query_athena(self, query, context={'Database': database}, do_not_wait=False): logging.debug('Making query {}'.format(query)) # Make query request dependent on whether the context is None or not if context is None: response = self.athena.start_query_execution( QueryString=query, ResultConfiguration={'OutputLocation': self.output_bucket} ) else: response = self.athena.start_query_execution( QueryString=query, QueryExecutionContext=context, ResultConfiguration={'OutputLocation': self.output_bucket} ) if do_not_wait: return response['QueryExecutionId'] self.wait_for_query_to_complete(response['QueryExecutionId']) # Paginate results and combine them rows = [] paginator = self.athena.get_paginator('get_query_results') response_iterator = paginator.paginate(QueryExecutionId=response['QueryExecutionId']) + row_count = 0 for response in response_iterator: + for row in response['ResultSet']['Rows']: - rows.extend(response['ResultSet']['Rows']) + row_count +=1 + if row_count == 1: + # Skip header + continue + rows.append(self.extract_response_values(row)) return rows ===========changed ref 3=========== # module: cloudtracker def print_actor_diff(performed_actors, allowed_actors, use_color): """ Given a list of actors that have performed actions, and a list that exist in the account, print the actors and whether they are still active. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 actors = {} for actor in performed_actors: if actor in allowed_actors: actors[actor] = PERFORMED_AND_ALLOWED else: actors[actor] = PERFORMED_BUT_NOT_ALLOWED for actor in allowed_actors: if actor not in actors: actors[actor] = ALLOWED_BUT_NOT_PERFORMED + for actor in sorted(actors.keys()): - for actor in sorted(actors.iterkeys()): if actors[actor] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(actor), use_color, 'white') elif actors[actor] == PERFORMED_BUT_NOT_ALLOWED: # Don't show users that existed but have since been deleted continue elif actors[actor] == ALLOWED_BUT_NOT_PERFORMED: colored_print("- {}".format(actor), use_color, 'red') else: raise Exception("Unknown constant") ===========changed ref 4=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): """ For an actor, given the actions they performed, and the privileges they were granted, print what they were allowed to do but did not, and other differences. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 actions = {} for action in performed_actions: # Convert to IAM names for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if action == cloudtrail_name: action = iam_name # See if this was allowed or not if action in allowed_actions: actions[action] = PERFORMED_AND_ALLOWED else: if action in NO_IAM: # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed # whether or not they are in IAM continue actions[action] = PERFORMED_BUT_NOT_ALLOWED # Find actions that were allowed, but there is no record of them being used for action in allowed_actions: if action not in actions: if not is_recorded_by_cloudtrail(action): actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED else: actions[action] = ALLOWED_BUT_NOT_PERFORMED + for action in sorted(actions.keys()): - for action in sorted(actions.iterkeys()): # Convert CloudTrail name back to IAM name display_name = action if not printfilter.get('show_benign', True): # Ignore actions that won't exfil or modify resources if ":list" in display_name or ":describe" in display_name: continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use</s> ===========changed ref 5=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 <s> if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.get_performed_roles
Modified
duo-labs~cloudtracker
f79d48979f00d2376d4bfa9200fb726e1e42b86e
Check start date; works with roles now
<3>:<del> raise Exception("Not implemented") <4>:<del> search = Search(using=self.es, index=self.index) <5>:<del> for query in self.searchfilter.values(): <6>:<del> search = search.query(query) <7>:<del> <8>:<del> userName_field = self.get_field_name('userIdentity.sessionContext.sessionIssuer.userName') <9>:<del> search.aggs.bucket('role_names', 'terms', field=userName_field, size=5000) <10>:<del> response = search.execute() <11>:<add> query = 'select distinct userIdentity.sessionContext.sessionIssuer.userName from {table_name} where {search_filter}'.format( <add> table_name=self.table_name, <add> search_filter=self.search_filter) <add> response = self.query_athena(query) <13>:<add> for row in response: <add> role = row[0] <del> for role in response.aggregations.role_names.buckets: <14>:<add> role_names[role] = True <del> role_names[role.key] = True
# module: cloudtracker.datasources.athena class Athena(object): def get_performed_roles(self): <0> """ <1> Returns the roles that performed actions within the search filters <2> """ <3> raise Exception("Not implemented") <4> search = Search(using=self.es, index=self.index) <5> for query in self.searchfilter.values(): <6> search = search.query(query) <7> <8> userName_field = self.get_field_name('userIdentity.sessionContext.sessionIssuer.userName') <9> search.aggs.bucket('role_names', 'terms', field=userName_field, size=5000) <10> response = search.execute() <11> <12> role_names = {} <13> for role in response.aggregations.role_names.buckets: <14> role_names[role.key] = True <15> return role_names <16>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = '' query_athena(query, context={'Database': database}, do_not_wait=False) at: cloudtracker.datasources.athena.Athena.__init__ self.search_filter = '((' + ' or '.join(month_restrictions) + ') and errorcode IS NULL)' self.table_name = 'cloudtrail_logs_{}'.format(account['id']) at: cloudtracker.datasources.athena.Athena.get_performed_users user_name = row[0] ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): def __init__(self, config, account, start, end, args): # Mute boto except errors logging.getLogger('botocore').setLevel(logging.WARN) logging.info('Source of CloudTrail logs: s3://{bucket}/{path}'.format( bucket=config['s3_bucket'], path=config['path'])) + + # Check start date is not older than a year, as we only create partitions for that far back + if (datetime.datetime.now() - datetime.datetime.strptime(start, '%Y-%m-%d')).days > 365: + raise Exception("Start date is over a year old. CloudTracker does not create or use partitions over a year old.") # # Create date filtering # month_restrictions = set() start = start.split('-') end = end.split('-') if start[0] == end[0]: for month in range(int(start[1]), int(end[1]) + 1): month_restrictions.add('(year = \'{:0>2}\' and month = \'{:0>2}\')'.format(start[0], month)) else: # Add restrictions for months in start year for month in range(int(start[1]), 12 + 1): month_restrictions.add('(year = \'{:0>2}\' and month = \'{:0>2}\')'.format(start[0], month)) # Add restrictions for months in middle years for year in range(int(start[0]), int(end[0])): for month in (1, 12 + 1): month_restrictions.add('(year = \'{:0>2}\' and month = \'{:0>2}\')'.format(year, month)) # Add restrictions for months in final year for month in range(1, int(end[1]) + 1): month_restrictions.add('(year = \'{:0>2}\' and month = \'{:0>2}\'</s> ===========changed ref 1=========== # module: cloudtracker.datasources.athena class Athena(object): def __init__(self, config, account, start, end, args): # offset: 1 <s> + 1): month_restrictions.add('(year = \'{:0>2}\' and month = \'{:0>2}\')'.format(end[0], month)) # Combine date filters and add error filter self.search_filter = '((' + ' or '.join(month_restrictions) + ') and errorcode IS NULL)' self.table_name = 'cloudtrail_logs_{}'.format(account['id']) # # Display the AWS identity (doubles as a check that boto creds are setup) # sts = boto3.client('sts') identity = sts.get_caller_identity() logging.info('Using AWS identity: {}'.format(identity['Arn'])) current_account_id = identity['Account'] region = boto3.session.Session().region_name if 'output_s3_bucket' in config: self.output_bucket = config['output_s3_bucket'] else: self.output_bucket = 's3://aws-athena-query-results-{}-{}'.format(current_account_id, region) logging.info('Using output bucket: {}'.format(self.output_bucket)) cloudtrail_log_path = 's3://{bucket}/{path}/AWSLogs/{account_id}/CloudTrail'.format( bucket=config['s3_bucket'], path=config['path'], account_id=account['id']) logging.info('Account cloudtrail log path: {}'.format(cloudtrail_log_path)) # Open connections to needed AWS services self.athena = boto3.client('athena') self.s3 = boto3.client('s3') if args.skip_setup: logging.info("Skipping initial table creation") </s> ===========changed ref 2=========== # module: cloudtracker.datasources.athena class Athena(object): def __init__(self, config, account, start, end, args): # offset: 2 <s> # Check we can access the S3 bucket resp = self.s3.list_objects_v2(Bucket=config['s3_bucket'], Prefix=config['path'], MaxKeys=1) if 'Contents' not in resp or len(resp['Contents']) == 0: exit('ERROR: S3 bucket has no contents. Ensure you have logs at s3://{bucket}/{path}'.format( bucket=config['s3_bucket'], path=config['path'])) # Ensure our database exists self.query_athena( 'CREATE DATABASE IF NOT EXISTS {db} {comment}'.format( db=self.database, comment='COMMENT \'Created by CloudTracker\''), context=None) # # Set up table # query = """CREATE EXTERNAL TABLE IF NOT EXISTS `{table_name}` ( `eventversion` string COMMENT 'from deserializer', `useridentity` struct<type:string,principalid:string,arn:string,accountid:string,invokedby:string,accesskeyid:string,username:string,sessioncontext:struct<attributes:struct<mfaauthenticated:string,creationdate:string>,sessionissuer:struct<type:string,principalid:string,arn:string,accountid:string,username:string>>> COMMENT 'from deserializer', `eventtime` string COMMENT 'from deserializer', `eventsource` string COMMENT 'from deserializer', `eventname` string COMMENT 'from deserializer', `awsregion` string COMMENT 'from deserializer', `sourceipaddress` string COMMENT 'from deserializer', `useragent` string COMMENT 'from deserializer', `errorcode` string COMMENT 'from deserializer', `errormessage` string COMMENT 'from deserializer', `requestparameters` string COMMENT 'from</s>
cloudtracker/Privileges.get_actions_from_statement
Modified
duo-labs~cloudtracker
95c5e2b00f55e43544276f41753e8f24519f45c6
Works for a user
<10>:<add> for iam_name, cloudtrail_name in EVENT_RENAMES.items(): <del> for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems():
# module: cloudtracker class Privileges(object): def get_actions_from_statement(self, stmt): <0> """Figures out what API calls have been granted from a statement""" <1> actions = {} <2> <3> for action in make_list(stmt['Action']): <4> # Normalize it <5> action = action.lower() <6> # Convert it's globbing to a regex <7> action = '^' + action.replace('*', '.*') + '$' <8> <9> for possible_action in self.aws_api_list: <10> for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): <11> if possible_action == cloudtrail_name: <12> possible_action = iam_name <13> if re.match(action, possible_action): <14> actions[possible_action] = True <15> <16> return actions <17>
===========unchanged ref 0=========== at: cloudtracker EVENT_RENAMES = { 's3:listallmybuckets': 's3:listbuckets', 's3:getbucketaccesscontrolpolicy': 's3:getbucketacl', 's3:setbucketaccesscontrolpolicy': 's3:putbucketacl', 's3:getbucketloggingstatus': 's3:getbucketlogging', 's3:setbucketloggingstatus': 's3:putbucketlogging' } make_list(obj) at: cloudtracker.Privileges stmts = None roles = None aws_api_list = None at: cloudtracker.Privileges.__init__ self.aws_api_list = aws_api_list at: re match(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]] match(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> Optional[Match[AnyStr]]
cloudtracker/print_diff
Modified
duo-labs~cloudtracker
95c5e2b00f55e43544276f41753e8f24519f45c6
Works for a user
<13>:<add> for iam_name, cloudtrail_name in EVENT_RENAMES.items(): <del> for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems():
# module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): <0> """ <1> For an actor, given the actions they performed, and the privileges they were granted, <2> print what they were allowed to do but did not, and other differences. <3> """ <4> PERFORMED_AND_ALLOWED = 1 <5> PERFORMED_BUT_NOT_ALLOWED = 2 <6> ALLOWED_BUT_NOT_PERFORMED = 3 <7> ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 <8> <9> actions = {} <10> <11> for action in performed_actions: <12> # Convert to IAM names <13> for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): <14> if action == cloudtrail_name: <15> action = iam_name <16> <17> # See if this was allowed or not <18> if action in allowed_actions: <19> actions[action] = PERFORMED_AND_ALLOWED <20> else: <21> if action in NO_IAM: <22> # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed <23> # whether or not they are in IAM <24> continue <25> actions[action] = PERFORMED_BUT_NOT_ALLOWED <26> <27> # Find actions that were allowed, but there is no record of them being used <28> for action in allowed_actions: <29> if action not in actions: <30> if not is_recorded_by_cloudtrail(action): <31> actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED <32> else: <33> actions[action] = ALLOWED_BUT_NOT_PERFORMED <34> <35> for action in sorted(actions.keys()): <36> # Convert CloudTrail name back to IAM name <37> display_name = action <38> <39> if not printfilter.get('show_benign', True): <40> # Ignore actions that won't exfil or modify resources <41> if ":list" in display_name or ":describe" in display_name: <42> continue <43> <44> </s>
===========below chunk 0=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant") ===========unchanged ref 0=========== at: cloudtracker EVENT_RENAMES = { 's3:listallmybuckets': 's3:listbuckets', 's3:getbucketaccesscontrolpolicy': 's3:getbucketacl', 's3:setbucketaccesscontrolpolicy': 's3:putbucketacl', 's3:getbucketloggingstatus': 's3:getbucketlogging', 's3:setbucketloggingstatus': 's3:putbucketlogging' } NO_IAM = { 'sts:getcalleridentity': True, 'sts:getsessiontoken': True, 'signin:consolelogin': True, 'signin:checkmfa': True, "signin:exitrole": True, "signin:renewrole": True, "signin:switchrole": True } is_recorded_by_cloudtrail(action) colored_print(text, use_color=True, color_name='white') at: typing.Mapping get(key: _KT, default: Union[_VT_co, _T]) -> Union[_VT_co, _T] get(key: _KT) -> Optional[_VT_co] ===========changed ref 0=========== # module: cloudtracker class Privileges(object): def get_actions_from_statement(self, stmt): """Figures out what API calls have been granted from a statement""" actions = {} for action in make_list(stmt['Action']): # Normalize it action = action.lower() # Convert it's globbing to a regex action = '^' + action.replace('*', '.*') + '$' for possible_action in self.aws_api_list: + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if possible_action == cloudtrail_name: possible_action = iam_name if re.match(action, possible_action): actions[possible_action] = True return actions
cloudtracker.datasources.athena/Athena.get_search_query
Modified
duo-labs~cloudtracker
95c5e2b00f55e43544276f41753e8f24519f45c6
Works for a user
<0>:<del> """ <1>:<del> Opens a connection to ElasticSearch and applies the initial filters <2>:<del> """ <3>:<del> raise Exception("Not implemented") <4>:<del> search = Search(using=self.es, index=self.index) <5>:<del> for query in self.searchfilter.values(): <6>:<del> search = search.query(query) <7>:<add> # Athena doesn't use this call, but needs to support it being called <add> return None <8>:<del> return search <9>:<del>
# module: cloudtracker.datasources.athena class Athena(object): def get_search_query(self): <0> """ <1> Opens a connection to ElasticSearch and applies the initial filters <2> """ <3> raise Exception("Not implemented") <4> search = Search(using=self.es, index=self.index) <5> for query in self.searchfilter.values(): <6> search = search.query(query) <7> <8> return search <9>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = '' ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): - def get_query_match(self, field, value): - raise Exception("Not implemented") - field = self.get_field_name(field) - return {'match': {field: value}} - ===========changed ref 1=========== # module: cloudtracker class Privileges(object): def get_actions_from_statement(self, stmt): """Figures out what API calls have been granted from a statement""" actions = {} for action in make_list(stmt['Action']): # Normalize it action = action.lower() # Convert it's globbing to a regex action = '^' + action.replace('*', '.*') + '$' for possible_action in self.aws_api_list: + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if possible_action == cloudtrail_name: possible_action = iam_name if re.match(action, possible_action): actions[possible_action] = True return actions ===========changed ref 2=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): """ For an actor, given the actions they performed, and the privileges they were granted, print what they were allowed to do but did not, and other differences. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 actions = {} for action in performed_actions: # Convert to IAM names + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if action == cloudtrail_name: action = iam_name # See if this was allowed or not if action in allowed_actions: actions[action] = PERFORMED_AND_ALLOWED else: if action in NO_IAM: # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed # whether or not they are in IAM continue actions[action] = PERFORMED_BUT_NOT_ALLOWED # Find actions that were allowed, but there is no record of them being used for action in allowed_actions: if action not in actions: if not is_recorded_by_cloudtrail(action): actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED else: actions[action] = ALLOWED_BUT_NOT_PERFORMED for action in sorted(actions.keys()): # Convert CloudTrail name back to IAM name display_name = action if not printfilter.get('show_benign', True): # Ignore actions that won't exfil or modify resources if ":list" in display_name or ":describe" in display_name: continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format</s> ===========changed ref 3=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 <s> continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.get_events_from_search
Modified
duo-labs~cloudtracker
95c5e2b00f55e43544276f41753e8f24519f45c6
Works for a user
<1>:<del> Given a started elasticsearch query, apply the remaining search filters, and <2>:<del> return the API calls that exist for this query. <3>:<del> s: search query <4>:<add> Given the results of a query for events, return these in a more usable fashion <5>:<del> raise Exception("Not implemented") <6>:<del> searchquery.aggs.bucket('event_names', 'terms', field=self.get_field_name('eventName'), size=5000) \ <7>:<del> .bucket('service_names', 'terms', field=self.get_field_name('eventSource'), size=5000) <8>:<del> response = searchquery.execute() <9>:<add> event_names = {} <add> print(json.dumps(searchresults, indent=4)) <10>:<add> for event in searchresults: <add> event = event[0] <add> # event is now a string like "{field0=s3.amazonaws.com, field1=GetBucketAcl}" <add> # I parse out the field manually <add> # TODO Find a smarter way to parse this data <del> event_names = {} <12>:<add> # Remove the '{' and '}' <add> event = event[1:len(event)-1] <add> <add> # Split into 'field0=s3.amazonaws.com' and 'field1=GetBucketAcl' <add> event = event.split(", ") <add> # Get the eventsource 's3.amazonaws.com' <add> service = event[0].split('=')[1] <add> # Get the service 's3' <del> for event in response.aggregations.event_names.buckets: <13>:<del> service = event.service_names.buckets[0].key <16>:<add> # Get the eventname
# module: cloudtracker.datasources.athena class Athena(object): + def get_events_from_search(self, searchresults): - def get_events_from_search(self, searchquery): <0> """ <1> Given a started elasticsearch query, apply the remaining search filters, and <2> return the API calls that exist for this query. <3> s: search query <4> """ <5> raise Exception("Not implemented") <6> searchquery.aggs.bucket('event_names', 'terms', field=self.get_field_name('eventName'), size=5000) \ <7> .bucket('service_names', 'terms', field=self.get_field_name('eventSource'), size=5000) <8> response = searchquery.execute() <9> <10> event_names = {} <11> <12> for event in response.aggregations.event_names.buckets: <13> service = event.service_names.buckets[0].key <14> service = service.split(".")[0] <15> <16> event_names[normalize_api_call(service, event.key)] = True <17> <18> return event_names <19>
===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): - def get_query_match(self, field, value): - raise Exception("Not implemented") - field = self.get_field_name(field) - return {'match': {field: value}} - ===========changed ref 1=========== # module: cloudtracker.datasources.athena class Athena(object): def get_search_query(self): - """ - Opens a connection to ElasticSearch and applies the initial filters - """ - raise Exception("Not implemented") - search = Search(using=self.es, index=self.index) - for query in self.searchfilter.values(): - search = search.query(query) + # Athena doesn't use this call, but needs to support it being called + return None - return search - ===========changed ref 2=========== # module: cloudtracker class Privileges(object): def get_actions_from_statement(self, stmt): """Figures out what API calls have been granted from a statement""" actions = {} for action in make_list(stmt['Action']): # Normalize it action = action.lower() # Convert it's globbing to a regex action = '^' + action.replace('*', '.*') + '$' for possible_action in self.aws_api_list: + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if possible_action == cloudtrail_name: possible_action = iam_name if re.match(action, possible_action): actions[possible_action] = True return actions ===========changed ref 3=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): """ For an actor, given the actions they performed, and the privileges they were granted, print what they were allowed to do but did not, and other differences. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 actions = {} for action in performed_actions: # Convert to IAM names + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if action == cloudtrail_name: action = iam_name # See if this was allowed or not if action in allowed_actions: actions[action] = PERFORMED_AND_ALLOWED else: if action in NO_IAM: # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed # whether or not they are in IAM continue actions[action] = PERFORMED_BUT_NOT_ALLOWED # Find actions that were allowed, but there is no record of them being used for action in allowed_actions: if action not in actions: if not is_recorded_by_cloudtrail(action): actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED else: actions[action] = ALLOWED_BUT_NOT_PERFORMED for action in sorted(actions.keys()): # Convert CloudTrail name back to IAM name display_name = action if not printfilter.get('show_benign', True): # Ignore actions that won't exfil or modify resources if ":list" in display_name or ":describe" in display_name: continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format</s> ===========changed ref 4=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 <s> continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.get_performed_event_names_by_user
Modified
duo-labs~cloudtracker
95c5e2b00f55e43544276f41753e8f24519f45c6
Works for a user
<1>:<del> raise Exception("Not implemented") <2>:<del> searchquery = searchquery.query(self.get_query_match('userIdentity.arn', user_iam['Arn'])) <3>:<del> return self.get_events_from_search(searchquery)
# module: cloudtracker.datasources.athena class Athena(object): + def get_performed_event_names_by_user(self, _, user_iam): - def get_performed_event_names_by_user(self, searchquery, user_iam): <0> """For a user, return all performed events""" <1> raise Exception("Not implemented") <2> searchquery = searchquery.query(self.get_query_match('userIdentity.arn', user_iam['Arn'])) <3> return self.get_events_from_search(searchquery) <4>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena get_query_match(field, value) get_events_from_search(searchquery) get_events_from_search(self, searchquery) ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): - def get_query_match(self, field, value): - raise Exception("Not implemented") - field = self.get_field_name(field) - return {'match': {field: value}} - ===========changed ref 1=========== # module: cloudtracker.datasources.athena class Athena(object): + def get_events_from_search(self, searchresults): - def get_events_from_search(self, searchquery): """ - Given a started elasticsearch query, apply the remaining search filters, and - return the API calls that exist for this query. - s: search query + Given the results of a query for events, return these in a more usable fashion """ - raise Exception("Not implemented") - searchquery.aggs.bucket('event_names', 'terms', field=self.get_field_name('eventName'), size=5000) \ - .bucket('service_names', 'terms', field=self.get_field_name('eventSource'), size=5000) - response = searchquery.execute() + event_names = {} + print(json.dumps(searchresults, indent=4)) + for event in searchresults: + event = event[0] + # event is now a string like "{field0=s3.amazonaws.com, field1=GetBucketAcl}" + # I parse out the field manually + # TODO Find a smarter way to parse this data - event_names = {} + # Remove the '{' and '}' + event = event[1:len(event)-1] + + # Split into 'field0=s3.amazonaws.com' and 'field1=GetBucketAcl' + event = event.split(", ") + # Get the eventsource 's3.amazonaws.com' + service = event[0].split('=')[1] + # Get the service 's3' - for event in response.aggregations.event_names.buckets: - service = event.service_names.buckets[0].key service = service.split(".")[0] + # Get the eventname 'GetBucketAcl' + eventname = event[1].split('=')[1] + + event_names[normalize_api_call(service, eventname)] = True</s> ===========changed ref 2=========== # module: cloudtracker.datasources.athena class Athena(object): + def get_events_from_search(self, searchresults): - def get_events_from_search(self, searchquery): # offset: 1 <s>1].split('=')[1] + + event_names[normalize_api_call(service, eventname)] = True - event_names[normalize_api_call(service, event.key)] = True return event_names ===========changed ref 3=========== # module: cloudtracker.datasources.athena class Athena(object): def get_search_query(self): - """ - Opens a connection to ElasticSearch and applies the initial filters - """ - raise Exception("Not implemented") - search = Search(using=self.es, index=self.index) - for query in self.searchfilter.values(): - search = search.query(query) + # Athena doesn't use this call, but needs to support it being called + return None - return search - ===========changed ref 4=========== # module: cloudtracker class Privileges(object): def get_actions_from_statement(self, stmt): """Figures out what API calls have been granted from a statement""" actions = {} for action in make_list(stmt['Action']): # Normalize it action = action.lower() # Convert it's globbing to a regex action = '^' + action.replace('*', '.*') + '$' for possible_action in self.aws_api_list: + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if possible_action == cloudtrail_name: possible_action = iam_name if re.match(action, possible_action): actions[possible_action] = True return actions ===========changed ref 5=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): """ For an actor, given the actions they performed, and the privileges they were granted, print what they were allowed to do but did not, and other differences. """ PERFORMED_AND_ALLOWED = 1 PERFORMED_BUT_NOT_ALLOWED = 2 ALLOWED_BUT_NOT_PERFORMED = 3 ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED = 4 actions = {} for action in performed_actions: # Convert to IAM names + for iam_name, cloudtrail_name in EVENT_RENAMES.items(): - for iam_name, cloudtrail_name in EVENT_RENAMES.iteritems(): if action == cloudtrail_name: action = iam_name # See if this was allowed or not if action in allowed_actions: actions[action] = PERFORMED_AND_ALLOWED else: if action in NO_IAM: # Ignore actions in cloudtrail such as sts:getcalleridentity that are allowed # whether or not they are in IAM continue actions[action] = PERFORMED_BUT_NOT_ALLOWED # Find actions that were allowed, but there is no record of them being used for action in allowed_actions: if action not in actions: if not is_recorded_by_cloudtrail(action): actions[action] = ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED else: actions[action] = ALLOWED_BUT_NOT_PERFORMED for action in sorted(actions.keys()): # Convert CloudTrail name back to IAM name display_name = action if not printfilter.get('show_benign', True): # Ignore actions that won't exfil or modify resources if ":list" in display_name or ":describe" in display_name: continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format</s> ===========changed ref 6=========== # module: cloudtracker def print_diff(performed_actions, allowed_actions, printfilter, use_color): # offset: 1 <s> continue if actions[action] == PERFORMED_AND_ALLOWED: colored_print(" {}".format(display_name), use_color, 'white') elif actions[action] == PERFORMED_BUT_NOT_ALLOWED: colored_print("+ {}".format(display_name), use_color, 'green') elif actions[action] == ALLOWED_BUT_NOT_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue colored_print("- {}".format(display_name), use_color, 'red') elif actions[action] == ALLOWED_BUT_NOT_KNOWN_IF_PERFORMED: if printfilter.get('show_used', True): # Ignore this as it wasn't used continue if printfilter.get('show_unknown', True): colored_print("? {}".format(display_name), use_color, 'yellow') else: raise Exception("Unknown constant")
cloudtracker.datasources.athena/Athena.get_events_from_search
Modified
duo-labs~cloudtracker
9183be38dc3eea486514dd9631a6713379ba0522
Role querying works
<4>:<del> print(json.dumps(searchresults, indent=4))
# module: cloudtracker.datasources.athena class Athena(object): def get_events_from_search(self, searchresults): <0> """ <1> Given the results of a query for events, return these in a more usable fashion <2> """ <3> event_names = {} <4> print(json.dumps(searchresults, indent=4)) <5> <6> for event in searchresults: <7> event = event[0] <8> # event is now a string like "{field0=s3.amazonaws.com, field1=GetBucketAcl}" <9> # I parse out the field manually <10> # TODO Find a smarter way to parse this data <11> <12> # Remove the '{' and '}' <13> event = event[1:len(event)-1] <14> <15> # Split into 'field0=s3.amazonaws.com' and 'field1=GetBucketAcl' <16> event = event.split(", ") <17> # Get the eventsource 's3.amazonaws.com' <18> service = event[0].split('=')[1] <19> # Get the service 's3' <20> service = service.split(".")[0] <21> <22> # Get the eventname 'GetBucketAcl' <23> eventname = event[1].split('=')[1] <24> <25> event_names[normalize_api_call(service, eventname)] = True <26> <27> return event_names <28>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = ''
cloudtracker.datasources.athena/Athena.get_performed_event_names_by_role
Modified
duo-labs~cloudtracker
9183be38dc3eea486514dd9631a6713379ba0522
Role querying works
<1>:<add> <add> query = 'select distinct (eventsource, eventname) from {table_name} where (userIdentity.sessionContext.sessionIssuer.arn = \'{identity}\') and {search_filter}'.format( <add> table_name=self.table_name, <add> identity=role_iam['Arn'], <add> search_filter=self.search_filter) <add> response = self.query_athena(query) <del> raise Exception("Not implemented") <2>:<del> field = 'userIdentity.sessionContext.sessionIssuer.arn' <3>:<del> searchquery = searchquery.query(self.get_query_match(field, role_iam['Arn'])) <4>:<del> return self.get_events_from_search(searchquery)
# module: cloudtracker.datasources.athena class Athena(object): + def get_performed_event_names_by_role(self, _, role_iam): - def get_performed_event_names_by_role(self, searchquery, role_iam): <0> """For a role, return all performed events""" <1> raise Exception("Not implemented") <2> field = 'userIdentity.sessionContext.sessionIssuer.arn' <3> searchquery = searchquery.query(self.get_query_match(field, role_iam['Arn'])) <4> return self.get_events_from_search(searchquery) <5>
===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): def get_events_from_search(self, searchresults): """ Given the results of a query for events, return these in a more usable fashion """ event_names = {} - print(json.dumps(searchresults, indent=4)) for event in searchresults: event = event[0] # event is now a string like "{field0=s3.amazonaws.com, field1=GetBucketAcl}" # I parse out the field manually # TODO Find a smarter way to parse this data # Remove the '{' and '}' event = event[1:len(event)-1] # Split into 'field0=s3.amazonaws.com' and 'field1=GetBucketAcl' event = event.split(", ") # Get the eventsource 's3.amazonaws.com' service = event[0].split('=')[1] # Get the service 's3' service = service.split(".")[0] # Get the eventname 'GetBucketAcl' eventname = event[1].split('=')[1] event_names[normalize_api_call(service, eventname)] = True return event_names
cloudtracker.datasources.athena/Athena.query_athena
Modified
duo-labs~cloudtracker
777eb0611533d76b113768aca2e4b99883a88838
Bug fixes
<29>:<add> if skip_header: <add> # Skip header <del> # Skip header <30>:<add> continue <del> continue
# module: cloudtracker.datasources.athena class Athena(object): + def query_athena(self, query, context={'Database': database}, do_not_wait=False, skip_header=True): - def query_athena(self, query, context={'Database': database}, do_not_wait=False): <0> logging.debug('Making query {}'.format(query)) <1> <2> # Make query request dependent on whether the context is None or not <3> if context is None: <4> response = self.athena.start_query_execution( <5> QueryString=query, <6> ResultConfiguration={'OutputLocation': self.output_bucket} <7> ) <8> else: <9> response = self.athena.start_query_execution( <10> QueryString=query, <11> QueryExecutionContext=context, <12> ResultConfiguration={'OutputLocation': self.output_bucket} <13> ) <14> <15> if do_not_wait: <16> return response['QueryExecutionId'] <17> <18> self.wait_for_query_to_complete(response['QueryExecutionId']) <19> <20> # Paginate results and combine them <21> rows = [] <22> paginator = self.athena.get_paginator('get_query_results') <23> response_iterator = paginator.paginate(QueryExecutionId=response['QueryExecutionId']) <24> row_count = 0 <25> for response in response_iterator: <26> for row in response['ResultSet']['Rows']: <27> row_count +=1 <28> if row_count == 1: <29> # Skip header <30> continue <31> rows.append(self.extract_response_values(row)) <32> return rows <33>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = '' extract_response_values(row) wait_for_query_to_complete(queryExecutionId) at: cloudtracker.datasources.athena.Athena.__init__ self.output_bucket = config['output_s3_bucket'] self.output_bucket = 's3://aws-athena-query-results-{}-{}'.format(current_account_id, region) self.athena = boto3.client('athena') at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None
cloudtracker/get_allowed_users
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<1>:<add> return jmespath.search('UserDetailList[].UserName', account_iam) <del> users = pyjq.all('.UserDetailList[].UserName', account_iam) <2>:<del> return users
# module: cloudtracker def get_allowed_users(account_iam): <0> """Return all the users in an IAM file""" <1> users = pyjq.all('.UserDetailList[].UserName', account_iam) <2> return users <3>
===========unchanged ref 0=========== at: json load(fp: SupportsRead[Union[str, bytes]], *, cls: Optional[Type[JSONDecoder]]=..., object_hook: Optional[Callable[[Dict[Any, Any]], Any]]=..., parse_float: Optional[Callable[[str], Any]]=..., parse_int: Optional[Callable[[str], Any]]=..., parse_constant: Optional[Callable[[str], Any]]=..., object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]]=..., **kwds: Any) -> Any
cloudtracker/get_allowed_roles
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<1>:<add> return jmespath.search('RoleDetailList[].RoleName', account_iam) <del> roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) <2>:<del> return roles
# module: cloudtracker def get_allowed_roles(account_iam): <0> """Return all the roles in an IAM file""" <1> roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) <2> return roles <3>
===========changed ref 0=========== # module: cloudtracker def get_allowed_users(account_iam): """Return all the users in an IAM file""" + return jmespath.search('UserDetailList[].UserName', account_iam) - users = pyjq.all('.UserDetailList[].UserName', account_iam) - return users
cloudtracker/get_user_iam
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<1>:<del> try: <2>:<add> user_iam = jmespath.search('UserDetailList[] | [?UserName == `{}`] | [0]'.format(username), account_iam) <del> user_iam = pyjq.one('.UserDetailList[] | select(.UserName == "{}")'.format(username), account_iam) <3>:<add> if user_iam is None: <del> except IndexError:
# module: cloudtracker def get_user_iam(username, account_iam): <0> """Given the IAM of an account, and a username, return the IAM data for the user""" <1> try: <2> user_iam = pyjq.one('.UserDetailList[] | select(.UserName == "{}")'.format(username), account_iam) <3> except IndexError: <4> exit("ERROR: Unknown user named {}".format(username)) <5> return user_iam <6>
===========changed ref 0=========== # module: cloudtracker def get_allowed_roles(account_iam): """Return all the roles in an IAM file""" + return jmespath.search('RoleDetailList[].RoleName', account_iam) - roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) - return roles ===========changed ref 1=========== # module: cloudtracker def get_allowed_users(account_iam): """Return all the users in an IAM file""" + return jmespath.search('UserDetailList[].UserName', account_iam) - users = pyjq.all('.UserDetailList[].UserName', account_iam) - return users
cloudtracker/get_role_iam
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<1>:<del> try: <2>:<add> role_iam = jmespath.search('RoleDetailList[] | [?RoleName == `{}`] | [0]'.format(rolename), account_iam) <del> role_iam = pyjq.one('.RoleDetailList[] | select(.RoleName == "{}")'.format(rolename), account_iam) <3>:<add> if role_iam is None: <del> except IndexError:
# module: cloudtracker def get_role_iam(rolename, account_iam): <0> """Given the IAM of an account, and a role name, return the IAM data for the role""" <1> try: <2> role_iam = pyjq.one('.RoleDetailList[] | select(.RoleName == "{}")'.format(rolename), account_iam) <3> except IndexError: <4> raise Exception("Unknown role named {}".format(rolename)) <5> return role_iam <6>
===========changed ref 0=========== # module: cloudtracker def get_allowed_roles(account_iam): """Return all the roles in an IAM file""" + return jmespath.search('RoleDetailList[].RoleName', account_iam) - roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) - return roles ===========changed ref 1=========== # module: cloudtracker def get_allowed_users(account_iam): """Return all the users in an IAM file""" + return jmespath.search('UserDetailList[].UserName', account_iam) - users = pyjq.all('.UserDetailList[].UserName', account_iam) - return users ===========changed ref 2=========== # module: cloudtracker def get_user_iam(username, account_iam): """Given the IAM of an account, and a username, return the IAM data for the user""" - try: + user_iam = jmespath.search('UserDetailList[] | [?UserName == `{}`] | [0]'.format(username), account_iam) - user_iam = pyjq.one('.UserDetailList[] | select(.UserName == "{}")'.format(username), account_iam) + if user_iam is None: - except IndexError: exit("ERROR: Unknown user named {}".format(username)) return user_iam
cloudtracker/get_user_allowed_actions
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<8>:<add> group_iam = jmespath.search('GroupDetailList[] | [?GroupName == `{}`] | [0]'.format(group), account_iam) <del> group_iam = pyjq.one('.GroupDetailList[] | select(.GroupName == "{}")'.format(group), account_iam) <9>:<add> if group_iam is None: <add> continue <11>:<del> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <12>:<del> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <13>:<add> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <add> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <del> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <14>:<add> if police is None: <add> continue <25>:<del> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <26>:<del> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <27>:<add> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <add> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <del> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <28>:<add> if policy is None: <add> continue <32>:<add> for stmt in jmespath.search('UserPolicyList
# module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): <0> """Return the privileges granted to a user by IAM""" <1> groups = user_iam['GroupList'] <2> managed_policies = user_iam['AttachedManagedPolicies'] <3> <4> privileges = Privileges(aws_api_list) <5> <6> # Get permissions from groups <7> for group in groups: <8> group_iam = pyjq.one('.GroupDetailList[] | select(.GroupName == "{}")'.format(group), account_iam) <9> # Get privileges from managed policies attached to the group <10> for managed_policy in group_iam['AttachedManagedPolicies']: <11> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <12> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <13> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <14> for stmt in make_list(policy['Statement']): <15> privileges.add_stmt(stmt) <16> <17> # Get privileges from in-line policies attached to the group <18> for inline_policy in group_iam['GroupPolicyList']: <19> policy = inline_policy['PolicyDocument'] <20> for stmt in make_list(policy['Statement']): <21> privileges.add_stmt(stmt) <22> <23> # Get privileges from managed policies attached to the user <24> for managed_policy in managed_policies: <25> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <26> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <27> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <28> for stmt in make_list(policy['Statement']): <29> privileges.add_stmt(stmt) <30> <31> # Get privileges from inline policies attached to the user <32> for stmt in pyjq.all('.UserPolicyList[].PolicyDocument.Statement[]', user_iam): <33> privileges.add_stmt</s>
===========below chunk 0=========== # module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): # offset: 1 return privileges.determine_allowed() ===========unchanged ref 0=========== at: cloudtracker Privileges(aws_api_list) make_list(obj) at: cloudtracker.Privileges stmts = None roles = None aws_api_list = None add_stmt(stmt) ===========changed ref 0=========== # module: cloudtracker def get_allowed_roles(account_iam): """Return all the roles in an IAM file""" + return jmespath.search('RoleDetailList[].RoleName', account_iam) - roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) - return roles ===========changed ref 1=========== # module: cloudtracker def get_allowed_users(account_iam): """Return all the users in an IAM file""" + return jmespath.search('UserDetailList[].UserName', account_iam) - users = pyjq.all('.UserDetailList[].UserName', account_iam) - return users ===========changed ref 2=========== # module: cloudtracker def get_role_iam(rolename, account_iam): """Given the IAM of an account, and a role name, return the IAM data for the role""" - try: + role_iam = jmespath.search('RoleDetailList[] | [?RoleName == `{}`] | [0]'.format(rolename), account_iam) - role_iam = pyjq.one('.RoleDetailList[] | select(.RoleName == "{}")'.format(rolename), account_iam) + if role_iam is None: - except IndexError: raise Exception("Unknown role named {}".format(rolename)) return role_iam ===========changed ref 3=========== # module: cloudtracker def get_user_iam(username, account_iam): """Given the IAM of an account, and a username, return the IAM data for the user""" - try: + user_iam = jmespath.search('UserDetailList[] | [?UserName == `{}`] | [0]'.format(username), account_iam) - user_iam = pyjq.one('.UserDetailList[] | select(.UserName == "{}")'.format(username), account_iam) + if user_iam is None: - except IndexError: exit("ERROR: Unknown user named {}".format(username)) return user_iam
cloudtracker/get_role_allowed_actions
Modified
duo-labs~cloudtracker
2ab853c27a8a324e0758632fe57612490446632a
removing pyjq requirement in favor of more lightweight jmespath
<5>:<del> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <6>:<del> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <7>:<add> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <add> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <del> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <8>:<add> if policy is None: <add> continue
# module: cloudtracker def get_role_allowed_actions(aws_api_list, role_iam, account_iam): <0> """Return the privileges granted to a role by IAM""" <1> privileges = Privileges(aws_api_list) <2> <3> # Get privileges from managed policies <4> for managed_policy in role_iam['AttachedManagedPolicies']: <5> policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ <6> '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' <7> policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) <8> for stmt in make_list(policy['Statement']): <9> privileges.add_stmt(stmt) <10> <11> # Get privileges from attached policies <12> for policy in role_iam['RolePolicyList']: <13> for stmt in make_list(policy['PolicyDocument']['Statement']): <14> privileges.add_stmt(stmt) <15> <16> return privileges.determine_allowed() <17>
===========unchanged ref 0=========== at: cloudtracker Privileges(aws_api_list) make_list(obj) at: cloudtracker.Privileges add_stmt(stmt) determine_allowed() at: cloudtracker.get_user_allowed_actions privileges = Privileges(aws_api_list) ===========changed ref 0=========== # module: cloudtracker def get_allowed_roles(account_iam): """Return all the roles in an IAM file""" + return jmespath.search('RoleDetailList[].RoleName', account_iam) - roles = pyjq.all('.RoleDetailList[].RoleName', account_iam) - return roles ===========changed ref 1=========== # module: cloudtracker def get_allowed_users(account_iam): """Return all the users in an IAM file""" + return jmespath.search('UserDetailList[].UserName', account_iam) - users = pyjq.all('.UserDetailList[].UserName', account_iam) - return users ===========changed ref 2=========== # module: cloudtracker def get_role_iam(rolename, account_iam): """Given the IAM of an account, and a role name, return the IAM data for the role""" - try: + role_iam = jmespath.search('RoleDetailList[] | [?RoleName == `{}`] | [0]'.format(rolename), account_iam) - role_iam = pyjq.one('.RoleDetailList[] | select(.RoleName == "{}")'.format(rolename), account_iam) + if role_iam is None: - except IndexError: raise Exception("Unknown role named {}".format(rolename)) return role_iam ===========changed ref 3=========== # module: cloudtracker def get_user_iam(username, account_iam): """Given the IAM of an account, and a username, return the IAM data for the user""" - try: + user_iam = jmespath.search('UserDetailList[] | [?UserName == `{}`] | [0]'.format(username), account_iam) - user_iam = pyjq.one('.UserDetailList[] | select(.UserName == "{}")'.format(username), account_iam) + if user_iam is None: - except IndexError: exit("ERROR: Unknown user named {}".format(username)) return user_iam ===========changed ref 4=========== # module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): """Return the privileges granted to a user by IAM""" groups = user_iam['GroupList'] managed_policies = user_iam['AttachedManagedPolicies'] privileges = Privileges(aws_api_list) # Get permissions from groups for group in groups: + group_iam = jmespath.search('GroupDetailList[] | [?GroupName == `{}`] | [0]'.format(group), account_iam) - group_iam = pyjq.one('.GroupDetailList[] | select(.GroupName == "{}")'.format(group), account_iam) + if group_iam is None: + continue # Get privileges from managed policies attached to the group for managed_policy in group_iam['AttachedManagedPolicies']: - policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ - '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' + policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' + policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) - policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) + if police is None: + continue for stmt in make_list(policy['Statement']): privileges.add_stmt(stmt) # Get privileges from in-line policies attached to the group for inline_policy in group_iam['GroupPolicyList']: policy = inline_policy['PolicyDocument'] for stmt in make_list(policy['Statement']): privileges.add_stmt(stmt) # Get privileges from managed policies attached to the user for managed_policy in managed_policies: - policy_filter = '.Policies[] | select(.Arn == "{}") | ' \ - '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document'</s> ===========changed ref 5=========== # module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): # offset: 1 <s> select(.Arn == "{}") | ' \ - '.PolicyVersionList[] | select(.IsDefaultVersion == true) | .Document' + policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' + policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) - policy = pyjq.one(policy_filter.format(managed_policy['PolicyArn']), account_iam) + if policy is None: + continue for stmt in make_list(policy['Statement']): privileges.add_stmt(stmt) # Get privileges from inline policies attached to the user + for stmt in jmespath.search('UserPolicyList[].PolicyDocument.Statement', user_iam): - for stmt in pyjq.all('.UserPolicyList[].PolicyDocument.Statement[]', user_iam): privileges.add_stmt(stmt) return privileges.determine_allowed()
tests.unit.test_cloudtracker/TestCloudtracker.test_policy
Modified
duo-labs~cloudtracker
1db68080f65be0bf44f74544b36c275a69f859c7
fixing a few bad unit tests
<9>:<add> self.assertEquals(sorted(privileges.determine_allowed()), <del> self.assertEquals(privileges.determine_allowed(), <10>:<add> sorted(['s3:putobjecttagging', 's3:deleteobjecttagging'])) <del> ['s3:putobjecttagging', 's3:deleteobjecttagging'])
# module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_policy(self): <0> """Test having multiple statements, some allowed, some denied""" <1> privileges = Privileges(self.aws_api_list) <2> # Create a privilege object with some allowed and denied <3> stmt = {"Action": ["s3:*ObjectT*"], "Resource": "*", "Effect": "Allow"} <4> privileges.add_stmt(stmt) <5> stmt = {'Action': ['s3:GetObjectTagging', 's3:GetObjectTorrent'], <6> "Resource": "*", <7> "Effect": "Deny"} <8> privileges.add_stmt(stmt) <9> self.assertEquals(privileges.determine_allowed(), <10> ['s3:putobjecttagging', 's3:deleteobjecttagging']) <11>
===========unchanged ref 0=========== at: cloudtracker Privileges(aws_api_list) at: cloudtracker.Privileges stmts = None roles = None aws_api_list = None add_stmt(stmt) determine_allowed() at: tests.unit.test_cloudtracker.TestCloudtracker aws_api_list = None role_iam = { "AssumeRolePolicyDocument": {}, "RoleId": "AROA00000000000000000", "CreateDate": "2017-01-01T00:00:00Z", "InstanceProfileList": [], "RoleName": "test_role", "Path": "/", "AttachedManagedPolicies": [], "RolePolicyList": [ { "PolicyName": "KmsDecryptSecrets", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": [ "kms:DescribeKey", "kms:Decrypt" ], "Resource": "*", "Effect": "Allow", "Sid": "" } ] } }, { "PolicyName": "S3PutObject", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:PutObject", "s3:PutObjectAcl", "s3:ListBucket" ], "Resource": "*", "Effect": "Allow" } ] } } ], "Arn": "arn:aws:iam::111111111111:role/test_role" } at: tests.unit.test_cloudtracker.TestCloudtracker.__init__ self.aws_api_list = read_aws_api_list() at: unittest.case.TestCase failureException: Type[BaseException] longMessage: bool maxDiff: Optional[int] _testMethodName: str ===========unchanged ref 1=========== _testMethodDoc: str assertEquals(first: Any, second: Any, msg: Any=...) -> None
tests.unit.test_cloudtracker/TestCloudtracker.test_print_diff
Modified
duo-labs~cloudtracker
1db68080f65be0bf44f74544b36c275a69f859c7
fixing a few bad unit tests
<12>:<add> with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <del> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <20>:<add> with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <del> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <28>:<add> with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <del> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_
# module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_print_diff(self): <0> """Test print_diff""" <1> <2> with capture(print_diff, [], [], {}, False) as output: <3> self.assertEquals('', output) <4> <5> def mocked_is_recorded_by_cloudtrail(action): <6> """Instead of reading the whole file, just cherry pick this one action used in the tests""" <7> if action == 's3:putobject': <8> return False <9> return True <10> <11> # One action allowed, and performed, and should be shown <12> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <13> with capture(print_diff, <14> ['s3:createbucket'], # performed <15> ['s3:createbucket'], # allowed <16> {'show_benign': True, 'show_used': False, 'show_unknown': True}, False) as output: <17> self.assertEquals(' s3:createbucket\n', output) <18> <19> # 3 actions allowed, one is used, one is unused, and one is unknown; show all <20> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): <21> with capture(print_diff, <22> ['s3:createbucket', 'sts:getcalleridentity'], # performed <23> ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed <24> {'show_benign': True, 'show_used': False, 'show_unknown': True}, False) as output: <25> self.assertEquals(' s3:createbucket\n- s3:deletebucket\n? s3:putobject\n', output) <26> <27> # Same as above, but only show the used one <28> with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_</s>
===========below chunk 0=========== # module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_print_diff(self): # offset: 1 with capture(print_diff, ['s3:createbucket', 'sts:getcalleridentity'], # performed ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed {'show_benign': True, 'show_used': True, 'show_unknown': True}, False) as output: self.assertEquals(' s3:createbucket\n', output) # Hide the unknown with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): with capture(print_diff, ['s3:createbucket', 'sts:getcalleridentity'], # performed ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed {'show_benign': True, 'show_used': False, 'show_unknown': False}, False) as output: self.assertEquals(' s3:createbucket\n- s3:deletebucket\n', output) ===========unchanged ref 0=========== at: cloudtracker print_diff(performed_actions, allowed_actions, printfilter, use_color) at: tests.unit.test_cloudtracker capture(command, *args, **kwargs) at: unittest.case.TestCase assertEquals(first: Any, second: Any, msg: Any=...) -> None at: unittest.mock _patcher(target: Any, new: _T, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[_T] _patcher(target: Any, *, spec: Optional[Any]=..., create: bool=..., spec_set: Optional[Any]=..., autospec: Optional[Any]=..., new_callable: Optional[Any]=..., **kwargs: Any) -> _patch[Union[MagicMock, AsyncMock]] ===========changed ref 0=========== # module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_policy(self): """Test having multiple statements, some allowed, some denied""" privileges = Privileges(self.aws_api_list) # Create a privilege object with some allowed and denied stmt = {"Action": ["s3:*ObjectT*"], "Resource": "*", "Effect": "Allow"} privileges.add_stmt(stmt) stmt = {'Action': ['s3:GetObjectTagging', 's3:GetObjectTorrent'], "Resource": "*", "Effect": "Deny"} privileges.add_stmt(stmt) + self.assertEquals(sorted(privileges.determine_allowed()), - self.assertEquals(privileges.determine_allowed(), + sorted(['s3:putobjecttagging', 's3:deleteobjecttagging'])) - ['s3:putobjecttagging', 's3:deleteobjecttagging'])
tests.unit.test_cloudtracker/TestCloudtracker.test_get_role_allowed_actions
Modified
duo-labs~cloudtracker
1db68080f65be0bf44f74544b36c275a69f859c7
fixing a few bad unit tests
<9>:<add> self.assertEquals(sorted(['s3:putobject', 'kms:describekey', 'kms:decrypt', 's3:putobjectacl']), <del> self.assertEquals(['s3:putobject', 'kms:describekey', 'kms:decrypt', 's3:putobjectacl'], <10>:<add> sorted(get_role_allowed_actions(aws_api_list, self.role_iam, account_iam))) <del> get_role_allowed_actions(aws_api_list, self.role_iam, account_iam))
# module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_get_role_allowed_actions(self): <0> """Test get_role_allowed_actions""" <1> account_iam = { <2> "RoleDetailList": [self.role_iam], <3> "UserDetailList": [], <4> "GroupDetailList": [], <5> "Policies": [] <6> } <7> <8> aws_api_list = read_aws_api_list() <9> self.assertEquals(['s3:putobject', 'kms:describekey', 'kms:decrypt', 's3:putobjectacl'], <10> get_role_allowed_actions(aws_api_list, self.role_iam, account_iam)) <11>
===========unchanged ref 0=========== at: cloudtracker get_role_allowed_actions(aws_api_list, role_iam, account_iam) read_aws_api_list(aws_api_list_file='aws_api_list.txt') at: tests.unit.test_cloudtracker.TestCloudtracker role_iam = { "AssumeRolePolicyDocument": {}, "RoleId": "AROA00000000000000000", "CreateDate": "2017-01-01T00:00:00Z", "InstanceProfileList": [], "RoleName": "test_role", "Path": "/", "AttachedManagedPolicies": [], "RolePolicyList": [ { "PolicyName": "KmsDecryptSecrets", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": [ "kms:DescribeKey", "kms:Decrypt" ], "Resource": "*", "Effect": "Allow", "Sid": "" } ] } }, { "PolicyName": "S3PutObject", "PolicyDocument": { "Version": "2012-10-17", "Statement": [ { "Action": [ "s3:PutObject", "s3:PutObjectAcl", "s3:ListBucket" ], "Resource": "*", "Effect": "Allow" } ] } } ], "Arn": "arn:aws:iam::111111111111:role/test_role" } at: unittest.case.TestCase assertEquals(first: Any, second: Any, msg: Any=...) -> None ===========changed ref 0=========== # module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_policy(self): """Test having multiple statements, some allowed, some denied""" privileges = Privileges(self.aws_api_list) # Create a privilege object with some allowed and denied stmt = {"Action": ["s3:*ObjectT*"], "Resource": "*", "Effect": "Allow"} privileges.add_stmt(stmt) stmt = {'Action': ['s3:GetObjectTagging', 's3:GetObjectTorrent'], "Resource": "*", "Effect": "Deny"} privileges.add_stmt(stmt) + self.assertEquals(sorted(privileges.determine_allowed()), - self.assertEquals(privileges.determine_allowed(), + sorted(['s3:putobjecttagging', 's3:deleteobjecttagging'])) - ['s3:putobjecttagging', 's3:deleteobjecttagging']) ===========changed ref 1=========== # module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_print_diff(self): """Test print_diff""" with capture(print_diff, [], [], {}, False) as output: self.assertEquals('', output) def mocked_is_recorded_by_cloudtrail(action): """Instead of reading the whole file, just cherry pick this one action used in the tests""" if action == 's3:putobject': return False return True # One action allowed, and performed, and should be shown + with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): - with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): with capture(print_diff, ['s3:createbucket'], # performed ['s3:createbucket'], # allowed {'show_benign': True, 'show_used': False, 'show_unknown': True}, False) as output: self.assertEquals(' s3:createbucket\n', output) # 3 actions allowed, one is used, one is unused, and one is unknown; show all + with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): - with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): with capture(print_diff, ['s3:createbucket', 'sts:getcalleridentity'], # performed ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed {'show_benign': True, 'show_used': False, 'show_unknown': True}, False) as output: self.assertEquals(' s3:createbucket\n- s3:deletebucket\</s> ===========changed ref 2=========== # module: tests.unit.test_cloudtracker class TestCloudtracker(unittest.TestCase): def test_print_diff(self): # offset: 1 <s>': True}, False) as output: self.assertEquals(' s3:createbucket\n- s3:deletebucket\n? s3:putobject\n', output) # Same as above, but only show the used one + with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): - with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): with capture(print_diff, ['s3:createbucket', 'sts:getcalleridentity'], # performed ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed {'show_benign': True, 'show_used': True, 'show_unknown': True}, False) as output: self.assertEquals(' s3:createbucket\n', output) # Hide the unknown + with patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): - with mock.patch('cloudtracker.is_recorded_by_cloudtrail', side_effect=mocked_is_recorded_by_cloudtrail): with capture(print_diff, ['s3:createbucket', 'sts:getcalleridentity'], # performed ['s3:createbucket', 's3:putobject', 's3:deletebucket'], # allowed {'show_benign': True, 'show_used': False, 'show_unknown': False}, False) as output: self.assertEquals(' s3:createbucket\n- s3:deletebucket\n', output)
cloudtracker/run
Modified
duo-labs~cloudtracker
28f23747169b6b468c9e3aedbed1a6f6729f7a79
removing need for Makefile to install elasticsearch dependencies
<6>:<add> try: <add> from cloudtracker.datasources.es import ElasticSearch <del> from cloudtracker.datasources.es import ElasticSearch <7>:<add> except ImportError: <add> exit( <add> "Elasticsearch support not installed. Install with support via " <add> "'pip install git+https://github.com/duo-labs/cloudtracker.git#egg=cloudtracker[es1]' for " <add> "elasticsearch 1 support, or " <add> "'pip install git+https://github.com/duo-labs/cloudtracker.git#egg=cloudtracker[es6]' for " <add> "elasticsearch 6 support" <add> )
# module: cloudtracker def run(args, config, start, end): <0> """Perform the requested command""" <1> use_color = args.use_color <2> <3> account = get_account(config['accounts'], args.account) <4> <5> if 'elasticsearch' in config: <6> from cloudtracker.datasources.es import ElasticSearch <7> datasource = ElasticSearch(config['elasticsearch'], start, end) <8> else: <9> logging.debug("Using Athena") <10> from cloudtracker.datasources.athena import Athena <11> datasource = Athena(config['athena'], account, start, end, args) <12> <13> # Read AWS actions <14> aws_api_list = read_aws_api_list() <15> <16> # Read cloudtrail_supported_events <17> global cloudtrail_supported_actions <18> cloudtrail_supported_actions = {} <19> with open("cloudtrail_supported_actions.txt") as f: <20> lines = f.readlines() <21> for line in lines: <22> (service, event) = line.rstrip().split(":") <23> cloudtrail_supported_actions[normalize_api_call(service, event)] = True <24> <25> account_iam = get_account_iam(account) <26> <27> if args.list: <28> actor_type = args.list <29> <30> if actor_type == 'users': <31> allowed_actors = get_allowed_users(account_iam) <32> performed_actors = datasource.get_performed_users() <33> elif actor_type == 'roles': <34> allowed_actors = get_allowed_roles(account_iam) <35> performed_actors = datasource.get_performed_roles() <36> else: <37> exit("ERROR: --list argument must be one of 'users' or 'roles'") <38> <39> print_actor_diff(performed_actors, allowed_actors, use_color) <40> <41> else: <42> if args.destaccount: <43> destination_account = get_account(config['accounts'], args.destaccount</s>
===========below chunk 0=========== # module: cloudtracker def run(args, config, start, end): # offset: 1 else: destination_account = account destination_iam = get_account_iam(destination_account) search_query = datasource.get_search_query() if args.user: username = args.user user_iam = get_user_iam(username, account_iam) print("Getting info on {}, user created {}".format(args.user, user_iam['CreateDate'])) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_user_in_role( search_query, user_iam, dest_role_iam) else: allowed_actions = get_user_allowed_actions(aws_api_list, user_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_user( search_query, user_iam) elif args.role: rolename = args.role role_iam = get_role_iam(rolename, account_iam) print("Getting info for role {}".format(rolename)) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_role_in_role( search_query, role_iam, dest_role_iam) else: allowed_actions = get_role_allowed_actions(aws_api_list, role_iam,</s> ===========below chunk 1=========== # module: cloudtracker def run(args, config, start, end): # offset: 2 <s>iam) else: allowed_actions = get_role_allowed_actions(aws_api_list, role_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_role( search_query, role_iam) else: exit("ERROR: Must specify a user or a role") printfilter = {} printfilter['show_unknown'] = args.show_unknown printfilter['show_benign'] = args.show_benign printfilter['show_used'] = args.show_used print_diff(performed_actions, allowed_actions, printfilter, use_color) ===========unchanged ref 0=========== at: cloudtracker normalize_api_call(service, eventName) get_account_iam(account) get_allowed_users(account_iam) get_allowed_roles(account_iam) print_actor_diff(performed_actors, allowed_actors, use_color) get_user_iam(username, account_iam) get_role_iam(rolename, account_iam) get_user_allowed_actions(aws_api_list, user_iam, account_iam) get_role_allowed_actions(aws_api_list, role_iam, account_iam) get_account(accounts, account_name) read_aws_api_list(aws_api_list_file='aws_api_list.txt') at: cloudtracker.datasources.athena Athena(config, account, start, end, args) at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = '' get_performed_users() get_performed_roles() get_search_query() get_performed_event_names_by_user(_, user_iam) get_performed_event_names_by_role(_, role_iam) at: cloudtracker.datasources.es ElasticSearch(config, start, end) at: cloudtracker.datasources.es.ElasticSearch es = None index = "cloudtrail" key_prefix = "" searchfilter = None get_performed_users() get_performed_roles() get_search_query() get_performed_event_names_by_user(searchquery, user_iam) ===========unchanged ref 1=========== get_performed_event_names_by_role(searchquery, role_iam) get_performed_event_names_by_user_in_role(searchquery, user_iam, role_iam) get_performed_event_names_by_role_in_role(searchquery, role_iam, dest_role_iam) at: io.FileIO readlines(self, hint: int=..., /) -> List[bytes] at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: typing.IO __slots__ = () readlines(hint: int=...) -> list[AnyStr]
cloudtracker/read_aws_api_list
Modified
duo-labs~cloudtracker
258b600227006bcaf07f96e2a04dcc5627fd30d6
using setuptools package_data to include api and cloudtrail txt files
<1>:<add> api_list_path = pkg_resources.resource_filename(__name__, "data/{}".format(aws_api_list_file)) <2>:<add> with open(api_list_path) as f: <del> with open(aws_api_list_file) as f: <5>:<add> service, event = line.rstrip().split(":") <del> (service, event) = line.rstrip().split(":")
# module: cloudtracker def read_aws_api_list(aws_api_list_file='aws_api_list.txt'): <0> """Read in the list of all known AWS API calls""" <1> aws_api_list = {} <2> with open(aws_api_list_file) as f: <3> lines = f.readlines() <4> for line in lines: <5> (service, event) = line.rstrip().split(":") <6> aws_api_list[normalize_api_call(service, event)] = True <7> return aws_api_list <8>
===========unchanged ref 0=========== at: io.TextIOWrapper readlines(self, hint: int=..., /) -> List[str] at: pkg_resources resource_filename = None at: typing.IO __slots__ = () readlines(hint: int=...) -> list[AnyStr]
cloudtracker/run
Modified
duo-labs~cloudtracker
258b600227006bcaf07f96e2a04dcc5627fd30d6
using setuptools package_data to include api and cloudtrail txt files
<27>:<add> ct_actions_path = pkg_resources.resource_filename(__name__, "data/{}".format("cloudtrail_supported_actions.txt")) <28>:<add> with open(ct_actions_path) as f: <del> with open("cloudtrail_supported_actions.txt") as f:
# module: cloudtracker def run(args, config, start, end): <0> """Perform the requested command""" <1> use_color = args.use_color <2> <3> account = get_account(config['accounts'], args.account) <4> <5> if 'elasticsearch' in config: <6> try: <7> from cloudtracker.datasources.es import ElasticSearch <8> except ImportError: <9> exit( <10> "Elasticsearch support not installed. Install with support via " <11> "'pip install git+https://github.com/duo-labs/cloudtracker.git#egg=cloudtracker[es1]' for " <12> "elasticsearch 1 support, or " <13> "'pip install git+https://github.com/duo-labs/cloudtracker.git#egg=cloudtracker[es6]' for " <14> "elasticsearch 6 support" <15> ) <16> datasource = ElasticSearch(config['elasticsearch'], start, end) <17> else: <18> logging.debug("Using Athena") <19> from cloudtracker.datasources.athena import Athena <20> datasource = Athena(config['athena'], account, start, end, args) <21> <22> # Read AWS actions <23> aws_api_list = read_aws_api_list() <24> <25> # Read cloudtrail_supported_events <26> global cloudtrail_supported_actions <27> cloudtrail_supported_actions = {} <28> with open("cloudtrail_supported_actions.txt") as f: <29> lines = f.readlines() <30> for line in lines: <31> (service, event) = line.rstrip().split(":") <32> cloudtrail_supported_actions[normalize_api_call(service, event)] = True <33> <34> account_iam = get_account_iam(account) <35> <36> if args.list: <37> actor_type = args.list <38> <39> if actor_type == 'users': <40> allowed_actors = get_allowed_users(account_iam) <41> performed_actors = datasource.get_performed_users() <42> elif actor_type == 'roles</s>
===========below chunk 0=========== # module: cloudtracker def run(args, config, start, end): # offset: 1 allowed_actors = get_allowed_roles(account_iam) performed_actors = datasource.get_performed_roles() else: exit("ERROR: --list argument must be one of 'users' or 'roles'") print_actor_diff(performed_actors, allowed_actors, use_color) else: if args.destaccount: destination_account = get_account(config['accounts'], args.destaccount) else: destination_account = account destination_iam = get_account_iam(destination_account) search_query = datasource.get_search_query() if args.user: username = args.user user_iam = get_user_iam(username, account_iam) print("Getting info on {}, user created {}".format(args.user, user_iam['CreateDate'])) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_user_in_role( search_query, user_iam, dest_role_iam) else: allowed_actions = get_user_allowed_actions(aws_api_list, user_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_user( search_query, user_iam) elif args.role: rolename = args.role role_iam = get_role_iam(rolename, account_iam) print("Getting info for role {}".format(rolename)) if args.destrole: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting</s> ===========below chunk 1=========== # module: cloudtracker def run(args, config, start, end): # offset: 2 <s>role: dest_role_iam = get_role_iam(args.destrole, destination_iam) print("Getting info for AssumeRole into {}".format(args.destrole)) allowed_actions = get_role_allowed_actions(aws_api_list, dest_role_iam, destination_iam) performed_actions = datasource.get_performed_event_names_by_role_in_role( search_query, role_iam, dest_role_iam) else: allowed_actions = get_role_allowed_actions(aws_api_list, role_iam, account_iam) performed_actions = datasource.get_performed_event_names_by_role( search_query, role_iam) else: exit("ERROR: Must specify a user or a role") printfilter = {} printfilter['show_unknown'] = args.show_unknown printfilter['show_benign'] = args.show_benign printfilter['show_used'] = args.show_used print_diff(performed_actions, allowed_actions, printfilter, use_color) ===========unchanged ref 0=========== at: cloudtracker normalize_api_call(service, eventName) get_account_iam(account) get_allowed_users(account_iam) get_allowed_roles(account_iam) print_actor_diff(performed_actors, allowed_actors, use_color) get_user_iam(username, account_iam) get_role_iam(rolename, account_iam) get_user_allowed_actions(aws_api_list, user_iam, account_iam) get_role_allowed_actions(aws_api_list, role_iam, account_iam) get_account(accounts, account_name) read_aws_api_list(aws_api_list_file='aws_api_list.txt') at: cloudtracker.datasources.athena Athena(config, account, start, end, args) at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = 'cloudtracker' output_bucket = 'aws-athena-query-results-ACCOUNT_ID-REGION' search_filter = '' table_name = '' get_performed_users() get_performed_roles() get_search_query() get_performed_event_names_by_user(_, user_iam) get_performed_event_names_by_role(_, role_iam) at: cloudtracker.datasources.es ElasticSearch(config, start, end) at: cloudtracker.datasources.es.ElasticSearch es = None index = "cloudtrail" key_prefix = "" searchfilter = None get_performed_users() get_performed_roles() get_search_query() get_performed_event_names_by_user(searchquery, user_iam) ===========unchanged ref 1=========== get_performed_event_names_by_role(searchquery, role_iam) get_performed_event_names_by_user_in_role(searchquery, user_iam, role_iam) get_performed_event_names_by_role_in_role(searchquery, role_iam, dest_role_iam) at: io.BufferedRandom readlines(self, hint: int=..., /) -> List[bytes] at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None at: pkg_resources resource_filename = None at: typing.IO readlines(hint: int=...) -> list[AnyStr] ===========changed ref 0=========== # module: cloudtracker def read_aws_api_list(aws_api_list_file='aws_api_list.txt'): """Read in the list of all known AWS API calls""" + api_list_path = pkg_resources.resource_filename(__name__, "data/{}".format(aws_api_list_file)) aws_api_list = {} + with open(api_list_path) as f: - with open(aws_api_list_file) as f: lines = f.readlines() for line in lines: + service, event = line.rstrip().split(":") - (service, event) = line.rstrip().split(":") aws_api_list[normalize_api_call(service, event)] = True return aws_api_list
cloudtracker/get_user_allowed_actions
Modified
duo-labs~cloudtracker
9c8e4a5fbe738d50c83b05a5cdcc1e836a48f696
fixing typo
<15>:<add> if policy is None: <del> if police is None:
# module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): <0> """Return the privileges granted to a user by IAM""" <1> groups = user_iam['GroupList'] <2> managed_policies = user_iam['AttachedManagedPolicies'] <3> <4> privileges = Privileges(aws_api_list) <5> <6> # Get permissions from groups <7> for group in groups: <8> group_iam = jmespath.search('GroupDetailList[] | [?GroupName == `{}`] | [0]'.format(group), account_iam) <9> if group_iam is None: <10> continue <11> # Get privileges from managed policies attached to the group <12> for managed_policy in group_iam['AttachedManagedPolicies']: <13> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <14> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <15> if police is None: <16> continue <17> for stmt in make_list(policy['Statement']): <18> privileges.add_stmt(stmt) <19> <20> # Get privileges from in-line policies attached to the group <21> for inline_policy in group_iam['GroupPolicyList']: <22> policy = inline_policy['PolicyDocument'] <23> for stmt in make_list(policy['Statement']): <24> privileges.add_stmt(stmt) <25> <26> # Get privileges from managed policies attached to the user <27> for managed_policy in managed_policies: <28> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <29> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <30> if policy is None: <31> continue <32> for stmt in make_list(policy['Statement']): <33> privileges.add_stmt(stmt) <34> <35> # Get privileges from inline policies attached to the user <36> for stmt in jmes</s>
===========below chunk 0=========== # module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): # offset: 1 privileges.add_stmt(stmt) return privileges.determine_allowed() ===========unchanged ref 0=========== at: cloudtracker Privileges(aws_api_list) make_list(obj) at: cloudtracker.Privileges stmts = None roles = None aws_api_list = None add_stmt(stmt) determine_allowed()
cloudtracker/get_user_allowed_actions
Modified
duo-labs~cloudtracker
08bf8b2c00214e4cefec837042e615409f275cfc
Fix "'NoneType' object is not iterable" error
<36>:<add> for stmt in jmespath.search('UserPolicyList[].PolicyDocument.Statement', user_iam) or []: <del> for stmt in jmespath
# module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): <0> """Return the privileges granted to a user by IAM""" <1> groups = user_iam['GroupList'] <2> managed_policies = user_iam['AttachedManagedPolicies'] <3> <4> privileges = Privileges(aws_api_list) <5> <6> # Get permissions from groups <7> for group in groups: <8> group_iam = jmespath.search('GroupDetailList[] | [?GroupName == `{}`] | [0]'.format(group), account_iam) <9> if group_iam is None: <10> continue <11> # Get privileges from managed policies attached to the group <12> for managed_policy in group_iam['AttachedManagedPolicies']: <13> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <14> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <15> if policy is None: <16> continue <17> for stmt in make_list(policy['Statement']): <18> privileges.add_stmt(stmt) <19> <20> # Get privileges from in-line policies attached to the group <21> for inline_policy in group_iam['GroupPolicyList']: <22> policy = inline_policy['PolicyDocument'] <23> for stmt in make_list(policy['Statement']): <24> privileges.add_stmt(stmt) <25> <26> # Get privileges from managed policies attached to the user <27> for managed_policy in managed_policies: <28> policy_filter = 'Policies[?Arn == `{}`].PolicyVersionList[?IsDefaultVersion == true] | [0][0].Document' <29> policy = jmespath.search(policy_filter.format(managed_policy['PolicyArn']), account_iam) <30> if policy is None: <31> continue <32> for stmt in make_list(policy['Statement']): <33> privileges.add_stmt(stmt) <34> <35> # Get privileges from inline policies attached to the user <36> for stmt in jmespath</s>
===========below chunk 0=========== # module: cloudtracker def get_user_allowed_actions(aws_api_list, user_iam, account_iam): # offset: 1 privileges.add_stmt(stmt) return privileges.determine_allowed() ===========unchanged ref 0=========== at: cloudtracker Privileges(aws_api_list) make_list(obj) at: cloudtracker.Privileges stmts = None roles = None aws_api_list = None add_stmt(stmt) determine_allowed()
setup/get_description
Modified
duo-labs~cloudtracker
063877cc04144d4a95fa93a2b8cdd760232e73c7
Fix bug
<0>:<add> return open(os.path.join(os.path.abspath(HERE), 'README.md'), encoding='utf-8').read() <del> with open(path.join(os.path.abspath(HERE), 'README.md'), encoding='utf-8') as f: <1>:<del> return f.read()
# module: setup def get_description(): <0> with open(path.join(os.path.abspath(HERE), 'README.md'), encoding='utf-8') as f: <1> return f.read() <2>
===========unchanged ref 0=========== at: io.FileIO read(self, size: int=..., /) -> bytes at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback at: setup HERE = os.path.dirname(__file__) at: typing.IO __slots__ = () read(n: int=...) -> AnyStr
cloudtracker.datasources.athena/Athena.query_athena
Modified
duo-labs~cloudtracker
18a183731770d10ec0a2b194526007b6b9270aad
Add support for Athena WorkGroup (#75)
<7>:<add> WorkGroup=self.workgroup <13>:<add> WorkGroup=self.workgroup
# module: cloudtracker.datasources.athena class Athena(object): def query_athena( self, query, context={"Database": database}, do_not_wait=False, skip_header=True ): <0> logging.debug("Making query {}".format(query)) <1> <2> # Make query request dependent on whether the context is None or not <3> if context is None: <4> response = self.athena.start_query_execution( <5> QueryString=query, <6> ResultConfiguration={"OutputLocation": self.output_bucket}, <7> ) <8> else: <9> response = self.athena.start_query_execution( <10> QueryString=query, <11> QueryExecutionContext=context, <12> ResultConfiguration={"OutputLocation": self.output_bucket}, <13> ) <14> <15> if do_not_wait: <16> return response["QueryExecutionId"] <17> <18> self.wait_for_query_to_complete(response["QueryExecutionId"]) <19> <20> # Paginate results and combine them <21> rows = [] <22> paginator = self.athena.get_paginator("get_query_results") <23> response_iterator = paginator.paginate( <24> QueryExecutionId=response["QueryExecutionId"] <25> ) <26> row_count = 0 <27> for response in response_iterator: <28> for row in response["ResultSet"]["Rows"]: <29> row_count += 1 <30> if row_count == 1: <31> if skip_header: <32> # Skip header <33> continue <34> rows.append(self.extract_response_values(row)) <35> return rows <36>
===========unchanged ref 0=========== at: cloudtracker.datasources.athena.Athena athena = None s3 = None database = "cloudtracker" output_bucket = "aws-athena-query-results-ACCOUNT_ID-REGION" search_filter = "" table_name = "" workgroup = 'primary' wait_for_query_to_complete(queryExecutionId) at: cloudtracker.datasources.athena.Athena.__init__ self.output_bucket = "s3://aws-athena-query-results-{}-{}".format( current_account_id, region ) self.output_bucket = config["output_s3_bucket"] self.workgroup = config["workgroup"] self.athena = boto3.client("athena") at: logging debug(msg: Any, *args: Any, exc_info: _ExcInfoType=..., stack_info: bool=..., extra: Optional[Dict[str, Any]]=..., **kwargs: Any) -> None ===========changed ref 0=========== # module: cloudtracker.datasources.athena class Athena(object): athena = None s3 = None database = "cloudtracker" output_bucket = "aws-athena-query-results-ACCOUNT_ID-REGION" search_filter = "" table_name = "" + workgroup = 'primary'
What.what/main
Modified
bee-san~pyWhat
9cbac76f290d2ca74bb2c010fb95ef21254cd35b
tests work
<0>:<del> print("hello!") <2>:<add> print("This is a " + r.check(kwargs["text"])[0]["Name"]) <del> r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o")
# module: What.what @click.command() + @click.option('-t', '--text', help="The text you want to identify.", required=True) - @click.option('-t', '--text', help="The text you want to identify.") def main(**kwargs): <0> print("hello!") <1> r = regex_identifier.RegexIdentifier() <2> r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <3>
===========unchanged ref 0=========== at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] ===========unchanged ref 1=========== option(*param_decls: str, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=..., hide_input: bool=..., is_flag: Optional[bool]=..., flag_value: Optional[Any]=..., multiple: bool=..., count: bool=..., allow_from_autoenv: bool=..., type: _T=..., help: Optional[str]=..., show_choices: bool=..., default: Optional[Any]=..., required: bool=..., callback: Optional[Callable[[Context, Union[Option, Parameter], Union[bool, int, str]], _T]]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., **kwargs: Any) -> _IdentityFunction option(*param_decls: str, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=..., hide_input: bool=..., is_flag: Optional[bool]=..., flag_value: Optional[Any]=..., multiple: bool=..., count: bool=..., allow_from_autoenv: bool=..., type: Type[int]=..., help: Optional[str]=..., show_choices: bool=..., default: Optional[Any]=..., required: bool=..., callback: Callable[[Context, Union[Option, Parameter], int], Any]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., **kwargs: Any) -> _IdentityFunction option(*param_decls: Text, cls: Type[Option]=..., show_default: Union[bool, Text]=..., prompt: Union[bool, Text]=..., confirmation_prompt: bool=...,</s> ===========unchanged ref 2=========== at: regex_identifier RegexIdentifier() at: regex_identifier.RegexIdentifier check(text)
What.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
9cbac76f290d2ca74bb2c010fb95ef21254cd35b
tests work
<0>:<add> with open("What/data.yaml", "r") as myfile: <del> with open("data.json", "r") as myfile: <2>:<del> <3>:<del> self.regexes = json.loads(data) <4>:<del> print(self.regexes) <5>:<del> <6>:<del> print("ok it runs??") <7>:<add> self.regexes = yaml.load(data, Loader=yaml.FullLoader)
# module: What.regex_identifier class RegexIdentifier: def __init__(self): <0> with open("data.json", "r") as myfile: <1> data = myfile.read() <2> <3> self.regexes = json.loads(data) <4> print(self.regexes) <5> <6> print("ok it runs??") <7>
===========unchanged ref 0=========== at: io.FileIO read(self, size: int=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: What.what - - - main() + if __name__ == "__main__": + main() ===========changed ref 1=========== # module: What.what @click.command() + @click.option('-t', '--text', help="The text you want to identify.", required=True) - @click.option('-t', '--text', help="The text you want to identify.") def main(**kwargs): - print("hello!") r = regex_identifier.RegexIdentifier() + print("This is a " + r.check(kwargs["text"])[0]["Name"]) - r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o")
What.regex_identifier/RegexIdentifier.check
Modified
bee-san~pyWhat
9cbac76f290d2ca74bb2c010fb95ef21254cd35b
tests work
<0>:<add> matches = [] <2>:<add> matches.append(reg) <del> print(reg) <3>:<add> return matches <del> print("it done it")
# module: What.regex_identifier class RegexIdentifier: + def check(self, text): <0> for reg in self.regexes: <1> if re.compile(reg["Regex"]).match(text): <2> print(reg) <3> print("it done it") <4>
===========unchanged ref 0=========== at: What.regex_identifier.RegexIdentifier.check matches = [] at: re compile(pattern: AnyStr, flags: _FlagsType=...) -> Pattern[AnyStr] compile(pattern: Pattern[AnyStr], flags: _FlagsType=...) -> Pattern[AnyStr] at: typing.Pattern flags: int groupindex: Mapping[str, int] groups: int pattern: AnyStr match(string: AnyStr, pos: int=..., endpos: int=...) -> Optional[Match[AnyStr]] ===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: def __init__(self): + with open("What/data.yaml", "r") as myfile: - with open("data.json", "r") as myfile: data = myfile.read() - - self.regexes = json.loads(data) - print(self.regexes) - - print("ok it runs??") + self.regexes = yaml.load(data, Loader=yaml.FullLoader) ===========changed ref 1=========== # module: What.what - - - main() + if __name__ == "__main__": + main() ===========changed ref 2=========== # module: What.what @click.command() + @click.option('-t', '--text', help="The text you want to identify.", required=True) - @click.option('-t', '--text', help="The text you want to identify.") def main(**kwargs): - print("hello!") r = regex_identifier.RegexIdentifier() + print("This is a " + r.check(kwargs["text"])[0]["Name"]) - r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o")
What.identifier/Identifier.__init__
Modified
bee-san~pyWhat
9cbac76f290d2ca74bb2c010fb95ef21254cd35b
tests work
<0>:<add> self.regex_id = RegexIdentifier() <add> self.lang_detect = LanguageDetector() <del> pass
# module: What.identifier class Identifier: def __init__(self): <0> pass <1>
===========changed ref 0=========== + # module: What.languageDetector + + ===========changed ref 1=========== + # module: What.languageDetector + + ===========changed ref 2=========== + # module: tests + + ===========changed ref 3=========== # module: What.what - - - main() + if __name__ == "__main__": + main() ===========changed ref 4=========== # module: What.regex_identifier class RegexIdentifier: + def check(self, text): + matches = [] for reg in self.regexes: if re.compile(reg["Regex"]).match(text): + matches.append(reg) - print(reg) + return matches - print("it done it") ===========changed ref 5=========== # module: What.what @click.command() + @click.option('-t', '--text', help="The text you want to identify.", required=True) - @click.option('-t', '--text', help="The text you want to identify.") def main(**kwargs): - print("hello!") r = regex_identifier.RegexIdentifier() + print("This is a " + r.check(kwargs["text"])[0]["Name"]) - r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") ===========changed ref 6=========== # module: What.regex_identifier class RegexIdentifier: def __init__(self): + with open("What/data.yaml", "r") as myfile: - with open("data.json", "r") as myfile: data = myfile.read() - - self.regexes = json.loads(data) - print(self.regexes) - - print("ok it runs??") + self.regexes = yaml.load(data, Loader=yaml.FullLoader) ===========changed ref 7=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + import what - from What import what what.main()
tests.test_regex_identifier/test_ctf_flag
Modified
bee-san~pyWhat
4cc88e9fe748fa782c309dd3e0dadbf2cedcabbd
fixed uppercase problem with CTF flags
<1>:<add> res = r.check("thm{hello}") <del> res = r.check("THM{hello}")
# module: tests.test_regex_identifier def test_ctf_flag(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("THM{hello}") <2> assert "Capture The Flag Flags" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text)
tests.test_identifier/test_identifier_works
Modified
bee-san~pyWhat
f85cc7459e744cd31191df8ae5d882ba7daf6a98
More tests
<1>:<add> out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <del> out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <2>:<add> assert "Dogecoin" in out["Regexes"][0]["Name"]
# module: tests.test_identifier def test_identifier_works(): <0> r = identifier.Identifier() <1> out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <2>
===========unchanged ref 0=========== at: What.identifier Identifier() at: What.identifier.Identifier identify(text: str) -> dict
tests.test_regex_identifier/test_ctf_flag
Modified
bee-san~pyWhat
f85cc7459e744cd31191df8ae5d882ba7daf6a98
More tests
<2>:<add> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] <del> assert "Capture The Flag Flags" in res[0]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("thm{hello}") <2> assert "Capture The Flag Flags" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator skipif: _SkipifMarkDecorator xfail: _XfailMarkDecorator parametrize: _ParametrizeMarkDecorator usefixtures: _UsefixturesMarkDecorator filterwarnings: _FilterwarningsMarkDecorator ===========changed ref 0=========== # module: tests.test_identifier + + + def test_identifier_spanish(): + r = identifier.Identifier() + out = r.identify("Me gustan los bombos y la musica ") + assert "es" in out["Language"] + ===========changed ref 1=========== # module: tests.test_identifier def test_identifier_works(): r = identifier.Identifier() + out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") - out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin" in out["Regexes"][0]["Name"]
tests.test_regex_identifier/test_ctf_flag_uppercase
Modified
bee-san~pyWhat
f85cc7459e744cd31191df8ae5d882ba7daf6a98
More tests
<2>:<add> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] <del> assert "Capture The Flag Flags" in res[0]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag_uppercase(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("FLAG{hello}") <2> assert "Capture The Flag Flags" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator at: tests.test_regex_identifier.test_https res = r.check("https://tryhackme.com") ===========changed ref 0=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") + def test_https(): + r = regex_identifier.RegexIdentifier() + res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Name"] + ===========changed ref 1=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] - assert "Capture The Flag Flags" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_identifier + + + def test_identifier_spanish(): + r = identifier.Identifier() + out = r.identify("Me gustan los bombos y la musica ") + assert "es" in out["Language"] + ===========changed ref 3=========== # module: tests.test_identifier def test_identifier_works(): r = identifier.Identifier() + out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") - out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin" in out["Regexes"][0]["Name"]
What.regex_identifier/RegexIdentifier.check
Modified
bee-san~pyWhat
5be82a1292f36fda72c3d3a801899c64c005ac46
Done for the day
<2>:<add> if re.compile(reg["Regex"], re.UNICODE).search(text): <del> if re.compile(reg["Regex"]).match(text):
# module: What.regex_identifier class RegexIdentifier: def check(self, text): <0> matches = [] <1> for reg in self.regexes: <2> if re.compile(reg["Regex"]).match(text): <3> matches.append(reg) <4> return matches <5>
===========unchanged ref 0=========== at: What.regex_identifier.RegexIdentifier.__init__ self.regexes = yaml.load(data, Loader=yaml.FullLoader) at: re UNICODE = RegexFlag.UNICODE compile(pattern: AnyStr, flags: _FlagsType=...) -> Pattern[AnyStr] compile(pattern: Pattern[AnyStr], flags: _FlagsType=...) -> Pattern[AnyStr] at: typing.Pattern flags: int groupindex: Mapping[str, int] groups: int pattern: AnyStr search(string: AnyStr, pos: int=..., endpos: int=...) -> Optional[Match[AnyStr]]
What.what/main
Modified
bee-san~pyWhat
5be82a1292f36fda72c3d3a801899c64c005ac46
Done for the day
<0>:<add> """ <add> What - Identify what something is.\n <add> Made by Bee https://twitter.com/bee_sec_san <add> https://github.com/bee-san\n <add> <add> Examples: <add> <add> * what "HTB{this is a flag}" <add> <add> * what "0x52908400098527886E0F7030069857D2E4169EE7" <add> <add> <add> """ <1>:<add> print("This is a " + r.check(text_input)[0]["Name"]) <del> print("This is a " + r.check(kwargs["text"])[0]["Name"])
# module: What.what @click.command() + # @click.option('-t', '--text', help="The text you want to identify.", required=True) - @click.option('-t', '--text', help="The text you want to identify.", required=True) + @click.argument('text_input', required=True) + def main(text_input): - def main(**kwargs): <0> r = regex_identifier.RegexIdentifier() <1> print("This is a " + r.check(kwargs["text"])[0]["Name"]) <2>
===========unchanged ref 0=========== at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction ===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: def check(self, text): matches = [] for reg in self.regexes: + if re.compile(reg["Regex"], re.UNICODE).search(text): - if re.compile(reg["Regex"]).match(text): matches.append(reg) return matches
What.what/main
Modified
bee-san~pyWhat
bd8cd711787a26df078b11d50982760d4325296e
regex in string
<10>:<add> <del> <13>:<add> <add> what_obj = What_Object() <add> identified_output = what_obj.what_is_this(text_input) <add> <add> print(identified_output) <del> r = regex_identifier.RegexIdentifier() <14>:<del> print("This is a " + r.check(text_input)[0]["Name"])
# module: What.what + @click.command() # @click.option('-t', '--text', help="The text you want to identify.", required=True) + @click.argument("text_input", required=True) - @click.argument('text_input', required=True) def main(text_input): <0> """ <1> What - Identify what something is.\n <2> Made by Bee https://twitter.com/bee_sec_san <3> https://github.com/bee-san\n <4> <5> Examples: <6> <7> * what "HTB{this is a flag}" <8> <9> * what "0x52908400098527886E0F7030069857D2E4169EE7" <10> <11> <12> """ <13> r = regex_identifier.RegexIdentifier() <14> print("This is a " + r.check(text_input)[0]["Name"]) <15>
===========unchanged ref 0=========== at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction
What.regex_identifier/RegexIdentifier.check
Modified
bee-san~pyWhat
bd8cd711787a26df078b11d50982760d4325296e
regex in string
<2>:<add> matched_regex = re.compile(reg["Regex"], re.UNICODE).search(text) <del> if re.compile(reg["Regex"], re.UNICODE).search(text): <3>:<add> if matched_regex: <add> matches.append({"Matched": matched_regex.group(), "Regex Pattern": reg}) <del> matches.append(reg)
# module: What.regex_identifier + class RegexIdentifier: def check(self, text): <0> matches = [] <1> for reg in self.regexes: <2> if re.compile(reg["Regex"], re.UNICODE).search(text): <3> matches.append(reg) <4> return matches <5>
===========unchanged ref 0=========== at: What.regex_identifier.RegexIdentifier.__init__ data = myfile.read() at: re UNICODE = RegexFlag.UNICODE compile(pattern: AnyStr, flags: _FlagsType=...) -> Pattern[AnyStr] compile(pattern: Pattern[AnyStr], flags: _FlagsType=...) -> Pattern[AnyStr] at: typing.Pattern flags: int groupindex: Mapping[str, int] groups: int pattern: AnyStr search(string: AnyStr, pos: int=..., endpos: int=...) -> Optional[Match[AnyStr]] at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: What.what - - class What: - def __init__(self): - self.id = identifier - ===========changed ref 1=========== # module: What.what + + + class What_Object: + def __init__(self): + self.id = identifier.Identifier() + ===========changed ref 2=========== # module: What.what + + + class What_Object: + + def what_is_this(self, text: str) -> dict: + """ + Returns a Python dictionary of everything that has been identified + """ + return self.id.identify(text) + ===========changed ref 3=========== # module: What.what - - def what_is_this(text: str) -> dict: if __name__ == "__main__": + main() - main() ===========changed ref 4=========== # module: What.what + @click.command() # @click.option('-t', '--text', help="The text you want to identify.", required=True) + @click.argument("text_input", required=True) - @click.argument('text_input', required=True) def main(text_input): """ What - Identify what something is.\n Made by Bee https://twitter.com/bee_sec_san https://github.com/bee-san\n Examples: * what "HTB{this is a flag}" * what "0x52908400098527886E0F7030069857D2E4169EE7" + - """ + + what_obj = What_Object() + identified_output = what_obj.what_is_this(text_input) + + print(identified_output) - r = regex_identifier.RegexIdentifier() - print("This is a " + r.check(text_input)[0]["Name"])
What.what/main
Modified
bee-san~pyWhat
fa19a7428ef1748c2dd99e7e31d5d2a91d3e30b3
Added pritning module
<16>:<add> <add> p = printer.Printing() <del> <17>:<add> p.pretty_print(identified_output) <del> print(identified_output)
# module: What.what @click.command() - # @click.option('-t', '--text', help="The text you want to identify.", required=True) @click.argument("text_input", required=True) def main(text_input): <0> """ <1> What - Identify what something is.\n <2> Made by Bee https://twitter.com/bee_sec_san <3> https://github.com/bee-san\n <4> <5> Examples: <6> <7> * what "HTB{this is a flag}" <8> <9> * what "0x52908400098527886E0F7030069857D2E4169EE7" <10> <11> <12> """ <13> <14> what_obj = What_Object() <15> identified_output = what_obj.what_is_this(text_input) <16> <17> print(identified_output) <18>
===========unchanged ref 0=========== at: What.what What_Object() at: What.what.What_Object what_is_this(text: str) -> dict at: click.decorators command(name: Optional[str]=..., cls: Optional[Type[Command]]=..., context_settings: Optional[Dict[Any, Any]]=..., help: Optional[str]=..., epilog: Optional[str]=..., short_help: Optional[str]=..., options_metavar: str=..., add_help_option: bool=..., hidden: bool=..., deprecated: bool=...) -> Callable[[Callable[..., Any]], Command] argument(*param_decls: Text, cls: Type[Argument]=..., required: Optional[bool]=..., type: Optional[_ConvertibleType]=..., default: Optional[Any]=..., callback: Optional[_Callback]=..., nargs: Optional[int]=..., metavar: Optional[str]=..., expose_value: bool=..., is_eager: bool=..., envvar: Optional[Union[str, List[str]]]=..., autocompletion: Optional[Callable[[Any, List[str], str], List[Union[str, Tuple[str, str]]]]]=...) -> _IdentityFunction at: printer Printing()
What.languageDetector/LanguageDetector.detect_what_lang
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<0>:<add> return detect_langs(text) <del> return detect(text)
# module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): <0> return detect(text) <1>
===========changed ref 0=========== + # module: tests.test_click + + ===========changed ref 1=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output +
tests.test_regex_identifier/test_regex_successfully_parses
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<1>:<add> print(r.regexes)
# module: tests.test_regex_identifier def test_regex_successfully_parses(): <0> r = regex_identifier.RegexIdentifier() <1> assert "Name" in r.regexes[0] <2>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier.__init__ self.regexes = yaml.load(data, Loader=yaml.FullLoader) ===========changed ref 0=========== + # module: tests.test_click + + ===========changed ref 1=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 2=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 3=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_regex_runs
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] <del> assert "Dogecoin" in res[0]["Name"]
# module: tests.test_regex_identifier def test_regex_runs(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <2> assert "Dogecoin" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== + # module: tests.test_click + + ===========changed ref 2=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 3=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 4=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_url
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] <del> assert "Uniform Resource Locator (URL)" in res[0]["Name"]
# module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("tryhackme.com") <2> assert "Uniform Resource Locator (URL)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator skipif: _SkipifMarkDecorator xfail: _XfailMarkDecorator parametrize: _ParametrizeMarkDecorator usefixtures: _UsefixturesMarkDecorator filterwarnings: _FilterwarningsMarkDecorator ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 2=========== + # module: tests.test_click + + ===========changed ref 3=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 4=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 5=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_https
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] <del> assert "Uniform Resource Locator (URL)" in res[0]["Name"]
# module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("https://tryhackme.com") <2> assert "Uniform Resource Locator (URL)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 3=========== + # module: tests.test_click + + ===========changed ref 4=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 5=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 6=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_ip
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] <del> assert "Uniform Resource Locator (URL)" in res[0]["Name"]
# module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("http://10.1.1.1") <2> assert "Uniform Resource Locator (URL)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 4=========== + # module: tests.test_click + + ===========changed ref 5=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 6=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 7=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_ip2
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] <del> assert "Uniform Resource Locator (URL)" in res[0]["Name"]
# module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("http://0.0.0.0") <2> assert "Uniform Resource Locator (URL)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 4=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 5=========== + # module: tests.test_click + + ===========changed ref 6=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 7=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 8=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_internationak_url
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] <del> assert "Uniform Resource Locator (URL)" in res[0]["Name"]
# module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("http://папироска.рф") <2> assert "Uniform Resource Locator (URL)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) at: _pytest.mark.structures MARK_GEN = MarkGenerator(_ispytest=True) at: _pytest.mark.structures.MarkGenerator skip: _SkipMarkDecorator ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 6=========== + # module: tests.test_click + + ===========changed ref 7=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 8=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 9=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_ctf_flag
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] <del> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("thm{hello}") <2> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 1=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 7=========== + # module: tests.test_click + + ===========changed ref 8=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 9=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 10=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_ctf_flag_uppercase
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] <del> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag_uppercase(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("FLAG{hello}") <2> assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 1=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 2=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 8=========== + # module: tests.test_click + + ===========changed ref 9=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 10=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 11=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_ethereum
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] <del> assert "Ethereum Wallet" in res[0]["Name"]
# module: tests.test_regex_identifier def test_ethereum(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") <2> assert "Ethereum Wallet" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 1=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 3=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 9=========== + # module: tests.test_click + + ===========changed ref 10=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 11=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 12=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_regex_identifier/test_bitcoin
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] <del> assert "Bitcoin" in res[0]["Name"]
# module: tests.test_regex_identifier def test_bitcoin(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") <2> assert "Bitcoin" in res[0]["Name"] <3>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 1=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 2=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 3=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 10=========== + # module: tests.test_click + + ===========changed ref 11=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 12=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 13=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_language_identifier/test_regex_successfully_parses
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert result[0].lang == "en" <del> assert result == "en"
# module: tests.test_language_identifier def test_regex_successfully_parses(): <0> r = languageDetector.LanguageDetector() <1> result = r.detect_what_lang("Hello my name is Bee!") <2> assert result == "en" <3>
===========unchanged ref 0=========== at: What.languageDetector LanguageDetector() at: What.languageDetector.LanguageDetector detect_what_lang(text) ===========changed ref 0=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 1=========== + # module: tests.test_click + + ===========changed ref 2=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 3=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 4=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 10=========== # module: tests.test_regex_identifier def test_bitcoin(): r = regex_identifier.RegexIdentifier() res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") + assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] - assert "Bitcoin" in res[0]["Name"] ===========changed ref 11=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 12=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 13=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 14=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_language_identifier/test_regex_successfully_parses_german
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert result[0].lang == "de" <del> assert result == "de"
# module: tests.test_language_identifier def test_regex_successfully_parses_german(): <0> r = languageDetector.LanguageDetector() <1> result = r.detect_what_lang("Ich spreche Deutusche") <2> assert result == "de" <3>
===========unchanged ref 0=========== at: What.languageDetector LanguageDetector() at: What.languageDetector.LanguageDetector detect_what_lang(text) ===========changed ref 0=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 1=========== # module: tests.test_language_identifier def test_regex_successfully_parses(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Hello my name is Bee!") + assert result[0].lang == "en" - assert result == "en" ===========changed ref 2=========== + # module: tests.test_click + + ===========changed ref 3=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 4=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 5=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 10=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 11=========== # module: tests.test_regex_identifier def test_bitcoin(): r = regex_identifier.RegexIdentifier() res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") + assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] - assert "Bitcoin" in res[0]["Name"] ===========changed ref 12=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 13=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 14=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 15=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_identifier/test_identifier_works
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "Dogecoin Wallet Address" in out["Regexes"][0]["Regex Pattern"]["Name"] <del> assert "Dogecoin" in out["Regexes"][0]["Name"]
# module: tests.test_identifier def test_identifier_works(): <0> r = identifier.Identifier() <1> out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") <2> assert "Dogecoin" in out["Regexes"][0]["Name"] <3>
===========unchanged ref 0=========== at: What.identifier Identifier() at: What.identifier.Identifier identify(text: str) -> dict ===========changed ref 0=========== + # module: tests.test_click + + ===========changed ref 1=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 2=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 3=========== # module: tests.test_language_identifier def test_regex_successfully_parses(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Hello my name is Bee!") + assert result[0].lang == "en" - assert result == "en" ===========changed ref 4=========== # module: tests.test_language_identifier def test_regex_successfully_parses_german(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Ich spreche Deutusche") + assert result[0].lang == "de" - assert result == "de" ===========changed ref 5=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 6=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 10=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 11=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 12=========== # module: tests.test_regex_identifier def test_bitcoin(): r = regex_identifier.RegexIdentifier() res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") + assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] - assert "Bitcoin" in res[0]["Name"] ===========changed ref 13=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 14=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 15=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 16=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
tests.test_identifier/test_identifier_spanish
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<2>:<add> assert "es" in out["Language"][0].lang <del> assert "es" in out["Language"]
# module: tests.test_identifier def test_identifier_spanish(): <0> r = identifier.Identifier() <1> out = r.identify("Me gustan los bombos y la musica ") <2> assert "es" in out["Language"] <3>
===========unchanged ref 0=========== at: What.identifier Identifier() at: What.identifier.Identifier identify(text: str) -> dict ===========changed ref 0=========== # module: tests.test_identifier def test_identifier_works(): r = identifier.Identifier() out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in out["Regexes"][0]["Regex Pattern"]["Name"] - assert "Dogecoin" in out["Regexes"][0]["Name"] ===========changed ref 1=========== + # module: tests.test_click + + ===========changed ref 2=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 3=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 4=========== # module: tests.test_language_identifier def test_regex_successfully_parses(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Hello my name is Bee!") + assert result[0].lang == "en" - assert result == "en" ===========changed ref 5=========== # module: tests.test_language_identifier def test_regex_successfully_parses_german(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Ich spreche Deutusche") + assert result[0].lang == "de" - assert result == "de" ===========changed ref 6=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 10=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 11=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 12=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 13=========== # module: tests.test_regex_identifier def test_bitcoin(): r = regex_identifier.RegexIdentifier() res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") + assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] - assert "Bitcoin" in res[0]["Name"] ===========changed ref 14=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 15=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 16=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 17=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
d17b860203bf7395e36089aadd3bc0d5024e7697
Tests work, fancy printing
<0>:<add> console = Console(highlight=False) <add> <add> languages = text["Language"] <add> <add> # calculate probability of each language <add> prob_language = "" <add> for i in languages: <add> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <add> <1>:<add> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <del> to_out += f"Possible language: {text['Language']}.\n" <3>:<add> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <add> table = Table(show_header=True, header_style="bold #D7Afff") <add> table.add_column("Matched Text") <add> table.add_column("Identified as") <add> table.add_column("Description") <del> to_out += f"Possible Identification:\n" <5>:<add> table.add_row( <add> i["Matched"],
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> to_out = "" <1> to_out += f"Possible language: {text['Language']}.\n" <2> if text["Regexes"]: <3> to_out += f"Possible Identification:\n" <4> for i in text["Regexes"]: <5> to_out += f'"{i["Matched"]}" is possibly {i["Regex Pattern"]["Name"]} - {i["Regex Pattern"]["Description"]}\n' <6> print(to_out) <7>
===========changed ref 0=========== + # module: tests.test_click + + ===========changed ref 1=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + return detect_langs(text) - return detect(text) ===========changed ref 2=========== # module: tests.test_regex_identifier def test_regex_successfully_parses(): r = regex_identifier.RegexIdentifier() + print(r.regexes) assert "Name" in r.regexes[0] ===========changed ref 3=========== # module: tests.test_language_identifier def test_regex_successfully_parses(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Hello my name is Bee!") + assert result[0].lang == "en" - assert result == "en" ===========changed ref 4=========== # module: tests.test_language_identifier def test_regex_successfully_parses_german(): r = languageDetector.LanguageDetector() result = r.detect_what_lang("Ich spreche Deutusche") + assert result[0].lang == "de" - assert result == "de" ===========changed ref 5=========== # module: tests.test_identifier def test_identifier_spanish(): r = identifier.Identifier() out = r.identify("Me gustan los bombos y la musica ") + assert "es" in out["Language"][0].lang - assert "es" in out["Language"] ===========changed ref 6=========== + # module: tests.test_click + + def test_hello_world(): + runner = CliRunner() + result = runner.invoke(main, ['1981328391THM{this is a flag}asdasda']) + assert result.exit_code == 0 + assert "THM{" in result.output + ===========changed ref 7=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_url(): r = regex_identifier.RegexIdentifier() res = r.check("tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 8=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_https(): r = regex_identifier.RegexIdentifier() res = r.check("https://tryhackme.com") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 9=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") - # @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip2(): r = regex_identifier.RegexIdentifier() res = r.check("http://0.0.0.0") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 10=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_ip(): r = regex_identifier.RegexIdentifier() res = r.check("http://10.1.1.1") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 11=========== # module: tests.test_regex_identifier def test_ctf_flag_uppercase(): r = regex_identifier.RegexIdentifier() res = r.check("FLAG{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 12=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") + assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] - assert "Flag from Capture The Flag (CyberSecurity)" in res[0]["Name"] ===========changed ref 13=========== # module: tests.test_regex_identifier def test_bitcoin(): r = regex_identifier.RegexIdentifier() res = r.check("1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY") + assert "Bitcoin" in res[0]["Regex Pattern"]["Name"] - assert "Bitcoin" in res[0]["Name"] ===========changed ref 14=========== # module: tests.test_regex_identifier def test_regex_runs(): r = regex_identifier.RegexIdentifier() res = r.check("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in res[0]["Regex Pattern"]["Name"] - assert "Dogecoin" in res[0]["Name"] ===========changed ref 15=========== # module: tests.test_regex_identifier def test_ethereum(): r = regex_identifier.RegexIdentifier() res = r.check("0x52908400098527886E0F7030069857D2E4169EE7") + assert "Ethereum Wallet" in res[0]["Regex Pattern"]["Name"] - assert "Ethereum Wallet" in res[0]["Name"] ===========changed ref 16=========== # module: tests.test_regex_identifier + @pytest.mark.skip(reason="Fails Regex due to http://") def test_internationak_url(): r = regex_identifier.RegexIdentifier() res = r.check("http://папироска.рф") + assert "Uniform Resource Locator (URL)" in res[0]["Regex Pattern"]["Name"] - assert "Uniform Resource Locator (URL)" in res[0]["Name"] ===========changed ref 17=========== # module: tests.test_identifier def test_identifier_works(): r = identifier.Identifier() out = r.identify("DANHz6EQVoWyZ9rER56DwTXHWUxfkv9k2o") + assert "Dogecoin Wallet Address" in out["Regexes"][0]["Regex Pattern"]["Name"] - assert "Dogecoin" in out["Regexes"][0]["Name"] ===========changed ref 18=========== # module: What.__main__ if __name__ == "__main__": major = sys.version_info[0] minor = sys.version_info[1] python_version = ( str(sys.version_info[0]) + "." + str(sys.version_info[1]) + "." + str(sys.version_info[2]) ) if major != 3 or (major == 3 and minor < 7): print( f"Name That Hash requires Python 3.7+, you are using {python_version}. Please install a higher Python version." ) sys.exit(1) + from What import what - import what what.main()
What.regex_identifier/RegexIdentifier.check
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<2>:<add> matched_regex = re.findall(reg["Regex"], text, re.UNICODE) <del> matched_regex = re.compile(reg["Regex"], re.UNICODE).search(text) <3>:<add> <4>:<add> for i in matched_regex: <add> matches.append({"Matched": i, "Regex Pattern": reg}) <del> matches.append({"Matched": matched_regex.group(), "Regex Pattern": reg})
# module: What.regex_identifier class RegexIdentifier: def check(self, text): <0> matches = [] <1> for reg in self.regexes: <2> matched_regex = re.compile(reg["Regex"], re.UNICODE).search(text) <3> if matched_regex: <4> matches.append({"Matched": matched_regex.group(), "Regex Pattern": reg}) <5> return matches <6>
===========unchanged ref 0=========== at: What.regex_identifier.RegexIdentifier.__init__ self.regexes = yaml.load(data, Loader=yaml.FullLoader) at: re UNICODE = RegexFlag.UNICODE findall(pattern: Pattern[AnyStr], string: AnyStr, flags: _FlagsType=...) -> List[Any] findall(pattern: AnyStr, string: AnyStr, flags: _FlagsType=...) -> List[Any] ===========changed ref 0=========== # module: scripts.get_file_sigs r = requests.get( "http://en.wikipedia.org/w/index.php?title=" + "List_of_file_signatures&action=raw" ) wt = wtp.parse(r.text) # prints first 3 items of json, delete [0:3] to print all. to_iter = {"root": wt.tables[0].data()} to_iter = to_iter["root"] to_dump = [] populars = set(["23 21"]) for i in range(1, len(to_iter)): to_insert = {} + to_insert["Hexadecimal File Signature"] = cleanhtml(to_iter[i][0]).replace(" ", "") - to_insert["Hexadecimal File Signature"] = cleanhtml(to_iter[i][0]) check_iso = cleanhtml(to_iter[i][1]) if len(set(check_iso)) <= 2: to_insert["ISO 8859-1"] = None else: to_insert["ISO 8859-1"] = check_iso check = to_iter[i][3] if check == "": to_insert["Filename Extension"] = None else: to_insert["Filename Extension"] = cleanhtml(check) des = to_iter[i][4] if "url" in des: splits = des.split("=") if "|" in splits[1]: # https://wiki.wireshark.org/Development/LibpcapFileFormat#Global_Header|title split_more = splits[1].split("|") print(split_more) to_insert["URL"] = split_more[0] else: to_insert["URL"] = splits[1] to_insert["Description"] = cleanhtml(splits[0]) else: to</s> ===========changed ref 1=========== # module: scripts.get_file_sigs # offset: 1 <s> splits[1] to_insert["Description"] = cleanhtml(splits[0]) else: to_insert["Description"] = cleanhtml(to_iter[i][4]) if to_insert["Hexadecimal File Signature"] in populars: to_insert["Popular"] = 1 else: to_insert["Popular"] = 0 to_dump.append(to_insert) + with open("file_signatures.yaml", "w") as ym: - with open('file_signatures.yaml', 'w') as ym: yaml.dump(to_dump, ym, allow_unicode=True) # https://en.wikipedia.org/api/rest_v1/page/html/List_of_file_signatures """ { "root": [ [ "[[Hexadecimal|Hex]] signature", "ISO 8859-1", "[[Offset (computer science)|Offset]]", "[[Filename extension]]", "Description" ], [ "<pre>23 21</pre>", "{{show file signature|23 21}}", "0", "", "Script or data to be passed to the program following the [[Shebang (Unix)|shebang]] (#!)" ], [ "<pre>a1 b2 c3 d4</pre>\n<pre>d4 c3 b2 a1</pre>", "{{show file signature|a1 b2 c3 d4}}\n{{show file signature|d4 c3 b2 a1}}", "0", "pcap", "Libpcap File Format<ref>{{cite web |url=https://wiki.w</s> ===========changed ref 2=========== # module: scripts.get_file_sigs # offset: 2 <s>ark.org/Development/LibpcapFileFormat#Global_Header|title=Libpcap File Format|access-date=2018-06-19}}</ref>" ] ] } """
What.languageDetector/LanguageDetector.detect_what_lang
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<0>:<add> try: <add> return detect_langs(text) <del> return detect_langs(text) <1>:<add> except langdetect.lang_detect_exception.LangDetectException as e: <add> return None
# module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): <0> return detect_langs(text) <1>
===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: + + def clean_text(self, text): + return text.replace("\n", "").replace("\t", "") + ===========changed ref 1=========== # module: What.regex_identifier class RegexIdentifier: def check(self, text): matches = [] for reg in self.regexes: + matched_regex = re.findall(reg["Regex"], text, re.UNICODE) - matched_regex = re.compile(reg["Regex"], re.UNICODE).search(text) + if matched_regex: + for i in matched_regex: + matches.append({"Matched": i, "Regex Pattern": reg}) - matches.append({"Matched": matched_regex.group(), "Regex Pattern": reg}) return matches ===========changed ref 2=========== # module: scripts.get_file_sigs r = requests.get( "http://en.wikipedia.org/w/index.php?title=" + "List_of_file_signatures&action=raw" ) wt = wtp.parse(r.text) # prints first 3 items of json, delete [0:3] to print all. to_iter = {"root": wt.tables[0].data()} to_iter = to_iter["root"] to_dump = [] populars = set(["23 21"]) for i in range(1, len(to_iter)): to_insert = {} + to_insert["Hexadecimal File Signature"] = cleanhtml(to_iter[i][0]).replace(" ", "") - to_insert["Hexadecimal File Signature"] = cleanhtml(to_iter[i][0]) check_iso = cleanhtml(to_iter[i][1]) if len(set(check_iso)) <= 2: to_insert["ISO 8859-1"] = None else: to_insert["ISO 8859-1"] = check_iso check = to_iter[i][3] if check == "": to_insert["Filename Extension"] = None else: to_insert["Filename Extension"] = cleanhtml(check) des = to_iter[i][4] if "url" in des: splits = des.split("=") if "|" in splits[1]: # https://wiki.wireshark.org/Development/LibpcapFileFormat#Global_Header|title split_more = splits[1].split("|") print(split_more) to_insert["URL"] = split_more[0] else: to_insert["URL"] = splits[1] to_insert["Description"] = cleanhtml(splits[0]) else: to</s> ===========changed ref 3=========== # module: scripts.get_file_sigs # offset: 1 <s> splits[1] to_insert["Description"] = cleanhtml(splits[0]) else: to_insert["Description"] = cleanhtml(to_iter[i][4]) if to_insert["Hexadecimal File Signature"] in populars: to_insert["Popular"] = 1 else: to_insert["Popular"] = 0 to_dump.append(to_insert) + with open("file_signatures.yaml", "w") as ym: - with open('file_signatures.yaml', 'w') as ym: yaml.dump(to_dump, ym, allow_unicode=True) # https://en.wikipedia.org/api/rest_v1/page/html/List_of_file_signatures """ { "root": [ [ "[[Hexadecimal|Hex]] signature", "ISO 8859-1", "[[Offset (computer science)|Offset]]", "[[Filename extension]]", "Description" ], [ "<pre>23 21</pre>", "{{show file signature|23 21}}", "0", "", "Script or data to be passed to the program following the [[Shebang (Unix)|shebang]] (#!)" ], [ "<pre>a1 b2 c3 d4</pre>\n<pre>d4 c3 b2 a1</pre>", "{{show file signature|a1 b2 c3 d4}}\n{{show file signature|d4 c3 b2 a1}}", "0", "pcap", "Libpcap File Format<ref>{{cite web |url=https://wiki.w</s> ===========changed ref 4=========== # module: scripts.get_file_sigs # offset: 2 <s>ark.org/Development/LibpcapFileFormat#Global_Header|title=Libpcap File Format|access-date=2018-06-19}}</ref>" ] ] } """
What.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<0>:<add> with open("file_signatures.yaml", "r") as myfile: <add> data = myfile.read() <add> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <del> pass
# module: What.magic_numbers class FileSignatures: def __init__(self): <0> pass <1>
===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: + + def clean_text(self, text): + return text.replace("\n", "").replace("\t", "") + ===========changed ref 1=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + try: + return detect_langs(text) - return detect_langs(text) + except langdetect.lang_detect_exception.LangDetectException as e: + return None ===========changed ref 2=========== # module: tests.test_click + + def test_file_fixture8(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 3=========== # module: tests.test_click + + def test_file_fixture13(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Bitcoin', str(result.output)) + ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture12(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 5=========== # module: tests.test_click + + def test_file_fixture3(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm', str(result.output)) + ===========changed ref 6=========== # module: tests.test_click + + def test_file_fixture10(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('dogechain', str(result.output)) + ===========changed ref 7=========== # module: tests.test_click + + def test_file_fixture9(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('etherscan', str(result.output)) + ===========changed ref 8=========== # module: tests.test_click + + def test_file_fixture7(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{"', str(result.output)) + ===========changed ref 9=========== # module: tests.test_click + + def test_file_fixture5(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{', str(result.output)) + ===========changed ref 10=========== # module: tests.test_click + + def test_file_fixture4(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Ethereum', str(result.output)) + ===========changed ref 11=========== # module: tests.test_click + + def test_file_fixture11(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Dogecoin', str(result.output)) + ===========changed ref 12=========== # module: tests.test_click + + def test_arg_parsing2(): + runner = CliRunner() + result = runner.invoke(main, ["http://10.1.1.1"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 13=========== # module: tests.test_click + + def test_file_fixture2(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 14=========== # module: tests.test_click + + def test_arg_parsing(): + runner = CliRunner() + result = runner.invoke(main, ["1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 15=========== # module: tests.test_click + + def test_file_fixture(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert re.findall('thm', str(result.output)) + assert re.findall('Ethereum', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 16=========== # module: What.regex_identifier class RegexIdentifier: def check(self, text): matches = [] for reg in self.regexes: + matched_regex = re.findall(reg["Regex"], text, re.UNICODE) - matched_regex = re.compile(reg["Regex"], re.UNICODE).search(text) + if matched_regex: + for i in matched_regex: + matches.append({"Matched": i, "Regex Pattern": reg}) - matches.append({"Matched": matched_regex.group(), "Regex Pattern": reg}) return matches
What.identifier/Identifier.__init__
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<2>:<add> self.file_sig = FileSignatures()
# module: What.identifier class Identifier: def __init__(self): <0> self.regex_id = RegexIdentifier() <1> self.lang_detect = LanguageDetector() <2>
===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: + + def clean_text(self, text): + return text.replace("\n", "").replace("\t", "") + ===========changed ref 1=========== # module: What.magic_numbers class FileSignatures: + + def open_file_loc(self, file_loc): + with open(file_loc, "r") as myfile: + r = myfile.read() + return r + ===========changed ref 2=========== # module: What.magic_numbers class FileSignatures: - - def open_file(self): - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - ===========changed ref 3=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + try: + return detect_langs(text) - return detect_langs(text) + except langdetect.lang_detect_exception.LangDetectException as e: + return None ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture8(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 5=========== # module: tests.test_click + + def test_file_fixture13(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Bitcoin', str(result.output)) + ===========changed ref 6=========== # module: tests.test_click + + def test_file_fixture12(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 7=========== # module: tests.test_click + + def test_file_fixture3(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm', str(result.output)) + ===========changed ref 8=========== # module: What.magic_numbers class FileSignatures: def __init__(self): + with open("file_signatures.yaml", "r") as myfile: + data = myfile.read() + self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) - pass ===========changed ref 9=========== # module: tests.test_click + + def test_file_fixture10(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('dogechain', str(result.output)) + ===========changed ref 10=========== # module: tests.test_click + + def test_file_fixture9(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('etherscan', str(result.output)) + ===========changed ref 11=========== # module: tests.test_click + + def test_file_fixture7(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{"', str(result.output)) + ===========changed ref 12=========== # module: tests.test_click + + def test_file_fixture5(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{', str(result.output)) + ===========changed ref 13=========== # module: tests.test_click + + def test_file_fixture4(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Ethereum', str(result.output)) + ===========changed ref 14=========== # module: tests.test_click + + def test_file_fixture11(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Dogecoin', str(result.output)) + ===========changed ref 15=========== # module: tests.test_click + + def test_arg_parsing2(): + runner = CliRunner() + result = runner.invoke(main, ["http://10.1.1.1"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 16=========== # module: What.magic_numbers class FileSignatures: + + def open_binary_scan_magic_nums(self, file_loc): + with open(file_loc, "rb") as myfile: + header = myfile.read(24) + header = str(binascii.hexlify(header))[2:-1] + return self.check_magic_nums(header) + ===========changed ref 17=========== # module: tests.test_click + + def test_file_fixture2(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 18=========== # module: tests.test_click + + def test_arg_parsing(): + runner = CliRunner() + result = runner.invoke(main, ["1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 19=========== # module: What.magic_numbers - - - # 4740001b0000b00d0001c100000001efff3690e23dffffff - - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - print(header) - ===========changed ref 20=========== # module: tests.test_click + + def test_file_fixture(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert re.findall('thm', str(result.output)) + assert re.findall('Ethereum', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 21=========== # module: What.magic_numbers class FileSignatures: + + def check_magic_nums(self, text): + for i in self.file_sigs: + to_check = i["Hexadecimal File Signature"] + # Say we have "16 23 21", the [0, len()] prevents it from executing + # as magic numbers only count at the start of the file. + if to_check == text[0 : len(to_check)]: + # A file can only be one type + return i + return None +
What.identifier/Identifier.identify
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<1>:<add> <add> magic_numbers = None <add> if self.file_exists(text): <add> magic_numbers = self.file_sig.open_binary_scan_magic_nums(text) <add> text = self.file_sig.open_file_loc(text) <add> identify_obj["File Signatures"] = magic_numbers <add> <add> if not magic_numbers: <add> # If file doesn't exist, check to see if the inputted text is <add> # a file in hex format <add> identify_obj["File Signatures"] = self.file_sig.check_magic_nums(text) <add>
# module: What.identifier class Identifier: def identify(self, text: str) -> dict: <0> identify_obj = {} <1> identify_obj["Language"] = self.lang_detect.detect_what_lang(text) <2> identify_obj["Regexes"] = self.regex_id.check(text) <3> <4> return identify_obj <5>
===========unchanged ref 0=========== at: What.languageDetector LanguageDetector() at: What.magic_numbers FileSignatures() at: What.regex_identifier RegexIdentifier() ===========changed ref 0=========== # module: What.identifier class Identifier: def __init__(self): self.regex_id = RegexIdentifier() self.lang_detect = LanguageDetector() + self.file_sig = FileSignatures() ===========changed ref 1=========== # module: What.regex_identifier class RegexIdentifier: + + def clean_text(self, text): + return text.replace("\n", "").replace("\t", "") + ===========changed ref 2=========== # module: What.magic_numbers class FileSignatures: + + def open_file_loc(self, file_loc): + with open(file_loc, "r") as myfile: + r = myfile.read() + return r + ===========changed ref 3=========== # module: What.magic_numbers class FileSignatures: - - def open_file(self): - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - ===========changed ref 4=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + try: + return detect_langs(text) - return detect_langs(text) + except langdetect.lang_detect_exception.LangDetectException as e: + return None ===========changed ref 5=========== # module: tests.test_click + + def test_file_fixture8(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 6=========== # module: tests.test_click + + def test_file_fixture13(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Bitcoin', str(result.output)) + ===========changed ref 7=========== # module: tests.test_click + + def test_file_fixture12(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 8=========== # module: tests.test_click + + def test_file_fixture3(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm', str(result.output)) + ===========changed ref 9=========== # module: What.magic_numbers class FileSignatures: def __init__(self): + with open("file_signatures.yaml", "r") as myfile: + data = myfile.read() + self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) - pass ===========changed ref 10=========== # module: tests.test_click + + def test_file_fixture10(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('dogechain', str(result.output)) + ===========changed ref 11=========== # module: tests.test_click + + def test_file_fixture9(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('etherscan', str(result.output)) + ===========changed ref 12=========== # module: tests.test_click + + def test_file_fixture7(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{"', str(result.output)) + ===========changed ref 13=========== # module: tests.test_click + + def test_file_fixture5(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{', str(result.output)) + ===========changed ref 14=========== # module: tests.test_click + + def test_file_fixture4(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Ethereum', str(result.output)) + ===========changed ref 15=========== # module: tests.test_click + + def test_file_fixture11(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Dogecoin', str(result.output)) + ===========changed ref 16=========== # module: tests.test_click + + def test_arg_parsing2(): + runner = CliRunner() + result = runner.invoke(main, ["http://10.1.1.1"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 17=========== # module: What.magic_numbers class FileSignatures: + + def open_binary_scan_magic_nums(self, file_loc): + with open(file_loc, "rb") as myfile: + header = myfile.read(24) + header = str(binascii.hexlify(header))[2:-1] + return self.check_magic_nums(header) + ===========changed ref 18=========== # module: tests.test_click + + def test_file_fixture2(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 19=========== # module: tests.test_click + + def test_arg_parsing(): + runner = CliRunner() + result = runner.invoke(main, ["1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 20=========== # module: What.magic_numbers - - - # 4740001b0000b00d0001c100000001efff3690e23dffffff - - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - print(header) - ===========changed ref 21=========== # module: tests.test_click + + def test_file_fixture(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert re.findall('thm', str(result.output)) + assert re.findall('Ethereum', str(result.output)) + assert "Dogecoin" in result.output +
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
3a7c0ec62c197dda0a6bfbb4da1a52b2361e8571
more regex
<6>:<add> if languages: <add> for i in languages: <del> for i in languages: <7>:<add> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <del> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <11>:<add> <add> if text["File Signatures"]: <add> to_out += "\n" <add> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <add> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <add> to_out += "\n" <add> <13>:<add> table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) <del> table = Table(show_header=True, header_style="bold #D7Afff") <18>:<add> matched = i["Matched"] <add> name = i["Regex Pattern"]["Name"] <add>
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> for i in languages: <7> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <8> <9> to_out = "" <10> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <11> if text["Regexes"]: <12> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <13> table = Table(show_header=True, header_style="bold #D7Afff") <14> table.add_column("Matched Text") <15> table.add_column("Identified as") <16> table.add_column("Description") <17> for i in text["Regexes"]: <18> table.add_row( <19> i["Matched"], <20> i["Regex Pattern"]["Name"], <21> i["Regex Pattern"]["Description"], <22> ) <23> console.print(to_out, table) <24> return 0 <25> console.print(to_out) <26>
===========changed ref 0=========== # module: What.identifier class Identifier: + + def file_exists(self, text): + return os.path.isfile(text) + ===========changed ref 1=========== # module: What.regex_identifier class RegexIdentifier: + + def clean_text(self, text): + return text.replace("\n", "").replace("\t", "") + ===========changed ref 2=========== # module: What.magic_numbers class FileSignatures: + + def open_file_loc(self, file_loc): + with open(file_loc, "r") as myfile: + r = myfile.read() + return r + ===========changed ref 3=========== # module: What.identifier class Identifier: def __init__(self): self.regex_id = RegexIdentifier() self.lang_detect = LanguageDetector() + self.file_sig = FileSignatures() ===========changed ref 4=========== # module: What.magic_numbers class FileSignatures: - - def open_file(self): - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - ===========changed ref 5=========== # module: What.languageDetector class LanguageDetector: def detect_what_lang(self, text): + try: + return detect_langs(text) - return detect_langs(text) + except langdetect.lang_detect_exception.LangDetectException as e: + return None ===========changed ref 6=========== # module: tests.test_click + + def test_file_fixture8(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 7=========== # module: tests.test_click + + def test_file_fixture13(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Bitcoin', str(result.output)) + ===========changed ref 8=========== # module: tests.test_click + + def test_file_fixture12(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 9=========== # module: tests.test_click + + def test_file_fixture3(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm', str(result.output)) + ===========changed ref 10=========== # module: What.magic_numbers class FileSignatures: def __init__(self): + with open("file_signatures.yaml", "r") as myfile: + data = myfile.read() + self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) - pass ===========changed ref 11=========== # module: tests.test_click + + def test_file_fixture10(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('dogechain', str(result.output)) + ===========changed ref 12=========== # module: tests.test_click + + def test_file_fixture9(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('etherscan', str(result.output)) + ===========changed ref 13=========== # module: tests.test_click + + def test_file_fixture7(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{"', str(result.output)) + ===========changed ref 14=========== # module: tests.test_click + + def test_file_fixture5(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('thm{', str(result.output)) + ===========changed ref 15=========== # module: tests.test_click + + def test_file_fixture4(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Ethereum', str(result.output)) + ===========changed ref 16=========== # module: tests.test_click + + def test_file_fixture11(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Dogecoin', str(result.output)) + ===========changed ref 17=========== # module: tests.test_click + + def test_arg_parsing2(): + runner = CliRunner() + result = runner.invoke(main, ["http://10.1.1.1"]) + assert result.exit_code == 0 + assert re.findall('URL', str(result.output)) + ===========changed ref 18=========== # module: What.magic_numbers class FileSignatures: + + def open_binary_scan_magic_nums(self, file_loc): + with open(file_loc, "rb") as myfile: + header = myfile.read(24) + header = str(binascii.hexlify(header))[2:-1] + return self.check_magic_nums(header) + ===========changed ref 19=========== # module: tests.test_click + + def test_file_fixture2(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert "Dogecoin" in result.output + ===========changed ref 20=========== # module: tests.test_click + + def test_arg_parsing(): + runner = CliRunner() + result = runner.invoke(main, ["1KFHE7w8BhaENAswwryaoccDb6qcT6DbYY"]) + assert result.exit_code == 0 + assert re.findall('blockchain', str(result.output)) + ===========changed ref 21=========== # module: What.magic_numbers - - - # 4740001b0000b00d0001c100000001efff3690e23dffffff - - with open("file", "rb") as myfile: - header = myfile.read(24) - header = str(binascii.hexlify(header))[2:-1] - print(header) - ===========changed ref 22=========== # module: tests.test_click + + def test_file_fixture(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('web', str(result.output)) + assert re.findall('thm', str(result.output)) + assert re.findall('Ethereum', str(result.output)) + assert "Dogecoin" in result.output +
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
ec1edb1642658f8415113baabc61c0aa3faa6ee4
infra stuff
<11>:<add> if prob_language: <add> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <del> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n"
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <9> <10> to_out = "" <11> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <12> <13> if text["File Signatures"]: <14> to_out += "\n" <15> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <16> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <17> to_out += "\n" <18> <19> if text["Regexes"]: <20> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <21> table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) <22> table.add_column("Matched Text") <23> table.add_column("Identified as") <24> table.add_column("Description") <25> for i in text["Regexes"]: <26> matched = i["Matched"] <27> name = i["Regex Pattern"]["Name"] <28> description = self.get_crypto_links(name, matched) <29> if not description: <30> description = i["Regex Pattern"]["Description"] <31> table.add_row( </s>
===========below chunk 0=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 name, description, ) console.print(to_out, table) return 0 console.print(to_out) ===========unchanged ref 0=========== at: What.printer.Printing get_crypto_links(text, matched) ===========changed ref 0=========== # module: tests.test_click + + def test_file_fixture_discover(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Discover', str(result.output)) + ===========changed ref 1=========== # module: tests.test_click + + def test_file_fixture_master_card(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('MasterCard', str(result.output)) + ===========changed ref 2=========== # module: tests.test_click + + def test_file_fixture_visa(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Visa', str(result.output)) + ===========changed ref 3=========== # module: tests.test_click + + def test_file_fixture_master_amex(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('American Express', str(result.output)) + ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture_master_diners(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Diners Club Card', str(result.output)) +
tests.test_regex_identifier/test_ctf_flag
Modified
bee-san~pyWhat
ec1edb1642658f8415113baabc61c0aa3faa6ee4
infra stuff
<3>:<add> "TryHackMe Flag Format" in res[0]["Regex Pattern"]["Name"] <del> "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("thm{hello}") <2> assert ( <3> "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] <4> ) <5>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_click + + def test_file_fixture_discover(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Discover', str(result.output)) + ===========changed ref 1=========== # module: tests.test_click + + def test_file_fixture_master_card(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('MasterCard', str(result.output)) + ===========changed ref 2=========== # module: tests.test_click + + def test_file_fixture_visa(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Visa', str(result.output)) + ===========changed ref 3=========== # module: tests.test_click + + def test_file_fixture_master_amex(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('American Express', str(result.output)) + ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture_master_diners(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Diners Club Card', str(result.output)) + ===========changed ref 5=========== # module: What.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" to_out = "" + if prob_language: + to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" - to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" if text["Regexes"]: to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: </s> ===========changed ref 6=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s>]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) return 0 console.print(to_out)
tests.test_regex_identifier/test_ctf_flag_uppercase
Modified
bee-san~pyWhat
ec1edb1642658f8415113baabc61c0aa3faa6ee4
infra stuff
<3>:<add> "CTF Flag" in res[0]["Regex Pattern"]["Name"] <del> "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"]
# module: tests.test_regex_identifier def test_ctf_flag_uppercase(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("FLAG{hello}") <2> assert ( <3> "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] <4> ) <5>
===========unchanged ref 0=========== at: What.regex_identifier RegexIdentifier() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: tests.test_regex_identifier def test_ctf_flag(): r = regex_identifier.RegexIdentifier() res = r.check("thm{hello}") assert ( + "TryHackMe Flag Format" in res[0]["Regex Pattern"]["Name"] - "Flag from Capture The Flag (CyberSecurity)" in res[0]["Regex Pattern"]["Name"] ) ===========changed ref 1=========== # module: tests.test_click + + def test_file_fixture_discover(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Discover', str(result.output)) + ===========changed ref 2=========== # module: tests.test_click + + def test_file_fixture_master_card(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('MasterCard', str(result.output)) + ===========changed ref 3=========== # module: tests.test_click + + def test_file_fixture_visa(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Visa', str(result.output)) + ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture_master_amex(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('American Express', str(result.output)) + ===========changed ref 5=========== # module: tests.test_click + + def test_file_fixture_master_diners(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall('Diners Club Card', str(result.output)) + ===========changed ref 6=========== # module: What.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" to_out = "" + if prob_language: + to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" - to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" if text["Regexes"]: to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: </s> ===========changed ref 7=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s>]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) return 0 console.print(to_out)
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
b2ab06c6e261cea3a419bafefcbf54cc67e18c34
black
<8>:<add> prob_language += ( <add> f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <del> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <9>:<add> ) <22>:<add> table = Table( <add> show_header=True, header_style="bold #D7Afff", show_lines=True <del> table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) <23>:<add> )
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <9> <10> to_out = "" <11> if prob_language: <12> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <13> <14> if text["File Signatures"]: <15> to_out += "\n" <16> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <17> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <18> to_out += "\n" <19> <20> if text["Regexes"]: <21> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <22> table = Table(show_header=True, header_style="bold #D7Afff", show_lines=True) <23> table.add_column("Matched Text") <24> table.add_column("Identified as") <25> table.add_column("Description") <26> for i in text["Regexes"]: <27> matched = i["Matched"] <28> name = i["Regex Pattern"]["Name"] <29> description = self.get_crypto_links(name, matched) <30> if not description: <31> description = i["Regex Pattern"]["Description"] </s>
===========below chunk 0=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 matched, name, description, ) console.print(to_out, table) return 0 console.print(to_out) ===========unchanged ref 0=========== at: What.printer.Printing get_crypto_links(text, matched)
What.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
305069ca5ad237f55140e602a6ed0a01b7e75f5c
fixing ci
<0>:<add> with open("Data/regex.yaml", "r") as myfile: <del> with open("What/data.yaml", "r") as myfile:
# module: What.regex_identifier class RegexIdentifier: def __init__(self): <0> with open("What/data.yaml", "r") as myfile: <1> data = myfile.read() <2> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: io.FileIO read(self, size: int=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream)
What.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
305069ca5ad237f55140e602a6ed0a01b7e75f5c
fixing ci
<0>:<add> with open("Data/file_signatures.yaml", "r") as myfile: <del> with open("file_signatures.yaml", "r") as myfile:
# module: What.magic_numbers class FileSignatures: def __init__(self): <0> with open("file_signatures.yaml", "r") as myfile: <1> data = myfile.read() <2> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: What.regex_identifier class RegexIdentifier: def __init__(self): + with open("Data/regex.yaml", "r") as myfile: - with open("What/data.yaml", "r") as myfile: data = myfile.read() self.regexes = yaml.load(data, Loader=yaml.FullLoader)
What.printer/Printing.get_crypto_links
Modified
bee-san~pyWhat
7175e14174380c3f00ed95bdfe35370978f2f996
Added more regex
<4>:<add> "YouTube Video ID": "https://www.youtube.com/watch?v=",
# module: What.printer class Printing: def get_crypto_links(self, text, matched): <0> explorers = { <1> "Ethereum Wallet": "https://etherscan.io/address/", <2> "Dogecoin Wallet Address": "https://dogechain.info/address/", <3> "Bitcoin Wallet": "https://www.blockchain.com/btc/address/", <4> } <5> if text in explorers: <6> return ( <7> "Click here to see the address on the blockchain " <8> + explorers[text] <9> + matched <10> ) <11> return None <12>
===========changed ref 0=========== # module: tests.test_click + + def test_file_fixture_ssn(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall("Social", str(result.output)) + ===========changed ref 1=========== # module: tests.test_click + + def test_file_fixture_email(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall("Email", str(result.output)) + ===========changed ref 2=========== # module: tests.test_click + + @pytest.mark.skip(reason="Matches on https://") + def test_file_fixture_ip(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall("Internet Protocol", str(result.output)) + ===========changed ref 3=========== # module: tests.test_click + + def test_file_fixture_youtube_id(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall("YouTube", str(result.output)) + ===========changed ref 4=========== # module: tests.test_click + + def test_file_fixture_youtube(): + runner = CliRunner() + result = runner.invoke(main, ["fixtures/file"]) + assert result.exit_code == 0 + assert re.findall("YouTube", str(result.output)) +
What.nameThatHash/Nth.get_hashes
Modified
bee-san~pyWhat
b29dc1b6753f5085911c99697e09069354dc30ac
Merge branch 'main' of github.com:bee-san/id into main
<0>:<add> print("\n") <add> print("Text is " + str(text)) <add> to_ret = runner.api_return_hashes_as_dict(text) <del> return runner.api_return_hashes_as_dict([hashes]) <1>:<add> print("\n") <add> import pprint <add> pprint.pprint(to_ret) <add> return to_ret
# module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: <0> return runner.api_return_hashes_as_dict([hashes]) <1>
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
b29dc1b6753f5085911c99697e09069354dc30ac
Merge branch 'main' of github.com:bee-san/id into main
<21>:<add> console.print(to_out) <add> to_out = "" <add>
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += ( <9> f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <10> ) <11> <12> to_out = "" <13> if prob_language: <14> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <15> <16> if text["File Signatures"]: <17> to_out += "\n" <18> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <19> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <20> to_out += "\n" <21> <22> if text["Regexes"]: <23> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <24> table = Table( <25> show_header=True, header_style="bold #D7Afff", show_lines=True <26> ) <27> table.add_column("Matched Text") <28> table.add_column("Identified as") <29> table.add_column("Description") <30> for i in text["Regexes"]: <31> matched = i["Matched"] <32> name = i["Regex Pattern"]["Name"] <33> description = self.get_crypto_links(name, matched) <34> if not description</s>
===========below chunk 0=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) return 0 console.print(to_out) ===========unchanged ref 0=========== at: What.printer.Printing get_crypto_links(self, text, matched) get_crypto_links(text, matched) ===========changed ref 0=========== # module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: + print("\n") + print("Text is " + str(text)) + to_ret = runner.api_return_hashes_as_dict(text) - return runner.api_return_hashes_as_dict([hashes]) + print("\n") + import pprint + pprint.pprint(to_ret) + return to_ret
What.printer/Printing.get_crypto_links
Modified
bee-san~pyWhat
b29dc1b6753f5085911c99697e09069354dc30ac
Merge branch 'main' of github.com:bee-san/id into main
<8>:<add> "Click here to analyse in the browser " <del> "Click here to see the address on the blockchain "
# module: What.printer class Printing: def get_crypto_links(self, text, matched): <0> explorers = { <1> "Ethereum Wallet": "https://etherscan.io/address/", <2> "Dogecoin Wallet Address": "https://dogechain.info/address/", <3> "Bitcoin Wallet": "https://www.blockchain.com/btc/address/", <4> "YouTube Video ID": "https://www.youtube.com/watch?v=", <5> } <6> if text in explorers: <7> return ( <8> "Click here to see the address on the blockchain " <9> + explorers[text] <10> + matched <11> ) <12> return None <13>
===========unchanged ref 0=========== at: json dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str ===========changed ref 0=========== # module: What.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += ( f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" ) to_out = "" if prob_language: to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" + console.print(to_out) + to_out = "" + if text["Regexes"]: to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"</s> ===========changed ref 1=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s> = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) + if text["Hashes"]: + to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" + table = Table( + show_header=True, header_style="bold #D7Afff", show_lines=True + ) + table.add_column("Matched Text") + table.add_column("Possible Hash Type") + table.add_column("Description") - return 0 - console.print(to_out) ===========changed ref 2=========== # module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: + print("\n") + print("Text is " + str(text)) + to_ret = runner.api_return_hashes_as_dict(text) - return runner.api_return_hashes_as_dict([hashes]) + print("\n") + import pprint + pprint.pprint(to_ret) + return to_ret
What.identifier/Identifier.__init__
Modified
bee-san~pyWhat
b29dc1b6753f5085911c99697e09069354dc30ac
Merge branch 'main' of github.com:bee-san/id into main
<3>:<add> self.name_that_hash = Nth()
# module: What.identifier class Identifier: def __init__(self): <0> self.regex_id = RegexIdentifier() <1> self.lang_detect = LanguageDetector() <2> self.file_sig = FileSignatures() <3>
===========unchanged ref 0=========== at: What.languageDetector LanguageDetector() at: What.regex_identifier RegexIdentifier() ===========changed ref 0=========== # module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: + print("\n") + print("Text is " + str(text)) + to_ret = runner.api_return_hashes_as_dict(text) - return runner.api_return_hashes_as_dict([hashes]) + print("\n") + import pprint + pprint.pprint(to_ret) + return to_ret ===========changed ref 1=========== # module: What.printer class Printing: def get_crypto_links(self, text, matched): explorers = { "Ethereum Wallet": "https://etherscan.io/address/", "Dogecoin Wallet Address": "https://dogechain.info/address/", "Bitcoin Wallet": "https://www.blockchain.com/btc/address/", "YouTube Video ID": "https://www.youtube.com/watch?v=", } if text in explorers: return ( + "Click here to analyse in the browser " - "Click here to see the address on the blockchain " + explorers[text] + matched ) return None ===========changed ref 2=========== # module: What.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += ( f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" ) to_out = "" if prob_language: to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" + console.print(to_out) + to_out = "" + if text["Regexes"]: to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"</s> ===========changed ref 3=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s> = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) + if text["Hashes"]: + to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" + table = Table( + show_header=True, header_style="bold #D7Afff", show_lines=True + ) + table.add_column("Matched Text") + table.add_column("Possible Hash Type") + table.add_column("Description") - return 0 - console.print(to_out)
What.identifier/Identifier.identify
Modified
bee-san~pyWhat
b29dc1b6753f5085911c99697e09069354dc30ac
Merge branch 'main' of github.com:bee-san/id into main
<15>:<add> # get_hashes takes a list of hashes, we split to give it a list <add> identify_obj["Hashes"] = self.name_that_hash.get_hashes(text.split()) <add> print("\n") <add> print(identify_obj["Hashes"]) <add> print("\n")
# module: What.identifier class Identifier: def identify(self, text: str) -> dict: <0> identify_obj = {} <1> <2> magic_numbers = None <3> if self.file_exists(text): <4> magic_numbers = self.file_sig.open_binary_scan_magic_nums(text) <5> text = self.file_sig.open_file_loc(text) <6> identify_obj["File Signatures"] = magic_numbers <7> <8> if not magic_numbers: <9> # If file doesn't exist, check to see if the inputted text is <10> # a file in hex format <11> identify_obj["File Signatures"] = self.file_sig.check_magic_nums(text) <12> <13> identify_obj["Language"] = self.lang_detect.detect_what_lang(text) <14> identify_obj["Regexes"] = self.regex_id.check(text) <15> <16> return identify_obj <17>
===========unchanged ref 0=========== at: What.identifier.Identifier file_exists(text) at: What.identifier.Identifier.__init__ self.regex_id = RegexIdentifier() self.lang_detect = LanguageDetector() at: What.languageDetector.LanguageDetector detect_what_lang(text) at: What.magic_numbers FileSignatures() at: What.magic_numbers.FileSignatures open_file_loc(file_loc) open_binary_scan_magic_nums(file_loc) check_magic_nums(text) at: What.nameThatHash Nth() at: What.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: What.identifier class Identifier: def __init__(self): self.regex_id = RegexIdentifier() self.lang_detect = LanguageDetector() self.file_sig = FileSignatures() + self.name_that_hash = Nth() ===========changed ref 1=========== # module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: + print("\n") + print("Text is " + str(text)) + to_ret = runner.api_return_hashes_as_dict(text) - return runner.api_return_hashes_as_dict([hashes]) + print("\n") + import pprint + pprint.pprint(to_ret) + return to_ret ===========changed ref 2=========== # module: What.printer class Printing: def get_crypto_links(self, text, matched): explorers = { "Ethereum Wallet": "https://etherscan.io/address/", "Dogecoin Wallet Address": "https://dogechain.info/address/", "Bitcoin Wallet": "https://www.blockchain.com/btc/address/", "YouTube Video ID": "https://www.youtube.com/watch?v=", } if text in explorers: return ( + "Click here to analyse in the browser " - "Click here to see the address on the blockchain " + explorers[text] + matched ) return None ===========changed ref 3=========== # module: What.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += ( f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" ) to_out = "" if prob_language: to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" + console.print(to_out) + to_out = "" + if text["Regexes"]: to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"</s> ===========changed ref 4=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s> = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) + if text["Hashes"]: + to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" + table = Table( + show_header=True, header_style="bold #D7Afff", show_lines=True + ) + table.add_column("Matched Text") + table.add_column("Possible Hash Type") + table.add_column("Description") - return 0 - console.print(to_out)
What.nameThatHash/Nth.get_hashes
Modified
bee-san~pyWhat
f406cb9c1eca31b4ec54a15a39b8039b3cdd807f
Logo work
<2>:<add> to_ret = runner.api_return_hashes_as_dict(text) <del> to_ret = runner.api_return_hashes_as_dict(text) <5>:<add>
# module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: <0> print("\n") <1> print("Text is " + str(text)) <2> to_ret = runner.api_return_hashes_as_dict(text) <3> print("\n") <4> import pprint <5> pprint.pprint(to_ret) <6> return to_ret <7>
===========unchanged ref 0=========== at: pprint pprint(object: object, stream: Optional[IO[str]]=..., indent: int=..., width: int=..., depth: Optional[int]=..., *, compact: bool=...) -> None
What.printer/Printing.pretty_print
Modified
bee-san~pyWhat
f406cb9c1eca31b4ec54a15a39b8039b3cdd807f
Logo work
<23>:<del>
# module: What.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += ( <9> f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <10> ) <11> <12> to_out = "" <13> if prob_language: <14> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <15> <16> if text["File Signatures"]: <17> to_out += "\n" <18> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <19> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <20> to_out += "\n" <21> console.print(to_out) <22> to_out = "" <23> <24> <25> if text["Regexes"]: <26> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <27> table = Table( <28> show_header=True, header_style="bold #D7Afff", show_lines=True <29> ) <30> table.add_column("Matched Text") <31> table.add_column("Identified as") <32> table.add_column("Description") <33> for i in text["Regexes"]: <34> matched = i["Matched"] <35> name = i["Regex Pattern"]["Name"] </s>
===========below chunk 0=========== # module: What.printer class Printing: def pretty_print(self, text: dict): # offset: 1 if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) if text["Hashes"]: to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Possible Hash Type") table.add_column("Description") ===========unchanged ref 0=========== at: What.printer.Printing get_crypto_links(text, matched) ===========changed ref 0=========== # module: What.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: print("\n") print("Text is " + str(text)) + to_ret = runner.api_return_hashes_as_dict(text) - to_ret = runner.api_return_hashes_as_dict(text) print("\n") import pprint + pprint.pprint(to_ret) return to_ret
PyWhat.printer/Printing.pretty_print
Modified
bee-san~pyWhat
8a39f3c110c3ef0e71d0804c5feff08985bf6683
Update printer.py
<25>:<add> to_out += "\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <del> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]"
# module: PyWhat.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += ( <9> f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <10> ) <11> <12> to_out = "" <13> if prob_language: <14> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <15> <16> if text["File Signatures"]: <17> to_out += "\n" <18> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <19> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <20> to_out += "\n" <21> console.print(to_out) <22> to_out = "" <23> <24> if text["Regexes"]: <25> to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <26> table = Table( <27> show_header=True, header_style="bold #D7Afff", show_lines=True <28> ) <29> table.add_column("Matched Text") <30> table.add_column("Identified as") <31> table.add_column("Description") <32> for i in text["Regexes"]: <33> matched = i["Matched"] <34> name = i["Regex Pattern"]["Name"] <35> </s>
===========below chunk 0=========== # module: PyWhat.printer class Printing: def pretty_print(self, text: dict): # offset: 1 if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) if text["Hashes"]: to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Possible Hash Type") table.add_column("Description") for hash_text in text["Hashes"].keys(): for types in text["Hashes"][hash_text]: table.add_row( hash_text, types["name"], types["description"], ) console.print(to_out, table) ===========unchanged ref 0=========== at: PyWhat.printer.Printing get_crypto_links(self, text, matched) get_crypto_links(text, matched)
PyWhat.printer/Printing.get_crypto_links
Modified
bee-san~pyWhat
8a39f3c110c3ef0e71d0804c5feff08985bf6683
Update printer.py
<5>:<add> "YouTube Channel ID": "https://www.youtube.com/channel/",
# module: PyWhat.printer class Printing: def get_crypto_links(self, text, matched): <0> explorers = { <1> "Ethereum Wallet": "https://etherscan.io/address/", <2> "Dogecoin Wallet Address": "https://dogechain.info/address/", <3> "Bitcoin Wallet": "https://www.blockchain.com/btc/address/", <4> "YouTube Video ID": "https://www.youtube.com/watch?v=", <5> } <6> if text in explorers: <7> return "Click here to analyse in the browser " + explorers[text] + matched <8> return None <9>
===========unchanged ref 0=========== at: json dumps(obj: Any, *, skipkeys: bool=..., ensure_ascii: bool=..., check_circular: bool=..., allow_nan: bool=..., cls: Optional[Type[JSONEncoder]]=..., indent: Union[None, int, str]=..., separators: Optional[Tuple[str, str]]=..., default: Optional[Callable[[Any], Any]]=..., sort_keys: bool=..., **kwds: Any) -> str ===========changed ref 0=========== # module: PyWhat.printer class Printing: def pretty_print(self, text: dict): console = Console(highlight=False) languages = text["Language"] # calculate probability of each language prob_language = "" if languages: for i in languages: prob_language += ( f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" ) to_out = "" if prob_language: to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" if text["File Signatures"]: to_out += "\n" to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." to_out += "\n" console.print(to_out) to_out = "" if text["Regexes"]: + to_out += "\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" - to_out += f"\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Identified as") table.add_column("Description") for i in text["Regexes"]: matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.</s> ===========changed ref 1=========== # module: PyWhat.printer class Printing: def pretty_print(self, text: dict): # offset: 1 <s> matched = i["Matched"] name = i["Regex Pattern"]["Name"] description = self.get_crypto_links(name, matched) if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) if text["Hashes"]: + to_out = "\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" - to_out = f"\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Possible Hash Type") table.add_column("Description") for hash_text in text["Hashes"].keys(): for types in text["Hashes"][hash_text]: table.add_row( hash_text, types["name"], types["description"], ) console.print(to_out, table)
PyWhat.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
66768b2d9c7a914ed61a8b900ed9607c3d5e17a8
Fix encoding error
<0>:<add> with open("Data/file_signatures.yaml", "r", encoding="utf8") as myfile: <del> with open("Data/file_signatures.yaml", "r") as myfile:
# module: PyWhat.magic_numbers class FileSignatures: def __init__(self): <0> with open("Data/file_signatures.yaml", "r") as myfile: <1> data = myfile.read() <2> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: io.TextIOWrapper read(self, size: Optional[int]=..., /) -> str at: typing.IO __slots__ = () read(n: int=...) -> AnyStr
PyWhat.nameThatHash/Nth.get_hashes
Modified
bee-san~pyWhat
c6fe2da0ec283fccb10a9f8f0aa6ff8d5cc9927f
Merge branch 'main' into bee-fix-tests
<0>:<del> print("\n") <1>:<del> print("Text is " + str(text)) <3>:<del> print("\n") <4>:<del> import pprint <5>:<del> <6>:<del> pprint.pprint(to_ret)
# module: PyWhat.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: <0> print("\n") <1> print("Text is " + str(text)) <2> to_ret = runner.api_return_hashes_as_dict(text) <3> print("\n") <4> import pprint <5> <6> pprint.pprint(to_ret) <7> return to_ret <8>
===========changed ref 0=========== # module: PyWhat.what - os.chdir(os.path.dirname(os.path.abspath(__file__))) if __name__ == "__main__": main()
PyWhat.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
c6fe2da0ec283fccb10a9f8f0aa6ff8d5cc9927f
Merge branch 'main' into bee-fix-tests
<0>:<add> with open("PyWhat/Data/regex.yaml", "r") as myfile: <del> with open("Data/regex.yaml", "r") as myfile:
# module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): <0> with open("Data/regex.yaml", "r") as myfile: <1> data = myfile.read() <2> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: io.BufferedRandom read(self, size: Optional[int]=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: PyWhat.what - os.chdir(os.path.dirname(os.path.abspath(__file__))) if __name__ == "__main__": main() ===========changed ref 1=========== # module: PyWhat.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: - print("\n") - print("Text is " + str(text)) to_ret = runner.api_return_hashes_as_dict(text) - print("\n") - import pprint - - pprint.pprint(to_ret) return to_ret
PyWhat.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
c6fe2da0ec283fccb10a9f8f0aa6ff8d5cc9927f
Merge branch 'main' into bee-fix-tests
<0>:<add> with open("PyWhat/Data/file_signatures.yaml", "r", encoding="utf8") as myfile: <del> with open("Data/file_signatures.yaml", "r", encoding="utf8") as myfile:
# module: PyWhat.magic_numbers class FileSignatures: def __init__(self): <0> with open("Data/file_signatures.yaml", "r", encoding="utf8") as myfile: <1> data = myfile.read() <2> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: PyWhat.what - os.chdir(os.path.dirname(os.path.abspath(__file__))) if __name__ == "__main__": main() ===========changed ref 1=========== # module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): + with open("PyWhat/Data/regex.yaml", "r") as myfile: - with open("Data/regex.yaml", "r") as myfile: data = myfile.read() self.regexes = yaml.load(data, Loader=yaml.FullLoader) ===========changed ref 2=========== # module: PyWhat.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: - print("\n") - print("Text is " + str(text)) to_ret = runner.api_return_hashes_as_dict(text) - print("\n") - import pprint - - pprint.pprint(to_ret) return to_ret
PyWhat.identifier/Identifier.identify
Modified
bee-san~pyWhat
c6fe2da0ec283fccb10a9f8f0aa6ff8d5cc9927f
Merge branch 'main' into bee-fix-tests
<17>:<del> print("\n") <18>:<del> print(identify_obj["Hashes"]) <19>:<del> print("\n")
# module: PyWhat.identifier class Identifier: def identify(self, text: str) -> dict: <0> identify_obj = {} <1> <2> magic_numbers = None <3> if self.file_exists(text): <4> magic_numbers = self.file_sig.open_binary_scan_magic_nums(text) <5> text = self.file_sig.open_file_loc(text) <6> identify_obj["File Signatures"] = magic_numbers <7> <8> if not magic_numbers: <9> # If file doesn't exist, check to see if the inputted text is <10> # a file in hex format <11> identify_obj["File Signatures"] = self.file_sig.check_magic_nums(text) <12> <13> identify_obj["Language"] = self.lang_detect.detect_what_lang(text) <14> identify_obj["Regexes"] = self.regex_id.check(text) <15> # get_hashes takes a list of hashes, we split to give it a list <16> identify_obj["Hashes"] = self.name_that_hash.get_hashes(text.split()) <17> print("\n") <18> print(identify_obj["Hashes"]) <19> print("\n") <20> <21> return identify_obj <22>
===========unchanged ref 0=========== at: PyWhat.identifier.Identifier.__init__ self.regex_id = RegexIdentifier() self.lang_detect = LanguageDetector() self.file_sig = FileSignatures() self.name_that_hash = Nth() at: PyWhat.languageDetector.LanguageDetector detect_what_lang(text) at: PyWhat.magic_numbers.FileSignatures open_file_loc(file_loc) open_binary_scan_magic_nums(file_loc) check_magic_nums(text) at: PyWhat.nameThatHash.Nth get_hashes(text: str) -> dict at: PyWhat.regex_identifier.RegexIdentifier check(text) at: os.path isfile(path: AnyPath) -> bool ===========changed ref 0=========== # module: PyWhat.nameThatHash class Nth: def get_hashes(self, text: str) -> dict: - print("\n") - print("Text is " + str(text)) to_ret = runner.api_return_hashes_as_dict(text) - print("\n") - import pprint - - pprint.pprint(to_ret) return to_ret ===========changed ref 1=========== # module: PyWhat.what - os.chdir(os.path.dirname(os.path.abspath(__file__))) if __name__ == "__main__": main() ===========changed ref 2=========== # module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): + with open("PyWhat/Data/regex.yaml", "r") as myfile: - with open("Data/regex.yaml", "r") as myfile: data = myfile.read() self.regexes = yaml.load(data, Loader=yaml.FullLoader) ===========changed ref 3=========== # module: PyWhat.magic_numbers class FileSignatures: def __init__(self): + with open("PyWhat/Data/file_signatures.yaml", "r", encoding="utf8") as myfile: - with open("Data/file_signatures.yaml", "r", encoding="utf8") as myfile: data = myfile.read() self.file_sigs = yaml.load(data, Loader=yaml.FullLoader)
PyWhat.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
723db85e458ea3b9035e12b7c9aebeed9b8beb24
Fix path issues
<0>:<add> path = "Data\\regex.yaml" <add> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <add> with open(fullpath, "r") as myfile: <del> with open("PyWhat/Data/regex.yaml", "r") as myfile:
# module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): <0> with open("PyWhat/Data/regex.yaml", "r") as myfile: <1> data = myfile.read() <2> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <3>
PyWhat.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
65518e3af502ecb9bfdb434c38484ebe4c4f04c1
Fix path issues and an encoding error
<0>:<add> path = "Data\\file_signatures.yaml" <add> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <add> with open(fullpath, "r", encoding="utf8", errors="ignore") as myfile: <del> with open("PyWhat/Data/file_signatures.yaml", "r", encoding="utf8") as myfile:
# module: PyWhat.magic_numbers class FileSignatures: def __init__(self): <0> with open("PyWhat/Data/file_signatures.yaml", "r", encoding="utf8") as myfile: <1> data = myfile.read() <2> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <3>
===========unchanged ref 0=========== at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes dirname(p: _PathLike[AnyStr]) -> AnyStr dirname(p: AnyStr) -> AnyStr abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback
PyWhat.magic_numbers/FileSignatures.open_file_loc
Modified
bee-san~pyWhat
65518e3af502ecb9bfdb434c38484ebe4c4f04c1
Fix path issues and an encoding error
<0>:<add> with open(file_loc, "r", encoding="utf8", errors="ignore") as myfile: <del> with open(file_loc, "r") as myfile:
# module: PyWhat.magic_numbers class FileSignatures: def open_file_loc(self, file_loc): <0> with open(file_loc, "r") as myfile: <1> r = myfile.read() <2> return r <3>
===========unchanged ref 0=========== at: PyWhat.magic_numbers.FileSignatures.__init__ fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream) ===========changed ref 0=========== # module: PyWhat.magic_numbers class FileSignatures: def __init__(self): + path = "Data\\file_signatures.yaml" + fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) + with open(fullpath, "r", encoding="utf8", errors="ignore") as myfile: - with open("PyWhat/Data/file_signatures.yaml", "r", encoding="utf8") as myfile: data = myfile.read() self.file_sigs = yaml.load(data, Loader=yaml.FullLoader)
PyWhat.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
98dd03502d42802923acc3a94a54913bc4f0170d
Fix path issue again
<0>:<add> path = "Data/regex.yaml" <del> path = "Data\\regex.yaml"
# module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): <0> path = "Data\\regex.yaml" <1> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <2> with open(fullpath, "r") as myfile: <3> data = myfile.read() <4> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <5>
===========unchanged ref 0=========== at: io.FileIO read(self, size: int=..., /) -> bytes at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes dirname(p: _PathLike[AnyStr]) -> AnyStr dirname(p: AnyStr) -> AnyStr abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream)
PyWhat.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
fb96a524248288918449b2154228deb1cb7f1106
Fix the other path issue
<0>:<add> path = "Data/file_signatures.yaml" <del> path = "Data\\file_signatures.yaml"
# module: PyWhat.magic_numbers class FileSignatures: def __init__(self): <0> path = "Data\\file_signatures.yaml" <1> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <2> with open(fullpath, "r", encoding="utf8", errors="ignore") as myfile: <3> data = myfile.read() <4> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <5>
===========unchanged ref 0=========== at: io.BufferedReader read(self, size: Optional[int]=..., /) -> bytes at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes dirname(p: _PathLike[AnyStr]) -> AnyStr dirname(p: AnyStr) -> AnyStr abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream)
PyWhat.printer/Printing.pretty_print
Modified
bee-san~pyWhat
c94b47404515a6fe857fef4f9dc8a135dbd157dd
Updated readme
# module: PyWhat.printer class Printing: def pretty_print(self, text: dict): <0> console = Console(highlight=False) <1> <2> languages = text["Language"] <3> <4> # calculate probability of each language <5> prob_language = "" <6> if languages: <7> for i in languages: <8> prob_language += ( <9> f" [red]{i.lang}[/red] {round(i.prob * 100)}% probability" <10> ) <11> <12> to_out = "" <13> if prob_language: <14> to_out += f"[bold #D7Afff]Possible language (ISO-639-1 code):[/bold #D7Afff]{prob_language}.\n" <15> <16> if text["File Signatures"]: <17> to_out += "\n" <18> to_out += f"[bold #D7Afff]File Identified[/bold #D7Afff] with Magic Numbers {text['File Signatures']['ISO 8859-1']}." <19> to_out += f"\n[bold #D7Afff]File Description:[/bold #D7Afff] {text['File Signatures']['Description']}." <20> to_out += "\n" <21> console.print(to_out) <22> to_out = "" <23> <24> if text["Regexes"]: <25> to_out += "\n[bold #D7Afff]Possible Identification[/bold #D7Afff]" <26> table = Table( <27> show_header=True, header_style="bold #D7Afff", show_lines=True <28> ) <29> table.add_column("Matched Text") <30> table.add_column("Identified as") <31> table.add_column("Description") <32> for i in text["Regexes"]: <33> matched = i["Matched"] <34> name = i["Regex Pattern"]["Name"] <35> </s>
===========below chunk 0=========== # module: PyWhat.printer class Printing: def pretty_print(self, text: dict): # offset: 1 if not description: description = i["Regex Pattern"]["Description"] table.add_row( matched, name, description, ) console.print(to_out, table) if text["Hashes"]: to_out = "\n[bold #D7Afff]Hashes Identified[/bold #D7Afff]" table = Table( show_header=True, header_style="bold #D7Afff", show_lines=True ) table.add_column("Matched Text") table.add_column("Possible Hash Type") table.add_column("Description") for hash_text in text["Hashes"].keys(): for types in text["Hashes"][hash_text]: table.add_row( hash_text, types["name"], types["description"], ) console.print(to_out, table) ===========unchanged ref 0=========== at: PyWhat.printer.Printing get_crypto_links(text, matched)
PyWhat.regex_identifier/RegexIdentifier.__init__
Modified
bee-san~pyWhat
9a7d21de3a80e1dc25ead5d0a0f457e19de20ec9
Switched from YAML -> JSON
<0>:<add> path = "Data/regex.json" <del> path = "Data/regex.yaml" <3>:<del> data = myfile.read() <4>:<del> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <5>:<add> self.regexes = json.load(myfile)
# module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): <0> path = "Data/regex.yaml" <1> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <2> with open(fullpath, "r") as myfile: <3> data = myfile.read() <4> self.regexes = yaml.load(data, Loader=yaml.FullLoader) <5>
===========unchanged ref 0=========== at: io.FileIO read(self, size: int=..., /) -> bytes at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes dirname(p: _PathLike[AnyStr]) -> AnyStr dirname(p: AnyStr) -> AnyStr abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback at: typing.IO __slots__ = () read(n: int=...) -> AnyStr at: yaml load(stream: Union[bytes, IO[bytes], Text, IO[Text]], Loader=...) -> Any at: yaml.loader FullLoader(stream)
PyWhat.magic_numbers/FileSignatures.__init__
Modified
bee-san~pyWhat
9a7d21de3a80e1dc25ead5d0a0f457e19de20ec9
Switched from YAML -> JSON
<0>:<add> path = "Data/file_signatures.json" <del> path = "Data/file_signatures.yaml" <3>:<del> data = myfile.read() <4>:<del> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <5>:<add> self.file_sigs = json.load(myfile)
# module: PyWhat.magic_numbers class FileSignatures: def __init__(self): <0> path = "Data/file_signatures.yaml" <1> fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) <2> with open(fullpath, "r", encoding="utf8", errors="ignore") as myfile: <3> data = myfile.read() <4> self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) <5>
===========unchanged ref 0=========== at: json load(fp: SupportsRead[Union[str, bytes]], *, cls: Optional[Type[JSONDecoder]]=..., object_hook: Optional[Callable[[Dict[Any, Any]], Any]]=..., parse_float: Optional[Callable[[str], Any]]=..., parse_int: Optional[Callable[[str], Any]]=..., parse_constant: Optional[Callable[[str], Any]]=..., object_pairs_hook: Optional[Callable[[List[Tuple[Any, Any]]], Any]]=..., **kwds: Any) -> Any at: os.path join(a: StrPath, *paths: StrPath) -> str join(a: BytesPath, *paths: BytesPath) -> bytes dirname(p: _PathLike[AnyStr]) -> AnyStr dirname(p: AnyStr) -> AnyStr abspath(path: _PathLike[AnyStr]) -> AnyStr abspath(path: AnyStr) -> AnyStr abspath = _abspath_fallback ===========changed ref 0=========== # module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): + path = "Data/regex.json" - path = "Data/regex.yaml" fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) with open(fullpath, "r") as myfile: - data = myfile.read() - self.regexes = yaml.load(data, Loader=yaml.FullLoader) + self.regexes = json.load(myfile)
tests.test_regex_identifier/test_username
Modified
bee-san~pyWhat
9a7d21de3a80e1dc25ead5d0a0f457e19de20ec9
Switched from YAML -> JSON
<2>:<add> assert "Key:Value" in res[0]["Regex Pattern"]["Name"] <del> assert "Username Password Combination" in res[0]["Regex Pattern"]["Name"]
# module: tests.test_regex_identifier def test_username(): <0> r = regex_identifier.RegexIdentifier() <1> res = r.check("james:S3cr37_P@$$W0rd") <2> assert "Username Password Combination" in res[0]["Regex Pattern"]["Name"] <3>
===========unchanged ref 0=========== at: PyWhat.regex_identifier RegexIdentifier() at: PyWhat.regex_identifier.RegexIdentifier check(text) ===========changed ref 0=========== # module: PyWhat.regex_identifier class RegexIdentifier: def __init__(self): + path = "Data/regex.json" - path = "Data/regex.yaml" fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) with open(fullpath, "r") as myfile: - data = myfile.read() - self.regexes = yaml.load(data, Loader=yaml.FullLoader) + self.regexes = json.load(myfile) ===========changed ref 1=========== # module: PyWhat.magic_numbers class FileSignatures: def __init__(self): + path = "Data/file_signatures.json" - path = "Data/file_signatures.yaml" fullpath = os.path.join(os.path.dirname(os.path.abspath(__file__)), path) with open(fullpath, "r", encoding="utf8", errors="ignore") as myfile: - data = myfile.read() - self.file_sigs = yaml.load(data, Loader=yaml.FullLoader) + self.file_sigs = json.load(myfile) ===========changed ref 2=========== # module: scripts.get_file_sigs r = requests.get( "http://en.wikipedia.org/w/index.php?title=" + "List_of_file_signatures&action=raw" ) wt = wtp.parse(r.text) # prints first 3 items of json, delete [0:3] to print all. to_iter = {"root": wt.tables[0].data()} to_iter = to_iter["root"] to_dump = [] populars = set(["23 21"]) for i in range(1, len(to_iter)): to_insert = {} to_insert["Hexadecimal File Signature"] = cleanhtml(to_iter[i][0]).replace(" ", "") check_iso = cleanhtml(to_iter[i][1]) if len(set(check_iso)) <= 2: to_insert["ISO 8859-1"] = None else: to_insert["ISO 8859-1"] = check_iso check = to_iter[i][3] if check == "": to_insert["Filename Extension"] = None else: to_insert["Filename Extension"] = cleanhtml(check) des = to_iter[i][4] if "url" in des: splits = des.split("=") if "|" in splits[1]: # https://wiki.wireshark.org/Development/LibpcapFileFormat#Global_Header|title split_more = splits[1].split("|") print(split_more) to_insert["URL"] = split_more[0] else: to_insert["URL"] = splits[1] to_insert["Description"] = cleanhtml(splits[0]) else: to_insert["Description"] = cleanhtml(to_iter[i][4]) if to_insert</s> ===========changed ref 3=========== # module: scripts.get_file_sigs # offset: 1 <s> to_insert["Description"] = cleanhtml(to_iter[i][4]) if to_insert["Hexadecimal File Signature"] in populars: to_insert["Popular"] = 1 else: to_insert["Popular"] = 0 to_dump.append(to_insert) + with open("file_signatures.json", "w") as outfile: - with open("file_signatures.yaml", "w") as ym: - yaml.dump(to_dump, ym, allow_unicode=True) - + json.dump(to_dump, outfile, indent=4) # https://en.wikipedia.org/api/rest_v1/page/html/List_of_file_signatures """ { "root": [ [ "[[Hexadecimal|Hex]] signature", "ISO 8859-1", "[[Offset (computer science)|Offset]]", "[[Filename extension]]", "Description" ], [ "<pre>23 21</pre>", "{{show file signature|23 21}}", "0", "", "Script or data to be passed to the program following the [[Shebang (Unix)|shebang]] (#!)" ], [ "<pre>a1 b2 c3 d4</pre>\n<pre>d4 c3 b2 a1</pre>", "{{show file signature|a1 b2 c3 d4}}\n{{show file signature|d4 c3 b2 a1}}", "0", "pcap", "Libpcap File Format<ref>{{cite web |url=https://wiki.wireshark.org/Development</s> ===========changed ref 4=========== # module: scripts.get_file_sigs # offset: 2 <s>pcapFileFormat#Global_Header|title=Libpcap File Format|access-date=2018-06-19}}</ref>" ] ] } """