Beispiel #1
0
 def __init__(self, request, response):
     # Initialize the jinja environment
     self.jinja_environment = jinja2.Environment(
         autoescape=True,
         loader=jinja2.FileSystemLoader(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../views'))
     )
     # Initialize logger
     utils.initialize_logger()
     self.auth = auth.get_auth()
     # If not logged in, the dispatch() call will redirect to /login if needed
     if self.logged_in():
         # Make sure a handler has a reference to the current user
         user_dict = self.auth.get_user_by_session()
         self.user = self.auth.store.user_model.get_by_id(user_dict['user_id'])
     #
     webapp2.RequestHandler.__init__(self, request, response)
Beispiel #2
0
 def __init__(self, eth_node_ip=None, eth_node_port=None) -> None:
     chain_class = Chain.configure(
         __name__='Blockchain',
         vm_configuration=(
             (constants.GENESIS_BLOCK_NUMBER, FrontierVMForFuzzTesting),
             (HOMESTEAD_MAINNET_BLOCK, HomesteadVMForFuzzTesting),
             (TANGERINE_WHISTLE_MAINNET_BLOCK, TangerineWhistleVMForFuzzTesting),
             (SPURIOUS_DRAGON_MAINNET_BLOCK, SpuriousDragonVMForFuzzTesting),
             (BYZANTIUM_MAINNET_BLOCK, ByzantiumVMForFuzzTesting),
             (PETERSBURG_MAINNET_BLOCK, PetersburgVMForFuzzTesting),
         ),
     )
     class MyMemoryDB(MemoryDB):
         def __init__(self) -> None:
             self.kv_store = {'storage': dict(), 'account': dict(), 'code': dict()}
         def rst(self) -> None:
             self.kv_store = {'storage': dict(), 'account': dict(), 'code': dict()}
     if eth_node_ip and eth_node_port and settings.REMOTE_FUZZING:
         self.w3 = Web3(HTTPProvider('http://%s:%s' % (eth_node_ip, eth_node_port)))
     else:
         self.w3 = None
     self.chain = chain_class.from_genesis_header(AtomicDB(MyMemoryDB()), MAINNET_GENESIS_HEADER)
     self.logger = initialize_logger("EVM")
     self.accounts = list()
     self.snapshot = None
     self.vm = None
Beispiel #3
0
    def __init__(self,
                 contract_name,
                 abi,
                 deployment_bytecode,
                 runtime_bytecode,
                 test_instrumented_evm,
                 blockchain_state,
                 solver,
                 args,
                 seed,
                 source_map=None):
        global logger

        logger = initialize_logger("Fuzzer  ")
        logger.title("Fuzzing contract %s", contract_name)

        cfg = ControlFlowGraph()
        cfg.build(runtime_bytecode, settings.EVM_VERSION)

        self.contract_name = contract_name
        self.interface = get_interface_from_abi(abi)
        self.deployement_bytecode = deployment_bytecode
        self.blockchain_state = blockchain_state
        self.instrumented_evm = test_instrumented_evm
        self.solver = solver
        self.args = args

        # Get some overall metric on the code
        self.overall_pcs, self.overall_jumpis = get_pcs_and_jumpis(
            runtime_bytecode)

        # Initialize results
        self.results = {"errors": {}}

        # Initialize fuzzing environment
        self.env = FuzzingEnvironment(
            instrumented_evm=self.instrumented_evm,
            contract_name=self.contract_name,
            solver=self.solver,
            results=self.results,
            symbolic_taint_analyzer=SymbolicTaintAnalyzer(),
            detector_executor=DetectorExecutor(
                source_map, get_function_signature_mapping(abi)),
            interface=self.interface,
            overall_pcs=self.overall_pcs,
            overall_jumpis=self.overall_jumpis,
            len_overall_pcs_with_children=0,
            other_contracts=list(),
            args=args,
            seed=seed,
            cfg=cfg,
            abi=abi)
Beispiel #4
0
    def __init__(self, source_map=None, function_signature_mapping={}):
        self.source_map = source_map
        self.function_signature_mapping = function_signature_mapping
        self.logger = initialize_logger("Detector")

        self.integer_overflow_detector = IntegerOverflowDetector()
        self.assertion_failure_detector = AssertionFailureDetector()
        self.arbitrary_memory_access_detector = ArbitraryMemoryAccessDetector()
        self.reentrancy_detector = ReentrancyDetector()
        self.transaction_order_dependency_detector = TransactionOrderDependencyDetector(
        )
        self.block_dependency_detector = BlockDependencyDetector()
        self.unhandled_exception_detector = UnhandledExceptionDetector()
        self.unsafe_delegatecall_detector = UnsafeDelegatecallDetector()
        self.leaking_ether_detector = LeakingEtherDetector()
        self.locking_ether_detector = LockingEtherDetector()
        self.unprotected_selfdestruct_detector = UnprotectedSelfdestructDetector(
        )
Beispiel #5
0
def main():
    print_logo()
    args = launch_argument_parser()

    logger = initialize_logger("Main    ")

    # Check if contract has already been analyzed
    if args.results and os.path.exists(args.results):
        os.remove(args.results)
        print("delteed file")
    #    logger.info("Contract "+str(args.source)+" has already been analyzed: "+str(args.results))
    #    sys.exit(0)

    # Initializing random
    if args.seed:
        seed = args.seed
        if not "PYTHONHASHSEED" in os.environ:
            logger.debug(
                "Please set PYTHONHASHSEED to '1' for Python's hash function to behave deterministically."
            )
    else:
        seed = random.random()
    random.seed(seed)
    logger.title("Initializing seed to %s", seed)

    # Initialize EVM
    instrumented_evm = InstrumentedEVM(settings.RPC_HOST, settings.RPC_PORT)
    instrumented_evm.set_vm_by_name(settings.EVM_VERSION)

    # Create Z3 solver instance
    solver = Solver()
    solver.set("timeout", settings.SOLVER_TIMEOUT)

    # Parse blockchain state if provided
    blockchain_state = []
    if args.blockchain_state:
        if args.blockchain_state.endswith(".json"):
            with open(args.blockchain_state) as json_file:
                for line in json_file.readlines():
                    blockchain_state.append(json.loads(line))
        elif args.blockchain_state.isnumeric():
            settings.BLOCK_HEIGHT = int(args.blockchain_state)
            instrumented_evm.set_vm(settings.BLOCK_HEIGHT)
        else:
            logger.error("Unsupported input file: " + args.blockchain_state)
            sys.exit(-1)

    # Compile source code to get deployment bytecode, runtime bytecode and ABI
    if args.source:
        if args.source.endswith(".sol"):
            compiler_output = compile(args.solc_version, settings.EVM_VERSION,
                                      args.source)
            if not compiler_output:
                logger.error("No compiler output for: " + args.source)
                sys.exit(-1)
            for contract_name, contract in compiler_output['contracts'][
                    args.source].items():
                if args.contract and contract_name != args.contract:
                    continue
                if contract['abi'] and contract['evm']['bytecode'][
                        'object'] and contract['evm']['deployedBytecode'][
                            'object']:
                    source_map = SourceMap(
                        ':'.join([args.source, contract_name]),
                        compiler_output)
                    Fuzzer(contract_name, contract["abi"],
                           contract['evm']['bytecode']['object'],
                           contract['evm']['deployedBytecode']['object'],
                           instrumented_evm, blockchain_state, solver, args,
                           seed, source_map).run()
        else:
            logger.error("Unsupported input file: " + args.source)
            sys.exit(-1)

    if args.abi:
        with open(args.abi) as json_file:
            abi = json.load(json_file)
            runtime_bytecode = instrumented_evm.get_code(
                to_canonical_address(args.contract)).hex()
            Fuzzer(args.contract, abi, None, runtime_bytecode,
                   instrumented_evm, blockchain_state, solver, args,
                   seed).run()
Beispiel #6
0
 def __init__(self, generator):
     self.logger = initialize_logger("Individual")
     self.chromosome = []
     self.solution = []
     self.generator = generator