Merge branch 'dev' into dev-json-additionalfields

pull/226/head
Josselin 6 years ago
commit d962ddeb5b
  1. 51
      README.md
  2. 2
      scripts/tests_generate_expected_json_4.sh
  3. 4
      scripts/tests_generate_expected_json_5.sh
  4. 8
      scripts/travis_install.sh
  5. 1
      scripts/travis_test_4.sh
  6. 2
      scripts/travis_test_5.sh
  7. 47
      slither/__main__.py
  8. 7
      slither/all_exceptions.py
  9. 2
      slither/analyses/write/are_variables_written.py
  10. 121
      slither/core/declarations/contract.py
  11. 3
      slither/core/exceptions.py
  12. 8
      slither/core/expressions/assignment_operation.py
  13. 8
      slither/core/expressions/binary_operation.py
  14. 11
      slither/core/expressions/unary_operation.py
  15. 45
      slither/core/variables/state_variable.py
  16. 2
      slither/detectors/all_detectors.py
  17. 9
      slither/detectors/erc/incorrect_erc20_interface.py
  18. 7
      slither/detectors/erc/incorrect_erc721_interface.py
  19. 43
      slither/detectors/operations/unchecked_low_level_return_values.py
  20. 40
      slither/detectors/operations/unchecked_send_return_value.py
  21. 17
      slither/detectors/operations/unused_return_values.py
  22. 3
      slither/exceptions.py
  23. 79
      slither/printers/summary/human_summary.py
  24. 31
      slither/slither.py
  25. 13
      slither/slithir/convert.py
  26. 3
      slither/slithir/exceptions.py
  27. 7
      slither/slithir/operations/binary.py
  28. 2
      slither/slithir/operations/return_operation.py
  29. 9
      slither/slithir/operations/unary.py
  30. 4
      slither/slithir/utils/ssa.py
  31. 6
      slither/slithir/variables/constant.py
  32. 4
      slither/solc_parsing/declarations/contract.py
  33. 10
      slither/solc_parsing/declarations/function.py
  34. 7
      slither/solc_parsing/exceptions.py
  35. 21
      slither/solc_parsing/expressions/expression_parsing.py
  36. 14
      slither/solc_parsing/slitherSolc.py
  37. 10
      slither/solc_parsing/solidity_types/type_parsing.py
  38. 11
      slither/solc_parsing/variables/variable_declaration.py
  39. 69
      slither/utils/erc.py
  40. 193
      slither/utils/standard_libraries.py
  41. 3
      slither/utils/type.py
  42. 2
      slither/visitors/expression/constants_folding.py
  43. 11
      slither/visitors/expression/expression.py
  44. 6
      slither/visitors/slithir/expression_to_slithir.py
  45. 8
      tests/expected_json/arbitrary_send-0.5.1.arbitrary-send.json
  46. 1
      tests/expected_json/arbitrary_send-0.5.1.arbitrary-send.txt
  47. 8
      tests/expected_json/arbitrary_send.arbitrary-send.json
  48. 1
      tests/expected_json/arbitrary_send.arbitrary-send.txt
  49. 8
      tests/expected_json/backdoor.backdoor.json
  50. 2
      tests/expected_json/backdoor.backdoor.txt
  51. 8
      tests/expected_json/backdoor.suicidal.json
  52. 2
      tests/expected_json/backdoor.suicidal.txt
  53. 8
      tests/expected_json/const_state_variables.constable-states.json
  54. 1
      tests/expected_json/const_state_variables.constable-states.txt
  55. 8
      tests/expected_json/constant-0.5.1.constant-function.json
  56. 1
      tests/expected_json/constant-0.5.1.constant-function.txt
  57. 8
      tests/expected_json/constant.constant-function.json
  58. 1
      tests/expected_json/constant.constant-function.txt
  59. 8
      tests/expected_json/controlled_delegatecall.controlled-delegatecall.json
  60. 1
      tests/expected_json/controlled_delegatecall.controlled-delegatecall.txt
  61. 8
      tests/expected_json/deprecated_calls.deprecated-standards.json
  62. 1
      tests/expected_json/deprecated_calls.deprecated-standards.txt
  63. 8
      tests/expected_json/erc20_indexed.erc20-indexed.json
  64. 1
      tests/expected_json/erc20_indexed.erc20-indexed.txt
  65. 8
      tests/expected_json/external_function.external-function.json
  66. 1
      tests/expected_json/external_function.external-function.txt
  67. 6
      tests/expected_json/external_function_2.external-function.json
  68. 1
      tests/expected_json/external_function_2.external-function.txt
  69. 8
      tests/expected_json/incorrect_equality.incorrect-equality.json
  70. 1
      tests/expected_json/incorrect_equality.incorrect-equality.txt
  71. 8
      tests/expected_json/incorrect_erc20_interface.erc20-interface.json
  72. 1
      tests/expected_json/incorrect_erc20_interface.erc20-interface.txt
  73. 8
      tests/expected_json/incorrect_erc721_interface.erc721-interface.json
  74. 1
      tests/expected_json/incorrect_erc721_interface.erc721-interface.txt
  75. 8
      tests/expected_json/inline_assembly_contract-0.5.1.assembly.json
  76. 1
      tests/expected_json/inline_assembly_contract-0.5.1.assembly.txt
  77. 8
      tests/expected_json/inline_assembly_contract.assembly.json
  78. 1
      tests/expected_json/inline_assembly_contract.assembly.txt
  79. 8
      tests/expected_json/inline_assembly_library-0.5.1.assembly.json
  80. 1
      tests/expected_json/inline_assembly_library-0.5.1.assembly.txt
  81. 8
      tests/expected_json/inline_assembly_library.assembly.json
  82. 1
      tests/expected_json/inline_assembly_library.assembly.txt
  83. 8
      tests/expected_json/locked_ether-0.5.1.locked-ether.json
  84. 1
      tests/expected_json/locked_ether-0.5.1.locked-ether.txt
  85. 8
      tests/expected_json/locked_ether.locked-ether.json
  86. 1
      tests/expected_json/locked_ether.locked-ether.txt
  87. 8
      tests/expected_json/low_level_calls.low-level-calls.json
  88. 1
      tests/expected_json/low_level_calls.low-level-calls.txt
  89. 8
      tests/expected_json/multiple_calls_in_loop.calls-loop.json
  90. 1
      tests/expected_json/multiple_calls_in_loop.calls-loop.txt
  91. 8
      tests/expected_json/naming_convention.naming-convention.json
  92. 1
      tests/expected_json/naming_convention.naming-convention.txt
  93. 8
      tests/expected_json/old_solc.sol.json.solc-version.json
  94. 2
      tests/expected_json/old_solc.sol.json.solc-version.txt
  95. 8
      tests/expected_json/pragma.0.4.24.pragma.json
  96. 16
      tests/expected_json/pragma.0.4.24.pragma.txt
  97. 8
      tests/expected_json/reentrancy-0.5.1.reentrancy-eth.json
  98. 1
      tests/expected_json/reentrancy-0.5.1.reentrancy-eth.txt
  99. 10
      tests/expected_json/reentrancy-0.5.1.reentrancy.txt
  100. 8
      tests/expected_json/reentrancy.reentrancy-eth.json
  101. Some files were not shown because too many files have changed in this diff Show More

