├── .gitignore ├── AUTHORS ├── LICENSE ├── README.md ├── bjoern-server.sh ├── build.gradle ├── conf └── logback.xml ├── docs ├── Makefile ├── make.bat └── source │ ├── conf.py │ ├── csvimport.rst │ ├── dbcontents.rst │ ├── firststeps.rst │ ├── gremlinshell.rst │ ├── index.rst │ ├── installation.rst │ ├── overview.rst │ └── plugins.rst ├── integrationTest ├── build.gradle └── test │ └── src │ ├── java │ └── IntegrationTestClass.java │ └── resources │ ├── edges.csv │ └── nodes.csv ├── projects ├── bjoern-lang │ ├── build.gradle │ └── src │ │ └── main │ │ └── groovy │ │ ├── controlflow.groovy │ │ ├── dataflow.groovy │ │ ├── lookup.groovy │ │ └── structure.groovy ├── bjoern-pluginlib │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── bjoern │ │ └── pluginlib │ │ ├── BjoernConstants.java │ │ ├── BjoernProject.java │ │ ├── LookupOperations.java │ │ ├── Traversals.java │ │ ├── connectors │ │ └── BjoernProjectConnector.java │ │ ├── plugintypes │ │ ├── BjoernProjectPlugin.java │ │ ├── RadareOrientGraphPlugin.java │ │ └── RadareProjectPlugin.java │ │ ├── radare │ │ └── emulation │ │ │ ├── ESILEmulator.java │ │ │ └── esil │ │ │ ├── ESILKeyword.java │ │ │ ├── ESILTokenEvaluator.java │ │ │ ├── ESILTokenStream.java │ │ │ └── memaccess │ │ │ ├── ESILAccessParser.java │ │ │ ├── ESILStackAccessEvaluator.java │ │ │ ├── MemoryAccess.java │ │ │ └── StackState.java │ │ └── structures │ │ ├── Aloc.java │ │ ├── BasicBlock.java │ │ ├── BjoernEdge.java │ │ ├── BjoernEdgeIterable.java │ │ ├── BjoernGraph.java │ │ ├── BjoernNode.java │ │ ├── BjoernNodeFactory.java │ │ ├── BjoernVertexIterable.java │ │ ├── Function.java │ │ └── Instruction.java ├── bjoern-plugins │ ├── alocs │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── alocs │ │ │ ├── AlocPlugin.java │ │ │ ├── AlocTypes.java │ │ │ └── FunctionAlocCreator.java │ ├── datadependence │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── datadependence │ │ │ ├── DataDependenceCreator.java │ │ │ ├── DataDependencePlugin.java │ │ │ └── ReachingDefinitionAnalyser.java │ ├── functionexport │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── functionexporter │ │ │ ├── FunctionExportPlugin.java │ │ │ └── io │ │ │ └── dot │ │ │ ├── DotTokens.java │ │ │ └── DotWriter.java │ ├── instructionlinker │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── instructionlinker │ │ │ └── InstructionLinkerPlugin.java │ ├── paramdetect │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── paramdetect │ │ │ └── ParamDetectPlugin.java │ ├── radareimporter │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── radareimporter │ │ │ ├── BlueprintsOutputModule.java │ │ │ └── RadareImporterPlugin.java │ ├── usedefanalyser │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── usedefanalyser │ │ │ ├── UseDefAnalyser.java │ │ │ └── UseDefAnalyserPlugin.java │ └── vsa │ │ ├── build.gradle │ │ └── src │ │ ├── main │ │ └── java │ │ │ └── bjoern │ │ │ └── plugins │ │ │ └── vsa │ │ │ ├── VSA.java │ │ │ ├── VSAPlugin.java │ │ │ ├── data │ │ │ ├── DataObject.java │ │ │ ├── DataObjectObserver.java │ │ │ ├── Flag.java │ │ │ ├── GenericDataObject.java │ │ │ ├── ObservableDataObject.java │ │ │ └── Register.java │ │ │ ├── domain │ │ │ ├── AbstractEnvironment.java │ │ │ ├── ValueSet.java │ │ │ └── memrgn │ │ │ │ ├── GlobalRegion.java │ │ │ │ ├── HeapRegion.java │ │ │ │ ├── LocalRegion.java │ │ │ │ └── MemoryRegion.java │ │ │ ├── structures │ │ │ ├── Bool3.java │ │ │ ├── DataWidth.java │ │ │ ├── StridedInterval.java │ │ │ ├── StridedInterval1Bit.java │ │ │ └── StridedInterval64Bit.java │ │ │ └── transformer │ │ │ ├── ESILTransformer.java │ │ │ ├── Transformer.java │ │ │ └── esil │ │ │ ├── ESILTransformationException.java │ │ │ ├── commands │ │ │ ├── AddAssignCommand.java │ │ │ ├── AddCommand.java │ │ │ ├── AndAssignCommand.java │ │ │ ├── AndCommand.java │ │ │ ├── ArithmeticCommand.java │ │ │ ├── AssignmentCommand.java │ │ │ ├── BitArithmeticCommand.java │ │ │ ├── CompoundAssignCommand.java │ │ │ ├── ConditionalCommand.java │ │ │ ├── DecAssignCommand.java │ │ │ ├── DecCommand.java │ │ │ ├── DivAssignCommand.java │ │ │ ├── DivCommand.java │ │ │ ├── ESILCommand.java │ │ │ ├── ESILCommandFactory.java │ │ │ ├── ESILCommandObserver.java │ │ │ ├── IncAssignCommand.java │ │ │ ├── IncCommand.java │ │ │ ├── ModAssignCommand.java │ │ │ ├── ModCommand.java │ │ │ ├── MulAssignCommand.java │ │ │ ├── MulCommand.java │ │ │ ├── NegAssignCommand.java │ │ │ ├── NegateCommand.java │ │ │ ├── ObservableESILCommand.java │ │ │ ├── OrAssignCommand.java │ │ │ ├── OrCommand.java │ │ │ ├── PeekCommand.java │ │ │ ├── PokeCommand.java │ │ │ ├── PopCommand.java │ │ │ ├── RelationalCommand.java │ │ │ ├── RotateLeftCommand.java │ │ │ ├── RotateRightCommand.java │ │ │ ├── ShiftLeftAssignCommand.java │ │ │ ├── ShiftLeftCommand.java │ │ │ ├── ShiftRightAssignCommand.java │ │ │ ├── ShiftRightCommand.java │ │ │ ├── SubAssignCommand.java │ │ │ ├── SubCommand.java │ │ │ ├── XorAssignCommand.java │ │ │ └── XorCommand.java │ │ │ └── stack │ │ │ ├── ESILStack.java │ │ │ ├── ESILStackItem.java │ │ │ ├── FlagContainer.java │ │ │ ├── RegisterContainer.java │ │ │ └── ValueSetContainer.java │ │ └── test │ │ └── java │ │ └── bjoern │ │ └── plugins │ │ └── vsa │ │ └── structures │ │ ├── ArithmeticTests.java │ │ ├── BitArithmeticTests.java │ │ └── SetOperationTests.java ├── bjoern-r2interface │ ├── build.gradle │ └── src │ │ └── main │ │ └── java │ │ └── bjoern │ │ ├── r2interface │ │ ├── R2Pipe.java │ │ ├── Radare.java │ │ ├── StreamGobbler.java │ │ ├── architectures │ │ │ ├── Architecture.java │ │ │ ├── UnknownArchitectureException.java │ │ │ └── X64Architecture.java │ │ ├── creators │ │ │ ├── JSONUtils.java │ │ │ ├── RadareBasicBlockCreator.java │ │ │ ├── RadareCallRefCreator.java │ │ │ ├── RadareFlagCreator.java │ │ │ ├── RadareFunctionContentCreator.java │ │ │ ├── RadareFunctionCreator.java │ │ │ └── RadareInstructionCreator.java │ │ └── exceptions │ │ │ ├── BasicBlockWithoutAddress.java │ │ │ ├── EmptyDisassembly.java │ │ │ ├── InvalidDisassembly.java │ │ │ └── InvalidRadareFunctionException.java │ │ └── structures │ │ ├── BjoernEdgeProperties.java │ │ ├── BjoernNodeProperties.java │ │ ├── BjoernNodeTypes.java │ │ ├── Node.java │ │ ├── NodeKey.java │ │ ├── RegisterFamily.java │ │ ├── RootNode.java │ │ ├── annotations │ │ └── Flag.java │ │ ├── edges │ │ ├── CallRef.java │ │ ├── ControlFlowEdge.java │ │ ├── DirectedEdge.java │ │ ├── EdgeTypes.java │ │ └── Reference.java │ │ └── interpretations │ │ ├── BasicBlock.java │ │ ├── Function.java │ │ ├── FunctionContent.java │ │ └── Instruction.java ├── octopus │ ├── .gitrepo │ ├── AUTHORS │ ├── LICENSE │ ├── octopus-lang │ │ ├── build.gradle │ │ └── src │ │ │ └── main │ │ │ └── groovy │ │ │ ├── exampleStep.groovy │ │ │ └── lookup.groovy │ ├── octopus-server │ │ ├── AUTHORS │ │ ├── LICENSE │ │ ├── build.gradle │ │ ├── conf │ │ │ └── orientdb-server-config.xml │ │ ├── octopus-server.sh │ │ └── src │ │ │ └── main │ │ │ ├── java │ │ │ └── octopus │ │ │ │ ├── OctopusMain.java │ │ │ │ ├── lib │ │ │ │ ├── GraphOperations.java │ │ │ │ ├── OctopusProjectWrapper.java │ │ │ │ ├── connectors │ │ │ │ │ ├── OctopusProjectConnector.java │ │ │ │ │ └── OrientDBConnector.java │ │ │ │ ├── plugintypes │ │ │ │ │ ├── OctopusProjectPlugin.java │ │ │ │ │ └── OrientGraphConnectionPlugin.java │ │ │ │ └── structures │ │ │ │ │ ├── OctopusNode.java │ │ │ │ │ └── OctopusNodeProperties.java │ │ │ │ └── server │ │ │ │ ├── Constants.java │ │ │ │ ├── commands │ │ │ │ ├── executeplugin │ │ │ │ │ └── ExecutePluginCommand.java │ │ │ │ ├── importcsv │ │ │ │ │ └── ImportCSVHandler.java │ │ │ │ ├── manageprojects │ │ │ │ │ └── ManageProjectsHandler.java │ │ │ │ └── manageshells │ │ │ │ │ └── ManageShellsHandler.java │ │ │ │ └── components │ │ │ │ ├── ftpserver │ │ │ │ └── OctopusFTPServer.java │ │ │ │ ├── gremlinShell │ │ │ │ ├── GroovyFileLoader.java │ │ │ │ ├── OctopusCompilerConfiguration.java │ │ │ │ ├── OctopusGremlinShell.java │ │ │ │ ├── OctopusScriptBase.java │ │ │ │ ├── ShellRunnable.java │ │ │ │ ├── fileWalker │ │ │ │ │ ├── FileNameMatcher.java │ │ │ │ │ ├── OrderedWalker.java │ │ │ │ │ ├── SourceFileListener.java │ │ │ │ │ ├── SourceFileWalker.java │ │ │ │ │ ├── UnorderedFileWalkerImpl.java │ │ │ │ │ └── UnorderedWalker.java │ │ │ │ └── io │ │ │ │ │ ├── BjoernClientReader.java │ │ │ │ │ └── BjoernClientWriter.java │ │ │ │ ├── orientdbImporter │ │ │ │ ├── ImportCSVRunnable.java │ │ │ │ └── ImportJob.java │ │ │ │ ├── pluginInterface │ │ │ │ ├── Plugin.java │ │ │ │ ├── PluginClassLoader.java │ │ │ │ └── PluginLoader.java │ │ │ │ ├── projectmanager │ │ │ │ ├── OctopusProject.java │ │ │ │ └── ProjectManager.java │ │ │ │ └── shellmanager │ │ │ │ └── ShellManager.java │ │ │ └── resources │ │ │ └── logback.xml │ └── orientdbimporter │ │ ├── AUTHORS │ │ ├── LICENSE │ │ ├── build.gradle │ │ └── src │ │ └── main │ │ └── java │ │ └── orientdbimporter │ │ ├── CSVBatchImporter.java │ │ ├── CSVCommands.java │ │ ├── CSVImporter.java │ │ ├── Constants.java │ │ └── processors │ │ ├── CSVFileProcessor.java │ │ ├── EdgeProcessor.java │ │ └── NodeProcessor.java └── radare2csv │ ├── AUTHORS │ ├── LICENSE │ ├── build.gradle │ ├── radare2csv.sh │ └── src │ └── main │ ├── java │ └── bjoern │ │ └── input │ │ ├── common │ │ ├── Exporter.java │ │ ├── InputModule.java │ │ └── outputModules │ │ │ ├── CSV │ │ │ ├── CSVOutputModule.java │ │ │ └── CSVWriter.java │ │ │ └── OutputModule.java │ │ └── radare │ │ ├── CommandLineInterface.java │ │ ├── CommonCommandLineInterface.java │ │ ├── RadareExporter.java │ │ ├── RadareExporterMain.java │ │ └── inputModule │ │ └── RadareInputModule.java │ └── resources │ └── logback.xml ├── python ├── bjoern-tools │ ├── .gitignore │ ├── .gitrepo │ ├── AUTHORS │ ├── LICENSE │ ├── bjoern │ │ ├── __init__.py │ │ ├── plugins │ │ │ ├── __init__.py │ │ │ ├── alocs.py │ │ │ ├── data_dependence.py │ │ │ ├── function_exporter.py │ │ │ ├── instruction_linker.py │ │ │ ├── use_def_analyser.py │ │ │ └── vsa.py │ │ └── shell │ │ │ ├── __init__.py │ │ │ ├── bjoern_console.py │ │ │ ├── config │ │ │ ├── __init__.py │ │ │ ├── config.py │ │ │ └── data │ │ │ │ └── bjosh.ini │ │ │ └── data │ │ │ └── bjosh_banner.txt │ ├── scripts │ │ ├── bjoern-alocs │ │ ├── bjoern-ddg │ │ ├── bjoern-functionexport │ │ ├── bjoern-import │ │ ├── bjoern-instructionlinker │ │ ├── bjoern-vsa │ │ └── bjosh │ └── setup.py └── octopus-tools │ ├── .gitignore │ ├── .gitrepo │ ├── AUTHORS │ ├── LICENSE │ ├── octopus │ ├── __init__.py │ ├── importer │ │ ├── OctopusImporter.py │ │ └── __init__.py │ ├── plugins │ │ ├── __init__.py │ │ └── plugin.py │ ├── server │ │ ├── DBInterface.py │ │ ├── __init__.py │ │ ├── orientdb │ │ │ ├── __init__.py │ │ │ ├── orientdb_plugin_executor.py │ │ │ ├── orientdb_project_manager.py │ │ │ ├── orientdb_server_command.py │ │ │ └── orientdb_shell_mananger.py │ │ ├── project_manager.py │ │ ├── python_shell_interface.py │ │ └── shell_manager.py │ ├── shell │ │ ├── __init__.py │ │ ├── completer │ │ │ ├── __init__.py │ │ │ └── octopus_rlcompleter.py │ │ ├── octopus_console.py │ │ ├── octopus_shell.py │ │ ├── octopus_shell_utils.py │ │ └── onlinehelp │ │ │ ├── __init__.py │ │ │ └── online_help.py │ └── shelltool │ │ ├── ChunkStartTool.py │ │ ├── CmdLineTool.py │ │ ├── DemuxTool.py │ │ ├── GraphvizTool.py │ │ ├── PipeTool.py │ │ ├── StartTool.py │ │ └── __init__.py │ ├── scripts │ ├── octopus-plugin │ └── octopus-project │ ├── setup.py │ └── tests │ ├── __init__.py │ ├── orientdb_server_command.py │ ├── orientdb_shell_manager.py │ └── python_shell_interface.py └── settings.gradle /.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | jars/ 3 | 4 | projects/octopus/octopus-server/projects/ 5 | projects/octopus/octopus-server/plugins/ 6 | projects/octopus/octopus-server/querylib/ 7 | projects/octopus/octopus-server/orientdb/ 8 | projects/octopus/octopus-server/orientdb.tar.gz 9 | 10 | projects/octopus/octopus-server/src/main/resources/logback-test.xml 11 | 12 | .gradle/ 13 | gradle/ 14 | gradlew 15 | gradlew.bat 16 | 17 | .idea/ 18 | *.iml 19 | *.ipr 20 | *.iws 21 | 22 | /bin/ 23 | -------------------------------------------------------------------------------- /AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Bjoern: a platform for graph-based analysis of binary code 2 | 3 | Bjoern is a platform for the analysis of binary code. The platform 4 | ports, extends, and reimplements concepts of the source code analysis 5 | platform joern. It generates a graph representation of native code 6 | directly from output provided by the open-source reverse engineering 7 | toolchain radare2, and stores it in a graph database using the Octopus 8 | server for collaborative code analysis. 9 | 10 | http://bjoern.readthedocs.org/en/latest/ 11 | -------------------------------------------------------------------------------- /bjoern-server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | BASEDIR=$(dirname "$0") 4 | 5 | while getopts :d: opt 6 | do 7 | case $opt in 8 | d) JAVA_OPTS="$JAVA_OPTS -ea -agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=$OPTARG" 9 | esac 10 | done 11 | 12 | export JAVA_OPTS 13 | 14 | $BASEDIR/projects/octopus/octopus-server/octopus-server.sh 15 | -------------------------------------------------------------------------------- /conf/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /docs/source/dbcontents.rst: -------------------------------------------------------------------------------- 1 | Database Contents 2 | ================= 3 | -------------------------------------------------------------------------------- /docs/source/firststeps.rst: -------------------------------------------------------------------------------- 1 | First steps (Tutorial) 2 | ---------------------- 3 | 4 | The following tutorial illustrates basic usage of bjoern. You will 5 | learn how to start the server, import code, spawn a bjoern-shell and 6 | run queries against the database. 7 | 8 | 1. Begin by starting the bjoern-server: 9 | 10 | .. code-block:: none 11 | 12 | ./bjoern-server.sh 13 | 14 | This starts an orientDB server instance, along with the OrientDB 15 | Studio on port 2480. Studio provides a useful interface to explore the 16 | database contents (see http://orientdb.com/docs/last/Home-page.html). 17 | 18 | 2. In another shell, import some code 19 | 20 | .. code-block:: none 21 | 22 | ./bjoern-import.sh /bin/ls 23 | 24 | This will start a thread inside the server process which performs the 25 | import. You will see an 'Import finished' message in the server log 26 | upon completion. 27 | 28 | 3. Create a shell thread using bjosh 29 | 30 | .. code-block:: none 31 | 32 | bjosh create 33 | 34 | 4. Connect to the shell process using bjosh 35 | 36 | .. code-block:: none 37 | 38 | bjosh connect 39 | 40 | 5. Get names of all functions (sample query) 41 | 42 | .. code-block:: none 43 | 44 | 45 | _ _ _ 46 | | |__ (_) ___ ___| |__ 47 | | '_ \| |/ _ \/ __| '_ \ 48 | | |_) | | (_) \__ \ | | | 49 | |_.__// |\___/|___/_| |_| 50 | |__/ bjoern shell 51 | 52 | 53 | bjoern> queryNodeIndex('nodeType:Func').repr 54 | 55 | 6. Get all calls 56 | 57 | .. code-block:: none 58 | 59 | getCallsTo('').map 60 | 61 | 7. Get basic blocks containing calls to 'malloc' 62 | 63 | .. code-block:: none 64 | 65 | getCallsTo('malloc').in('IS_BB_OF').repr 66 | 67 | 8. Walk to first instruction of each function 68 | 69 | .. code-block:: none 70 | 71 | getFunctions('').funcToInstr().repr 72 | -------------------------------------------------------------------------------- /docs/source/gremlinshell.rst: -------------------------------------------------------------------------------- 1 | Shell Access (Gremlin) 2 | ====================== 3 | 4 | Octopus provides access to Gremlin shells that can be used to 5 | query the database. Shells run inside the server process and can 6 | therefore make use of the 'plocal' binary protocol for efficient 7 | access. 8 | 9 | Usage 10 | ----- 11 | 12 | The shells currently running inside the server process can be listed 13 | using the `listshells` command as follows: 14 | 15 | .. code-block:: none 16 | 17 | curl http://localhost:2480/listshells 18 | 19 | A new shell can be created using the `shellcreate` command as follows. 20 | 21 | .. code-block:: none 22 | 23 | curl http://localhost:2480/shellcreate/[dbname] 24 | 25 | where `dbname` is the name of the database to connect to. By default, 26 | a shell for `bjoernDB` is created. 27 | 28 | Configuration 29 | ------------- 30 | 31 | none 32 | -------------------------------------------------------------------------------- /docs/source/index.rst: -------------------------------------------------------------------------------- 1 | Welcome to bjoern's documentation! 2 | ================================= 3 | 4 | Bjoern is a platform for the analysis of binary code. The platform 5 | ports, extends, and reimplements concepts of the source code analysis 6 | platform joern. It generates a graph representation of native code 7 | directly from output provided by the open-source reverse engineering 8 | toolchain radare2, and stores it in an OrientDB graph database for 9 | subsequent mining with graph database queries. 10 | 11 | Contents: 12 | 13 | .. toctree:: 14 | :maxdepth: 2 15 | 16 | overview 17 | installation 18 | firststeps 19 | dbcontents 20 | csvimport 21 | gremlinshell 22 | plugins 23 | 24 | .. 25 | Indices and tables 26 | ================== 27 | 28 | * :ref:`genindex` 29 | * :ref:`modindex` 30 | * :ref:`search` 31 | -------------------------------------------------------------------------------- /docs/source/installation.rst: -------------------------------------------------------------------------------- 1 | Installation 2 | ============= 3 | 4 | System Requirements and Dependencies 5 | ------------------------------------- 6 | 7 | - **A Java Virtual Machine 1.8.** Bjoern is written in Java 8 and does 8 | not build with Java 7. It has been tested with OpenJDK 8 but should 9 | also work with Oracle's JVM. 10 | 11 | - **Radare2** The primitives provided by the radare2 reverse 12 | engineering framework are employed to dissect and analyze binary 13 | files to obtain graph-based program representations from them. 14 | 15 | - **OrientDB 2.1.5 Community Edition.** The bjoern-server is based on 16 | OrientDB version *2.1.5* and has not been tested with any other 17 | version. You can download the correct version 18 | `here `_ . 19 | 20 | - **Bjoern-shell [Optional. ]** The bjoern-shell is a convenient tool 21 | to query the database contents and develop new query-primitives 22 | (so-called steps) that can be re-used in subsequent queries. 23 | 24 | Installing radare2 25 | ------------------ 26 | 27 | Please follow the instructions `here 28 | `_ to install radare2, and make 29 | sure the programs `radare2` and `r2` are in the path. 30 | 31 | Building bjoern (step-by-step) 32 | ------------------------------ 33 | 34 | .. code-block:: none 35 | 36 | git clone https://github.com/fabsx00/bjoern 37 | cd bjoern 38 | gradle deploy 39 | 40 | This will build the bjoern-server and install python utilities into 41 | the user site-packages directory (typically `~/.local/`). To test your 42 | installation, try running 43 | 44 | .. code-block:: none 45 | 46 | bjoern-import 47 | 48 | If this command is unavailable, please make sure the script directory 49 | (typically `~/.local/bin/`) is in the path, e.g., by adding the 50 | following to your `~/.bashrc`: 51 | 52 | .. code-block:: none 53 | 54 | export PATH=$PATH:~/.local/bin 55 | -------------------------------------------------------------------------------- /integrationTest/build.gradle: -------------------------------------------------------------------------------- 1 | sourceSets { 2 | intTest { 3 | java { 4 | srcDir 'test/src/java' 5 | } 6 | } 7 | } 8 | 9 | dependencies { 10 | intTestCompile group: 'org.testng', name: 'testng', version: '6.9.10' 11 | 12 | intTestCompile project(':projects:octopus:orientdbimporter') 13 | intTestCompile project(':projects:bjoern-plugins:instructionlinker') 14 | intTestCompile project(':projects:octopus:octopus-server') 15 | } 16 | 17 | task integrationTest(type:Test) { 18 | useTestNG() 19 | testLogging.showStandardStreams = true 20 | testClassesDir = sourceSets.intTest.output.classesDir 21 | classpath = sourceSets.intTest.runtimeClasspath 22 | } -------------------------------------------------------------------------------- /projects/bjoern-lang/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | task copyLang(type:Copy) { 3 | from "${project.projectDir}/src/main/groovy/" 4 | into "${project.projectDir}/../octopus/octopus-server/querylib/bjoern/" 5 | } 6 | 7 | build.dependsOn copyLang 8 | -------------------------------------------------------------------------------- /projects/bjoern-lang/src/main/groovy/controlflow.groovy: -------------------------------------------------------------------------------- 1 | package bjoernsteps; 2 | 3 | getPrevInstr = { def pattern -> 4 | _().in('NEXT_INSTR').dedup() 5 | .loop(2){it.path.isSimple() && !it.object.repr.contains(pattern) } 6 | {it.object.repr.contains(pattern)} 7 | .enablePath() 8 | } 9 | 10 | getNextInstr = { def pattern -> 11 | _().out('NEXT_INSTR').dedup() 12 | .loop(2){it.path.isSimple() && !it.object.repr.contains(pattern) } 13 | {it.object.repr.contains(pattern)} 14 | .enablePath() 15 | } 16 | -------------------------------------------------------------------------------- /projects/bjoern-lang/src/main/groovy/dataflow.groovy: -------------------------------------------------------------------------------- 1 | reachesWith = { args -> 2 | _().outE("REACHES").filter { it.aloc in args }.inV() 3 | } 4 | 5 | reachesWithout = { args -> 6 | _().outE("REACHES").filter { !(it.aloc in args) }.inV() 7 | } 8 | 9 | revReachesWith = { args -> 10 | _().inE("REACHES").filter { it.aloc in args }.outV() 11 | } 12 | 13 | revReachesWithout = { args -> 14 | _().inE("REACHES").filter { !(it.aloc in args) }.outV() 15 | } 16 | -------------------------------------------------------------------------------- /projects/bjoern-lang/src/main/groovy/lookup.groovy: -------------------------------------------------------------------------------- 1 | package bjoernsteps; 2 | 3 | queryNodeIndex = { luceneQuery -> 4 | 5 | queryStr = 'SELECT * FROM V WHERE [addr,code,comment,esil,key,nodeType,repr] LUCENE "' + luceneQuery + '"'; 6 | query = new com.orientechnologies.orient.core.sql.OCommandSQL(queryStr); 7 | g.getRawGraph().command(query).execute().toList()._().transform { g.v(it.getIdentity()) } 8 | } 9 | 10 | getCallsTo = { callee -> 11 | queryNodeIndex("nodeType:Flag").filter { 12 | it.code.contains(callee) 13 | }.copySplit(_().in("IS_ANNOTATED_BY").out("INTERPRETABLE_AS").has("nodeType", "Instr").in("CALL"), 14 | _().transform{queryNodeIndex("nodeType:Instr AND addr:" + Integer.toHexString(Integer.parseInt(it.addr,16) - 1))} 15 | .scatter()).exhaustMerge().dedup() 16 | } 17 | 18 | getFunctions = { name -> 19 | queryNodeIndex('nodeType:Func') 20 | .filter { it.repr.contains(name) } 21 | } 22 | 23 | jumpToAddr = { addr -> 24 | if (addr instanceof String) { 25 | addr = addr.startsWith("0x") ? addr.substring(2) : addr 26 | addr = Long.parseLong(addr, 16) 27 | } 28 | addr = Long.toHexString(addr) 29 | query = String.format('nodeType:Root AND addr:%s', addr) 30 | queryNodeIndex(query) 31 | } 32 | 33 | jumpToInstrAtAddr = { addr -> 34 | jumpToAddr(addr).out("INTERPRETABLE_AS").filter { it.nodeType == "Instr" } 35 | } 36 | -------------------------------------------------------------------------------- /projects/bjoern-lang/src/main/groovy/structure.groovy: -------------------------------------------------------------------------------- 1 | package bjoernsteps; 2 | 3 | inSameBlock = { 4 | _().in('IS_BB_OF').out('IS_BB_OF') 5 | } 6 | 7 | funcToFirstInstr = { 8 | _().in('INTERPRETABLE_AS').out('INTERPRETABLE_AS') 9 | .filter { it.nodeType == 'Instr' } 10 | } 11 | 12 | funcToAlocs = { 13 | _().out("ALOC_USE_EDGE") 14 | } 15 | 16 | instrToBlock = { 17 | _().in("IS_BB_OF") 18 | } 19 | 20 | blockToFunc = { 21 | _().in("IS_FUNC_OF") 22 | } 23 | 24 | instrToFunc = { 25 | _().instrToBlock().blockToFunc() 26 | } 27 | 28 | followCallToFunc = { 29 | _().out("CALL").instrToFunc() 30 | } -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 3 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 4 | compile group: 'com.orientechnologies', name: 'orientdb-core', version: '2.1.5' 5 | compile group: 'org.json', name: 'json', version: '20141113' 6 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 7 | 8 | compile project(':projects:bjoern-r2interface') 9 | } -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/BjoernConstants.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib; 2 | 3 | import bjoern.structures.BjoernNodeProperties; 4 | import com.orientechnologies.orient.core.sql.OCommandSQL; 5 | 6 | import java.util.Arrays; 7 | 8 | public class BjoernConstants 9 | { 10 | 11 | private static final String[] INDEX_KEYS = { 12 | BjoernNodeProperties.ADDR, 13 | BjoernNodeProperties.CODE, 14 | BjoernNodeProperties.COMMENT, 15 | BjoernNodeProperties.ESIL, 16 | BjoernNodeProperties.KEY, 17 | BjoernNodeProperties.TYPE, 18 | BjoernNodeProperties.REPR 19 | }; 20 | 21 | public static final String INDEX_NAME = Arrays.asList(INDEX_KEYS).toString(); 22 | 23 | public static final OCommandSQL LUCENE_QUERY = new OCommandSQL( 24 | "SELECT * FROM V WHERE " + INDEX_NAME + " LUCENE ?"); 25 | 26 | } 27 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/BjoernProject.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib; 2 | 3 | import java.io.File; 4 | 5 | import octopus.lib.OctopusProjectWrapper; 6 | 7 | public class BjoernProject extends OctopusProjectWrapper { 8 | 9 | public String getPathToBinary() 10 | { 11 | return getPathToProjectDir() + File.separator + "binary"; 12 | } 13 | 14 | public String getR2ProjectFilename() 15 | { 16 | return getPathToProjectDir() + File.separator + "radareProject"; 17 | } 18 | 19 | public String getNodeFilename() 20 | { 21 | return getPathToProjectDir() + File.separator + "nodes.csv"; 22 | } 23 | 24 | public String getEdgeFilename() 25 | { 26 | return getPathToProjectDir() + File.separator + "edges.csv"; 27 | } 28 | 29 | } 30 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/LookupOperations.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib; 2 | 3 | import bjoern.structures.BjoernNodeTypes; 4 | import bjoern.pluginlib.structures.Function; 5 | import com.tinkerpop.blueprints.Vertex; 6 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 7 | 8 | import java.util.stream.Collectors; 9 | import java.util.stream.StreamSupport; 10 | 11 | public class LookupOperations 12 | { 13 | 14 | @Deprecated 15 | public static Iterable getAllFunctions(OrientGraphNoTx graph) 16 | { 17 | Iterable functions = graph.command( 18 | BjoernConstants.LUCENE_QUERY).execute("nodeType:" + BjoernNodeTypes.FUNCTION); 19 | return functions; 20 | } 21 | 22 | public static Iterable getFunctions(OrientGraphNoTx graph) 23 | { 24 | boolean parallel = true; 25 | Iterable functions = graph.command(BjoernConstants.LUCENE_QUERY) 26 | .execute("nodeType:" + BjoernNodeTypes.FUNCTION); 27 | return StreamSupport.stream(functions.spliterator(), parallel).map(Function::new) 28 | .collect(Collectors.toList()); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/connectors/BjoernProjectConnector.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.connectors; 2 | 3 | import bjoern.pluginlib.BjoernProject; 4 | import octopus.lib.OctopusProjectWrapper; 5 | import octopus.lib.connectors.OctopusProjectConnector; 6 | import octopus.server.components.projectmanager.OctopusProject; 7 | 8 | public class BjoernProjectConnector extends OctopusProjectConnector { 9 | 10 | @Override 11 | protected OctopusProjectWrapper createNewProject(OctopusProject oProject) 12 | { 13 | BjoernProject bjoernProject = new BjoernProject(); 14 | bjoernProject.setWrappedProject(oProject); 15 | return bjoernProject; 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/plugintypes/BjoernProjectPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.plugintypes; 2 | 3 | import bjoern.pluginlib.connectors.BjoernProjectConnector; 4 | import octopus.lib.plugintypes.OctopusProjectPlugin; 5 | 6 | public abstract class BjoernProjectPlugin extends OctopusProjectPlugin 7 | { 8 | public BjoernProjectPlugin() 9 | { 10 | setProjectConnector(new BjoernProjectConnector()); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/plugintypes/RadareOrientGraphPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.plugintypes; 2 | 3 | import bjoern.pluginlib.connectors.BjoernProjectConnector; 4 | import octopus.lib.connectors.OrientDBConnector; 5 | import octopus.server.components.pluginInterface.Plugin; 6 | import org.json.JSONObject; 7 | 8 | public abstract class RadareOrientGraphPlugin implements Plugin 9 | { 10 | 11 | OrientDBConnector orientConnector = new OrientDBConnector(); 12 | BjoernProjectConnector bjoernProjectConnector = new BjoernProjectConnector(); 13 | 14 | private String databaseName; 15 | private String projectName; 16 | 17 | @Override 18 | public void configure(JSONObject settings) 19 | { 20 | projectName = settings.getString("projectName"); 21 | } 22 | 23 | @Override 24 | public void beforeExecution() throws Exception 25 | { 26 | bjoernProjectConnector.connect(projectName); 27 | databaseName = bjoernProjectConnector.getWrapper().getDatabaseName(); 28 | orientConnector.connect(databaseName); 29 | } 30 | 31 | @Override 32 | public void afterExecution() throws Exception 33 | { 34 | bjoernProjectConnector.disconnect(); 35 | orientConnector.disconnect(); 36 | } 37 | 38 | 39 | } 40 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/plugintypes/RadareProjectPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.plugintypes; 2 | 3 | import java.io.IOException; 4 | 5 | import bjoern.pluginlib.BjoernProject; 6 | import bjoern.r2interface.Radare; 7 | import octopus.lib.connectors.OrientDBConnector; 8 | 9 | public abstract class RadareProjectPlugin extends BjoernProjectPlugin 10 | { 11 | 12 | private Radare radare = new Radare(); 13 | private BjoernProject project; 14 | private OrientDBConnector orientConnector = new OrientDBConnector(); 15 | 16 | @Override 17 | public void beforeExecution() throws Exception 18 | { 19 | loadR2Project(); 20 | connectToProjectDatabase(); 21 | } 22 | 23 | private void loadR2Project() throws IOException 24 | { 25 | setProject((BjoernProject) getProjectConnector().getWrapper()); 26 | String r2ProjectFilename = getProject().getR2ProjectFilename(); 27 | String pathToBinary = getProject().getPathToBinary(); 28 | getRadare().loadBinary(pathToBinary); 29 | getRadare().loadProject(r2ProjectFilename); 30 | } 31 | 32 | private void connectToProjectDatabase() 33 | { 34 | String databaseName = getProject().getDatabaseName(); 35 | getOrientConnector().connect(databaseName); 36 | } 37 | 38 | @Override 39 | public void afterExecution() throws Exception 40 | { 41 | getOrientConnector().disconnect(); 42 | getRadare().shutdown(); 43 | } 44 | 45 | protected Radare getRadare() 46 | { 47 | return radare; 48 | } 49 | 50 | protected void setRadare(Radare radare) 51 | { 52 | this.radare = radare; 53 | } 54 | 55 | protected BjoernProject getProject() 56 | { 57 | return project; 58 | } 59 | 60 | protected void setProject(BjoernProject project) 61 | { 62 | this.project = project; 63 | } 64 | 65 | protected OrientDBConnector getOrientConnector() 66 | { 67 | return orientConnector; 68 | } 69 | 70 | protected void setOrientConnector(OrientDBConnector orientConnector) 71 | { 72 | this.orientConnector = orientConnector; 73 | } 74 | 75 | } 76 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/radare/emulation/esil/ESILTokenEvaluator.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.radare.emulation.esil; 2 | 3 | public class ESILTokenEvaluator 4 | { 5 | 6 | public long parseNumericConstant(String token) 7 | { 8 | if (token.startsWith("0x")) 9 | { 10 | return Long.parseUnsignedLong(token.substring(2), 16); 11 | } 12 | return Long.parseLong(token, 10); 13 | } 14 | 15 | public boolean isNumericConstant(String token) 16 | { 17 | if (token.startsWith("0x")) 18 | { 19 | return isHexadecimalConstant(token.substring(2)); 20 | } else 21 | { 22 | return isDecimalConstant(token); 23 | } 24 | } 25 | 26 | public boolean isHexadecimalConstant(String token) 27 | { 28 | if (token.equals("")) 29 | { 30 | return false; 31 | } 32 | for (Character c : token.toCharArray()) 33 | { 34 | if (Character.digit(c, 16) == -1) 35 | { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | 42 | public boolean isDecimalConstant(String token) 43 | { 44 | if (token.equals("")) 45 | { 46 | return false; 47 | } 48 | if (token.startsWith(("-")) && token.length() > 1) 49 | { 50 | token = token.substring(1); 51 | } 52 | for (Character c : token.toCharArray()) 53 | { 54 | if (Character.digit(c, 10) == -1) 55 | { 56 | return false; 57 | } 58 | } 59 | return true; 60 | } 61 | 62 | public boolean isFlag(String token) 63 | { 64 | return isInternalFlag(token) || (token.length() == 2 && token.endsWith("f")); 65 | } 66 | 67 | private boolean isInternalFlag(String token) 68 | { 69 | return token.startsWith("$"); 70 | } 71 | 72 | public boolean isRegister(String token) 73 | { 74 | return !isFlag(token); 75 | } 76 | 77 | public boolean isEsilKeyword(String token) 78 | { 79 | return ESILKeyword.fromString(token) != null; 80 | } 81 | 82 | } 83 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/radare/emulation/esil/ESILTokenStream.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.radare.emulation.esil; 2 | 3 | import java.util.Arrays; 4 | import java.util.HashSet; 5 | import java.util.Set; 6 | 7 | public class ESILTokenStream { 8 | 9 | private String[] tokens; 10 | private int index = 0; 11 | 12 | public static final int TOKEN_NOT_FOUND = -1; 13 | 14 | public ESILTokenStream(String esilCode) 15 | { 16 | tokens = esilCode.split(","); 17 | } 18 | 19 | public boolean isEmpty() 20 | { 21 | return (index >= tokens.length); 22 | } 23 | 24 | public boolean hasNext() 25 | { 26 | return (index < tokens.length); 27 | } 28 | 29 | public String next() 30 | { 31 | if(isEmpty()) 32 | return null; 33 | 34 | return tokens[index++]; 35 | } 36 | 37 | public String getTokenAt(int i) 38 | { 39 | return tokens[i]; 40 | } 41 | 42 | public String getEsilCode(int startIndex, int stopIndex) 43 | { 44 | StringBuilder builder = new StringBuilder(); 45 | 46 | for(int i = startIndex; i < stopIndex; i++){ 47 | builder.append(tokens[i] + ","); 48 | } 49 | 50 | String retString = builder.toString(); 51 | return retString.substring(0, retString.length() - 1); 52 | } 53 | 54 | 55 | public int skipUntilToken(String token) 56 | { 57 | return skipUntilToken(new HashSet(Arrays.asList(token))); 58 | } 59 | 60 | 61 | public int skipUntilToken(Set tokens) 62 | { 63 | String t; 64 | 65 | while(hasNext()){ 66 | t = next(); 67 | 68 | if(tokens.contains(t)){ 69 | return index - 1; 70 | } 71 | } 72 | 73 | return TOKEN_NOT_FOUND; 74 | } 75 | 76 | } 77 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/radare/emulation/esil/memaccess/ESILAccessParser.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.radare.emulation.esil.memaccess; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | import bjoern.pluginlib.radare.emulation.esil.ESILTokenStream; 5 | 6 | public class ESILAccessParser 7 | { 8 | 9 | private static class ExtractorState 10 | { 11 | 12 | public ExtractorState(int i, String e) 13 | { 14 | index = i; 15 | expr = e; 16 | } 17 | 18 | int index; 19 | String expr; 20 | } 21 | 22 | public static String parse(ESILTokenStream tokenStream, int index) 23 | { 24 | ExtractorState state = extract_(tokenStream, index - 1); 25 | return state.expr; 26 | } 27 | 28 | 29 | private static ExtractorState extract_(ESILTokenStream tokenStream, int index) 30 | { 31 | String curToken = tokenStream.getTokenAt(index); 32 | 33 | ESILKeyword accessKeyword = ESILKeyword.fromString(curToken); 34 | if (accessKeyword == null) 35 | // is token a non-keyword? 36 | return new ExtractorState(index - 1, curToken); 37 | 38 | String retString = curToken; 39 | 40 | int curIndex = index - 1; 41 | for (int i = 0; i < accessKeyword.numberOfArgs; i++) 42 | { 43 | ExtractorState state = extract_(tokenStream, curIndex); 44 | curIndex = state.index; 45 | retString = state.expr + "," + retString; 46 | } 47 | 48 | return new ExtractorState(curIndex, retString); 49 | } 50 | 51 | } 52 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/radare/emulation/esil/memaccess/MemoryAccess.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.radare.emulation.esil.memaccess; 2 | 3 | public class MemoryAccess { 4 | 5 | private String esilExpression; 6 | private String address; 7 | private String instructionRepr; 8 | private String completeEsilExpression; 9 | 10 | public String getEsilExpression() 11 | { 12 | return esilExpression; 13 | } 14 | 15 | public void setEsilExpression(String esilExpression) 16 | { 17 | this.esilExpression = esilExpression; 18 | } 19 | 20 | public String getAddress() 21 | { 22 | return address; 23 | } 24 | 25 | public void setAddress(String address) 26 | { 27 | this.address = address; 28 | } 29 | 30 | public void debugOut() 31 | { 32 | System.out.println("Repr: " + instructionRepr); 33 | System.out.println("Complete: " + completeEsilExpression); 34 | System.out.println("Expr: " + esilExpression); 35 | System.out.println("Addr: " + address); 36 | } 37 | 38 | public String getInstructionRepr() 39 | { 40 | return instructionRepr; 41 | } 42 | 43 | public void setInstructionRepr(String instructionRepr) 44 | { 45 | this.instructionRepr = instructionRepr; 46 | } 47 | 48 | public String getCompleteEsilExpression() 49 | { 50 | return completeEsilExpression; 51 | } 52 | 53 | public void setCompleteEsilExpression(String completeEsilExpression) 54 | { 55 | this.completeEsilExpression = completeEsilExpression; 56 | } 57 | 58 | 59 | 60 | } 61 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/radare/emulation/esil/memaccess/StackState.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.radare.emulation.esil.memaccess; 2 | 3 | public class StackState { 4 | 5 | private long basePtrValue; 6 | private long stackPtrValue; 7 | 8 | public StackState(long basePtrValue, long stackPtrValue) 9 | { 10 | this.basePtrValue = basePtrValue; 11 | this.stackPtrValue = stackPtrValue; 12 | } 13 | 14 | public long getBasePtrValue() 15 | { 16 | return basePtrValue; 17 | } 18 | 19 | public long getStackPtrValue() 20 | { 21 | return stackPtrValue; 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/Aloc.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import bjoern.structures.BjoernNodeProperties; 4 | import bjoern.structures.BjoernNodeTypes; 5 | import com.tinkerpop.blueprints.Vertex; 6 | 7 | public class Aloc extends BjoernNode 8 | { 9 | public Aloc(Vertex vertex) 10 | { 11 | super(vertex, BjoernNodeTypes.ALOC); 12 | } 13 | 14 | public String getName() 15 | { 16 | return getProperty(BjoernNodeProperties.NAME).toString(); 17 | } 18 | 19 | public boolean isFlag() 20 | { 21 | return getProperty(BjoernNodeProperties.SUBTYPE).toString().equals("flag"); 22 | } 23 | 24 | public boolean isRegister() 25 | { 26 | return getProperty(BjoernNodeProperties.SUBTYPE).toString().equals("reg"); 27 | } 28 | 29 | public boolean isLocalVariable() 30 | { 31 | return getProperty(BjoernNodeProperties.SUBTYPE).toString().equals("local"); 32 | } 33 | 34 | @Override 35 | public String toString() 36 | { 37 | StringBuilder sb = new StringBuilder(); 38 | sb.append(getProperty(BjoernNodeProperties.TYPE).toString()); 39 | sb.append("("); 40 | sb.append(BjoernNodeProperties.NAME); 41 | sb.append(":"); 42 | sb.append(getProperty(BjoernNodeProperties.NAME).toString()); 43 | sb.append(")"); 44 | return sb.toString(); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/BasicBlock.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import bjoern.structures.BjoernNodeTypes; 4 | import bjoern.structures.edges.EdgeTypes; 5 | import com.tinkerpop.blueprints.Vertex; 6 | import com.tinkerpop.gremlin.java.GremlinPipeline; 7 | 8 | import java.util.Iterator; 9 | 10 | public class BasicBlock extends BjoernNode 11 | { 12 | 13 | private static final String[] CFLOW_EDGES = {EdgeTypes.CFLOW, EdgeTypes 14 | .CFLOW_TRUE, EdgeTypes.CFLOW_FALSE}; 15 | 16 | public BasicBlock(Vertex vertex) 17 | { 18 | super(vertex, BjoernNodeTypes.BASIC_BLOCK); 19 | } 20 | 21 | public Instruction getEntry() 22 | { 23 | Iterator instructions = orderedInstructions().iterator(); 24 | if (instructions.hasNext()) 25 | { 26 | return instructions.next(); 27 | } 28 | return null; 29 | } 30 | 31 | public Instruction getExit() 32 | { 33 | Iterator instructions = orderedInstructions().iterator(); 34 | Instruction last = null; 35 | if (instructions.hasNext()) 36 | { 37 | last = instructions.next(); 38 | } 39 | while (instructions.hasNext()) 40 | { 41 | last = instructions.next(); 42 | } 43 | return last; 44 | } 45 | 46 | public GremlinPipeline instructions() 47 | { 48 | return new GremlinPipeline(this) 49 | .out(EdgeTypes.IS_BB_OF).dedup().cast(Instruction.class); 50 | } 51 | 52 | public GremlinPipeline orderedInstructions() 53 | { 54 | return instructions().order(pair -> pair.getA().compareTo(pair.getB 55 | ())); 56 | } 57 | 58 | public GremlinPipeline cflow() 59 | { 60 | return new GremlinPipeline<>(this.getBaseVertex()).out(CFLOW_EDGES) 61 | .transform(BasicBlock::new); 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/BjoernEdge.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import com.tinkerpop.blueprints.Direction; 4 | import com.tinkerpop.blueprints.Edge; 5 | import com.tinkerpop.blueprints.Vertex; 6 | import com.tinkerpop.blueprints.util.wrappers.wrapped.WrappedElement; 7 | 8 | public class BjoernEdge extends WrappedElement implements Edge 9 | { 10 | public BjoernEdge(Edge edge) 11 | { 12 | super(edge); 13 | } 14 | 15 | @Override 16 | public Vertex getVertex(Direction direction) throws IllegalArgumentException 17 | { 18 | return BjoernNodeFactory.create(getBaseEdge().getVertex(direction)); 19 | } 20 | 21 | @Override 22 | public String getLabel() 23 | { 24 | return getBaseEdge().getLabel(); 25 | } 26 | 27 | private Edge getBaseEdge() 28 | { 29 | return (Edge) getBaseElement(); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/BjoernEdgeIterable.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import com.tinkerpop.blueprints.Edge; 4 | 5 | import java.util.Iterator; 6 | 7 | public class BjoernEdgeIterable implements Iterable 8 | { 9 | private final Iterable iterable; 10 | 11 | public BjoernEdgeIterable(Iterable iterable) 12 | { 13 | this.iterable = iterable; 14 | } 15 | 16 | @Override 17 | public Iterator iterator() 18 | { 19 | return new Iterator() 20 | { 21 | final Iterator baseIterable = iterable.iterator(); 22 | 23 | @Override 24 | public boolean hasNext() 25 | { 26 | return baseIterable.hasNext(); 27 | } 28 | 29 | @Override 30 | public Edge next() 31 | { 32 | return new BjoernEdge(baseIterable.next()); 33 | } 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/BjoernNodeFactory.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import bjoern.structures.BjoernNodeTypes; 4 | import bjoern.structures.BjoernNodeProperties; 5 | import com.tinkerpop.blueprints.Vertex; 6 | 7 | public class BjoernNodeFactory 8 | { 9 | public static BjoernNode create(Vertex vertex) 10 | { 11 | String nodeType = vertex.getProperty(BjoernNodeProperties.TYPE); 12 | switch (nodeType) 13 | { 14 | case BjoernNodeTypes.ALOC: 15 | return new Aloc(vertex); 16 | case BjoernNodeTypes.BASIC_BLOCK: 17 | return new BasicBlock(vertex); 18 | case BjoernNodeTypes.FUNCTION: 19 | return new Function(vertex); 20 | case BjoernNodeTypes.INSTRUCTION: 21 | return new Instruction(vertex); 22 | default: 23 | return new BjoernNode(vertex); 24 | } 25 | 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/BjoernVertexIterable.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import com.tinkerpop.blueprints.Vertex; 4 | 5 | import java.util.Iterator; 6 | 7 | public class BjoernVertexIterable implements Iterable 8 | { 9 | private final Iterable iterable; 10 | 11 | public BjoernVertexIterable(Iterable iterable) 12 | { 13 | this.iterable = iterable; 14 | } 15 | 16 | @Override 17 | public Iterator iterator() 18 | { 19 | return new Iterator() 20 | { 21 | final Iterator baseIterator = iterable.iterator(); 22 | 23 | @Override 24 | public boolean hasNext() 25 | { 26 | return baseIterator.hasNext(); 27 | } 28 | 29 | @Override 30 | public Vertex next() 31 | { 32 | return BjoernNodeFactory.create(baseIterator.next()); 33 | } 34 | }; 35 | } 36 | } 37 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/Function.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import bjoern.structures.BjoernNodeTypes; 4 | import bjoern.structures.edges.EdgeTypes; 5 | import com.tinkerpop.blueprints.Vertex; 6 | import com.tinkerpop.gremlin.java.GremlinPipeline; 7 | 8 | public class Function extends BjoernNode 9 | { 10 | 11 | public Function(Vertex vertex) 12 | { 13 | super(vertex, BjoernNodeTypes.FUNCTION); 14 | } 15 | 16 | public GremlinPipeline basicBlocks() 17 | { 18 | return new GremlinPipeline<>().start(this.getBaseVertex()).out(EdgeTypes.IS_FUNCTION_OF).transform(BasicBlock::new); 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /projects/bjoern-pluginlib/src/main/java/bjoern/pluginlib/structures/Instruction.java: -------------------------------------------------------------------------------- 1 | package bjoern.pluginlib.structures; 2 | 3 | import bjoern.pluginlib.Traversals; 4 | import bjoern.structures.BjoernNodeProperties; 5 | import bjoern.structures.BjoernNodeTypes; 6 | import bjoern.structures.edges.EdgeTypes; 7 | import com.tinkerpop.blueprints.Direction; 8 | import com.tinkerpop.blueprints.Vertex; 9 | import com.tinkerpop.gremlin.java.GremlinPipeline; 10 | 11 | public class Instruction extends BjoernNode implements Comparable 12 | { 13 | 14 | public Instruction(Vertex vertex) 15 | { 16 | super(vertex, BjoernNodeTypes.INSTRUCTION); 17 | } 18 | 19 | 20 | public String getEsilCode() 21 | { 22 | return getProperty(BjoernNodeProperties.ESIL); 23 | } 24 | 25 | @Override 26 | public int compareTo(Instruction instruction) 27 | { 28 | if (this.getAddress() < instruction.getAddress()) 29 | { 30 | return -1; 31 | } else if (this.getAddress() > instruction.getAddress()) 32 | { 33 | return 1; 34 | } else 35 | { 36 | return 0; 37 | } 38 | } 39 | 40 | public boolean isCall() 41 | { 42 | return call().hasNext(); 43 | } 44 | 45 | public GremlinPipeline call() 46 | { 47 | return new GremlinPipeline<>(this.getBaseVertex()).out(EdgeTypes.CALL).transform(Instruction::new); 48 | } 49 | 50 | public GremlinPipeline exits() 51 | { 52 | final int MAX_LOOPS = 10000; 53 | final String[] EDGES = {Traversals.INSTR_CFLOW_EDGE, Traversals.INSTR_CFLOW_TRANSITIVE_EDGE}; 54 | if (!this.getVertices(Direction.OUT, EDGES).iterator().hasNext()) 55 | { 56 | return new GremlinPipeline<>(this); 57 | } else 58 | { 59 | return new GremlinPipeline<>(this.getBaseVertex()).as("start") 60 | .out(EDGES).dedup().loop("start", 61 | arg -> arg.getLoops() < MAX_LOOPS, 62 | arg -> arg.getLoops() < MAX_LOOPS 63 | && !arg.getObject().getEdges(Direction.OUT, EDGES).iterator().hasNext()) 64 | .dedup() 65 | .transform(Instruction::new); 66 | } 67 | } 68 | } 69 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/alocs/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies{ 3 | 4 | compile project(':projects:bjoern-pluginlib') 5 | 6 | } 7 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/alocs/src/main/java/bjoern/plugins/alocs/AlocPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.alocs; 2 | 3 | import java.io.IOException; 4 | 5 | import bjoern.pluginlib.structures.Function; 6 | import com.tinkerpop.blueprints.Vertex; 7 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 8 | 9 | import bjoern.pluginlib.LookupOperations; 10 | import bjoern.pluginlib.plugintypes.RadareProjectPlugin; 11 | 12 | public class AlocPlugin extends RadareProjectPlugin { 13 | 14 | OrientGraphNoTx graph; 15 | 16 | @Override 17 | public void execute() throws Exception 18 | { 19 | graph = getOrientConnector().getNoTxGraphInstance(); 20 | Iterable allFunctions = LookupOperations.getFunctions(graph); 21 | 22 | try{ 23 | createAlocsForFunctions(allFunctions); 24 | } catch(RuntimeException exception){ 25 | exception.printStackTrace(); 26 | } 27 | 28 | graph.shutdown(); 29 | } 30 | 31 | private void createAlocsForFunctions(Iterable functions) throws IOException 32 | { 33 | for(Function func : functions) 34 | { 35 | new FunctionAlocCreator(getRadare(), graph).createAlocsForFunction(func); 36 | } 37 | 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/alocs/src/main/java/bjoern/plugins/alocs/AlocTypes.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.alocs; 2 | 3 | public class AlocTypes 4 | { 5 | public static final String FLAG = "flag"; 6 | public static final String REGISTER = "reg"; 7 | public static final String LOCAL = "local"; 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/datadependence/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | 3 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 4 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 5 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 6 | 7 | compile project(':projects:bjoern-pluginlib') 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/functionexport/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | 3 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 4 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 5 | compile group: 'org.json', name: 'json', version: '20141113' 6 | 7 | compile project(':projects:bjoern-pluginlib') 8 | 9 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 10 | 11 | runtime group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3' 12 | runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' 13 | 14 | } -------------------------------------------------------------------------------- /projects/bjoern-plugins/functionexport/src/main/java/bjoern/plugins/functionexporter/io/dot/DotTokens.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.functionexporter.io.dot; 2 | 3 | public class DotTokens { 4 | 5 | public static final String NODE = "node"; 6 | public static final String EDGE = "edge"; 7 | public static final String EDGE_OP = "->"; 8 | public static final String DIGRAPH = "digraph"; 9 | public static final String NEWLINE = "\n"; 10 | } 11 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/instructionlinker/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies { 3 | 4 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 5 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 6 | 7 | compile project(':projects:bjoern-pluginlib') 8 | 9 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 10 | 11 | runtime group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3' 12 | runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' 13 | 14 | } 15 | 16 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/paramdetect/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies{ 3 | 4 | compile project(':projects:bjoern-pluginlib') 5 | 6 | } 7 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/paramdetect/src/main/java/bjoern/plugins/paramdetect/ParamDetectPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.paramdetect; 2 | 3 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 4 | 5 | import octopus.lib.plugintypes.OrientGraphConnectionPlugin; 6 | 7 | public class ParamDetectPlugin extends OrientGraphConnectionPlugin { 8 | 9 | @Override 10 | public void execute() throws Exception 11 | { 12 | OrientGraphNoTx graph = orientConnector.getNoTxGraphInstance(); 13 | orientConnector.disconnect(); 14 | } 15 | } 16 | 17 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/radareimporter/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | 3 | compile project(':projects:bjoern-pluginlib') 4 | compile project(':projects:radare2csv') 5 | 6 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 7 | 8 | runtime group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3' 9 | runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' 10 | 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/radareimporter/src/main/java/bjoern/plugins/radareimporter/RadareImporterPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.radareimporter; 2 | 3 | import bjoern.input.radare.RadareExporter; 4 | import bjoern.pluginlib.BjoernProject; 5 | import bjoern.pluginlib.plugintypes.BjoernProjectPlugin; 6 | import octopus.server.components.orientdbImporter.ImportCSVRunnable; 7 | import octopus.server.components.orientdbImporter.ImportJob; 8 | 9 | public class RadareImporterPlugin extends BjoernProjectPlugin { 10 | 11 | @Override 12 | public void execute() throws Exception 13 | { 14 | raiseIfDatabaseForProjectExists(); 15 | extractCSVFilesFromBinary(); 16 | importCSVFilesIntoDatabase(); 17 | } 18 | 19 | private void extractCSVFilesFromBinary() 20 | { 21 | BjoernProject bjoernProject = (BjoernProject) getProjectConnector().getWrapper(); 22 | 23 | String pathToBinary = bjoernProject.getPathToBinary(); 24 | String pathToProjectDir = bjoernProject.getPathToProjectDir(); 25 | RadareExporter radareExporter = new RadareExporter(); 26 | radareExporter.tryToExport(pathToBinary, pathToProjectDir, null); 27 | } 28 | 29 | private void importCSVFilesIntoDatabase() 30 | { 31 | ImportJob importJob = createImportJobForProject(); 32 | (new ImportCSVRunnable(importJob)).run(); 33 | } 34 | 35 | private ImportJob createImportJobForProject() 36 | { 37 | BjoernProject bjoernProject = (BjoernProject) getProjectConnector().getWrapper(); 38 | 39 | String dbName = bjoernProject.getDatabaseName(); 40 | String nodeFilename = bjoernProject.getNodeFilename(); 41 | String edgeFilename = bjoernProject.getEdgeFilename(); 42 | return new ImportJob(nodeFilename, edgeFilename, dbName); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/usedefanalyser/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies { 2 | 3 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 4 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 5 | 6 | compile project(':projects:bjoern-pluginlib') 7 | compile project(':projects:bjoern-plugins:vsa') 8 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 9 | 10 | testCompile group: 'junit', name: 'junit', version: '4.+' 11 | 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/usedefanalyser/src/main/java/bjoern/plugins/usedefanalyser/UseDefAnalyserPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.usedefanalyser; 2 | 3 | import bjoern.pluginlib.LookupOperations; 4 | import bjoern.pluginlib.Traversals; 5 | import bjoern.pluginlib.structures.Aloc; 6 | import bjoern.pluginlib.structures.BasicBlock; 7 | import bjoern.pluginlib.structures.Function; 8 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 9 | import octopus.lib.plugintypes.OrientGraphConnectionPlugin; 10 | 11 | import java.util.List; 12 | 13 | public class UseDefAnalyserPlugin extends OrientGraphConnectionPlugin 14 | { 15 | @Override 16 | public void execute() throws Exception 17 | { 18 | OrientGraphNoTx graph = orientConnector.getNoTxGraphInstance(); 19 | UseDefAnalyser analyzer = new UseDefAnalyser(); 20 | for (Function function : LookupOperations.getFunctions(graph)) 21 | { 22 | List alocs = Traversals.functionToAlocs(function); 23 | for (BasicBlock block : function.basicBlocks()) 24 | { 25 | analyzer.analyse(block, alocs); 26 | } 27 | } 28 | } 29 | 30 | } 31 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies { 3 | 4 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 5 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 6 | 7 | compile project(':projects:bjoern-pluginlib') 8 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 9 | 10 | testCompile group: 'junit', name: 'junit', version: '4.+' 11 | 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/VSAPlugin.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa; 2 | 3 | import bjoern.pluginlib.LookupOperations; 4 | import bjoern.pluginlib.structures.Function; 5 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 6 | import octopus.lib.plugintypes.OrientGraphConnectionPlugin; 7 | import org.slf4j.Logger; 8 | import org.slf4j.LoggerFactory; 9 | 10 | public class VSAPlugin extends OrientGraphConnectionPlugin 11 | { 12 | private Logger logger = LoggerFactory.getLogger(VSAPlugin.class); 13 | 14 | @Override 15 | public void execute() throws Exception 16 | { 17 | OrientGraphNoTx graph = orientConnector.getNoTxGraphInstance(); 18 | VSA vsa = new VSA(); 19 | for (Function function : LookupOperations.getFunctions(graph)) 20 | { 21 | try 22 | { 23 | logger.info(function.toString()); 24 | vsa.performIntraProceduralVSA(function); 25 | } catch (Exception e) 26 | { 27 | logger.error("Error for function " + function + ": " + e.getMessage()); 28 | } 29 | } 30 | graph.shutdown(); 31 | } 32 | 33 | } 34 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/DataObject.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | public interface DataObject 4 | { 5 | String getIdentifier(); 6 | 7 | DataObject copy(); 8 | 9 | T read(); 10 | 11 | void write(T value); 12 | 13 | } 14 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/DataObjectObserver.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | public interface DataObjectObserver 4 | { 5 | void updateRead(DataObject dataObject); 6 | 7 | void updateWrite(DataObject dataObject, T value); 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/Flag.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | import bjoern.plugins.vsa.structures.Bool3; 4 | 5 | public class Flag extends GenericDataObject 6 | { 7 | public Flag(String identifier, Bool3 value) 8 | { 9 | super(identifier, value); 10 | } 11 | 12 | @Override 13 | public Flag copy() 14 | { 15 | return new Flag(getIdentifier(), read()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/GenericDataObject.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | public abstract class GenericDataObject implements DataObject 4 | { 5 | private final String identifier; 6 | private T value; 7 | 8 | public GenericDataObject(String identifier, T value) 9 | { 10 | this.identifier = identifier; 11 | this.value = value; 12 | } 13 | 14 | @Override 15 | public String getIdentifier() 16 | { 17 | return this.identifier; 18 | } 19 | 20 | @Override 21 | public T read() 22 | { 23 | return this.value; 24 | } 25 | 26 | @Override 27 | public void write(T value) 28 | { 29 | this.value = value; 30 | 31 | } 32 | 33 | @Override 34 | public String toString() 35 | { 36 | return this.identifier + " = " + this.value; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/ObservableDataObject.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | import java.util.ArrayList; 4 | import java.util.Collection; 5 | 6 | public class ObservableDataObject implements DataObject 7 | { 8 | private final DataObject dataObject; 9 | private Collection> observers; 10 | 11 | public ObservableDataObject(DataObject dataObject) 12 | { 13 | this.dataObject = dataObject; 14 | this.observers = new ArrayList<>(); 15 | } 16 | 17 | @Override 18 | public String getIdentifier() 19 | { 20 | return dataObject.getIdentifier(); 21 | } 22 | 23 | @Override 24 | public ObservableDataObject copy() 25 | { 26 | ObservableDataObject copy = new ObservableDataObject<>(dataObject.copy()); 27 | copy.observers.addAll(observers); 28 | return copy; 29 | } 30 | 31 | @Override 32 | public T read() 33 | { 34 | notifyAboutReadAccess(); 35 | return dataObject.read(); 36 | } 37 | 38 | @Override 39 | public void write(T value) 40 | { 41 | notifyAboutWriteAccess(value); 42 | dataObject.write(value); 43 | } 44 | 45 | @Override 46 | public String toString() 47 | { 48 | return dataObject.toString(); 49 | } 50 | 51 | private void notifyAboutReadAccess() 52 | { 53 | for (DataObjectObserver observer : observers) 54 | { 55 | observer.updateRead(dataObject); 56 | } 57 | } 58 | 59 | private void notifyAboutWriteAccess(T value) 60 | { 61 | for (DataObjectObserver observer : observers) 62 | { 63 | observer.updateWrite(dataObject, value); 64 | } 65 | } 66 | 67 | public void addObserver(DataObjectObserver observer) 68 | { 69 | this.observers.add(observer); 70 | } 71 | 72 | } 73 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/data/Register.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.data; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class Register extends GenericDataObject 6 | { 7 | public Register(String identifier, ValueSet value) 8 | { 9 | super(identifier, value); 10 | } 11 | 12 | @Override 13 | public DataObject copy() 14 | { 15 | return new Register(getIdentifier(), read()); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/domain/memrgn/GlobalRegion.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.domain.memrgn; 2 | 3 | public class GlobalRegion implements MemoryRegion 4 | { 5 | private static final GlobalRegion GLOBAL_REGION = new GlobalRegion(); 6 | 7 | private GlobalRegion() {} 8 | 9 | public static GlobalRegion getGlobalRegion() 10 | { 11 | return GLOBAL_REGION; 12 | } 13 | 14 | 15 | @Override 16 | public String toString() 17 | { 18 | return "global"; 19 | } 20 | 21 | } 22 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/domain/memrgn/HeapRegion.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.domain.memrgn; 2 | 3 | public class HeapRegion implements MemoryRegion 4 | { 5 | private static int counter = 0; 6 | private final long id; 7 | 8 | private HeapRegion(long id) 9 | { 10 | this.id = id; 11 | } 12 | 13 | public static HeapRegion getHeapRegion() 14 | { 15 | return new HeapRegion(counter++); 16 | } 17 | 18 | @Override 19 | public boolean equals(Object o) 20 | { 21 | if (!(o instanceof HeapRegion)) 22 | { 23 | return false; 24 | } 25 | 26 | HeapRegion other = (HeapRegion) o; 27 | return this.id == other.id; 28 | } 29 | 30 | @Override 31 | public int hashCode() 32 | { 33 | return (int) (id ^ (id >>> 32)); 34 | } 35 | 36 | @Override 37 | public String toString() 38 | { 39 | return "heap" + id; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/domain/memrgn/LocalRegion.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.domain.memrgn; 2 | 3 | public class LocalRegion implements MemoryRegion 4 | { 5 | private static int counter = 0; 6 | private final long id; 7 | 8 | private LocalRegion(long id) 9 | { 10 | this.id = id; 11 | } 12 | 13 | public static LocalRegion newLocalRegion() 14 | { 15 | return new LocalRegion(counter++); 16 | } 17 | 18 | @Override 19 | public boolean equals(Object o) 20 | { 21 | if (!(o instanceof LocalRegion)) 22 | { 23 | return false; 24 | } 25 | 26 | LocalRegion other = (LocalRegion) o; 27 | return this.id == other.id; 28 | } 29 | 30 | @Override 31 | public int hashCode() 32 | { 33 | return (int) (id ^ (id >>> 32)); 34 | } 35 | 36 | 37 | @Override 38 | public String toString() 39 | { 40 | return "local" + id; 41 | } 42 | } 43 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/domain/memrgn/MemoryRegion.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.domain.memrgn; 2 | 3 | public interface MemoryRegion 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/structures/Bool3.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.structures; 2 | 3 | public enum Bool3 4 | { 5 | TRUE, 6 | FALSE, 7 | MAYBE; 8 | 9 | public Bool3 and(Bool3 bool) 10 | { 11 | switch (this) 12 | { 13 | case FALSE: 14 | return FALSE; 15 | case MAYBE: 16 | switch (bool) 17 | { 18 | case FALSE: 19 | return FALSE; 20 | case MAYBE: 21 | case TRUE: 22 | return MAYBE; 23 | } 24 | case TRUE: 25 | default: 26 | return bool; 27 | } 28 | } 29 | 30 | public Bool3 or(Bool3 bool) 31 | { 32 | switch (this) 33 | { 34 | case FALSE: 35 | return bool; 36 | case MAYBE: 37 | switch (bool) 38 | { 39 | case FALSE: 40 | case MAYBE: 41 | return MAYBE; 42 | case TRUE: 43 | return TRUE; 44 | } 45 | case TRUE: 46 | default: 47 | return TRUE; 48 | } 49 | } 50 | 51 | public Bool3 not() 52 | { 53 | switch (this) 54 | { 55 | case TRUE: 56 | return FALSE; 57 | case MAYBE: 58 | return MAYBE; 59 | case FALSE: 60 | default: 61 | return TRUE; 62 | } 63 | } 64 | 65 | public Bool3 xor(Bool3 bool) 66 | { 67 | switch (this) 68 | { 69 | case FALSE: 70 | return bool; 71 | case MAYBE: 72 | return MAYBE; 73 | case TRUE: 74 | default: 75 | return bool.not(); 76 | } 77 | } 78 | 79 | public Bool3 join(Bool3 bool) 80 | { 81 | switch (this) 82 | { 83 | case FALSE: 84 | return MAYBE.and(bool); 85 | case MAYBE: 86 | return MAYBE; 87 | case TRUE: 88 | default: 89 | return MAYBE.or(bool); 90 | } 91 | } 92 | } 93 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/structures/StridedInterval1Bit.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.structures; 2 | 3 | public class StridedInterval1Bit extends StridedInterval 4 | { 5 | static final StridedInterval1Bit BOTTOM = new StridedInterval1Bit(1, 1, 0); 6 | static final StridedInterval1Bit TOP = new StridedInterval1Bit(1, DataWidth.R64.getMinimumValue(), 7 | DataWidth.R1.getMaximumValue()); 8 | 9 | protected StridedInterval1Bit(long stride, long lower, long upper) 10 | { 11 | super(stride, lower, upper, DataWidth.R1); 12 | } 13 | 14 | @Override 15 | public String toString() 16 | { 17 | if (isSingletonSet() || isBottom()) 18 | { 19 | return super.toString(); 20 | } else 21 | { 22 | return "{" + lowerBound + ", " + upperBound + "}"; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/structures/StridedInterval64Bit.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.structures; 2 | 3 | final class StridedInterval64Bit extends StridedInterval 4 | { 5 | 6 | static final StridedInterval64Bit BOTTOM = new StridedInterval64Bit(1, 1, 0); 7 | static final StridedInterval64Bit TOP = new StridedInterval64Bit(1, DataWidth.R64.getMinimumValue(), 8 | DataWidth.R64.getMaximumValue()); 9 | 10 | StridedInterval64Bit(long stride, long lower, long upper) 11 | { 12 | super(stride, lower, upper, DataWidth.R64); 13 | } 14 | 15 | } 16 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/Transformer.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer; 2 | 3 | import bjoern.plugins.vsa.domain.AbstractEnvironment; 4 | 5 | public interface Transformer 6 | { 7 | AbstractEnvironment transform(String esilCode, AbstractEnvironment env); 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/ESILTransformationException.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil; 2 | 3 | public class ESILTransformationException extends RuntimeException 4 | { 5 | public ESILTransformationException(String message) 6 | { 7 | super(message); 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/AddAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class AddAssignCommand extends CompoundAssignCommand 6 | { 7 | public AddAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.ADD)); 10 | } 11 | } 12 | 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/AddCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class AddCommand extends ArithmeticCommand 6 | { 7 | @Override 8 | protected ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.add(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/AndAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class AndAssignCommand extends CompoundAssignCommand 6 | { 7 | public AndAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.AND)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/AndCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class AndCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.and(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ArithmeticCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 5 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 6 | 7 | import java.util.Deque; 8 | 9 | public abstract class ArithmeticCommand implements ESILCommand 10 | { 11 | @Override 12 | public final ESILStackItem execute(Deque stack) 13 | { 14 | ValueSet leftOperand = stack.pop().execute(stack).getValue(); 15 | ValueSet rightOperand = stack.pop().execute(stack).getValue(); 16 | ValueSet result = execute(leftOperand, rightOperand); 17 | return new ValueSetContainer(result); 18 | } 19 | 20 | protected abstract ValueSet execute(ValueSet leftOperand, 21 | ValueSet rightOperand); 22 | } 23 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/AssignmentCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.data.DataObject; 4 | import bjoern.plugins.vsa.domain.ValueSet; 5 | import bjoern.plugins.vsa.structures.Bool3; 6 | import bjoern.plugins.vsa.structures.StridedInterval; 7 | import bjoern.plugins.vsa.transformer.esil.ESILTransformationException; 8 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 9 | import bjoern.plugins.vsa.transformer.esil.stack.FlagContainer; 10 | import bjoern.plugins.vsa.transformer.esil.stack.RegisterContainer; 11 | 12 | import java.util.Deque; 13 | 14 | public class AssignmentCommand implements ESILCommand { 15 | @Override 16 | public ESILStackItem execute(Deque stack) { 17 | 18 | ESILStackItem item = stack.pop().execute(stack); 19 | 20 | if (item instanceof RegisterContainer) { 21 | RegisterContainer registerContainer = (RegisterContainer) item; 22 | DataObject register = registerContainer.getRegister(); 23 | register.write(stack.pop().execute(stack).getValue()); 24 | } else if (item instanceof FlagContainer) { 25 | FlagContainer flagContainer = (FlagContainer) item; 26 | DataObject flag = flagContainer.getFlag(); 27 | ValueSet valueSet = stack.pop().execute(stack).getValue(); 28 | if (valueSet.isGlobal()) { 29 | StridedInterval stridedInterval = valueSet 30 | .getValueOfGlobalRegion(); 31 | if (stridedInterval.isZero()) { 32 | flag.write(Bool3.FALSE); 33 | } else if (stridedInterval.isOne()) { 34 | flag.write(Bool3.TRUE); 35 | } else { 36 | flag.write(Bool3.MAYBE); 37 | } 38 | } else { 39 | throw new ESILTransformationException( 40 | "Error while executing assignment command: Cannot " 41 | + "assign " 42 | + valueSet + " to flag"); 43 | } 44 | } else { 45 | throw new ESILTransformationException( 46 | "Error while executing assignment command"); 47 | } 48 | return null; 49 | } 50 | } 51 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/BitArithmeticCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 5 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 6 | 7 | import java.util.Deque; 8 | 9 | public abstract class BitArithmeticCommand implements ESILCommand 10 | { 11 | @Override 12 | public final ESILStackItem execute(Deque stack) 13 | { 14 | ValueSet leftOperand = stack.pop().execute(stack).getValue(); 15 | ValueSet rightOperand = stack.pop().execute(stack).getValue(); 16 | ValueSet result = execute(leftOperand, rightOperand); 17 | return new ValueSetContainer(result); 18 | } 19 | 20 | public abstract ValueSet execute(ValueSet leftOperand, 21 | ValueSet rightOperand); 22 | } 23 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/CompoundAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 5 | 6 | import java.util.Deque; 7 | 8 | public class CompoundAssignCommand implements ESILCommand 9 | { 10 | private final ESILCommand command; 11 | 12 | public CompoundAssignCommand(ESILCommand command) 13 | { 14 | this.command = command; 15 | } 16 | 17 | @Override 18 | public final ESILStackItem execute(Deque stack) 19 | { 20 | ESILCommand item = stack.peek(); 21 | stack.push(command); 22 | stack.push(item); 23 | return ESILCommandFactory.getCommand(ESILKeyword.ASSIGNMENT) 24 | .execute(stack); 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ConditionalCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.structures.StridedInterval; 5 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 6 | 7 | import java.util.Deque; 8 | 9 | public class ConditionalCommand implements ESILCommand 10 | { 11 | 12 | private final String esilCode; 13 | 14 | public ConditionalCommand(String esilCode) 15 | { 16 | this.esilCode = esilCode; 17 | } 18 | 19 | @Override 20 | public ESILStackItem execute(Deque stack) 21 | { 22 | ValueSet operand = stack.pop().execute(stack).getValue(); 23 | StridedInterval interval = operand.getValueOfGlobalRegion(); 24 | if (interval.isZero()) 25 | { 26 | return null; 27 | } else if (interval.isOne()) 28 | { 29 | // emulate this.esilCode 30 | return null; 31 | } else 32 | { 33 | // emulate this.esilCode 34 | return null; 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/DecAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class DecAssignCommand extends CompoundAssignCommand 6 | { 7 | public DecAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.DEC)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/DecCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.structures.DataWidth; 5 | import bjoern.plugins.vsa.structures.StridedInterval; 6 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 7 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 8 | 9 | import java.util.Deque; 10 | 11 | public class DecCommand implements ESILCommand 12 | { 13 | @Override 14 | public ESILStackItem execute(Deque stack) 15 | { 16 | ValueSet operand = stack.pop().execute(stack).getValue(); 17 | ValueSet result = operand.sub(ValueSet 18 | .newGlobal(StridedInterval.getSingletonSet(1, DataWidth.R64))); 19 | return new ValueSetContainer(result); 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/DivAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class DivAssignCommand extends CompoundAssignCommand 6 | { 7 | public DivAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.DIV)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/DivCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class DivCommand extends ArithmeticCommand 6 | { 7 | @Override 8 | protected ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.div(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ESILCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 4 | 5 | import java.util.Deque; 6 | 7 | public interface ESILCommand 8 | { 9 | ESILStackItem execute(Deque stack); 10 | } 11 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ESILCommandObserver.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | public interface ESILCommandObserver 4 | { 5 | void beforeExecution(ESILCommand command); 6 | 7 | void afterExecution(ESILCommand command); 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/IncAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class IncAssignCommand extends CompoundAssignCommand 6 | { 7 | public IncAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.INC)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/IncCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.structures.DataWidth; 5 | import bjoern.plugins.vsa.structures.StridedInterval; 6 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 7 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 8 | 9 | import java.util.Deque; 10 | 11 | public class IncCommand implements ESILCommand 12 | { 13 | @Override 14 | public ESILStackItem execute(Deque stack) 15 | { 16 | 17 | ValueSet operand = stack.pop().execute(stack).getValue(); 18 | ValueSet result = operand.add(ValueSet 19 | .newGlobal(StridedInterval.getSingletonSet(1, DataWidth.R64))); 20 | return new ValueSetContainer(result); 21 | } 22 | } 23 | 24 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ModAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class ModAssignCommand extends CompoundAssignCommand 6 | { 7 | public ModAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.MOD)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ModCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class ModCommand extends ArithmeticCommand 6 | { 7 | @Override 8 | protected ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.mod(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/MulAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class MulAssignCommand extends CompoundAssignCommand 6 | { 7 | public MulAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.MUL)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/MulCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class MulCommand extends ArithmeticCommand 6 | { 7 | @Override 8 | protected ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.mul(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/NegAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class NegAssignCommand extends CompoundAssignCommand 6 | { 7 | public NegAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.NEG)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/NegateCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 5 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 6 | 7 | import java.util.Deque; 8 | 9 | public class NegateCommand implements ESILCommand 10 | { 11 | @Override 12 | public ESILStackItem execute(Deque stack) 13 | { 14 | ValueSet result = stack.pop().execute(stack).getValue().negate(); 15 | return new ValueSetContainer(result); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ObservableESILCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 4 | 5 | import java.util.ArrayList; 6 | import java.util.Collection; 7 | import java.util.Deque; 8 | 9 | public class ObservableESILCommand implements ESILCommand 10 | { 11 | private final ESILCommand command; 12 | private Collection observers; 13 | 14 | public ObservableESILCommand(ESILCommand command) 15 | { 16 | this.command = command; 17 | this.observers = new ArrayList<>(); 18 | } 19 | 20 | @Override 21 | public ESILStackItem execute(Deque stack) 22 | { 23 | notifyBeforeExecution(); 24 | ESILStackItem result = this.command.execute(stack); 25 | notifyAfterExecution(); 26 | return result; 27 | } 28 | 29 | private void notifyBeforeExecution() 30 | { 31 | for (ESILCommandObserver observer : observers) 32 | { 33 | observer.beforeExecution(this.command); 34 | } 35 | } 36 | 37 | private void notifyAfterExecution() 38 | { 39 | for (ESILCommandObserver observer : observers) 40 | { 41 | observer.afterExecution(this.command); 42 | } 43 | } 44 | 45 | public void addObserver(ESILCommandObserver observer) 46 | { 47 | this.observers.add(observer); 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/OrAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class OrAssignCommand extends CompoundAssignCommand 6 | { 7 | public OrAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.OR)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/OrCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class OrCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.or(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/PeekCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.structures.DataWidth; 5 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 6 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 7 | 8 | import java.util.Deque; 9 | 10 | public class PeekCommand implements ESILCommand 11 | { 12 | @Override 13 | public ESILStackItem execute(Deque stack) 14 | { 15 | ValueSet address = stack.pop().execute(stack).getValue(); 16 | return new ValueSetContainer(ValueSet.newTop(DataWidth.R64)); 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/PokeCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 5 | 6 | import java.util.Deque; 7 | 8 | public class PokeCommand implements ESILCommand 9 | { 10 | @Override 11 | public ESILStackItem execute(Deque stack) 12 | { 13 | ValueSet destinationAddress = stack.pop().execute(stack).getValue(); 14 | ValueSet value = stack.pop().execute(stack).getValue(); 15 | // write value to aloc at destinationAddress 16 | 17 | // this command returns nothing/no item is pushed on the stack 18 | return null; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/PopCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 4 | 5 | import java.util.Deque; 6 | 7 | public class PopCommand implements ESILCommand 8 | { 9 | private ESILStackItem item; 10 | 11 | public PopCommand(ESILStackItem item) 12 | { 13 | this.item = item; 14 | } 15 | 16 | @Override 17 | public ESILStackItem execute(Deque stack) 18 | { 19 | return this.item; 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/RelationalCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | import bjoern.plugins.vsa.structures.DataWidth; 5 | import bjoern.plugins.vsa.structures.StridedInterval; 6 | import bjoern.plugins.vsa.transformer.esil.stack.ESILStackItem; 7 | import bjoern.plugins.vsa.transformer.esil.stack.ValueSetContainer; 8 | 9 | import java.util.Deque; 10 | 11 | public class RelationalCommand implements ESILCommand 12 | { 13 | @Override 14 | public final ESILStackItem execute(Deque stack) 15 | { 16 | ValueSet leftOperand = stack.pop().execute(stack).getValue(); 17 | ValueSet rightOperand = stack.pop().execute(stack).getValue(); 18 | ValueSet result = execute(leftOperand, rightOperand); 19 | 20 | return new ValueSetContainer(result); 21 | } 22 | 23 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 24 | { 25 | return ValueSet.newGlobal(StridedInterval.getTop(DataWidth.R1)); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/RotateLeftCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class RotateLeftCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.rotateLeft(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/RotateRightCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class RotateRightCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.rotateRight(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ShiftLeftAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class ShiftLeftAssignCommand extends CompoundAssignCommand 6 | { 7 | public ShiftLeftAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.SHIFT_LEFT)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ShiftLeftCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class ShiftLeftCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.shiftLeft(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ShiftRightAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class ShiftRightAssignCommand extends CompoundAssignCommand 6 | { 7 | public ShiftRightAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.SHIFT_RIGHT)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/ShiftRightCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class ShiftRightCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.shiftRight(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/SubAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class SubAssignCommand extends CompoundAssignCommand 6 | { 7 | public SubAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.SUB)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/SubCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class SubCommand extends ArithmeticCommand 6 | { 7 | @Override 8 | protected ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.sub(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/XorAssignCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.pluginlib.radare.emulation.esil.ESILKeyword; 4 | 5 | public class XorAssignCommand extends CompoundAssignCommand 6 | { 7 | public XorAssignCommand() 8 | { 9 | super(ESILCommandFactory.getCommand(ESILKeyword.XOR)); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/commands/XorCommand.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.commands; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class XorCommand extends BitArithmeticCommand 6 | { 7 | @Override 8 | public ValueSet execute(ValueSet leftOperand, ValueSet rightOperand) 9 | { 10 | return leftOperand.xor(rightOperand); 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/stack/ESILStack.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.stack; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | import java.util.Deque; 6 | import java.util.LinkedList; 7 | 8 | public class ESILStack 9 | { 10 | private final Deque stack; 11 | 12 | public ESILStack() {stack = new LinkedList<>();} 13 | 14 | public void push(ESILStackItem item) 15 | { 16 | this.stack.push(item); 17 | } 18 | 19 | public void pushValueSet(ValueSet valueSet) 20 | { 21 | this.push(new ValueSetContainer(valueSet)); 22 | } 23 | 24 | public ValueSet popValueSet() 25 | { 26 | return this.stack.pop().getValue(); 27 | } 28 | 29 | public ESILStackItem pop() 30 | { 31 | return stack.pop(); 32 | } 33 | 34 | public ESILStackItem peek() 35 | { 36 | return stack.peek(); 37 | } 38 | 39 | @Override 40 | public String toString() 41 | { 42 | return stack.toString(); 43 | } 44 | 45 | } 46 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/stack/ESILStackItem.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.stack; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public interface ESILStackItem 6 | { 7 | ValueSet getValue(); 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/stack/FlagContainer.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.stack; 2 | 3 | import bjoern.plugins.vsa.data.DataObject; 4 | import bjoern.plugins.vsa.domain.ValueSet; 5 | import bjoern.plugins.vsa.structures.Bool3; 6 | import bjoern.plugins.vsa.structures.DataWidth; 7 | import bjoern.plugins.vsa.structures.StridedInterval; 8 | 9 | public class FlagContainer implements ESILStackItem 10 | { 11 | 12 | private final DataObject dataObject; 13 | 14 | public FlagContainer(DataObject dataObject) 15 | { 16 | this.dataObject = dataObject; 17 | } 18 | 19 | public DataObject getFlag() 20 | { 21 | return this.dataObject; 22 | } 23 | 24 | public ValueSet getValue() 25 | { 26 | Bool3 value = dataObject.read(); 27 | switch (value) 28 | { 29 | case FALSE: 30 | return ValueSet.newGlobal(StridedInterval.getSingletonSet(0, DataWidth.R1)); 31 | case TRUE: 32 | return ValueSet.newGlobal(StridedInterval.getSingletonSet(1, DataWidth.R1)); 33 | case MAYBE: 34 | default: 35 | return ValueSet.newGlobal(StridedInterval.getTop(DataWidth.R1)); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/stack/RegisterContainer.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.stack; 2 | 3 | import bjoern.plugins.vsa.data.DataObject; 4 | import bjoern.plugins.vsa.domain.ValueSet; 5 | 6 | public class RegisterContainer implements ESILStackItem 7 | { 8 | 9 | private final DataObject dataObject; 10 | 11 | public RegisterContainer(DataObject register) 12 | { 13 | this.dataObject = register; 14 | } 15 | 16 | 17 | public DataObject getRegister() 18 | { 19 | return this.dataObject; 20 | } 21 | 22 | @Override 23 | public ValueSet getValue() 24 | { 25 | return dataObject.read(); 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/main/java/bjoern/plugins/vsa/transformer/esil/stack/ValueSetContainer.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.transformer.esil.stack; 2 | 3 | import bjoern.plugins.vsa.domain.ValueSet; 4 | 5 | public class ValueSetContainer implements ESILStackItem 6 | { 7 | 8 | private final ValueSet valueSet; 9 | 10 | public ValueSetContainer(ValueSet valueSet) 11 | { 12 | if (valueSet == null) 13 | { 14 | throw new IllegalArgumentException("Value must not be null"); 15 | } 16 | this.valueSet = valueSet; 17 | } 18 | 19 | @Override 20 | public ValueSet getValue() 21 | { 22 | return valueSet; 23 | } 24 | 25 | @Override 26 | public String toString() 27 | { 28 | return valueSet.toString(); 29 | } 30 | } 31 | -------------------------------------------------------------------------------- /projects/bjoern-plugins/vsa/src/test/java/bjoern/plugins/vsa/structures/ArithmeticTests.java: -------------------------------------------------------------------------------- 1 | package bjoern.plugins.vsa.structures; 2 | 3 | import org.junit.Test; 4 | 5 | import static org.junit.Assert.*; 6 | 7 | public class ArithmeticTests 8 | { 9 | 10 | @Test 11 | public void testAddCase1() 12 | { 13 | StridedInterval a = StridedInterval.getStridedInterval(1, -5, -3, DataWidth.R4); 14 | StridedInterval b = StridedInterval.getStridedInterval(1, -7, -6, DataWidth.R4); 15 | 16 | StridedInterval expected = StridedInterval.getStridedInterval(1, 4, 7, DataWidth.R4); 17 | assertEquals(expected, a.add(b)); 18 | } 19 | 20 | @Test 21 | public void testAddCase2() 22 | { 23 | StridedInterval a = StridedInterval.getStridedInterval(6, -7, 5, DataWidth.R4); 24 | StridedInterval b = StridedInterval.getStridedInterval(2, -3, 7, DataWidth.R4); 25 | 26 | StridedInterval expexted = StridedInterval.getTop(DataWidth.R4); 27 | assertEquals(expexted, a.add(b)); 28 | } 29 | 30 | @Test 31 | public void testAddCase3() 32 | { 33 | StridedInterval a = StridedInterval.getStridedInterval(4, -4, 4, DataWidth.R4); 34 | StridedInterval b = StridedInterval.getStridedInterval(2, -3, 3, DataWidth.R4); 35 | 36 | StridedInterval expexted = StridedInterval.getStridedInterval(2, -7, 7, DataWidth.R4); 37 | assertEquals(expexted, a.add(b)); 38 | } 39 | 40 | @Test 41 | public void testNegateCase1() 42 | { 43 | StridedInterval a = StridedInterval.getSingletonSet(-8, DataWidth.R4); 44 | assertEquals(a, a.negate()); 45 | } 46 | 47 | @Test 48 | public void testNegateCase2() 49 | { 50 | StridedInterval a = StridedInterval.getStridedInterval(3, -7, 5, DataWidth.R4); 51 | StridedInterval expected = StridedInterval.getStridedInterval(3, -5, 7, DataWidth.R4); 52 | assertEquals(expected, a.negate()); 53 | } 54 | 55 | @Test 56 | public void testNegateCase3() 57 | { 58 | StridedInterval a = StridedInterval.getStridedInterval(3, -8, 4, DataWidth.R4); 59 | StridedInterval expected = StridedInterval.getTop(DataWidth.R4); 60 | assertEquals(expected, a.negate()); 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/build.gradle: -------------------------------------------------------------------------------- 1 | dependencies 2 | { 3 | compile group: 'org.json', name: 'json', version: '20141113' 4 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 5 | 6 | runtime group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3' 7 | runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' 8 | 9 | compile project(':projects:octopus:octopus-server') 10 | 11 | } -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/R2Pipe.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface; 2 | 3 | // Adapted from: 4 | // https://github.com/radare/radare2-bindings/blob/master/r2pipe/java/org/radare/r2pipe/R2Pipe.java 5 | 6 | import org.slf4j.Logger; 7 | import org.slf4j.LoggerFactory; 8 | 9 | import java.io.IOException; 10 | import java.io.InputStream; 11 | import java.io.OutputStream; 12 | 13 | class R2Pipe 14 | { 15 | private static final Logger logger = LoggerFactory.getLogger(R2Pipe.class); 16 | 17 | public final String R2_LOC = "radare2"; 18 | private final Process process; 19 | private OutputStream stdin; 20 | private InputStream stdout; 21 | 22 | public R2Pipe(String filename) throws IOException 23 | { 24 | process = spawnR2Process(filename); 25 | connectProcessPipes(); 26 | readUpToZeroByte(); 27 | } 28 | 29 | private void connectProcessPipes() 30 | { 31 | stdin = process.getOutputStream(); 32 | stdout = process.getInputStream(); 33 | StreamGobbler errorGobbler = new StreamGobbler(process.getErrorStream(), "ERROR"); 34 | errorGobbler.start(); 35 | } 36 | 37 | 38 | private Process spawnR2Process(String filename) throws IOException 39 | { 40 | ProcessBuilder processBuilder = new ProcessBuilder(R2_LOC, "-q0", filename); 41 | return processBuilder.start(); 42 | } 43 | 44 | public String cmd(String cmd) throws IOException 45 | { 46 | cmdNoResponse(cmd); 47 | String result = readUpToZeroByte(); 48 | return result; 49 | } 50 | 51 | public void cmdNoResponse(String cmd) throws IOException 52 | { 53 | logger.debug("r2 command: {}", cmd); 54 | cmd += "\n"; 55 | 56 | stdin.write((cmd).getBytes()); 57 | stdin.flush(); 58 | } 59 | 60 | public String readUpToZeroByte() throws IOException 61 | { 62 | StringBuffer sb = new StringBuffer(); 63 | byte[] b = new byte[1]; 64 | while (stdout.read(b) == 1) 65 | { 66 | if (b[0] == '\0') 67 | break; 68 | sb.append((char) b[0]); 69 | } 70 | return sb.toString(); 71 | } 72 | 73 | public void quit() throws Exception 74 | { 75 | cmd("q"); 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/StreamGobbler.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface; 2 | 3 | // Adapted from: 4 | // http://www.javaworld.com/article/2071275/core-java/when-runtime-exec---won-t.html 5 | 6 | import java.io.BufferedReader; 7 | import java.io.IOException; 8 | import java.io.InputStream; 9 | import java.io.InputStreamReader; 10 | 11 | public class StreamGobbler extends Thread 12 | { 13 | InputStream is; 14 | String type; 15 | 16 | public StreamGobbler(InputStream is, String type) 17 | { 18 | this.is = is; 19 | this.type = type; 20 | } 21 | 22 | @Override 23 | public void run() 24 | { 25 | try 26 | { 27 | InputStreamReader isr = new InputStreamReader(is); 28 | BufferedReader br = new BufferedReader(isr); 29 | String line = null; 30 | while ((line = br.readLine()) != null) 31 | { 32 | } 33 | } 34 | catch (IOException ioe) 35 | { 36 | ioe.printStackTrace(); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/architectures/Architecture.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.architectures; 2 | 3 | public abstract class Architecture { 4 | 5 | public abstract boolean isCall(String repr); 6 | public abstract boolean isRet(String repr); 7 | public abstract boolean isPop(String repr); 8 | public abstract boolean isPush(String repr); 9 | 10 | public abstract boolean isFlag(String registerName); 11 | public abstract String getStackRegisterName(); 12 | public abstract String getBaseRegisterName(); 13 | 14 | } 15 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/architectures/UnknownArchitectureException.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.architectures; 2 | 3 | public class UnknownArchitectureException extends Exception 4 | { 5 | } 6 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/architectures/X64Architecture.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.architectures; 2 | 3 | public class X64Architecture extends Architecture { 4 | 5 | @Override 6 | public boolean isCall(String repr) 7 | { 8 | return repr.startsWith("call"); 9 | } 10 | 11 | @Override 12 | public boolean isRet(String repr) 13 | { 14 | return repr.startsWith("ret"); 15 | } 16 | 17 | @Override 18 | public boolean isPop(String repr) 19 | { 20 | return repr.startsWith("pop"); 21 | } 22 | 23 | @Override 24 | public boolean isPush(String repr) 25 | { 26 | return repr.startsWith("push"); 27 | } 28 | 29 | @Override 30 | public boolean isFlag(String registerName) 31 | { 32 | return (registerName.length() == 2 && registerName.endsWith("f")); 33 | } 34 | 35 | @Override 36 | public String getStackRegisterName() 37 | { 38 | return "rsp"; 39 | } 40 | 41 | @Override 42 | public String getBaseRegisterName() 43 | { 44 | return "rbp"; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/JSONUtils.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | import org.json.JSONException; 4 | import org.json.JSONObject; 5 | 6 | public class JSONUtils 7 | { 8 | public static Long getLongFromObject(JSONObject block, String key) 9 | { 10 | try 11 | { 12 | Long val = block.getLong(key); 13 | return val; 14 | } catch (JSONException ex) 15 | { 16 | return null; 17 | } 18 | } 19 | 20 | public static String getStringFromObject(JSONObject jsonObj, String key) 21 | { 22 | try 23 | { 24 | String val = jsonObj.getString(key); 25 | return val; 26 | } catch (JSONException ex) 27 | { 28 | return null; 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/RadareBasicBlockCreator.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | 4 | import bjoern.structures.interpretations.BasicBlock; 5 | import bjoern.structures.interpretations.Instruction; 6 | import org.json.JSONArray; 7 | import org.json.JSONObject; 8 | 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | 12 | 13 | public class RadareBasicBlockCreator 14 | { 15 | 16 | public static BasicBlock createFromJSON(JSONObject block) 17 | { 18 | long addr = block.getLong("offset"); 19 | JSONArray instructionsJSON = block.getJSONArray("ops"); 20 | BasicBlock node = new BasicBlock.Builder(addr).withInstructions(getInstructionsFromJSON(instructionsJSON)) 21 | .build(); 22 | return node; 23 | } 24 | 25 | private static List getInstructionsFromJSON(JSONArray instructionsJSON) 26 | { 27 | 28 | List instructions = new LinkedList<>(); 29 | int numberOfInstructions = instructionsJSON.length(); 30 | for (int i = 0; i < numberOfInstructions; i++) 31 | { 32 | JSONObject instructionJSON = instructionsJSON.getJSONObject(i); 33 | Instruction instruction = RadareInstructionCreator.createFromJSON(instructionJSON); 34 | instructions.add(instruction); 35 | } 36 | return instructions; 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/RadareCallRefCreator.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | import bjoern.structures.edges.CallRef; 4 | 5 | public class RadareCallRefCreator { 6 | 7 | public static CallRef create(long addr) 8 | { 9 | return null; 10 | } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/RadareFlagCreator.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | import bjoern.structures.annotations.Flag; 4 | import org.json.JSONObject; 5 | 6 | public class RadareFlagCreator 7 | { 8 | public static Flag createFromJSON(JSONObject jsonFunction) 9 | { 10 | Long address = jsonFunction.getLong("offset"); 11 | String name = jsonFunction.getString("name"); 12 | Long size = jsonFunction.getLong("size"); 13 | 14 | return new Flag.Builder(address).withValue(name).withLenght(size).build(); 15 | } 16 | } 17 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/RadareFunctionCreator.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | 4 | import bjoern.structures.interpretations.Function; 5 | import bjoern.structures.interpretations.FunctionContent; 6 | import org.json.JSONObject; 7 | 8 | 9 | public class RadareFunctionCreator 10 | { 11 | 12 | public static Function createFromJSON(JSONObject jsonFunction) 13 | { 14 | Long address = jsonFunction.getLong("offset"); 15 | String name = jsonFunction.getString("name"); 16 | FunctionContent content = getFunctionContentFromJSON(jsonFunction); 17 | Function function = new Function.Builder(address).withName(name).withContent(content).build(); 18 | return function; 19 | } 20 | 21 | private static FunctionContent getFunctionContentFromJSON(JSONObject jsonFunction) 22 | { 23 | try 24 | { 25 | return RadareFunctionContentCreator.createFromJSON(jsonFunction); 26 | } catch (Exception e) 27 | { 28 | return new FunctionContent(); 29 | } 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/creators/RadareInstructionCreator.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.creators; 2 | 3 | import bjoern.structures.interpretations.Instruction; 4 | import org.json.JSONObject; 5 | 6 | public class RadareInstructionCreator 7 | { 8 | public static Instruction createFromJSON(JSONObject jsonObj) 9 | { 10 | Long address = jsonObj.getLong("offset"); 11 | String representation = jsonObj.getString("opcode"); 12 | String esilCode = jsonObj.getString("esil"); 13 | String bytes = jsonObj.getString("bytes"); 14 | String comment = JSONUtils.getStringFromObject(jsonObj, "comment"); 15 | 16 | return new Instruction.Builder(address).withRepresentation(representation).withESILCode(esilCode) 17 | .withBytes(bytes).withComment(comment).build(); 18 | } 19 | } 20 | 21 | 22 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/exceptions/BasicBlockWithoutAddress.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.exceptions; 2 | 3 | public class BasicBlockWithoutAddress extends Exception 4 | { 5 | private static final long serialVersionUID = 8899838300267123816L; 6 | } 7 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/exceptions/EmptyDisassembly.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.exceptions; 2 | 3 | public class EmptyDisassembly extends InvalidDisassembly 4 | { 5 | private static final long serialVersionUID = 7059206616782743599L; 6 | 7 | } 8 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/exceptions/InvalidDisassembly.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.exceptions; 2 | 3 | public class InvalidDisassembly extends Exception 4 | { 5 | 6 | private static final long serialVersionUID = -192747385709670186L; 7 | 8 | } 9 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/r2interface/exceptions/InvalidRadareFunctionException.java: -------------------------------------------------------------------------------- 1 | package bjoern.r2interface.exceptions; 2 | 3 | public class InvalidRadareFunctionException extends Exception 4 | { 5 | 6 | public InvalidRadareFunctionException() 7 | { 8 | super(); 9 | } 10 | 11 | public InvalidRadareFunctionException(String message) 12 | { 13 | super(message); 14 | } 15 | 16 | private static final long serialVersionUID = -6004874353334720581L; 17 | 18 | } 19 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/BjoernEdgeProperties.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | public class BjoernEdgeProperties 4 | { 5 | public static final String VALUE = "value"; 6 | } 7 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/BjoernNodeProperties.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | import octopus.lib.structures.OctopusNodeProperties; 4 | 5 | public class BjoernNodeProperties extends OctopusNodeProperties 6 | { 7 | 8 | public static final String NAME = "name"; 9 | public static final String REPR = "repr"; 10 | public static final String CODE = "code"; 11 | public static final String ADDR = "addr"; 12 | public static final String COMMENT = "comment"; 13 | 14 | public static final Object VAR = "var"; 15 | public static final String ESIL = "esil"; 16 | 17 | public static final String WIDTH = "width"; 18 | } 19 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/BjoernNodeTypes.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | public class BjoernNodeTypes 4 | { 5 | public static final String BASIC_BLOCK = "BB"; 6 | public static final String INSTRUCTION = "Instr"; 7 | public static final String FUNCTION = "Func"; 8 | public static final Object LOCAL_VAR = "Local"; 9 | public static final Object ARG = "Arg"; 10 | public static final String FLAG = "Flag"; 11 | public static final String ALOC = "Aloc"; 12 | public static final String ROOT = "Root"; 13 | } 14 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/Node.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | import java.util.HashMap; 4 | import java.util.Map; 5 | 6 | public abstract class Node 7 | { 8 | private NodeKey nodeKey; 9 | private final Long address; 10 | private final String type; 11 | private final String comment; 12 | 13 | public static abstract class Builder 14 | { 15 | private final Long address; 16 | private final String type; 17 | private String comment; 18 | 19 | public Builder(Long address, String type) 20 | { 21 | this.address = address; 22 | this.type = type; 23 | } 24 | 25 | public Builder withComment(String comment) 26 | { 27 | this.comment = comment; 28 | return this; 29 | } 30 | } 31 | 32 | public Node(Builder builder) 33 | { 34 | this.address = builder.address; 35 | this.type = builder.type; 36 | this.comment = builder.comment; 37 | } 38 | 39 | public Long getAddress() 40 | { 41 | return address; 42 | } 43 | 44 | public String getAddressAsHexString() 45 | { 46 | return Long.toHexString(getAddress()); 47 | } 48 | 49 | public String getType() 50 | { 51 | return type; 52 | } 53 | 54 | public String getComment() 55 | { 56 | return comment; 57 | } 58 | 59 | public NodeKey createKey() 60 | { 61 | if (nodeKey == null) 62 | { 63 | nodeKey = new NodeKey(getAddress(), getType()); 64 | } 65 | return nodeKey; 66 | } 67 | 68 | public String getKey() 69 | { 70 | return getType() + "_" + getAddressAsHexString(); 71 | } 72 | 73 | public Map getProperties() 74 | { 75 | Map properties = new HashMap<>(); 76 | properties.put(BjoernNodeProperties.KEY, getKey()); 77 | properties.put(BjoernNodeProperties.TYPE, getType()); 78 | properties.put(BjoernNodeProperties.ADDR, getAddressAsHexString()); 79 | properties.put(BjoernNodeProperties.COMMENT, getComment()); 80 | return properties; 81 | } 82 | 83 | @Override 84 | public String toString() 85 | { 86 | return getKey(); 87 | } 88 | } 89 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/NodeKey.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | public final class NodeKey 4 | { 5 | private final String type; 6 | private final Long address; 7 | 8 | public NodeKey(long address, String type) 9 | { 10 | this.address = address; 11 | this.type = type; 12 | } 13 | 14 | @Override 15 | public boolean equals(Object o) 16 | { 17 | if (!(o instanceof NodeKey)) 18 | { 19 | return false; 20 | } 21 | NodeKey other = (NodeKey) o; 22 | 23 | return address.equals(other.address) && type.equals(other.type); 24 | } 25 | 26 | @Override 27 | public int hashCode() 28 | { 29 | int result = type.hashCode(); 30 | result = 31 * result + address.hashCode(); 31 | return result; 32 | } 33 | 34 | @Override 35 | public String toString() 36 | { 37 | return this.type + "_" + Long.toHexString(this.address); 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/RegisterFamily.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | public class RegisterFamily { 4 | private String name; 5 | private int start; 6 | private int end; 7 | 8 | public RegisterFamily(String name, int start, int end) 9 | { 10 | this.name = name; 11 | this.start = start; 12 | this.end = end; 13 | } 14 | 15 | public boolean overlaps(RegisterFamily otherFamily) 16 | { 17 | boolean overlap; 18 | 19 | return start <= otherFamily.end && end >= otherFamily.start; 20 | } 21 | 22 | public void merge(RegisterFamily otherFamily) 23 | { 24 | name = otherFamily.name; 25 | start = Math.min(start, otherFamily.start); 26 | end = Math.max(end, otherFamily.end); 27 | } 28 | 29 | public String getName() 30 | { 31 | return name; 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/RootNode.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures; 2 | 3 | public class RootNode extends Node 4 | { 5 | 6 | public static class Builder extends Node.Builder 7 | { 8 | public Builder(Long address) 9 | { 10 | super(address, BjoernNodeTypes.ROOT); 11 | } 12 | 13 | public RootNode build() 14 | { 15 | return new RootNode(this); 16 | } 17 | } 18 | 19 | public RootNode(Builder builder) 20 | { 21 | super(builder); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/annotations/Flag.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.annotations; 2 | 3 | import bjoern.structures.BjoernNodeProperties; 4 | import bjoern.structures.BjoernNodeTypes; 5 | import bjoern.structures.Node; 6 | 7 | import java.util.Map; 8 | 9 | /** 10 | * A flag is a concept from radare2. 11 | * It's essentially an annotation attached to an address. 12 | * It has a fixed value and a length, that is, the flag 13 | * is associated with a sub string of the binary. 14 | */ 15 | 16 | public class Flag extends Node 17 | { 18 | private final String value; 19 | private final long length; 20 | 21 | public static class Builder extends Node.Builder 22 | { 23 | private String value; 24 | private long length; 25 | 26 | public Builder(Long address) 27 | { 28 | super(address, BjoernNodeTypes.FLAG); 29 | } 30 | 31 | public Builder withValue(String value) 32 | { 33 | this.value = value; 34 | return this; 35 | } 36 | 37 | public Builder withLenght(long length) 38 | { 39 | this.length = length; 40 | return this; 41 | } 42 | 43 | public Flag build() 44 | { 45 | return new Flag(this); 46 | } 47 | } 48 | 49 | public Flag(Builder builder) 50 | { 51 | super(builder); 52 | this.value = builder.value; 53 | this.length = builder.length; 54 | } 55 | 56 | public String getValue() 57 | { 58 | return value; 59 | } 60 | 61 | public long getLength() 62 | { 63 | return length; 64 | } 65 | 66 | @Override 67 | public Map getProperties() 68 | { 69 | Map properties = super.getProperties(); 70 | properties.put(BjoernNodeProperties.CODE, getValue()); 71 | return properties; 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/edges/CallRef.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.edges; 2 | 3 | import bjoern.structures.NodeKey; 4 | 5 | public class CallRef extends Reference 6 | { 7 | public CallRef(NodeKey sourceKey, NodeKey destKey) 8 | { 9 | super(sourceKey, destKey, EdgeTypes.CALL); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/edges/ControlFlowEdge.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.edges; 2 | 3 | import bjoern.structures.NodeKey; 4 | 5 | public class ControlFlowEdge extends DirectedEdge 6 | { 7 | public ControlFlowEdge(NodeKey sourceKey, NodeKey destKey, String type) 8 | { 9 | super(sourceKey, destKey, type); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/edges/DirectedEdge.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.edges; 2 | 3 | import bjoern.structures.NodeKey; 4 | 5 | public class DirectedEdge 6 | { 7 | private NodeKey sourceKey; 8 | private NodeKey destKey; 9 | private String type; 10 | 11 | public DirectedEdge(NodeKey sourceKey, NodeKey destKey, String type) 12 | { 13 | setSourceKey(sourceKey); 14 | setDestKey(destKey); 15 | setType(type); 16 | } 17 | 18 | public NodeKey getSourceKey() 19 | { 20 | return sourceKey; 21 | } 22 | 23 | private void setSourceKey(NodeKey sourceKey) 24 | { 25 | this.sourceKey = sourceKey; 26 | } 27 | 28 | public NodeKey getDestKey() 29 | { 30 | return destKey; 31 | } 32 | 33 | private void setDestKey(NodeKey destKey) 34 | { 35 | this.destKey = destKey; 36 | } 37 | 38 | public String getType() 39 | { 40 | return type; 41 | } 42 | 43 | private void setType(String type) 44 | { 45 | this.type = type; 46 | } 47 | 48 | @Override 49 | public String toString() 50 | { 51 | return "(" + sourceKey + ")--[" + type + "]-->(" + destKey + ")"; 52 | } 53 | } 54 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/edges/EdgeTypes.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.edges; 2 | 3 | public class EdgeTypes 4 | { 5 | public static final String CFLOW = "CFLOW_ALWAYS"; 6 | public static final String CFLOW_TRUE = "CFLOW_TRUE"; 7 | public static final String CFLOW_FALSE = "CFLOW_FALSE"; 8 | public static final String IS_BB_OF = "IS_BB_OF"; 9 | public static final String IS_FUNCTION_OF = "IS_FUNC_OF"; 10 | public static final String CALL = "CALL"; 11 | public static final String ANNOTATION = "IS_ANNOTATED_BY"; 12 | public static final String INTERPRETATION = "INTERPRETABLE_AS"; 13 | public static final String READ = "READ"; 14 | public static final String WRITE = "WRITE"; 15 | 16 | } 17 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/edges/Reference.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.edges; 2 | 3 | import bjoern.structures.NodeKey; 4 | 5 | public abstract class Reference extends DirectedEdge 6 | { 7 | public Reference(NodeKey sourceKey, NodeKey destKey, String type) 8 | { 9 | super(sourceKey, destKey, type); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/interpretations/Function.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.interpretations; 2 | 3 | import bjoern.structures.BjoernNodeProperties; 4 | import bjoern.structures.BjoernNodeTypes; 5 | import bjoern.structures.Node; 6 | 7 | import java.util.Map; 8 | 9 | 10 | public class Function extends Node 11 | { 12 | 13 | private final FunctionContent content; 14 | private final String name; 15 | 16 | public static class Builder extends Node.Builder 17 | { 18 | 19 | private String name; 20 | private FunctionContent content; 21 | 22 | public Builder(Long address) 23 | { 24 | super(address, BjoernNodeTypes.FUNCTION); 25 | } 26 | 27 | public Builder withName(String name) 28 | { 29 | this.name = name; 30 | return this; 31 | } 32 | 33 | public Builder withContent(FunctionContent content) 34 | { 35 | this.content = content; 36 | return this; 37 | } 38 | 39 | public Function build() 40 | { 41 | return new Function(this); 42 | } 43 | 44 | } 45 | 46 | public Function(Builder builder) 47 | { 48 | super(builder); 49 | this.name = builder.name; 50 | this.content = builder.content; 51 | } 52 | 53 | public FunctionContent getContent() 54 | { 55 | return content; 56 | } 57 | 58 | public String getName() 59 | { 60 | return name; 61 | } 62 | 63 | @Override 64 | public Map getProperties() 65 | { 66 | Map properties = super.getProperties(); 67 | properties.put(BjoernNodeProperties.REPR, getName()); 68 | return properties; 69 | } 70 | } 71 | -------------------------------------------------------------------------------- /projects/bjoern-r2interface/src/main/java/bjoern/structures/interpretations/FunctionContent.java: -------------------------------------------------------------------------------- 1 | package bjoern.structures.interpretations; 2 | 3 | import bjoern.r2interface.exceptions.InvalidRadareFunctionException; 4 | import bjoern.structures.edges.ControlFlowEdge; 5 | import bjoern.structures.edges.DirectedEdge; 6 | 7 | import java.util.Collection; 8 | import java.util.HashMap; 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | 12 | public class FunctionContent 13 | { 14 | HashMap basicBlocks = new HashMap(); 15 | List controlFlowEdges = new LinkedList(); 16 | 17 | public Collection getBasicBlocks() 18 | { 19 | return basicBlocks.values(); 20 | } 21 | 22 | public List getControlFlowEdges() 23 | { 24 | return controlFlowEdges; 25 | } 26 | 27 | public BasicBlock getBasicBlockAtAddress(long addr) 28 | { 29 | return basicBlocks.get(addr); 30 | } 31 | 32 | public void addBasicBlock(long addr, BasicBlock node) 33 | { 34 | // TODO: It should be enough to pass node and 35 | // read its address from the respective field. 36 | basicBlocks.put(addr, node); 37 | } 38 | 39 | public void registerBasicBlock(BasicBlock node) throws InvalidRadareFunctionException 40 | { 41 | BasicBlock block = getBasicBlockAtAddress(node.getAddress()); 42 | 43 | if (block != null) 44 | throw new InvalidRadareFunctionException("Duplicate basic block in function"); 45 | 46 | addBasicBlock(node.getAddress(), node); 47 | } 48 | 49 | public void addControlFlowEdge(ControlFlowEdge edge) 50 | { 51 | controlFlowEdges.add(edge); 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /projects/octopus/.gitrepo: -------------------------------------------------------------------------------- 1 | ; DO NOT EDIT (unless you know what you are doing) 2 | ; 3 | ; This subdirectory is a git "subrepo", and this file is maintained by the 4 | ; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme 5 | ; 6 | [subrepo] 7 | remote = git@github.com:octopus-platform/octopus.git 8 | branch = master 9 | commit = 1498f074e8b1e8c5c883ef1d6ee6795caaf34109 10 | parent = 9ddd71ff1aefeab6b33cd6bed29541a56f2f3407 11 | cmdver = 0.3.0 12 | -------------------------------------------------------------------------------- /projects/octopus/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /projects/octopus/octopus-lang/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | 3 | task copyLang(type:Copy) { 4 | from "${project.projectDir}/src/main/groovy/" 5 | into "${project.projectDir}/../octopus-server/querylib/octopus/" 6 | } 7 | 8 | build.dependsOn copyLang 9 | -------------------------------------------------------------------------------- /projects/octopus/octopus-lang/src/main/groovy/exampleStep.groovy: -------------------------------------------------------------------------------- 1 | exStep = { args -> 2 | _().nodeType 3 | } 4 | -------------------------------------------------------------------------------- /projects/octopus/octopus-lang/src/main/groovy/lookup.groovy: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/projects/octopus/octopus-lang/src/main/groovy/lookup.groovy -------------------------------------------------------------------------------- /projects/octopus/octopus-server/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/octopus-server.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | 4 | MAXHEAP="-Xmx${OCTOPUS_SERVER_MAXHEAP:-512m}" 5 | MAXDISKCACHE="-Dstorage.diskCache.bufferSize=${OCTOPUS_SERVER_MAXDISKCACHE:-8192}" 6 | OPTS_FROM_ORIENTDB="-server -Djna.nosys=true -XX:+HeapDumpOnOutOfMemoryError -Djava.awt.headless=true -Dfile.encoding=UTF8 -Drhino.opt.level=9 -Dprofiler.enabled=true" 7 | 8 | OCTOPUS_HOME=`dirname $0` 9 | 10 | exec java $JAVA_OPTS $MAXHEAP $MAXDISKCACHE $OPTS_FROM_ORIENTDB -DOCTOPUS_HOME="$OCTOPUS_HOME" -cp "$OCTOPUS_HOME/jars/*" octopus.OctopusMain 11 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/OctopusMain.java: -------------------------------------------------------------------------------- 1 | package octopus; 2 | 3 | import com.orientechnologies.orient.server.OServer; 4 | import com.orientechnologies.orient.server.OServerMain; 5 | 6 | import octopus.server.components.ftpserver.OctopusFTPServer; 7 | 8 | public class OctopusMain { 9 | 10 | static OctopusMain main; 11 | String octopusHome; 12 | OServer server; 13 | OctopusFTPServer ftpServer; 14 | 15 | public static void main(String[] args) throws java.lang.Exception 16 | { 17 | main = new OctopusMain(); 18 | main.startOrientdb(); 19 | main.startFTPServer(); 20 | } 21 | 22 | public OctopusMain() 23 | { 24 | initializeOctopusHome(); 25 | } 26 | 27 | private void initializeOctopusHome() 28 | { 29 | octopusHome = System.getProperty("OCTOPUS_HOME"); 30 | 31 | if (octopusHome == null) 32 | { 33 | throw new RuntimeException("System property OCTOPUS_HOME not defined."); 34 | } 35 | } 36 | 37 | public void startOrientdb() throws java.lang.Exception 38 | { 39 | System.setProperty("ORIENTDB_HOME",octopusHome + "/orientdb"); 40 | System.setProperty("orientdb.www.path",octopusHome +"/orientdb/www"); 41 | System.setProperty("orientdb.config.file", octopusHome + "/conf/orientdb-server-config.xml"); 42 | 43 | server = OServerMain.create(); 44 | server.startup(); 45 | server.activate(); 46 | } 47 | 48 | private void startFTPServer() 49 | { 50 | ftpServer = new OctopusFTPServer(); 51 | ftpServer.start(octopusHome); 52 | } 53 | 54 | public void stopOrientdb() 55 | { 56 | server.shutdown(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/GraphOperations.java: -------------------------------------------------------------------------------- 1 | package octopus.lib; 2 | 3 | import java.util.Map; 4 | import java.util.Map.Entry; 5 | 6 | import com.tinkerpop.blueprints.Direction; 7 | import com.tinkerpop.blueprints.Edge; 8 | import com.tinkerpop.blueprints.Graph; 9 | import com.tinkerpop.blueprints.Vertex; 10 | 11 | import octopus.lib.structures.OctopusNode; 12 | 13 | public class GraphOperations 14 | { 15 | 16 | /** 17 | * Add an edge from the node src to the node dst if it does 18 | * not already exist. 19 | * 20 | * @param src the source of the edge 21 | * @param dst the destination of the edge 22 | */ 23 | public static void addEdge(Graph graph, OctopusNode src, OctopusNode dst, String edgeType) 24 | { 25 | for (Edge edge : src.getBaseVertex().getEdges(Direction.OUT, 26 | edgeType)) 27 | { 28 | if (edge.getVertex(Direction.IN).equals(dst.getBaseVertex())) 29 | { 30 | return; 31 | } 32 | } 33 | graph.addEdge(0, src.getBaseVertex(), dst.getBaseVertex(), edgeType); 34 | } 35 | 36 | public static Vertex addNode(Graph graph, Map properties) 37 | { 38 | Vertex newVertex = graph.addVertex(0); 39 | 40 | for (Entry entrySet : properties.entrySet()) 41 | { 42 | newVertex.setProperty(entrySet.getKey(), entrySet.getValue()); 43 | } 44 | return newVertex; 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/OctopusProjectWrapper.java: -------------------------------------------------------------------------------- 1 | package octopus.lib; 2 | 3 | import octopus.server.components.projectmanager.OctopusProject; 4 | 5 | public class OctopusProjectWrapper { 6 | 7 | private OctopusProject oProject; 8 | 9 | public void setWrappedProject(OctopusProject project) 10 | { 11 | oProject = project; 12 | } 13 | 14 | public String getPathToProjectDir() 15 | { 16 | return oProject.getPathToProjectDir(); 17 | } 18 | 19 | public String getDatabaseName() 20 | { 21 | return oProject.getDatabaseName(); 22 | } 23 | 24 | } 25 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/connectors/OctopusProjectConnector.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.connectors; 2 | 3 | import octopus.lib.OctopusProjectWrapper; 4 | import octopus.server.components.projectmanager.OctopusProject; 5 | import octopus.server.components.projectmanager.ProjectManager; 6 | 7 | public abstract class OctopusProjectConnector { 8 | 9 | OctopusProjectWrapper wrapper; 10 | 11 | public void connect(String projectName) 12 | { 13 | wrapper = openProject(projectName); 14 | } 15 | 16 | protected OctopusProjectWrapper openProject(String projectName) 17 | { 18 | OctopusProject oProject = ProjectManager.getProjectByName(projectName); 19 | if(oProject == null) 20 | throw new RuntimeException("Error: project does not exist"); 21 | 22 | return createNewProject(oProject); 23 | } 24 | 25 | protected abstract OctopusProjectWrapper createNewProject(OctopusProject oProject); 26 | 27 | public void disconnect() 28 | { 29 | // TODO Auto-generated method stub 30 | } 31 | 32 | public OctopusProjectWrapper getWrapper() 33 | { 34 | return wrapper; 35 | } 36 | 37 | 38 | } 39 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/connectors/OrientDBConnector.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.connectors; 2 | 3 | import com.tinkerpop.blueprints.impls.orient.OrientGraph; 4 | import com.tinkerpop.blueprints.impls.orient.OrientGraphFactory; 5 | import com.tinkerpop.blueprints.impls.orient.OrientGraphNoTx; 6 | 7 | 8 | public class OrientDBConnector { 9 | 10 | private static final int MAX_POOL_SIZE = 10; 11 | private OrientGraphFactory graphFactory; 12 | 13 | public void connect(String databaseName) 14 | { 15 | graphFactory = new OrientGraphFactory( 16 | "plocal:" + System.getProperty("ORIENTDB_HOME") + "/databases/" + databaseName) 17 | .setupPool(1, MAX_POOL_SIZE); 18 | } 19 | 20 | public OrientGraphNoTx getNoTxGraphInstance() 21 | { 22 | return graphFactory.getNoTx(); 23 | } 24 | 25 | public OrientGraph getGraphInstance() 26 | { 27 | return graphFactory.getTx(); 28 | } 29 | 30 | public void disconnect() 31 | { 32 | graphFactory.close(); 33 | } 34 | 35 | } 36 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/plugintypes/OctopusProjectPlugin.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.plugintypes; 2 | 3 | import java.io.IOException; 4 | 5 | import org.json.JSONObject; 6 | 7 | import com.orientechnologies.orient.client.remote.OServerAdmin; 8 | 9 | import octopus.lib.connectors.OctopusProjectConnector; 10 | import octopus.server.components.pluginInterface.Plugin; 11 | import orientdbimporter.Constants; 12 | 13 | public abstract class OctopusProjectPlugin implements Plugin 14 | { 15 | 16 | private OctopusProjectConnector projectConnector; 17 | 18 | protected void setProjectConnector(OctopusProjectConnector connector) 19 | { 20 | this.projectConnector = connector; 21 | } 22 | 23 | @Override 24 | public void configure(JSONObject settings) 25 | { 26 | String projectName = settings.getString("projectName"); 27 | getProjectConnector().connect(projectName); 28 | } 29 | 30 | protected void raiseIfDatabaseForProjectExists() 31 | { 32 | String dbName = getProjectConnector().getWrapper().getDatabaseName(); 33 | 34 | boolean databaseExists = doesDatabaseExist(dbName); 35 | if (databaseExists) 36 | throw new RuntimeException("Database already exists. Skipping."); 37 | } 38 | 39 | private boolean doesDatabaseExist(String dbName) 40 | { 41 | try 42 | { 43 | return new OServerAdmin("localhost/" + dbName).connect( 44 | Constants.DB_USERNAME, Constants.DB_PASSWORD).existsDatabase(); 45 | 46 | } catch (IOException e) 47 | { 48 | throw new RuntimeException("Error determining whether database exists"); 49 | } 50 | } 51 | 52 | protected OctopusProjectConnector getProjectConnector() 53 | { 54 | return projectConnector; 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/plugintypes/OrientGraphConnectionPlugin.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.plugintypes; 2 | 3 | import org.json.JSONObject; 4 | 5 | import octopus.lib.connectors.OrientDBConnector; 6 | import octopus.server.components.pluginInterface.Plugin; 7 | 8 | public abstract class OrientGraphConnectionPlugin implements Plugin 9 | { 10 | private String databaseName; 11 | protected OrientDBConnector orientConnector = new OrientDBConnector(); 12 | 13 | @Override 14 | public void configure(JSONObject settings) 15 | { 16 | databaseName = settings.getString("database"); 17 | } 18 | 19 | @Override 20 | public void beforeExecution() throws Exception 21 | { 22 | orientConnector.connect(databaseName); 23 | } 24 | 25 | @Override 26 | public void afterExecution() throws Exception 27 | { 28 | orientConnector.disconnect(); 29 | } 30 | 31 | 32 | public String getDatabaseName() 33 | { 34 | return databaseName; 35 | } 36 | 37 | } 38 | 39 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/structures/OctopusNode.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.structures; 2 | 3 | import com.tinkerpop.blueprints.Vertex; 4 | import com.tinkerpop.blueprints.util.wrappers.wrapped.WrappedElement; 5 | 6 | public abstract class OctopusNode extends WrappedElement implements Vertex 7 | { 8 | 9 | public OctopusNode(Vertex vertex) 10 | { 11 | super(vertex); 12 | if (vertex == null) 13 | { 14 | throw new IllegalArgumentException("vertex must not be null."); 15 | } 16 | } 17 | 18 | public OctopusNode(Vertex vertex, String nodeType) 19 | { 20 | this(vertex); 21 | if (!vertex.getProperty(OctopusNodeProperties.TYPE).equals(nodeType)) 22 | { 23 | throw new IllegalArgumentException("Invalid node. Expected a node of type " + nodeType + " was " + vertex 24 | .getProperty(OctopusNodeProperties.TYPE)); 25 | } 26 | } 27 | 28 | public Vertex getBaseVertex() 29 | { 30 | return (Vertex) getBaseElement(); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/lib/structures/OctopusNodeProperties.java: -------------------------------------------------------------------------------- 1 | package octopus.lib.structures; 2 | 3 | public class OctopusNodeProperties { 4 | 5 | public static final String TYPE = "nodeType"; 6 | public static final String SUBTYPE = "subType"; 7 | public static final String KEY = "key"; 8 | 9 | } 10 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/Constants.java: -------------------------------------------------------------------------------- 1 | package octopus.server; 2 | 3 | public class Constants 4 | { 5 | 6 | public static final String DEFAULT_DB_NAME = "bjoernDB"; 7 | 8 | public static final String DB_USERNAME = "root"; 9 | public static final String DB_PASSWORD = "admin"; 10 | 11 | public static final int MAX_NODES_FOR_KEY = 128; 12 | 13 | } 14 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/commands/importcsv/ImportCSVHandler.java: -------------------------------------------------------------------------------- 1 | package octopus.server.commands.importcsv; 2 | 3 | import org.slf4j.Logger; 4 | import org.slf4j.LoggerFactory; 5 | 6 | import com.orientechnologies.common.log.OLogManager; 7 | import com.orientechnologies.orient.server.config.OServerCommandConfiguration; 8 | import com.orientechnologies.orient.server.network.protocol.http.OHttpRequest; 9 | import com.orientechnologies.orient.server.network.protocol.http.OHttpResponse; 10 | import com.orientechnologies.orient.server.network.protocol.http.OHttpUtils; 11 | import com.orientechnologies.orient.server.network.protocol.http.command.OServerCommandAbstract; 12 | 13 | import octopus.server.components.orientdbImporter.ImportCSVRunnable; 14 | import octopus.server.components.orientdbImporter.ImportJob; 15 | 16 | public class ImportCSVHandler extends OServerCommandAbstract 17 | { 18 | 19 | private static final Logger logger = LoggerFactory 20 | .getLogger(ImportCSVHandler.class); 21 | 22 | public ImportCSVHandler(final OServerCommandConfiguration iConfiguration) 23 | { 24 | } 25 | 26 | @Override 27 | public boolean execute(OHttpRequest iRequest, OHttpResponse iResponse) 28 | throws Exception 29 | { 30 | logger.info("Importer called"); 31 | 32 | ImportJob importJob = getImportJobFromRequest(iRequest); 33 | (new ImportCSVRunnable(importJob)).run(); 34 | 35 | iResponse.send(OHttpUtils.STATUS_OK_CODE, "OK", null, 36 | OHttpUtils.CONTENT_TEXT_PLAIN, ""); 37 | 38 | OLogManager.instance().warn(this, "Response sent."); 39 | 40 | return false; 41 | } 42 | 43 | private ImportJob getImportJobFromRequest(OHttpRequest iRequest) 44 | { 45 | String[] urlParts = checkSyntax( 46 | iRequest.url, 47 | 4, 48 | "Syntax error: importcsv////"); 49 | 50 | return new ImportJob(urlParts[1], urlParts[2], urlParts[3]); 51 | } 52 | 53 | @Override 54 | public String[] getNames() 55 | { 56 | return new String[] { "GET|importcsv/*" }; 57 | } 58 | 59 | } 60 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/GroovyFileLoader.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell; 2 | 3 | import groovy.lang.GroovyShell; 4 | import octopus.server.components.gremlinShell.fileWalker.SourceFileListener; 5 | 6 | import java.io.IOException; 7 | import java.nio.file.Path; 8 | 9 | import org.codehaus.groovy.control.CompilationFailedException; 10 | import org.slf4j.Logger; 11 | import org.slf4j.LoggerFactory; 12 | 13 | public class GroovyFileLoader extends SourceFileListener 14 | { 15 | 16 | private static final Logger logger = LoggerFactory 17 | .getLogger(GroovyFileLoader.class); 18 | 19 | private GroovyShell groovyShell; 20 | 21 | public void setGroovyShell(GroovyShell groovyshell) 22 | { 23 | this.groovyShell = groovyshell; 24 | } 25 | 26 | @Override 27 | public void visitFile(Path filename) 28 | { 29 | try 30 | { 31 | groovyShell.evaluate(filename.toFile()); 32 | } 33 | catch (CompilationFailedException e) 34 | { 35 | logger.warn("Compilation failure for standard library: {}", 36 | e.getMessage()); 37 | } 38 | catch (IOException e) 39 | { 40 | // TODO Auto-generated catch block 41 | e.printStackTrace(); 42 | } 43 | } 44 | 45 | @Override 46 | public void initialize() 47 | { 48 | } 49 | 50 | @Override 51 | public void shutdown() 52 | { 53 | } 54 | 55 | @Override 56 | public void preVisitDirectory(Path dir) 57 | { 58 | } 59 | 60 | @Override 61 | public void postVisitDirectory(Path dir) 62 | { 63 | } 64 | 65 | } 66 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/OctopusCompilerConfiguration.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell; 2 | 3 | import java.util.ArrayList; 4 | import java.util.List; 5 | 6 | import org.codehaus.groovy.control.CompilerConfiguration; 7 | import org.codehaus.groovy.control.customizers.ImportCustomizer; 8 | 9 | import com.tinkerpop.gremlin.Imports; 10 | 11 | public class OctopusCompilerConfiguration extends CompilerConfiguration 12 | { 13 | 14 | public OctopusCompilerConfiguration() 15 | { 16 | this.setScriptBaseClass(OctopusScriptBase.class.getName()); 17 | this.addCompilationCustomizers(new BjoernImportCustomizer()); 18 | } 19 | 20 | } 21 | 22 | class BjoernImportCustomizer extends ImportCustomizer 23 | { 24 | 25 | private static final List imports = new ArrayList(); 26 | 27 | static 28 | { 29 | imports.addAll(Imports.getImports()); 30 | imports.add("com.tinkerpop.gremlin.Tokens.T"); 31 | imports.add("com.tinkerpop.gremlin.groovy.*"); 32 | imports.add("groovy.grape.Grape"); 33 | } 34 | 35 | public BjoernImportCustomizer() 36 | { 37 | for (String s : imports) 38 | { 39 | String importString = new String(s); 40 | byte mask = 0b00; 41 | if (importString.endsWith(".*")) 42 | { 43 | importString = importString.substring(0, 44 | importString.lastIndexOf(".*")); 45 | mask |= 0b01; 46 | } 47 | if (importString.startsWith("static")) 48 | { 49 | importString = importString.substring(7); 50 | mask |= 0b10; 51 | } 52 | switch (mask) 53 | { 54 | case 0b00: 55 | addImports(importString); 56 | break; 57 | case 0b01: 58 | addStarImports(importString); 59 | break; 60 | case 0b10: 61 | break; 62 | case 0b11: 63 | addStaticStars(importString); 64 | break; 65 | } 66 | } 67 | } 68 | 69 | } -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/OctopusScriptBase.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell; 2 | 3 | import groovy.lang.Script; 4 | 5 | import java.util.Set; 6 | 7 | import com.tinkerpop.gremlin.groovy.Gremlin; 8 | 9 | public abstract class OctopusScriptBase extends Script 10 | { 11 | 12 | public Set listSteps() 13 | { 14 | return Gremlin.getStepNames(); 15 | } 16 | 17 | public Set listSteps(String prefix) 18 | { 19 | Set steps = listSteps(); 20 | steps.removeIf(step -> !step.startsWith(prefix)); 21 | return steps; 22 | } 23 | 24 | public Set listVariables() 25 | { 26 | return getBinding().getVariables().keySet(); 27 | } 28 | 29 | public void removeVariable(String variable) 30 | { 31 | getBinding().getVariables().remove(variable); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/fileWalker/FileNameMatcher.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.fileWalker; 2 | 3 | import java.nio.file.FileSystems; 4 | import java.nio.file.Path; 5 | import java.nio.file.PathMatcher; 6 | 7 | public class FileNameMatcher 8 | { 9 | private PathMatcher matcher; 10 | 11 | public void setFilenameFilter(String pattern) 12 | { 13 | // TODO Auto-generated method stub 14 | matcher = FileSystems.getDefault().getPathMatcher("glob:" + pattern); 15 | } 16 | 17 | public boolean fileMatches(Path file) 18 | { 19 | Path name = file.getFileName(); 20 | if (name == null) 21 | return false; 22 | return matcher.matches(name); 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/fileWalker/SourceFileListener.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.fileWalker; 2 | 3 | import java.nio.file.Path; 4 | 5 | /** 6 | * Abstract base class for classes observing the SourceFileWalker. 7 | */ 8 | 9 | public abstract class SourceFileListener 10 | { 11 | abstract public void initialize(); 12 | 13 | abstract public void shutdown(); 14 | 15 | abstract public void visitFile(Path filename); 16 | 17 | abstract public void preVisitDirectory(Path dir); 18 | 19 | abstract public void postVisitDirectory(Path dir); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/fileWalker/SourceFileWalker.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.fileWalker; 2 | 3 | import java.io.File; 4 | import java.io.IOException; 5 | 6 | public abstract class SourceFileWalker 7 | { 8 | protected final String DEFAULT_FILENAME_FILTER = "*.{c,cpp,h,cc,hpp,java}"; 9 | 10 | public abstract void setFilenameFilter(String filter); 11 | 12 | /** 13 | * Add a listener object that will be informed of all visited source files 14 | * and directories. 15 | */ 16 | 17 | public abstract void addListener(SourceFileListener listener); 18 | 19 | /** 20 | * Walk list of files and directory names and report them to listeners. 21 | * 22 | * @param fileAndDirNames: 23 | * A list of file and/or directory names 24 | */ 25 | 26 | public void walk(String[] fileAndDirNames) throws IOException 27 | { 28 | for (String filename : fileAndDirNames) 29 | { 30 | 31 | if (!pathIsAccessible(filename)) 32 | { 33 | System.err.println("Warning: Skipping " + filename 34 | + " because it is not accessible"); 35 | continue; 36 | } 37 | walkExistingFileOrDirectory(filename); 38 | } 39 | } 40 | 41 | protected abstract void walkExistingFileOrDirectory(String dirName) 42 | throws IOException; 43 | 44 | private boolean pathIsAccessible(String path) 45 | { 46 | File file = new File(path); 47 | if (!file.exists()) 48 | return false; 49 | 50 | // TODO: add more checks, for example, do we have sufficient 51 | // permissions for access? 52 | 53 | return true; 54 | } 55 | 56 | } -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/fileWalker/UnorderedFileWalkerImpl.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.fileWalker; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.FileVisitResult; 5 | import java.nio.file.Path; 6 | import java.nio.file.SimpleFileVisitor; 7 | import java.nio.file.attribute.BasicFileAttributes; 8 | import java.util.LinkedList; 9 | import java.util.List; 10 | 11 | class UnorderedFileWalkerImpl extends SimpleFileVisitor 12 | { 13 | private FileNameMatcher matcher = new FileNameMatcher(); 14 | private List listeners = new LinkedList(); 15 | 16 | public void setFilenameFilter(String pattern) 17 | { 18 | matcher.setFilenameFilter(pattern); 19 | } 20 | 21 | public void addListener(SourceFileListener listener) 22 | { 23 | listeners.add(listener); 24 | } 25 | 26 | @Override 27 | public FileVisitResult preVisitDirectory(Path dir, 28 | BasicFileAttributes attrs) 29 | { 30 | notifyListenersOfDirEntry(dir); 31 | return FileVisitResult.CONTINUE; 32 | } 33 | 34 | private void notifyListenersOfDirEntry(Path dir) 35 | { 36 | for (SourceFileListener listener : listeners) 37 | { 38 | listener.preVisitDirectory(dir); 39 | } 40 | } 41 | 42 | @Override 43 | public FileVisitResult postVisitDirectory(Path dir, IOException exc) 44 | { 45 | notifyListenersOfDirExit(dir); 46 | return FileVisitResult.CONTINUE; 47 | } 48 | 49 | private void notifyListenersOfDirExit(Path dir) 50 | { 51 | for (SourceFileListener listener : listeners) 52 | { 53 | listener.postVisitDirectory(dir); 54 | } 55 | } 56 | 57 | @Override 58 | public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) 59 | { 60 | 61 | if (!matcher.fileMatches(file)) 62 | { 63 | return FileVisitResult.CONTINUE; 64 | } 65 | 66 | notifyListenersOfFile(file); 67 | return FileVisitResult.CONTINUE; 68 | } 69 | 70 | private void notifyListenersOfFile(Path filename) 71 | { 72 | for (SourceFileListener listener : listeners) 73 | { 74 | listener.visitFile(filename); 75 | } 76 | } 77 | 78 | } -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/fileWalker/UnorderedWalker.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.fileWalker; 2 | 3 | import java.io.IOException; 4 | import java.nio.file.Files; 5 | import java.nio.file.Path; 6 | import java.nio.file.Paths; 7 | 8 | public class UnorderedWalker extends SourceFileWalker 9 | { 10 | private UnorderedFileWalkerImpl sourceFileWalkerImpl = new UnorderedFileWalkerImpl(); 11 | 12 | public UnorderedWalker() 13 | { 14 | sourceFileWalkerImpl.setFilenameFilter(DEFAULT_FILENAME_FILTER); 15 | } 16 | 17 | public void setFilenameFilter(String filter) 18 | { 19 | sourceFileWalkerImpl.setFilenameFilter(filter); 20 | } 21 | 22 | public void addListener(SourceFileListener listener) 23 | { 24 | sourceFileWalkerImpl.addListener(listener); 25 | } 26 | 27 | protected void walkExistingFileOrDirectory(String dirName) 28 | throws IOException 29 | { 30 | Path dir = Paths.get(dirName); 31 | Files.walkFileTree(dir, sourceFileWalkerImpl); 32 | } 33 | 34 | } 35 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/io/BjoernClientReader.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.io; 2 | 3 | import java.io.IOException; 4 | import java.io.Reader; 5 | 6 | public class BjoernClientReader extends Reader 7 | { 8 | private Reader in; 9 | 10 | public BjoernClientReader(Reader in) 11 | { 12 | this.in = in; 13 | } 14 | 15 | @Override 16 | public void close() throws IOException 17 | { 18 | in.close(); 19 | } 20 | 21 | @Override 22 | public int read(char[] cbuf, int off, int len) throws IOException 23 | { 24 | return in.read(cbuf, off, len); 25 | } 26 | 27 | public String readMessage() throws IOException 28 | { 29 | StringBuilder builder = new StringBuilder(); 30 | int c; 31 | while ((c = in.read()) != -1) 32 | { 33 | // Messages end with "...\0" (NUL byte) 34 | if (c == '\0') 35 | { 36 | String message = builder.toString(); 37 | return message; 38 | } else 39 | { 40 | builder.append((char) c); 41 | } 42 | } 43 | return null; 44 | } 45 | 46 | } 47 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/gremlinShell/io/BjoernClientWriter.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.gremlinShell.io; 2 | 3 | import com.tinkerpop.pipes.Pipe; 4 | 5 | import java.io.BufferedWriter; 6 | import java.io.IOException; 7 | import java.io.Writer; 8 | 9 | public class BjoernClientWriter extends BufferedWriter 10 | { 11 | 12 | public BjoernClientWriter(Writer out) 13 | { 14 | super(out); 15 | } 16 | 17 | private void writeEndOfMessage() throws IOException 18 | { 19 | write("\0"); 20 | } 21 | 22 | public void writeMessage(String message) throws IOException 23 | { 24 | write(message); 25 | writeEndOfMessage(); 26 | flush(); 27 | } 28 | 29 | public void writeResult(Object result) throws IOException 30 | { 31 | if (result == null) 32 | { 33 | writeMessage(""); 34 | } else if (result instanceof Pipe) 35 | { 36 | StringBuilder sBuilder = new StringBuilder(); 37 | Iterable iterable = (Iterable) result; 38 | for (Object obj : iterable) 39 | { 40 | if (obj != null) 41 | { 42 | sBuilder.append(obj.toString()); 43 | sBuilder.append("\n"); 44 | } 45 | } 46 | if (sBuilder.length() > 0) 47 | { 48 | sBuilder.deleteCharAt(sBuilder.length() - 1); 49 | } 50 | writeMessage(sBuilder.toString()); 51 | } else 52 | { 53 | writeMessage(result.toString()); 54 | } 55 | } 56 | 57 | } 58 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/orientdbImporter/ImportCSVRunnable.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.orientdbImporter; 2 | 3 | import java.io.IOException; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import orientdbimporter.CSVBatchImporter; 9 | 10 | public class ImportCSVRunnable implements Runnable 11 | { 12 | 13 | private static final Logger logger = LoggerFactory 14 | .getLogger(ImportCSVRunnable.class); 15 | 16 | private final ImportJob importJob; 17 | 18 | public ImportCSVRunnable(ImportJob importJob) 19 | { 20 | this.importJob = importJob; 21 | } 22 | 23 | @Override 24 | public void run() 25 | { 26 | 27 | CSVBatchImporter csvBatchImporter = new CSVBatchImporter(); 28 | 29 | String nodeFilename = importJob.getNodeFilename(); 30 | String edgeFilename = importJob.getEdgeFilename(); 31 | 32 | String dbName = importJob.getDbName(); 33 | 34 | try 35 | { 36 | csvBatchImporter.setDbName(dbName); 37 | csvBatchImporter.importCSVFiles(nodeFilename, edgeFilename); 38 | } 39 | catch (IOException e) 40 | { 41 | e.printStackTrace(); 42 | } 43 | 44 | logger.info("Import finished"); 45 | } 46 | 47 | } 48 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/orientdbImporter/ImportJob.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.orientdbImporter; 2 | 3 | public class ImportJob 4 | { 5 | private final String nodeFilename; 6 | private final String edgeFilename; 7 | private final String dbName; 8 | 9 | public ImportJob(String nodeFilename, String edgeFilename, String dbName) 10 | { 11 | this.nodeFilename = nodeFilename; 12 | this.edgeFilename = edgeFilename; 13 | this.dbName = dbName; 14 | } 15 | 16 | public String getNodeFilename() 17 | { 18 | return nodeFilename; 19 | } 20 | 21 | public String getEdgeFilename() 22 | { 23 | return edgeFilename; 24 | } 25 | 26 | 27 | public String getDbName() 28 | { 29 | return dbName; 30 | } 31 | 32 | } -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/pluginInterface/Plugin.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.pluginInterface; 2 | 3 | import org.json.JSONObject; 4 | 5 | public interface Plugin 6 | { 7 | void configure(JSONObject settings); 8 | 9 | void execute() throws Exception; 10 | 11 | default void beforeExecution() throws Exception {} 12 | 13 | default void afterExecution() throws Exception {} 14 | 15 | default Object result() 16 | { 17 | return null; 18 | } 19 | } -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/pluginInterface/PluginLoader.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.pluginInterface; 2 | 3 | import java.nio.file.Path; 4 | 5 | public class PluginLoader 6 | { 7 | public static Plugin load(Path pathToJar, String pluginClass) 8 | { 9 | ClassLoader parentClassLoader = PluginClassLoader.class 10 | .getClassLoader(); 11 | PluginClassLoader classLoader = new PluginClassLoader( 12 | parentClassLoader); 13 | classLoader.setJarFilename(pathToJar.toString()); 14 | // It would be cleaner to put the name of the class implementing the 15 | // plugin somewhere in the jar. 16 | Class myObjectClass = classLoader.loadClass(pluginClass); 17 | try 18 | { 19 | return (Plugin) myObjectClass.newInstance(); 20 | } catch (Exception e) 21 | { 22 | return null; 23 | } 24 | } 25 | } 26 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/java/octopus/server/components/projectmanager/OctopusProject.java: -------------------------------------------------------------------------------- 1 | package octopus.server.components.projectmanager; 2 | 3 | public class OctopusProject 4 | { 5 | 6 | private final String pathToProjectDir; 7 | private final String databaseName; 8 | 9 | public OctopusProject(String pathToProjectDir, String databaseName) 10 | { 11 | this.pathToProjectDir = pathToProjectDir; 12 | this.databaseName = databaseName; 13 | } 14 | 15 | public String getPathToProjectDir() 16 | { 17 | return pathToProjectDir; 18 | } 19 | 20 | public String getDatabaseName() 21 | { 22 | return databaseName; 23 | } 24 | 25 | } 26 | -------------------------------------------------------------------------------- /projects/octopus/octopus-server/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies { 3 | compile group: 'com.orientechnologies', name: 'orientdb-core', version: '2.1.5' 4 | compile group: 'com.orientechnologies', name: 'orientdb-client', version: '2.1.5' 5 | compile group: 'com.orientechnologies', name: 'orientdb-graphdb', version: '2.1.5' 6 | compile group: 'com.tinkerpop.blueprints', name: 'blueprints-core', version: '2.6.0' 7 | compile group: 'com.opencsv', name: 'opencsv', version: '3.5' 8 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 9 | } 10 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/src/main/java/orientdbimporter/CSVBatchImporter.java: -------------------------------------------------------------------------------- 1 | package orientdbimporter; 2 | 3 | import java.io.IOException; 4 | 5 | import com.orientechnologies.orient.client.remote.OServerAdmin; 6 | import com.tinkerpop.blueprints.util.wrappers.batch.BatchGraph; 7 | 8 | import orientdbimporter.CSVImporter; 9 | import orientdbimporter.processors.EdgeProcessor; 10 | import orientdbimporter.processors.NodeProcessor; 11 | 12 | public class CSVBatchImporter extends CSVImporter 13 | { 14 | @Override 15 | protected void openDatabase() throws IOException 16 | { 17 | isNewDatabase = !databaseExists(dbName); 18 | openNoTxForMassiveInsert(); 19 | graph = BatchGraph.wrap(noTx, 1000); 20 | } 21 | 22 | @Override 23 | protected void processNodeFile(String filename) throws IOException 24 | { 25 | if (filename == null) 26 | return; 27 | (new NodeProcessor(this)).process(filename); 28 | } 29 | 30 | @Override 31 | protected void processEdgeFile(String filename) throws IOException 32 | { 33 | if (filename == null) 34 | return; 35 | (new EdgeProcessor(this)).process(filename); 36 | } 37 | 38 | private boolean databaseExists(String dbName) throws IOException 39 | { 40 | return new OServerAdmin("localhost/" + dbName).connect( 41 | Constants.DB_USERNAME, Constants.DB_PASSWORD).existsDatabase(); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/src/main/java/orientdbimporter/CSVCommands.java: -------------------------------------------------------------------------------- 1 | package orientdbimporter; 2 | 3 | public class CSVCommands { 4 | 5 | public static final String ADD = "A"; 6 | public static final String ADD_NO_REPLACE = "ANR"; 7 | 8 | } 9 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/src/main/java/orientdbimporter/Constants.java: -------------------------------------------------------------------------------- 1 | package orientdbimporter; 2 | 3 | 4 | public class Constants 5 | { 6 | 7 | public static final String DEFAULT_DB_NAME = "bjoernDB"; 8 | 9 | public static final String DB_USERNAME = "root"; 10 | public static final String DB_PASSWORD = "admin"; 11 | 12 | public static final int MAX_NODES_FOR_KEY = 128; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/src/main/java/orientdbimporter/processors/CSVFileProcessor.java: -------------------------------------------------------------------------------- 1 | package orientdbimporter.processors; 2 | 3 | import java.io.FileNotFoundException; 4 | import java.io.FileReader; 5 | import java.io.IOException; 6 | 7 | import com.opencsv.CSVReader; 8 | 9 | import orientdbimporter.CSVImporter; 10 | 11 | public abstract class CSVFileProcessor 12 | { 13 | protected final CSVImporter importer; 14 | 15 | public CSVFileProcessor(CSVImporter importer) 16 | { 17 | this.importer = importer; 18 | } 19 | 20 | public void process(String filename) throws IOException 21 | { 22 | CSVReader csvReader = getCSVReaderForFile(filename); 23 | 24 | String[] row = csvReader.readNext(); 25 | if (row == null) 26 | throw new RuntimeException("File must contain at least one line"); 27 | 28 | processFirstRow(csvReader, row); 29 | 30 | while ((row = csvReader.readNext()) != null) 31 | { 32 | processRow(row); 33 | } 34 | } 35 | 36 | protected abstract void processFirstRow(CSVReader csvReader, String[] row) 37 | throws IOException; 38 | 39 | protected abstract void processRow(String[] row); 40 | 41 | private CSVReader getCSVReaderForFile(String filename) 42 | throws FileNotFoundException 43 | { 44 | CSVReader reader; 45 | FileReader fileReader = new FileReader(filename); 46 | reader = new CSVReader(fileReader, '\t'); 47 | return reader; 48 | } 49 | 50 | protected String[] rowToKeys(String[] row) 51 | { 52 | String[] keys = new String[row.length]; 53 | for (int i = 0; i < row.length; i++) 54 | { 55 | keys[i] = row[i]; 56 | } 57 | return keys; 58 | } 59 | 60 | } 61 | -------------------------------------------------------------------------------- /projects/octopus/orientdbimporter/src/main/java/orientdbimporter/processors/EdgeProcessor.java: -------------------------------------------------------------------------------- 1 | package orientdbimporter.processors; 2 | 3 | import java.io.IOException; 4 | 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | 8 | import com.opencsv.CSVReader; 9 | import com.tinkerpop.blueprints.Edge; 10 | import com.tinkerpop.blueprints.Graph; 11 | import com.tinkerpop.blueprints.Vertex; 12 | 13 | import orientdbimporter.CSVImporter; 14 | 15 | public class EdgeProcessor extends CSVFileProcessor 16 | { 17 | private static final Logger logger = LoggerFactory 18 | .getLogger(EdgeProcessor.class); 19 | 20 | public EdgeProcessor(CSVImporter importer) 21 | { 22 | super(importer); 23 | } 24 | 25 | @Override 26 | protected void processFirstRow(CSVReader csvReader, String[] row) 27 | throws IOException 28 | { 29 | initializeEdgeKeys(row); 30 | } 31 | 32 | private void initializeEdgeKeys(String[] row) 33 | { 34 | String[] keys = rowToKeys(row); 35 | importer.setEdgeKeys(keys); 36 | } 37 | 38 | @Override 39 | protected void processRow(String[] row) 40 | { 41 | if (row.length < 3) 42 | return; 43 | 44 | String srcId = row[0]; 45 | String dstId = row[1]; 46 | String label = row[2]; 47 | 48 | Graph graph = importer.getGraph(); 49 | 50 | Vertex outVertex = lookupVertex(srcId, graph); 51 | Vertex inVertex = lookupVertex(dstId, graph); 52 | 53 | if (outVertex == null) 54 | { 55 | logger.info("Cannot resolve source node {} for {} -> {}", srcId, 56 | srcId, dstId); 57 | return; 58 | } 59 | 60 | if (inVertex == null) 61 | { 62 | logger.info("Cannot resolve destination node {} for {} -> {}", 63 | dstId, srcId, dstId); 64 | return; 65 | } 66 | 67 | Edge edge = graph.addEdge(0, outVertex, inVertex, label); 68 | 69 | for (int i = 3; i < row.length; i++) 70 | { 71 | edge.setProperty(importer.getEdgeKeys()[i], row[i]); 72 | } 73 | } 74 | 75 | protected Vertex lookupVertex(String id, Graph batchGraph) 76 | { 77 | return batchGraph.getVertex(id); 78 | } 79 | 80 | } 81 | -------------------------------------------------------------------------------- /projects/radare2csv/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /projects/radare2csv/build.gradle: -------------------------------------------------------------------------------- 1 | 2 | dependencies { 3 | compile group: 'commons-cli', name: 'commons-cli', version: '1.2' 4 | compile group: 'org.apache.commons', name: 'commons-lang3', version: '3.3.2' 5 | 6 | compile group: 'org.json', name: 'json', version: '20141113' 7 | 8 | compile project(':projects:bjoern-r2interface') 9 | 10 | compile group: 'org.slf4j', name: 'slf4j-api', version: '1.7.13' 11 | 12 | runtime group: 'ch.qos.logback', name: 'logback-core', version: '1.1.3' 13 | runtime group: 'ch.qos.logback', name: 'logback-classic', version: '1.1.3' 14 | 15 | } 16 | 17 | task copyToLib(type: Copy) { 18 | into "jars" 19 | from configurations.runtime 20 | } 21 | 22 | clean.dependsOn cleanCopyToLib 23 | copyToLib.dependsOn compileJava 24 | build.dependsOn copyToLib -------------------------------------------------------------------------------- /projects/radare2csv/radare2csv.sh: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | BASEDIR=$(dirname "$0") 4 | 5 | java -cp "$BASEDIR/build/libs/radare2csv.jar:$BASEDIR/jars/*" bjoern.input.radare.RadareExporterMain $@ 6 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/common/InputModule.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.common; 2 | 3 | import java.io.IOException; 4 | import java.util.Iterator; 5 | 6 | import bjoern.structures.annotations.Flag; 7 | import bjoern.structures.edges.CallRef; 8 | import bjoern.structures.interpretations.Function; 9 | 10 | public interface InputModule 11 | { 12 | void initialize(String filename, String projectFilename) throws IOException; 13 | 14 | void finish(String outputDir); 15 | 16 | Iterator getFunctions() throws IOException; 17 | 18 | Iterator getFlags() throws IOException; 19 | 20 | 21 | Iterator getCallReferences() throws IOException; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/common/outputModules/CSV/CSVOutputModule.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.common.outputModules.CSV; 2 | 3 | import bjoern.input.common.outputModules.OutputModule; 4 | import bjoern.structures.Node; 5 | import bjoern.structures.edges.DirectedEdge; 6 | 7 | import java.io.IOException; 8 | import java.util.HashMap; 9 | import java.util.Map; 10 | 11 | public class CSVOutputModule implements OutputModule 12 | { 13 | 14 | @Override 15 | public void initialize(String outputDir) throws IOException 16 | { 17 | CSVWriter.changeOutputDir(outputDir); 18 | } 19 | 20 | @Override 21 | public void finish() 22 | { 23 | CSVWriter.finish(); 24 | } 25 | 26 | @Override 27 | public void writeNode(Node node) 28 | { 29 | CSVWriter.writeNode(node); 30 | } 31 | 32 | @Override 33 | public void writeNodeNoReplace(Node node) 34 | { 35 | CSVWriter.writeNoReplaceNode(node); 36 | } 37 | 38 | @Override 39 | public void writeEdge(DirectedEdge edge) 40 | { 41 | CSVWriter.writeEdge(edge); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/common/outputModules/OutputModule.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.common.outputModules; 2 | 3 | import bjoern.structures.Node; 4 | import bjoern.structures.edges.DirectedEdge; 5 | 6 | import java.io.IOException; 7 | 8 | public interface OutputModule 9 | { 10 | 11 | void initialize(String outputDir) throws IOException; 12 | 13 | void finish(); 14 | 15 | void writeNode(Node node); 16 | 17 | void writeNodeNoReplace(Node node); 18 | 19 | void writeEdge(DirectedEdge edge); 20 | 21 | } 22 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/radare/CommandLineInterface.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.radare; 2 | 3 | import org.apache.commons.cli.Option; 4 | import org.apache.commons.cli.OptionBuilder; 5 | import org.apache.commons.cli.ParseException; 6 | 7 | public class CommandLineInterface extends CommonCommandLineInterface 8 | { 9 | 10 | private String binaryFilename; 11 | private String outputDir = "."; 12 | private String projectFilename; 13 | 14 | @Override 15 | protected void initializeOptions() 16 | { 17 | super.initializeOptions(); 18 | 19 | Option outputDirectory = OptionBuilder.withArgName("outdir").hasArg() 20 | .withDescription("the directory the output will be written to") 21 | .create("outdir"); 22 | 23 | options.addOption(outputDirectory); 24 | } 25 | 26 | public String getBinaryFilename() 27 | { 28 | return binaryFilename; 29 | } 30 | 31 | public String getProjectFilename() 32 | { 33 | return projectFilename; 34 | } 35 | 36 | public void parseCommandLine(String[] args) throws ParseException 37 | { 38 | if (args.length == 0) 39 | throw new RuntimeException("Please supply a file to process"); 40 | 41 | cmd = parser.parse(options, args); 42 | 43 | if (cmd.hasOption("outdir")) 44 | outputDir = cmd.getOptionValue("outdir"); 45 | 46 | String[] arguments = cmd.getArgs(); 47 | binaryFilename = arguments[0]; 48 | if(arguments.length > 1) 49 | projectFilename = arguments[1]; 50 | 51 | } 52 | 53 | public void printHelp() 54 | { 55 | formater.printHelp("exporter ", options); 56 | } 57 | 58 | public String getOutputDir() 59 | { 60 | return outputDir; 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/radare/CommonCommandLineInterface.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.radare; 2 | 3 | 4 | import org.apache.commons.cli.BasicParser; 5 | import org.apache.commons.cli.CommandLine; 6 | import org.apache.commons.cli.CommandLineParser; 7 | import org.apache.commons.cli.HelpFormatter; 8 | import org.apache.commons.cli.Options; 9 | 10 | public class CommonCommandLineInterface 11 | { 12 | public CommonCommandLineInterface() 13 | { 14 | initializeOptions(); 15 | } 16 | 17 | protected void initializeOptions() 18 | { 19 | } 20 | 21 | protected Options options = new Options(); 22 | protected CommandLineParser parser = new BasicParser(); 23 | protected HelpFormatter formater = new HelpFormatter(); 24 | protected CommandLine cmd = null; 25 | 26 | } 27 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/java/bjoern/input/radare/RadareExporterMain.java: -------------------------------------------------------------------------------- 1 | package bjoern.input.radare; 2 | 3 | 4 | public class RadareExporterMain 5 | { 6 | 7 | public static void main(String[] args) 8 | { 9 | RadareExporter exporter = new RadareExporter(); 10 | exporter.run(args); 11 | } 12 | 13 | } 14 | -------------------------------------------------------------------------------- /projects/radare2csv/src/main/resources/logback.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 8 | 9 | %d{HH:mm:ss.SSS} [%thread] %-5level %logger{5} - %msg%n 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | -------------------------------------------------------------------------------- /python/bjoern-tools/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | 3 | .idea/ 4 | -------------------------------------------------------------------------------- /python/bjoern-tools/.gitrepo: -------------------------------------------------------------------------------- 1 | ; DO NOT EDIT (unless you know what you are doing) 2 | ; 3 | ; This subdirectory is a git "subrepo", and this file is maintained by the 4 | ; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme 5 | ; 6 | [subrepo] 7 | remote = git@github.com:octopus-platform/bjoern-tools.git 8 | branch = master 9 | commit = 42d69670cdd1e11762800b310bd46f6336dfac77 10 | parent = 5b92427012f2db89b480f8e88ef6a07c577903ad 11 | cmdver = 0.3.0 12 | -------------------------------------------------------------------------------- /python/bjoern-tools/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/bjoern-tools/bjoern/__init__.py -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/bjoern-tools/bjoern/plugins/__init__.py -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/alocs.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class Alocs(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = "alocs.jar" 8 | self._classname = "bjoern.plugins.alocs.AlocPlugin" 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["projectName"] = value 13 | else: 14 | super().__setattr__(key, value) 15 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/data_dependence.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class DataDependenceCreator(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = 'datadependence.jar' 8 | self._classname = 'bjoern.plugins.datadependence.DataDependencePlugin' 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["database"] = value 13 | else: 14 | super().__setattr__(key, value) 15 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/function_exporter.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class FunctionExporter(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = "functionexport.jar" 8 | self._classname = "bjoern.plugins.functionexporter.FunctionExportPlugin" 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["database"] = value 13 | elif key == "format": 14 | self._settings["format"] = value 15 | elif key == "outdir": 16 | self._settings["outdir"] = value 17 | elif key == "nodes": 18 | self._settings["nodes"] = value 19 | elif key == "edges": 20 | self._settings["edges"] = value 21 | elif key == "threads": 22 | self._settings["threads"] = value 23 | else: 24 | super().__setattr__(key, value) 25 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/instruction_linker.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class InstructionLinker(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = "instructionlinker.jar" 8 | self._classname = "bjoern.plugins.instructionlinker.InstructionLinkerPlugin" 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["database"] = value 13 | else: 14 | super().__setattr__(key, value) 15 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/use_def_analyser.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class UseDefAnalyser(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = 'usedefanalyser.jar' 8 | self._classname = 'bjoern.plugins.usedefanalyser.UseDefAnalyserPlugin' 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["database"] = value 13 | else: 14 | super().__setattr__(key, value) 15 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/plugins/vsa.py: -------------------------------------------------------------------------------- 1 | from octopus.plugins.plugin import OctopusPlugin 2 | 3 | 4 | class VSA(OctopusPlugin): 5 | def __init__(self, executor): 6 | super().__init__(executor) 7 | self._pluginname = 'vsa.jar' 8 | self._classname = 'bjoern.plugins.vsa.VSAPlugin' 9 | 10 | def __setattr__(self, key, value): 11 | if key == "project": 12 | self._settings["database"] = value 13 | else: 14 | super().__setattr__(key, value) 15 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/bjoern-tools/bjoern/shell/__init__.py -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/bjoern_console.py: -------------------------------------------------------------------------------- 1 | import os 2 | import sys 3 | 4 | from octopus.shell.octopus_console import OctopusInteractiveConsole 5 | from octopus.shell.onlinehelp.online_help import OnlineHelp 6 | from bjoern.shell.config.config import config 7 | from octopus.shell.octopus_shell_utils import reload as _reload 8 | 9 | 10 | class BjoernInteractiveConsole(OctopusInteractiveConsole): 11 | def __init__(self, octopus_shell): 12 | def reload(path=config["queries"]["libdir"]): 13 | _reload(octopus_shell, path) 14 | 15 | super().__init__(octopus_shell=octopus_shell, locals={"reload": reload}) 16 | self.help = OnlineHelp(config["queries"]["docdir"]) 17 | 18 | def init_file(self): 19 | return config['readline']['init'] 20 | 21 | def hist_file(self): 22 | return config['readline']['hist'] 23 | 24 | def _load_banner(self): 25 | base = os.path.dirname(__file__) 26 | path = "data/bjosh_banner.txt" 27 | fname = os.path.join(base, path) 28 | try: 29 | with open(fname, 'r') as f: 30 | self.banner = f.read() 31 | except: 32 | self.banner = "bjosh --- bjoern shell\n" 33 | 34 | def _load_prompt(self): 35 | sys.ps1 = "bjosh> " 36 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/config/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/bjoern-tools/bjoern/shell/config/__init__.py -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/config/config.py: -------------------------------------------------------------------------------- 1 | import configparser 2 | import os 3 | 4 | USER_CONFIG_FILE = os.path.expanduser('~/.bjosh.ini') 5 | GLOBAL_CONFIG_FILE = os.path.join(os.path.dirname(__file__), 'data', 'bjosh.ini') 6 | 7 | config = configparser.ConfigParser() 8 | config.read([GLOBAL_CONFIG_FILE, USER_CONFIG_FILE]) 9 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/config/data/bjosh.ini: -------------------------------------------------------------------------------- 1 | [bjoern] 2 | port = 2480 3 | host = localhost 4 | 5 | [queries] 6 | libdir = querylib 7 | docdir = querylib/doc 8 | 9 | [readline] 10 | init = ~/.bjoern_inputrc 11 | hist = ~/.bjoern_history 12 | -------------------------------------------------------------------------------- /python/bjoern-tools/bjoern/shell/data/bjosh_banner.txt: -------------------------------------------------------------------------------- 1 | _ _ _ 2 | | |__ (_) ___ ___| |__ 3 | | '_ \| |/ _ \/ __| '_ \ 4 | | |_) | | (_) \__ \ | | | 5 | |_.__// |\___/|___/_| |_| 6 | |__/ bjoern shell 7 | -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-alocs: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | 5 | from bjoern.plugins.alocs import Alocs 6 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 7 | 8 | parser = argparse.ArgumentParser(description="Abstract locations (Alocs) plugin.") 9 | parser.add_argument( 10 | "-s", "--server-host", 11 | type=str, 12 | default="localhost", 13 | help="set the hostname of the octopus server") 14 | 15 | parser.add_argument( 16 | "-p", "--server-port", 17 | type=int, 18 | default=2480, 19 | help="set the port number of the octopus server") 20 | 21 | parser.add_argument( 22 | "project", 23 | type=str, 24 | help="run the plugin for this project") 25 | 26 | args = parser.parse_args() 27 | 28 | plugin_executor = OrientDBPluginExecutor(args.server_host, args.server_port) 29 | plugin = Alocs(plugin_executor) 30 | plugin.project = args.project 31 | plugin.execute() 32 | -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-ddg: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | 5 | from bjoern.plugins.use_def_analyser import UseDefAnalyser 6 | from bjoern.plugins.data_dependence import DataDependenceCreator 7 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 8 | 9 | parser = argparse.ArgumentParser(description="Value set analysis (VSA) plugin.") 10 | parser.add_argument( 11 | "-s", "--server-host", 12 | type=str, 13 | default="localhost", 14 | help="set the hostname of the octopus server") 15 | 16 | parser.add_argument( 17 | "-p", "--server-port", 18 | type=int, 19 | default=2480, 20 | help="set the port number of the octopus server") 21 | 22 | parser.add_argument( 23 | "project", 24 | type=str, 25 | help="run the plugin for this project") 26 | 27 | args = parser.parse_args() 28 | 29 | plugin_executor = OrientDBPluginExecutor(args.server_host, args.server_port) 30 | use_def_analyser = UseDefAnalyser(plugin_executor) 31 | use_def_analyser.project = args.project 32 | use_def_analyser.execute() 33 | data_dependence_creator = DataDependenceCreator(plugin_executor) 34 | data_dependence_creator.project = args.project 35 | data_dependence_creator.execute() -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-functionexport: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | import os 5 | 6 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 7 | 8 | from bjoern.plugins.function_exporter import FunctionExporter 9 | 10 | parser = argparse.ArgumentParser(description="Function export plugin.") 11 | parser.add_argument( 12 | "-s", "--server-host", 13 | type=str, 14 | default="localhost", 15 | help="set the hostname of the octopus server") 16 | 17 | parser.add_argument( 18 | "-p", "--server-port", 19 | type=int, 20 | default=2480, 21 | help="set the port number of the octopus server") 22 | 23 | parser.add_argument( 24 | "project", 25 | type=str, 26 | help="run the plugin for this project") 27 | 28 | parser.add_argument( 29 | "-f", "--format", 30 | type=str, 31 | default="graphml", 32 | choices=["graphml", "dot", "gml"], 33 | help="export graphs in this format") 34 | 35 | parser.add_argument( 36 | "-o", "--outdir", 37 | type=str, 38 | default=os.getcwd(), 39 | help="write graphs to this directory") 40 | 41 | parser.add_argument( 42 | "-n", "--nodes", 43 | type=str, 44 | nargs="+", 45 | help="export nodes of the given types") 46 | 47 | parser.add_argument( 48 | "-e", "--edges", 49 | type=str, 50 | nargs="+", 51 | help="export edges of the given types") 52 | 53 | args = parser.parse_args() 54 | 55 | plugin_executor = OrientDBPluginExecutor(args.server_host, args.server_port) 56 | plugin = FunctionExporter(plugin_executor) 57 | plugin.project = args.project 58 | plugin.format = args.format 59 | plugin.outdir = args.outdir 60 | plugin.nodes = args.nodes 61 | plugin.edges = args.edges 62 | plugin.execute() 63 | -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-import: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import sys 4 | import os 5 | 6 | from octopus.importer.OctopusImporter import OctopusImporter 7 | 8 | class BjoernImporter(OctopusImporter): 9 | 10 | def __init__(self): 11 | self.importerPluginJSON = """{ 12 | "plugin": "radareimporter.jar", 13 | "class": "bjoern.plugins.radareimporter.RadareImporterPlugin", 14 | "settings": { 15 | "projectName": "%s", 16 | }} 17 | """ 18 | 19 | def main(filename): 20 | importer = BjoernImporter() 21 | importer.importFile(filename) 22 | 23 | def usage(): 24 | print('%s ' % (sys.argv[0])) 25 | 26 | if __name__ == '__main__': 27 | 28 | if len(sys.argv) != 2: 29 | usage() 30 | exit() 31 | 32 | main(sys.argv[1]) 33 | -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-instructionlinker: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | 5 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 6 | 7 | from bjoern.plugins.instruction_linker import InstructionLinker 8 | 9 | parser = argparse.ArgumentParser(description="Instruction linker plugin.") 10 | parser.add_argument( 11 | "-s", "--server-host", 12 | type=str, 13 | default="localhost", 14 | help="set the hostname of the octopus server") 15 | 16 | parser.add_argument( 17 | "-p", "--server-port", 18 | type=int, 19 | default=2480, 20 | help="set the port number of the octopus server") 21 | 22 | parser.add_argument( 23 | "project", 24 | type=str, 25 | help="run the plugin for this project") 26 | 27 | args = parser.parse_args() 28 | 29 | plugin_executor = OrientDBPluginExecutor(args.server_host, args.server_port) 30 | plugin = InstructionLinker(plugin_executor) 31 | plugin.project = args.project 32 | plugin.execute() 33 | -------------------------------------------------------------------------------- /python/bjoern-tools/scripts/bjoern-vsa: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | 5 | from bjoern.plugins.vsa import VSA 6 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 7 | 8 | parser = argparse.ArgumentParser(description="Value set analysis (VSA) plugin.") 9 | parser.add_argument( 10 | "-s", "--server-host", 11 | type=str, 12 | default="localhost", 13 | help="set the hostname of the octopus server") 14 | 15 | parser.add_argument( 16 | "-p", "--server-port", 17 | type=int, 18 | default=2480, 19 | help="set the port number of the octopus server") 20 | 21 | parser.add_argument( 22 | "project", 23 | type=str, 24 | help="run the plugin for this project") 25 | 26 | args = parser.parse_args() 27 | 28 | plugin_executor = OrientDBPluginExecutor(args.server_host, args.server_port) 29 | plugin = VSA(plugin_executor) 30 | plugin.project = args.project 31 | plugin.execute() 32 | -------------------------------------------------------------------------------- /python/bjoern-tools/setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from distutils.core import setup 3 | 4 | if (sys.version_info.major, sys.version_info.minor) < (3, 4): 5 | sys.exit("Python < 3.4 not supported.") 6 | 7 | setup( 8 | name='bjoern-tools', 9 | version='0.1', 10 | packages=['bjoern', 'bjoern.plugins', 'bjoern.shell', 'bjoern.shell.config'], 11 | package_dir={ 12 | 'bjoern.shell': 'bjoern/shell', 13 | 'bjoern.shell.config': 'bjoern/shell/config' 14 | }, 15 | package_data={ 16 | 'bjoern.shell': ['data/bjosh_banner.txt'], 17 | 'bjoern.shell.config': ['data/bjosh.ini'] 18 | }, 19 | url='https://github.com/octopus-platform/bjoern-tools', 20 | license='LGPLv3', 21 | scripts=['scripts/bjoern-import', 'scripts/bjoern-instructionlinker', 'scripts/bjoern-functionexport', 22 | 'scripts/bjoern-alocs', 'scripts/bjoern-vsa', 'scripts/bjoern-ddg', 'scripts/bjosh']) 23 | -------------------------------------------------------------------------------- /python/octopus-tools/.gitignore: -------------------------------------------------------------------------------- 1 | build/ 2 | 3 | .idea 4 | -------------------------------------------------------------------------------- /python/octopus-tools/.gitrepo: -------------------------------------------------------------------------------- 1 | ; DO NOT EDIT (unless you know what you are doing) 2 | ; 3 | ; This subdirectory is a git "subrepo", and this file is maintained by the 4 | ; git-subrepo command. See https://github.com/git-commands/git-subrepo#readme 5 | ; 6 | [subrepo] 7 | remote = git@github.com:octopus-platform/octopus-tools.git 8 | branch = master 9 | commit = 96058fdf99852f2697d9f44b03d92fc3009cc59c 10 | parent = d10836be221ead2d104c649417e4c77226cd8d9b 11 | cmdver = 0.3.0 12 | -------------------------------------------------------------------------------- /python/octopus-tools/AUTHORS: -------------------------------------------------------------------------------- 1 | Fabian Yamaguchi 2 | Alwin Maier 3 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/importer/OctopusImporter.py: -------------------------------------------------------------------------------- 1 | import sys, os 2 | import http.client 3 | import urllib 4 | 5 | from ftplib import FTP 6 | 7 | SERVER_HOST = 'localhost' 8 | SERVER_PORT = '2480' 9 | FTP_PORT = 23231 10 | 11 | class OctopusImporter: 12 | def __init__(self): 13 | pass 14 | 15 | def importFile(self, filename): 16 | self.filename = filename 17 | self.createProject() 18 | self.uploadFile() 19 | self.executeImporterPlugin() 20 | 21 | def createProject(self): 22 | self.projectName = os.path.split(self.filename)[-1] 23 | print('Creating project: %s' % (self.projectName)) 24 | 25 | conn = self._getConnectionToServer() 26 | conn.request("GET", "/manageprojects/create/%s" % (self.projectName)) 27 | 28 | def _getConnectionToServer(self): 29 | return http.client.HTTPConnection(SERVER_HOST + ":" + SERVER_PORT) 30 | 31 | def uploadFile(self): 32 | print('Uploading file: %s' % (self.filename)) 33 | 34 | ftp = FTP() 35 | ftp.connect(SERVER_HOST, FTP_PORT) 36 | ftp.login() 37 | filenameToWriteTo = os.path.join(self.projectName, "binary") 38 | ftp.storbinary('STOR ' + filenameToWriteTo, open(self.filename, 'rb')) 39 | ftp.close() 40 | 41 | def executeImporterPlugin(self): 42 | print('Executing importer plugin') 43 | conn = self._getConnectionToServer() 44 | conn.request("POST", "/executeplugin/", self.importerPluginJSON % (self.projectName)) 45 | response = conn.getresponse() 46 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/importer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/importer/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/plugins/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/plugins/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/plugins/plugin.py: -------------------------------------------------------------------------------- 1 | class OctopusPlugin(object): 2 | def __init__(self, executor): 3 | self._executer = executor 4 | self._pluginname = None 5 | self._classname = None 6 | self._settings = {} 7 | 8 | def execute(self): 9 | return self._executer.execute(self._pluginname, self._classname, self._settings) 10 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/DBInterface.py: -------------------------------------------------------------------------------- 1 | 2 | from octopus.server.python_shell_interface import PythonShellInterface 3 | 4 | import os 5 | 6 | class DBInterface: 7 | 8 | def connectToDatabase(self, databaseName = 'octopusDB'): 9 | self.j = PythonShellInterface() 10 | self.j.setDatabaseName(databaseName) 11 | self.j.connectToDatabase() 12 | 13 | def runGremlinQuery(self, query): 14 | return self.j.runGremlinQuery(query) 15 | 16 | def chunks(self, ids, chunkSize): 17 | return self.j.chunks(ids, chunkSize) 18 | 19 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/server/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/orientdb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/server/orientdb/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/orientdb/orientdb_plugin_executor.py: -------------------------------------------------------------------------------- 1 | import json 2 | 3 | from octopus.server.orientdb.orientdb_server_command import OrientDBServerCommand 4 | 5 | 6 | class OrientDBPluginExecutor(object): 7 | def __init__(self, server_host, server_port): 8 | self.command = OrientDBServerCommand(server_host, server_port) 9 | 10 | def execute(self, pluginname, classname, settings=None): 11 | data = {"plugin": pluginname, "class": classname, "settings": settings} 12 | json_data = json.dumps(data) 13 | return self.post(json_data) 14 | 15 | def post(self, json_data): 16 | return self.command.execute_post_command("/executeplugin/", json_data) 17 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/orientdb/orientdb_project_manager.py: -------------------------------------------------------------------------------- 1 | import base64 2 | 3 | from octopus.server.orientdb.orientdb_server_command import OrientDBServerCommand 4 | from octopus.server.project_manager import ProjectManager 5 | 6 | 7 | class OrientDBProjectManager(ProjectManager): 8 | def __init__(self, server_host, server_port): 9 | self.command = OrientDBServerCommand(server_host, server_port) 10 | 11 | def create(self, project_name): 12 | return self.command.execute_get_command("/manageprojects/create/{}".format(project_name)) 13 | 14 | def delete(self, project_name): 15 | return self.command.execute_get_command("/manageprojects/delete/{}".format(project_name)) 16 | 17 | def list(self): 18 | return self.command.execute_get_command("/manageprojects/list") 19 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/orientdb/orientdb_server_command.py: -------------------------------------------------------------------------------- 1 | import http.client 2 | 3 | 4 | class OrientDBServerCommand(object): 5 | def __init__(self, server_host="localhost", server_port="2480"): 6 | self._server_host = server_host 7 | self._server_port = server_port 8 | self._connection = None 9 | 10 | def _connect(self): 11 | self._connection = http.client.HTTPConnection("{}:{}".format(self._server_host, self._server_port)) 12 | 13 | def _disconnect(self): 14 | self._connection.close() 15 | 16 | def execute_post_command(self, name, body=None, headers={}): 17 | self._connect() 18 | self._connection.request("POST", name, body, headers) 19 | response = self._connection.getresponse().read().decode().strip() 20 | self._disconnect() 21 | return response 22 | 23 | def execute_get_command(self, name): 24 | self._connect() 25 | self._connection.request("GET", name) 26 | response = self._connection.getresponse().read().decode().strip() 27 | self._disconnect() 28 | return response 29 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/orientdb/orientdb_shell_mananger.py: -------------------------------------------------------------------------------- 1 | from octopus.server.orientdb.orientdb_server_command import OrientDBServerCommand 2 | from octopus.server.shell_manager import ShellManager 3 | 4 | 5 | class OrientDBShellManager(ShellManager): 6 | def __init__(self, server_host, server_port): 7 | self.command = OrientDBServerCommand(server_host, server_port) 8 | 9 | def create(self, project_name, shellname = 'noname'): 10 | response = self.command.execute_get_command("/manageshells/create/{}/{}".format(project_name, shellname)) 11 | port = int(response) 12 | return port 13 | 14 | def list(self, project_name=None, shell_port=None, filter_occupied=False): 15 | response = self.command.execute_get_command("/manageshells/list") 16 | if not response: 17 | return 18 | for shell in response.split('\n'): 19 | port, dbName, name, occupied = shell.split('\t') 20 | port = int(port) 21 | occupied = True if occupied == 'true' else False 22 | if (not project_name or dbName == project_name) \ 23 | and (not shell_port or port == shell_port) \ 24 | and (not filter_occupied or not occupied): 25 | yield port, dbName, name, ('occupied' if occupied else 'free') 26 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/project_manager.py: -------------------------------------------------------------------------------- 1 | class ProjectManager(object): 2 | def create(self, project_name): 3 | pass 4 | 5 | def delete(self, project_name): 6 | pass 7 | 8 | def list_projects(self): 9 | pass 10 | 11 | def upload_file(self, project_name, filename): 12 | pass 13 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/server/shell_manager.py: -------------------------------------------------------------------------------- 1 | class ShellManager(object): 2 | def create(self, project_name): 3 | pass 4 | 5 | def list(self, project_name=None, shellport=None): 6 | pass 7 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/shell/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/completer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/shell/completer/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/completer/octopus_rlcompleter.py: -------------------------------------------------------------------------------- 1 | import readline 2 | 3 | from octopus.shell.octopus_shell_utils import get_variables, get_stepnames, get_object_methods 4 | 5 | 6 | class OctopusShellCompleter(object): 7 | def __init__(self, shell): 8 | self.shell = shell 9 | self.context = None 10 | self.matches = None 11 | readline.set_completer_delims(".)(}{") 12 | 13 | def complete(self, text, state): 14 | if state == 0: 15 | self.set_context() 16 | if self.context == 'groovy': 17 | self.matches = self._get_groovy_matches(text) 18 | elif self.context == 'gremlin': 19 | self.matches = self._get_gremlin_matches(text) 20 | else: 21 | self.matches = [] 22 | 23 | try: 24 | return self.matches[state] 25 | except IndexError: 26 | return None 27 | 28 | def set_context(self): 29 | line = readline.get_line_buffer() 30 | for c in reversed(line): 31 | if c in '.': 32 | self.context = "gremlin" 33 | return 34 | if c in ')}': 35 | self.context = "complete" 36 | return 37 | elif c in '({': 38 | self.context = "groovy" 39 | return 40 | 41 | self.context = "groovy" 42 | 43 | def _get_groovy_matches(self, text): 44 | total = get_variables(self.shell) 45 | return [match for match in total if match.startswith(text)] 46 | 47 | def _get_gremlin_matches(self, text): 48 | buffer = readline.get_line_buffer() 49 | tail = buffer.rsplit('.', 1)[0] 50 | variables = get_variables(self.shell) 51 | steps = get_stepnames(self.shell) 52 | if tail: 53 | methods = get_object_methods(self.shell, tail) 54 | total = variables + steps + methods 55 | return [match for match in total if match.startswith(text)] 56 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/octopus_shell.py: -------------------------------------------------------------------------------- 1 | import re 2 | import socket 3 | 4 | 5 | class OctopusShellConnection(object): 6 | def __init__(self, host, port): 7 | self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM) 8 | self._host = host 9 | self._port = port 10 | 11 | def connect(self): 12 | self.socket.connect((self.host, self.port)) 13 | 14 | def request(self, request): 15 | request = "{}\0".format(request.strip()) 16 | request = request.encode() 17 | self.socket.sendall(request) 18 | 19 | def getresponse(self): 20 | response = b"" 21 | while True: 22 | chunk = self.socket.recv(2048) 23 | response += chunk 24 | try: 25 | if response[-1] == 0x00: 26 | break 27 | except: 28 | pass 29 | 30 | response = response[:-1].decode().strip() 31 | return response 32 | 33 | def run_command(self, command): 34 | self.request(command) 35 | response = self.getresponse() 36 | if re.match("\[.*Exception\]", response): 37 | raise RuntimeError(response) 38 | return response.split('\n') 39 | 40 | def close(self): 41 | self._socket.close() 42 | 43 | @property 44 | def socket(self): 45 | return self._socket 46 | 47 | @property 48 | def host(self): 49 | return self._host 50 | 51 | @property 52 | def port(self): 53 | return self._port 54 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/octopus_shell_utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | 3 | 4 | def get_stepnames(self): 5 | try: 6 | steps = self.connection.run_command("listSteps()") 7 | return steps 8 | except: 9 | return [] 10 | 11 | 12 | def get_variables(shell): 13 | try: 14 | variables = shell.run_command("listVariables()") 15 | return variables 16 | except: 17 | return [] 18 | 19 | 20 | def get_object_methods(shell, command): 21 | try: 22 | methods = shell.run_command("{}.getClass().getMethods().name.unique()".format(command)) 23 | return methods 24 | except: 25 | return [] 26 | 27 | 28 | def reload(shell, path): 29 | if os.path.isdir(path): 30 | reload_dir(shell, path) 31 | elif os.path.isfile(path): 32 | reload_file(shell, path) 33 | 34 | 35 | def reload_dir(shell, directory): 36 | for dirpath, dirnames, filenames in os.walk(directory): 37 | dirnames[:] = [d for d in dirnames if not d.startswith('.')] 38 | filenames[:] = [f for f in filenames if not f.startswith('.')] 39 | for filename in filenames: 40 | _, ext = os.path.splitext(filename) 41 | if ext == ".groovy": 42 | reload_file(shell, os.path.abspath(os.path.join(dirpath, filename))) 43 | 44 | 45 | def reload_file(shell, filename): 46 | print("loading file {} ...".format(filename), end=' ') 47 | try: 48 | with open(filename, 'r') as f: 49 | shell.run_command(f.read()) 50 | except IOError: 51 | print("failed") 52 | else: 53 | print("done") 54 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shell/onlinehelp/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/shell/onlinehelp/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/ChunkStartTool.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | A shell tool that constructs queries from arguments and flags, then 4 | outputs results. In contrast to StartTool, this tool performs chunking 5 | to increase performance. 6 | """ 7 | 8 | from octopus.server.DBInterface import DBInterface 9 | from octopus.shelltool.CmdLineTool import CmdLineTool 10 | 11 | CHUNK_SIZE = 256 12 | 13 | class ChunkStartTool(CmdLineTool): 14 | 15 | def __init__(self, DESCRIPTION): 16 | CmdLineTool.__init__(self, DESCRIPTION) 17 | 18 | # @Override 19 | def _constructIdQuery(self): 20 | pass 21 | 22 | # @Override 23 | def _constructQueryForChunk(self, chunk): 24 | pass 25 | 26 | # @Override 27 | def handleChunkResult(self, res, chunk): 28 | pass 29 | 30 | # @Override 31 | def _start(self): 32 | pass 33 | 34 | def _stop(self): 35 | pass 36 | 37 | def _runImpl(self): 38 | 39 | self.dbInterface = DBInterface() 40 | self.dbInterface.connectToDatabase() 41 | 42 | self._start() 43 | 44 | query = self._constructIdQuery() 45 | ids = self.dbInterface.runGremlinQuery(query) 46 | 47 | for chunk in self.dbInterface.chunks(ids, CHUNK_SIZE): 48 | query = self._constructQueryForChunk(chunk) 49 | res = self.dbInterface.runGremlinQuery(query) 50 | self._handleChunkResult(res, chunk) 51 | 52 | self._stop() 53 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/CmdLineTool.py: -------------------------------------------------------------------------------- 1 | 2 | from argparse import ArgumentParser 3 | 4 | class CmdLineTool: 5 | 6 | def __init__(self, description): 7 | self.description = description 8 | self._initializeOptParser() 9 | 10 | def _initializeOptParser(self): 11 | self.argParser = ArgumentParser(description = self.description) 12 | 13 | def run(self): 14 | """ 15 | Run the tool. Call this function after all additional 16 | arguments have been provided 17 | """ 18 | self._parseCommandLine() 19 | self._runImpl() 20 | 21 | # @Override 22 | def _runImpl(self): 23 | pass 24 | 25 | def _parseCommandLine(self): 26 | self.args = self.argParser.parse_args() 27 | 28 | def _usage(self): 29 | self.argParser.print_help() 30 | 31 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/DemuxTool.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python2 2 | 3 | import sys, os 4 | from octopus.shelltool.PipeTool import PipeTool 5 | 6 | """ A tool processing lines where the first field is interpreted as a 7 | key. Lines are accumulated until the key changes or the end of the 8 | file is encountered. Tab is the only delimiter.""" 9 | 10 | class DemuxTool(PipeTool): 11 | 12 | def __init__(self, DESCRIPTION): 13 | PipeTool.__init__(self, DESCRIPTION) 14 | self.currentKey = '' 15 | self.lines = [] 16 | 17 | # @Override 18 | def processLine(self, line): 19 | record = line.split('\t') 20 | if(len(record) < 2 ): 21 | sys.stderr.write('Warning: input line does not contain key\n') 22 | return 23 | 24 | k = record[0] 25 | if self.currentKey != '' and k != self.currentKey: 26 | self.processLines() 27 | self.lines = [] 28 | 29 | self.currentKey = k 30 | self.lines.append(line) 31 | 32 | # This function is called when lines have been accumulated. 33 | # Override to implement functionality of specific tools. 34 | def processLines(self): 35 | print(self.lines) 36 | 37 | # @Override 38 | def streamEnd(self): 39 | if self.lines != []: 40 | self.processLines() 41 | 42 | 43 | if __name__ == '__main__': 44 | tool = DemuxTool('foo') 45 | tool.run() 46 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/GraphvizTool.py: -------------------------------------------------------------------------------- 1 | 2 | from octopus.shelltool.PipeTool import PipeTool 3 | from pygraphviz import AGraph 4 | 5 | class GraphvizTool(PipeTool): 6 | 7 | def __init__(self, description): 8 | PipeTool.__init__(self, description) 9 | self.lines = [] 10 | 11 | # @Override 12 | def processLine(self, line): 13 | ENDMARKER = '//###' 14 | 15 | if line == ENDMARKER: 16 | self.processLines() 17 | self.lines = [] 18 | else: 19 | self.lines.append(line) 20 | 21 | def processLines(self): 22 | if len(self.lines) == 0: 23 | return 24 | 25 | self.identifier = self.lines[0][2:] 26 | 27 | s = '\n'.join(self.lines) 28 | A = AGraph() 29 | G = A.from_string(s) 30 | self.processGraph(G) 31 | 32 | 33 | def processGraph(self, G): 34 | print(G) 35 | 36 | # @Override 37 | def streamEnd(self): 38 | if self.lines != []: 39 | self.processLines() 40 | 41 | def _outputGraph(self, G, identifier): 42 | ENDMARKER = '//###' 43 | self.output('//' + identifier + '\n') 44 | self.output(str(G) + '\n') 45 | self.output(ENDMARKER + '\n') 46 | 47 | if __name__ == '__main__': 48 | tool = GraphvizTool('foo') 49 | tool.run() 50 | 51 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/PipeTool.py: -------------------------------------------------------------------------------- 1 | 2 | import sys 3 | from argparse import FileType 4 | from octopus.shelltool.CmdLineTool import CmdLineTool 5 | 6 | """ A Unix-style pipe tool, which reads from stdin if it is not a 7 | tty-like device or optionally from a provided file and accepts 8 | switches. 9 | """ 10 | 11 | class PipeTool(CmdLineTool): 12 | 13 | def __init__(self, description): 14 | CmdLineTool.__init__(self, description) 15 | 16 | self.argParser.add_argument('-f', '--file', nargs='?', 17 | type = FileType('r'), default=sys.stdin, 18 | help='read input from the provided file') 19 | 20 | self.argParser.add_argument('-o', '--out', nargs='?', type= 21 | FileType('w'), default=sys.stdout, 22 | help = 'write output to provided file') 23 | 24 | def _runImpl(self): 25 | 26 | if self.args.file != sys.stdin or not sys.stdin.isatty(): 27 | self._processStream() 28 | else: 29 | self._usage() 30 | 31 | def output(self, s): 32 | self.args.out.write(s) 33 | 34 | def _processStream(self): 35 | self.streamStart() 36 | for line in self.args.file: 37 | self.processLine(line.rstrip()) 38 | self.streamEnd() 39 | 40 | def processLine(self, line): 41 | """ This function is called for each line read from the input 42 | source. Note that the newline character has already been 43 | removed when the function is called. Override this method to 44 | implement your tool""" 45 | pass 46 | 47 | def streamStart(self): 48 | """ Called when before reading the first item from the 49 | stream. Override.""" 50 | pass 51 | 52 | def streamEnd(self): 53 | """ Called after reading the last item from the 54 | stream. Override.""" 55 | pass 56 | 57 | 58 | if __name__ == '__main__': 59 | 60 | tool = PipeTool("foo") 61 | tool.run() 62 | 63 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/StartTool.py: -------------------------------------------------------------------------------- 1 | 2 | """ 3 | A shell tool that constructs a query from arguments and flags and 4 | outputs results. This is different from a PipeTool as StartTool can 5 | only occur at the beginning of a chain. 6 | """ 7 | 8 | from octopus.server.DBInterface import DBInterface 9 | from octopus.shelltool.CmdLineTool import CmdLineTool 10 | 11 | class StartTool(CmdLineTool): 12 | 13 | def __init__(self, DESCRIPTION): 14 | CmdLineTool.__init__(self, DESCRIPTION) 15 | 16 | # @Override 17 | def _constructQuery(self): 18 | """ 19 | Create a query from arguments that will be passed to the 20 | database. 21 | """ 22 | pass 23 | 24 | # @Override 25 | def _handleResult(self, res): 26 | """ 27 | Process the result of the query. 28 | """ 29 | pass 30 | 31 | def _runImpl(self): 32 | query = self._constructQuery() 33 | 34 | self.dbInterface = DBInterface() 35 | self.dbInterface.connectToDatabase() 36 | 37 | res = self.dbInterface.runGremlinQuery(query) 38 | self._handleResult(res) 39 | 40 | -------------------------------------------------------------------------------- /python/octopus-tools/octopus/shelltool/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/octopus/shelltool/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/scripts/octopus-plugin: -------------------------------------------------------------------------------- 1 | #!python 2 | 3 | import argparse 4 | 5 | from octopus.server.orientdb.orientdb_plugin_executor import OrientDBPluginExecutor 6 | 7 | parser = argparse.ArgumentParser(description="Generic plugin executor.") 8 | 9 | parser.add_argument( 10 | "-s", "--server-host", 11 | type=str, 12 | default="localhost", 13 | help="set the hostname of the octopus server") 14 | 15 | parser.add_argument( 16 | "-p", "--server-port", 17 | type=int, 18 | default=2480, 19 | help="set the port number of the octopus server") 20 | 21 | parser.add_argument( 22 | "configuration", 23 | type=argparse.FileType("r"), 24 | help="use this configuration file") 25 | 26 | args = parser.parse_args() 27 | 28 | executor = OrientDBPluginExecutor(args.server_host, args.server_port) 29 | print(executor.post(args.configuration)) 30 | -------------------------------------------------------------------------------- /python/octopus-tools/setup.py: -------------------------------------------------------------------------------- 1 | import sys 2 | from distutils.core import setup 3 | 4 | if (sys.version_info.major, sys.version_info.minor) < (3, 4): 5 | sys.exit("Python < 3.4 not supported.") 6 | 7 | setup( 8 | name='octopus-tools', 9 | version='0.1', 10 | license='LGPLv3', 11 | packages=['octopus', 'octopus.server', 'octopus.server.orientdb', 'octopus.plugins', 'octopus.shell', 12 | 'octopus.shell.completer', 'octopus.shell.onlinehelp', 'octopus.importer', 'octopus.shelltool'], 13 | scripts=['scripts/octopus-project', 'scripts/octopus-plugin'] 14 | ) 15 | -------------------------------------------------------------------------------- /python/octopus-tools/tests/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/octopus-platform/bjoern/828a45f7ed3cb4398e25bdfd27c93871c27a4a68/python/octopus-tools/tests/__init__.py -------------------------------------------------------------------------------- /python/octopus-tools/tests/orientdb_server_command.py: -------------------------------------------------------------------------------- 1 | 2 | import unittest 3 | 4 | from octopus.server.orientdb.orientdb_server_command import OrientDBServerCommand 5 | 6 | class TestOrientDBServerCommand(unittest.TestCase): 7 | 8 | def testUnreachableServer(self): 9 | 10 | self.hostname = 'localhost' 11 | self.port = '1337' 12 | 13 | cmd = OrientDBServerCommand(self.hostname, self.port) 14 | self.assertRaises(ConnectionRefusedError, cmd.execute_get_command, "foo") 15 | -------------------------------------------------------------------------------- /python/octopus-tools/tests/orientdb_shell_manager.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from octopus.server.orientdb.orientdb_shell_mananger import OrientDBShellManager 4 | 5 | 6 | class TestOrientDBShellManager(unittest.TestCase): 7 | def testUnreachableServer(self): 8 | self.hostname = 'localhost' 9 | self.port = '1337' 10 | 11 | shell_manager = OrientDBShellManager(self.hostname, self.port) 12 | shells = shell_manager.list() 13 | self.assertRaises(ConnectionRefusedError, list, shells) 14 | -------------------------------------------------------------------------------- /python/octopus-tools/tests/python_shell_interface.py: -------------------------------------------------------------------------------- 1 | import unittest 2 | 3 | from octopus.server.python_shell_interface import PythonShellInterface 4 | 5 | 6 | class TestPythonShellInterface(unittest.TestCase): 7 | 8 | def setUp(self): 9 | self.databaseName = 'testDatabase' 10 | self.hostname = 'localhost' 11 | self.port = '2480' 12 | 13 | def testUnreachableServer(self): 14 | 15 | self.port = '1337' 16 | self.assertRaises(ConnectionRefusedError, self._connectToDatabase) 17 | 18 | def testConnect(self): 19 | self._connectToDatabase() 20 | 21 | def testGremlinQuery(self): 22 | self._connectToDatabase() 23 | retList = self.shell_interface.runGremlinQuery("g") 24 | self.assertEqual(len(retList), 1) 25 | 26 | def _connectToDatabase(self): 27 | self._configureShellInterface() 28 | self.shell_interface.connectToDatabase() 29 | 30 | def _configureShellInterface(self): 31 | self.shell_interface = PythonShellInterface() 32 | self.shell_interface.setHost(self.hostname) 33 | self.shell_interface.setPort(self.port) 34 | self.shell_interface.setDatabaseName(self.databaseName) 35 | 36 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | include 'projects:octopus:orientdbimporter' 2 | include 'projects:octopus:octopus-server' 3 | include 'projects:octopus:octopus-lang' 4 | 5 | include 'projects:radare2csv' 6 | include 'projects:bjoern-r2interface' 7 | 8 | include 'projects:bjoern-pluginlib' 9 | include 'projects:bjoern-plugins:functionexport' 10 | include 'projects:bjoern-plugins:instructionlinker' 11 | include 'projects:bjoern-plugins:radareimporter' 12 | include 'projects:bjoern-plugins:paramdetect' 13 | include 'projects:bjoern-plugins:alocs' 14 | include 'projects:bjoern-plugins:vsa' 15 | include 'projects:bjoern-plugins:usedefanalyser' 16 | include 'projects:bjoern-plugins:datadependence' 17 | 18 | include 'projects:bjoern-lang' 19 | 20 | include 'integrationTest' 21 | 22 | --------------------------------------------------------------------------------