id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
230,800 | litl/backoff | backoff/_wait_gen.py | expo | def expo(base=2, factor=1, max_value=None):
"""Generator for exponential decay.
Args:
base: The mathematical base of the exponentiation operation
factor: Factor to multiply the exponentation by.
max_value: The maximum value to yield. Once the value in the
true exponential sequence exceeds this, the value
of max_value will forever after be yielded.
"""
n = 0
while True:
a = factor * base ** n
if max_value is None or a < max_value:
yield a
n += 1
else:
yield max_value | python | def expo(base=2, factor=1, max_value=None):
"""Generator for exponential decay.
Args:
base: The mathematical base of the exponentiation operation
factor: Factor to multiply the exponentation by.
max_value: The maximum value to yield. Once the value in the
true exponential sequence exceeds this, the value
of max_value will forever after be yielded.
"""
n = 0
while True:
a = factor * base ** n
if max_value is None or a < max_value:
yield a
n += 1
else:
yield max_value | [
"def",
"expo",
"(",
"base",
"=",
"2",
",",
"factor",
"=",
"1",
",",
"max_value",
"=",
"None",
")",
":",
"n",
"=",
"0",
"while",
"True",
":",
"a",
"=",
"factor",
"*",
"base",
"**",
"n",
"if",
"max_value",
"is",
"None",
"or",
"a",
"<",
"max_value",
":",
"yield",
"a",
"n",
"+=",
"1",
"else",
":",
"yield",
"max_value"
] | Generator for exponential decay.
Args:
base: The mathematical base of the exponentiation operation
factor: Factor to multiply the exponentation by.
max_value: The maximum value to yield. Once the value in the
true exponential sequence exceeds this, the value
of max_value will forever after be yielded. | [
"Generator",
"for",
"exponential",
"decay",
"."
] | 229d30adce4128f093550a1761c49594c78df4b4 | https://github.com/litl/backoff/blob/229d30adce4128f093550a1761c49594c78df4b4/backoff/_wait_gen.py#L6-L23 |
230,801 | litl/backoff | backoff/_wait_gen.py | fibo | def fibo(max_value=None):
"""Generator for fibonaccial decay.
Args:
max_value: The maximum value to yield. Once the value in the
true fibonacci sequence exceeds this, the value
of max_value will forever after be yielded.
"""
a = 1
b = 1
while True:
if max_value is None or a < max_value:
yield a
a, b = b, a + b
else:
yield max_value | python | def fibo(max_value=None):
"""Generator for fibonaccial decay.
Args:
max_value: The maximum value to yield. Once the value in the
true fibonacci sequence exceeds this, the value
of max_value will forever after be yielded.
"""
a = 1
b = 1
while True:
if max_value is None or a < max_value:
yield a
a, b = b, a + b
else:
yield max_value | [
"def",
"fibo",
"(",
"max_value",
"=",
"None",
")",
":",
"a",
"=",
"1",
"b",
"=",
"1",
"while",
"True",
":",
"if",
"max_value",
"is",
"None",
"or",
"a",
"<",
"max_value",
":",
"yield",
"a",
"a",
",",
"b",
"=",
"b",
",",
"a",
"+",
"b",
"else",
":",
"yield",
"max_value"
] | Generator for fibonaccial decay.
Args:
max_value: The maximum value to yield. Once the value in the
true fibonacci sequence exceeds this, the value
of max_value will forever after be yielded. | [
"Generator",
"for",
"fibonaccial",
"decay",
"."
] | 229d30adce4128f093550a1761c49594c78df4b4 | https://github.com/litl/backoff/blob/229d30adce4128f093550a1761c49594c78df4b4/backoff/_wait_gen.py#L26-L41 |
230,802 | litl/backoff | backoff/_wait_gen.py | constant | def constant(interval=1):
"""Generator for constant intervals.
Args:
interval: A constant value to yield or an iterable of such values.
"""
try:
itr = iter(interval)
except TypeError:
itr = itertools.repeat(interval)
for val in itr:
yield val | python | def constant(interval=1):
"""Generator for constant intervals.
Args:
interval: A constant value to yield or an iterable of such values.
"""
try:
itr = iter(interval)
except TypeError:
itr = itertools.repeat(interval)
for val in itr:
yield val | [
"def",
"constant",
"(",
"interval",
"=",
"1",
")",
":",
"try",
":",
"itr",
"=",
"iter",
"(",
"interval",
")",
"except",
"TypeError",
":",
"itr",
"=",
"itertools",
".",
"repeat",
"(",
"interval",
")",
"for",
"val",
"in",
"itr",
":",
"yield",
"val"
] | Generator for constant intervals.
Args:
interval: A constant value to yield or an iterable of such values. | [
"Generator",
"for",
"constant",
"intervals",
"."
] | 229d30adce4128f093550a1761c49594c78df4b4 | https://github.com/litl/backoff/blob/229d30adce4128f093550a1761c49594c78df4b4/backoff/_wait_gen.py#L44-L56 |
230,803 | crytic/slither | slither/detectors/erc20/incorrect_interface.py | IncorrectERC20InterfaceDetection.detect_incorrect_erc20_interface | def detect_incorrect_erc20_interface(contract):
""" Detect incorrect ERC20 interface
Returns:
list(str) : list of incorrect function signatures
"""
functions = [f for f in contract.functions if f.contract == contract and \
IncorrectERC20InterfaceDetection.incorrect_erc20_interface(f.signature)]
return functions | python | def detect_incorrect_erc20_interface(contract):
""" Detect incorrect ERC20 interface
Returns:
list(str) : list of incorrect function signatures
"""
functions = [f for f in contract.functions if f.contract == contract and \
IncorrectERC20InterfaceDetection.incorrect_erc20_interface(f.signature)]
return functions | [
"def",
"detect_incorrect_erc20_interface",
"(",
"contract",
")",
":",
"functions",
"=",
"[",
"f",
"for",
"f",
"in",
"contract",
".",
"functions",
"if",
"f",
".",
"contract",
"==",
"contract",
"and",
"IncorrectERC20InterfaceDetection",
".",
"incorrect_erc20_interface",
"(",
"f",
".",
"signature",
")",
"]",
"return",
"functions"
] | Detect incorrect ERC20 interface
Returns:
list(str) : list of incorrect function signatures | [
"Detect",
"incorrect",
"ERC20",
"interface"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/erc20/incorrect_interface.py#L49-L57 |
230,804 | crytic/slither | slither/detectors/erc20/incorrect_interface.py | IncorrectERC20InterfaceDetection._detect | def _detect(self):
""" Detect incorrect erc20 interface
Returns:
dict: [contrat name] = set(str) events
"""
results = []
for c in self.contracts:
functions = IncorrectERC20InterfaceDetection.detect_incorrect_erc20_interface(c)
if functions:
info = "{} ({}) has incorrect ERC20 function interface(s):\n"
info = info.format(c.name,
c.source_mapping_str)
for function in functions:
info += "\t-{} ({})\n".format(function.name, function.source_mapping_str)
json = self.generate_json_result(info)
self.add_functions_to_json(functions, json)
results.append(json)
return results | python | def _detect(self):
""" Detect incorrect erc20 interface
Returns:
dict: [contrat name] = set(str) events
"""
results = []
for c in self.contracts:
functions = IncorrectERC20InterfaceDetection.detect_incorrect_erc20_interface(c)
if functions:
info = "{} ({}) has incorrect ERC20 function interface(s):\n"
info = info.format(c.name,
c.source_mapping_str)
for function in functions:
info += "\t-{} ({})\n".format(function.name, function.source_mapping_str)
json = self.generate_json_result(info)
self.add_functions_to_json(functions, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"functions",
"=",
"IncorrectERC20InterfaceDetection",
".",
"detect_incorrect_erc20_interface",
"(",
"c",
")",
"if",
"functions",
":",
"info",
"=",
"\"{} ({}) has incorrect ERC20 function interface(s):\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"c",
".",
"name",
",",
"c",
".",
"source_mapping_str",
")",
"for",
"function",
"in",
"functions",
":",
"info",
"+=",
"\"\\t-{} ({})\\n\"",
".",
"format",
"(",
"function",
".",
"name",
",",
"function",
".",
"source_mapping_str",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_functions_to_json",
"(",
"functions",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect incorrect erc20 interface
Returns:
dict: [contrat name] = set(str) events | [
"Detect",
"incorrect",
"erc20",
"interface"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/erc20/incorrect_interface.py#L59-L78 |
230,805 | crytic/slither | slither/detectors/shadowing/local.py | LocalShadowing.detect_shadowing_definitions | def detect_shadowing_definitions(self, contract):
""" Detects if functions, access modifiers, events, state variables, and local variables are named after
reserved keywords. Any such definitions are returned in a list.
Returns:
list of tuple: (type, contract name, definition)"""
result = []
# Loop through all functions + modifiers in this contract.
for function in contract.functions + contract.modifiers:
# We should only look for functions declared directly in this contract (not in a base contract).
if function.contract != contract:
continue
# This function was declared in this contract, we check what its local variables might shadow.
for variable in function.variables:
overshadowed = []
for scope_contract in [contract] + contract.inheritance:
# Check functions
for scope_function in scope_contract.functions:
if variable.name == scope_function.name and scope_function.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_FUNCTION, scope_contract.name, scope_function))
# Check modifiers
for scope_modifier in scope_contract.modifiers:
if variable.name == scope_modifier.name and scope_modifier.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_MODIFIER, scope_contract.name, scope_modifier))
# Check events
for scope_event in scope_contract.events:
if variable.name == scope_event.name and scope_event.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_EVENT, scope_contract.name, scope_event))
# Check state variables
for scope_state_variable in scope_contract.variables:
if variable.name == scope_state_variable.name and scope_state_variable.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_STATE_VARIABLE, scope_contract.name, scope_state_variable))
# If we have found any overshadowed objects, we'll want to add it to our result list.
if overshadowed:
result.append((contract.name, function.name, variable, overshadowed))
return result | python | def detect_shadowing_definitions(self, contract):
""" Detects if functions, access modifiers, events, state variables, and local variables are named after
reserved keywords. Any such definitions are returned in a list.
Returns:
list of tuple: (type, contract name, definition)"""
result = []
# Loop through all functions + modifiers in this contract.
for function in contract.functions + contract.modifiers:
# We should only look for functions declared directly in this contract (not in a base contract).
if function.contract != contract:
continue
# This function was declared in this contract, we check what its local variables might shadow.
for variable in function.variables:
overshadowed = []
for scope_contract in [contract] + contract.inheritance:
# Check functions
for scope_function in scope_contract.functions:
if variable.name == scope_function.name and scope_function.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_FUNCTION, scope_contract.name, scope_function))
# Check modifiers
for scope_modifier in scope_contract.modifiers:
if variable.name == scope_modifier.name and scope_modifier.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_MODIFIER, scope_contract.name, scope_modifier))
# Check events
for scope_event in scope_contract.events:
if variable.name == scope_event.name and scope_event.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_EVENT, scope_contract.name, scope_event))
# Check state variables
for scope_state_variable in scope_contract.variables:
if variable.name == scope_state_variable.name and scope_state_variable.contract == scope_contract:
overshadowed.append((self.OVERSHADOWED_STATE_VARIABLE, scope_contract.name, scope_state_variable))
# If we have found any overshadowed objects, we'll want to add it to our result list.
if overshadowed:
result.append((contract.name, function.name, variable, overshadowed))
return result | [
"def",
"detect_shadowing_definitions",
"(",
"self",
",",
"contract",
")",
":",
"result",
"=",
"[",
"]",
"# Loop through all functions + modifiers in this contract.",
"for",
"function",
"in",
"contract",
".",
"functions",
"+",
"contract",
".",
"modifiers",
":",
"# We should only look for functions declared directly in this contract (not in a base contract).",
"if",
"function",
".",
"contract",
"!=",
"contract",
":",
"continue",
"# This function was declared in this contract, we check what its local variables might shadow.",
"for",
"variable",
"in",
"function",
".",
"variables",
":",
"overshadowed",
"=",
"[",
"]",
"for",
"scope_contract",
"in",
"[",
"contract",
"]",
"+",
"contract",
".",
"inheritance",
":",
"# Check functions",
"for",
"scope_function",
"in",
"scope_contract",
".",
"functions",
":",
"if",
"variable",
".",
"name",
"==",
"scope_function",
".",
"name",
"and",
"scope_function",
".",
"contract",
"==",
"scope_contract",
":",
"overshadowed",
".",
"append",
"(",
"(",
"self",
".",
"OVERSHADOWED_FUNCTION",
",",
"scope_contract",
".",
"name",
",",
"scope_function",
")",
")",
"# Check modifiers",
"for",
"scope_modifier",
"in",
"scope_contract",
".",
"modifiers",
":",
"if",
"variable",
".",
"name",
"==",
"scope_modifier",
".",
"name",
"and",
"scope_modifier",
".",
"contract",
"==",
"scope_contract",
":",
"overshadowed",
".",
"append",
"(",
"(",
"self",
".",
"OVERSHADOWED_MODIFIER",
",",
"scope_contract",
".",
"name",
",",
"scope_modifier",
")",
")",
"# Check events",
"for",
"scope_event",
"in",
"scope_contract",
".",
"events",
":",
"if",
"variable",
".",
"name",
"==",
"scope_event",
".",
"name",
"and",
"scope_event",
".",
"contract",
"==",
"scope_contract",
":",
"overshadowed",
".",
"append",
"(",
"(",
"self",
".",
"OVERSHADOWED_EVENT",
",",
"scope_contract",
".",
"name",
",",
"scope_event",
")",
")",
"# Check state variables",
"for",
"scope_state_variable",
"in",
"scope_contract",
".",
"variables",
":",
"if",
"variable",
".",
"name",
"==",
"scope_state_variable",
".",
"name",
"and",
"scope_state_variable",
".",
"contract",
"==",
"scope_contract",
":",
"overshadowed",
".",
"append",
"(",
"(",
"self",
".",
"OVERSHADOWED_STATE_VARIABLE",
",",
"scope_contract",
".",
"name",
",",
"scope_state_variable",
")",
")",
"# If we have found any overshadowed objects, we'll want to add it to our result list.",
"if",
"overshadowed",
":",
"result",
".",
"append",
"(",
"(",
"contract",
".",
"name",
",",
"function",
".",
"name",
",",
"variable",
",",
"overshadowed",
")",
")",
"return",
"result"
] | Detects if functions, access modifiers, events, state variables, and local variables are named after
reserved keywords. Any such definitions are returned in a list.
Returns:
list of tuple: (type, contract name, definition) | [
"Detects",
"if",
"functions",
"access",
"modifiers",
"events",
"state",
"variables",
"and",
"local",
"variables",
"are",
"named",
"after",
"reserved",
"keywords",
".",
"Any",
"such",
"definitions",
"are",
"returned",
"in",
"a",
"list",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/shadowing/local.py#L51-L90 |
230,806 | crytic/slither | slither/detectors/shadowing/local.py | LocalShadowing._detect | def _detect(self):
""" Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_shadowing_definitions(contract)
if shadows:
for shadow in shadows:
local_parent_name = shadow[1]
local_variable = shadow[2]
overshadowed = shadow[3]
info = '{}.{}.{} (local variable @ {}) shadows:\n'.format(contract.name,
local_parent_name,
local_variable.name,
local_variable.source_mapping_str)
for overshadowed_entry in overshadowed:
info += "\t- {}.{} ({} @ {})\n".format(overshadowed_entry[1],
overshadowed_entry[2],
overshadowed_entry[0],
overshadowed_entry[2].source_mapping_str)
# Generate relevant JSON data for this shadowing definition.
json = self.generate_json_result(info)
self.add_variable_to_json(local_variable, json)
for overshadowed_entry in overshadowed:
if overshadowed_entry[0] in [self.OVERSHADOWED_FUNCTION, self.OVERSHADOWED_MODIFIER,
self.OVERSHADOWED_EVENT]:
self.add_function_to_json(overshadowed_entry[2], json)
elif overshadowed_entry[0] == self.OVERSHADOWED_STATE_VARIABLE:
self.add_variable_to_json(overshadowed_entry[2], json)
results.append(json)
return results | python | def _detect(self):
""" Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_shadowing_definitions(contract)
if shadows:
for shadow in shadows:
local_parent_name = shadow[1]
local_variable = shadow[2]
overshadowed = shadow[3]
info = '{}.{}.{} (local variable @ {}) shadows:\n'.format(contract.name,
local_parent_name,
local_variable.name,
local_variable.source_mapping_str)
for overshadowed_entry in overshadowed:
info += "\t- {}.{} ({} @ {})\n".format(overshadowed_entry[1],
overshadowed_entry[2],
overshadowed_entry[0],
overshadowed_entry[2].source_mapping_str)
# Generate relevant JSON data for this shadowing definition.
json = self.generate_json_result(info)
self.add_variable_to_json(local_variable, json)
for overshadowed_entry in overshadowed:
if overshadowed_entry[0] in [self.OVERSHADOWED_FUNCTION, self.OVERSHADOWED_MODIFIER,
self.OVERSHADOWED_EVENT]:
self.add_function_to_json(overshadowed_entry[2], json)
elif overshadowed_entry[0] == self.OVERSHADOWED_STATE_VARIABLE:
self.add_variable_to_json(overshadowed_entry[2], json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"contract",
"in",
"self",
".",
"contracts",
":",
"shadows",
"=",
"self",
".",
"detect_shadowing_definitions",
"(",
"contract",
")",
"if",
"shadows",
":",
"for",
"shadow",
"in",
"shadows",
":",
"local_parent_name",
"=",
"shadow",
"[",
"1",
"]",
"local_variable",
"=",
"shadow",
"[",
"2",
"]",
"overshadowed",
"=",
"shadow",
"[",
"3",
"]",
"info",
"=",
"'{}.{}.{} (local variable @ {}) shadows:\\n'",
".",
"format",
"(",
"contract",
".",
"name",
",",
"local_parent_name",
",",
"local_variable",
".",
"name",
",",
"local_variable",
".",
"source_mapping_str",
")",
"for",
"overshadowed_entry",
"in",
"overshadowed",
":",
"info",
"+=",
"\"\\t- {}.{} ({} @ {})\\n\"",
".",
"format",
"(",
"overshadowed_entry",
"[",
"1",
"]",
",",
"overshadowed_entry",
"[",
"2",
"]",
",",
"overshadowed_entry",
"[",
"0",
"]",
",",
"overshadowed_entry",
"[",
"2",
"]",
".",
"source_mapping_str",
")",
"# Generate relevant JSON data for this shadowing definition.",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_variable_to_json",
"(",
"local_variable",
",",
"json",
")",
"for",
"overshadowed_entry",
"in",
"overshadowed",
":",
"if",
"overshadowed_entry",
"[",
"0",
"]",
"in",
"[",
"self",
".",
"OVERSHADOWED_FUNCTION",
",",
"self",
".",
"OVERSHADOWED_MODIFIER",
",",
"self",
".",
"OVERSHADOWED_EVENT",
"]",
":",
"self",
".",
"add_function_to_json",
"(",
"overshadowed_entry",
"[",
"2",
"]",
",",
"json",
")",
"elif",
"overshadowed_entry",
"[",
"0",
"]",
"==",
"self",
".",
"OVERSHADOWED_STATE_VARIABLE",
":",
"self",
".",
"add_variable_to_json",
"(",
"overshadowed_entry",
"[",
"2",
"]",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect shadowing local variables
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'} | [
"Detect",
"shadowing",
"local",
"variables"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/shadowing/local.py#L92-L131 |
230,807 | crytic/slither | slither/detectors/variables/possible_const_state_variables.py | ConstCandidateStateVars._detect | def _detect(self):
""" Detect state variables that could be const
"""
results = []
all_info = ''
all_variables = [c.state_variables for c in self.slither.contracts]
all_variables = set([item for sublist in all_variables for item in sublist])
all_non_constant_elementary_variables = set([v for v in all_variables
if self._valid_candidate(v)])
all_functions = [c.all_functions_called for c in self.slither.contracts]
all_functions = list(set([item for sublist in all_functions for item in sublist]))
all_variables_written = [f.state_variables_written for f in all_functions]
all_variables_written = set([item for sublist in all_variables_written for item in sublist])
constable_variables = [v for v in all_non_constant_elementary_variables
if (not v in all_variables_written) and self._constant_initial_expression(v)]
# Order for deterministic results
constable_variables = sorted(constable_variables, key=lambda x: x.canonical_name)
for v in constable_variables:
info = "{}.{} should be constant ({})\n".format(v.contract.name,
v.name,
v.source_mapping_str)
all_info += info
if all_info != '':
json = self.generate_json_result(all_info)
self.add_variables_to_json(constable_variables, json)
results.append(json)
return results | python | def _detect(self):
""" Detect state variables that could be const
"""
results = []
all_info = ''
all_variables = [c.state_variables for c in self.slither.contracts]
all_variables = set([item for sublist in all_variables for item in sublist])
all_non_constant_elementary_variables = set([v for v in all_variables
if self._valid_candidate(v)])
all_functions = [c.all_functions_called for c in self.slither.contracts]
all_functions = list(set([item for sublist in all_functions for item in sublist]))
all_variables_written = [f.state_variables_written for f in all_functions]
all_variables_written = set([item for sublist in all_variables_written for item in sublist])
constable_variables = [v for v in all_non_constant_elementary_variables
if (not v in all_variables_written) and self._constant_initial_expression(v)]
# Order for deterministic results
constable_variables = sorted(constable_variables, key=lambda x: x.canonical_name)
for v in constable_variables:
info = "{}.{} should be constant ({})\n".format(v.contract.name,
v.name,
v.source_mapping_str)
all_info += info
if all_info != '':
json = self.generate_json_result(all_info)
self.add_variables_to_json(constable_variables, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"all_info",
"=",
"''",
"all_variables",
"=",
"[",
"c",
".",
"state_variables",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts",
"]",
"all_variables",
"=",
"set",
"(",
"[",
"item",
"for",
"sublist",
"in",
"all_variables",
"for",
"item",
"in",
"sublist",
"]",
")",
"all_non_constant_elementary_variables",
"=",
"set",
"(",
"[",
"v",
"for",
"v",
"in",
"all_variables",
"if",
"self",
".",
"_valid_candidate",
"(",
"v",
")",
"]",
")",
"all_functions",
"=",
"[",
"c",
".",
"all_functions_called",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts",
"]",
"all_functions",
"=",
"list",
"(",
"set",
"(",
"[",
"item",
"for",
"sublist",
"in",
"all_functions",
"for",
"item",
"in",
"sublist",
"]",
")",
")",
"all_variables_written",
"=",
"[",
"f",
".",
"state_variables_written",
"for",
"f",
"in",
"all_functions",
"]",
"all_variables_written",
"=",
"set",
"(",
"[",
"item",
"for",
"sublist",
"in",
"all_variables_written",
"for",
"item",
"in",
"sublist",
"]",
")",
"constable_variables",
"=",
"[",
"v",
"for",
"v",
"in",
"all_non_constant_elementary_variables",
"if",
"(",
"not",
"v",
"in",
"all_variables_written",
")",
"and",
"self",
".",
"_constant_initial_expression",
"(",
"v",
")",
"]",
"# Order for deterministic results",
"constable_variables",
"=",
"sorted",
"(",
"constable_variables",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
".",
"canonical_name",
")",
"for",
"v",
"in",
"constable_variables",
":",
"info",
"=",
"\"{}.{} should be constant ({})\\n\"",
".",
"format",
"(",
"v",
".",
"contract",
".",
"name",
",",
"v",
".",
"name",
",",
"v",
".",
"source_mapping_str",
")",
"all_info",
"+=",
"info",
"if",
"all_info",
"!=",
"''",
":",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"all_info",
")",
"self",
".",
"add_variables_to_json",
"(",
"constable_variables",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect state variables that could be const | [
"Detect",
"state",
"variables",
"that",
"could",
"be",
"const"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/variables/possible_const_state_variables.py#L66-L96 |
230,808 | crytic/slither | slither/detectors/functions/suicidal.py | Suicidal.detect_suicidal_func | def detect_suicidal_func(func):
""" Detect if the function is suicidal
Detect the public functions calling suicide/selfdestruct without protection
Returns:
(bool): True if the function is suicidal
"""
if func.is_constructor:
return False
if func.visibility != 'public':
return False
calls = [c.name for c in func.internal_calls]
if not ('suicide(address)' in calls or 'selfdestruct(address)' in calls):
return False
if func.is_protected():
return False
return True | python | def detect_suicidal_func(func):
""" Detect if the function is suicidal
Detect the public functions calling suicide/selfdestruct without protection
Returns:
(bool): True if the function is suicidal
"""
if func.is_constructor:
return False
if func.visibility != 'public':
return False
calls = [c.name for c in func.internal_calls]
if not ('suicide(address)' in calls or 'selfdestruct(address)' in calls):
return False
if func.is_protected():
return False
return True | [
"def",
"detect_suicidal_func",
"(",
"func",
")",
":",
"if",
"func",
".",
"is_constructor",
":",
"return",
"False",
"if",
"func",
".",
"visibility",
"!=",
"'public'",
":",
"return",
"False",
"calls",
"=",
"[",
"c",
".",
"name",
"for",
"c",
"in",
"func",
".",
"internal_calls",
"]",
"if",
"not",
"(",
"'suicide(address)'",
"in",
"calls",
"or",
"'selfdestruct(address)'",
"in",
"calls",
")",
":",
"return",
"False",
"if",
"func",
".",
"is_protected",
"(",
")",
":",
"return",
"False",
"return",
"True"
] | Detect if the function is suicidal
Detect the public functions calling suicide/selfdestruct without protection
Returns:
(bool): True if the function is suicidal | [
"Detect",
"if",
"the",
"function",
"is",
"suicidal"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/suicidal.py#L37-L58 |
230,809 | crytic/slither | slither/detectors/functions/suicidal.py | Suicidal._detect | def _detect(self):
""" Detect the suicidal functions
"""
results = []
for c in self.contracts:
functions = self.detect_suicidal(c)
for func in functions:
txt = "{}.{} ({}) allows anyone to destruct the contract\n"
info = txt.format(func.contract.name,
func.name,
func.source_mapping_str)
json = self.generate_json_result(info)
self.add_function_to_json(func, json)
results.append(json)
return results | python | def _detect(self):
""" Detect the suicidal functions
"""
results = []
for c in self.contracts:
functions = self.detect_suicidal(c)
for func in functions:
txt = "{}.{} ({}) allows anyone to destruct the contract\n"
info = txt.format(func.contract.name,
func.name,
func.source_mapping_str)
json = self.generate_json_result(info)
self.add_function_to_json(func, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"functions",
"=",
"self",
".",
"detect_suicidal",
"(",
"c",
")",
"for",
"func",
"in",
"functions",
":",
"txt",
"=",
"\"{}.{} ({}) allows anyone to destruct the contract\\n\"",
"info",
"=",
"txt",
".",
"format",
"(",
"func",
".",
"contract",
".",
"name",
",",
"func",
".",
"name",
",",
"func",
".",
"source_mapping_str",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_function_to_json",
"(",
"func",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect the suicidal functions | [
"Detect",
"the",
"suicidal",
"functions"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/suicidal.py#L67-L84 |
230,810 | crytic/slither | slither/detectors/operations/unused_return_values.py | UnusedReturnValues._detect | def _detect(self):
""" Detect high level calls which return a value that are never used
"""
results = []
for c in self.slither.contracts:
for f in c.functions + c.modifiers:
if f.contract != c:
continue
unused_return = self.detect_unused_return_values(f)
if unused_return:
info = "{}.{} ({}) does not use the value returned by external calls:\n"
info = info.format(f.contract.name,
f.name,
f.source_mapping_str)
for node in unused_return:
info += "\t-{} ({})\n".format(node.expression, node.source_mapping_str)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
self.add_nodes_to_json(unused_return, json)
results.append(json)
return results | python | def _detect(self):
""" Detect high level calls which return a value that are never used
"""
results = []
for c in self.slither.contracts:
for f in c.functions + c.modifiers:
if f.contract != c:
continue
unused_return = self.detect_unused_return_values(f)
if unused_return:
info = "{}.{} ({}) does not use the value returned by external calls:\n"
info = info.format(f.contract.name,
f.name,
f.source_mapping_str)
for node in unused_return:
info += "\t-{} ({})\n".format(node.expression, node.source_mapping_str)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
self.add_nodes_to_json(unused_return, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts",
":",
"for",
"f",
"in",
"c",
".",
"functions",
"+",
"c",
".",
"modifiers",
":",
"if",
"f",
".",
"contract",
"!=",
"c",
":",
"continue",
"unused_return",
"=",
"self",
".",
"detect_unused_return_values",
"(",
"f",
")",
"if",
"unused_return",
":",
"info",
"=",
"\"{}.{} ({}) does not use the value returned by external calls:\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"f",
".",
"contract",
".",
"name",
",",
"f",
".",
"name",
",",
"f",
".",
"source_mapping_str",
")",
"for",
"node",
"in",
"unused_return",
":",
"info",
"+=",
"\"\\t-{} ({})\\n\"",
".",
"format",
"(",
"node",
".",
"expression",
",",
"node",
".",
"source_mapping_str",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_function_to_json",
"(",
"f",
",",
"json",
")",
"self",
".",
"add_nodes_to_json",
"(",
"unused_return",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect high level calls which return a value that are never used | [
"Detect",
"high",
"level",
"calls",
"which",
"return",
"a",
"value",
"that",
"are",
"never",
"used"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/operations/unused_return_values.py#L61-L83 |
230,811 | crytic/slither | slither/printers/inheritance/inheritance_graph.py | PrinterInheritanceGraph._summary | def _summary(self, contract):
"""
Build summary using HTML
"""
ret = ''
# Add arrows (number them if there is more than one path so we know order of declaration for inheritance).
if len(contract.immediate_inheritance) == 1:
ret += '%s -> %s;\n' % (contract.name, contract.immediate_inheritance[0])
else:
for i in range(0, len(contract.immediate_inheritance)):
ret += '%s -> %s [ label="%s" ];\n' % (contract.name, contract.immediate_inheritance[i], i + 1)
# Functions
visibilities = ['public', 'external']
public_functions = [self._get_pattern_func(f, contract) for f in contract.functions if
not f.is_constructor and f.contract == contract and f.visibility in visibilities]
public_functions = ''.join(public_functions)
private_functions = [self._get_pattern_func(f, contract) for f in contract.functions if
not f.is_constructor and f.contract == contract and f.visibility not in visibilities]
private_functions = ''.join(private_functions)
# Modifiers
modifiers = [self._get_pattern_func(m, contract) for m in contract.modifiers if m.contract == contract]
modifiers = ''.join(modifiers)
# Public variables
public_variables = [self._get_pattern_var(v, contract) for v in contract.variables if
v.contract == contract and v.visibility in visibilities]
public_variables = ''.join(public_variables)
private_variables = [self._get_pattern_var(v, contract) for v in contract.variables if
v.contract == contract and v.visibility not in visibilities]
private_variables = ''.join(private_variables)
# Obtain any indirect shadowing information for this node.
indirect_shadowing_information = self._get_indirect_shadowing_information(contract)
# Build the node label
ret += '%s[shape="box"' % contract.name
ret += 'label=< <TABLE border="0">'
ret += '<TR><TD align="center"><B>%s</B></TD></TR>' % contract.name
if public_functions:
ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>'
ret += '%s' % public_functions
if private_functions:
ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>'
ret += '%s' % private_functions
if modifiers:
ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>'
ret += '%s' % modifiers
if public_variables:
ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>'
ret += '%s' % public_variables
if private_variables:
ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>'
ret += '%s' % private_variables
if indirect_shadowing_information:
ret += '<TR><TD><BR/></TD></TR><TR><TD align="left" border="1"><font color="#777777" point-size="10">%s</font></TD></TR>' % indirect_shadowing_information.replace('\n', '<BR/>')
ret += '</TABLE> >];\n'
return ret | python | def _summary(self, contract):
"""
Build summary using HTML
"""
ret = ''
# Add arrows (number them if there is more than one path so we know order of declaration for inheritance).
if len(contract.immediate_inheritance) == 1:
ret += '%s -> %s;\n' % (contract.name, contract.immediate_inheritance[0])
else:
for i in range(0, len(contract.immediate_inheritance)):
ret += '%s -> %s [ label="%s" ];\n' % (contract.name, contract.immediate_inheritance[i], i + 1)
# Functions
visibilities = ['public', 'external']
public_functions = [self._get_pattern_func(f, contract) for f in contract.functions if
not f.is_constructor and f.contract == contract and f.visibility in visibilities]
public_functions = ''.join(public_functions)
private_functions = [self._get_pattern_func(f, contract) for f in contract.functions if
not f.is_constructor and f.contract == contract and f.visibility not in visibilities]
private_functions = ''.join(private_functions)
# Modifiers
modifiers = [self._get_pattern_func(m, contract) for m in contract.modifiers if m.contract == contract]
modifiers = ''.join(modifiers)
# Public variables
public_variables = [self._get_pattern_var(v, contract) for v in contract.variables if
v.contract == contract and v.visibility in visibilities]
public_variables = ''.join(public_variables)
private_variables = [self._get_pattern_var(v, contract) for v in contract.variables if
v.contract == contract and v.visibility not in visibilities]
private_variables = ''.join(private_variables)
# Obtain any indirect shadowing information for this node.
indirect_shadowing_information = self._get_indirect_shadowing_information(contract)
# Build the node label
ret += '%s[shape="box"' % contract.name
ret += 'label=< <TABLE border="0">'
ret += '<TR><TD align="center"><B>%s</B></TD></TR>' % contract.name
if public_functions:
ret += '<TR><TD align="left"><I>Public Functions:</I></TD></TR>'
ret += '%s' % public_functions
if private_functions:
ret += '<TR><TD align="left"><I>Private Functions:</I></TD></TR>'
ret += '%s' % private_functions
if modifiers:
ret += '<TR><TD align="left"><I>Modifiers:</I></TD></TR>'
ret += '%s' % modifiers
if public_variables:
ret += '<TR><TD align="left"><I>Public Variables:</I></TD></TR>'
ret += '%s' % public_variables
if private_variables:
ret += '<TR><TD align="left"><I>Private Variables:</I></TD></TR>'
ret += '%s' % private_variables
if indirect_shadowing_information:
ret += '<TR><TD><BR/></TD></TR><TR><TD align="left" border="1"><font color="#777777" point-size="10">%s</font></TD></TR>' % indirect_shadowing_information.replace('\n', '<BR/>')
ret += '</TABLE> >];\n'
return ret | [
"def",
"_summary",
"(",
"self",
",",
"contract",
")",
":",
"ret",
"=",
"''",
"# Add arrows (number them if there is more than one path so we know order of declaration for inheritance).",
"if",
"len",
"(",
"contract",
".",
"immediate_inheritance",
")",
"==",
"1",
":",
"ret",
"+=",
"'%s -> %s;\\n'",
"%",
"(",
"contract",
".",
"name",
",",
"contract",
".",
"immediate_inheritance",
"[",
"0",
"]",
")",
"else",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"contract",
".",
"immediate_inheritance",
")",
")",
":",
"ret",
"+=",
"'%s -> %s [ label=\"%s\" ];\\n'",
"%",
"(",
"contract",
".",
"name",
",",
"contract",
".",
"immediate_inheritance",
"[",
"i",
"]",
",",
"i",
"+",
"1",
")",
"# Functions",
"visibilities",
"=",
"[",
"'public'",
",",
"'external'",
"]",
"public_functions",
"=",
"[",
"self",
".",
"_get_pattern_func",
"(",
"f",
",",
"contract",
")",
"for",
"f",
"in",
"contract",
".",
"functions",
"if",
"not",
"f",
".",
"is_constructor",
"and",
"f",
".",
"contract",
"==",
"contract",
"and",
"f",
".",
"visibility",
"in",
"visibilities",
"]",
"public_functions",
"=",
"''",
".",
"join",
"(",
"public_functions",
")",
"private_functions",
"=",
"[",
"self",
".",
"_get_pattern_func",
"(",
"f",
",",
"contract",
")",
"for",
"f",
"in",
"contract",
".",
"functions",
"if",
"not",
"f",
".",
"is_constructor",
"and",
"f",
".",
"contract",
"==",
"contract",
"and",
"f",
".",
"visibility",
"not",
"in",
"visibilities",
"]",
"private_functions",
"=",
"''",
".",
"join",
"(",
"private_functions",
")",
"# Modifiers",
"modifiers",
"=",
"[",
"self",
".",
"_get_pattern_func",
"(",
"m",
",",
"contract",
")",
"for",
"m",
"in",
"contract",
".",
"modifiers",
"if",
"m",
".",
"contract",
"==",
"contract",
"]",
"modifiers",
"=",
"''",
".",
"join",
"(",
"modifiers",
")",
"# Public variables",
"public_variables",
"=",
"[",
"self",
".",
"_get_pattern_var",
"(",
"v",
",",
"contract",
")",
"for",
"v",
"in",
"contract",
".",
"variables",
"if",
"v",
".",
"contract",
"==",
"contract",
"and",
"v",
".",
"visibility",
"in",
"visibilities",
"]",
"public_variables",
"=",
"''",
".",
"join",
"(",
"public_variables",
")",
"private_variables",
"=",
"[",
"self",
".",
"_get_pattern_var",
"(",
"v",
",",
"contract",
")",
"for",
"v",
"in",
"contract",
".",
"variables",
"if",
"v",
".",
"contract",
"==",
"contract",
"and",
"v",
".",
"visibility",
"not",
"in",
"visibilities",
"]",
"private_variables",
"=",
"''",
".",
"join",
"(",
"private_variables",
")",
"# Obtain any indirect shadowing information for this node.",
"indirect_shadowing_information",
"=",
"self",
".",
"_get_indirect_shadowing_information",
"(",
"contract",
")",
"# Build the node label",
"ret",
"+=",
"'%s[shape=\"box\"'",
"%",
"contract",
".",
"name",
"ret",
"+=",
"'label=< <TABLE border=\"0\">'",
"ret",
"+=",
"'<TR><TD align=\"center\"><B>%s</B></TD></TR>'",
"%",
"contract",
".",
"name",
"if",
"public_functions",
":",
"ret",
"+=",
"'<TR><TD align=\"left\"><I>Public Functions:</I></TD></TR>'",
"ret",
"+=",
"'%s'",
"%",
"public_functions",
"if",
"private_functions",
":",
"ret",
"+=",
"'<TR><TD align=\"left\"><I>Private Functions:</I></TD></TR>'",
"ret",
"+=",
"'%s'",
"%",
"private_functions",
"if",
"modifiers",
":",
"ret",
"+=",
"'<TR><TD align=\"left\"><I>Modifiers:</I></TD></TR>'",
"ret",
"+=",
"'%s'",
"%",
"modifiers",
"if",
"public_variables",
":",
"ret",
"+=",
"'<TR><TD align=\"left\"><I>Public Variables:</I></TD></TR>'",
"ret",
"+=",
"'%s'",
"%",
"public_variables",
"if",
"private_variables",
":",
"ret",
"+=",
"'<TR><TD align=\"left\"><I>Private Variables:</I></TD></TR>'",
"ret",
"+=",
"'%s'",
"%",
"private_variables",
"if",
"indirect_shadowing_information",
":",
"ret",
"+=",
"'<TR><TD><BR/></TD></TR><TR><TD align=\"left\" border=\"1\"><font color=\"#777777\" point-size=\"10\">%s</font></TD></TR>'",
"%",
"indirect_shadowing_information",
".",
"replace",
"(",
"'\\n'",
",",
"'<BR/>'",
")",
"ret",
"+=",
"'</TABLE> >];\\n'",
"return",
"ret"
] | Build summary using HTML | [
"Build",
"summary",
"using",
"HTML"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/inheritance/inheritance_graph.py#L103-L165 |
230,812 | crytic/slither | slither/detectors/shadowing/builtin_symbols.py | BuiltinSymbolShadowing.detect_builtin_shadowing_definitions | def detect_builtin_shadowing_definitions(self, contract):
""" Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local variable parent])"""
result = []
# Loop through all functions, modifiers, variables (state and local) to detect any built-in symbol keywords.
for function in contract.functions:
if function.contract == contract:
if self.is_builtin_symbol(function.name):
result.append((self.SHADOWING_FUNCTION, function, None))
result += self.detect_builtin_shadowing_locals(function)
for modifier in contract.modifiers:
if modifier.contract == contract:
if self.is_builtin_symbol(modifier.name):
result.append((self.SHADOWING_MODIFIER, modifier, None))
result += self.detect_builtin_shadowing_locals(modifier)
for variable in contract.variables:
if variable.contract == contract:
if self.is_builtin_symbol(variable.name):
result.append((self.SHADOWING_STATE_VARIABLE, variable, None))
for event in contract.events:
if event.contract == contract:
if self.is_builtin_symbol(event.name):
result.append((self.SHADOWING_EVENT, event, None))
return result | python | def detect_builtin_shadowing_definitions(self, contract):
""" Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local variable parent])"""
result = []
# Loop through all functions, modifiers, variables (state and local) to detect any built-in symbol keywords.
for function in contract.functions:
if function.contract == contract:
if self.is_builtin_symbol(function.name):
result.append((self.SHADOWING_FUNCTION, function, None))
result += self.detect_builtin_shadowing_locals(function)
for modifier in contract.modifiers:
if modifier.contract == contract:
if self.is_builtin_symbol(modifier.name):
result.append((self.SHADOWING_MODIFIER, modifier, None))
result += self.detect_builtin_shadowing_locals(modifier)
for variable in contract.variables:
if variable.contract == contract:
if self.is_builtin_symbol(variable.name):
result.append((self.SHADOWING_STATE_VARIABLE, variable, None))
for event in contract.events:
if event.contract == contract:
if self.is_builtin_symbol(event.name):
result.append((self.SHADOWING_EVENT, event, None))
return result | [
"def",
"detect_builtin_shadowing_definitions",
"(",
"self",
",",
"contract",
")",
":",
"result",
"=",
"[",
"]",
"# Loop through all functions, modifiers, variables (state and local) to detect any built-in symbol keywords.",
"for",
"function",
"in",
"contract",
".",
"functions",
":",
"if",
"function",
".",
"contract",
"==",
"contract",
":",
"if",
"self",
".",
"is_builtin_symbol",
"(",
"function",
".",
"name",
")",
":",
"result",
".",
"append",
"(",
"(",
"self",
".",
"SHADOWING_FUNCTION",
",",
"function",
",",
"None",
")",
")",
"result",
"+=",
"self",
".",
"detect_builtin_shadowing_locals",
"(",
"function",
")",
"for",
"modifier",
"in",
"contract",
".",
"modifiers",
":",
"if",
"modifier",
".",
"contract",
"==",
"contract",
":",
"if",
"self",
".",
"is_builtin_symbol",
"(",
"modifier",
".",
"name",
")",
":",
"result",
".",
"append",
"(",
"(",
"self",
".",
"SHADOWING_MODIFIER",
",",
"modifier",
",",
"None",
")",
")",
"result",
"+=",
"self",
".",
"detect_builtin_shadowing_locals",
"(",
"modifier",
")",
"for",
"variable",
"in",
"contract",
".",
"variables",
":",
"if",
"variable",
".",
"contract",
"==",
"contract",
":",
"if",
"self",
".",
"is_builtin_symbol",
"(",
"variable",
".",
"name",
")",
":",
"result",
".",
"append",
"(",
"(",
"self",
".",
"SHADOWING_STATE_VARIABLE",
",",
"variable",
",",
"None",
")",
")",
"for",
"event",
"in",
"contract",
".",
"events",
":",
"if",
"event",
".",
"contract",
"==",
"contract",
":",
"if",
"self",
".",
"is_builtin_symbol",
"(",
"event",
".",
"name",
")",
":",
"result",
".",
"append",
"(",
"(",
"self",
".",
"SHADOWING_EVENT",
",",
"event",
",",
"None",
")",
")",
"return",
"result"
] | Detects if functions, access modifiers, events, state variables, or local variables are named after built-in
symbols. Any such definitions are returned in a list.
Returns:
list of tuple: (type, definition, [local variable parent]) | [
"Detects",
"if",
"functions",
"access",
"modifiers",
"events",
"state",
"variables",
"or",
"local",
"variables",
"are",
"named",
"after",
"built",
"-",
"in",
"symbols",
".",
"Any",
"such",
"definitions",
"are",
"returned",
"in",
"a",
"list",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/shadowing/builtin_symbols.py#L83-L112 |
230,813 | crytic/slither | slither/detectors/shadowing/builtin_symbols.py | BuiltinSymbolShadowing._detect | def _detect(self):
""" Detect shadowing of built-in symbols
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_builtin_shadowing_definitions(contract)
if shadows:
for shadow in shadows:
# Obtain components
shadow_type = shadow[0]
shadow_object = shadow[1]
local_variable_parent = shadow[2]
# Build the path for our info string
local_variable_path = contract.name + "."
if local_variable_parent is not None:
local_variable_path += local_variable_parent.name + "."
local_variable_path += shadow_object.name
info = '{} ({} @ {}) shadows built-in symbol \"{}"\n'.format(local_variable_path,
shadow_type,
shadow_object.source_mapping_str,
shadow_object.name)
# Generate relevant JSON data for this shadowing definition.
json = self.generate_json_result(info)
if shadow_type in [self.SHADOWING_FUNCTION, self.SHADOWING_MODIFIER, self.SHADOWING_EVENT]:
self.add_function_to_json(shadow_object, json)
elif shadow_type in [self.SHADOWING_STATE_VARIABLE, self.SHADOWING_LOCAL_VARIABLE]:
self.add_variable_to_json(shadow_object, json)
results.append(json)
return results | python | def _detect(self):
""" Detect shadowing of built-in symbols
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'}
"""
results = []
for contract in self.contracts:
shadows = self.detect_builtin_shadowing_definitions(contract)
if shadows:
for shadow in shadows:
# Obtain components
shadow_type = shadow[0]
shadow_object = shadow[1]
local_variable_parent = shadow[2]
# Build the path for our info string
local_variable_path = contract.name + "."
if local_variable_parent is not None:
local_variable_path += local_variable_parent.name + "."
local_variable_path += shadow_object.name
info = '{} ({} @ {}) shadows built-in symbol \"{}"\n'.format(local_variable_path,
shadow_type,
shadow_object.source_mapping_str,
shadow_object.name)
# Generate relevant JSON data for this shadowing definition.
json = self.generate_json_result(info)
if shadow_type in [self.SHADOWING_FUNCTION, self.SHADOWING_MODIFIER, self.SHADOWING_EVENT]:
self.add_function_to_json(shadow_object, json)
elif shadow_type in [self.SHADOWING_STATE_VARIABLE, self.SHADOWING_LOCAL_VARIABLE]:
self.add_variable_to_json(shadow_object, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"contract",
"in",
"self",
".",
"contracts",
":",
"shadows",
"=",
"self",
".",
"detect_builtin_shadowing_definitions",
"(",
"contract",
")",
"if",
"shadows",
":",
"for",
"shadow",
"in",
"shadows",
":",
"# Obtain components",
"shadow_type",
"=",
"shadow",
"[",
"0",
"]",
"shadow_object",
"=",
"shadow",
"[",
"1",
"]",
"local_variable_parent",
"=",
"shadow",
"[",
"2",
"]",
"# Build the path for our info string",
"local_variable_path",
"=",
"contract",
".",
"name",
"+",
"\".\"",
"if",
"local_variable_parent",
"is",
"not",
"None",
":",
"local_variable_path",
"+=",
"local_variable_parent",
".",
"name",
"+",
"\".\"",
"local_variable_path",
"+=",
"shadow_object",
".",
"name",
"info",
"=",
"'{} ({} @ {}) shadows built-in symbol \\\"{}\"\\n'",
".",
"format",
"(",
"local_variable_path",
",",
"shadow_type",
",",
"shadow_object",
".",
"source_mapping_str",
",",
"shadow_object",
".",
"name",
")",
"# Generate relevant JSON data for this shadowing definition.",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"if",
"shadow_type",
"in",
"[",
"self",
".",
"SHADOWING_FUNCTION",
",",
"self",
".",
"SHADOWING_MODIFIER",
",",
"self",
".",
"SHADOWING_EVENT",
"]",
":",
"self",
".",
"add_function_to_json",
"(",
"shadow_object",
",",
"json",
")",
"elif",
"shadow_type",
"in",
"[",
"self",
".",
"SHADOWING_STATE_VARIABLE",
",",
"self",
".",
"SHADOWING_LOCAL_VARIABLE",
"]",
":",
"self",
".",
"add_variable_to_json",
"(",
"shadow_object",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect shadowing of built-in symbols
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func', 'shadow'} | [
"Detect",
"shadowing",
"of",
"built",
"-",
"in",
"symbols"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/shadowing/builtin_symbols.py#L114-L152 |
230,814 | crytic/slither | slither/utils/inheritance_analysis.py | detect_c3_function_shadowing | def detect_c3_function_shadowing(contract):
"""
Detects and obtains functions which are indirectly shadowed via multiple inheritance by C3 linearization
properties, despite not directly inheriting from each other.
:param contract: The contract to check for potential C3 linearization shadowing within.
:return: A list of list of tuples: (contract, function), where each inner list describes colliding functions.
The later elements in the inner list overshadow the earlier ones. The contract-function pair's function does not
need to be defined in its paired contract, it may have been inherited within it.
"""
# Loop through all contracts, and all underlying functions.
results = {}
for i in range(0, len(contract.immediate_inheritance) - 1):
inherited_contract1 = contract.immediate_inheritance[i]
for function1 in inherited_contract1.functions_and_modifiers:
# If this function has already be handled or is unimplemented, we skip it
if function1.full_name in results or function1.is_constructor or not function1.is_implemented:
continue
# Define our list of function instances which overshadow each other.
functions_matching = [(inherited_contract1, function1)]
already_processed = set([function1])
# Loop again through other contracts and functions to compare to.
for x in range(i + 1, len(contract.immediate_inheritance)):
inherited_contract2 = contract.immediate_inheritance[x]
# Loop for each function in this contract
for function2 in inherited_contract2.functions_and_modifiers:
# Skip this function if it is the last function that was shadowed.
if function2 in already_processed or function2.is_constructor or not function2.is_implemented:
continue
# If this function does have the same full name, it is shadowing through C3 linearization.
if function1.full_name == function2.full_name:
functions_matching.append((inherited_contract2, function2))
already_processed.add(function2)
# If we have more than one definition matching the same signature, we add it to the results.
if len(functions_matching) > 1:
results[function1.full_name] = functions_matching
return list(results.values()) | python | def detect_c3_function_shadowing(contract):
"""
Detects and obtains functions which are indirectly shadowed via multiple inheritance by C3 linearization
properties, despite not directly inheriting from each other.
:param contract: The contract to check for potential C3 linearization shadowing within.
:return: A list of list of tuples: (contract, function), where each inner list describes colliding functions.
The later elements in the inner list overshadow the earlier ones. The contract-function pair's function does not
need to be defined in its paired contract, it may have been inherited within it.
"""
# Loop through all contracts, and all underlying functions.
results = {}
for i in range(0, len(contract.immediate_inheritance) - 1):
inherited_contract1 = contract.immediate_inheritance[i]
for function1 in inherited_contract1.functions_and_modifiers:
# If this function has already be handled or is unimplemented, we skip it
if function1.full_name in results or function1.is_constructor or not function1.is_implemented:
continue
# Define our list of function instances which overshadow each other.
functions_matching = [(inherited_contract1, function1)]
already_processed = set([function1])
# Loop again through other contracts and functions to compare to.
for x in range(i + 1, len(contract.immediate_inheritance)):
inherited_contract2 = contract.immediate_inheritance[x]
# Loop for each function in this contract
for function2 in inherited_contract2.functions_and_modifiers:
# Skip this function if it is the last function that was shadowed.
if function2 in already_processed or function2.is_constructor or not function2.is_implemented:
continue
# If this function does have the same full name, it is shadowing through C3 linearization.
if function1.full_name == function2.full_name:
functions_matching.append((inherited_contract2, function2))
already_processed.add(function2)
# If we have more than one definition matching the same signature, we add it to the results.
if len(functions_matching) > 1:
results[function1.full_name] = functions_matching
return list(results.values()) | [
"def",
"detect_c3_function_shadowing",
"(",
"contract",
")",
":",
"# Loop through all contracts, and all underlying functions.",
"results",
"=",
"{",
"}",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"contract",
".",
"immediate_inheritance",
")",
"-",
"1",
")",
":",
"inherited_contract1",
"=",
"contract",
".",
"immediate_inheritance",
"[",
"i",
"]",
"for",
"function1",
"in",
"inherited_contract1",
".",
"functions_and_modifiers",
":",
"# If this function has already be handled or is unimplemented, we skip it",
"if",
"function1",
".",
"full_name",
"in",
"results",
"or",
"function1",
".",
"is_constructor",
"or",
"not",
"function1",
".",
"is_implemented",
":",
"continue",
"# Define our list of function instances which overshadow each other.",
"functions_matching",
"=",
"[",
"(",
"inherited_contract1",
",",
"function1",
")",
"]",
"already_processed",
"=",
"set",
"(",
"[",
"function1",
"]",
")",
"# Loop again through other contracts and functions to compare to.",
"for",
"x",
"in",
"range",
"(",
"i",
"+",
"1",
",",
"len",
"(",
"contract",
".",
"immediate_inheritance",
")",
")",
":",
"inherited_contract2",
"=",
"contract",
".",
"immediate_inheritance",
"[",
"x",
"]",
"# Loop for each function in this contract",
"for",
"function2",
"in",
"inherited_contract2",
".",
"functions_and_modifiers",
":",
"# Skip this function if it is the last function that was shadowed.",
"if",
"function2",
"in",
"already_processed",
"or",
"function2",
".",
"is_constructor",
"or",
"not",
"function2",
".",
"is_implemented",
":",
"continue",
"# If this function does have the same full name, it is shadowing through C3 linearization.",
"if",
"function1",
".",
"full_name",
"==",
"function2",
".",
"full_name",
":",
"functions_matching",
".",
"append",
"(",
"(",
"inherited_contract2",
",",
"function2",
")",
")",
"already_processed",
".",
"add",
"(",
"function2",
")",
"# If we have more than one definition matching the same signature, we add it to the results.",
"if",
"len",
"(",
"functions_matching",
")",
">",
"1",
":",
"results",
"[",
"function1",
".",
"full_name",
"]",
"=",
"functions_matching",
"return",
"list",
"(",
"results",
".",
"values",
"(",
")",
")"
] | Detects and obtains functions which are indirectly shadowed via multiple inheritance by C3 linearization
properties, despite not directly inheriting from each other.
:param contract: The contract to check for potential C3 linearization shadowing within.
:return: A list of list of tuples: (contract, function), where each inner list describes colliding functions.
The later elements in the inner list overshadow the earlier ones. The contract-function pair's function does not
need to be defined in its paired contract, it may have been inherited within it. | [
"Detects",
"and",
"obtains",
"functions",
"which",
"are",
"indirectly",
"shadowed",
"via",
"multiple",
"inheritance",
"by",
"C3",
"linearization",
"properties",
"despite",
"not",
"directly",
"inheriting",
"from",
"each",
"other",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/utils/inheritance_analysis.py#L6-L50 |
230,815 | crytic/slither | slither/detectors/variables/uninitialized_state_variables.py | UninitializedStateVarsDetection._detect | def _detect(self):
""" Detect uninitialized state variables
Recursively visit the calls
Returns:
dict: [contract name] = set(state variable uninitialized)
"""
results = []
for c in self.slither.contracts_derived:
ret = self.detect_uninitialized(c)
for variable, functions in ret:
info = "{}.{} ({}) is never initialized. It is used in:\n"
info = info.format(variable.contract.name,
variable.name,
variable.source_mapping_str)
for f in functions:
info += "\t- {} ({})\n".format(f.name, f.source_mapping_str)
source = [variable.source_mapping]
source += [f.source_mapping for f in functions]
json = self.generate_json_result(info)
self.add_variable_to_json(variable, json)
self.add_functions_to_json(functions, json)
results.append(json)
return results | python | def _detect(self):
""" Detect uninitialized state variables
Recursively visit the calls
Returns:
dict: [contract name] = set(state variable uninitialized)
"""
results = []
for c in self.slither.contracts_derived:
ret = self.detect_uninitialized(c)
for variable, functions in ret:
info = "{}.{} ({}) is never initialized. It is used in:\n"
info = info.format(variable.contract.name,
variable.name,
variable.source_mapping_str)
for f in functions:
info += "\t- {} ({})\n".format(f.name, f.source_mapping_str)
source = [variable.source_mapping]
source += [f.source_mapping for f in functions]
json = self.generate_json_result(info)
self.add_variable_to_json(variable, json)
self.add_functions_to_json(functions, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts_derived",
":",
"ret",
"=",
"self",
".",
"detect_uninitialized",
"(",
"c",
")",
"for",
"variable",
",",
"functions",
"in",
"ret",
":",
"info",
"=",
"\"{}.{} ({}) is never initialized. It is used in:\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"variable",
".",
"contract",
".",
"name",
",",
"variable",
".",
"name",
",",
"variable",
".",
"source_mapping_str",
")",
"for",
"f",
"in",
"functions",
":",
"info",
"+=",
"\"\\t- {} ({})\\n\"",
".",
"format",
"(",
"f",
".",
"name",
",",
"f",
".",
"source_mapping_str",
")",
"source",
"=",
"[",
"variable",
".",
"source_mapping",
"]",
"source",
"+=",
"[",
"f",
".",
"source_mapping",
"for",
"f",
"in",
"functions",
"]",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_variable_to_json",
"(",
"variable",
",",
"json",
")",
"self",
".",
"add_functions_to_json",
"(",
"functions",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect uninitialized state variables
Recursively visit the calls
Returns:
dict: [contract name] = set(state variable uninitialized) | [
"Detect",
"uninitialized",
"state",
"variables"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/variables/uninitialized_state_variables.py#L84-L110 |
230,816 | crytic/slither | slither/detectors/functions/external_function.py | ExternalFunction.detect_functions_called | def detect_functions_called(contract):
""" Returns a list of InternallCall, SolidityCall
calls made in a function
Returns:
(list): List of all InternallCall, SolidityCall
"""
result = []
# Obtain all functions reachable by this contract.
for func in contract.all_functions_called:
# Loop through all nodes in the function, add all calls to a list.
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalCall, SolidityCall)):
result.append(ir.function)
return result | python | def detect_functions_called(contract):
""" Returns a list of InternallCall, SolidityCall
calls made in a function
Returns:
(list): List of all InternallCall, SolidityCall
"""
result = []
# Obtain all functions reachable by this contract.
for func in contract.all_functions_called:
# Loop through all nodes in the function, add all calls to a list.
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalCall, SolidityCall)):
result.append(ir.function)
return result | [
"def",
"detect_functions_called",
"(",
"contract",
")",
":",
"result",
"=",
"[",
"]",
"# Obtain all functions reachable by this contract.",
"for",
"func",
"in",
"contract",
".",
"all_functions_called",
":",
"# Loop through all nodes in the function, add all calls to a list.",
"for",
"node",
"in",
"func",
".",
"nodes",
":",
"for",
"ir",
"in",
"node",
".",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"InternalCall",
",",
"SolidityCall",
")",
")",
":",
"result",
".",
"append",
"(",
"ir",
".",
"function",
")",
"return",
"result"
] | Returns a list of InternallCall, SolidityCall
calls made in a function
Returns:
(list): List of all InternallCall, SolidityCall | [
"Returns",
"a",
"list",
"of",
"InternallCall",
"SolidityCall",
"calls",
"made",
"in",
"a",
"function"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/external_function.py#L27-L43 |
230,817 | crytic/slither | slither/detectors/functions/external_function.py | ExternalFunction._contains_internal_dynamic_call | def _contains_internal_dynamic_call(contract):
"""
Checks if a contract contains a dynamic call either in a direct definition, or through inheritance.
Returns:
(boolean): True if this contract contains a dynamic call (including through inheritance).
"""
for func in contract.all_functions_called:
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalDynamicCall)):
return True
return False | python | def _contains_internal_dynamic_call(contract):
"""
Checks if a contract contains a dynamic call either in a direct definition, or through inheritance.
Returns:
(boolean): True if this contract contains a dynamic call (including through inheritance).
"""
for func in contract.all_functions_called:
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (InternalDynamicCall)):
return True
return False | [
"def",
"_contains_internal_dynamic_call",
"(",
"contract",
")",
":",
"for",
"func",
"in",
"contract",
".",
"all_functions_called",
":",
"for",
"node",
"in",
"func",
".",
"nodes",
":",
"for",
"ir",
"in",
"node",
".",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"InternalDynamicCall",
")",
")",
":",
"return",
"True",
"return",
"False"
] | Checks if a contract contains a dynamic call either in a direct definition, or through inheritance.
Returns:
(boolean): True if this contract contains a dynamic call (including through inheritance). | [
"Checks",
"if",
"a",
"contract",
"contains",
"a",
"dynamic",
"call",
"either",
"in",
"a",
"direct",
"definition",
"or",
"through",
"inheritance",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/external_function.py#L46-L58 |
230,818 | crytic/slither | slither/detectors/functions/external_function.py | ExternalFunction.get_base_most_function | def get_base_most_function(function):
"""
Obtains the base function definition for the provided function. This could be used to obtain the original
definition of a function, if the provided function is an override.
Returns:
(function): Returns the base-most function of a provided function. (The original definition).
"""
# Loop through the list of inherited contracts and this contract, to find the first function instance which
# matches this function's signature. Note here that `inheritance` is in order from most basic to most extended.
for contract in function.contract.inheritance + [function.contract]:
# Loop through the functions not inherited (explicitly defined in this contract).
for f in contract.functions_not_inherited:
# If it matches names, this is the base most function.
if f.full_name == function.full_name:
return f
# Somehow we couldn't resolve it, which shouldn't happen, as the provided function should be found if we could
# not find some any more basic.
raise Exception("Could not resolve the base-most function for the provided function.") | python | def get_base_most_function(function):
"""
Obtains the base function definition for the provided function. This could be used to obtain the original
definition of a function, if the provided function is an override.
Returns:
(function): Returns the base-most function of a provided function. (The original definition).
"""
# Loop through the list of inherited contracts and this contract, to find the first function instance which
# matches this function's signature. Note here that `inheritance` is in order from most basic to most extended.
for contract in function.contract.inheritance + [function.contract]:
# Loop through the functions not inherited (explicitly defined in this contract).
for f in contract.functions_not_inherited:
# If it matches names, this is the base most function.
if f.full_name == function.full_name:
return f
# Somehow we couldn't resolve it, which shouldn't happen, as the provided function should be found if we could
# not find some any more basic.
raise Exception("Could not resolve the base-most function for the provided function.") | [
"def",
"get_base_most_function",
"(",
"function",
")",
":",
"# Loop through the list of inherited contracts and this contract, to find the first function instance which",
"# matches this function's signature. Note here that `inheritance` is in order from most basic to most extended.",
"for",
"contract",
"in",
"function",
".",
"contract",
".",
"inheritance",
"+",
"[",
"function",
".",
"contract",
"]",
":",
"# Loop through the functions not inherited (explicitly defined in this contract).",
"for",
"f",
"in",
"contract",
".",
"functions_not_inherited",
":",
"# If it matches names, this is the base most function.",
"if",
"f",
".",
"full_name",
"==",
"function",
".",
"full_name",
":",
"return",
"f",
"# Somehow we couldn't resolve it, which shouldn't happen, as the provided function should be found if we could",
"# not find some any more basic.",
"raise",
"Exception",
"(",
"\"Could not resolve the base-most function for the provided function.\"",
")"
] | Obtains the base function definition for the provided function. This could be used to obtain the original
definition of a function, if the provided function is an override.
Returns:
(function): Returns the base-most function of a provided function. (The original definition). | [
"Obtains",
"the",
"base",
"function",
"definition",
"for",
"the",
"provided",
"function",
".",
"This",
"could",
"be",
"used",
"to",
"obtain",
"the",
"original",
"definition",
"of",
"a",
"function",
"if",
"the",
"provided",
"function",
"is",
"an",
"override",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/external_function.py#L61-L82 |
230,819 | crytic/slither | slither/detectors/functions/external_function.py | ExternalFunction.get_all_function_definitions | def get_all_function_definitions(base_most_function):
"""
Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions defined for it.
"""
# We assume the provided function is the base-most function, so we check all derived contracts
# for a redefinition
return [base_most_function] + [function for derived_contract in base_most_function.contract.derived_contracts
for function in derived_contract.functions
if function.full_name == base_most_function.full_name] | python | def get_all_function_definitions(base_most_function):
"""
Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions defined for it.
"""
# We assume the provided function is the base-most function, so we check all derived contracts
# for a redefinition
return [base_most_function] + [function for derived_contract in base_most_function.contract.derived_contracts
for function in derived_contract.functions
if function.full_name == base_most_function.full_name] | [
"def",
"get_all_function_definitions",
"(",
"base_most_function",
")",
":",
"# We assume the provided function is the base-most function, so we check all derived contracts",
"# for a redefinition",
"return",
"[",
"base_most_function",
"]",
"+",
"[",
"function",
"for",
"derived_contract",
"in",
"base_most_function",
".",
"contract",
".",
"derived_contracts",
"for",
"function",
"in",
"derived_contract",
".",
"functions",
"if",
"function",
".",
"full_name",
"==",
"base_most_function",
".",
"full_name",
"]"
] | Obtains all function definitions given a base-most function. This includes the provided function, plus any
overrides of that function.
Returns:
(list): Returns any the provided function and any overriding functions defined for it. | [
"Obtains",
"all",
"function",
"definitions",
"given",
"a",
"base",
"-",
"most",
"function",
".",
"This",
"includes",
"the",
"provided",
"function",
"plus",
"any",
"overrides",
"of",
"that",
"function",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/external_function.py#L85-L97 |
230,820 | crytic/slither | slither/detectors/functions/complex_function.py | ComplexFunction.detect_complex_func | def detect_complex_func(func):
"""Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7
"""
result = []
code_complexity = compute_cyclomatic_complexity(func)
if code_complexity > ComplexFunction.MAX_CYCLOMATIC_COMPLEXITY:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_CYCLOMATIC
})
"""Detect the number of external calls in the func
shouldn't be greater than 5
"""
count = 0
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (HighLevelCall, LowLevelCall, LibraryCall)):
count += 1
if count > ComplexFunction.MAX_EXTERNAL_CALLS:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_EXTERNAL_CALL
})
"""Checks the number of the state variables written
shouldn't be greater than 10
"""
if len(func.state_variables_written) > ComplexFunction.MAX_STATE_VARIABLES:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_STATE_VARS
})
return result | python | def detect_complex_func(func):
"""Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7
"""
result = []
code_complexity = compute_cyclomatic_complexity(func)
if code_complexity > ComplexFunction.MAX_CYCLOMATIC_COMPLEXITY:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_CYCLOMATIC
})
"""Detect the number of external calls in the func
shouldn't be greater than 5
"""
count = 0
for node in func.nodes:
for ir in node.irs:
if isinstance(ir, (HighLevelCall, LowLevelCall, LibraryCall)):
count += 1
if count > ComplexFunction.MAX_EXTERNAL_CALLS:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_EXTERNAL_CALL
})
"""Checks the number of the state variables written
shouldn't be greater than 10
"""
if len(func.state_variables_written) > ComplexFunction.MAX_STATE_VARIABLES:
result.append({
"func": func,
"cause": ComplexFunction.CAUSE_STATE_VARS
})
return result | [
"def",
"detect_complex_func",
"(",
"func",
")",
":",
"result",
"=",
"[",
"]",
"code_complexity",
"=",
"compute_cyclomatic_complexity",
"(",
"func",
")",
"if",
"code_complexity",
">",
"ComplexFunction",
".",
"MAX_CYCLOMATIC_COMPLEXITY",
":",
"result",
".",
"append",
"(",
"{",
"\"func\"",
":",
"func",
",",
"\"cause\"",
":",
"ComplexFunction",
".",
"CAUSE_CYCLOMATIC",
"}",
")",
"\"\"\"Detect the number of external calls in the func\n shouldn't be greater than 5\n \"\"\"",
"count",
"=",
"0",
"for",
"node",
"in",
"func",
".",
"nodes",
":",
"for",
"ir",
"in",
"node",
".",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"HighLevelCall",
",",
"LowLevelCall",
",",
"LibraryCall",
")",
")",
":",
"count",
"+=",
"1",
"if",
"count",
">",
"ComplexFunction",
".",
"MAX_EXTERNAL_CALLS",
":",
"result",
".",
"append",
"(",
"{",
"\"func\"",
":",
"func",
",",
"\"cause\"",
":",
"ComplexFunction",
".",
"CAUSE_EXTERNAL_CALL",
"}",
")",
"\"\"\"Checks the number of the state variables written\n shouldn't be greater than 10\n \"\"\"",
"if",
"len",
"(",
"func",
".",
"state_variables_written",
")",
">",
"ComplexFunction",
".",
"MAX_STATE_VARIABLES",
":",
"result",
".",
"append",
"(",
"{",
"\"func\"",
":",
"func",
",",
"\"cause\"",
":",
"ComplexFunction",
".",
"CAUSE_STATE_VARS",
"}",
")",
"return",
"result"
] | Detect the cyclomatic complexity of the contract functions
shouldn't be greater than 7 | [
"Detect",
"the",
"cyclomatic",
"complexity",
"of",
"the",
"contract",
"functions",
"shouldn",
"t",
"be",
"greater",
"than",
"7"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/functions/complex_function.py#L36-L73 |
230,821 | crytic/slither | slither/detectors/variables/unused_state_variables.py | UnusedStateVars._detect | def _detect(self):
""" Detect unused state variables
"""
results = []
for c in self.slither.contracts_derived:
unusedVars = self.detect_unused(c)
if unusedVars:
info = ''
for var in unusedVars:
info += "{}.{} ({}) is never used in {}\n".format(var.contract.name,
var.name,
var.source_mapping_str,
c.name)
json = self.generate_json_result(info)
self.add_variables_to_json(unusedVars, json)
results.append(json)
return results | python | def _detect(self):
""" Detect unused state variables
"""
results = []
for c in self.slither.contracts_derived:
unusedVars = self.detect_unused(c)
if unusedVars:
info = ''
for var in unusedVars:
info += "{}.{} ({}) is never used in {}\n".format(var.contract.name,
var.name,
var.source_mapping_str,
c.name)
json = self.generate_json_result(info)
self.add_variables_to_json(unusedVars, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"slither",
".",
"contracts_derived",
":",
"unusedVars",
"=",
"self",
".",
"detect_unused",
"(",
"c",
")",
"if",
"unusedVars",
":",
"info",
"=",
"''",
"for",
"var",
"in",
"unusedVars",
":",
"info",
"+=",
"\"{}.{} ({}) is never used in {}\\n\"",
".",
"format",
"(",
"var",
".",
"contract",
".",
"name",
",",
"var",
".",
"name",
",",
"var",
".",
"source_mapping_str",
",",
"c",
".",
"name",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_variables_to_json",
"(",
"unusedVars",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect unused state variables | [
"Detect",
"unused",
"state",
"variables"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/variables/unused_state_variables.py#L51-L70 |
230,822 | crytic/slither | slither/detectors/variables/uninitialized_local_variables.py | UninitializedLocalVars._detect | def _detect(self):
""" Detect uninitialized local variables
Recursively visit the calls
Returns:
dict: [contract name] = set(local variable uninitialized)
"""
results = []
self.results = []
self.visited_all_paths = {}
for contract in self.slither.contracts:
for function in contract.functions:
if function.is_implemented and function.contract == contract:
if function.contains_assembly:
continue
# dont consider storage variable, as they are detected by another detector
uninitialized_local_variables = [v for v in function.local_variables if not v.is_storage and v.uninitialized]
function.entry_point.context[self.key] = uninitialized_local_variables
self._detect_uninitialized(function, function.entry_point, [])
all_results = list(set(self.results))
for(function, uninitialized_local_variable) in all_results:
var_name = uninitialized_local_variable.name
info = "{} in {}.{} ({}) is a local variable never initialiazed\n"
info = info.format(var_name,
function.contract.name,
function.name,
uninitialized_local_variable.source_mapping_str)
json = self.generate_json_result(info)
self.add_variable_to_json(uninitialized_local_variable, json)
self.add_function_to_json(function, json)
results.append(json)
return results | python | def _detect(self):
""" Detect uninitialized local variables
Recursively visit the calls
Returns:
dict: [contract name] = set(local variable uninitialized)
"""
results = []
self.results = []
self.visited_all_paths = {}
for contract in self.slither.contracts:
for function in contract.functions:
if function.is_implemented and function.contract == contract:
if function.contains_assembly:
continue
# dont consider storage variable, as they are detected by another detector
uninitialized_local_variables = [v for v in function.local_variables if not v.is_storage and v.uninitialized]
function.entry_point.context[self.key] = uninitialized_local_variables
self._detect_uninitialized(function, function.entry_point, [])
all_results = list(set(self.results))
for(function, uninitialized_local_variable) in all_results:
var_name = uninitialized_local_variable.name
info = "{} in {}.{} ({}) is a local variable never initialiazed\n"
info = info.format(var_name,
function.contract.name,
function.name,
uninitialized_local_variable.source_mapping_str)
json = self.generate_json_result(info)
self.add_variable_to_json(uninitialized_local_variable, json)
self.add_function_to_json(function, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"self",
".",
"results",
"=",
"[",
"]",
"self",
".",
"visited_all_paths",
"=",
"{",
"}",
"for",
"contract",
"in",
"self",
".",
"slither",
".",
"contracts",
":",
"for",
"function",
"in",
"contract",
".",
"functions",
":",
"if",
"function",
".",
"is_implemented",
"and",
"function",
".",
"contract",
"==",
"contract",
":",
"if",
"function",
".",
"contains_assembly",
":",
"continue",
"# dont consider storage variable, as they are detected by another detector",
"uninitialized_local_variables",
"=",
"[",
"v",
"for",
"v",
"in",
"function",
".",
"local_variables",
"if",
"not",
"v",
".",
"is_storage",
"and",
"v",
".",
"uninitialized",
"]",
"function",
".",
"entry_point",
".",
"context",
"[",
"self",
".",
"key",
"]",
"=",
"uninitialized_local_variables",
"self",
".",
"_detect_uninitialized",
"(",
"function",
",",
"function",
".",
"entry_point",
",",
"[",
"]",
")",
"all_results",
"=",
"list",
"(",
"set",
"(",
"self",
".",
"results",
")",
")",
"for",
"(",
"function",
",",
"uninitialized_local_variable",
")",
"in",
"all_results",
":",
"var_name",
"=",
"uninitialized_local_variable",
".",
"name",
"info",
"=",
"\"{} in {}.{} ({}) is a local variable never initialiazed\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"var_name",
",",
"function",
".",
"contract",
".",
"name",
",",
"function",
".",
"name",
",",
"uninitialized_local_variable",
".",
"source_mapping_str",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_variable_to_json",
"(",
"uninitialized_local_variable",
",",
"json",
")",
"self",
".",
"add_function_to_json",
"(",
"function",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect uninitialized local variables
Recursively visit the calls
Returns:
dict: [contract name] = set(local variable uninitialized) | [
"Detect",
"uninitialized",
"local",
"variables"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/variables/uninitialized_local_variables.py#L79-L116 |
230,823 | crytic/slither | slither/detectors/erc20/unindexed_event_parameters.py | UnindexedERC20EventParameters._detect | def _detect(self):
"""
Detect un-indexed ERC20 event parameters in all contracts.
"""
results = []
for c in self.contracts:
unindexed_params = self.detect_erc20_unindexed_event_params(c)
if unindexed_params:
info = "{} ({}) does not mark important ERC20 parameters as 'indexed':\n"
info = info.format(c.name, c.source_mapping_str)
for (event, parameter) in unindexed_params:
info += "\t-{} ({}) does not index parameter '{}'\n".format(event.name, event.source_mapping_str, parameter.name)
# Add the events to the JSON (note: we do not add the params/vars as they have no source mapping).
json = self.generate_json_result(info)
self.add_functions_to_json([event for event, _ in unindexed_params], json)
results.append(json)
return results | python | def _detect(self):
"""
Detect un-indexed ERC20 event parameters in all contracts.
"""
results = []
for c in self.contracts:
unindexed_params = self.detect_erc20_unindexed_event_params(c)
if unindexed_params:
info = "{} ({}) does not mark important ERC20 parameters as 'indexed':\n"
info = info.format(c.name, c.source_mapping_str)
for (event, parameter) in unindexed_params:
info += "\t-{} ({}) does not index parameter '{}'\n".format(event.name, event.source_mapping_str, parameter.name)
# Add the events to the JSON (note: we do not add the params/vars as they have no source mapping).
json = self.generate_json_result(info)
self.add_functions_to_json([event for event, _ in unindexed_params], json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"unindexed_params",
"=",
"self",
".",
"detect_erc20_unindexed_event_params",
"(",
"c",
")",
"if",
"unindexed_params",
":",
"info",
"=",
"\"{} ({}) does not mark important ERC20 parameters as 'indexed':\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"c",
".",
"name",
",",
"c",
".",
"source_mapping_str",
")",
"for",
"(",
"event",
",",
"parameter",
")",
"in",
"unindexed_params",
":",
"info",
"+=",
"\"\\t-{} ({}) does not index parameter '{}'\\n\"",
".",
"format",
"(",
"event",
".",
"name",
",",
"event",
".",
"source_mapping_str",
",",
"parameter",
".",
"name",
")",
"# Add the events to the JSON (note: we do not add the params/vars as they have no source mapping).",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_functions_to_json",
"(",
"[",
"event",
"for",
"event",
",",
"_",
"in",
"unindexed_params",
"]",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect un-indexed ERC20 event parameters in all contracts. | [
"Detect",
"un",
"-",
"indexed",
"ERC20",
"event",
"parameters",
"in",
"all",
"contracts",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/erc20/unindexed_event_parameters.py#L67-L85 |
230,824 | crytic/slither | slither/core/slither_core.py | Slither.print_functions | def print_functions(self, d):
"""
Export all the functions to dot files
"""
for c in self.contracts:
for f in c.functions:
f.cfg_to_dot(os.path.join(d, '{}.{}.dot'.format(c.name, f.name))) | python | def print_functions(self, d):
"""
Export all the functions to dot files
"""
for c in self.contracts:
for f in c.functions:
f.cfg_to_dot(os.path.join(d, '{}.{}.dot'.format(c.name, f.name))) | [
"def",
"print_functions",
"(",
"self",
",",
"d",
")",
":",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"for",
"f",
"in",
"c",
".",
"functions",
":",
"f",
".",
"cfg_to_dot",
"(",
"os",
".",
"path",
".",
"join",
"(",
"d",
",",
"'{}.{}.dot'",
".",
"format",
"(",
"c",
".",
"name",
",",
"f",
".",
"name",
")",
")",
")"
] | Export all the functions to dot files | [
"Export",
"all",
"the",
"functions",
"to",
"dot",
"files"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/slither_core.py#L155-L161 |
230,825 | crytic/slither | slither/printers/inheritance/inheritance.py | PrinterInheritance.output | def output(self, filename):
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
info = 'Inheritance\n'
if not self.contracts:
return
info += blue('Child_Contract -> ') + green('Immediate_Base_Contracts')
info += green(' [Not_Immediate_Base_Contracts]')
for child in self.contracts:
info += blue(f'\n+ {child.name}')
if child.inheritance:
immediate = child.immediate_inheritance
not_immediate = [i for i in child.inheritance if i not in immediate]
info += ' -> ' + green(", ".join(map(str, immediate)))
if not_immediate:
info += ", ["+ green(", ".join(map(str, not_immediate))) + "]"
info += green('\n\nBase_Contract -> ') + blue('Immediate_Child_Contracts')
info += blue(' [Not_Immediate_Child_Contracts]')
for base in self.contracts:
info += green(f'\n+ {base.name}')
children = list(self._get_child_contracts(base))
if children:
immediate = [child for child in children if base in child.immediate_inheritance]
not_immediate = [child for child in children if not child in immediate]
info += ' -> ' + blue(", ".join(map(str, immediate)))
if not_immediate:
info += ', [' + blue(", ".join(map(str, not_immediate))) + ']'
self.info(info) | python | def output(self, filename):
"""
Output the inheritance relation
_filename is not used
Args:
_filename(string)
"""
info = 'Inheritance\n'
if not self.contracts:
return
info += blue('Child_Contract -> ') + green('Immediate_Base_Contracts')
info += green(' [Not_Immediate_Base_Contracts]')
for child in self.contracts:
info += blue(f'\n+ {child.name}')
if child.inheritance:
immediate = child.immediate_inheritance
not_immediate = [i for i in child.inheritance if i not in immediate]
info += ' -> ' + green(", ".join(map(str, immediate)))
if not_immediate:
info += ", ["+ green(", ".join(map(str, not_immediate))) + "]"
info += green('\n\nBase_Contract -> ') + blue('Immediate_Child_Contracts')
info += blue(' [Not_Immediate_Child_Contracts]')
for base in self.contracts:
info += green(f'\n+ {base.name}')
children = list(self._get_child_contracts(base))
if children:
immediate = [child for child in children if base in child.immediate_inheritance]
not_immediate = [child for child in children if not child in immediate]
info += ' -> ' + blue(", ".join(map(str, immediate)))
if not_immediate:
info += ', [' + blue(", ".join(map(str, not_immediate))) + ']'
self.info(info) | [
"def",
"output",
"(",
"self",
",",
"filename",
")",
":",
"info",
"=",
"'Inheritance\\n'",
"if",
"not",
"self",
".",
"contracts",
":",
"return",
"info",
"+=",
"blue",
"(",
"'Child_Contract -> '",
")",
"+",
"green",
"(",
"'Immediate_Base_Contracts'",
")",
"info",
"+=",
"green",
"(",
"' [Not_Immediate_Base_Contracts]'",
")",
"for",
"child",
"in",
"self",
".",
"contracts",
":",
"info",
"+=",
"blue",
"(",
"f'\\n+ {child.name}'",
")",
"if",
"child",
".",
"inheritance",
":",
"immediate",
"=",
"child",
".",
"immediate_inheritance",
"not_immediate",
"=",
"[",
"i",
"for",
"i",
"in",
"child",
".",
"inheritance",
"if",
"i",
"not",
"in",
"immediate",
"]",
"info",
"+=",
"' -> '",
"+",
"green",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"immediate",
")",
")",
")",
"if",
"not_immediate",
":",
"info",
"+=",
"\", [\"",
"+",
"green",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"not_immediate",
")",
")",
")",
"+",
"\"]\"",
"info",
"+=",
"green",
"(",
"'\\n\\nBase_Contract -> '",
")",
"+",
"blue",
"(",
"'Immediate_Child_Contracts'",
")",
"info",
"+=",
"blue",
"(",
"' [Not_Immediate_Child_Contracts]'",
")",
"for",
"base",
"in",
"self",
".",
"contracts",
":",
"info",
"+=",
"green",
"(",
"f'\\n+ {base.name}'",
")",
"children",
"=",
"list",
"(",
"self",
".",
"_get_child_contracts",
"(",
"base",
")",
")",
"if",
"children",
":",
"immediate",
"=",
"[",
"child",
"for",
"child",
"in",
"children",
"if",
"base",
"in",
"child",
".",
"immediate_inheritance",
"]",
"not_immediate",
"=",
"[",
"child",
"for",
"child",
"in",
"children",
"if",
"not",
"child",
"in",
"immediate",
"]",
"info",
"+=",
"' -> '",
"+",
"blue",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"immediate",
")",
")",
")",
"if",
"not_immediate",
":",
"info",
"+=",
"', ['",
"+",
"blue",
"(",
"\", \"",
".",
"join",
"(",
"map",
"(",
"str",
",",
"not_immediate",
")",
")",
")",
"+",
"']'",
"self",
".",
"info",
"(",
"info",
")"
] | Output the inheritance relation
_filename is not used
Args:
_filename(string) | [
"Output",
"the",
"inheritance",
"relation"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/printers/inheritance/inheritance.py#L23-L58 |
230,826 | crytic/slither | slither/detectors/variables/uninitialized_storage_variables.py | UninitializedStorageVars._detect | def _detect(self):
""" Detect uninitialized storage variables
Recursively visit the calls
Returns:
dict: [contract name] = set(storage variable uninitialized)
"""
results = []
self.results = []
self.visited_all_paths = {}
for contract in self.slither.contracts:
for function in contract.functions:
if function.is_implemented:
uninitialized_storage_variables = [v for v in function.local_variables if v.is_storage and v.uninitialized]
function.entry_point.context[self.key] = uninitialized_storage_variables
self._detect_uninitialized(function, function.entry_point, [])
for(function, uninitialized_storage_variable) in self.results:
var_name = uninitialized_storage_variable.name
info = "{} in {}.{} ({}) is a storage variable never initialiazed\n"
info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str)
json = self.generate_json_result(info)
self.add_variable_to_json(uninitialized_storage_variable, json)
self.add_function_to_json(function, json)
results.append(json)
return results | python | def _detect(self):
""" Detect uninitialized storage variables
Recursively visit the calls
Returns:
dict: [contract name] = set(storage variable uninitialized)
"""
results = []
self.results = []
self.visited_all_paths = {}
for contract in self.slither.contracts:
for function in contract.functions:
if function.is_implemented:
uninitialized_storage_variables = [v for v in function.local_variables if v.is_storage and v.uninitialized]
function.entry_point.context[self.key] = uninitialized_storage_variables
self._detect_uninitialized(function, function.entry_point, [])
for(function, uninitialized_storage_variable) in self.results:
var_name = uninitialized_storage_variable.name
info = "{} in {}.{} ({}) is a storage variable never initialiazed\n"
info = info.format(var_name, function.contract.name, function.name, uninitialized_storage_variable.source_mapping_str)
json = self.generate_json_result(info)
self.add_variable_to_json(uninitialized_storage_variable, json)
self.add_function_to_json(function, json)
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"self",
".",
"results",
"=",
"[",
"]",
"self",
".",
"visited_all_paths",
"=",
"{",
"}",
"for",
"contract",
"in",
"self",
".",
"slither",
".",
"contracts",
":",
"for",
"function",
"in",
"contract",
".",
"functions",
":",
"if",
"function",
".",
"is_implemented",
":",
"uninitialized_storage_variables",
"=",
"[",
"v",
"for",
"v",
"in",
"function",
".",
"local_variables",
"if",
"v",
".",
"is_storage",
"and",
"v",
".",
"uninitialized",
"]",
"function",
".",
"entry_point",
".",
"context",
"[",
"self",
".",
"key",
"]",
"=",
"uninitialized_storage_variables",
"self",
".",
"_detect_uninitialized",
"(",
"function",
",",
"function",
".",
"entry_point",
",",
"[",
"]",
")",
"for",
"(",
"function",
",",
"uninitialized_storage_variable",
")",
"in",
"self",
".",
"results",
":",
"var_name",
"=",
"uninitialized_storage_variable",
".",
"name",
"info",
"=",
"\"{} in {}.{} ({}) is a storage variable never initialiazed\\n\"",
"info",
"=",
"info",
".",
"format",
"(",
"var_name",
",",
"function",
".",
"contract",
".",
"name",
",",
"function",
".",
"name",
",",
"uninitialized_storage_variable",
".",
"source_mapping_str",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_variable_to_json",
"(",
"uninitialized_storage_variable",
",",
"json",
")",
"self",
".",
"add_function_to_json",
"(",
"function",
",",
"json",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect uninitialized storage variables
Recursively visit the calls
Returns:
dict: [contract name] = set(storage variable uninitialized) | [
"Detect",
"uninitialized",
"storage",
"variables"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/variables/uninitialized_storage_variables.py#L86-L117 |
230,827 | crytic/slither | slither/detectors/reentrancy/reentrancy.py | Reentrancy._can_callback | def _can_callback(self, irs):
"""
Detect if the node contains a call that can
be used to re-entrance
Consider as valid target:
- low level call
- high level call
Do not consider Send/Transfer as there is not enough gas
"""
for ir in irs:
if isinstance(ir, LowLevelCall):
return True
if isinstance(ir, HighLevelCall) and not isinstance(ir, LibraryCall):
# If solidity >0.5, STATICCALL is used
if self.slither.solc_version and self.slither.solc_version.startswith('0.5.'):
if isinstance(ir.function, Function) and (ir.function.view or ir.function.pure):
continue
if isinstance(ir.function, Variable):
continue
# If there is a call to itself
# We can check that the function called is
# reentrancy-safe
if ir.destination == SolidityVariable('this'):
if isinstance(ir.function, Variable):
continue
if not ir.function.all_high_level_calls():
if not ir.function.all_low_level_calls():
continue
return True
return False | python | def _can_callback(self, irs):
"""
Detect if the node contains a call that can
be used to re-entrance
Consider as valid target:
- low level call
- high level call
Do not consider Send/Transfer as there is not enough gas
"""
for ir in irs:
if isinstance(ir, LowLevelCall):
return True
if isinstance(ir, HighLevelCall) and not isinstance(ir, LibraryCall):
# If solidity >0.5, STATICCALL is used
if self.slither.solc_version and self.slither.solc_version.startswith('0.5.'):
if isinstance(ir.function, Function) and (ir.function.view or ir.function.pure):
continue
if isinstance(ir.function, Variable):
continue
# If there is a call to itself
# We can check that the function called is
# reentrancy-safe
if ir.destination == SolidityVariable('this'):
if isinstance(ir.function, Variable):
continue
if not ir.function.all_high_level_calls():
if not ir.function.all_low_level_calls():
continue
return True
return False | [
"def",
"_can_callback",
"(",
"self",
",",
"irs",
")",
":",
"for",
"ir",
"in",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"LowLevelCall",
")",
":",
"return",
"True",
"if",
"isinstance",
"(",
"ir",
",",
"HighLevelCall",
")",
"and",
"not",
"isinstance",
"(",
"ir",
",",
"LibraryCall",
")",
":",
"# If solidity >0.5, STATICCALL is used",
"if",
"self",
".",
"slither",
".",
"solc_version",
"and",
"self",
".",
"slither",
".",
"solc_version",
".",
"startswith",
"(",
"'0.5.'",
")",
":",
"if",
"isinstance",
"(",
"ir",
".",
"function",
",",
"Function",
")",
"and",
"(",
"ir",
".",
"function",
".",
"view",
"or",
"ir",
".",
"function",
".",
"pure",
")",
":",
"continue",
"if",
"isinstance",
"(",
"ir",
".",
"function",
",",
"Variable",
")",
":",
"continue",
"# If there is a call to itself",
"# We can check that the function called is",
"# reentrancy-safe",
"if",
"ir",
".",
"destination",
"==",
"SolidityVariable",
"(",
"'this'",
")",
":",
"if",
"isinstance",
"(",
"ir",
".",
"function",
",",
"Variable",
")",
":",
"continue",
"if",
"not",
"ir",
".",
"function",
".",
"all_high_level_calls",
"(",
")",
":",
"if",
"not",
"ir",
".",
"function",
".",
"all_low_level_calls",
"(",
")",
":",
"continue",
"return",
"True",
"return",
"False"
] | Detect if the node contains a call that can
be used to re-entrance
Consider as valid target:
- low level call
- high level call
Do not consider Send/Transfer as there is not enough gas | [
"Detect",
"if",
"the",
"node",
"contains",
"a",
"call",
"that",
"can",
"be",
"used",
"to",
"re",
"-",
"entrance"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/reentrancy/reentrancy.py#L37-L68 |
230,828 | crytic/slither | slither/detectors/reentrancy/reentrancy.py | Reentrancy._can_send_eth | def _can_send_eth(irs):
"""
Detect if the node can send eth
"""
for ir in irs:
if isinstance(ir, (HighLevelCall, LowLevelCall, Transfer, Send)):
if ir.call_value:
return True
return False | python | def _can_send_eth(irs):
"""
Detect if the node can send eth
"""
for ir in irs:
if isinstance(ir, (HighLevelCall, LowLevelCall, Transfer, Send)):
if ir.call_value:
return True
return False | [
"def",
"_can_send_eth",
"(",
"irs",
")",
":",
"for",
"ir",
"in",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"HighLevelCall",
",",
"LowLevelCall",
",",
"Transfer",
",",
"Send",
")",
")",
":",
"if",
"ir",
".",
"call_value",
":",
"return",
"True",
"return",
"False"
] | Detect if the node can send eth | [
"Detect",
"if",
"the",
"node",
"can",
"send",
"eth"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/reentrancy/reentrancy.py#L71-L79 |
230,829 | crytic/slither | slither/core/cfg/node.py | Node.remove_father | def remove_father(self, father):
""" Remove the father node. Do nothing if the node is not a father
Args:
fathers: list of fathers to add
"""
self._fathers = [x for x in self._fathers if x.node_id != father.node_id] | python | def remove_father(self, father):
""" Remove the father node. Do nothing if the node is not a father
Args:
fathers: list of fathers to add
"""
self._fathers = [x for x in self._fathers if x.node_id != father.node_id] | [
"def",
"remove_father",
"(",
"self",
",",
"father",
")",
":",
"self",
".",
"_fathers",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_fathers",
"if",
"x",
".",
"node_id",
"!=",
"father",
".",
"node_id",
"]"
] | Remove the father node. Do nothing if the node is not a father
Args:
fathers: list of fathers to add | [
"Remove",
"the",
"father",
"node",
".",
"Do",
"nothing",
"if",
"the",
"node",
"is",
"not",
"a",
"father"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/cfg/node.py#L485-L491 |
230,830 | crytic/slither | slither/core/cfg/node.py | Node.remove_son | def remove_son(self, son):
""" Remove the son node. Do nothing if the node is not a son
Args:
fathers: list of fathers to add
"""
self._sons = [x for x in self._sons if x.node_id != son.node_id] | python | def remove_son(self, son):
""" Remove the son node. Do nothing if the node is not a son
Args:
fathers: list of fathers to add
"""
self._sons = [x for x in self._sons if x.node_id != son.node_id] | [
"def",
"remove_son",
"(",
"self",
",",
"son",
")",
":",
"self",
".",
"_sons",
"=",
"[",
"x",
"for",
"x",
"in",
"self",
".",
"_sons",
"if",
"x",
".",
"node_id",
"!=",
"son",
".",
"node_id",
"]"
] | Remove the son node. Do nothing if the node is not a son
Args:
fathers: list of fathers to add | [
"Remove",
"the",
"son",
"node",
".",
"Do",
"nothing",
"if",
"the",
"node",
"is",
"not",
"a",
"son"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/cfg/node.py#L493-L499 |
230,831 | crytic/slither | slither/detectors/statements/deprecated_calls.py | DeprecatedStandards.detect_deprecated_references_in_node | def detect_deprecated_references_in_node(self, node):
""" Detects if a node makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text)"""
# Define our results list
results = []
# If this node has an expression, we check the underlying expression.
if node.expression:
results += self.detect_deprecation_in_expression(node.expression)
# Check if there is usage of any deprecated solidity variables or functions
for dep_node in self.DEPRECATED_NODE_TYPES:
if node.type == dep_node[0]:
results.append(dep_node)
return results | python | def detect_deprecated_references_in_node(self, node):
""" Detects if a node makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text)"""
# Define our results list
results = []
# If this node has an expression, we check the underlying expression.
if node.expression:
results += self.detect_deprecation_in_expression(node.expression)
# Check if there is usage of any deprecated solidity variables or functions
for dep_node in self.DEPRECATED_NODE_TYPES:
if node.type == dep_node[0]:
results.append(dep_node)
return results | [
"def",
"detect_deprecated_references_in_node",
"(",
"self",
",",
"node",
")",
":",
"# Define our results list",
"results",
"=",
"[",
"]",
"# If this node has an expression, we check the underlying expression.",
"if",
"node",
".",
"expression",
":",
"results",
"+=",
"self",
".",
"detect_deprecation_in_expression",
"(",
"node",
".",
"expression",
")",
"# Check if there is usage of any deprecated solidity variables or functions",
"for",
"dep_node",
"in",
"self",
".",
"DEPRECATED_NODE_TYPES",
":",
"if",
"node",
".",
"type",
"==",
"dep_node",
"[",
"0",
"]",
":",
"results",
".",
"append",
"(",
"dep_node",
")",
"return",
"results"
] | Detects if a node makes use of any deprecated standards.
Returns:
list of tuple: (detecting_signature, original_text, recommended_text) | [
"Detects",
"if",
"a",
"node",
"makes",
"use",
"of",
"any",
"deprecated",
"standards",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/statements/deprecated_calls.py#L88-L105 |
230,832 | crytic/slither | slither/detectors/statements/deprecated_calls.py | DeprecatedStandards.detect_deprecated_references_in_contract | def detect_deprecated_references_in_contract(self, contract):
""" Detects the usage of any deprecated built-in symbols.
Returns:
list of tuple: (state_variable | node, (detecting_signature, original_text, recommended_text))"""
results = []
for state_variable in contract.variables:
if state_variable.contract != contract:
continue
if state_variable.expression:
deprecated_results = self.detect_deprecation_in_expression(state_variable.expression)
if deprecated_results:
results.append((state_variable, deprecated_results))
# Loop through all functions + modifiers in this contract.
for function in contract.functions + contract.modifiers:
# We should only look for functions declared directly in this contract (not in a base contract).
if function.contract != contract:
continue
# Loop through each node in this function.
for node in function.nodes:
# Detect deprecated references in the node.
deprecated_results = self.detect_deprecated_references_in_node(node)
# Detect additional deprecated low-level-calls.
for ir in node.irs:
if isinstance(ir, LowLevelCall):
for dep_llc in self.DEPRECATED_LOW_LEVEL_CALLS:
if ir.function_name == dep_llc[0]:
deprecated_results.append(dep_llc)
# If we have any results from this iteration, add them to our results list.
if deprecated_results:
results.append((node, deprecated_results))
return results | python | def detect_deprecated_references_in_contract(self, contract):
""" Detects the usage of any deprecated built-in symbols.
Returns:
list of tuple: (state_variable | node, (detecting_signature, original_text, recommended_text))"""
results = []
for state_variable in contract.variables:
if state_variable.contract != contract:
continue
if state_variable.expression:
deprecated_results = self.detect_deprecation_in_expression(state_variable.expression)
if deprecated_results:
results.append((state_variable, deprecated_results))
# Loop through all functions + modifiers in this contract.
for function in contract.functions + contract.modifiers:
# We should only look for functions declared directly in this contract (not in a base contract).
if function.contract != contract:
continue
# Loop through each node in this function.
for node in function.nodes:
# Detect deprecated references in the node.
deprecated_results = self.detect_deprecated_references_in_node(node)
# Detect additional deprecated low-level-calls.
for ir in node.irs:
if isinstance(ir, LowLevelCall):
for dep_llc in self.DEPRECATED_LOW_LEVEL_CALLS:
if ir.function_name == dep_llc[0]:
deprecated_results.append(dep_llc)
# If we have any results from this iteration, add them to our results list.
if deprecated_results:
results.append((node, deprecated_results))
return results | [
"def",
"detect_deprecated_references_in_contract",
"(",
"self",
",",
"contract",
")",
":",
"results",
"=",
"[",
"]",
"for",
"state_variable",
"in",
"contract",
".",
"variables",
":",
"if",
"state_variable",
".",
"contract",
"!=",
"contract",
":",
"continue",
"if",
"state_variable",
".",
"expression",
":",
"deprecated_results",
"=",
"self",
".",
"detect_deprecation_in_expression",
"(",
"state_variable",
".",
"expression",
")",
"if",
"deprecated_results",
":",
"results",
".",
"append",
"(",
"(",
"state_variable",
",",
"deprecated_results",
")",
")",
"# Loop through all functions + modifiers in this contract.",
"for",
"function",
"in",
"contract",
".",
"functions",
"+",
"contract",
".",
"modifiers",
":",
"# We should only look for functions declared directly in this contract (not in a base contract).",
"if",
"function",
".",
"contract",
"!=",
"contract",
":",
"continue",
"# Loop through each node in this function.",
"for",
"node",
"in",
"function",
".",
"nodes",
":",
"# Detect deprecated references in the node.",
"deprecated_results",
"=",
"self",
".",
"detect_deprecated_references_in_node",
"(",
"node",
")",
"# Detect additional deprecated low-level-calls.",
"for",
"ir",
"in",
"node",
".",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"LowLevelCall",
")",
":",
"for",
"dep_llc",
"in",
"self",
".",
"DEPRECATED_LOW_LEVEL_CALLS",
":",
"if",
"ir",
".",
"function_name",
"==",
"dep_llc",
"[",
"0",
"]",
":",
"deprecated_results",
".",
"append",
"(",
"dep_llc",
")",
"# If we have any results from this iteration, add them to our results list.",
"if",
"deprecated_results",
":",
"results",
".",
"append",
"(",
"(",
"node",
",",
"deprecated_results",
")",
")",
"return",
"results"
] | Detects the usage of any deprecated built-in symbols.
Returns:
list of tuple: (state_variable | node, (detecting_signature, original_text, recommended_text)) | [
"Detects",
"the",
"usage",
"of",
"any",
"deprecated",
"built",
"-",
"in",
"symbols",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/statements/deprecated_calls.py#L107-L144 |
230,833 | crytic/slither | slither/__main__.py | process | def process(filename, args, detector_classes, printer_classes):
"""
The core high-level code for running Slither static analysis.
Returns:
list(result), int: Result list and number of contracts analyzed
"""
ast = '--ast-compact-json'
if args.legacy_ast:
ast = '--ast-json'
args.filter_paths = parse_filter_paths(args)
slither = Slither(filename,
ast_format=ast,
**vars(args))
return _process(slither, detector_classes, printer_classes) | python | def process(filename, args, detector_classes, printer_classes):
"""
The core high-level code for running Slither static analysis.
Returns:
list(result), int: Result list and number of contracts analyzed
"""
ast = '--ast-compact-json'
if args.legacy_ast:
ast = '--ast-json'
args.filter_paths = parse_filter_paths(args)
slither = Slither(filename,
ast_format=ast,
**vars(args))
return _process(slither, detector_classes, printer_classes) | [
"def",
"process",
"(",
"filename",
",",
"args",
",",
"detector_classes",
",",
"printer_classes",
")",
":",
"ast",
"=",
"'--ast-compact-json'",
"if",
"args",
".",
"legacy_ast",
":",
"ast",
"=",
"'--ast-json'",
"args",
".",
"filter_paths",
"=",
"parse_filter_paths",
"(",
"args",
")",
"slither",
"=",
"Slither",
"(",
"filename",
",",
"ast_format",
"=",
"ast",
",",
"*",
"*",
"vars",
"(",
"args",
")",
")",
"return",
"_process",
"(",
"slither",
",",
"detector_classes",
",",
"printer_classes",
")"
] | The core high-level code for running Slither static analysis.
Returns:
list(result), int: Result list and number of contracts analyzed | [
"The",
"core",
"high",
"-",
"level",
"code",
"for",
"running",
"Slither",
"static",
"analysis",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/__main__.py#L38-L53 |
230,834 | crytic/slither | slither/detectors/attributes/const_functions.py | ConstantFunctions._detect | def _detect(self):
""" Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'}
"""
results = []
for c in self.contracts:
for f in c.functions:
if f.contract != c:
continue
if f.view or f.pure:
if f.contains_assembly:
attr = 'view' if f.view else 'pure'
info = '{}.{} ({}) is declared {} but contains assembly code\n'
info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
json['elements'].append({'type': 'info',
'contains_assembly' : True})
results.append(json)
variables_written = f.all_state_variables_written()
if variables_written:
attr = 'view' if f.view else 'pure'
info = '{}.{} ({}) is declared {} but changes state variables:\n'
info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
for variable_written in variables_written:
info += '\t- {}.{}\n'.format(variable_written.contract.name,
variable_written.name)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
self.add_variables_to_json(variables_written, json)
json['elements'].append({'type': 'info',
'contains_assembly' : False})
results.append(json)
return results | python | def _detect(self):
""" Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'}
"""
results = []
for c in self.contracts:
for f in c.functions:
if f.contract != c:
continue
if f.view or f.pure:
if f.contains_assembly:
attr = 'view' if f.view else 'pure'
info = '{}.{} ({}) is declared {} but contains assembly code\n'
info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
json['elements'].append({'type': 'info',
'contains_assembly' : True})
results.append(json)
variables_written = f.all_state_variables_written()
if variables_written:
attr = 'view' if f.view else 'pure'
info = '{}.{} ({}) is declared {} but changes state variables:\n'
info = info.format(f.contract.name, f.name, f.source_mapping_str, attr)
for variable_written in variables_written:
info += '\t- {}.{}\n'.format(variable_written.contract.name,
variable_written.name)
json = self.generate_json_result(info)
self.add_function_to_json(f, json)
self.add_variables_to_json(variables_written, json)
json['elements'].append({'type': 'info',
'contains_assembly' : False})
results.append(json)
return results | [
"def",
"_detect",
"(",
"self",
")",
":",
"results",
"=",
"[",
"]",
"for",
"c",
"in",
"self",
".",
"contracts",
":",
"for",
"f",
"in",
"c",
".",
"functions",
":",
"if",
"f",
".",
"contract",
"!=",
"c",
":",
"continue",
"if",
"f",
".",
"view",
"or",
"f",
".",
"pure",
":",
"if",
"f",
".",
"contains_assembly",
":",
"attr",
"=",
"'view'",
"if",
"f",
".",
"view",
"else",
"'pure'",
"info",
"=",
"'{}.{} ({}) is declared {} but contains assembly code\\n'",
"info",
"=",
"info",
".",
"format",
"(",
"f",
".",
"contract",
".",
"name",
",",
"f",
".",
"name",
",",
"f",
".",
"source_mapping_str",
",",
"attr",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_function_to_json",
"(",
"f",
",",
"json",
")",
"json",
"[",
"'elements'",
"]",
".",
"append",
"(",
"{",
"'type'",
":",
"'info'",
",",
"'contains_assembly'",
":",
"True",
"}",
")",
"results",
".",
"append",
"(",
"json",
")",
"variables_written",
"=",
"f",
".",
"all_state_variables_written",
"(",
")",
"if",
"variables_written",
":",
"attr",
"=",
"'view'",
"if",
"f",
".",
"view",
"else",
"'pure'",
"info",
"=",
"'{}.{} ({}) is declared {} but changes state variables:\\n'",
"info",
"=",
"info",
".",
"format",
"(",
"f",
".",
"contract",
".",
"name",
",",
"f",
".",
"name",
",",
"f",
".",
"source_mapping_str",
",",
"attr",
")",
"for",
"variable_written",
"in",
"variables_written",
":",
"info",
"+=",
"'\\t- {}.{}\\n'",
".",
"format",
"(",
"variable_written",
".",
"contract",
".",
"name",
",",
"variable_written",
".",
"name",
")",
"json",
"=",
"self",
".",
"generate_json_result",
"(",
"info",
")",
"self",
".",
"add_function_to_json",
"(",
"f",
",",
"json",
")",
"self",
".",
"add_variables_to_json",
"(",
"variables_written",
",",
"json",
")",
"json",
"[",
"'elements'",
"]",
".",
"append",
"(",
"{",
"'type'",
":",
"'info'",
",",
"'contains_assembly'",
":",
"False",
"}",
")",
"results",
".",
"append",
"(",
"json",
")",
"return",
"results"
] | Detect the constant function changing the state
Recursively visit the calls
Returns:
list: {'vuln', 'filename,'contract','func','#varsWritten'} | [
"Detect",
"the",
"constant",
"function",
"changing",
"the",
"state"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/detectors/attributes/const_functions.py#L44-L84 |
230,835 | crytic/slither | slither/core/declarations/contract.py | Contract.constructor | def constructor(self):
'''
Return the contract's immediate constructor.
If there is no immediate constructor, returns the first constructor
executed, following the c3 linearization
Return None if there is no constructor.
'''
cst = self.constructor_not_inherited
if cst:
return cst
for inherited_contract in self.inheritance:
cst = inherited_contract.constructor_not_inherited
if cst:
return cst
return None | python | def constructor(self):
'''
Return the contract's immediate constructor.
If there is no immediate constructor, returns the first constructor
executed, following the c3 linearization
Return None if there is no constructor.
'''
cst = self.constructor_not_inherited
if cst:
return cst
for inherited_contract in self.inheritance:
cst = inherited_contract.constructor_not_inherited
if cst:
return cst
return None | [
"def",
"constructor",
"(",
"self",
")",
":",
"cst",
"=",
"self",
".",
"constructor_not_inherited",
"if",
"cst",
":",
"return",
"cst",
"for",
"inherited_contract",
"in",
"self",
".",
"inheritance",
":",
"cst",
"=",
"inherited_contract",
".",
"constructor_not_inherited",
"if",
"cst",
":",
"return",
"cst",
"return",
"None"
] | Return the contract's immediate constructor.
If there is no immediate constructor, returns the first constructor
executed, following the c3 linearization
Return None if there is no constructor. | [
"Return",
"the",
"contract",
"s",
"immediate",
"constructor",
".",
"If",
"there",
"is",
"no",
"immediate",
"constructor",
"returns",
"the",
"first",
"constructor",
"executed",
"following",
"the",
"c3",
"linearization",
"Return",
"None",
"if",
"there",
"is",
"no",
"constructor",
"."
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L168-L182 |
230,836 | crytic/slither | slither/core/declarations/contract.py | Contract.get_functions_reading_from_variable | def get_functions_reading_from_variable(self, variable):
'''
Return the functions reading the variable
'''
return [f for f in self.functions if f.is_reading(variable)] | python | def get_functions_reading_from_variable(self, variable):
'''
Return the functions reading the variable
'''
return [f for f in self.functions if f.is_reading(variable)] | [
"def",
"get_functions_reading_from_variable",
"(",
"self",
",",
"variable",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"functions",
"if",
"f",
".",
"is_reading",
"(",
"variable",
")",
"]"
] | Return the functions reading the variable | [
"Return",
"the",
"functions",
"reading",
"the",
"variable"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L339-L343 |
230,837 | crytic/slither | slither/core/declarations/contract.py | Contract.get_functions_writing_to_variable | def get_functions_writing_to_variable(self, variable):
'''
Return the functions writting the variable
'''
return [f for f in self.functions if f.is_writing(variable)] | python | def get_functions_writing_to_variable(self, variable):
'''
Return the functions writting the variable
'''
return [f for f in self.functions if f.is_writing(variable)] | [
"def",
"get_functions_writing_to_variable",
"(",
"self",
",",
"variable",
")",
":",
"return",
"[",
"f",
"for",
"f",
"in",
"self",
".",
"functions",
"if",
"f",
".",
"is_writing",
"(",
"variable",
")",
"]"
] | Return the functions writting the variable | [
"Return",
"the",
"functions",
"writting",
"the",
"variable"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L345-L349 |
230,838 | crytic/slither | slither/core/declarations/contract.py | Contract.get_source_var_declaration | def get_source_var_declaration(self, var):
""" Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.variables if x.name == var)) | python | def get_source_var_declaration(self, var):
""" Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.variables if x.name == var)) | [
"def",
"get_source_var_declaration",
"(",
"self",
",",
"var",
")",
":",
"return",
"next",
"(",
"(",
"x",
".",
"source_mapping",
"for",
"x",
"in",
"self",
".",
"variables",
"if",
"x",
".",
"name",
"==",
"var",
")",
")"
] | Return the source mapping where the variable is declared
Args:
var (str): variable name
Returns:
(dict): sourceMapping | [
"Return",
"the",
"source",
"mapping",
"where",
"the",
"variable",
"is",
"declared"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L351-L359 |
230,839 | crytic/slither | slither/core/declarations/contract.py | Contract.get_source_event_declaration | def get_source_event_declaration(self, event):
""" Return the source mapping where the event is declared
Args:
event (str): event name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.events if x.name == event)) | python | def get_source_event_declaration(self, event):
""" Return the source mapping where the event is declared
Args:
event (str): event name
Returns:
(dict): sourceMapping
"""
return next((x.source_mapping for x in self.events if x.name == event)) | [
"def",
"get_source_event_declaration",
"(",
"self",
",",
"event",
")",
":",
"return",
"next",
"(",
"(",
"x",
".",
"source_mapping",
"for",
"x",
"in",
"self",
".",
"events",
"if",
"x",
".",
"name",
"==",
"event",
")",
")"
] | Return the source mapping where the event is declared
Args:
event (str): event name
Returns:
(dict): sourceMapping | [
"Return",
"the",
"source",
"mapping",
"where",
"the",
"event",
"is",
"declared"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L361-L369 |
230,840 | crytic/slither | slither/core/declarations/contract.py | Contract.get_summary | def get_summary(self):
""" Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)
"""
func_summaries = [f.get_summary() for f in self.functions]
modif_summaries = [f.get_summary() for f in self.modifiers]
return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries) | python | def get_summary(self):
""" Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)
"""
func_summaries = [f.get_summary() for f in self.functions]
modif_summaries = [f.get_summary() for f in self.modifiers]
return (self.name, [str(x) for x in self.inheritance], [str(x) for x in self.variables], func_summaries, modif_summaries) | [
"def",
"get_summary",
"(",
"self",
")",
":",
"func_summaries",
"=",
"[",
"f",
".",
"get_summary",
"(",
")",
"for",
"f",
"in",
"self",
".",
"functions",
"]",
"modif_summaries",
"=",
"[",
"f",
".",
"get_summary",
"(",
")",
"for",
"f",
"in",
"self",
".",
"modifiers",
"]",
"return",
"(",
"self",
".",
"name",
",",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"inheritance",
"]",
",",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"variables",
"]",
",",
"func_summaries",
",",
"modif_summaries",
")"
] | Return the function summary
Returns:
(str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries) | [
"Return",
"the",
"function",
"summary"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L512-L520 |
230,841 | crytic/slither | slither/core/declarations/contract.py | Contract.is_erc20 | def is_erc20(self):
"""
Check if the contract is an erc20 token
Note: it does not check for correct return values
Returns:
bool
"""
full_names = [f.full_name for f in self.functions]
return 'transfer(address,uint256)' in full_names and\
'transferFrom(address,address,uint256)' in full_names and\
'approve(address,uint256)' in full_names | python | def is_erc20(self):
"""
Check if the contract is an erc20 token
Note: it does not check for correct return values
Returns:
bool
"""
full_names = [f.full_name for f in self.functions]
return 'transfer(address,uint256)' in full_names and\
'transferFrom(address,address,uint256)' in full_names and\
'approve(address,uint256)' in full_names | [
"def",
"is_erc20",
"(",
"self",
")",
":",
"full_names",
"=",
"[",
"f",
".",
"full_name",
"for",
"f",
"in",
"self",
".",
"functions",
"]",
"return",
"'transfer(address,uint256)'",
"in",
"full_names",
"and",
"'transferFrom(address,address,uint256)'",
"in",
"full_names",
"and",
"'approve(address,uint256)'",
"in",
"full_names"
] | Check if the contract is an erc20 token
Note: it does not check for correct return values
Returns:
bool | [
"Check",
"if",
"the",
"contract",
"is",
"an",
"erc20",
"token"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/contract.py#L530-L541 |
230,842 | crytic/slither | slither/slithir/convert.py | integrate_value_gas | def integrate_value_gas(result):
'''
Integrate value and gas temporary arguments to call instruction
'''
was_changed = True
calls = []
while was_changed:
# We loop until we do not find any call to value or gas
was_changed = False
# Find all the assignments
assigments = {}
for i in result:
if isinstance(i, OperationWithLValue):
assigments[i.lvalue.name] = i
if isinstance(i, TmpCall):
if isinstance(i.called, Variable) and i.called.name in assigments:
ins_ori = assigments[i.called.name]
i.set_ori(ins_ori)
to_remove = []
variable_to_replace = {}
# Replace call to value, gas to an argument of the real call
for idx in range(len(result)):
ins = result[idx]
# value can be shadowed, so we check that the prev ins
# is an Argument
if is_value(ins) and isinstance(result[idx-1], Argument):
was_changed = True
result[idx-1].set_type(ArgumentType.VALUE)
result[idx-1].call_id = ins.ori.variable_left.name
calls.append(ins.ori.variable_left)
to_remove.append(ins)
variable_to_replace[ins.lvalue.name] = ins.ori.variable_left
elif is_gas(ins) and isinstance(result[idx-1], Argument):
was_changed = True
result[idx-1].set_type(ArgumentType.GAS)
result[idx-1].call_id = ins.ori.variable_left.name
calls.append(ins.ori.variable_left)
to_remove.append(ins)
variable_to_replace[ins.lvalue.name] = ins.ori.variable_left
# Remove the call to value/gas instruction
result = [i for i in result if not i in to_remove]
# update the real call
for ins in result:
if isinstance(ins, TmpCall):
# use of while if there redirections
while ins.called.name in variable_to_replace:
was_changed = True
ins.call_id = variable_to_replace[ins.called.name].name
calls.append(ins.called)
ins.called = variable_to_replace[ins.called.name]
if isinstance(ins, Argument):
while ins.call_id in variable_to_replace:
was_changed = True
ins.call_id = variable_to_replace[ins.call_id].name
calls = list(set([str(c) for c in calls]))
idx = 0
calls_d = {}
for call in calls:
calls_d[str(call)] = idx
idx = idx+1
return result | python | def integrate_value_gas(result):
'''
Integrate value and gas temporary arguments to call instruction
'''
was_changed = True
calls = []
while was_changed:
# We loop until we do not find any call to value or gas
was_changed = False
# Find all the assignments
assigments = {}
for i in result:
if isinstance(i, OperationWithLValue):
assigments[i.lvalue.name] = i
if isinstance(i, TmpCall):
if isinstance(i.called, Variable) and i.called.name in assigments:
ins_ori = assigments[i.called.name]
i.set_ori(ins_ori)
to_remove = []
variable_to_replace = {}
# Replace call to value, gas to an argument of the real call
for idx in range(len(result)):
ins = result[idx]
# value can be shadowed, so we check that the prev ins
# is an Argument
if is_value(ins) and isinstance(result[idx-1], Argument):
was_changed = True
result[idx-1].set_type(ArgumentType.VALUE)
result[idx-1].call_id = ins.ori.variable_left.name
calls.append(ins.ori.variable_left)
to_remove.append(ins)
variable_to_replace[ins.lvalue.name] = ins.ori.variable_left
elif is_gas(ins) and isinstance(result[idx-1], Argument):
was_changed = True
result[idx-1].set_type(ArgumentType.GAS)
result[idx-1].call_id = ins.ori.variable_left.name
calls.append(ins.ori.variable_left)
to_remove.append(ins)
variable_to_replace[ins.lvalue.name] = ins.ori.variable_left
# Remove the call to value/gas instruction
result = [i for i in result if not i in to_remove]
# update the real call
for ins in result:
if isinstance(ins, TmpCall):
# use of while if there redirections
while ins.called.name in variable_to_replace:
was_changed = True
ins.call_id = variable_to_replace[ins.called.name].name
calls.append(ins.called)
ins.called = variable_to_replace[ins.called.name]
if isinstance(ins, Argument):
while ins.call_id in variable_to_replace:
was_changed = True
ins.call_id = variable_to_replace[ins.call_id].name
calls = list(set([str(c) for c in calls]))
idx = 0
calls_d = {}
for call in calls:
calls_d[str(call)] = idx
idx = idx+1
return result | [
"def",
"integrate_value_gas",
"(",
"result",
")",
":",
"was_changed",
"=",
"True",
"calls",
"=",
"[",
"]",
"while",
"was_changed",
":",
"# We loop until we do not find any call to value or gas",
"was_changed",
"=",
"False",
"# Find all the assignments",
"assigments",
"=",
"{",
"}",
"for",
"i",
"in",
"result",
":",
"if",
"isinstance",
"(",
"i",
",",
"OperationWithLValue",
")",
":",
"assigments",
"[",
"i",
".",
"lvalue",
".",
"name",
"]",
"=",
"i",
"if",
"isinstance",
"(",
"i",
",",
"TmpCall",
")",
":",
"if",
"isinstance",
"(",
"i",
".",
"called",
",",
"Variable",
")",
"and",
"i",
".",
"called",
".",
"name",
"in",
"assigments",
":",
"ins_ori",
"=",
"assigments",
"[",
"i",
".",
"called",
".",
"name",
"]",
"i",
".",
"set_ori",
"(",
"ins_ori",
")",
"to_remove",
"=",
"[",
"]",
"variable_to_replace",
"=",
"{",
"}",
"# Replace call to value, gas to an argument of the real call",
"for",
"idx",
"in",
"range",
"(",
"len",
"(",
"result",
")",
")",
":",
"ins",
"=",
"result",
"[",
"idx",
"]",
"# value can be shadowed, so we check that the prev ins",
"# is an Argument",
"if",
"is_value",
"(",
"ins",
")",
"and",
"isinstance",
"(",
"result",
"[",
"idx",
"-",
"1",
"]",
",",
"Argument",
")",
":",
"was_changed",
"=",
"True",
"result",
"[",
"idx",
"-",
"1",
"]",
".",
"set_type",
"(",
"ArgumentType",
".",
"VALUE",
")",
"result",
"[",
"idx",
"-",
"1",
"]",
".",
"call_id",
"=",
"ins",
".",
"ori",
".",
"variable_left",
".",
"name",
"calls",
".",
"append",
"(",
"ins",
".",
"ori",
".",
"variable_left",
")",
"to_remove",
".",
"append",
"(",
"ins",
")",
"variable_to_replace",
"[",
"ins",
".",
"lvalue",
".",
"name",
"]",
"=",
"ins",
".",
"ori",
".",
"variable_left",
"elif",
"is_gas",
"(",
"ins",
")",
"and",
"isinstance",
"(",
"result",
"[",
"idx",
"-",
"1",
"]",
",",
"Argument",
")",
":",
"was_changed",
"=",
"True",
"result",
"[",
"idx",
"-",
"1",
"]",
".",
"set_type",
"(",
"ArgumentType",
".",
"GAS",
")",
"result",
"[",
"idx",
"-",
"1",
"]",
".",
"call_id",
"=",
"ins",
".",
"ori",
".",
"variable_left",
".",
"name",
"calls",
".",
"append",
"(",
"ins",
".",
"ori",
".",
"variable_left",
")",
"to_remove",
".",
"append",
"(",
"ins",
")",
"variable_to_replace",
"[",
"ins",
".",
"lvalue",
".",
"name",
"]",
"=",
"ins",
".",
"ori",
".",
"variable_left",
"# Remove the call to value/gas instruction",
"result",
"=",
"[",
"i",
"for",
"i",
"in",
"result",
"if",
"not",
"i",
"in",
"to_remove",
"]",
"# update the real call ",
"for",
"ins",
"in",
"result",
":",
"if",
"isinstance",
"(",
"ins",
",",
"TmpCall",
")",
":",
"# use of while if there redirections",
"while",
"ins",
".",
"called",
".",
"name",
"in",
"variable_to_replace",
":",
"was_changed",
"=",
"True",
"ins",
".",
"call_id",
"=",
"variable_to_replace",
"[",
"ins",
".",
"called",
".",
"name",
"]",
".",
"name",
"calls",
".",
"append",
"(",
"ins",
".",
"called",
")",
"ins",
".",
"called",
"=",
"variable_to_replace",
"[",
"ins",
".",
"called",
".",
"name",
"]",
"if",
"isinstance",
"(",
"ins",
",",
"Argument",
")",
":",
"while",
"ins",
".",
"call_id",
"in",
"variable_to_replace",
":",
"was_changed",
"=",
"True",
"ins",
".",
"call_id",
"=",
"variable_to_replace",
"[",
"ins",
".",
"call_id",
"]",
".",
"name",
"calls",
"=",
"list",
"(",
"set",
"(",
"[",
"str",
"(",
"c",
")",
"for",
"c",
"in",
"calls",
"]",
")",
")",
"idx",
"=",
"0",
"calls_d",
"=",
"{",
"}",
"for",
"call",
"in",
"calls",
":",
"calls_d",
"[",
"str",
"(",
"call",
")",
"]",
"=",
"idx",
"idx",
"=",
"idx",
"+",
"1",
"return",
"result"
] | Integrate value and gas temporary arguments to call instruction | [
"Integrate",
"value",
"and",
"gas",
"temporary",
"arguments",
"to",
"call",
"instruction"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L144-L213 |
230,843 | crytic/slither | slither/slithir/convert.py | propagate_type_and_convert_call | def propagate_type_and_convert_call(result, node):
'''
Propagate the types variables and convert tmp call to real call operation
'''
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result):
ins = result[idx]
if isinstance(ins, TmpCall):
new_ins = extract_tmp_call(ins, node.function.contract)
if new_ins:
new_ins.set_node(ins.node)
ins = new_ins
result[idx] = ins
if isinstance(ins, Argument):
if ins.get_type() in [ArgumentType.GAS]:
assert not ins.call_id in calls_gas
calls_gas[ins.call_id] = ins.argument
elif ins.get_type() in [ArgumentType.VALUE]:
assert not ins.call_id in calls_value
calls_value[ins.call_id] = ins.argument
else:
assert ins.get_type() == ArgumentType.CALL
call_data.append(ins.argument)
if isinstance(ins, (HighLevelCall, NewContract, InternalDynamicCall)):
if ins.call_id in calls_value:
ins.call_value = calls_value[ins.call_id]
if ins.call_id in calls_gas:
ins.call_gas = calls_gas[ins.call_id]
if isinstance(ins, (Call, NewContract, NewStructure)):
ins.arguments = call_data
call_data = []
if is_temporary(ins):
del result[idx]
continue
new_ins = propagate_types(ins, node)
if new_ins:
if isinstance(new_ins, (list,)):
if len(new_ins) == 2:
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx+1, new_ins[1])
idx = idx + 1
else:
assert len(new_ins) == 3
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
new_ins[2].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx+1, new_ins[1])
result.insert(idx+2, new_ins[2])
idx = idx + 2
else:
new_ins.set_node(ins.node)
result[idx] = new_ins
idx = idx +1
return result | python | def propagate_type_and_convert_call(result, node):
'''
Propagate the types variables and convert tmp call to real call operation
'''
calls_value = {}
calls_gas = {}
call_data = []
idx = 0
# use of while len() as result can be modified during the iteration
while idx < len(result):
ins = result[idx]
if isinstance(ins, TmpCall):
new_ins = extract_tmp_call(ins, node.function.contract)
if new_ins:
new_ins.set_node(ins.node)
ins = new_ins
result[idx] = ins
if isinstance(ins, Argument):
if ins.get_type() in [ArgumentType.GAS]:
assert not ins.call_id in calls_gas
calls_gas[ins.call_id] = ins.argument
elif ins.get_type() in [ArgumentType.VALUE]:
assert not ins.call_id in calls_value
calls_value[ins.call_id] = ins.argument
else:
assert ins.get_type() == ArgumentType.CALL
call_data.append(ins.argument)
if isinstance(ins, (HighLevelCall, NewContract, InternalDynamicCall)):
if ins.call_id in calls_value:
ins.call_value = calls_value[ins.call_id]
if ins.call_id in calls_gas:
ins.call_gas = calls_gas[ins.call_id]
if isinstance(ins, (Call, NewContract, NewStructure)):
ins.arguments = call_data
call_data = []
if is_temporary(ins):
del result[idx]
continue
new_ins = propagate_types(ins, node)
if new_ins:
if isinstance(new_ins, (list,)):
if len(new_ins) == 2:
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx+1, new_ins[1])
idx = idx + 1
else:
assert len(new_ins) == 3
new_ins[0].set_node(ins.node)
new_ins[1].set_node(ins.node)
new_ins[2].set_node(ins.node)
del result[idx]
result.insert(idx, new_ins[0])
result.insert(idx+1, new_ins[1])
result.insert(idx+2, new_ins[2])
idx = idx + 2
else:
new_ins.set_node(ins.node)
result[idx] = new_ins
idx = idx +1
return result | [
"def",
"propagate_type_and_convert_call",
"(",
"result",
",",
"node",
")",
":",
"calls_value",
"=",
"{",
"}",
"calls_gas",
"=",
"{",
"}",
"call_data",
"=",
"[",
"]",
"idx",
"=",
"0",
"# use of while len() as result can be modified during the iteration",
"while",
"idx",
"<",
"len",
"(",
"result",
")",
":",
"ins",
"=",
"result",
"[",
"idx",
"]",
"if",
"isinstance",
"(",
"ins",
",",
"TmpCall",
")",
":",
"new_ins",
"=",
"extract_tmp_call",
"(",
"ins",
",",
"node",
".",
"function",
".",
"contract",
")",
"if",
"new_ins",
":",
"new_ins",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"ins",
"=",
"new_ins",
"result",
"[",
"idx",
"]",
"=",
"ins",
"if",
"isinstance",
"(",
"ins",
",",
"Argument",
")",
":",
"if",
"ins",
".",
"get_type",
"(",
")",
"in",
"[",
"ArgumentType",
".",
"GAS",
"]",
":",
"assert",
"not",
"ins",
".",
"call_id",
"in",
"calls_gas",
"calls_gas",
"[",
"ins",
".",
"call_id",
"]",
"=",
"ins",
".",
"argument",
"elif",
"ins",
".",
"get_type",
"(",
")",
"in",
"[",
"ArgumentType",
".",
"VALUE",
"]",
":",
"assert",
"not",
"ins",
".",
"call_id",
"in",
"calls_value",
"calls_value",
"[",
"ins",
".",
"call_id",
"]",
"=",
"ins",
".",
"argument",
"else",
":",
"assert",
"ins",
".",
"get_type",
"(",
")",
"==",
"ArgumentType",
".",
"CALL",
"call_data",
".",
"append",
"(",
"ins",
".",
"argument",
")",
"if",
"isinstance",
"(",
"ins",
",",
"(",
"HighLevelCall",
",",
"NewContract",
",",
"InternalDynamicCall",
")",
")",
":",
"if",
"ins",
".",
"call_id",
"in",
"calls_value",
":",
"ins",
".",
"call_value",
"=",
"calls_value",
"[",
"ins",
".",
"call_id",
"]",
"if",
"ins",
".",
"call_id",
"in",
"calls_gas",
":",
"ins",
".",
"call_gas",
"=",
"calls_gas",
"[",
"ins",
".",
"call_id",
"]",
"if",
"isinstance",
"(",
"ins",
",",
"(",
"Call",
",",
"NewContract",
",",
"NewStructure",
")",
")",
":",
"ins",
".",
"arguments",
"=",
"call_data",
"call_data",
"=",
"[",
"]",
"if",
"is_temporary",
"(",
"ins",
")",
":",
"del",
"result",
"[",
"idx",
"]",
"continue",
"new_ins",
"=",
"propagate_types",
"(",
"ins",
",",
"node",
")",
"if",
"new_ins",
":",
"if",
"isinstance",
"(",
"new_ins",
",",
"(",
"list",
",",
")",
")",
":",
"if",
"len",
"(",
"new_ins",
")",
"==",
"2",
":",
"new_ins",
"[",
"0",
"]",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"new_ins",
"[",
"1",
"]",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"del",
"result",
"[",
"idx",
"]",
"result",
".",
"insert",
"(",
"idx",
",",
"new_ins",
"[",
"0",
"]",
")",
"result",
".",
"insert",
"(",
"idx",
"+",
"1",
",",
"new_ins",
"[",
"1",
"]",
")",
"idx",
"=",
"idx",
"+",
"1",
"else",
":",
"assert",
"len",
"(",
"new_ins",
")",
"==",
"3",
"new_ins",
"[",
"0",
"]",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"new_ins",
"[",
"1",
"]",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"new_ins",
"[",
"2",
"]",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"del",
"result",
"[",
"idx",
"]",
"result",
".",
"insert",
"(",
"idx",
",",
"new_ins",
"[",
"0",
"]",
")",
"result",
".",
"insert",
"(",
"idx",
"+",
"1",
",",
"new_ins",
"[",
"1",
"]",
")",
"result",
".",
"insert",
"(",
"idx",
"+",
"2",
",",
"new_ins",
"[",
"2",
"]",
")",
"idx",
"=",
"idx",
"+",
"2",
"else",
":",
"new_ins",
".",
"set_node",
"(",
"ins",
".",
"node",
")",
"result",
"[",
"idx",
"]",
"=",
"new_ins",
"idx",
"=",
"idx",
"+",
"1",
"return",
"result"
] | Propagate the types variables and convert tmp call to real call operation | [
"Propagate",
"the",
"types",
"variables",
"and",
"convert",
"tmp",
"call",
"to",
"real",
"call",
"operation"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L222-L292 |
230,844 | crytic/slither | slither/slithir/convert.py | convert_to_push | def convert_to_push(ir, node):
"""
Convert a call to a PUSH operaiton
The funciton assume to receive a correct IR
The checks must be done by the caller
May necessitate to create an intermediate operation (InitArray)
Necessitate to return the lenght (see push documentation)
As a result, the function return may return a list
"""
lvalue = ir.lvalue
if isinstance(ir.arguments[0], list):
ret = []
val = TemporaryVariable(node)
operation = InitArray(ir.arguments[0], val)
ret.append(operation)
ir = Push(ir.destination, val)
length = Literal(len(operation.init_values))
t = operation.init_values[0].type
ir.lvalue.set_type(ArrayType(t, length))
ret.append(ir)
if lvalue:
length = Length(ir.array, lvalue)
length.lvalue.points_to = ir.lvalue
ret.append(length)
return ret
ir = Push(ir.destination, ir.arguments[0])
if lvalue:
ret = []
ret.append(ir)
length = Length(ir.array, lvalue)
length.lvalue.points_to = ir.lvalue
ret.append(length)
return ret
return ir | python | def convert_to_push(ir, node):
"""
Convert a call to a PUSH operaiton
The funciton assume to receive a correct IR
The checks must be done by the caller
May necessitate to create an intermediate operation (InitArray)
Necessitate to return the lenght (see push documentation)
As a result, the function return may return a list
"""
lvalue = ir.lvalue
if isinstance(ir.arguments[0], list):
ret = []
val = TemporaryVariable(node)
operation = InitArray(ir.arguments[0], val)
ret.append(operation)
ir = Push(ir.destination, val)
length = Literal(len(operation.init_values))
t = operation.init_values[0].type
ir.lvalue.set_type(ArrayType(t, length))
ret.append(ir)
if lvalue:
length = Length(ir.array, lvalue)
length.lvalue.points_to = ir.lvalue
ret.append(length)
return ret
ir = Push(ir.destination, ir.arguments[0])
if lvalue:
ret = []
ret.append(ir)
length = Length(ir.array, lvalue)
length.lvalue.points_to = ir.lvalue
ret.append(length)
return ret
return ir | [
"def",
"convert_to_push",
"(",
"ir",
",",
"node",
")",
":",
"lvalue",
"=",
"ir",
".",
"lvalue",
"if",
"isinstance",
"(",
"ir",
".",
"arguments",
"[",
"0",
"]",
",",
"list",
")",
":",
"ret",
"=",
"[",
"]",
"val",
"=",
"TemporaryVariable",
"(",
"node",
")",
"operation",
"=",
"InitArray",
"(",
"ir",
".",
"arguments",
"[",
"0",
"]",
",",
"val",
")",
"ret",
".",
"append",
"(",
"operation",
")",
"ir",
"=",
"Push",
"(",
"ir",
".",
"destination",
",",
"val",
")",
"length",
"=",
"Literal",
"(",
"len",
"(",
"operation",
".",
"init_values",
")",
")",
"t",
"=",
"operation",
".",
"init_values",
"[",
"0",
"]",
".",
"type",
"ir",
".",
"lvalue",
".",
"set_type",
"(",
"ArrayType",
"(",
"t",
",",
"length",
")",
")",
"ret",
".",
"append",
"(",
"ir",
")",
"if",
"lvalue",
":",
"length",
"=",
"Length",
"(",
"ir",
".",
"array",
",",
"lvalue",
")",
"length",
".",
"lvalue",
".",
"points_to",
"=",
"ir",
".",
"lvalue",
"ret",
".",
"append",
"(",
"length",
")",
"return",
"ret",
"ir",
"=",
"Push",
"(",
"ir",
".",
"destination",
",",
"ir",
".",
"arguments",
"[",
"0",
"]",
")",
"if",
"lvalue",
":",
"ret",
"=",
"[",
"]",
"ret",
".",
"append",
"(",
"ir",
")",
"length",
"=",
"Length",
"(",
"ir",
".",
"array",
",",
"lvalue",
")",
"length",
".",
"lvalue",
".",
"points_to",
"=",
"ir",
".",
"lvalue",
"ret",
".",
"append",
"(",
"length",
")",
"return",
"ret",
"return",
"ir"
] | Convert a call to a PUSH operaiton
The funciton assume to receive a correct IR
The checks must be done by the caller
May necessitate to create an intermediate operation (InitArray)
Necessitate to return the lenght (see push documentation)
As a result, the function return may return a list | [
"Convert",
"a",
"call",
"to",
"a",
"PUSH",
"operaiton"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L579-L626 |
230,845 | crytic/slither | slither/slithir/convert.py | get_type | def get_type(t):
"""
Convert a type to a str
If the instance is a Contract, return 'address' instead
"""
if isinstance(t, UserDefinedType):
if isinstance(t.type, Contract):
return 'address'
return str(t) | python | def get_type(t):
"""
Convert a type to a str
If the instance is a Contract, return 'address' instead
"""
if isinstance(t, UserDefinedType):
if isinstance(t.type, Contract):
return 'address'
return str(t) | [
"def",
"get_type",
"(",
"t",
")",
":",
"if",
"isinstance",
"(",
"t",
",",
"UserDefinedType",
")",
":",
"if",
"isinstance",
"(",
"t",
".",
"type",
",",
"Contract",
")",
":",
"return",
"'address'",
"return",
"str",
"(",
"t",
")"
] | Convert a type to a str
If the instance is a Contract, return 'address' instead | [
"Convert",
"a",
"type",
"to",
"a",
"str",
"If",
"the",
"instance",
"is",
"a",
"Contract",
"return",
"address",
"instead"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L661-L669 |
230,846 | crytic/slither | slither/slithir/convert.py | find_references_origin | def find_references_origin(irs):
"""
Make lvalue of each Index, Member operation
points to the left variable
"""
for ir in irs:
if isinstance(ir, (Index, Member)):
ir.lvalue.points_to = ir.variable_left | python | def find_references_origin(irs):
"""
Make lvalue of each Index, Member operation
points to the left variable
"""
for ir in irs:
if isinstance(ir, (Index, Member)):
ir.lvalue.points_to = ir.variable_left | [
"def",
"find_references_origin",
"(",
"irs",
")",
":",
"for",
"ir",
"in",
"irs",
":",
"if",
"isinstance",
"(",
"ir",
",",
"(",
"Index",
",",
"Member",
")",
")",
":",
"ir",
".",
"lvalue",
".",
"points_to",
"=",
"ir",
".",
"variable_left"
] | Make lvalue of each Index, Member operation
points to the left variable | [
"Make",
"lvalue",
"of",
"each",
"Index",
"Member",
"operation",
"points",
"to",
"the",
"left",
"variable"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L768-L775 |
230,847 | crytic/slither | slither/slithir/convert.py | apply_ir_heuristics | def apply_ir_heuristics(irs, node):
"""
Apply a set of heuristic to improve slithIR
"""
irs = integrate_value_gas(irs)
irs = propagate_type_and_convert_call(irs, node)
irs = remove_unused(irs)
find_references_origin(irs)
return irs | python | def apply_ir_heuristics(irs, node):
"""
Apply a set of heuristic to improve slithIR
"""
irs = integrate_value_gas(irs)
irs = propagate_type_and_convert_call(irs, node)
irs = remove_unused(irs)
find_references_origin(irs)
return irs | [
"def",
"apply_ir_heuristics",
"(",
"irs",
",",
"node",
")",
":",
"irs",
"=",
"integrate_value_gas",
"(",
"irs",
")",
"irs",
"=",
"propagate_type_and_convert_call",
"(",
"irs",
",",
"node",
")",
"irs",
"=",
"remove_unused",
"(",
"irs",
")",
"find_references_origin",
"(",
"irs",
")",
"return",
"irs"
] | Apply a set of heuristic to improve slithIR | [
"Apply",
"a",
"set",
"of",
"heuristic",
"to",
"improve",
"slithIR"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/slithir/convert.py#L832-L844 |
230,848 | crytic/slither | slither/core/declarations/function.py | Function.return_type | def return_type(self):
"""
Return the list of return type
If no return, return None
"""
returns = self.returns
if returns:
return [r.type for r in returns]
return None | python | def return_type(self):
"""
Return the list of return type
If no return, return None
"""
returns = self.returns
if returns:
return [r.type for r in returns]
return None | [
"def",
"return_type",
"(",
"self",
")",
":",
"returns",
"=",
"self",
".",
"returns",
"if",
"returns",
":",
"return",
"[",
"r",
".",
"type",
"for",
"r",
"in",
"returns",
"]",
"return",
"None"
] | Return the list of return type
If no return, return None | [
"Return",
"the",
"list",
"of",
"return",
"type",
"If",
"no",
"return",
"return",
"None"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L249-L257 |
230,849 | crytic/slither | slither/core/declarations/function.py | Function.all_solidity_variables_read | def all_solidity_variables_read(self):
""" recursive version of solidity_read
"""
if self._all_solidity_variables_read is None:
self._all_solidity_variables_read = self._explore_functions(
lambda x: x.solidity_variables_read)
return self._all_solidity_variables_read | python | def all_solidity_variables_read(self):
""" recursive version of solidity_read
"""
if self._all_solidity_variables_read is None:
self._all_solidity_variables_read = self._explore_functions(
lambda x: x.solidity_variables_read)
return self._all_solidity_variables_read | [
"def",
"all_solidity_variables_read",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_read",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_read",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"solidity_variables_read",
")",
"return",
"self",
".",
"_all_solidity_variables_read"
] | recursive version of solidity_read | [
"recursive",
"version",
"of",
"solidity_read"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L629-L635 |
230,850 | crytic/slither | slither/core/declarations/function.py | Function.all_state_variables_written | def all_state_variables_written(self):
""" recursive version of variables_written
"""
if self._all_state_variables_written is None:
self._all_state_variables_written = self._explore_functions(
lambda x: x.state_variables_written)
return self._all_state_variables_written | python | def all_state_variables_written(self):
""" recursive version of variables_written
"""
if self._all_state_variables_written is None:
self._all_state_variables_written = self._explore_functions(
lambda x: x.state_variables_written)
return self._all_state_variables_written | [
"def",
"all_state_variables_written",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_state_variables_written",
"is",
"None",
":",
"self",
".",
"_all_state_variables_written",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"state_variables_written",
")",
"return",
"self",
".",
"_all_state_variables_written"
] | recursive version of variables_written | [
"recursive",
"version",
"of",
"variables_written"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L651-L657 |
230,851 | crytic/slither | slither/core/declarations/function.py | Function.all_internal_calls | def all_internal_calls(self):
""" recursive version of internal_calls
"""
if self._all_internals_calls is None:
self._all_internals_calls = self._explore_functions(lambda x: x.internal_calls)
return self._all_internals_calls | python | def all_internal_calls(self):
""" recursive version of internal_calls
"""
if self._all_internals_calls is None:
self._all_internals_calls = self._explore_functions(lambda x: x.internal_calls)
return self._all_internals_calls | [
"def",
"all_internal_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_internals_calls",
"is",
"None",
":",
"self",
".",
"_all_internals_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"internal_calls",
")",
"return",
"self",
".",
"_all_internals_calls"
] | recursive version of internal_calls | [
"recursive",
"version",
"of",
"internal_calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L659-L664 |
230,852 | crytic/slither | slither/core/declarations/function.py | Function.all_low_level_calls | def all_low_level_calls(self):
""" recursive version of low_level calls
"""
if self._all_low_level_calls is None:
self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls)
return self._all_low_level_calls | python | def all_low_level_calls(self):
""" recursive version of low_level calls
"""
if self._all_low_level_calls is None:
self._all_low_level_calls = self._explore_functions(lambda x: x.low_level_calls)
return self._all_low_level_calls | [
"def",
"all_low_level_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_low_level_calls",
"is",
"None",
":",
"self",
".",
"_all_low_level_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"low_level_calls",
")",
"return",
"self",
".",
"_all_low_level_calls"
] | recursive version of low_level calls | [
"recursive",
"version",
"of",
"low_level",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L666-L671 |
230,853 | crytic/slither | slither/core/declarations/function.py | Function.all_high_level_calls | def all_high_level_calls(self):
""" recursive version of high_level calls
"""
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls | python | def all_high_level_calls(self):
""" recursive version of high_level calls
"""
if self._all_high_level_calls is None:
self._all_high_level_calls = self._explore_functions(lambda x: x.high_level_calls)
return self._all_high_level_calls | [
"def",
"all_high_level_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_high_level_calls",
"is",
"None",
":",
"self",
".",
"_all_high_level_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"high_level_calls",
")",
"return",
"self",
".",
"_all_high_level_calls"
] | recursive version of high_level calls | [
"recursive",
"version",
"of",
"high_level",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L673-L678 |
230,854 | crytic/slither | slither/core/declarations/function.py | Function.all_library_calls | def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | python | def all_library_calls(self):
""" recursive version of library calls
"""
if self._all_library_calls is None:
self._all_library_calls = self._explore_functions(lambda x: x.library_calls)
return self._all_library_calls | [
"def",
"all_library_calls",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_library_calls",
"is",
"None",
":",
"self",
".",
"_all_library_calls",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"x",
".",
"library_calls",
")",
"return",
"self",
".",
"_all_library_calls"
] | recursive version of library calls | [
"recursive",
"version",
"of",
"library",
"calls"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L680-L685 |
230,855 | crytic/slither | slither/core/declarations/function.py | Function.all_conditional_state_variables_read | def all_conditional_state_variables_read(self, include_loop=True):
"""
Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_state_variables_read_with_loop is None:
self._all_conditional_state_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read_with_loop
else:
if self._all_conditional_state_variables_read is None:
self._all_conditional_state_variables_read = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read | python | def all_conditional_state_variables_read(self, include_loop=True):
"""
Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_state_variables_read_with_loop is None:
self._all_conditional_state_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read_with_loop
else:
if self._all_conditional_state_variables_read is None:
self._all_conditional_state_variables_read = self._explore_functions(
lambda x: self._explore_func_cond_read(x,
include_loop))
return self._all_conditional_state_variables_read | [
"def",
"all_conditional_state_variables_read",
"(",
"self",
",",
"include_loop",
"=",
"True",
")",
":",
"if",
"include_loop",
":",
"if",
"self",
".",
"_all_conditional_state_variables_read_with_loop",
"is",
"None",
":",
"self",
".",
"_all_conditional_state_variables_read_with_loop",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"self",
".",
"_explore_func_cond_read",
"(",
"x",
",",
"include_loop",
")",
")",
"return",
"self",
".",
"_all_conditional_state_variables_read_with_loop",
"else",
":",
"if",
"self",
".",
"_all_conditional_state_variables_read",
"is",
"None",
":",
"self",
".",
"_all_conditional_state_variables_read",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"self",
".",
"_explore_func_cond_read",
"(",
"x",
",",
"include_loop",
")",
")",
"return",
"self",
".",
"_all_conditional_state_variables_read"
] | Return the state variable used in a condition
Over approximate and also return index access
It won't work if the variable is assigned to a temp variable | [
"Return",
"the",
"state",
"variable",
"used",
"in",
"a",
"condition"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L692-L710 |
230,856 | crytic/slither | slither/core/declarations/function.py | Function.all_conditional_solidity_variables_read | def all_conditional_solidity_variables_read(self, include_loop=True):
"""
Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_solidity_variables_read_with_loop is None:
self._all_conditional_solidity_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read_with_loop
else:
if self._all_conditional_solidity_variables_read is None:
self._all_conditional_solidity_variables_read = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read | python | def all_conditional_solidity_variables_read(self, include_loop=True):
"""
Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable
"""
if include_loop:
if self._all_conditional_solidity_variables_read_with_loop is None:
self._all_conditional_solidity_variables_read_with_loop = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read_with_loop
else:
if self._all_conditional_solidity_variables_read is None:
self._all_conditional_solidity_variables_read = self._explore_functions(
lambda x: self._explore_func_conditional(x,
self._solidity_variable_in_binary,
include_loop))
return self._all_conditional_solidity_variables_read | [
"def",
"all_conditional_solidity_variables_read",
"(",
"self",
",",
"include_loop",
"=",
"True",
")",
":",
"if",
"include_loop",
":",
"if",
"self",
".",
"_all_conditional_solidity_variables_read_with_loop",
"is",
"None",
":",
"self",
".",
"_all_conditional_solidity_variables_read_with_loop",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"self",
".",
"_explore_func_conditional",
"(",
"x",
",",
"self",
".",
"_solidity_variable_in_binary",
",",
"include_loop",
")",
")",
"return",
"self",
".",
"_all_conditional_solidity_variables_read_with_loop",
"else",
":",
"if",
"self",
".",
"_all_conditional_solidity_variables_read",
"is",
"None",
":",
"self",
".",
"_all_conditional_solidity_variables_read",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"self",
".",
"_explore_func_conditional",
"(",
"x",
",",
"self",
".",
"_solidity_variable_in_binary",
",",
"include_loop",
")",
")",
"return",
"self",
".",
"_all_conditional_solidity_variables_read"
] | Return the Soldiity variables directly used in a condtion
Use of the IR to filter index access
Assumption: the solidity vars are used directly in the conditional node
It won't work if the variable is assigned to a temp variable | [
"Return",
"the",
"Soldiity",
"variables",
"directly",
"used",
"in",
"a",
"condtion"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L726-L747 |
230,857 | crytic/slither | slither/core/declarations/function.py | Function.all_solidity_variables_used_as_args | def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solidity_variables_used_as_args = self._explore_functions(
lambda x: self._explore_func_nodes(x, self._solidity_variable_in_internal_calls))
return self._all_solidity_variables_used_as_args | python | def all_solidity_variables_used_as_args(self):
"""
Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender)
"""
if self._all_solidity_variables_used_as_args is None:
self._all_solidity_variables_used_as_args = self._explore_functions(
lambda x: self._explore_func_nodes(x, self._solidity_variable_in_internal_calls))
return self._all_solidity_variables_used_as_args | [
"def",
"all_solidity_variables_used_as_args",
"(",
"self",
")",
":",
"if",
"self",
".",
"_all_solidity_variables_used_as_args",
"is",
"None",
":",
"self",
".",
"_all_solidity_variables_used_as_args",
"=",
"self",
".",
"_explore_functions",
"(",
"lambda",
"x",
":",
"self",
".",
"_explore_func_nodes",
"(",
"x",
",",
"self",
".",
"_solidity_variable_in_internal_calls",
")",
")",
"return",
"self",
".",
"_all_solidity_variables_used_as_args"
] | Return the Soldiity variables directly used in a call
Use of the IR to filter index access
Used to catch check(msg.sender) | [
"Return",
"the",
"Soldiity",
"variables",
"directly",
"used",
"in",
"a",
"call"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L763-L773 |
230,858 | crytic/slither | slither/core/declarations/function.py | Function.is_protected | def is_protected(self):
"""
Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool)
"""
if self.is_constructor:
return True
conditional_vars = self.all_conditional_solidity_variables_read(include_loop=False)
args_vars = self.all_solidity_variables_used_as_args()
return SolidityVariableComposed('msg.sender') in conditional_vars + args_vars | python | def is_protected(self):
"""
Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool)
"""
if self.is_constructor:
return True
conditional_vars = self.all_conditional_solidity_variables_read(include_loop=False)
args_vars = self.all_solidity_variables_used_as_args()
return SolidityVariableComposed('msg.sender') in conditional_vars + args_vars | [
"def",
"is_protected",
"(",
"self",
")",
":",
"if",
"self",
".",
"is_constructor",
":",
"return",
"True",
"conditional_vars",
"=",
"self",
".",
"all_conditional_solidity_variables_read",
"(",
"include_loop",
"=",
"False",
")",
"args_vars",
"=",
"self",
".",
"all_solidity_variables_used_as_args",
"(",
")",
"return",
"SolidityVariableComposed",
"(",
"'msg.sender'",
")",
"in",
"conditional_vars",
"+",
"args_vars"
] | Determine if the function is protected using a check on msg.sender
Only detects if msg.sender is directly used in a condition
For example, it wont work for:
address a = msg.sender
require(a == owner)
Returns
(bool) | [
"Determine",
"if",
"the",
"function",
"is",
"protected",
"using",
"a",
"check",
"on",
"msg",
".",
"sender"
] | 04c147f7e50223c6af458ca430befae747ccd259 | https://github.com/crytic/slither/blob/04c147f7e50223c6af458ca430befae747ccd259/slither/core/declarations/function.py#L940-L956 |
230,859 | TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.auth_string | def auth_string(self):
'''
Authenticate based on username and token which is base64-encoded
'''
username_token = '{username}:{token}'.format(username=self.username, token=self.token)
b64encoded_string = b64encode(username_token)
auth_string = 'Token {b64}'.format(b64=b64encoded_string)
return auth_string | python | def auth_string(self):
'''
Authenticate based on username and token which is base64-encoded
'''
username_token = '{username}:{token}'.format(username=self.username, token=self.token)
b64encoded_string = b64encode(username_token)
auth_string = 'Token {b64}'.format(b64=b64encoded_string)
return auth_string | [
"def",
"auth_string",
"(",
"self",
")",
":",
"username_token",
"=",
"'{username}:{token}'",
".",
"format",
"(",
"username",
"=",
"self",
".",
"username",
",",
"token",
"=",
"self",
".",
"token",
")",
"b64encoded_string",
"=",
"b64encode",
"(",
"username_token",
")",
"auth_string",
"=",
"'Token {b64}'",
".",
"format",
"(",
"b64",
"=",
"b64encoded_string",
")",
"return",
"auth_string"
] | Authenticate based on username and token which is base64-encoded | [
"Authenticate",
"based",
"on",
"username",
"and",
"token",
"which",
"is",
"base64",
"-",
"encoded"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L27-L36 |
230,860 | TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.api_related | def api_related(self, query):
'''
Find related objects through SoltraEdge API
'''
url = "{0}/{1}/related/?format=json".format(self.base_url, query)
response = requests.get(url, headers=self.headers, verify=self.verify_ssl)
if response.status_code == 200:
return response.json()
else:
self.error('Received status code: {0} from Soltra Server. Content:\n{1}'.format(
response.status_code, response.text)
) | python | def api_related(self, query):
'''
Find related objects through SoltraEdge API
'''
url = "{0}/{1}/related/?format=json".format(self.base_url, query)
response = requests.get(url, headers=self.headers, verify=self.verify_ssl)
if response.status_code == 200:
return response.json()
else:
self.error('Received status code: {0} from Soltra Server. Content:\n{1}'.format(
response.status_code, response.text)
) | [
"def",
"api_related",
"(",
"self",
",",
"query",
")",
":",
"url",
"=",
"\"{0}/{1}/related/?format=json\"",
".",
"format",
"(",
"self",
".",
"base_url",
",",
"query",
")",
"response",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"self",
".",
"headers",
",",
"verify",
"=",
"self",
".",
"verify_ssl",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"return",
"response",
".",
"json",
"(",
")",
"else",
":",
"self",
".",
"error",
"(",
"'Received status code: {0} from Soltra Server. Content:\\n{1}'",
".",
"format",
"(",
"response",
".",
"status_code",
",",
"response",
".",
"text",
")",
")"
] | Find related objects through SoltraEdge API | [
"Find",
"related",
"objects",
"through",
"SoltraEdge",
"API"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L55-L68 |
230,861 | TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.tlp_classifiers | def tlp_classifiers(self, name_tlp, val_tlp):
'''
Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP"
'''
classifier = {
"WHITE": 0,
"GREEN": 1,
"AMBER": 2,
"RED": 3
}
valid = True
if classifier[name_tlp] > val_tlp:
valid = False
return valid | python | def tlp_classifiers(self, name_tlp, val_tlp):
'''
Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP"
'''
classifier = {
"WHITE": 0,
"GREEN": 1,
"AMBER": 2,
"RED": 3
}
valid = True
if classifier[name_tlp] > val_tlp:
valid = False
return valid | [
"def",
"tlp_classifiers",
"(",
"self",
",",
"name_tlp",
",",
"val_tlp",
")",
":",
"classifier",
"=",
"{",
"\"WHITE\"",
":",
"0",
",",
"\"GREEN\"",
":",
"1",
",",
"\"AMBER\"",
":",
"2",
",",
"\"RED\"",
":",
"3",
"}",
"valid",
"=",
"True",
"if",
"classifier",
"[",
"name_tlp",
"]",
">",
"val_tlp",
":",
"valid",
"=",
"False",
"return",
"valid"
] | Classifier between Cortex and Soltra.
Soltra uses name-TLP, and Cortex "value-TLP" | [
"Classifier",
"between",
"Cortex",
"and",
"Soltra",
".",
"Soltra",
"uses",
"name",
"-",
"TLP",
"and",
"Cortex",
"value",
"-",
"TLP"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L71-L89 |
230,862 | TheHive-Project/Cortex-Analyzers | analyzers/SoltraEdge/soltra.py | SoltraEdge.pop_object | def pop_object(self, element):
'''
Pop the object element if the object contains an higher TLP then allowed.
'''
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element['id'] = ''
element['url'] = ''
element['type'] = ''
element['tags'] = []
element['etlp'] = None
element['title'] = redacted_text
element['tlpColor'] = element['tlpColor']
element['uploaded_on'] = ''
element['uploaded_by'] = ''
element['description'] = redacted_text
element['children_types'] = []
element['summary']['type'] = ''
element['summary']['value'] = ''
element['summary']['title'] = redacted_text
element['summary']['description'] = redacted_text
return element | python | def pop_object(self, element):
'''
Pop the object element if the object contains an higher TLP then allowed.
'''
redacted_text = "Redacted. Object contained TLP value higher than allowed."
element['id'] = ''
element['url'] = ''
element['type'] = ''
element['tags'] = []
element['etlp'] = None
element['title'] = redacted_text
element['tlpColor'] = element['tlpColor']
element['uploaded_on'] = ''
element['uploaded_by'] = ''
element['description'] = redacted_text
element['children_types'] = []
element['summary']['type'] = ''
element['summary']['value'] = ''
element['summary']['title'] = redacted_text
element['summary']['description'] = redacted_text
return element | [
"def",
"pop_object",
"(",
"self",
",",
"element",
")",
":",
"redacted_text",
"=",
"\"Redacted. Object contained TLP value higher than allowed.\"",
"element",
"[",
"'id'",
"]",
"=",
"''",
"element",
"[",
"'url'",
"]",
"=",
"''",
"element",
"[",
"'type'",
"]",
"=",
"''",
"element",
"[",
"'tags'",
"]",
"=",
"[",
"]",
"element",
"[",
"'etlp'",
"]",
"=",
"None",
"element",
"[",
"'title'",
"]",
"=",
"redacted_text",
"element",
"[",
"'tlpColor'",
"]",
"=",
"element",
"[",
"'tlpColor'",
"]",
"element",
"[",
"'uploaded_on'",
"]",
"=",
"''",
"element",
"[",
"'uploaded_by'",
"]",
"=",
"''",
"element",
"[",
"'description'",
"]",
"=",
"redacted_text",
"element",
"[",
"'children_types'",
"]",
"=",
"[",
"]",
"element",
"[",
"'summary'",
"]",
"[",
"'type'",
"]",
"=",
"''",
"element",
"[",
"'summary'",
"]",
"[",
"'value'",
"]",
"=",
"''",
"element",
"[",
"'summary'",
"]",
"[",
"'title'",
"]",
"=",
"redacted_text",
"element",
"[",
"'summary'",
"]",
"[",
"'description'",
"]",
"=",
"redacted_text",
"return",
"element"
] | Pop the object element if the object contains an higher TLP then allowed. | [
"Pop",
"the",
"object",
"element",
"if",
"the",
"object",
"contains",
"an",
"higher",
"TLP",
"then",
"allowed",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/SoltraEdge/soltra.py#L92-L116 |
230,863 | TheHive-Project/Cortex-Analyzers | analyzers/CERTatPassiveDNS/whois_wrapper.py | __query | def __query(domain, limit=100):
"""Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str
"""
s = check_output(['{}'.format(os.path.join(os.path.dirname(__file__), 'whois.sh')), '--limit {} {}'.format(limit, domain)], universal_newlines=True)
return s | python | def __query(domain, limit=100):
"""Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str
"""
s = check_output(['{}'.format(os.path.join(os.path.dirname(__file__), 'whois.sh')), '--limit {} {}'.format(limit, domain)], universal_newlines=True)
return s | [
"def",
"__query",
"(",
"domain",
",",
"limit",
"=",
"100",
")",
":",
"s",
"=",
"check_output",
"(",
"[",
"'{}'",
".",
"format",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"'whois.sh'",
")",
")",
",",
"'--limit {} {}'",
".",
"format",
"(",
"limit",
",",
"domain",
")",
"]",
",",
"universal_newlines",
"=",
"True",
")",
"return",
"s"
] | Using the shell script to query pdns.cert.at is a hack, but python raises an error every time using subprocess
functions to call whois. So this hack is avoiding calling whois directly. Ugly, but works.
:param domain: The domain pdns is queried with.
:type domain: str
:param limit: Maximum number of results
:type limit: int
:returns: str -- Console output from whois call.
:rtype: str | [
"Using",
"the",
"shell",
"script",
"to",
"query",
"pdns",
".",
"cert",
".",
"at",
"is",
"a",
"hack",
"but",
"python",
"raises",
"an",
"error",
"every",
"time",
"using",
"subprocess",
"functions",
"to",
"call",
"whois",
".",
"So",
"this",
"hack",
"is",
"avoiding",
"calling",
"whois",
"directly",
".",
"Ugly",
"but",
"works",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CERTatPassiveDNS/whois_wrapper.py#L6-L18 |
230,864 | TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_oletools.py | OLEToolsSubmodule.analyze_vba | def analyze_vba(self, path):
"""Analyze a given sample for malicious vba."""
try:
vba_parser = VBA_Parser_CLI(path, relaxed=True)
vbaparser_result = vba_parser.process_file_json(show_decoded_strings=True,
display_code=True,
hide_attributes=False,
vba_code_only=False,
show_deobfuscated_code=True,
deobfuscate=True)
self.add_result_subsection('Olevba', vbaparser_result)
except TypeError:
self.add_result_subsection('Oletools VBA Analysis failed', 'Analysis failed due to an filetype error.'
'The file does not seem to be a valid MS-Office '
'file.') | python | def analyze_vba(self, path):
"""Analyze a given sample for malicious vba."""
try:
vba_parser = VBA_Parser_CLI(path, relaxed=True)
vbaparser_result = vba_parser.process_file_json(show_decoded_strings=True,
display_code=True,
hide_attributes=False,
vba_code_only=False,
show_deobfuscated_code=True,
deobfuscate=True)
self.add_result_subsection('Olevba', vbaparser_result)
except TypeError:
self.add_result_subsection('Oletools VBA Analysis failed', 'Analysis failed due to an filetype error.'
'The file does not seem to be a valid MS-Office '
'file.') | [
"def",
"analyze_vba",
"(",
"self",
",",
"path",
")",
":",
"try",
":",
"vba_parser",
"=",
"VBA_Parser_CLI",
"(",
"path",
",",
"relaxed",
"=",
"True",
")",
"vbaparser_result",
"=",
"vba_parser",
".",
"process_file_json",
"(",
"show_decoded_strings",
"=",
"True",
",",
"display_code",
"=",
"True",
",",
"hide_attributes",
"=",
"False",
",",
"vba_code_only",
"=",
"False",
",",
"show_deobfuscated_code",
"=",
"True",
",",
"deobfuscate",
"=",
"True",
")",
"self",
".",
"add_result_subsection",
"(",
"'Olevba'",
",",
"vbaparser_result",
")",
"except",
"TypeError",
":",
"self",
".",
"add_result_subsection",
"(",
"'Oletools VBA Analysis failed'",
",",
"'Analysis failed due to an filetype error.'",
"'The file does not seem to be a valid MS-Office '",
"'file.'",
")"
] | Analyze a given sample for malicious vba. | [
"Analyze",
"a",
"given",
"sample",
"for",
"malicious",
"vba",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_oletools.py#L98-L115 |
230,865 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/maxminddb/reader.py | Reader.get | def get(self, ip_address):
"""Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation
"""
address = ipaddress.ip_address(ip_address)
if address.version == 6 and self._metadata.ip_version == 4:
raise ValueError('Error looking up {0}. You attempted to look up '
'an IPv6 address in an IPv4-only database.'.format(
ip_address))
pointer = self._find_address_in_tree(address)
return self._resolve_data_pointer(pointer) if pointer else None | python | def get(self, ip_address):
"""Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation
"""
address = ipaddress.ip_address(ip_address)
if address.version == 6 and self._metadata.ip_version == 4:
raise ValueError('Error looking up {0}. You attempted to look up '
'an IPv6 address in an IPv4-only database.'.format(
ip_address))
pointer = self._find_address_in_tree(address)
return self._resolve_data_pointer(pointer) if pointer else None | [
"def",
"get",
"(",
"self",
",",
"ip_address",
")",
":",
"address",
"=",
"ipaddress",
".",
"ip_address",
"(",
"ip_address",
")",
"if",
"address",
".",
"version",
"==",
"6",
"and",
"self",
".",
"_metadata",
".",
"ip_version",
"==",
"4",
":",
"raise",
"ValueError",
"(",
"'Error looking up {0}. You attempted to look up '",
"'an IPv6 address in an IPv4-only database.'",
".",
"format",
"(",
"ip_address",
")",
")",
"pointer",
"=",
"self",
".",
"_find_address_in_tree",
"(",
"address",
")",
"return",
"self",
".",
"_resolve_data_pointer",
"(",
"pointer",
")",
"if",
"pointer",
"else",
"None"
] | Return the record for the ip_address in the MaxMind DB
Arguments:
ip_address -- an IP address in the standard string notation | [
"Return",
"the",
"record",
"for",
"the",
"ip_address",
"in",
"the",
"MaxMind",
"DB"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/maxminddb/reader.py#L61-L76 |
230,866 | TheHive-Project/Cortex-Analyzers | analyzers/Crtsh/crtshquery.py | CrtshAnalyzer.search | def search(self, domain, wildcard=True):
"""
Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={}
"""
base_url = "https://crt.sh/?q={}&output=json"
if wildcard:
domain = "%25.{}".format(domain)
url = base_url.format(domain)
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
req = requests.get(url, headers={'User-Agent': ua})
if req.ok:
try:
content = req.content.decode('utf-8')
data = json.loads(content.replace('}{', '},{'))
return data
except Exception:
self.error("Error retrieving information.")
return None | python | def search(self, domain, wildcard=True):
"""
Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={}
"""
base_url = "https://crt.sh/?q={}&output=json"
if wildcard:
domain = "%25.{}".format(domain)
url = base_url.format(domain)
ua = 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'
req = requests.get(url, headers={'User-Agent': ua})
if req.ok:
try:
content = req.content.decode('utf-8')
data = json.loads(content.replace('}{', '},{'))
return data
except Exception:
self.error("Error retrieving information.")
return None | [
"def",
"search",
"(",
"self",
",",
"domain",
",",
"wildcard",
"=",
"True",
")",
":",
"base_url",
"=",
"\"https://crt.sh/?q={}&output=json\"",
"if",
"wildcard",
":",
"domain",
"=",
"\"%25.{}\"",
".",
"format",
"(",
"domain",
")",
"url",
"=",
"base_url",
".",
"format",
"(",
"domain",
")",
"ua",
"=",
"'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:40.0) Gecko/20100101 Firefox/40.1'",
"req",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"ua",
"}",
")",
"if",
"req",
".",
"ok",
":",
"try",
":",
"content",
"=",
"req",
".",
"content",
".",
"decode",
"(",
"'utf-8'",
")",
"data",
"=",
"json",
".",
"loads",
"(",
"content",
".",
"replace",
"(",
"'}{'",
",",
"'},{'",
")",
")",
"return",
"data",
"except",
"Exception",
":",
"self",
".",
"error",
"(",
"\"Error retrieving information.\"",
")",
"return",
"None"
] | Search crt.sh for the given domain.
domain -- Domain to search for
wildcard -- Whether or not to prepend a wildcard to the domain
(default: True)
Return a list of a certificate dict:
{
"issuer_ca_id": 16418,
"issuer_name": "C=US, O=Let's Encrypt, CN=Let's Encrypt Authority X3",
"name_value": "hatch.uber.com",
"min_cert_id": 325717795,
"min_entry_timestamp": "2018-02-08T16:47:39.089",
"not_before": "2018-02-08T15:47:39"
}
XML notation would also include the base64 cert:
https://crt.sh/atom?q={} | [
"Search",
"crt",
".",
"sh",
"for",
"the",
"given",
"domain",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Crtsh/crtshquery.py#L10-L47 |
230,867 | TheHive-Project/Cortex-Analyzers | analyzers/MISP/mispclient.py | MISPClient.__search | def __search(self, value, type_attribute):
"""Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none]
"""
results = []
if not value:
raise EmptySearchtermError
for idx, connection in enumerate(self.misp_connections):
misp_response = connection.search(type_attribute=type_attribute, values=value)
# Fixes #94
if isinstance(self.misp_name, list):
name = self.misp_name[idx]
else:
name = self.misp_name
results.append({'url': connection.root_url,
'name': name,
'result': self.__clean(misp_response)})
return results | python | def __search(self, value, type_attribute):
"""Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none]
"""
results = []
if not value:
raise EmptySearchtermError
for idx, connection in enumerate(self.misp_connections):
misp_response = connection.search(type_attribute=type_attribute, values=value)
# Fixes #94
if isinstance(self.misp_name, list):
name = self.misp_name[idx]
else:
name = self.misp_name
results.append({'url': connection.root_url,
'name': name,
'result': self.__clean(misp_response)})
return results | [
"def",
"__search",
"(",
"self",
",",
"value",
",",
"type_attribute",
")",
":",
"results",
"=",
"[",
"]",
"if",
"not",
"value",
":",
"raise",
"EmptySearchtermError",
"for",
"idx",
",",
"connection",
"in",
"enumerate",
"(",
"self",
".",
"misp_connections",
")",
":",
"misp_response",
"=",
"connection",
".",
"search",
"(",
"type_attribute",
"=",
"type_attribute",
",",
"values",
"=",
"value",
")",
"# Fixes #94",
"if",
"isinstance",
"(",
"self",
".",
"misp_name",
",",
"list",
")",
":",
"name",
"=",
"self",
".",
"misp_name",
"[",
"idx",
"]",
"else",
":",
"name",
"=",
"self",
".",
"misp_name",
"results",
".",
"append",
"(",
"{",
"'url'",
":",
"connection",
".",
"root_url",
",",
"'name'",
":",
"name",
",",
"'result'",
":",
"self",
".",
"__clean",
"(",
"misp_response",
")",
"}",
")",
"return",
"results"
] | Search method call wrapper.
:param value: value to search for.
:type value: str
:param type_attribute: attribute types to search for.
:type type_attribute: [list, none] | [
"Search",
"method",
"call",
"wrapper",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MISP/mispclient.py#L213-L236 |
230,868 | TheHive-Project/Cortex-Analyzers | analyzers/TorBlutmagie/tor_blutmagie.py | TorBlutmagieClient.search_tor_node | def search_tor_node(self, data_type, data):
"""Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list
"""
results = []
if data_type == 'ip':
results = self._get_node_from_ip(data)
elif data_type == 'fqdn':
results = self._get_node_from_fqdn(data)
elif data_type == 'domain':
results = self._get_node_from_domain(data)
else:
pass
return {"nodes": results} | python | def search_tor_node(self, data_type, data):
"""Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list
"""
results = []
if data_type == 'ip':
results = self._get_node_from_ip(data)
elif data_type == 'fqdn':
results = self._get_node_from_fqdn(data)
elif data_type == 'domain':
results = self._get_node_from_domain(data)
else:
pass
return {"nodes": results} | [
"def",
"search_tor_node",
"(",
"self",
",",
"data_type",
",",
"data",
")",
":",
"results",
"=",
"[",
"]",
"if",
"data_type",
"==",
"'ip'",
":",
"results",
"=",
"self",
".",
"_get_node_from_ip",
"(",
"data",
")",
"elif",
"data_type",
"==",
"'fqdn'",
":",
"results",
"=",
"self",
".",
"_get_node_from_fqdn",
"(",
"data",
")",
"elif",
"data_type",
"==",
"'domain'",
":",
"results",
"=",
"self",
".",
"_get_node_from_domain",
"(",
"data",
")",
"else",
":",
"pass",
"return",
"{",
"\"nodes\"",
":",
"results",
"}"
] | Lookup an artifact to check if it is a known tor exit node.
:param data_type: The artifact type. Must be one of 'ip', 'fqdn'
or 'domain'
:param data: The artifact to lookup
:type data_type: str
:type data: str
:return: Data relative to the tor node. If the looked-up artifact is
related to a tor exit node it will contain a `nodes` array.
That array will contains a list of nodes containing the
following keys:
- name: name given to the router
- ip: their IP address
- hostname: Hostname of the router
- country_code: ISO2 code of the country hosting the router
- as_name: ASName registering the router
- as_number: ASNumber registering the router
Otherwise, `nodes` will be empty.
:rtype: list | [
"Lookup",
"an",
"artifact",
"to",
"check",
"if",
"it",
"is",
"a",
"known",
"tor",
"exit",
"node",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/TorBlutmagie/tor_blutmagie.py#L80-L110 |
230,869 | TheHive-Project/Cortex-Analyzers | analyzers/Yara/yara_analyzer.py | YaraAnalyzer.check | def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list
"""
result = []
for rule in self.ruleset:
matches = rule.match(file)
for match in matches:
result.append(str(match))
return result | python | def check(self, file):
"""
Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list
"""
result = []
for rule in self.ruleset:
matches = rule.match(file)
for match in matches:
result.append(str(match))
return result | [
"def",
"check",
"(",
"self",
",",
"file",
")",
":",
"result",
"=",
"[",
"]",
"for",
"rule",
"in",
"self",
".",
"ruleset",
":",
"matches",
"=",
"rule",
".",
"match",
"(",
"file",
")",
"for",
"match",
"in",
"matches",
":",
"result",
".",
"append",
"(",
"str",
"(",
"match",
")",
")",
"return",
"result"
] | Checks a given file against all available yara rules
:param file: Path to file
:type file:str
:returns: Python dictionary containing the results
:rtype: list | [
"Checks",
"a",
"given",
"file",
"against",
"all",
"available",
"yara",
"rules"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Yara/yara_analyzer.py#L32-L47 |
230,870 | TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveDNS/circl_passivedns.py | CIRCLPassiveDNSAnalyzer.query | def query(self, domain):
"""The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict]
"""
result = {}
try:
result = self.pdns.query(domain)
except:
self.error('Exception while querying passiveDNS. Check the domain format.')
# Clean the datetime problems in order to correct the json serializability
clean_result = []
for ind, resultset in enumerate(result):
if resultset.get('time_first', None):
resultset['time_first'] = resultset.get('time_first').isoformat(' ')
if resultset.get('time_last', None):
resultset['time_last'] = resultset.get('time_last').isoformat(' ')
clean_result.append(resultset)
return clean_result | python | def query(self, domain):
"""The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict]
"""
result = {}
try:
result = self.pdns.query(domain)
except:
self.error('Exception while querying passiveDNS. Check the domain format.')
# Clean the datetime problems in order to correct the json serializability
clean_result = []
for ind, resultset in enumerate(result):
if resultset.get('time_first', None):
resultset['time_first'] = resultset.get('time_first').isoformat(' ')
if resultset.get('time_last', None):
resultset['time_last'] = resultset.get('time_last').isoformat(' ')
clean_result.append(resultset)
return clean_result | [
"def",
"query",
"(",
"self",
",",
"domain",
")",
":",
"result",
"=",
"{",
"}",
"try",
":",
"result",
"=",
"self",
".",
"pdns",
".",
"query",
"(",
"domain",
")",
"except",
":",
"self",
".",
"error",
"(",
"'Exception while querying passiveDNS. Check the domain format.'",
")",
"# Clean the datetime problems in order to correct the json serializability",
"clean_result",
"=",
"[",
"]",
"for",
"ind",
",",
"resultset",
"in",
"enumerate",
"(",
"result",
")",
":",
"if",
"resultset",
".",
"get",
"(",
"'time_first'",
",",
"None",
")",
":",
"resultset",
"[",
"'time_first'",
"]",
"=",
"resultset",
".",
"get",
"(",
"'time_first'",
")",
".",
"isoformat",
"(",
"' '",
")",
"if",
"resultset",
".",
"get",
"(",
"'time_last'",
",",
"None",
")",
":",
"resultset",
"[",
"'time_last'",
"]",
"=",
"resultset",
".",
"get",
"(",
"'time_last'",
")",
".",
"isoformat",
"(",
"' '",
")",
"clean_result",
".",
"append",
"(",
"resultset",
")",
"return",
"clean_result"
] | The actual query happens here. Time from queries is replaced with isoformat.
:param domain: The domain which should gets queried.
:type domain: str
:returns: List of dicts containing the search results.
:rtype: [list, dict] | [
"The",
"actual",
"query",
"happens",
"here",
".",
"Time",
"from",
"queries",
"is",
"replaced",
"with",
"isoformat",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveDNS/circl_passivedns.py#L13-L37 |
230,871 | TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveSSL/circl_passivessl.py | CIRCLPassiveSSLAnalyzer.query_ip | def query_ip(self, ip):
"""
Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict
"""
try:
result = self.pssl.query(ip)
except:
self.error('Exception during processing with passiveSSL. '
'Please check the format of ip.')
# Check for empty result
# result is always assigned, self.error exits the function.
if not result.get(ip, None):
certificates = []
else:
certificates = list(result.get(ip).get('certificates'))
newresult = {'ip': ip,
'certificates': []}
for cert in certificates:
newresult['certificates'].append({'fingerprint': cert,
'subject': result.get(ip).get('subjects').get(cert).get('values')[0]})
return newresult | python | def query_ip(self, ip):
"""
Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict
"""
try:
result = self.pssl.query(ip)
except:
self.error('Exception during processing with passiveSSL. '
'Please check the format of ip.')
# Check for empty result
# result is always assigned, self.error exits the function.
if not result.get(ip, None):
certificates = []
else:
certificates = list(result.get(ip).get('certificates'))
newresult = {'ip': ip,
'certificates': []}
for cert in certificates:
newresult['certificates'].append({'fingerprint': cert,
'subject': result.get(ip).get('subjects').get(cert).get('values')[0]})
return newresult | [
"def",
"query_ip",
"(",
"self",
",",
"ip",
")",
":",
"try",
":",
"result",
"=",
"self",
".",
"pssl",
".",
"query",
"(",
"ip",
")",
"except",
":",
"self",
".",
"error",
"(",
"'Exception during processing with passiveSSL. '",
"'Please check the format of ip.'",
")",
"# Check for empty result",
"# result is always assigned, self.error exits the function.",
"if",
"not",
"result",
".",
"get",
"(",
"ip",
",",
"None",
")",
":",
"certificates",
"=",
"[",
"]",
"else",
":",
"certificates",
"=",
"list",
"(",
"result",
".",
"get",
"(",
"ip",
")",
".",
"get",
"(",
"'certificates'",
")",
")",
"newresult",
"=",
"{",
"'ip'",
":",
"ip",
",",
"'certificates'",
":",
"[",
"]",
"}",
"for",
"cert",
"in",
"certificates",
":",
"newresult",
"[",
"'certificates'",
"]",
".",
"append",
"(",
"{",
"'fingerprint'",
":",
"cert",
",",
"'subject'",
":",
"result",
".",
"get",
"(",
"ip",
")",
".",
"get",
"(",
"'subjects'",
")",
".",
"get",
"(",
"cert",
")",
".",
"get",
"(",
"'values'",
")",
"[",
"0",
"]",
"}",
")",
"return",
"newresult"
] | Queries Circl.lu Passive SSL for an ip using PyPSSL class. Returns error if nothing is found.
:param ip: IP to query for
:type ip: str
:returns: python dict of results
:rtype: dict | [
"Queries",
"Circl",
".",
"lu",
"Passive",
"SSL",
"for",
"an",
"ip",
"using",
"PyPSSL",
"class",
".",
"Returns",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveSSL/circl_passivessl.py#L16-L43 |
230,872 | TheHive-Project/Cortex-Analyzers | analyzers/CIRCLPassiveSSL/circl_passivessl.py | CIRCLPassiveSSLAnalyzer.query_certificate | def query_certificate(self, cert_hash):
"""
Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict
"""
try:
cquery = self.pssl.query_cert(cert_hash)
except Exception:
self.error('Exception during processing with passiveSSL. '
'This happens if the given hash is not sha1 or contains dashes/colons etc. '
'Please make sure to submit a clean formatted sha1 hash.')
# fetch_cert raises an error if no certificate was found.
try:
cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
except Exception:
cfetch = {}
return {'query': cquery,
'cert': cfetch} | python | def query_certificate(self, cert_hash):
"""
Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict
"""
try:
cquery = self.pssl.query_cert(cert_hash)
except Exception:
self.error('Exception during processing with passiveSSL. '
'This happens if the given hash is not sha1 or contains dashes/colons etc. '
'Please make sure to submit a clean formatted sha1 hash.')
# fetch_cert raises an error if no certificate was found.
try:
cfetch = self.pssl.fetch_cert(cert_hash, make_datetime=False)
except Exception:
cfetch = {}
return {'query': cquery,
'cert': cfetch} | [
"def",
"query_certificate",
"(",
"self",
",",
"cert_hash",
")",
":",
"try",
":",
"cquery",
"=",
"self",
".",
"pssl",
".",
"query_cert",
"(",
"cert_hash",
")",
"except",
"Exception",
":",
"self",
".",
"error",
"(",
"'Exception during processing with passiveSSL. '",
"'This happens if the given hash is not sha1 or contains dashes/colons etc. '",
"'Please make sure to submit a clean formatted sha1 hash.'",
")",
"# fetch_cert raises an error if no certificate was found.",
"try",
":",
"cfetch",
"=",
"self",
".",
"pssl",
".",
"fetch_cert",
"(",
"cert_hash",
",",
"make_datetime",
"=",
"False",
")",
"except",
"Exception",
":",
"cfetch",
"=",
"{",
"}",
"return",
"{",
"'query'",
":",
"cquery",
",",
"'cert'",
":",
"cfetch",
"}"
] | Queries Circl.lu Passive SSL for a certificate hash using PyPSSL class. Returns error if nothing is found.
:param cert_hash: hash to query for
:type cert_hash: str
:return: python dict of results
:rtype: dict | [
"Queries",
"Circl",
".",
"lu",
"Passive",
"SSL",
"for",
"a",
"certificate",
"hash",
"using",
"PyPSSL",
"class",
".",
"Returns",
"error",
"if",
"nothing",
"is",
"found",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/CIRCLPassiveSSL/circl_passivessl.py#L45-L68 |
230,873 | TheHive-Project/Cortex-Analyzers | analyzers/GreyNoise/greynoise.py | GreyNoiseAnalyzer._get_level | def _get_level(current_level, new_intention):
"""
Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level
"""
intention_level_map = OrderedDict([
('info', 'info'),
('benign', 'safe'),
('suspicious', 'suspicious'),
('malicious', 'malicious')
])
levels = intention_level_map.values()
new_level = intention_level_map.get(new_intention, 'info')
new_index = levels.index(new_level)
try:
current_index = levels.index(current_level)
except ValueError: # There is no existing level
current_index = -1
return new_level if new_index > current_index else current_level | python | def _get_level(current_level, new_intention):
"""
Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level
"""
intention_level_map = OrderedDict([
('info', 'info'),
('benign', 'safe'),
('suspicious', 'suspicious'),
('malicious', 'malicious')
])
levels = intention_level_map.values()
new_level = intention_level_map.get(new_intention, 'info')
new_index = levels.index(new_level)
try:
current_index = levels.index(current_level)
except ValueError: # There is no existing level
current_index = -1
return new_level if new_index > current_index else current_level | [
"def",
"_get_level",
"(",
"current_level",
",",
"new_intention",
")",
":",
"intention_level_map",
"=",
"OrderedDict",
"(",
"[",
"(",
"'info'",
",",
"'info'",
")",
",",
"(",
"'benign'",
",",
"'safe'",
")",
",",
"(",
"'suspicious'",
",",
"'suspicious'",
")",
",",
"(",
"'malicious'",
",",
"'malicious'",
")",
"]",
")",
"levels",
"=",
"intention_level_map",
".",
"values",
"(",
")",
"new_level",
"=",
"intention_level_map",
".",
"get",
"(",
"new_intention",
",",
"'info'",
")",
"new_index",
"=",
"levels",
".",
"index",
"(",
"new_level",
")",
"try",
":",
"current_index",
"=",
"levels",
".",
"index",
"(",
"current_level",
")",
"except",
"ValueError",
":",
"# There is no existing level",
"current_index",
"=",
"-",
"1",
"return",
"new_level",
"if",
"new_index",
">",
"current_index",
"else",
"current_level"
] | Map GreyNoise intentions to Cortex maliciousness levels.
Accept a Cortex level and a GreyNoise intention, the return the more malicious of the two.
:param current_level: A Cortex maliciousness level
https://github.com/TheHive-Project/CortexDocs/blob/master/api/how-to-create-an-analyzer.md#output
:param new_intention: An intention field value from a GreyNoise record
https://github.com/GreyNoise-Intelligence/api.greynoise.io#v1queryip
:return: The more malicious of the 2 submitted values as a Cortex maliciousness level | [
"Map",
"GreyNoise",
"intentions",
"to",
"Cortex",
"maliciousness",
"levels",
".",
"Accept",
"a",
"Cortex",
"level",
"and",
"a",
"GreyNoise",
"intention",
"the",
"return",
"the",
"more",
"malicious",
"of",
"the",
"two",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GreyNoise/greynoise.py#L16-L44 |
230,874 | TheHive-Project/Cortex-Analyzers | analyzers/GreyNoise/greynoise.py | GreyNoiseAnalyzer.summary | def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe)
"""
try:
taxonomies = []
if raw.get('records'):
final_level = None
taxonomy_data = defaultdict(int)
for record in raw.get('records', []):
name = record.get('name', 'unknown')
intention = record.get('intention', 'unknown')
taxonomy_data[name] += 1
final_level = self._get_level(final_level, intention)
if len(taxonomy_data) > 1: # Multiple tags have been found
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', 'entries', len(taxonomy_data)))
else: # There is only one tag found, possibly multiple times
for name, count in taxonomy_data.iteritems():
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', name, count))
else:
taxonomies.append(self.build_taxonomy('info', 'GreyNoise', 'Records', 'None'))
return {"taxonomies": taxonomies}
except Exception as e:
self.error('Summary failed\n{}'.format(e.message)) | python | def summary(self, raw):
"""
Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe)
"""
try:
taxonomies = []
if raw.get('records'):
final_level = None
taxonomy_data = defaultdict(int)
for record in raw.get('records', []):
name = record.get('name', 'unknown')
intention = record.get('intention', 'unknown')
taxonomy_data[name] += 1
final_level = self._get_level(final_level, intention)
if len(taxonomy_data) > 1: # Multiple tags have been found
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', 'entries', len(taxonomy_data)))
else: # There is only one tag found, possibly multiple times
for name, count in taxonomy_data.iteritems():
taxonomies.append(self.build_taxonomy(final_level, 'GreyNoise', name, count))
else:
taxonomies.append(self.build_taxonomy('info', 'GreyNoise', 'Records', 'None'))
return {"taxonomies": taxonomies}
except Exception as e:
self.error('Summary failed\n{}'.format(e.message)) | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"try",
":",
"taxonomies",
"=",
"[",
"]",
"if",
"raw",
".",
"get",
"(",
"'records'",
")",
":",
"final_level",
"=",
"None",
"taxonomy_data",
"=",
"defaultdict",
"(",
"int",
")",
"for",
"record",
"in",
"raw",
".",
"get",
"(",
"'records'",
",",
"[",
"]",
")",
":",
"name",
"=",
"record",
".",
"get",
"(",
"'name'",
",",
"'unknown'",
")",
"intention",
"=",
"record",
".",
"get",
"(",
"'intention'",
",",
"'unknown'",
")",
"taxonomy_data",
"[",
"name",
"]",
"+=",
"1",
"final_level",
"=",
"self",
".",
"_get_level",
"(",
"final_level",
",",
"intention",
")",
"if",
"len",
"(",
"taxonomy_data",
")",
">",
"1",
":",
"# Multiple tags have been found",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"final_level",
",",
"'GreyNoise'",
",",
"'entries'",
",",
"len",
"(",
"taxonomy_data",
")",
")",
")",
"else",
":",
"# There is only one tag found, possibly multiple times",
"for",
"name",
",",
"count",
"in",
"taxonomy_data",
".",
"iteritems",
"(",
")",
":",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"final_level",
",",
"'GreyNoise'",
",",
"name",
",",
"count",
")",
")",
"else",
":",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"'info'",
",",
"'GreyNoise'",
",",
"'Records'",
",",
"'None'",
")",
")",
"return",
"{",
"\"taxonomies\"",
":",
"taxonomies",
"}",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"error",
"(",
"'Summary failed\\n{}'",
".",
"format",
"(",
"e",
".",
"message",
")",
")"
] | Return one taxonomy summarizing the reported tags
If there is only one tag, use it as the predicate
If there are multiple tags, use "entries" as the predicate
Use the total count as the value
Use the most malicious level found
Examples:
Input
{
"name": SCANNER1,
"intention": ""
}
Output
GreyNoise:SCANNER1 = 1 (info)
Input
{
"name": SCANNER1,
"intention": "malicious"
},
{
"name": SCANNER1,
"intention": "benign"
}
Output
GreyNoise:SCANNER1 = 2 (malicious)
Input
{
"name": SCANNER1,
"intention": ""
},
{
"name": SCANNER1,
"intention": "safe"
},
{
"name": SCANNER2,
"intention": ""
}
Output
GreyNoise:entries = 3 (safe) | [
"Return",
"one",
"taxonomy",
"summarizing",
"the",
"reported",
"tags",
"If",
"there",
"is",
"only",
"one",
"tag",
"use",
"it",
"as",
"the",
"predicate",
"If",
"there",
"are",
"multiple",
"tags",
"use",
"entries",
"as",
"the",
"predicate",
"Use",
"the",
"total",
"count",
"as",
"the",
"value",
"Use",
"the",
"most",
"malicious",
"level",
"found"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GreyNoise/greynoise.py#L62-L136 |
230,875 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PublicApi.scan_file | def scan_file(self, this_file):
""" Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key}
try:
if type(this_file) == str and os.path.isfile(this_file):
files = {'file': (this_file, open(this_file, 'rb'))}
elif isinstance(this_file, StringIO.StringIO):
files = {'file': this_file.read()}
else:
files = {'file': this_file}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/scan', files=files, params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_file(self, this_file):
""" Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key}
try:
if type(this_file) == str and os.path.isfile(this_file):
files = {'file': (this_file, open(this_file, 'rb'))}
elif isinstance(this_file, StringIO.StringIO):
files = {'file': this_file.read()}
else:
files = {'file': this_file}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/scan', files=files, params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_file",
"(",
"self",
",",
"this_file",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
"}",
"try",
":",
"if",
"type",
"(",
"this_file",
")",
"==",
"str",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"this_file",
")",
":",
"files",
"=",
"{",
"'file'",
":",
"(",
"this_file",
",",
"open",
"(",
"this_file",
",",
"'rb'",
")",
")",
"}",
"elif",
"isinstance",
"(",
"this_file",
",",
"StringIO",
".",
"StringIO",
")",
":",
"files",
"=",
"{",
"'file'",
":",
"this_file",
".",
"read",
"(",
")",
"}",
"else",
":",
"files",
"=",
"{",
"'file'",
":",
"this_file",
"}",
"except",
"TypeError",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base",
"+",
"'file/scan'",
",",
"files",
"=",
"files",
",",
"params",
"=",
"params",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"return",
"_return_response_and_status_code",
"(",
"response",
")"
] | Submit a file to be scanned by VirusTotal
:param this_file: File to be scanned (32MB file size limit)
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"file",
"to",
"be",
"scanned",
"by",
"VirusTotal"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L62-L84 |
230,876 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PublicApi.scan_url | def scan_url(self, this_url):
""" Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key, 'url': this_url}
try:
response = requests.post(self.base + 'url/scan', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_url(self, this_url):
""" Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink.
"""
params = {'apikey': self.api_key, 'url': this_url}
try:
response = requests.post(self.base + 'url/scan', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_url",
"(",
"self",
",",
"this_url",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'url'",
":",
"this_url",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base",
"+",
"'url/scan'",
",",
"params",
"=",
"params",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"return",
"_return_response_and_status_code",
"(",
"response",
")"
] | Submit a URL to be scanned by VirusTotal.
:param this_url: The URL that should be scanned. This parameter accepts a list of URLs (up to 4 with the
standard request rate) so as to perform a batch scanning request with one single call. The
URLs must be separated by a new line character.
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"URL",
"to",
"be",
"scanned",
"by",
"VirusTotal",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L124-L139 |
230,877 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_file | def get_file(self, this_hash):
""" Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content
"""
params = {'apikey': self.api_key, 'hash': this_hash}
try:
response = requests.get(self.base + 'file/download', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
if response.status_code == requests.codes.ok:
return response.content
elif response.status_code == 403:
return dict(error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | python | def get_file(self, this_hash):
""" Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content
"""
params = {'apikey': self.api_key, 'hash': this_hash}
try:
response = requests.get(self.base + 'file/download', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
if response.status_code == requests.codes.ok:
return response.content
elif response.status_code == 403:
return dict(error='You tried to perform calls to functions for which you require a Private API key.',
response_code=response.status_code)
elif response.status_code == 404:
return dict(error='File not found.', response_code=response.status_code)
else:
return dict(response_code=response.status_code) | [
"def",
"get_file",
"(",
"self",
",",
"this_hash",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'hash'",
":",
"this_hash",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'file/download'",
",",
"params",
"=",
"params",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"if",
"response",
".",
"status_code",
"==",
"requests",
".",
"codes",
".",
"ok",
":",
"return",
"response",
".",
"content",
"elif",
"response",
".",
"status_code",
"==",
"403",
":",
"return",
"dict",
"(",
"error",
"=",
"'You tried to perform calls to functions for which you require a Private API key.'",
",",
"response_code",
"=",
"response",
".",
"status_code",
")",
"elif",
"response",
".",
"status_code",
"==",
"404",
":",
"return",
"dict",
"(",
"error",
"=",
"'File not found.'",
",",
"response_code",
"=",
"response",
".",
"status_code",
")",
"else",
":",
"return",
"dict",
"(",
"response_code",
"=",
"response",
".",
"status_code",
")"
] | Download a file by its hash.
Downloads a file from VirusTotal's store given one of its hashes. This call can be used in conjuction with
the file searching call in order to download samples that match a given set of criteria.
:param this_hash: The md5/sha1/sha256 hash of the file you want to download.
:return: Downloaded file in response.content | [
"Download",
"a",
"file",
"by",
"its",
"hash",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L501-L525 |
230,878 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_url_report | def get_url_report(self, this_url, scan='0', allinfo=1):
""" Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response
"""
params = {'apikey': self.api_key, 'resource': this_url, 'scan': scan, 'allinfo': allinfo}
try:
response = requests.get(self.base + 'url/report', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def get_url_report(self, this_url, scan='0', allinfo=1):
""" Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response
"""
params = {'apikey': self.api_key, 'resource': this_url, 'scan': scan, 'allinfo': allinfo}
try:
response = requests.get(self.base + 'url/report', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"get_url_report",
"(",
"self",
",",
"this_url",
",",
"scan",
"=",
"'0'",
",",
"allinfo",
"=",
"1",
")",
":",
"params",
"=",
"{",
"'apikey'",
":",
"self",
".",
"api_key",
",",
"'resource'",
":",
"this_url",
",",
"'scan'",
":",
"scan",
",",
"'allinfo'",
":",
"allinfo",
"}",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'url/report'",
",",
"params",
"=",
"params",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"return",
"_return_response_and_status_code",
"(",
"response",
")"
] | Get the scan results for a URL.
:param this_url: A URL for which you want to retrieve the most recent report. You may also specify a scan_id
(sha256-timestamp as returned by the URL submission API) to access a specific report. At the same time, you
can specify a CSV list made up of a combination of urls and scan_ids (up to 25 items) so as to perform a batch
request with one single call. The CSV list must be separated by new line characters.
:param scan: (optional) This is an optional parameter that when set to "1" will automatically submit the URL
for analysis if no report is found for it in VirusTotal's database. In this case the result will contain a
scan_id field that can be used to query the analysis report later on.
:param allinfo: (optional) If this parameter is specified and set to "1" additional info regarding the URL
(other than the URL scanning engine results) will also be returned. This additional info includes VirusTotal
related metadata (first seen date, last seen date, files downloaded from the given URL, etc.) and the output
of other tools and datasets when fed with the URL.
:return: JSON response | [
"Get",
"the",
"scan",
"results",
"for",
"a",
"URL",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L548-L572 |
230,879 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | PrivateApi.get_comments | def get_comments(self, resource, before=None):
""" Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date.
"""
params = dict(apikey=self.api_key, resource=resource, before=before)
try:
response = requests.get(self.base + 'comments/get', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def get_comments(self, resource, before=None):
""" Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date.
"""
params = dict(apikey=self.api_key, resource=resource, before=before)
try:
response = requests.get(self.base + 'comments/get', params=params, proxies=self.proxies)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"get_comments",
"(",
"self",
",",
"resource",
",",
"before",
"=",
"None",
")",
":",
"params",
"=",
"dict",
"(",
"apikey",
"=",
"self",
".",
"api_key",
",",
"resource",
"=",
"resource",
",",
"before",
"=",
"before",
")",
"try",
":",
"response",
"=",
"requests",
".",
"get",
"(",
"self",
".",
"base",
"+",
"'comments/get'",
",",
"params",
"=",
"params",
",",
"proxies",
"=",
"self",
".",
"proxies",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"return",
"_return_response_and_status_code",
"(",
"response",
")"
] | Get comments for a file or URL.
Retrieve a list of VirusTotal Community comments for a given file or URL. VirusTotal Community comments are
user submitted reviews on a given item, these comments may contain anything from the in-the-wild locations of
files up to fully-featured reverse engineering reports on a given sample.
:param resource: Either an md5/sha1/sha256 hash of the file or the URL itself you want to retrieve.
:param before: (optional) A datetime token that allows you to iterate over all comments on a specific item
whenever it has been commented on more than 25 times.
:return: JSON response - The application answers with the comments sorted in descending order according to
their date. | [
"Get",
"comments",
"for",
"a",
"file",
"or",
"URL",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L659-L679 |
230,880 | TheHive-Project/Cortex-Analyzers | analyzers/VirusTotal/virustotal_api.py | IntelApi.save_downloaded_file | def save_downloaded_file(filename, save_file_at, file_stream):
""" Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file.
"""
filename = os.path.join(save_file_at, filename)
with open(filename, 'wb') as f:
f.write(file_stream)
f.flush() | python | def save_downloaded_file(filename, save_file_at, file_stream):
""" Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file.
"""
filename = os.path.join(save_file_at, filename)
with open(filename, 'wb') as f:
f.write(file_stream)
f.flush() | [
"def",
"save_downloaded_file",
"(",
"filename",
",",
"save_file_at",
",",
"file_stream",
")",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"save_file_at",
",",
"filename",
")",
"with",
"open",
"(",
"filename",
",",
"'wb'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"file_stream",
")",
"f",
".",
"flush",
"(",
")"
] | Save Downloaded File to Disk Helper Function
:param save_file_at: Path of where to save the file.
:param file_stream: File stream
:param filename: Name to save the file. | [
"Save",
"Downloaded",
"File",
"to",
"Disk",
"Helper",
"Function"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VirusTotal/virustotal_api.py#L758-L768 |
230,881 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/geoip2/records.py | PlaceRecord.name | def name(self):
"""Dict with locale codes as keys and localized name as value"""
# pylint:disable=E1101
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | python | def name(self):
"""Dict with locale codes as keys and localized name as value"""
# pylint:disable=E1101
return next((self.names.get(x) for x in self._locales if x in
self.names), None) | [
"def",
"name",
"(",
"self",
")",
":",
"# pylint:disable=E1101",
"return",
"next",
"(",
"(",
"self",
".",
"names",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"self",
".",
"_locales",
"if",
"x",
"in",
"self",
".",
"names",
")",
",",
"None",
")"
] | Dict with locale codes as keys and localized name as value | [
"Dict",
"with",
"locale",
"codes",
"as",
"keys",
"and",
"localized",
"name",
"as",
"value"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/geoip2/records.py#L40-L44 |
230,882 | TheHive-Project/Cortex-Analyzers | analyzers/Patrowl/patrowl.py | PatrowlAnalyzer.summary | def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = "info"
namespace = "Patrowl"
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_level']
# Grade
if risk_level['grade'] in ["A", "B"]:
level = "safe"
else:
level = "suspicious"
taxonomies.append(self.build_taxonomy(level, namespace, "Grade", risk_level['grade']))
# Findings
if risk_level['high'] > 0:
level = "malicious"
elif risk_level['medium'] > 0 or risk_level['low'] > 0:
level = "suspicious"
else:
level = "info"
taxonomies.append(self.build_taxonomy(
level, namespace, "Findings", "{}/{}/{}/{}".format(
risk_level['high'],
risk_level['medium'],
risk_level['low'],
risk_level['info']
)))
#todo: add_asset service
return {"taxonomies": taxonomies} | python | def summary(self, raw):
"""Parse, format and return scan summary."""
taxonomies = []
level = "info"
namespace = "Patrowl"
# getreport service
if self.service == 'getreport':
if 'risk_level' in raw and raw['risk_level']:
risk_level = raw['risk_level']
# Grade
if risk_level['grade'] in ["A", "B"]:
level = "safe"
else:
level = "suspicious"
taxonomies.append(self.build_taxonomy(level, namespace, "Grade", risk_level['grade']))
# Findings
if risk_level['high'] > 0:
level = "malicious"
elif risk_level['medium'] > 0 or risk_level['low'] > 0:
level = "suspicious"
else:
level = "info"
taxonomies.append(self.build_taxonomy(
level, namespace, "Findings", "{}/{}/{}/{}".format(
risk_level['high'],
risk_level['medium'],
risk_level['low'],
risk_level['info']
)))
#todo: add_asset service
return {"taxonomies": taxonomies} | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"taxonomies",
"=",
"[",
"]",
"level",
"=",
"\"info\"",
"namespace",
"=",
"\"Patrowl\"",
"# getreport service",
"if",
"self",
".",
"service",
"==",
"'getreport'",
":",
"if",
"'risk_level'",
"in",
"raw",
"and",
"raw",
"[",
"'risk_level'",
"]",
":",
"risk_level",
"=",
"raw",
"[",
"'risk_level'",
"]",
"# Grade",
"if",
"risk_level",
"[",
"'grade'",
"]",
"in",
"[",
"\"A\"",
",",
"\"B\"",
"]",
":",
"level",
"=",
"\"safe\"",
"else",
":",
"level",
"=",
"\"suspicious\"",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"\"Grade\"",
",",
"risk_level",
"[",
"'grade'",
"]",
")",
")",
"# Findings",
"if",
"risk_level",
"[",
"'high'",
"]",
">",
"0",
":",
"level",
"=",
"\"malicious\"",
"elif",
"risk_level",
"[",
"'medium'",
"]",
">",
"0",
"or",
"risk_level",
"[",
"'low'",
"]",
">",
"0",
":",
"level",
"=",
"\"suspicious\"",
"else",
":",
"level",
"=",
"\"info\"",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"\"Findings\"",
",",
"\"{}/{}/{}/{}\"",
".",
"format",
"(",
"risk_level",
"[",
"'high'",
"]",
",",
"risk_level",
"[",
"'medium'",
"]",
",",
"risk_level",
"[",
"'low'",
"]",
",",
"risk_level",
"[",
"'info'",
"]",
")",
")",
")",
"#todo: add_asset service",
"return",
"{",
"\"taxonomies\"",
":",
"taxonomies",
"}"
] | Parse, format and return scan summary. | [
"Parse",
"format",
"and",
"return",
"scan",
"summary",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Patrowl/patrowl.py#L17-L53 |
230,883 | TheHive-Project/Cortex-Analyzers | analyzers/Patrowl/patrowl.py | PatrowlAnalyzer.run | def run(self):
"""Run the analyzer."""
try:
if self.service == 'getreport':
service_url = '{}/assets/api/v1/details/{}'.format(
self.url, self.get_data())
headers = {
'Authorization': 'token {}'.format(self.api_key)
}
response = requests.get(service_url, headers=headers)
self.report(response.json())
else:
self.error('Unknown Patrowl service')
except Exception as e:
self.unexpectedError(e) | python | def run(self):
"""Run the analyzer."""
try:
if self.service == 'getreport':
service_url = '{}/assets/api/v1/details/{}'.format(
self.url, self.get_data())
headers = {
'Authorization': 'token {}'.format(self.api_key)
}
response = requests.get(service_url, headers=headers)
self.report(response.json())
else:
self.error('Unknown Patrowl service')
except Exception as e:
self.unexpectedError(e) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"service",
"==",
"'getreport'",
":",
"service_url",
"=",
"'{}/assets/api/v1/details/{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"self",
".",
"get_data",
"(",
")",
")",
"headers",
"=",
"{",
"'Authorization'",
":",
"'token {}'",
".",
"format",
"(",
"self",
".",
"api_key",
")",
"}",
"response",
"=",
"requests",
".",
"get",
"(",
"service_url",
",",
"headers",
"=",
"headers",
")",
"self",
".",
"report",
"(",
"response",
".",
"json",
"(",
")",
")",
"else",
":",
"self",
".",
"error",
"(",
"'Unknown Patrowl service'",
")",
"except",
"Exception",
"as",
"e",
":",
"self",
".",
"unexpectedError",
"(",
"e",
")"
] | Run the analyzer. | [
"Run",
"the",
"analyzer",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Patrowl/patrowl.py#L55-L73 |
230,884 | TheHive-Project/Cortex-Analyzers | analyzers/BackscatterIO/backscatter-io.py | BackscatterAnalyzer.run | def run(self):
"""Run the process to get observation data from Backscatter.io."""
kwargs = {'query': self.get_data()}
if self.data_type == "ip":
kwargs.update({'query_type': 'ip'})
elif self.data_type == "network":
kwargs.update({'query_type': 'network'})
elif self.data_type == 'autonomous-system':
kwargs.update({'query_type': 'asn'})
elif self.data_type == 'port':
kwargs.update({'query_type': 'port'})
else:
self.notSupported()
return False
if self.service == 'observations':
response = self.bs.get_observations(**kwargs)
self.report(response)
elif self.service == 'enrichment':
response = self.bs.enrich(**kwargs)
self.report(response)
else:
self.report({'error': 'Invalid service defined.'}) | python | def run(self):
"""Run the process to get observation data from Backscatter.io."""
kwargs = {'query': self.get_data()}
if self.data_type == "ip":
kwargs.update({'query_type': 'ip'})
elif self.data_type == "network":
kwargs.update({'query_type': 'network'})
elif self.data_type == 'autonomous-system':
kwargs.update({'query_type': 'asn'})
elif self.data_type == 'port':
kwargs.update({'query_type': 'port'})
else:
self.notSupported()
return False
if self.service == 'observations':
response = self.bs.get_observations(**kwargs)
self.report(response)
elif self.service == 'enrichment':
response = self.bs.enrich(**kwargs)
self.report(response)
else:
self.report({'error': 'Invalid service defined.'}) | [
"def",
"run",
"(",
"self",
")",
":",
"kwargs",
"=",
"{",
"'query'",
":",
"self",
".",
"get_data",
"(",
")",
"}",
"if",
"self",
".",
"data_type",
"==",
"\"ip\"",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'ip'",
"}",
")",
"elif",
"self",
".",
"data_type",
"==",
"\"network\"",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'network'",
"}",
")",
"elif",
"self",
".",
"data_type",
"==",
"'autonomous-system'",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'asn'",
"}",
")",
"elif",
"self",
".",
"data_type",
"==",
"'port'",
":",
"kwargs",
".",
"update",
"(",
"{",
"'query_type'",
":",
"'port'",
"}",
")",
"else",
":",
"self",
".",
"notSupported",
"(",
")",
"return",
"False",
"if",
"self",
".",
"service",
"==",
"'observations'",
":",
"response",
"=",
"self",
".",
"bs",
".",
"get_observations",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"report",
"(",
"response",
")",
"elif",
"self",
".",
"service",
"==",
"'enrichment'",
":",
"response",
"=",
"self",
".",
"bs",
".",
"enrich",
"(",
"*",
"*",
"kwargs",
")",
"self",
".",
"report",
"(",
"response",
")",
"else",
":",
"self",
".",
"report",
"(",
"{",
"'error'",
":",
"'Invalid service defined.'",
"}",
")"
] | Run the process to get observation data from Backscatter.io. | [
"Run",
"the",
"process",
"to",
"get",
"observation",
"data",
"from",
"Backscatter",
".",
"io",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/BackscatterIO/backscatter-io.py#L28-L50 |
230,885 | TheHive-Project/Cortex-Analyzers | analyzers/BackscatterIO/backscatter-io.py | BackscatterAnalyzer.summary | def summary(self, raw):
"""Use the Backscatter.io summary data to create a view."""
taxonomies = list()
level = 'info'
namespace = 'Backscatter.io'
if self.service == 'observations':
summary = raw.get('results', dict()).get('summary', dict())
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Observations', summary.get('observations_count', 0)),
self.build_taxonomy(level, namespace, 'IP Addresses', summary.get('ip_address_count', 0)),
self.build_taxonomy(level, namespace, 'Networks', summary.get('network_count', 0)),
self.build_taxonomy(level, namespace, 'AS', summary.get('autonomous_system_count', 0)),
self.build_taxonomy(level, namespace, 'Ports', summary.get('port_count', 0)),
self.build_taxonomy(level, namespace, 'Protocols', summary.get('protocol_count', 0))
]
elif self.service == 'enrichment':
summary = raw.get('results', dict())
if self.data_type == 'ip':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network', summary.get('network')),
self.build_taxonomy(level, namespace, 'Network Broadcast', summary.get('network_broadcast')),
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size')),
self.build_taxonomy(level, namespace, 'Country', summary.get('country_name')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name')),
]
elif self.data_type == 'network':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size'))
]
elif self.data_type == 'autonomous-system':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Prefix Count', summary.get('prefix_count')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name'))
]
elif self.data_type == 'port':
for result in raw.get('results', list()):
display = "%s (%s)" % (result.get('service'), result.get('protocol'))
taxonomies.append(self.build_taxonomy(level, namespace, 'Service', display))
else:
pass
else:
pass
return {"taxonomies": taxonomies} | python | def summary(self, raw):
"""Use the Backscatter.io summary data to create a view."""
taxonomies = list()
level = 'info'
namespace = 'Backscatter.io'
if self.service == 'observations':
summary = raw.get('results', dict()).get('summary', dict())
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Observations', summary.get('observations_count', 0)),
self.build_taxonomy(level, namespace, 'IP Addresses', summary.get('ip_address_count', 0)),
self.build_taxonomy(level, namespace, 'Networks', summary.get('network_count', 0)),
self.build_taxonomy(level, namespace, 'AS', summary.get('autonomous_system_count', 0)),
self.build_taxonomy(level, namespace, 'Ports', summary.get('port_count', 0)),
self.build_taxonomy(level, namespace, 'Protocols', summary.get('protocol_count', 0))
]
elif self.service == 'enrichment':
summary = raw.get('results', dict())
if self.data_type == 'ip':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network', summary.get('network')),
self.build_taxonomy(level, namespace, 'Network Broadcast', summary.get('network_broadcast')),
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size')),
self.build_taxonomy(level, namespace, 'Country', summary.get('country_name')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name')),
]
elif self.data_type == 'network':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Network Size', summary.get('network_size'))
]
elif self.data_type == 'autonomous-system':
taxonomies = taxonomies + [
self.build_taxonomy(level, namespace, 'Prefix Count', summary.get('prefix_count')),
self.build_taxonomy(level, namespace, 'AS Number', summary.get('as_num')),
self.build_taxonomy(level, namespace, 'AS Name', summary.get('as_name'))
]
elif self.data_type == 'port':
for result in raw.get('results', list()):
display = "%s (%s)" % (result.get('service'), result.get('protocol'))
taxonomies.append(self.build_taxonomy(level, namespace, 'Service', display))
else:
pass
else:
pass
return {"taxonomies": taxonomies} | [
"def",
"summary",
"(",
"self",
",",
"raw",
")",
":",
"taxonomies",
"=",
"list",
"(",
")",
"level",
"=",
"'info'",
"namespace",
"=",
"'Backscatter.io'",
"if",
"self",
".",
"service",
"==",
"'observations'",
":",
"summary",
"=",
"raw",
".",
"get",
"(",
"'results'",
",",
"dict",
"(",
")",
")",
".",
"get",
"(",
"'summary'",
",",
"dict",
"(",
")",
")",
"taxonomies",
"=",
"taxonomies",
"+",
"[",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Observations'",
",",
"summary",
".",
"get",
"(",
"'observations_count'",
",",
"0",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'IP Addresses'",
",",
"summary",
".",
"get",
"(",
"'ip_address_count'",
",",
"0",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Networks'",
",",
"summary",
".",
"get",
"(",
"'network_count'",
",",
"0",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'AS'",
",",
"summary",
".",
"get",
"(",
"'autonomous_system_count'",
",",
"0",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Ports'",
",",
"summary",
".",
"get",
"(",
"'port_count'",
",",
"0",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Protocols'",
",",
"summary",
".",
"get",
"(",
"'protocol_count'",
",",
"0",
")",
")",
"]",
"elif",
"self",
".",
"service",
"==",
"'enrichment'",
":",
"summary",
"=",
"raw",
".",
"get",
"(",
"'results'",
",",
"dict",
"(",
")",
")",
"if",
"self",
".",
"data_type",
"==",
"'ip'",
":",
"taxonomies",
"=",
"taxonomies",
"+",
"[",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Network'",
",",
"summary",
".",
"get",
"(",
"'network'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Network Broadcast'",
",",
"summary",
".",
"get",
"(",
"'network_broadcast'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Network Size'",
",",
"summary",
".",
"get",
"(",
"'network_size'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Country'",
",",
"summary",
".",
"get",
"(",
"'country_name'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'AS Number'",
",",
"summary",
".",
"get",
"(",
"'as_num'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'AS Name'",
",",
"summary",
".",
"get",
"(",
"'as_name'",
")",
")",
",",
"]",
"elif",
"self",
".",
"data_type",
"==",
"'network'",
":",
"taxonomies",
"=",
"taxonomies",
"+",
"[",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Network Size'",
",",
"summary",
".",
"get",
"(",
"'network_size'",
")",
")",
"]",
"elif",
"self",
".",
"data_type",
"==",
"'autonomous-system'",
":",
"taxonomies",
"=",
"taxonomies",
"+",
"[",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Prefix Count'",
",",
"summary",
".",
"get",
"(",
"'prefix_count'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'AS Number'",
",",
"summary",
".",
"get",
"(",
"'as_num'",
")",
")",
",",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'AS Name'",
",",
"summary",
".",
"get",
"(",
"'as_name'",
")",
")",
"]",
"elif",
"self",
".",
"data_type",
"==",
"'port'",
":",
"for",
"result",
"in",
"raw",
".",
"get",
"(",
"'results'",
",",
"list",
"(",
")",
")",
":",
"display",
"=",
"\"%s (%s)\"",
"%",
"(",
"result",
".",
"get",
"(",
"'service'",
")",
",",
"result",
".",
"get",
"(",
"'protocol'",
")",
")",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"level",
",",
"namespace",
",",
"'Service'",
",",
"display",
")",
")",
"else",
":",
"pass",
"else",
":",
"pass",
"return",
"{",
"\"taxonomies\"",
":",
"taxonomies",
"}"
] | Use the Backscatter.io summary data to create a view. | [
"Use",
"the",
"Backscatter",
".",
"io",
"summary",
"data",
"to",
"create",
"a",
"view",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/BackscatterIO/backscatter-io.py#L52-L97 |
230,886 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/maxminddb/decoder.py | Decoder.decode | def decode(self, offset):
"""Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode
"""
new_offset = offset + 1
(ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset])
type_num = ctrl_byte >> 5
# Extended type
if not type_num:
(type_num, new_offset) = self._read_extended(new_offset)
(size, new_offset) = self._size_from_ctrl_byte(
ctrl_byte, new_offset, type_num)
return self._type_decoder[type_num](self, size, new_offset) | python | def decode(self, offset):
"""Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode
"""
new_offset = offset + 1
(ctrl_byte,) = struct.unpack(b'!B', self._buffer[offset:new_offset])
type_num = ctrl_byte >> 5
# Extended type
if not type_num:
(type_num, new_offset) = self._read_extended(new_offset)
(size, new_offset) = self._size_from_ctrl_byte(
ctrl_byte, new_offset, type_num)
return self._type_decoder[type_num](self, size, new_offset) | [
"def",
"decode",
"(",
"self",
",",
"offset",
")",
":",
"new_offset",
"=",
"offset",
"+",
"1",
"(",
"ctrl_byte",
",",
")",
"=",
"struct",
".",
"unpack",
"(",
"b'!B'",
",",
"self",
".",
"_buffer",
"[",
"offset",
":",
"new_offset",
"]",
")",
"type_num",
"=",
"ctrl_byte",
">>",
"5",
"# Extended type",
"if",
"not",
"type_num",
":",
"(",
"type_num",
",",
"new_offset",
")",
"=",
"self",
".",
"_read_extended",
"(",
"new_offset",
")",
"(",
"size",
",",
"new_offset",
")",
"=",
"self",
".",
"_size_from_ctrl_byte",
"(",
"ctrl_byte",
",",
"new_offset",
",",
"type_num",
")",
"return",
"self",
".",
"_type_decoder",
"[",
"type_num",
"]",
"(",
"self",
",",
"size",
",",
"new_offset",
")"
] | Decode a section of the data section starting at offset
Arguments:
offset -- the location of the data structure to decode | [
"Decode",
"a",
"section",
"of",
"the",
"data",
"section",
"starting",
"at",
"offset"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/maxminddb/decoder.py#L116-L131 |
230,887 | TheHive-Project/Cortex-Analyzers | analyzers/VMRay/vmrayclient.py | VMRayClient.get_sample | def get_sample(self, samplehash):
"""
Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/'
if len(samplehash) == 32: # MD5
apiurl += 'md5/'
elif len(samplehash) == 40: # SHA1
apiurl += 'sha1/'
elif len(samplehash) == 64: # SHA256
apiurl += 'sha256/'
else:
raise UnknownHashTypeError('Sample hash has an unknown length.')
res = self.session.get(self.url + apiurl + samplehash)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text)) | python | def get_sample(self, samplehash):
"""
Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/'
if len(samplehash) == 32: # MD5
apiurl += 'md5/'
elif len(samplehash) == 40: # SHA1
apiurl += 'sha1/'
elif len(samplehash) == 64: # SHA256
apiurl += 'sha256/'
else:
raise UnknownHashTypeError('Sample hash has an unknown length.')
res = self.session.get(self.url + apiurl + samplehash)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text)) | [
"def",
"get_sample",
"(",
"self",
",",
"samplehash",
")",
":",
"apiurl",
"=",
"'/rest/sample/'",
"if",
"len",
"(",
"samplehash",
")",
"==",
"32",
":",
"# MD5",
"apiurl",
"+=",
"'md5/'",
"elif",
"len",
"(",
"samplehash",
")",
"==",
"40",
":",
"# SHA1",
"apiurl",
"+=",
"'sha1/'",
"elif",
"len",
"(",
"samplehash",
")",
"==",
"64",
":",
"# SHA256",
"apiurl",
"+=",
"'sha256/'",
"else",
":",
"raise",
"UnknownHashTypeError",
"(",
"'Sample hash has an unknown length.'",
")",
"res",
"=",
"self",
".",
"session",
".",
"get",
"(",
"self",
".",
"url",
"+",
"apiurl",
"+",
"samplehash",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"text",
")",
"else",
":",
"raise",
"BadResponseError",
"(",
"'Response from VMRay was not HTTP 200.'",
"' Responsecode: {}; Text: {}'",
".",
"format",
"(",
"res",
".",
"status_code",
",",
"res",
".",
"text",
")",
")"
] | Downloads information about a sample using a given hash.
:param samplehash: hash to search for. Has to be either md5, sha1 or sha256
:type samplehash: str
:returns: Dictionary of results
:rtype: dict | [
"Downloads",
"information",
"about",
"a",
"sample",
"using",
"a",
"given",
"hash",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VMRay/vmrayclient.py#L69-L93 |
230,888 | TheHive-Project/Cortex-Analyzers | analyzers/VMRay/vmrayclient.py | VMRayClient.submit_sample | def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/submit?sample_file'
params = {'sample_filename_b64enc': base64.b64encode(filename.encode('utf-8')),
'reanalyze': self.reanalyze}
if tags:
params['tags'] = ','.join(tags)
if os.path.isfile(filepath):
res = self.session.post(url=self.url + apiurl,
files=[('sample_file', open(filepath, mode='rb'))],
params=params)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text))
else:
raise SampleFileNotFoundError('Given sample file was not found.') | python | def submit_sample(self, filepath, filename, tags=['TheHive']):
"""
Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict
"""
apiurl = '/rest/sample/submit?sample_file'
params = {'sample_filename_b64enc': base64.b64encode(filename.encode('utf-8')),
'reanalyze': self.reanalyze}
if tags:
params['tags'] = ','.join(tags)
if os.path.isfile(filepath):
res = self.session.post(url=self.url + apiurl,
files=[('sample_file', open(filepath, mode='rb'))],
params=params)
if res.status_code == 200:
return json.loads(res.text)
else:
raise BadResponseError('Response from VMRay was not HTTP 200.'
' Responsecode: {}; Text: {}'.format(res.status_code, res.text))
else:
raise SampleFileNotFoundError('Given sample file was not found.') | [
"def",
"submit_sample",
"(",
"self",
",",
"filepath",
",",
"filename",
",",
"tags",
"=",
"[",
"'TheHive'",
"]",
")",
":",
"apiurl",
"=",
"'/rest/sample/submit?sample_file'",
"params",
"=",
"{",
"'sample_filename_b64enc'",
":",
"base64",
".",
"b64encode",
"(",
"filename",
".",
"encode",
"(",
"'utf-8'",
")",
")",
",",
"'reanalyze'",
":",
"self",
".",
"reanalyze",
"}",
"if",
"tags",
":",
"params",
"[",
"'tags'",
"]",
"=",
"','",
".",
"join",
"(",
"tags",
")",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"filepath",
")",
":",
"res",
"=",
"self",
".",
"session",
".",
"post",
"(",
"url",
"=",
"self",
".",
"url",
"+",
"apiurl",
",",
"files",
"=",
"[",
"(",
"'sample_file'",
",",
"open",
"(",
"filepath",
",",
"mode",
"=",
"'rb'",
")",
")",
"]",
",",
"params",
"=",
"params",
")",
"if",
"res",
".",
"status_code",
"==",
"200",
":",
"return",
"json",
".",
"loads",
"(",
"res",
".",
"text",
")",
"else",
":",
"raise",
"BadResponseError",
"(",
"'Response from VMRay was not HTTP 200.'",
"' Responsecode: {}; Text: {}'",
".",
"format",
"(",
"res",
".",
"status_code",
",",
"res",
".",
"text",
")",
")",
"else",
":",
"raise",
"SampleFileNotFoundError",
"(",
"'Given sample file was not found.'",
")"
] | Uploads a new sample to VMRay api. Filename gets sent base64 encoded.
:param filepath: path to sample
:type filepath: str
:param filename: filename of the original file
:type filename: str
:param tags: List of tags to apply to the sample
:type tags: list(str)
:returns: Dictionary of results
:rtype: dict | [
"Uploads",
"a",
"new",
"sample",
"to",
"VMRay",
"api",
".",
"Filename",
"gets",
"sent",
"base64",
"encoded",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/VMRay/vmrayclient.py#L95-L124 |
230,889 | TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_manalyze.py | ManalyzeSubmodule.build_results | def build_results(self, results):
"""Properly format the results"""
self.add_result_subsection(
'Exploit mitigation techniques',
{
'level': results.get('Plugins', {}).get('mitigation', {}).get('level', None),
'summary': results.get('Plugins', {}).get('mitigation', {}).get('summary', None),
'content': results.get('Plugins', {}).get('mitigation', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious strings',
{
'level': results.get('Plugins', {}).get('strings', {}).get('level', None),
'summary': results.get('Plugins', {}).get('strings', {}).get('summary', None),
'content': results.get('Plugins', {}).get('strings', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious imports',
{
'level': results.get('Plugins', {}).get('imports', {}).get('level', None),
'summary': results.get('Plugins', {}).get('imports', {}).get('summary', None),
'content': results.get('Plugins', {}).get('imports', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Packer',
{
'level': results.get('Plugins', {}).get('packer', {}).get('level', None),
'summary': results.get('Plugins', {}).get('packer', {}).get('summary', None),
'content': results.get('Plugins', {}).get('packer', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Clamav',
{
'level': results.get('Plugins', {}).get('clamav', {}).get('level', None),
'summary': results.get('Plugins', {}).get('clamav', {}).get('summary', None),
'content': results.get('Plugins', {}).get('clamav', {}).get('plugin_output', None)
}
)
self.add_result_subsection('Manalyze raw output', json.dumps(results, indent=4)) | python | def build_results(self, results):
"""Properly format the results"""
self.add_result_subsection(
'Exploit mitigation techniques',
{
'level': results.get('Plugins', {}).get('mitigation', {}).get('level', None),
'summary': results.get('Plugins', {}).get('mitigation', {}).get('summary', None),
'content': results.get('Plugins', {}).get('mitigation', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious strings',
{
'level': results.get('Plugins', {}).get('strings', {}).get('level', None),
'summary': results.get('Plugins', {}).get('strings', {}).get('summary', None),
'content': results.get('Plugins', {}).get('strings', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Suspicious imports',
{
'level': results.get('Plugins', {}).get('imports', {}).get('level', None),
'summary': results.get('Plugins', {}).get('imports', {}).get('summary', None),
'content': results.get('Plugins', {}).get('imports', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Packer',
{
'level': results.get('Plugins', {}).get('packer', {}).get('level', None),
'summary': results.get('Plugins', {}).get('packer', {}).get('summary', None),
'content': results.get('Plugins', {}).get('packer', {}).get('plugin_output', None)
}
)
self.add_result_subsection(
'Clamav',
{
'level': results.get('Plugins', {}).get('clamav', {}).get('level', None),
'summary': results.get('Plugins', {}).get('clamav', {}).get('summary', None),
'content': results.get('Plugins', {}).get('clamav', {}).get('plugin_output', None)
}
)
self.add_result_subsection('Manalyze raw output', json.dumps(results, indent=4)) | [
"def",
"build_results",
"(",
"self",
",",
"results",
")",
":",
"self",
".",
"add_result_subsection",
"(",
"'Exploit mitigation techniques'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mitigation'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'level'",
",",
"None",
")",
",",
"'summary'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mitigation'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'summary'",
",",
"None",
")",
",",
"'content'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'mitigation'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'plugin_output'",
",",
"None",
")",
"}",
")",
"self",
".",
"add_result_subsection",
"(",
"'Suspicious strings'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'strings'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'level'",
",",
"None",
")",
",",
"'summary'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'strings'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'summary'",
",",
"None",
")",
",",
"'content'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'strings'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'plugin_output'",
",",
"None",
")",
"}",
")",
"self",
".",
"add_result_subsection",
"(",
"'Suspicious imports'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'imports'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'level'",
",",
"None",
")",
",",
"'summary'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'imports'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'summary'",
",",
"None",
")",
",",
"'content'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'imports'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'plugin_output'",
",",
"None",
")",
"}",
")",
"self",
".",
"add_result_subsection",
"(",
"'Packer'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'packer'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'level'",
",",
"None",
")",
",",
"'summary'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'packer'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'summary'",
",",
"None",
")",
",",
"'content'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'packer'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'plugin_output'",
",",
"None",
")",
"}",
")",
"self",
".",
"add_result_subsection",
"(",
"'Clamav'",
",",
"{",
"'level'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'clamav'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'level'",
",",
"None",
")",
",",
"'summary'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'clamav'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'summary'",
",",
"None",
")",
",",
"'content'",
":",
"results",
".",
"get",
"(",
"'Plugins'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'clamav'",
",",
"{",
"}",
")",
".",
"get",
"(",
"'plugin_output'",
",",
"None",
")",
"}",
")",
"self",
".",
"add_result_subsection",
"(",
"'Manalyze raw output'",
",",
"json",
".",
"dumps",
"(",
"results",
",",
"indent",
"=",
"4",
")",
")"
] | Properly format the results | [
"Properly",
"format",
"the",
"results"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_manalyze.py#L65-L107 |
230,890 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | v4_int_to_packed | def v4_int_to_packed(address):
"""The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address.
"""
if address > _BaseV4._ALL_ONES:
raise ValueError('Address too large for IPv4')
return Bytes(struct.pack('!I', address)) | python | def v4_int_to_packed(address):
"""The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address.
"""
if address > _BaseV4._ALL_ONES:
raise ValueError('Address too large for IPv4')
return Bytes(struct.pack('!I', address)) | [
"def",
"v4_int_to_packed",
"(",
"address",
")",
":",
"if",
"address",
">",
"_BaseV4",
".",
"_ALL_ONES",
":",
"raise",
"ValueError",
"(",
"'Address too large for IPv4'",
")",
"return",
"Bytes",
"(",
"struct",
".",
"pack",
"(",
"'!I'",
",",
"address",
")",
")"
] | The binary representation of this address.
Args:
address: An integer representation of an IPv4 IP address.
Returns:
The binary representation of this address.
Raises:
ValueError: If the integer is too large to be an IPv4 IP
address. | [
"The",
"binary",
"representation",
"of",
"this",
"address",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L122-L137 |
230,891 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _get_prefix_length | def _get_prefix_length(number1, number2, bits):
"""Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers.
"""
for i in range(bits):
if number1 >> i == number2 >> i:
return bits - i
return 0 | python | def _get_prefix_length(number1, number2, bits):
"""Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers.
"""
for i in range(bits):
if number1 >> i == number2 >> i:
return bits - i
return 0 | [
"def",
"_get_prefix_length",
"(",
"number1",
",",
"number2",
",",
"bits",
")",
":",
"for",
"i",
"in",
"range",
"(",
"bits",
")",
":",
"if",
"number1",
">>",
"i",
"==",
"number2",
">>",
"i",
":",
"return",
"bits",
"-",
"i",
"return",
"0"
] | Get the number of leading bits that are same for two numbers.
Args:
number1: an integer.
number2: another integer.
bits: the maximum number of bits to compare.
Returns:
The number of leading bits that are the same for two numbers. | [
"Get",
"the",
"number",
"of",
"leading",
"bits",
"that",
"are",
"same",
"for",
"two",
"numbers",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L170-L185 |
230,892 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet._prefix_from_ip_int | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask.
"""
prefixlen = self._max_prefixlen
while prefixlen:
if ip_int & 1:
break
ip_int >>= 1
prefixlen -= 1
if ip_int == (1 << prefixlen) - 1:
return prefixlen
else:
raise NetmaskValueError('Bit pattern does not match /1*0*/') | python | def _prefix_from_ip_int(self, ip_int):
"""Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask.
"""
prefixlen = self._max_prefixlen
while prefixlen:
if ip_int & 1:
break
ip_int >>= 1
prefixlen -= 1
if ip_int == (1 << prefixlen) - 1:
return prefixlen
else:
raise NetmaskValueError('Bit pattern does not match /1*0*/') | [
"def",
"_prefix_from_ip_int",
"(",
"self",
",",
"ip_int",
")",
":",
"prefixlen",
"=",
"self",
".",
"_max_prefixlen",
"while",
"prefixlen",
":",
"if",
"ip_int",
"&",
"1",
":",
"break",
"ip_int",
">>=",
"1",
"prefixlen",
"-=",
"1",
"if",
"ip_int",
"==",
"(",
"1",
"<<",
"prefixlen",
")",
"-",
"1",
":",
"return",
"prefixlen",
"else",
":",
"raise",
"NetmaskValueError",
"(",
"'Bit pattern does not match /1*0*/'",
")"
] | Return prefix length from a bitwise netmask.
Args:
ip_int: An integer, the netmask in expanded bitwise format.
Returns:
An integer, the prefix length.
Raises:
NetmaskValueError: If the input is not a valid netmask. | [
"Return",
"prefix",
"length",
"from",
"a",
"bitwise",
"netmask",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L854-L877 |
230,893 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet._prefix_from_prefix_string | def _prefix_from_prefix_string(self, prefixlen_str):
"""Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range.
"""
try:
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
raise ValueError
prefixlen = int(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
raise ValueError
except ValueError:
raise NetmaskValueError('%s is not a valid prefix length' %
prefixlen_str)
return prefixlen | python | def _prefix_from_prefix_string(self, prefixlen_str):
"""Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range.
"""
try:
if not _BaseV4._DECIMAL_DIGITS.issuperset(prefixlen_str):
raise ValueError
prefixlen = int(prefixlen_str)
if not (0 <= prefixlen <= self._max_prefixlen):
raise ValueError
except ValueError:
raise NetmaskValueError('%s is not a valid prefix length' %
prefixlen_str)
return prefixlen | [
"def",
"_prefix_from_prefix_string",
"(",
"self",
",",
"prefixlen_str",
")",
":",
"try",
":",
"if",
"not",
"_BaseV4",
".",
"_DECIMAL_DIGITS",
".",
"issuperset",
"(",
"prefixlen_str",
")",
":",
"raise",
"ValueError",
"prefixlen",
"=",
"int",
"(",
"prefixlen_str",
")",
"if",
"not",
"(",
"0",
"<=",
"prefixlen",
"<=",
"self",
".",
"_max_prefixlen",
")",
":",
"raise",
"ValueError",
"except",
"ValueError",
":",
"raise",
"NetmaskValueError",
"(",
"'%s is not a valid prefix length'",
"%",
"prefixlen_str",
")",
"return",
"prefixlen"
] | Turn a prefix length string into an integer.
Args:
prefixlen_str: A decimal string containing the prefix length.
Returns:
The prefix length as an integer.
Raises:
NetmaskValueError: If the input is malformed or out of range. | [
"Turn",
"a",
"prefix",
"length",
"string",
"into",
"an",
"integer",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L879-L901 |
230,894 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseNet.masked | def masked(self):
"""Return the network object with the host bits masked out."""
return IPNetwork('%s/%d' % (self.network, self._prefixlen),
version=self._version) | python | def masked(self):
"""Return the network object with the host bits masked out."""
return IPNetwork('%s/%d' % (self.network, self._prefixlen),
version=self._version) | [
"def",
"masked",
"(",
"self",
")",
":",
"return",
"IPNetwork",
"(",
"'%s/%d'",
"%",
"(",
"self",
".",
"network",
",",
"self",
".",
"_prefixlen",
")",
",",
"version",
"=",
"self",
".",
"_version",
")"
] | Return the network object with the host bits masked out. | [
"Return",
"the",
"network",
"object",
"with",
"the",
"host",
"bits",
"masked",
"out",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L999-L1002 |
230,895 | TheHive-Project/Cortex-Analyzers | analyzers/MaxMind/ipaddr.py | _BaseV6._string_from_ip_int | def _string_from_ip_int(self, ip_int=None):
"""Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones.
"""
if not ip_int and ip_int != 0:
ip_int = int(self._ip)
if ip_int > self._ALL_ONES:
raise ValueError('IPv6 address is too large')
hex_str = '%032x' % ip_int
hextets = []
for x in range(0, 32, 4):
hextets.append('%x' % int(hex_str[x:x+4], 16))
hextets = self._compress_hextets(hextets)
return ':'.join(hextets) | python | def _string_from_ip_int(self, ip_int=None):
"""Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones.
"""
if not ip_int and ip_int != 0:
ip_int = int(self._ip)
if ip_int > self._ALL_ONES:
raise ValueError('IPv6 address is too large')
hex_str = '%032x' % ip_int
hextets = []
for x in range(0, 32, 4):
hextets.append('%x' % int(hex_str[x:x+4], 16))
hextets = self._compress_hextets(hextets)
return ':'.join(hextets) | [
"def",
"_string_from_ip_int",
"(",
"self",
",",
"ip_int",
"=",
"None",
")",
":",
"if",
"not",
"ip_int",
"and",
"ip_int",
"!=",
"0",
":",
"ip_int",
"=",
"int",
"(",
"self",
".",
"_ip",
")",
"if",
"ip_int",
">",
"self",
".",
"_ALL_ONES",
":",
"raise",
"ValueError",
"(",
"'IPv6 address is too large'",
")",
"hex_str",
"=",
"'%032x'",
"%",
"ip_int",
"hextets",
"=",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"0",
",",
"32",
",",
"4",
")",
":",
"hextets",
".",
"append",
"(",
"'%x'",
"%",
"int",
"(",
"hex_str",
"[",
"x",
":",
"x",
"+",
"4",
"]",
",",
"16",
")",
")",
"hextets",
"=",
"self",
".",
"_compress_hextets",
"(",
"hextets",
")",
"return",
"':'",
".",
"join",
"(",
"hextets",
")"
] | Turns a 128-bit integer into hexadecimal notation.
Args:
ip_int: An integer, the IP address.
Returns:
A string, the hexadecimal representation of the address.
Raises:
ValueError: The address is bigger than 128 bits of all ones. | [
"Turns",
"a",
"128",
"-",
"bit",
"integer",
"into",
"hexadecimal",
"notation",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/MaxMind/ipaddr.py#L1532-L1557 |
230,896 | TheHive-Project/Cortex-Analyzers | analyzers/Malwares/malwares_api.py | Api.scan_file | def scan_file(self, this_file, this_filename):
""" Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink.
"""
params = {
'api_key': self.api_key,
'filename': this_filename
}
try:
files = {'file': (this_file.name, open(this_file.name, 'rb'), 'application/octet-stream')}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/upload', files=files, data=params)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | python | def scan_file(self, this_file, this_filename):
""" Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink.
"""
params = {
'api_key': self.api_key,
'filename': this_filename
}
try:
files = {'file': (this_file.name, open(this_file.name, 'rb'), 'application/octet-stream')}
except TypeError as e:
return dict(error=e.message)
try:
response = requests.post(self.base + 'file/upload', files=files, data=params)
except requests.RequestException as e:
return dict(error=e.message)
return _return_response_and_status_code(response) | [
"def",
"scan_file",
"(",
"self",
",",
"this_file",
",",
"this_filename",
")",
":",
"params",
"=",
"{",
"'api_key'",
":",
"self",
".",
"api_key",
",",
"'filename'",
":",
"this_filename",
"}",
"try",
":",
"files",
"=",
"{",
"'file'",
":",
"(",
"this_file",
".",
"name",
",",
"open",
"(",
"this_file",
".",
"name",
",",
"'rb'",
")",
",",
"'application/octet-stream'",
")",
"}",
"except",
"TypeError",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"try",
":",
"response",
"=",
"requests",
".",
"post",
"(",
"self",
".",
"base",
"+",
"'file/upload'",
",",
"files",
"=",
"files",
",",
"data",
"=",
"params",
")",
"except",
"requests",
".",
"RequestException",
"as",
"e",
":",
"return",
"dict",
"(",
"error",
"=",
"e",
".",
"message",
")",
"return",
"_return_response_and_status_code",
"(",
"response",
")"
] | Submit a file to be scanned by Malwares
:param this_file: File to be scanned (200MB file size limit)
:param this_filename: Filename for scanned file
:return: JSON response that contains scan_id and permalink. | [
"Submit",
"a",
"file",
"to",
"be",
"scanned",
"by",
"Malwares"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Malwares/malwares_api.py#L17-L38 |
230,897 | TheHive-Project/Cortex-Analyzers | analyzers/GoogleSafebrowsing/safebrowsing.py | SafebrowsingClient.__prepare_body | def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict
"""
body = {
'client': {
'clientId': self.client_id,
'clientVersion': self.client_version
}
}
if search_type == 'url':
data = {
'threatTypes': [
'MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE', 'POTENTIALLY_HARMFUL_APPLICATION'
],
'platformTypes': ['ANY_PLATFORM', 'ALL_PLATFORMS', 'WINDOWS', 'LINUX', 'OSX', 'ANDROID', 'IOS'],
'threatEntryTypes': ['URL']
}
elif search_type == 'ip':
data = {
'threatTypes': ['MALWARE'],
'platformTypes': ['WINDOWS', 'LINUX', 'OSX'],
'threatEntryTypes': ['IP_RANGE']
}
else:
raise SearchTypeNotSupportedError('Currently supported search types are \'url\' and \'ip\'.')
# TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?
data['threatEntries'] = [{'url': search_value}]
body['threatInfo'] = data
return body | python | def __prepare_body(self, search_value, search_type='url'):
"""
Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict
"""
body = {
'client': {
'clientId': self.client_id,
'clientVersion': self.client_version
}
}
if search_type == 'url':
data = {
'threatTypes': [
'MALWARE', 'SOCIAL_ENGINEERING', 'UNWANTED_SOFTWARE', 'POTENTIALLY_HARMFUL_APPLICATION'
],
'platformTypes': ['ANY_PLATFORM', 'ALL_PLATFORMS', 'WINDOWS', 'LINUX', 'OSX', 'ANDROID', 'IOS'],
'threatEntryTypes': ['URL']
}
elif search_type == 'ip':
data = {
'threatTypes': ['MALWARE'],
'platformTypes': ['WINDOWS', 'LINUX', 'OSX'],
'threatEntryTypes': ['IP_RANGE']
}
else:
raise SearchTypeNotSupportedError('Currently supported search types are \'url\' and \'ip\'.')
# TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?
data['threatEntries'] = [{'url': search_value}]
body['threatInfo'] = data
return body | [
"def",
"__prepare_body",
"(",
"self",
",",
"search_value",
",",
"search_type",
"=",
"'url'",
")",
":",
"body",
"=",
"{",
"'client'",
":",
"{",
"'clientId'",
":",
"self",
".",
"client_id",
",",
"'clientVersion'",
":",
"self",
".",
"client_version",
"}",
"}",
"if",
"search_type",
"==",
"'url'",
":",
"data",
"=",
"{",
"'threatTypes'",
":",
"[",
"'MALWARE'",
",",
"'SOCIAL_ENGINEERING'",
",",
"'UNWANTED_SOFTWARE'",
",",
"'POTENTIALLY_HARMFUL_APPLICATION'",
"]",
",",
"'platformTypes'",
":",
"[",
"'ANY_PLATFORM'",
",",
"'ALL_PLATFORMS'",
",",
"'WINDOWS'",
",",
"'LINUX'",
",",
"'OSX'",
",",
"'ANDROID'",
",",
"'IOS'",
"]",
",",
"'threatEntryTypes'",
":",
"[",
"'URL'",
"]",
"}",
"elif",
"search_type",
"==",
"'ip'",
":",
"data",
"=",
"{",
"'threatTypes'",
":",
"[",
"'MALWARE'",
"]",
",",
"'platformTypes'",
":",
"[",
"'WINDOWS'",
",",
"'LINUX'",
",",
"'OSX'",
"]",
",",
"'threatEntryTypes'",
":",
"[",
"'IP_RANGE'",
"]",
"}",
"else",
":",
"raise",
"SearchTypeNotSupportedError",
"(",
"'Currently supported search types are \\'url\\' and \\'ip\\'.'",
")",
"# TODO: Only found threatEntry 'url' in the docs. What to use for ip_range?",
"data",
"[",
"'threatEntries'",
"]",
"=",
"[",
"{",
"'url'",
":",
"search_value",
"}",
"]",
"body",
"[",
"'threatInfo'",
"]",
"=",
"data",
"return",
"body"
] | Prepares the http body for querying safebrowsing api. Maybe the list need to get adjusted.
:param search_value: value to search for
:type search_value: str
:param search_type: 'url' or 'ip'
:type search_type: str
:returns: http body as dict
:rtype: dict | [
"Prepares",
"the",
"http",
"body",
"for",
"querying",
"safebrowsing",
"api",
".",
"Maybe",
"the",
"list",
"need",
"to",
"get",
"adjusted",
"."
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/GoogleSafebrowsing/safebrowsing.py#L26-L63 |
230,898 | TheHive-Project/Cortex-Analyzers | analyzers/Robtex/robtex.py | RobtexAnalyzer.query_rpdns | def query_rpdns(self):
"""
Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list
"""
results = requests.get('https://freeapi.robtex.com/pdns/reverse/{}'.format(self.get_data())).text.split('\r\n')
jsonresults = []
for idx, r in enumerate(results):
if len(r) > 0:
jsonresults.append(json.loads(r))
return jsonresults | python | def query_rpdns(self):
"""
Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list
"""
results = requests.get('https://freeapi.robtex.com/pdns/reverse/{}'.format(self.get_data())).text.split('\r\n')
jsonresults = []
for idx, r in enumerate(results):
if len(r) > 0:
jsonresults.append(json.loads(r))
return jsonresults | [
"def",
"query_rpdns",
"(",
"self",
")",
":",
"results",
"=",
"requests",
".",
"get",
"(",
"'https://freeapi.robtex.com/pdns/reverse/{}'",
".",
"format",
"(",
"self",
".",
"get_data",
"(",
")",
")",
")",
".",
"text",
".",
"split",
"(",
"'\\r\\n'",
")",
"jsonresults",
"=",
"[",
"]",
"for",
"idx",
",",
"r",
"in",
"enumerate",
"(",
"results",
")",
":",
"if",
"len",
"(",
"r",
")",
">",
"0",
":",
"jsonresults",
".",
"append",
"(",
"json",
".",
"loads",
"(",
"r",
")",
")",
"return",
"jsonresults"
] | Queries robtex reverse pdns-api using an ip as parameter
:return: Dictionary containing results
:rtype: list | [
"Queries",
"robtex",
"reverse",
"pdns",
"-",
"api",
"using",
"an",
"ip",
"as",
"parameter"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/Robtex/robtex.py#L22-L34 |
230,899 | TheHive-Project/Cortex-Analyzers | analyzers/FileInfo/submodules/submodule_rtfobj.py | RTFObjectSubmodule.module_summary | def module_summary(self):
"""Count the malicious and suspicious sections, check for CVE description"""
suspicious = 0
malicious = 0
count = 0
cve = False
taxonomies = []
for section in self.results:
if section['submodule_section_content']['class'] == 'malicious':
malicious += 1
elif section['submodule_section_content']['class'] == 'suspicious':
suspicious += 1
if 'CVE' in section['submodule_section_content']['clsid_description']:
cve = True
count += 1
if malicious > 0:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'MaliciousRTFObjects', malicious))
if suspicious > 0:
taxonomies.append(self.build_taxonomy('suspicious', 'FileInfo', 'SuspiciousRTFObjects', suspicious))
if cve:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'PossibleCVEExploit', 'True'))
taxonomies.append(self.build_taxonomy('info', 'FileInfo', 'RTFObjects', count))
self.summary['taxonomies'] = taxonomies
return self.summary | python | def module_summary(self):
"""Count the malicious and suspicious sections, check for CVE description"""
suspicious = 0
malicious = 0
count = 0
cve = False
taxonomies = []
for section in self.results:
if section['submodule_section_content']['class'] == 'malicious':
malicious += 1
elif section['submodule_section_content']['class'] == 'suspicious':
suspicious += 1
if 'CVE' in section['submodule_section_content']['clsid_description']:
cve = True
count += 1
if malicious > 0:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'MaliciousRTFObjects', malicious))
if suspicious > 0:
taxonomies.append(self.build_taxonomy('suspicious', 'FileInfo', 'SuspiciousRTFObjects', suspicious))
if cve:
taxonomies.append(self.build_taxonomy('malicious', 'FileInfo', 'PossibleCVEExploit', 'True'))
taxonomies.append(self.build_taxonomy('info', 'FileInfo', 'RTFObjects', count))
self.summary['taxonomies'] = taxonomies
return self.summary | [
"def",
"module_summary",
"(",
"self",
")",
":",
"suspicious",
"=",
"0",
"malicious",
"=",
"0",
"count",
"=",
"0",
"cve",
"=",
"False",
"taxonomies",
"=",
"[",
"]",
"for",
"section",
"in",
"self",
".",
"results",
":",
"if",
"section",
"[",
"'submodule_section_content'",
"]",
"[",
"'class'",
"]",
"==",
"'malicious'",
":",
"malicious",
"+=",
"1",
"elif",
"section",
"[",
"'submodule_section_content'",
"]",
"[",
"'class'",
"]",
"==",
"'suspicious'",
":",
"suspicious",
"+=",
"1",
"if",
"'CVE'",
"in",
"section",
"[",
"'submodule_section_content'",
"]",
"[",
"'clsid_description'",
"]",
":",
"cve",
"=",
"True",
"count",
"+=",
"1",
"if",
"malicious",
">",
"0",
":",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"'malicious'",
",",
"'FileInfo'",
",",
"'MaliciousRTFObjects'",
",",
"malicious",
")",
")",
"if",
"suspicious",
">",
"0",
":",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"'suspicious'",
",",
"'FileInfo'",
",",
"'SuspiciousRTFObjects'",
",",
"suspicious",
")",
")",
"if",
"cve",
":",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"'malicious'",
",",
"'FileInfo'",
",",
"'PossibleCVEExploit'",
",",
"'True'",
")",
")",
"taxonomies",
".",
"append",
"(",
"self",
".",
"build_taxonomy",
"(",
"'info'",
",",
"'FileInfo'",
",",
"'RTFObjects'",
",",
"count",
")",
")",
"self",
".",
"summary",
"[",
"'taxonomies'",
"]",
"=",
"taxonomies",
"return",
"self",
".",
"summary"
] | Count the malicious and suspicious sections, check for CVE description | [
"Count",
"the",
"malicious",
"and",
"suspicious",
"sections",
"check",
"for",
"CVE",
"description"
] | 8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf | https://github.com/TheHive-Project/Cortex-Analyzers/blob/8dae6a8c4cf9af5554ae8c844985c4b44d4bd4bf/analyzers/FileInfo/submodules/submodule_rtfobj.py#L20-L50 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.