@ -48,30 +48,33 @@ Num | Detector | What it Detects | Impact | Confidence
7 | `controlled-delegatecall` | [Controlled delegatecall destination](https://github.com/crytic/slither/wiki/Detector-Documentation#controlled-delegatecall) | High | Medium 7 | `controlled-delegatecall` | [Controlled delegatecall destination](https://github.com/crytic/slither/wiki/Detector-Documentation#controlled-delegatecall) | High | Medium
8 | `reentrancy-eth` | [Reentrancy vulnerabilities (theft of ethers)](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities) | High | Medium 8 | `reentrancy-eth` | [Reentrancy vulnerabilities (theft of ethers)](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities) | High | Medium
9 | `erc20-interface` | [Incorrect ERC20 interfaces](https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc20-interface) | Medium | High 9 | `erc20-interface` | [Incorrect ERC20 interfaces](https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc20-interface) | Medium | High
10 | `incorrect-equality` | [Dangerous strict equalities](https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-strict-equalities) | Medium | High 10 | `erc721-interface` | [Incorrect ERC721 interfaces](https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc721-interface) | Medium | High
11 | `locked-ether` | [Contracts that lock ether](https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether) | Medium | High 11 | `incorrect-equality` | [Dangerous strict equalities](https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-strict-equalities) | Medium | High
12 | `shadowing-abstract` | [State variables shadowing from abstract contracts](https://github.com/crytic/slither/wiki/Detector-Documentation#state-variable-shadowing-from-abstract-contracts) | Medium | High 12 | `locked-ether` | [Contracts that lock ether](https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether) | Medium | High
13 | `constant-function` | [Constant functions changing the state](https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state) | Medium | Medium 13 | `shadowing-abstract` | [State variables shadowing from abstract contracts](https://github.com/crytic/slither/wiki/Detector-Documentation#state-variable-shadowing-from-abstract-contracts) | Medium | High
14 | `reentrancy-no-eth` | [Reentrancy vulnerabilities (no theft of ethers)](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-1) | Medium | Medium 14 | `constant-function` | [Constant functions changing the state](https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state) | Medium | Medium
15 | `tx-origin` | [Dangerous usage of `tx.origin`](https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-usage-of-txorigin) | Medium | Medium 15 | `reentrancy-no-eth` | [Reentrancy vulnerabilities (no theft of ethers)](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-1) | Medium | Medium
16 | `uninitialized-local` | [Uninitialized local variables](https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-local-variables) | Medium | Medium 16 | `tx-origin` | [Dangerous usage of `tx.origin`](https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-usage-of-txorigin) | Medium | Medium
17 | `unused-return` | [Unused return values](https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return) | Medium | Medium 17 | `unchecked-lowlevel` | [Unchecked low-level calls](https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-low-level) | Medium | Medium
18 | `shadowing-builtin` | [Built-in symbol shadowing](https://github.com/crytic/slither/wiki/Detector-Documentation#builtin-symbol-shadowing) | Low | High 18 | `unchecked-send` | [Unchecked send](https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-send) | Medium | Medium
19 | `shadowing-local` | [Local variables shadowing](https://github.com/crytic/slither/wiki/Detector-Documentation#local-variable-shadowing) | Low | High 19 | `uninitialized-local` | [Uninitialized local variables](https://github.com/crytic/slither/wiki/Detector-Documentation#uninitialized-local-variables) | Medium | Medium
20 | `calls-loop` | [Multiple calls in a loop](https://github.com/crytic/slither/wiki/Detector-Documentation/_edit#calls-inside-a-loop) | Low | Medium 20 | `unused-return` | [Unused return values](https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return) | Medium | Medium
21 | `reentrancy-benign` | [Benign reentrancy vulnerabilities](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-2) | Low | Medium 21 | `shadowing-builtin` | [Built-in symbol shadowing](https://github.com/crytic/slither/wiki/Detector-Documentation#builtin-symbol-shadowing) | Low | High
22 | `timestamp` | [Dangerous usage of `block.timestamp`](https://github.com/crytic/slither/wiki/Detector-Documentation#block-timestamp) | Low | Medium 22 | `shadowing-local` | [Local variables shadowing](https://github.com/crytic/slither/wiki/Detector-Documentation#local-variable-shadowing) | Low | High
23 | `assembly` | [Assembly usage](https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage) | Informational | High 23 | `calls-loop` | [Multiple calls in a loop](https://github.com/crytic/slither/wiki/Detector-Documentation/_edit#calls-inside-a-loop) | Low | Medium
24 | `constable-states` | [State variables that could be declared constant](https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant) | Informational | High 24 | `reentrancy-benign` | [Benign reentrancy vulnerabilities](https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities-2) | Low | Medium
25 | `deprecated-standards` | [Deprecated Solidity Standards](https://github.com/crytic/slither/wiki/Detector-Documentation#deprecated-standards) | Informational | High 25 | `timestamp` | [Dangerous usage of `block.timestamp`](https://github.com/crytic/slither/wiki/Detector-Documentation#block-timestamp) | Low | Medium
26 | `erc20-indexed` | [Un-indexed ERC20 event parameters](https://github.com/crytic/slither/wiki/Detector-Documentation#unindexed-erc20-event-parameters) | Informational | High 26 | `assembly` | [Assembly usage](https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage) | Informational | High
27 | `external-function` | [Public function that could be declared as external](https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-as-external) | Informational | High 27 | `constable-states` | [State variables that could be declared constant](https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant) | Informational | High
28 | `low-level-calls` | [Low level calls](https://github.com/crytic/slither/wiki/Detector-Documentation#low-level-calls) | Informational | High 28 | `deprecated-standards` | [Deprecated Solidity Standards](https://github.com/crytic/slither/wiki/Detector-Documentation#deprecated-standards) | Informational | High
29 | `naming-convention` | [Conformance to Solidity naming conventions](https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions) | Informational | High 29 | `erc20-indexed` | [Un-indexed ERC20 event parameters](https://github.com/crytic/slither/wiki/Detector-Documentation#unindexed-erc20-event-parameters) | Informational | High
30 | `pragma` | [If different pragma directives are used](https://github.com/crytic/slither/wiki/Detector-Documentation#different-pragma-directives-are-used) | Informational | High 30 | `external-function` | [Public function that could be declared as external](https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-as-external) | Informational | High
31 | `solc-version` | [Incorrect Solidity version (< 0.4.24 or complex pragma)](https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-version-of-solidity) | Informational | High 31 | `low-level-calls` | [Low level calls](https://github.com/crytic/slither/wiki/Detector-Documentation#low-level-calls) | Informational | High
32 | `unused-state` | [Unused state variables](https://github.com/crytic/slither/wiki/Detector-Documentation#unused-state-variables) | Informational | High 32 | `naming-convention` | [Conformance to Solidity naming conventions](https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions) | Informational | High
33 | `too-many-digits` | [Conformance to numeric notation best practices](https://github.com/crytic/slither/wiki/Detector-Documentation#too-many-digits) | Informational | Medium 33 | `pragma` | [If different pragma directives are used](https://github.com/crytic/slither/wiki/Detector-Documentation#different-pragma-directives-are-used) | Informational | High
34 | `solc-version` | [Incorrect Solidity version (< 0.4.24 or complex pragma)](https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-version-of-solidity) | Informational | High
35 | `unused-state` | [Unused state variables](https://github.com/crytic/slither/wiki/Detector-Documentation#unused-state-variables) | Informational | High
36 | `too-many-digits` | [Conformance to numeric notation best practices](https://github.com/crytic/slither/wiki/Detector-Documentation#too-many-digits) | Informational | Medium
[Contact us](https://www.trailofbits.com/contact/) to get access to additional detectors. [Contact us](https://www.trailofbits.com/contact/) to get access to additional detectors.

@ -17,6 +17,7 @@ generate_expected_json(){
sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename" -i sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename" -i
sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename_txt" -i
} }
@ -54,3 +55,4 @@ generate_expected_json(){
#generate_expected_json tests/shadowing_local_variable.sol "shadowing-local" #generate_expected_json tests/shadowing_local_variable.sol "shadowing-local"
#generate_expected_json tests/solc_version_incorrect.sol "solc-version" #generate_expected_json tests/solc_version_incorrect.sol "solc-version"
#generate_expected_json tests/right_to_left_override.sol "rtlo" #generate_expected_json tests/right_to_left_override.sol "rtlo"
#generate_expected_json tests/unchecked_lowlevel.sol "unchecked-lowlevel"

@ -17,6 +17,7 @@ generate_expected_json(){
slither "$1" --solc-disable-warnings --detect "$2" --json "$output_filename" --solc solc-0.5.1 > $output_filename_txt 2>&1 slither "$1" --solc-disable-warnings --detect "$2" --json "$output_filename" --solc solc-0.5.1 > $output_filename_txt 2>&1
sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename" -i sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename" -i
sed "s|$CURRENT_PATH|$TRAVIS_PATH|g" "$output_filename_txt" -i
} }
#generate_expected_json tests/uninitialized-0.5.1.sol "uninitialized-state" #generate_expected_json tests/uninitialized-0.5.1.sol "uninitialized-state"
@ -25,7 +26,6 @@ generate_expected_json(){
#generate_expected_json tests/pragma.0.4.24.sol "pragma" #generate_expected_json tests/pragma.0.4.24.sol "pragma"
#generate_expected_json tests/old_solc.sol.json "solc-version" #generate_expected_json tests/old_solc.sol.json "solc-version"
#generate_expected_json tests/reentrancy-0.5.1.sol "reentrancy-eth" #generate_expected_json tests/reentrancy-0.5.1.sol "reentrancy-eth"
#generate_expected_json tests/reentrancy-0.5.1.sol "reentrancy"
#generate_expected_json tests/uninitialized_storage_pointer.sol "uninitialized-storage" #generate_expected_json tests/uninitialized_storage_pointer.sol "uninitialized-storage"
#generate_expected_json tests/tx_origin-0.5.1.sol "tx-origin" #generate_expected_json tests/tx_origin-0.5.1.sol "tx-origin"
#generate_expected_json tests/locked_ether-0.5.1.sol "locked-ether" #generate_expected_json tests/locked_ether-0.5.1.sol "locked-ether"
@ -35,4 +35,6 @@ generate_expected_json(){
#generate_expected_json tests/constant-0.5.1.sol "constant-function" #generate_expected_json tests/constant-0.5.1.sol "constant-function"
#generate_expected_json tests/incorrect_equality.sol "incorrect-equality" #generate_expected_json tests/incorrect_equality.sol "incorrect-equality"
#generate_expected_json tests/too_many_digits.sol "too-many-digits" #generate_expected_json tests/too_many_digits.sol "too-many-digits"
#generate_expected_json tests/unchecked_lowlevel-0.5.1.sol "unchecked-lowlevel"
#generate_expected_json tests/unchecked_send-0.5.1.sol "unchecked-send"

@ -1,4 +1,12 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# TODO: temporary until the next crytic-compile release
git clone https://github.com/crytic/crytic-compile
cd crytic-compile
git checkout dev
python setup.py install
cd ..
python setup.py install python setup.py install
# Used by travis_test.sh # Used by travis_test.sh
pip install deepdiff pip install deepdiff

@ -69,6 +69,7 @@ test_slither(){
} }
test_slither tests/unchecked_lowlevel.sol "unchecked-lowlevel"
test_slither tests/deprecated_calls.sol "deprecated-standards" test_slither tests/deprecated_calls.sol "deprecated-standards"
test_slither tests/erc20_indexed.sol "erc20-indexed" test_slither tests/erc20_indexed.sol "erc20-indexed"
test_slither tests/incorrect_erc20_interface.sol "erc20-interface" test_slither tests/incorrect_erc20_interface.sol "erc20-interface"

@ -69,6 +69,8 @@ test_slither(){
} }
test_slither tests/unchecked_lowlevel-0.5.1.sol "unchecked-lowlevel"
test_slither tests/unchecked_send-0.5.1.sol "unchecked-send"
test_slither tests/uninitialized-0.5.1.sol "uninitialized-state" test_slither tests/uninitialized-0.5.1.sol "uninitialized-state"
test_slither tests/backdoor.sol "backdoor" test_slither tests/backdoor.sol "backdoor"
test_slither tests/backdoor.sol "suicidal" test_slither tests/backdoor.sol "suicidal"

@ -24,11 +24,11 @@ from slither.utils.command_line import (output_detectors, output_results_to_mark
output_detectors_json, output_printers, output_detectors_json, output_printers,
output_to_markdown, output_wiki) output_to_markdown, output_wiki)
from crytic_compile import is_supported from crytic_compile import is_supported
from slither.exceptions import SlitherException
logging.basicConfig() logging.basicConfig()
logger = logging.getLogger("Slither") logger = logging.getLogger("Slither")
################################################################################### ###################################################################################
################################################################################### ###################################################################################
# region Process functions # region Process functions
@ -99,12 +99,27 @@ def process_files(filenames, args, detector_classes, printer_classes):
################################################################################### ###################################################################################
################################################################################### ###################################################################################
def wrap_json_stdout(success, error_message, results=None):
return {
"success": success,
"error": error_message,
"results": results
}
def output_json(results, filename): def output_json(results, filename):
json_result = wrap_json_stdout(True, None, results)
if filename is None:
# Write json to console
print(json.dumps(json_result))
else:
# Write json to file
if os.path.isfile(filename): if os.path.isfile(filename):
logger.info(yellow(f'{filename} exists already, the overwrite is prevented')) logger.info(yellow(f'{filename} exists already, the overwrite is prevented'))
else: else:
with open(filename, 'w', encoding='utf8') as f: with open(filename, 'w', encoding='utf8') as f:
json.dump(results, f, indent=2) json.dump(json_result, f, indent=2)
# endregion # endregion
################################################################################### ###################################################################################
@ -327,7 +342,7 @@ def parse_args(detector_classes, printer_classes):
group_misc.add_argument('--json', group_misc.add_argument('--json',
help='Export results as JSON', help='Export the results as a JSON file ("--json -" to export to stdout)',
action='store', action='store',
default=defaults_flag_in_config['json']) default=defaults_flag_in_config['json'])
@ -474,14 +489,15 @@ class FormatterCryticCompile(logging.Formatter):
txt = '\n'.join(txt) txt = '\n'.join(txt)
record.args = (record.args[0], txt) record.args = (record.args[0], txt)
return super().format(record) return super().format(record)
# endregion
# endregion
################################################################################### ###################################################################################
################################################################################### ###################################################################################
# region Main # region Main
################################################################################### ###################################################################################
################################################################################### ###################################################################################
def main(): def main():
detectors, printers = get_detectors_and_printers() detectors, printers = get_detectors_and_printers()
@ -498,6 +514,11 @@ def main_impl(all_detector_classes, all_printer_classes):
# Set colorization option # Set colorization option
set_colorization_enabled(not args.disable_color) set_colorization_enabled(not args.disable_color)
# If we are outputting json to stdout, we'll want to disable any logging.
stdout_json = args.json == "-"
if stdout_json:
logging.disable(logging.CRITICAL)
printer_classes = choose_printers(args, all_printer_classes) printer_classes = choose_printers(args, all_printer_classes)
detector_classes = choose_detectors(args, all_detector_classes) detector_classes = choose_detectors(args, all_detector_classes)
@ -556,7 +577,7 @@ def main_impl(all_detector_classes, all_printer_classes):
raise Exception("Unrecognised file/dir path: '#{filename}'".format(filename=filename)) raise Exception("Unrecognised file/dir path: '#{filename}'".format(filename=filename))
if args.json: if args.json:
output_json(results, args.json) output_json(results, None if stdout_json else args.json)
if args.checklist: if args.checklist:
output_results_to_markdown(results) output_results_to_markdown(results)
# Dont print the number of result for printers # Dont print the number of result for printers
@ -570,7 +591,21 @@ def main_impl(all_detector_classes, all_printer_classes):
return return
exit(results) exit(results)
except SlitherException as se:
# Output our error accordingly, via JSON or logging.
if stdout_json:
print(json.dumps(wrap_json_stdout(False, repr(se), [])))
else:
logging.error(red('Error:'))
logging.error(red(se))
logging.error('Please report an issue to https://github.com/crytic/slither/issues')
sys.exit(-1)
except Exception: except Exception:
# Output our error accordingly, via JSON or logging.
if stdout_json:
print(json.dumps(wrap_json_stdout(False, traceback.format_exc(), [])))
else:
logging.error('Error in %s' % args.filename) logging.error('Error in %s' % args.filename)
logging.error(traceback.format_exc()) logging.error(traceback.format_exc())
sys.exit(-1) sys.exit(-1)
@ -581,4 +616,6 @@ if __name__ == '__main__':
main() main()
# endregion # endregion

@ -0,0 +1,7 @@
"""
This module import all slither exceptions
"""
from slither.slithir.exceptions import SlithIRError
from slither.solc_parsing.exceptions import ParsingError, ParsingContractNotFound, ParsingNameReuse
from slither.core.exceptions import SlitherCoreError
from slither.exceptions import SlitherException

@ -33,6 +33,8 @@ def _visit(node, visited, variables_written, variables_to_write):
variables_written = variables_written + [ir.lvalue] variables_written = variables_written + [ir.lvalue]
lvalue = ir.lvalue lvalue = ir.lvalue
while isinstance(lvalue, ReferenceVariable): while isinstance(lvalue, ReferenceVariable):
if lvalue not in refs:
break
variables_written = variables_written + [refs[lvalue]] variables_written = variables_written + [refs[lvalue]]
lvalue = refs[lvalue] lvalue = refs[lvalue]

@ -5,6 +5,9 @@ import logging
from slither.core.children.child_slither import ChildSlither from slither.core.children.child_slither import ChildSlither
from slither.core.source_mapping.source_mapping import SourceMapping from slither.core.source_mapping.source_mapping import SourceMapping
from slither.core.declarations.function import Function from slither.core.declarations.function import Function
from slither.utils.erc import ERC20_signatures, \
ERC165_signatures, ERC223_signatures, ERC721_signatures, \
ERC1820_signatures, ERC777_signatures
logger = logging.getLogger("Contract") logger = logging.getLogger("Contract")
@ -35,6 +38,8 @@ class Contract(ChildSlither, SourceMapping):
self._using_for = {} self._using_for = {}
self._kind = None self._kind = None
self._signatures = None
self._initial_state_variables = [] # ssa self._initial_state_variables = [] # ssa
@ -212,6 +217,20 @@ class Contract(ChildSlither, SourceMapping):
################################################################################### ###################################################################################
################################################################################### ###################################################################################
@property
def functions_signatures(self):
"""
Return the signatures of all the public/eterxnal functions/state variables
:return: list(string) the signatures of all the functions that can be called
"""
if self._signatures == None:
sigs = [v.full_name for v in self.state_variables if v.visibility in ['public',
'external']]
sigs += set([f.full_name for f in self.functions if f.visibility in ['public', 'external']])
self._signatures = list(set(sigs))
return self._signatures
@property @property
def functions(self): def functions(self):
''' '''
@ -534,50 +553,101 @@ class Contract(ChildSlither, SourceMapping):
################################################################################### ###################################################################################
################################################################################### ###################################################################################
def ercs(self):
"""
Return the ERC implemented
:return: list of string
"""
all = [('ERC20', lambda x: x.is_erc20()),
('ERC165', lambda x: x.is_erc165()),
('ERC1820', lambda x: x.is_erc1820()),
('ERC223', lambda x: x.is_erc223()),
('ERC721', lambda x: x.is_erc721()),
('ERC777', lambda x: x.is_erc777())]
return [erc[0] for erc in all if erc[1](self)]
def is_erc20(self): def is_erc20(self):
""" """
Check if the contract is an erc20 token Check if the contract is an erc20 token
Note: it does not check for correct return values Note: it does not check for correct return values
Returns: :return: Returns a true if the contract is an erc20
bool
""" """
full_names = set([f.full_name for f in self.functions]) full_names = self.functions_signatures
return 'transfer(address,uint256)' in full_names and\ return all((s in full_names for s in ERC20_signatures))
'transferFrom(address,address,uint256)' in full_names and\
'approve(address,uint256)' in full_names def is_erc165(self):
"""
Check if the contract is an erc165 token
Note: it does not check for correct return values
:return: Returns a true if the contract is an erc165
"""
full_names = self.functions_signatures
return all((s in full_names for s in ERC165_signatures))
def is_erc1820(self):
"""
Check if the contract is an erc1820
Note: it does not check for correct return values
:return: Returns a true if the contract is an erc165
"""
full_names = self.functions_signatures
return all((s in full_names for s in ERC1820_signatures))
def is_erc223(self):
"""
Check if the contract is an erc223 token
Note: it does not check for correct return values
:return: Returns a true if the contract is an erc223
"""
full_names = self.functions_signatures
return all((s in full_names for s in ERC223_signatures))
def is_erc721(self): def is_erc721(self):
full_names = set([f.full_name for f in self.functions]) """
return self.is_erc20() and\ Check if the contract is an erc721 token
'ownerOf(uint256)' in full_names and\
'safeTransferFrom(address,address,uint256,bytes)' in full_names and\ Note: it does not check for correct return values
'safeTransferFrom(address,address,uint256)' in full_names and\ :return: Returns a true if the contract is an erc721
'setApprovalForAll(address,bool)' in full_names and\ """
'getApproved(uint256)' in full_names and\ full_names = self.functions_signatures
'isApprovedForAll(address,address)' in full_names return all((s in full_names for s in ERC721_signatures))
def is_erc777(self):
"""
Check if the contract is an erc777
def has_an_erc20_function(self): Note: it does not check for correct return values
:return: Returns a true if the contract is an erc165
"""
full_names = self.functions_signatures
return all((s in full_names for s in ERC777_signatures))
def is_possible_erc20(self):
""" """
Checks if the provided contract could be attempting to implement ERC20 standards. Checks if the provided contract could be attempting to implement ERC20 standards.
:param contract: The contract to check for token compatibility. :param contract: The contract to check for token compatibility.
:return: Returns a boolean indicating if the provided contract met the token standard. :return: Returns a boolean indicating if the provided contract met the token standard.
""" """
full_names = set([f.full_name for f in self.functions]) # We do not check for all the functions, as name(), symbol(), might give too many FPs
full_names = self.functions_signatures
return 'transfer(address,uint256)' in full_names or \ return 'transfer(address,uint256)' in full_names or \
'transferFrom(address,address,uint256)' in full_names or \ 'transferFrom(address,address,uint256)' in full_names or \
'approve(address,uint256)' in full_names 'approve(address,uint256)' in full_names
def has_an_erc721_function(self): def is_possible_erc721(self):
""" """
Checks if the provided contract could be attempting to implement ERC721 standards. Checks if the provided contract could be attempting to implement ERC721 standards.
:param contract: The contract to check for token compatibility. :param contract: The contract to check for token compatibility.
:return: Returns a boolean indicating if the provided contract met the token standard. :return: Returns a boolean indicating if the provided contract met the token standard.
""" """
full_names = set([f.full_name for f in self.functions]) # We do not check for all the functions, as name(), symbol(), might give too many FPs
return self.has_an_erc20_function() and \ full_names = self.functions_signatures
('ownerOf(uint256)' in full_names or return ('ownerOf(uint256)' in full_names or
'safeTransferFrom(address,address,uint256,bytes)' in full_names or 'safeTransferFrom(address,address,uint256,bytes)' in full_names or
'safeTransferFrom(address,address,uint256)' in full_names or 'safeTransferFrom(address,address,uint256)' in full_names or
'setApprovalForAll(address,bool)' in full_names or 'setApprovalForAll(address,bool)' in full_names or
@ -585,6 +655,17 @@ class Contract(ChildSlither, SourceMapping):
'isApprovedForAll(address,address)' in full_names) 'isApprovedForAll(address,address)' in full_names)
# endregion
###################################################################################
###################################################################################
# region Dependencies
###################################################################################
###################################################################################
def is_from_dependency(self):
if self.slither.crytic_compile is None:
return False
return self.slither.crytic_compile.is_dependency(self.source_mapping['filename_absolute'])
# endregion # endregion
################################################################################### ###################################################################################

@ -0,0 +1,3 @@
from slither.exceptions import SlitherException
class SlitherCoreError(SlitherException): pass

@ -1,7 +1,7 @@
import logging import logging
from slither.core.expressions.expression_typed import ExpressionTyped from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression from slither.core.expressions.expression import Expression
from slither.core.exceptions import SlitherCoreError
logger = logging.getLogger("AssignmentOperation") logger = logging.getLogger("AssignmentOperation")
@ -43,8 +43,7 @@ class AssignmentOperationType:
if operation_type == '%=': if operation_type == '%=':
return AssignmentOperationType.ASSIGN_MODULO return AssignmentOperationType.ASSIGN_MODULO
logger.error('get_type: Unknown operation type {})'.format(operation_type)) raise SlitherCoreError('get_type: Unknown operation type {})'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def str(operation_type): def str(operation_type):
@ -71,8 +70,7 @@ class AssignmentOperationType:
if operation_type == AssignmentOperationType.ASSIGN_MODULO: if operation_type == AssignmentOperationType.ASSIGN_MODULO:
return '%=' return '%='
logger.error('str: Unknown operation type {})'.format(operation_type)) raise SlitherCoreError('str: Unknown operation type {})'.format(operation_type))
exit(-1)
class AssignmentOperation(ExpressionTyped): class AssignmentOperation(ExpressionTyped):

@ -1,7 +1,7 @@
import logging import logging
from slither.core.expressions.expression_typed import ExpressionTyped from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression from slither.core.expressions.expression import Expression
from slither.core.exceptions import SlitherCoreError
logger = logging.getLogger("BinaryOperation") logger = logging.getLogger("BinaryOperation")
@ -67,8 +67,7 @@ class BinaryOperationType:
if operation_type == '||': if operation_type == '||':
return BinaryOperationType.OROR return BinaryOperationType.OROR
logger.error('get_type: Unknown operation type {})'.format(operation_type)) raise SlitherCoreError('get_type: Unknown operation type {})'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def str(operation_type): def str(operation_type):
@ -110,8 +109,7 @@ class BinaryOperationType:
return '&&' return '&&'
if operation_type == BinaryOperationType.OROR: if operation_type == BinaryOperationType.OROR:
return '||' return '||'
logger.error('str: Unknown operation type {})'.format(operation_type)) raise SlitherCoreError('str: Unknown operation type {})'.format(operation_type))
exit(-1)
class BinaryOperation(ExpressionTyped): class BinaryOperation(ExpressionTyped):

@ -1,7 +1,7 @@
import logging import logging
from slither.core.expressions.expression_typed import ExpressionTyped from slither.core.expressions.expression_typed import ExpressionTyped
from slither.core.expressions.expression import Expression from slither.core.expressions.expression import Expression
from slither.core.solidity_types.type import Type from slither.core.exceptions import SlitherCoreError
logger = logging.getLogger("UnaryOperation") logger = logging.getLogger("UnaryOperation")
@ -38,8 +38,7 @@ class UnaryOperationType:
return UnaryOperationType.PLUSPLUS_POST return UnaryOperationType.PLUSPLUS_POST
if operation_type == '--': if operation_type == '--':
return UnaryOperationType.MINUSMINUS_POST return UnaryOperationType.MINUSMINUS_POST
logger.error('get_type: Unknown operation type {}'.format(operation_type)) raise SlitherCoreError('get_type: Unknown operation type {}'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def str(operation_type): def str(operation_type):
@ -58,8 +57,7 @@ class UnaryOperationType:
if operation_type in [UnaryOperationType.MINUSMINUS_PRE, UnaryOperationType.MINUSMINUS_POST]: if operation_type in [UnaryOperationType.MINUSMINUS_PRE, UnaryOperationType.MINUSMINUS_POST]:
return '--' return '--'
logger.error('str: Unknown operation type {}'.format(operation_type)) raise SlitherCoreError('str: Unknown operation type {}'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def is_prefix(operation_type): def is_prefix(operation_type):
@ -74,8 +72,7 @@ class UnaryOperationType:
elif operation_type in [UnaryOperationType.PLUSPLUS_POST, UnaryOperationType.MINUSMINUS_POST]: elif operation_type in [UnaryOperationType.PLUSPLUS_POST, UnaryOperationType.MINUSMINUS_POST]:
return False return False
logger.error('is_prefix: Unknown operation type {}'.format(operation_type)) raise SlitherCoreError('is_prefix: Unknown operation type {}'.format(operation_type))
exit(-1)
class UnaryOperation(ExpressionTyped): class UnaryOperation(ExpressionTyped):

@ -1,8 +1,53 @@
from .variable import Variable from .variable import Variable
from slither.core.children.child_contract import ChildContract from slither.core.children.child_contract import ChildContract
from slither.utils.type import export_nested_types_from_variable
class StateVariable(ChildContract, Variable): class StateVariable(ChildContract, Variable):
###################################################################################
###################################################################################
# region Signature
###################################################################################
###################################################################################
@property
def signature(self):
"""
Return the signature of the state variable as a function signature
:return: (str, list(str), list(str)), as (name, list parameters type, list return values type)
"""
return self.name, [str(x) for x in export_nested_types_from_variable(self)], self.type
@property
def signature_str(self):
"""
Return the signature of the state variable as a function signature
:return: str: func_name(type1,type2) returns(type3)
"""
name, parameters, returnVars = self.signature
return name+'('+','.join(parameters)+') returns('+','.join(returnVars)+')'
# endregion
###################################################################################
###################################################################################
# region Name
###################################################################################
###################################################################################
@property @property
def canonical_name(self): def canonical_name(self):
return '{}:{}'.format(self.contract.name, self.name) return '{}:{}'.format(self.contract.name, self.name)
@property
def full_name(self):
"""
Return the name of the state variable as a function signaure
str: func_name(type1,type2)
:return: the function signature without the return values
"""
name, parameters, _ = self.signature
return name+'('+','.join(parameters)+')'
# endregion
###################################################################################
###################################################################################

@ -34,5 +34,7 @@ from .erc.unindexed_event_parameters import UnindexedERC20EventParameters
from .statements.deprecated_calls import DeprecatedStandards from .statements.deprecated_calls import DeprecatedStandards
from .source.rtlo import RightToLeftOverride from .source.rtlo import RightToLeftOverride
from .statements.too_many_digits import TooManyDigits from .statements.too_many_digits import TooManyDigits
from .operations.unchecked_low_level_return_values import UncheckedLowLevel
from .operations.unchecked_send_return_value import UncheckedSend
# #
# #

@ -62,15 +62,16 @@ contract Token{
list(str) : list of incorrect function signatures list(str) : list of incorrect function signatures
""" """
# Verify this is an ERC20 contract. # Verify this is an ERC20 contract.
if not contract.has_an_erc20_function(): if not contract.is_possible_erc20():
return [] return []
# If this contract implements a function from ERC721, we can assume it is an ERC721 token. These tokens # If this contract implements a function from ERC721, we can assume it is an ERC721 token. These tokens
# offer functions which are similar to ERC20, but are not compatible. # offer functions which are similar to ERC20, but are not compatible.
if contract.has_an_erc721_function(): if contract.is_possible_erc721():
return [] return []
functions = [f for f in contract.functions if IncorrectERC20InterfaceDetection.incorrect_erc20_interface(f.signature)] funcs = contract.functions
functions = [f for f in funcs if IncorrectERC20InterfaceDetection.incorrect_erc20_interface(f.signature)]
return functions return functions
def _detect(self): def _detect(self):
@ -80,7 +81,7 @@ contract Token{
dict: [contract name] = set(str) events dict: [contract name] = set(str) events
""" """
results = [] results = []
for c in self.contracts: for c in self.slither.contracts_derived:
functions = IncorrectERC20InterfaceDetection.detect_incorrect_erc20_interface(c) functions = IncorrectERC20InterfaceDetection.detect_incorrect_erc20_interface(c)
if functions: if functions:
for function in functions: for function in functions:

@ -68,10 +68,11 @@ contract Token{
""" """
# Verify this is an ERC721 contract. # Verify this is an ERC721 contract.
if not contract.has_an_erc721_function() or not contract.has_an_erc20_function(): if not contract.is_possible_erc721() or not contract.is_possible_erc20():
return [] return []
functions = [f for f in contract.functions if IncorrectERC721InterfaceDetection.incorrect_erc721_interface(f.signature)] funcs = contract.functions
functions = [f for f in funcs if IncorrectERC721InterfaceDetection.incorrect_erc721_interface(f.signature)]
return functions return functions
def _detect(self): def _detect(self):
@ -81,7 +82,7 @@ contract Token{
dict: [contract name] = set(str) events dict: [contract name] = set(str) events
""" """
results = [] results = []
for c in self.contracts: for c in self.slither.contracts_derived:
functions = IncorrectERC721InterfaceDetection.detect_incorrect_erc721_interface(c) functions = IncorrectERC721InterfaceDetection.detect_incorrect_erc721_interface(c)
if functions: if functions:
for function in functions: for function in functions:

@ -0,0 +1,43 @@
"""
Module detecting unused return values from low level
"""
from slither.detectors.abstract_detector import DetectorClassification
from .unused_return_values import UnusedReturnValues
from slither.slithir.operations import LowLevelCall
class UncheckedLowLevel(UnusedReturnValues):
"""
If the return value of a send is not checked, it might lead to losing ether
"""
ARGUMENT = 'unchecked-lowlevel'
HELP = 'Unchecked low-level calls'
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = 'https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-low-level'
WIKI_TITLE = 'Unchecked low-level calls'
WIKI_DESCRIPTION = 'The return value of a low-level call is not checked.'
WIKI_EXPLOIT_SCENARIO = '''
```solidity
contract MyConc{
function my_func(address payable dst) public payable{
dst.call.value(msg.value)("");
}
}
```
The return value of the low-level call is not checked. As a result if the callfailed, the ether will be locked in the contract.
If the low level is used to prevent blocking operations, consider logging failed calls.
'''
WIKI_RECOMMENDATION = 'Ensure that the return value of low-level call is checked or logged.'
_txt_description = "low-level calls"
def _is_instance(self, ir):
return isinstance(ir, LowLevelCall)

@ -0,0 +1,40 @@
"""
Module detecting unused return values from send
"""
from slither.detectors.abstract_detector import DetectorClassification
from .unused_return_values import UnusedReturnValues
from slither.slithir.operations import Send
class UncheckedSend(UnusedReturnValues):
"""
If the return value of a send is not checked, it might lead to losing ether
"""
ARGUMENT = 'unchecked-send'
HELP = 'Unchecked send'
IMPACT = DetectorClassification.MEDIUM
CONFIDENCE = DetectorClassification.MEDIUM
WIKI = 'https://github.com/crytic/slither/wiki/Detector-Documentation#unchecked-send'
WIKI_TITLE = 'Unchecked Send'
WIKI_DESCRIPTION = 'The return value of a send is not checked.'
WIKI_EXPLOIT_SCENARIO = '''
```solidity
contract MyConc{
function my_func(address payable dst) public payable{
dst.send(msg.value);
}
}
```
The return value of `send` is not checked. As a result if the send failed, the ether will be locked in the contract.
If `send` is used to prevent blocking operations, consider logging the failed sent.
'''
WIKI_RECOMMENDATION = 'Ensure that the return value of send is checked or logged.'
_txt_description = "send calls"
def _is_instance(self, ir):
return isinstance(ir, Send)

@ -2,9 +2,8 @@
Module detecting unused return values from external calls Module detecting unused return values from external calls
""" """
from collections import defaultdict
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.slithir.operations.high_level_call import HighLevelCall from slither.slithir.operations import HighLevelCall, InternalCall, InternalDynamicCall
from slither.core.variables.state_variable import StateVariable from slither.core.variables.state_variable import StateVariable
class UnusedReturnValues(AbstractDetector): class UnusedReturnValues(AbstractDetector):
@ -19,7 +18,6 @@ class UnusedReturnValues(AbstractDetector):
WIKI = 'https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return' WIKI = 'https://github.com/crytic/slither/wiki/Detector-Documentation#unused-return'
WIKI_TITLE = 'Unused return' WIKI_TITLE = 'Unused return'
WIKI_DESCRIPTION = 'The return value of an external call is not stored in a local or state variable.' WIKI_DESCRIPTION = 'The return value of an external call is not stored in a local or state variable.'
WIKI_EXPLOIT_SCENARIO = ''' WIKI_EXPLOIT_SCENARIO = '''
@ -33,7 +31,12 @@ contract MyConc{
``` ```
`MyConc` calls `add` of SafeMath, but does not store the result in `a`. As a result, the computation has no effect.''' `MyConc` calls `add` of SafeMath, but does not store the result in `a`. As a result, the computation has no effect.'''
WIKI_RECOMMENDATION = 'Ensure that all the return values of the function calls are stored in a local or state variable.' WIKI_RECOMMENDATION = 'Ensure that all the return values of the function calls are used.'
_txt_description = "external calls"
def _is_instance(self, ir):
return isinstance(ir, HighLevelCall)
def detect_unused_return_values(self, f): def detect_unused_return_values(self, f):
""" """
@ -47,7 +50,7 @@ contract MyConc{
nodes_origin = {} nodes_origin = {}
for n in f.nodes: for n in f.nodes:
for ir in n.irs: for ir in n.irs:
if isinstance(ir, HighLevelCall): if self._is_instance(ir):
# if a return value is stored in a state variable, it's ok # if a return value is stored in a state variable, it's ok
if ir.lvalue and not isinstance(ir.lvalue, StateVariable): if ir.lvalue and not isinstance(ir.lvalue, StateVariable):
values_returned.append(ir.lvalue) values_returned.append(ir.lvalue)
@ -69,10 +72,11 @@ contract MyConc{
unused_return = self.detect_unused_return_values(f) unused_return = self.detect_unused_return_values(f)
if unused_return: if unused_return:
for node in unused_return: for node in unused_return:
info = "{}.{} ({}) ignores return value by external call \"{}\" ({})\n" info = "{}.{} ({}) ignores return value by {} \"{}\" ({})\n"
info = info.format(f.contract.name, info = info.format(f.contract.name,
f.name, f.name,
f.source_mapping_str, f.source_mapping_str,
self._txt_description,
node.expression, node.expression,
node.source_mapping_str) node.source_mapping_str)
@ -82,3 +86,4 @@ contract MyConc{
results.append(json) results.append(json)
return results return results

@ -0,0 +1,3 @@
class SlitherException(Exception): pass
class SlitherError(SlitherException): pass

@ -6,7 +6,7 @@ import logging
from slither.printers.abstract_printer import AbstractPrinter from slither.printers.abstract_printer import AbstractPrinter
from slither.utils.code_complexity import compute_cyclomatic_complexity from slither.utils.code_complexity import compute_cyclomatic_complexity
from slither.utils.colors import green, red, yellow from slither.utils.colors import green, red, yellow
from slither.utils.standard_libraries import is_standard_library
class PrinterHumanSummary(AbstractPrinter): class PrinterHumanSummary(AbstractPrinter):
ARGUMENT = 'human-summary' ARGUMENT = 'human-summary'
@ -88,8 +88,14 @@ class PrinterHumanSummary(AbstractPrinter):
issues_informational, issues_low, issues_medium, issues_high = self._get_detectors_result() issues_informational, issues_low, issues_medium, issues_high = self._get_detectors_result()
txt = "Number of informational issues: {}\n".format(green(issues_informational)) txt = "Number of informational issues: {}\n".format(green(issues_informational))
txt += "Number of low issues: {}\n".format(green(issues_low)) txt += "Number of low issues: {}\n".format(green(issues_low))
if issues_medium > 0:
txt += "Number of medium issues: {}\n".format(yellow(issues_medium)) txt += "Number of medium issues: {}\n".format(yellow(issues_medium))
else:
txt += "Number of medium issues: {}\n".format(green(issues_medium))
if issues_high > 0:
txt += "Number of high issues: {}\n".format(red(issues_high)) txt += "Number of high issues: {}\n".format(red(issues_high))
else:
txt += "Number of high issues: {}\n\n".format(green(issues_high))
return txt return txt
@ -119,6 +125,49 @@ class PrinterHumanSummary(AbstractPrinter):
def _number_functions(contract): def _number_functions(contract):
return len(contract.functions) return len(contract.functions)
def _lines_number(self):
if not self.slither.source_code:
return None
total_dep_lines = 0
total_lines = 0
for filename, source_code in self.slither.source_code.items():
lines = len(source_code.splitlines())
is_dep = False
if self.slither.crytic_compile:
is_dep = self.slither.crytic_compile.is_dependency(filename)
if is_dep:
total_dep_lines += lines
else:
total_lines += lines
return total_lines, total_dep_lines
def _compilation_type(self):
if self.slither.crytic_compile is None:
return 'Compilation non standard\n'
return f'Compiled with {self.slither.crytic_compile.type}\n'
def _number_contracts(self):
if self.slither.crytic_compile is None:
len(self.slither.contracts), 0
deps = [c for c in self.slither.contracts if c.is_from_dependency()]
contracts = [c for c in self.slither.contracts if not c.is_from_dependency()]
return len(contracts), len(deps)
def _standard_libraries(self):
libraries = []
for contract in self.contracts:
lib = is_standard_library(contract)
if lib:
libraries.append(lib)
return libraries
def _ercs(self):
ercs = []
for contract in self.contracts:
ercs += contract.ercs()
return list(set(ercs))
def output(self, _filename): def output(self, _filename):
""" """
_filename is not used _filename is not used
@ -126,15 +175,37 @@ class PrinterHumanSummary(AbstractPrinter):
_filename(string) _filename(string)
""" """
txt = "Analyze of {}\n".format(self.slither.filename) txt = "\n"
txt += self._compilation_type()
lines_number = self._lines_number()
if lines_number:
total_lines, total_dep_lines = lines_number
txt += f'Number of lines: {total_lines} (+ {total_dep_lines} in dependencies)\n'
number_contracts, number_contracts_deps = self._number_contracts()
txt += f'Number of contracts: {number_contracts} (+ {number_contracts_deps} in dependencies) \n\n'
txt += self.get_detectors_result() txt += self.get_detectors_result()
libs = self._standard_libraries()
if libs:
txt += f'\nUse: {", ".join(libs)}\n'
ercs = self._ercs()
if ercs:
txt += f'ERCs: {", ".join(ercs)}\n'
for contract in self.slither.contracts_derived: for contract in self.slither.contracts_derived:
txt += "\nContract {}\n".format(contract.name) txt += "\nContract {}\n".format(contract.name)
txt += self.is_complex_code(contract) txt += self.is_complex_code(contract)
txt += '\tNumber of functions: {}\n'.format(self._number_functions(contract))
ercs = contract.ercs()
if ercs:
txt += '\tERCs: ' + ','.join(ercs) + '\n'
is_erc20 = contract.is_erc20() is_erc20 = contract.is_erc20()
txt += '\tNumber of functions:{}'.format(self._number_functions(contract))
txt += "\tIs ERC20 token: {}\n".format(contract.is_erc20())
if is_erc20: if is_erc20:
txt += '\tERC20 info:\n'
txt += self.get_summary_erc20(contract) txt += self.get_summary_erc20(contract)
self.info(txt) self.info(txt)

@ -11,7 +11,7 @@ from crytic_compile import CryticCompile, InvalidCompilation
from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification from slither.detectors.abstract_detector import AbstractDetector, DetectorClassification
from slither.printers.abstract_printer import AbstractPrinter from slither.printers.abstract_printer import AbstractPrinter
from .solc_parsing.slitherSolc import SlitherSolc from .solc_parsing.slitherSolc import SlitherSolc
from .utils.colors import red from .exceptions import SlitherError
logger = logging.getLogger("Slither") logger = logging.getLogger("Slither")
logging.basicConfig() logging.basicConfig()
@ -44,10 +44,6 @@ class Slither(SlitherSolc):
embark_overwrite_config (bool): overwrite original config file (default false) embark_overwrite_config (bool): overwrite original config file (default false)
''' '''
truffle_ignore = kwargs.get('truffle_ignore', False)
embark_ignore = kwargs.get('embark_ignore', False)
# list of files provided (see --splitted option) # list of files provided (see --splitted option)
if isinstance(contract, list): if isinstance(contract, list):
self._init_from_list(contract) self._init_from_list(contract)
@ -56,14 +52,11 @@ class Slither(SlitherSolc):
else: else:
super(Slither, self).__init__('') super(Slither, self).__init__('')
try: try:
cryticCompile = CryticCompile(contract, **kwargs) crytic_compile = CryticCompile(contract, **kwargs)
self._crytic_compile = cryticCompile self._crytic_compile = crytic_compile
except InvalidCompilation as e: except InvalidCompilation as e:
logger.error('Invalid compilation') raise SlitherError('Invalid compilation: \n'+str(e))
logger.error(e) for path, ast in crytic_compile.asts.items():
exit(-1)
for path, ast in cryticCompile.asts.items():
self._parse_contracts_from_loaded_json(ast, path) self._parse_contracts_from_loaded_json(ast, path)
self._add_source_code(path) self._add_source_code(path)
@ -81,14 +74,12 @@ class Slither(SlitherSolc):
def _init_from_raw_json(self, filename): def _init_from_raw_json(self, filename):
if not os.path.isfile(filename): if not os.path.isfile(filename):
logger.error('{} does not exist (are you in the correct directory?)'.format(filename)) raise SlitherError('{} does not exist (are you in the correct directory?)'.format(filename))
exit(-1)
assert filename.endswith('json') assert filename.endswith('json')
with open(filename, encoding='utf8') as astFile: with open(filename, encoding='utf8') as astFile:
stdout = astFile.read() stdout = astFile.read()
if not stdout: if not stdout:
logger.info('Empty AST file: %s', filename) raise SlitherError('Empty AST file: %s', filename)
sys.exit(-1)
contracts_json = stdout.split('\n=') contracts_json = stdout.split('\n=')
super(Slither, self).__init__(filename) super(Slither, self).__init__(filename)
@ -169,21 +160,19 @@ class Slither(SlitherSolc):
) )
) )
if any(isinstance(obj, cls) for obj in instances_list): if any(type(obj) == cls for obj in instances_list):
raise Exception( raise Exception(
"You can't register {!r} twice.".format(cls) "You can't register {!r} twice.".format(cls)
) )
def _run_solc(self, filename, solc, disable_solc_warnings, solc_arguments, ast_format): def _run_solc(self, filename, solc, disable_solc_warnings, solc_arguments, ast_format):
if not os.path.isfile(filename): if not os.path.isfile(filename):
logger.error('{} does not exist (are you in the correct directory?)'.format(filename)) raise SlitherError('{} does not exist (are you in the correct directory?)'.format(filename))
exit(-1)
assert filename.endswith('json') assert filename.endswith('json')
with open(filename, encoding='utf8') as astFile: with open(filename, encoding='utf8') as astFile:
stdout = astFile.read() stdout = astFile.read()
if not stdout: if not stdout:
logger.info('Empty AST file: %s', filename) raise SlitherError('Empty AST file: %s', filename)
sys.exit(-1)
stdout = stdout.split('\n=') stdout = stdout.split('\n=')
return stdout return stdout

@ -33,6 +33,7 @@ from slither.slithir.variables import (Constant, ReferenceVariable,
from slither.visitors.slithir.expression_to_slithir import ExpressionToSlithIR from slither.visitors.slithir.expression_to_slithir import ExpressionToSlithIR
from slither.utils.function import get_function_id from slither.utils.function import get_function_id
from slither.utils.type import export_nested_types_from_variable from slither.utils.type import export_nested_types_from_variable
from slither.slithir.exceptions import SlithIRError
logger = logging.getLogger('ConvertToIR') logger = logging.getLogger('ConvertToIR')
@ -457,8 +458,7 @@ def propagate_types(ir, node):
# temporary operation; they will be removed # temporary operation; they will be removed
pass pass
else: else:
logger.error('Not handling {} during type propgation'.format(type(ir))) raise SlithIRError('Not handling {} during type propgation'.format(type(ir)))
exit(-1)
def extract_tmp_call(ins, contract): def extract_tmp_call(ins, contract):
assert isinstance(ins, TmpCall) assert isinstance(ins, TmpCall)
@ -577,8 +577,7 @@ def convert_to_low_level(ir):
new_ir.arguments = ir.arguments new_ir.arguments = ir.arguments
new_ir.lvalue.set_type(ElementaryType('bool')) new_ir.lvalue.set_type(ElementaryType('bool'))
return new_ir return new_ir
logger.error('Incorrect conversion to low level {}'.format(ir)) raise SlithIRError('Incorrect conversion to low level {}'.format(ir))
exit(-1)
def convert_to_push(ir, node): def convert_to_push(ir, node):
""" """
@ -679,6 +678,9 @@ def convert_type_library_call(ir, lib_contract):
func = lib_contract.get_function_from_signature(sig) func = lib_contract.get_function_from_signature(sig)
if not func: if not func:
func = lib_contract.get_state_variable_from_name(ir.function_name) func = lib_contract.get_state_variable_from_name(ir.function_name)
if func:
# stop to explore if func is found (prevent dupplicate issue)
break
# In case of multiple binding to the same type # In case of multiple binding to the same type
if not func: if not func:
# specific lookup when the compiler does implicit conversion # specific lookup when the compiler does implicit conversion
@ -713,6 +715,9 @@ def convert_type_of_high_and_internal_level_call(ir, contract):
func = contract.get_function_from_signature(sig) func = contract.get_function_from_signature(sig)
if not func: if not func:
func = contract.get_state_variable_from_name(ir.function_name) func = contract.get_state_variable_from_name(ir.function_name)
if func:
# stop to explore if func is found (prevent dupplicate issue)
break
if not func: if not func:
# specific lookup when the compiler does implicit conversion # specific lookup when the compiler does implicit conversion
# for example # for example

@ -0,0 +1,3 @@
from slither.exceptions import SlitherException
class SlithIRError(SlitherException): pass

@ -4,6 +4,7 @@ from slither.core.variables.variable import Variable
from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue
from slither.core.solidity_types import ElementaryType from slither.core.solidity_types import ElementaryType
from slither.slithir.variables import ReferenceVariable from slither.slithir.variables import ReferenceVariable
from slither.slithir.exceptions import SlithIRError
logger = logging.getLogger("BinaryOperationIR") logger = logging.getLogger("BinaryOperationIR")
@ -80,8 +81,7 @@ class BinaryType(object):
if operation_type == '||': if operation_type == '||':
return BinaryType.OROR return BinaryType.OROR
logger.error('get_type: Unknown operation type {})'.format(operation_type)) raise SlithIRError('get_type: Unknown operation type {})'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def str(operation_type): def str(operation_type):
@ -123,8 +123,7 @@ class BinaryType(object):
return '&&' return '&&'
if operation_type == BinaryType.OROR: if operation_type == BinaryType.OROR:
return '||' return '||'
logger.error('str: Unknown operation type {})'.format(operation_type)) raise SlithIRError('str: Unknown operation type {})'.format(operation_type))
exit(-1)
class Binary(OperationWithLValue): class Binary(OperationWithLValue):

@ -40,7 +40,7 @@ class Return(Operation):
@property @property
def values(self): def values(self):
return self._values return self._unroll(self._values)
def __str__(self): def __str__(self):
return "RETURN {}".format(','.join(['{}'.format(x) for x in self.values])) return "RETURN {}".format(','.join(['{}'.format(x) for x in self.values]))

@ -1,8 +1,7 @@
import logging import logging
from slither.slithir.operations.lvalue import OperationWithLValue from slither.slithir.operations.lvalue import OperationWithLValue
from slither.core.variables.variable import Variable
from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue from slither.slithir.utils.utils import is_valid_lvalue, is_valid_rvalue
from slither.slithir.exceptions import SlithIRError
logger = logging.getLogger("BinaryOperationIR") logger = logging.getLogger("BinaryOperationIR")
@ -17,8 +16,7 @@ class UnaryType:
return UnaryType.BANG return UnaryType.BANG
if operation_type == '~': if operation_type == '~':
return UnaryType.TILD return UnaryType.TILD
logger.error('get_type: Unknown operation type {}'.format(operation_type)) raise SlithIRError('get_type: Unknown operation type {}'.format(operation_type))
exit(-1)
@staticmethod @staticmethod
def str(operation_type): def str(operation_type):
@ -27,8 +25,7 @@ class UnaryType:
if operation_type == UnaryType.TILD: if operation_type == UnaryType.TILD:
return '~' return '~'
logger.error('str: Unknown operation type {}'.format(operation_type)) raise SlithIRError('str: Unknown operation type {}'.format(operation_type))
exit(-1)
class Unary(OperationWithLValue): class Unary(OperationWithLValue):

@ -22,6 +22,7 @@ from slither.slithir.variables import (Constant, LocalIRVariable,
ReferenceVariable, ReferenceVariableSSA, ReferenceVariable, ReferenceVariableSSA,
StateIRVariable, TemporaryVariable, StateIRVariable, TemporaryVariable,
TemporaryVariableSSA, TupleVariable, TupleVariableSSA) TemporaryVariableSSA, TupleVariable, TupleVariableSSA)
from slither.slithir.exceptions import SlithIRError
logger = logging.getLogger('SSA_Conversion') logger = logging.getLogger('SSA_Conversion')
@ -662,7 +663,6 @@ def copy_ir(ir, *instances):
return Length(value, lvalue) return Length(value, lvalue)
logger.error('Impossible ir copy on {} ({})'.format(ir, type(ir))) raise SlithIRError('Impossible ir copy on {} ({})'.format(ir, type(ir)))
exit(-1)
# endregion # endregion

@ -13,8 +13,8 @@ class Constant(SlithIRVariable):
if type: if type:
assert isinstance(type, ElementaryType) assert isinstance(type, ElementaryType)
self._type = type self._type = type
if type.type in Int + Uint: if type.type in Int + Uint + ['address']:
if val.startswith('0x'): if val.startswith('0x') or val.startswith('0X'):
self._val = int(val, 16) self._val = int(val, 16)
else: else:
if 'e' in val: if 'e' in val:
@ -24,7 +24,7 @@ class Constant(SlithIRVariable):
base, expo = val.split('E') base, expo = val.split('E')
self._val = int(float(base) * (10 ** int(expo))) self._val = int(float(base) * (10 ** int(expo)))
else: else:
self._val = int(val) self._val = int(float(val))
elif type.type == 'bool': elif type.type == 'bool':
self._val = val == 'true' self._val = val == 'true'
else: else:

@ -9,6 +9,7 @@ from slither.solc_parsing.declarations.modifier import ModifierSolc
from slither.solc_parsing.declarations.structure import StructureSolc from slither.solc_parsing.declarations.structure import StructureSolc
from slither.solc_parsing.solidity_types.type_parsing import parse_type from slither.solc_parsing.solidity_types.type_parsing import parse_type
from slither.solc_parsing.variables.state_variable import StateVariableSolc from slither.solc_parsing.variables.state_variable import StateVariableSolc
from slither.solc_parsing.exceptions import ParsingError
logger = logging.getLogger("ContractSolcParsing") logger = logging.getLogger("ContractSolcParsing")
@ -186,8 +187,7 @@ class ContractSolc04(Contract):
elif item[self.get_key()] == 'UsingForDirective': elif item[self.get_key()] == 'UsingForDirective':
self._usingForNotParsed.append(item) self._usingForNotParsed.append(item)
else: else:
logger.error('Unknown contract item: '+item[self.get_key()]) raise ParsingError('Unknown contract item: '+item[self.get_key()])
exit(-1)
return return
def _parse_struct(self, struct): def _parse_struct(self, struct):

@ -26,6 +26,7 @@ from slither.utils.expression_manipulations import SplitTernaryExpression
from slither.utils.utils import unroll from slither.utils.utils import unroll
from slither.visitors.expression.export_values import ExportValues from slither.visitors.expression.export_values import ExportValues
from slither.visitors.expression.has_conditional import HasConditional from slither.visitors.expression.has_conditional import HasConditional
from slither.solc_parsing.exceptions import ParsingError
logger = logging.getLogger("FunctionSolc") logger = logging.getLogger("FunctionSolc")
@ -725,8 +726,7 @@ class FunctionSolc(Function):
link_nodes(node, new_node) link_nodes(node, new_node)
node = new_node node = new_node
else: else:
logger.error('Statement not parsed %s'%name) raise ParsingError('Statement not parsed %s'%name)
exit(-1)
return node return node
@ -814,8 +814,7 @@ class FunctionSolc(Function):
end_node = self._find_end_loop(node, [], 0) end_node = self._find_end_loop(node, [], 0)
if not end_node: if not end_node:
logger.error('Break in no-loop context {}'.format(node)) raise ParsingError('Break in no-loop context {}'.format(node))
exit(-1)
for son in node.sons: for son in node.sons:
son.remove_father(node) son.remove_father(node)
@ -826,8 +825,7 @@ class FunctionSolc(Function):
start_node = self._find_start_loop(node, []) start_node = self._find_start_loop(node, [])
if not start_node: if not start_node:
logger.error('Continue in no-loop context {}'.format(node.nodeId())) raise ParsingError('Continue in no-loop context {}'.format(node.nodeId()))
exit(-1)
for son in node.sons: for son in node.sons:
son.remove_father(node) son.remove_father(node)

@ -0,0 +1,7 @@
from slither.exceptions import SlitherException
class ParsingError(SlitherException): pass
class ParsingNameReuse(SlitherException): pass
class ParsingContractNotFound(SlitherException): pass

@ -35,7 +35,7 @@ from slither.core.solidity_types import (ArrayType, ElementaryType,
FunctionType, MappingType) FunctionType, MappingType)
from slither.solc_parsing.solidity_types.type_parsing import (UnknownType, from slither.solc_parsing.solidity_types.type_parsing import (UnknownType,
parse_type) parse_type)
from slither.solc_parsing.exceptions import ParsingError
logger = logging.getLogger("ExpressionParsing") logger = logging.getLogger("ExpressionParsing")
@ -78,8 +78,7 @@ def find_variable(var_name, caller_context, referenced_declaration=None):
function = caller_context function = caller_context
contract = function.contract contract = function.contract
else: else:
logger.error('Incorrect caller context') raise ParsingError('Incorrect caller context')
exit(-1)
if function: if function:
# We look for variable declared with the referencedDeclaration attr # We look for variable declared with the referencedDeclaration attr
@ -497,10 +496,17 @@ def parse_expression(expression, caller_context):
value = '0x'+expression['attributes']['hexvalue'] value = '0x'+expression['attributes']['hexvalue']
type = expression['attributes']['type'] type = expression['attributes']['type']
if type.startswith('int_const '): if type is None:
if value.isdecimal():
type = ElementaryType('uint256')
else:
type = ElementaryType('string')
elif type.startswith('int_const '):
type = ElementaryType('uint256') type = ElementaryType('uint256')
elif type.startswith('bool'): elif type.startswith('bool'):
type = ElementaryType('bool') type = ElementaryType('bool')
elif type.startswith('address'):
type = ElementaryType('address')
else: else:
type = ElementaryType('string') type = ElementaryType('string')
literal = Literal(value, type) literal = Literal(value, type)
@ -627,8 +633,7 @@ def parse_expression(expression, caller_context):
elif type_name[caller_context.get_key()] == 'FunctionTypeName': elif type_name[caller_context.get_key()] == 'FunctionTypeName':
array_type = parse_type(type_name, caller_context) array_type = parse_type(type_name, caller_context)
else: else:
logger.error('Incorrect type array {}'.format(type_name)) raise ParsingError('Incorrect type array {}'.format(type_name))
exit(-1)
array = NewArray(depth, array_type) array = NewArray(depth, array_type)
return array return array
@ -664,5 +669,5 @@ def parse_expression(expression, caller_context):
call = CallExpression(called, arguments, 'Modifier') call = CallExpression(called, arguments, 'Modifier')
return call return call
logger.error('Expression not parsed %s'%name) raise ParsingError('Expression not parsed %s'%name)
exit(-1)

@ -14,6 +14,7 @@ from slither.core.declarations.import_directive import Import
from slither.analyses.data_dependency.data_dependency import compute_dependency from slither.analyses.data_dependency.data_dependency import compute_dependency
from slither.utils.colors import red from slither.utils.colors import red
from .exceptions import ParsingNameReuse, ParsingContractNotFound
class SlitherSolc(Slither): class SlitherSolc(Slither):
@ -182,8 +183,7 @@ class SlitherSolc(Slither):
info += '\n{} is defined in:'.format(contract.name) info += '\n{} is defined in:'.format(contract.name)
info += '\n- {}\n- {}'.format(contract.source_mapping_str, info += '\n- {}\n- {}'.format(contract.source_mapping_str,
self._contracts[contract.name].source_mapping_str) self._contracts[contract.name].source_mapping_str)
logger.error(info) raise ParsingNameReuse(info)
exit(-1)
else: else:
self._contracts_by_id[contract.id] = contract self._contracts_by_id[contract.id] = contract
self._contracts[contract.name] = contract self._contracts[contract.name] = contract
@ -217,11 +217,11 @@ class SlitherSolc(Slither):
father_constructors.append(self._contracts_by_id[i]) father_constructors.append(self._contracts_by_id[i])
except KeyError: except KeyError:
logger.error(red('A contract was not found, it is likely that your codebase contains muliple contracts with the same name')) txt = 'A contract was not found, it is likely that your codebase contains muliple contracts with the same name'
logger.error(red('Truffle does not handle this case during compilation')) txt += 'Truffle does not handle this case during compilation'
logger.error(red('Please read https://github.com/trailofbits/slither/wiki#keyerror-or-nonetype-error')) txt += 'Please read https://github.com/trailofbits/slither/wiki#keyerror-or-nonetype-error'
logger.error(red('And update your code to remove the duplicate')) txt += 'And update your code to remove the duplicate'
exit(-1) raise ParsingContractNotFound(txt)
contract.setInheritance(ancestors, fathers, father_constructors) contract.setInheritance(ancestors, fathers, father_constructors)
contracts_to_be_analyzed = self.contracts contracts_to_be_analyzed = self.contracts

@ -13,6 +13,7 @@ from slither.core.declarations.function import Function
from slither.core.expressions.literal import Literal from slither.core.expressions.literal import Literal
from slither.solc_parsing.exceptions import ParsingError
import re import re
logger = logging.getLogger('TypeParsing') logger = logging.getLogger('TypeParsing')
@ -118,8 +119,7 @@ def _find_from_type_name(name, contract, contracts, structures, enums):
return MappingType(from_type, to_type) return MappingType(from_type, to_type)
if not var_type: if not var_type:
logger.error('Type not found '+str(name)) raise ParsingError('Type not found '+str(name))
exit(-1)
return UserDefinedType(var_type) return UserDefinedType(var_type)
@ -134,8 +134,7 @@ def parse_type(t, caller_context):
elif isinstance(caller_context, Function): elif isinstance(caller_context, Function):
contract = caller_context.contract contract = caller_context.contract
else: else:
logger.error('Incorrect caller context') raise ParsingError('Incorrect caller context')
exit(-1)
is_compact_ast = caller_context.is_compact_ast is_compact_ast = caller_context.is_compact_ast
@ -223,5 +222,4 @@ def parse_type(t, caller_context):
return FunctionType(params_vars, return_values_vars) return FunctionType(params_vars, return_values_vars)
logger.error('Type name not found '+str(t)) raise ParsingError('Type name not found '+str(t))
exit(-1)

@ -6,7 +6,7 @@ from slither.core.variables.variable import Variable
from slither.solc_parsing.solidity_types.type_parsing import parse_type, UnknownType from slither.solc_parsing.solidity_types.type_parsing import parse_type, UnknownType
from slither.core.solidity_types.elementary_type import ElementaryType, NonElementaryType from slither.core.solidity_types.elementary_type import ElementaryType, NonElementaryType
from slither.solc_parsing.exceptions import ParsingError
logger = logging.getLogger("VariableDeclarationSolcParsing") logger = logging.getLogger("VariableDeclarationSolcParsing")
class MultipleVariablesDeclaration(Exception): class MultipleVariablesDeclaration(Exception):
@ -51,8 +51,7 @@ class VariableDeclarationSolc(Variable):
elif nodeType == 'VariableDeclaration': elif nodeType == 'VariableDeclaration':
self._init_from_declaration(var, var['value']) self._init_from_declaration(var, var['value'])
else: else:
logger.error('Incorrect variable declaration type {}'.format(nodeType)) raise ParsingError('Incorrect variable declaration type {}'.format(nodeType))
exit(-1)
else: else:
nodeType = var['name'] nodeType = var['name']
@ -65,15 +64,13 @@ class VariableDeclarationSolc(Variable):
elif len(var['children']) > 2: elif len(var['children']) > 2:
raise MultipleVariablesDeclaration raise MultipleVariablesDeclaration
else: else:
logger.error('Variable declaration without children?'+var) raise ParsingError('Variable declaration without children?'+var)
exit(-1)
declaration = var['children'][0] declaration = var['children'][0]
self._init_from_declaration(declaration, init) self._init_from_declaration(declaration, init)
elif nodeType == 'VariableDeclaration': elif nodeType == 'VariableDeclaration':
self._init_from_declaration(var, None) self._init_from_declaration(var, None)
else: else:
logger.error('Incorrect variable declaration type {}'.format(nodeType)) raise ParsingError('Incorrect variable declaration type {}'.format(nodeType))
exit(-1)
@property @property
def initialized(self): def initialized(self):

@ -0,0 +1,69 @@
def erc_to_signatures(erc):
return [f'{e[0]}({",".join(e[1])})' for e in erc]
# Final
# https://eips.ethereum.org/EIPS/eip-20
# name, symbolc, decimals are optionals
ERC20 = [('totalSupply', [], 'uint256'),
('balanceOf', ['address'], 'uint256'),
('transfer', ['address', 'uint256'], 'bool'),
('transferFrom', ['address', 'address', 'uint256'], 'bool'),
('approve', ['address', 'uint256'], 'bool'),
('allowance', ['address', 'address'], 'uint256')]
ERC20_signatures = erc_to_signatures(ERC20)
# Draft
# https://github.com/ethereum/eips/issues/223
ERC223 = [('name', [], 'string'),
('symbol', [], 'string'),
('decimals', [], 'uint8'),
('totalSupply', [], 'uint256'),
('balanceOf', ['address'], 'uint256'),
('transfer', ['address', 'uint256'], 'bool'),
('transfer', ['address', 'uint256', 'bytes'], 'bool'),
('transfer', ['address', 'uint256', 'bytes', 'string'], 'bool')]
ERC223_signatures = erc_to_signatures(ERC223)
# Final
# https://eips.ethereum.org/EIPS/eip-165
ERC165 = [('supportsInterface', ['bytes4'], 'bool')]
ERC165_signatures = erc_to_signatures(ERC165)
# Final
# https://eips.ethereum.org/EIPS/eip-721
# Must have ERC165
# name, symbol, tokenURI are optionals
ERC721 = [('balanceOf', ['address'], 'uint256'),
('ownerOf', ['uint256'], 'address'),
('safeTransferFrom', ['address', 'address', 'uint256', 'bytes'], ''),
('safeTransferFrom', ['address', 'address', 'uint256'], ''),
('transferFrom', ['address', 'address', 'uint256'], ''),
('approve', ['address', 'uint256'], ''),
('setApprovalForAll', ['address', 'bool'], ''),
('getApproved', ['uint256'], 'address'),
('isApprovedForAll', ['address', 'address'], 'bool')] + ERC165
ERC721_signatures = erc_to_signatures(ERC721)
# Final
# https://eips.ethereum.org/EIPS/eip-1820
ERC1820 = [('canImplementInterfaceForAddress', ['bytes32', 'address'], 'bytes32')]
ERC1820_signatures = erc_to_signatures(ERC1820)
# Last Call
# https://eips.ethereum.org/EIPS/eip-777
ERC777 = [('name', [], 'string'),
('symbol', [], 'string'),
('totalSupply', [], 'uint256'),
('balanceOf', ['address'], 'uint256'),
('granularity', [], 'uint256'),
('defaultOperators', [], 'address[]'),
('isOperatorFor', ['address', 'address'], 'bool'),
('authorizeOperator', ['address'], ''),
('revokeOperator', ['address'], ''),
('send', ['address', 'uint256', 'bytes'], ''),
('operatorSend', ['address', 'address', 'uint256', 'bytes', 'bytes'], ''),
('burn', ['uint256', 'bytes'] , ''),
('operatorBurn', ['address', 'uint256', 'bytes', 'bytes'] , '')]
ERC777_signatures = erc_to_signatures(ERC777)

@ -0,0 +1,193 @@
from pathlib import Path
libraries = {
'Openzeppelin-SafeMath': lambda x: is_openzepellin_safemath(x),
'Openzeppelin-ECRecovery': lambda x: is_openzepellin_ecrecovery(x),
'Openzeppelin-Ownable': lambda x: is_openzepellin_ownable(x),
'Openzeppelin-ERC20': lambda x: is_openzepellin_erc20(x),
'Openzeppelin-ERC721': lambda x: is_openzepellin_erc721(x),
'Zos-Upgrade': lambda x: is_zos_initializable(x),
'Dapphub-DSAuth': lambda x: is_dapphub_ds_auth(x),
'Dapphub-DSMath': lambda x: is_dapphub_ds_math(x),
'Dapphub-DSToken': lambda x: is_dapphub_ds_token(x),
'Dapphub-DSProxy': lambda x: is_dapphub_ds_proxy(x),
'Dapphub-DSGroup': lambda x: is_dapphub_ds_group(x),
}
def is_standard_library(contract):
for name, is_lib in libraries.items():
if is_lib(contract):
return name
return None
###################################################################################
###################################################################################
# region General libraries
###################################################################################
###################################################################################
def is_openzepellin(contract):
if not contract.is_from_dependency():
return False
return 'openzeppelin-solidity' in Path(contract.source_mapping['filename_absolute']).parts
def is_zos(contract):
if not contract.is_from_dependency():
return False
return 'zos-lib' in Path(contract.source_mapping['filename_absolute']).parts
# endregion
###################################################################################
###################################################################################
# region SafeMath
###################################################################################
###################################################################################
def is_safemath(contract):
return contract.name == "SafeMath"
def is_openzepellin_safemath(contract):
return is_safemath(contract) and is_openzepellin(contract)
# endregion
###################################################################################
###################################################################################
# region ECRecovery
###################################################################################
###################################################################################
def is_ecrecovery(contract):
return contract.name == 'ECRecovery'
def is_openzepellin_ecrecovery(contract):
return is_ecrecovery(contract) and is_openzepellin(contract)
# endregion
###################################################################################
###################################################################################
# region Ownable
###################################################################################
###################################################################################
def is_ownable(contract):
return contract.name == 'Ownable'
def is_openzepellin_ownable(contract):
return is_ownable(contract) and is_openzepellin(contract)
# endregion
###################################################################################
###################################################################################
# region ERC20
###################################################################################
###################################################################################
def is_erc20(contract):
return contract.name == 'ERC20'
def is_openzepellin_erc20(contract):
return is_erc20(contract) and is_openzepellin(contract)
# endregion
###################################################################################
###################################################################################
# region ERC721
###################################################################################
###################################################################################
def is_erc721(contract):
return contract.name == 'ERC721'
def is_openzepellin_erc721(contract):
return is_erc721(contract) and is_openzepellin(contract)
# endregion
###################################################################################
###################################################################################
# region Zos Initializable
###################################################################################
###################################################################################
def is_initializable(contract):
return contract.name == 'Initializable'
def is_zos_initializable(contract):
return is_initializable(contract) and is_zos(contract)
# endregion
###################################################################################
###################################################################################
# region DappHub
###################################################################################
###################################################################################
dapphubs = {
'DSAuth': 'ds-auth',
'DSMath': 'ds-math',
'DSToken': 'ds-token',
'DSProxy': 'ds-proxy',
'DSGroup': 'ds-group',
}
def _is_ds(contract, name):
return contract.name == name
def _is_dappdhub_ds(contract, name):
if not contract.is_from_dependency():
return False
if not dapphubs[name] in Path(contract.source_mapping['filename_absolute']).parts:
return False
return _is_ds(contract, name)
def is_ds_auth(contract):
return _is_ds(contract, 'DSAuth')
def is_dapphub_ds_auth(contract):
return _is_dappdhub_ds(contract, 'DSAuth')
def is_ds_math(contract):
return _is_ds(contract, 'DSMath')
def is_dapphub_ds_math(contract):
return _is_dappdhub_ds(contract, 'DSMath')
def is_ds_token(contract):
return _is_ds(contract, 'DSToken')
def is_dapphub_ds_token(contract):
return _is_dappdhub_ds(contract, 'DSToken')
def is_ds_proxy(contract):
return _is_ds(contract, 'DSProxy')
def is_dapphub_ds_proxy(contract):
return _is_dappdhub_ds(contract, 'DSProxy')
def is_ds_group(contract):
return _is_ds(contract, 'DSGroup')
def is_dapphub_ds_group(contract):
return _is_dappdhub_ds(contract, 'DSGroup')

@ -1,16 +1,19 @@
from slither.core.solidity_types import (ArrayType, MappingType, ElementaryType) from slither.core.solidity_types import (ArrayType, MappingType, ElementaryType)
def _add_mapping_parameter(t, l): def _add_mapping_parameter(t, l):
while isinstance(t, MappingType): while isinstance(t, MappingType):
l.append(t.type_from) l.append(t.type_from)
t = t.type_to t = t.type_to
_add_array_parameter(t, l) _add_array_parameter(t, l)
def _add_array_parameter(t, l): def _add_array_parameter(t, l):
while isinstance(t, ArrayType): while isinstance(t, ArrayType):
l.append(ElementaryType('uint256')) l.append(ElementaryType('uint256'))
t = t.type t = t.type
def export_nested_types_from_variable(variable): def export_nested_types_from_variable(variable):
""" """
Export the list of nested types (mapping/array) Export the list of nested types (mapping/array)

@ -21,8 +21,8 @@ def set_val(expression, val):
class ConstantFolding(ExpressionVisitor): class ConstantFolding(ExpressionVisitor):
def __init__(self, expression, type): def __init__(self, expression, type):
super(ConstantFolding, self).__init__(expression)
self._type = type self._type = type
super(ConstantFolding, self).__init__(expression)
def result(self): def result(self):
return Literal(int(get_val(self._expression)), self._type) return Literal(int(get_val(self._expression)), self._type)

@ -15,12 +15,14 @@ from slither.core.expressions.new_elementary_type import NewElementaryType
from slither.core.expressions.tuple_expression import TupleExpression from slither.core.expressions.tuple_expression import TupleExpression
from slither.core.expressions.type_conversion import TypeConversion from slither.core.expressions.type_conversion import TypeConversion
from slither.core.expressions.unary_operation import UnaryOperation from slither.core.expressions.unary_operation import UnaryOperation
from slither.exceptions import SlitherError
logger = logging.getLogger("ExpressionVisitor") logger = logging.getLogger("ExpressionVisitor")
class ExpressionVisitor: class ExpressionVisitor:
def __init__(self, expression): def __init__(self, expression):
# Inherited class must declared their variables prior calling super().__init__
self._expression = expression self._expression = expression
self._result = None self._result = None
self._visit_expression(self.expression) self._visit_expression(self.expression)
@ -86,8 +88,7 @@ class ExpressionVisitor:
pass pass
else: else:
logger.error('Expression not handled: {}'.format(expression)) raise SlitherError('Expression not handled: {}'.format(expression))
exit(-1)
self._post_visit(expression) self._post_visit(expression)
@ -200,8 +201,7 @@ class ExpressionVisitor:
pass pass
else: else:
logger.error('Expression not handled: {}'.format(expression)) raise SlitherError('Expression not handled: {}'.format(expression))
exit(-1)
# pre_expression_name # pre_expression_name
@ -302,8 +302,7 @@ class ExpressionVisitor:
pass pass
else: else:
logger.error('Expression not handled: {}'.format(expression)) raise SlitherError('Expression not handled: {}'.format(expression))
exit(-1)
# post_expression_name # post_expression_name

@ -17,8 +17,7 @@ from slither.slithir.variables import (Constant, ReferenceVariable,
TemporaryVariable, TupleVariable) TemporaryVariable, TupleVariable)
from slither.visitors.expression.expression import ExpressionVisitor from slither.visitors.expression.expression import ExpressionVisitor
#from slither.slithir.variables.state_variable import StateIRVariable from slither.slithir.exceptions import SlithIRError
#from slither.slithir.variables.local_variable import LocalIRVariable
logger = logging.getLogger("VISTIOR:ExpressionToSlithIR") logger = logging.getLogger("VISTIOR:ExpressionToSlithIR")
@ -57,8 +56,7 @@ def convert_assignment(left, right, t, return_type):
elif t == AssignmentOperationType.ASSIGN_MODULO: elif t == AssignmentOperationType.ASSIGN_MODULO:
return Binary(left, left, right, BinaryType.MODULO) return Binary(left, left, right, BinaryType.MODULO)
logger.error('Missing type during assignment conversion') raise SlithIRError('Missing type during assignment conversion')
exit(-1)
class ExpressionToSlithIR(ExpressionVisitor): class ExpressionToSlithIR(ExpressionVisitor):

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "arbitrary-send", "check": "arbitrary-send",
"impact": "High", "impact": "High",
@ -201,4 +204,5 @@
} }
] ]
} }
] ]
}

@ -6,4 +6,5 @@ Test.indirect (tests/arbitrary_send-0.5.1.sol#19-21) sends eth to arbitrary user
Dangerous calls: Dangerous calls:
- destination.send(address(this).balance) (tests/arbitrary_send-0.5.1.sol#20) - destination.send(address(this).balance) (tests/arbitrary_send-0.5.1.sol#20)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/arbitrary_send-0.5.1.arbitrary-send.json exists already, the overwrite is prevented
INFO:Slither:tests/arbitrary_send-0.5.1.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/arbitrary_send-0.5.1.sol analyzed (1 contracts), 2 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "arbitrary-send", "check": "arbitrary-send",
"impact": "High", "impact": "High",
@ -201,4 +204,5 @@
} }
] ]
} }
] ]
}

@ -6,4 +6,5 @@ Test.indirect (tests/arbitrary_send.sol#19-21) sends eth to arbitrary user
Dangerous calls: Dangerous calls:
- destination.send(address(this).balance) (tests/arbitrary_send.sol#20) - destination.send(address(this).balance) (tests/arbitrary_send.sol#20)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#functions-that-send-ether-to-arbitrary-destinations
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/arbitrary_send.arbitrary-send.json exists already, the overwrite is prevented
INFO:Slither:tests/arbitrary_send.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/arbitrary_send.sol analyzed (1 contracts), 2 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "backdoor", "check": "backdoor",
"impact": "High", "impact": "High",
@ -49,4 +52,5 @@
} }
] ]
} }
] ]
}

@ -1,5 +1,5 @@
INFO:Detectors: INFO:Detectors:
Backdoor function found in C.i_am_a_backdoor (tests/backdoor.sol#4-6) Backdoor function found in C.i_am_a_backdoor (tests/backdoor.sol#4-6)
Reference: https://github.com/trailofbits/slither/wiki/Adding-a-new-detector Reference: https://github.com/trailofbits/slither/wiki/Adding-a-new-detector
INFO:Slither:/home/monty/Private/tob/tools/slither-public/scripts/../tests/expected_json/backdoor.backdoor.json exists already, the overwrite is prevented INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/backdoor.backdoor.json exists already, the overwrite is prevented
INFO:Slither:tests/backdoor.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/backdoor.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "suicidal", "check": "suicidal",
"impact": "High", "impact": "High",
@ -49,4 +52,5 @@
} }
] ]
} }
] ]
}

@ -1,5 +1,5 @@
INFO:Detectors: INFO:Detectors:
C.i_am_a_backdoor (tests/backdoor.sol#4-6) allows anyone to destruct the contract C.i_am_a_backdoor (tests/backdoor.sol#4-6) allows anyone to destruct the contract
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#suicidal Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#suicidal
INFO:Slither:/home/monty/Private/tob/tools/slither-public/scripts/../tests/expected_json/backdoor.suicidal.json exists already, the overwrite is prevented INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/backdoor.suicidal.json exists already, the overwrite is prevented
INFO:Slither:tests/backdoor.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/backdoor.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "constable-states", "check": "constable-states",
"impact": "Informational", "impact": "Informational",
@ -109,4 +112,5 @@
} }
] ]
} }
] ]
}

@ -6,4 +6,5 @@ B.mySistersAddress should be constant (tests/const_state_variables.sol#26)
MyConc.should_be_constant should be constant (tests/const_state_variables.sol#42) MyConc.should_be_constant should be constant (tests/const_state_variables.sol#42)
MyConc.should_be_constant_2 should be constant (tests/const_state_variables.sol#43) MyConc.should_be_constant_2 should be constant (tests/const_state_variables.sol#43)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#state-variables-that-could-be-declared-constant
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/const_state_variables.constable-states.json exists already, the overwrite is prevented
INFO:Slither:tests/const_state_variables.sol analyzed (3 contracts), 1 result(s) found INFO:Slither:tests/const_state_variables.sol analyzed (3 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "constant-function", "check": "constant-function",
"impact": "Medium", "impact": "Medium",
@ -64,4 +67,5 @@
} }
] ]
} }
] ]
}

@ -1,4 +1,5 @@
INFO:Detectors: INFO:Detectors:
Constant.test_assembly_bug (tests/constant-0.5.1.sol#15-17) is declared view but contains assembly code Constant.test_assembly_bug (tests/constant-0.5.1.sol#15-17) is declared view but contains assembly code
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/constant-0.5.1.constant-function.json exists already, the overwrite is prevented
INFO:Slither:tests/constant-0.5.1.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/constant-0.5.1.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "constant-function", "check": "constant-function",
"impact": "Medium", "impact": "Medium",
@ -249,4 +252,5 @@
} }
] ]
} }
] ]
}

@ -5,4 +5,5 @@ Constant.test_constant_bug (tests/constant.sol#9-11) is declared view but change
- Constant.a - Constant.a
Constant.test_assembly_bug (tests/constant.sol#22-24) is declared view but contains assembly code Constant.test_assembly_bug (tests/constant.sol#22-24) is declared view but contains assembly code
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#constant-functions-changing-the-state
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/constant.constant-function.json exists already, the overwrite is prevented
INFO:Slither:tests/constant.sol analyzed (1 contracts), 3 result(s) found INFO:Slither:tests/constant.sol analyzed (1 contracts), 3 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "controlled-delegatecall", "check": "controlled-delegatecall",
"impact": "High", "impact": "High",
@ -170,4 +173,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ C.bad_delegate_call (tests/controlled_delegatecall.sol#8-11) uses delegatecall t
C.bad_delegate_call2 (tests/controlled_delegatecall.sol#18-20) uses delegatecall to a input-controlled function id C.bad_delegate_call2 (tests/controlled_delegatecall.sol#18-20) uses delegatecall to a input-controlled function id
addr_bad.delegatecall(abi.encode(func_id,data)) (tests/controlled_delegatecall.sol#19) addr_bad.delegatecall(abi.encode(func_id,data)) (tests/controlled_delegatecall.sol#19)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#controlled-delegatecall Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#controlled-delegatecall
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/controlled_delegatecall.controlled-delegatecall.json exists already, the overwrite is prevented
INFO:Slither:tests/controlled_delegatecall.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/controlled_delegatecall.sol analyzed (1 contracts), 2 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "deprecated-standards", "check": "deprecated-standards",
"impact": "Informational", "impact": "Informational",
@ -177,4 +180,5 @@
} }
] ]
} }
] ]
}

@ -14,4 +14,5 @@ Deprecated standard detected @ tests/deprecated_calls.sol#22:
Deprecated standard detected @ tests/deprecated_calls.sol#25: Deprecated standard detected @ tests/deprecated_calls.sol#25:
- Usage of "suicide()" should be replaced with "selfdestruct()" - Usage of "suicide()" should be replaced with "selfdestruct()"
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#deprecated-standards Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#deprecated-standards
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/deprecated_calls.deprecated-standards.json exists already, the overwrite is prevented
INFO:Slither:tests/deprecated_calls.sol analyzed (1 contracts), 7 result(s) found INFO:Slither:tests/deprecated_calls.sol analyzed (1 contracts), 7 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "erc20-indexed", "check": "erc20-indexed",
"impact": "Informational", "impact": "Informational",
@ -179,4 +182,5 @@
} }
] ]
} }
] ]
}

@ -5,4 +5,5 @@ IERC20Bad (tests/erc20_indexed.sol#12-21) does not mark important ERC20 paramete
-Approval (tests/erc20_indexed.sol#20) does not index parameter 'owner' -Approval (tests/erc20_indexed.sol#20) does not index parameter 'owner'
-Approval (tests/erc20_indexed.sol#20) does not index parameter 'spender' -Approval (tests/erc20_indexed.sol#20) does not index parameter 'spender'
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unindexed-erc20-event-parameters Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#unindexed-erc20-event-parameters
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/erc20_indexed.erc20-indexed.json exists already, the overwrite is prevented
INFO:Slither:tests/erc20_indexed.sol analyzed (3 contracts), 1 result(s) found INFO:Slither:tests/erc20_indexed.sol analyzed (3 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "external-function", "check": "external-function",
"impact": "Informational", "impact": "Informational",
@ -243,4 +246,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ ContractWithFunctionNotCalled.funcNotCalled2 (tests/external_function.sol#17-19)
ContractWithFunctionNotCalled.funcNotCalled (tests/external_function.sol#21-23) should be declared external ContractWithFunctionNotCalled.funcNotCalled (tests/external_function.sol#21-23) should be declared external
ContractWithFunctionNotCalled2.funcNotCalled (tests/external_function.sol#32-39) should be declared external ContractWithFunctionNotCalled2.funcNotCalled (tests/external_function.sol#32-39) should be declared external
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-as-external Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#public-function-that-could-be-declared-as-external
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/external_function.external-function.json exists already, the overwrite is prevented
INFO:Slither:tests/external_function.sol analyzed (5 contracts), 4 result(s) found INFO:Slither:tests/external_function.sol analyzed (5 contracts), 4 result(s) found

@ -1 +1,5 @@
[] {
"success": true,
"error": null,
"results": []
}

@ -1 +1,2 @@
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/external_function_2.external-function.json exists already, the overwrite is prevented
INFO:Slither:tests/external_function_2.sol analyzed (4 contracts), 0 result(s) found INFO:Slither:tests/external_function_2.sol analyzed (4 contracts), 0 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "incorrect-equality", "check": "incorrect-equality",
"impact": "Medium", "impact": "Medium",
@ -1363,4 +1366,5 @@
} }
] ]
} }
] ]
}

@ -74,4 +74,5 @@ TestSolidityKeyword.bad1 (tests/incorrect_equality.sol#127-129) uses a dangerous
TestSolidityKeyword.bad2 (tests/incorrect_equality.sol#131-133) uses a dangerous strict equality: TestSolidityKeyword.bad2 (tests/incorrect_equality.sol#131-133) uses a dangerous strict equality:
- require(bool)(block.number == 0) - require(bool)(block.number == 0)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-strict-equalities Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#dangerous-strict-equalities
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/incorrect_equality.incorrect-equality.json exists already, the overwrite is prevented
INFO:Slither:tests/incorrect_equality.sol analyzed (5 contracts), 12 result(s) found INFO:Slither:tests/incorrect_equality.sol analyzed (5 contracts), 12 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "erc20-interface", "check": "erc20-interface",
"impact": "Medium", "impact": "Medium",
@ -253,4 +256,5 @@
} }
] ]
} }
] ]
}

@ -7,4 +7,5 @@ Token (tests/incorrect_erc20_interface.sol#3-10) has incorrect ERC20 function in
-balanceOf (tests/incorrect_erc20_interface.sol#8) -balanceOf (tests/incorrect_erc20_interface.sol#8)
-allowance (tests/incorrect_erc20_interface.sol#9) -allowance (tests/incorrect_erc20_interface.sol#9)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc20-interface Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc20-interface
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/incorrect_erc20_interface.erc20-interface.json exists already, the overwrite is prevented
INFO:Slither:tests/incorrect_erc20_interface.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/incorrect_erc20_interface.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "erc721-interface", "check": "erc721-interface",
"impact": "Medium", "impact": "Medium",
@ -439,4 +442,5 @@
} }
] ]
} }
] ]
}

@ -11,4 +11,5 @@ Token (tests/incorrect_erc721_interface.sol#6-16) has incorrect ERC721 function
-getApproved (tests/incorrect_erc721_interface.sol#14) -getApproved (tests/incorrect_erc721_interface.sol#14)
-isApprovedForAll (tests/incorrect_erc721_interface.sol#15) -isApprovedForAll (tests/incorrect_erc721_interface.sol#15)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc721-interface Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-erc721-interface
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/incorrect_erc721_interface.erc721-interface.json exists already, the overwrite is prevented
INFO:Slither:tests/incorrect_erc721_interface.sol analyzed (2 contracts), 1 result(s) found INFO:Slither:tests/incorrect_erc721_interface.sol analyzed (2 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "assembly", "check": "assembly",
"impact": "Informational", "impact": "Informational",
@ -101,4 +104,5 @@
} }
] ]
} }
] ]
}

@ -2,4 +2,5 @@ INFO:Detectors:
GetCode.at uses assembly (tests/inline_assembly_contract-0.5.1.sol#6-20) GetCode.at uses assembly (tests/inline_assembly_contract-0.5.1.sol#6-20)
- tests/inline_assembly_contract-0.5.1.sol#7-20 - tests/inline_assembly_contract-0.5.1.sol#7-20
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/inline_assembly_contract-0.5.1.assembly.json exists already, the overwrite is prevented
INFO:Slither:tests/inline_assembly_contract-0.5.1.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/inline_assembly_contract-0.5.1.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "assembly", "check": "assembly",
"impact": "Informational", "impact": "Informational",
@ -101,4 +104,5 @@
} }
] ]
} }
] ]
}

@ -2,4 +2,5 @@ INFO:Detectors:
GetCode.at uses assembly (tests/inline_assembly_contract.sol#6-20) GetCode.at uses assembly (tests/inline_assembly_contract.sol#6-20)
- tests/inline_assembly_contract.sol#7-20 - tests/inline_assembly_contract.sol#7-20
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/inline_assembly_contract.assembly.json exists already, the overwrite is prevented
INFO:Slither:tests/inline_assembly_contract.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/inline_assembly_contract.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "assembly", "check": "assembly",
"impact": "Informational", "impact": "Informational",
@ -255,4 +258,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ VectorSum.sumAsm uses assembly (tests/inline_assembly_library-0.5.1.sol#16-22)
VectorSum.sumPureAsm uses assembly (tests/inline_assembly_library-0.5.1.sol#25-47) VectorSum.sumPureAsm uses assembly (tests/inline_assembly_library-0.5.1.sol#25-47)
- tests/inline_assembly_library-0.5.1.sol#26-47 - tests/inline_assembly_library-0.5.1.sol#26-47
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/inline_assembly_library-0.5.1.assembly.json exists already, the overwrite is prevented
INFO:Slither:tests/inline_assembly_library-0.5.1.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/inline_assembly_library-0.5.1.sol analyzed (1 contracts), 2 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "assembly", "check": "assembly",
"impact": "Informational", "impact": "Informational",
@ -255,4 +258,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ VectorSum.sumAsm uses assembly (tests/inline_assembly_library.sol#16-22)
VectorSum.sumPureAsm uses assembly (tests/inline_assembly_library.sol#25-47) VectorSum.sumPureAsm uses assembly (tests/inline_assembly_library.sol#25-47)
- tests/inline_assembly_library.sol#26-47 - tests/inline_assembly_library.sol#26-47
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#assembly-usage
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/inline_assembly_library.assembly.json exists already, the overwrite is prevented
INFO:Slither:tests/inline_assembly_library.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/inline_assembly_library.sol analyzed (1 contracts), 2 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "locked-ether", "check": "locked-ether",
"impact": "Medium", "impact": "Medium",
@ -66,4 +69,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ Contract locking ether found in :
- receive (tests/locked_ether-0.5.1.sol#4-6) - receive (tests/locked_ether-0.5.1.sol#4-6)
But does not have a function to withdraw the ether But does not have a function to withdraw the ether
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/locked_ether-0.5.1.locked-ether.json exists already, the overwrite is prevented
INFO:Slither:tests/locked_ether-0.5.1.sol analyzed (4 contracts), 1 result(s) found INFO:Slither:tests/locked_ether-0.5.1.sol analyzed (4 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "locked-ether", "check": "locked-ether",
"impact": "Medium", "impact": "Medium",
@ -66,4 +69,5 @@
} }
] ]
} }
] ]
}

@ -4,4 +4,5 @@ Contract locking ether found in :
- receive (tests/locked_ether.sol#4-6) - receive (tests/locked_ether.sol#4-6)
But does not have a function to withdraw the ether But does not have a function to withdraw the ether
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#contracts-that-lock-ether
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/locked_ether.locked-ether.json exists already, the overwrite is prevented
INFO:Slither:tests/locked_ether.sol analyzed (4 contracts), 1 result(s) found INFO:Slither:tests/locked_ether.sol analyzed (4 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "low-level-calls", "check": "low-level-calls",
"impact": "Informational", "impact": "Informational",
@ -64,4 +67,5 @@
} }
] ]
} }
] ]
}

@ -2,4 +2,5 @@ INFO:Detectors:
Low level call in Sender.send (tests/low_level_calls.sol#5-7): Low level call in Sender.send (tests/low_level_calls.sol#5-7):
-_receiver.call.value(msg.value).gas(7777)() tests/low_level_calls.sol#6 -_receiver.call.value(msg.value).gas(7777)() tests/low_level_calls.sol#6
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#low-level-calls Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#low-level-calls
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/low_level_calls.low-level-calls.json exists already, the overwrite is prevented
INFO:Slither:tests/low_level_calls.sol analyzed (2 contracts), 1 result(s) found INFO:Slither:tests/low_level_calls.sol analyzed (2 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "calls-loop", "check": "calls-loop",
"impact": "Low", "impact": "Low",
@ -76,4 +79,5 @@
} }
] ]
} }
] ]
}

@ -2,4 +2,5 @@ INFO:Detectors:
CallInLoop.bad has external calls inside a loop: CallInLoop.bad has external calls inside a loop:
- destinations[i].transfer(i) (tests/multiple_calls_in_loop.sol#11) - destinations[i].transfer(i) (tests/multiple_calls_in_loop.sol#11)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation/_edit#calls-inside-a-loop Reference: https://github.com/crytic/slither/wiki/Detector-Documentation/_edit#calls-inside-a-loop
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/multiple_calls_in_loop.calls-loop.json exists already, the overwrite is prevented
INFO:Slither:tests/multiple_calls_in_loop.sol analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/multiple_calls_in_loop.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "naming-convention", "check": "naming-convention",
"impact": "Informational", "impact": "Informational",
@ -363,4 +366,5 @@
} }
] ]
} }
] ]
}

@ -12,4 +12,5 @@ Parameter '_used' of T.test (tests/naming_convention.sol#59) is not in mixedCase
Variable 'T._myPublicVar' (tests/naming_convention.sol#56) is not in mixedCase Variable 'T._myPublicVar' (tests/naming_convention.sol#56) is not in mixedCase
Variable 'T.l' (tests/naming_convention.sol#67) used l, O, I, which should not be used Variable 'T.l' (tests/naming_convention.sol#67) used l, O, I, which should not be used
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#conformance-to-solidity-naming-conventions
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/naming_convention.naming-convention.json exists already, the overwrite is prevented
INFO:Slither:tests/naming_convention.sol analyzed (3 contracts), 12 result(s) found INFO:Slither:tests/naming_convention.sol analyzed (3 contracts), 12 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "solc-version", "check": "solc-version",
"impact": "Informational", "impact": "Informational",
@ -22,4 +25,5 @@
} }
] ]
} }
] ]
}

@ -2,5 +2,5 @@ INFO:Detectors:
Detected issues with version pragma in tests/old_solc.sol.json: Detected issues with version pragma in tests/old_solc.sol.json:
- pragma solidity0.4.21 (None): it allows old versions - pragma solidity0.4.21 (None): it allows old versions
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-version-of-solidity Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#incorrect-version-of-solidity
INFO:Slither:/home/monty/Private/tob/tools/slither-public/scripts/../tests/expected_json/old_solc.sol.json.solc-version.json exists already, the overwrite is prevented INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/old_solc.sol.json.solc-version.json exists already, the overwrite is prevented
INFO:Slither:tests/old_solc.sol.json analyzed (1 contracts), 1 result(s) found INFO:Slither:tests/old_solc.sol.json analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "pragma", "check": "pragma",
"impact": "Informational", "impact": "Informational",
@ -41,4 +44,5 @@
} }
] ]
} }
] ]
}

@ -1,8 +1,8 @@
ERROR:Slither:Invalid compilation INFO:Detectors:
ERROR:Slither:Invalid solc compilation tests/pragma.0.4.23.sol:1:1: Error: Source file requires different compiler version (current compiler is 0.5.1+commit.c8a2cb62.Linux.g++ - note that nightly builds are considered to be strictly less than the released version Different versions of Solidity is used in :
pragma solidity ^0.4.23; - Version used: ['^0.4.23', '^0.4.24']
^----------------------^ - tests/pragma.0.4.23.sol#1 declares pragma solidity^0.4.23
tests/pragma.0.4.24.sol:1:1: Error: Source file requires different compiler version (current compiler is 0.5.1+commit.c8a2cb62.Linux.g++ - note that nightly builds are considered to be strictly less than the released version - tests/pragma.0.4.24.sol#1 declares pragma solidity^0.4.24
pragma solidity ^0.4.24; Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#different-pragma-directives-are-used
^----------------------^ INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/pragma.0.4.24.pragma.json exists already, the overwrite is prevented
INFO:Slither:tests/pragma.0.4.24.sol analyzed (1 contracts), 1 result(s) found

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "reentrancy-eth", "check": "reentrancy-eth",
"impact": "High", "impact": "High",
@ -272,4 +275,5 @@
} }
] ]
} }
] ]
}

@ -10,4 +10,5 @@ Reentrancy in Reentrancy.withdrawBalance_fixed_3 (tests/reentrancy-0.5.1.sol#44-
State variables written after the call(s): State variables written after the call(s):
- userBalance (tests/reentrancy-0.5.1.sol#51) - userBalance (tests/reentrancy-0.5.1.sol#51)
Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities Reference: https://github.com/crytic/slither/wiki/Detector-Documentation#reentrancy-vulnerabilities
INFO:Slither:/home/travis/build/crytic/slither/scripts/../tests/expected_json/reentrancy-0.5.1.reentrancy-eth.json exists already, the overwrite is prevented
INFO:Slither:tests/reentrancy-0.5.1.sol analyzed (1 contracts), 2 result(s) found INFO:Slither:tests/reentrancy-0.5.1.sol analyzed (1 contracts), 2 result(s) found

@ -1,10 +0,0 @@
Traceback (most recent call last):
File "/home/monty/Envs/slither/bin/slither", line 11, in <module>
load_entry_point('slither-analyzer', 'console_scripts', 'slither')()
File "/home/monty/Private/tob/tools/slither-public/slither/__main__.py", line 469, in main
main_impl(all_detector_classes=detectors, all_printer_classes=printers)
File "/home/monty/Private/tob/tools/slither-public/slither/__main__.py", line 483, in main_impl
detector_classes = choose_detectors(args, all_detector_classes)
File "/home/monty/Private/tob/tools/slither-public/slither/__main__.py", line 176, in choose_detectors
raise Exception('Error: {} is not a detector'.format(d))
Exception: Error: reentrancy is not a detector

@ -1,4 +1,7 @@
[ {
"success": true,
"error": null,
"results": [
{ {
"check": "reentrancy-eth", "check": "reentrancy-eth",
"impact": "High", "impact": "High",
@ -306,4 +309,5 @@
} }
] ]
} }
] ]
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save