├── .gitignore ├── EXAMPLE.md ├── LICENSE.md ├── Playbook ├── README.md ├── polar-v1-public.pdf ├── polar └── __init__.py ├── requirements.txt ├── screenshots ├── Screenshot1.png ├── Screenshot2.png ├── Screenshot3.png └── Screenshot4.png └── setup.py /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | env/ 12 | build/ 13 | develop-eggs/ 14 | dist/ 15 | downloads/ 16 | eggs/ 17 | .eggs/ 18 | lib/ 19 | lib64/ 20 | parts/ 21 | sdist/ 22 | var/ 23 | *.egg-info/ 24 | .installed.cfg 25 | *.egg 26 | 27 | # PyInstaller 28 | # Usually these files are written by a python script from a template 29 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 30 | *.manifest 31 | *.spec 32 | 33 | # Installer logs 34 | pip-log.txt 35 | pip-delete-this-directory.txt 36 | 37 | # Unit test / coverage reports 38 | htmlcov/ 39 | .tox/ 40 | .coverage 41 | .coverage.* 42 | .cache 43 | nosetests.xml 44 | coverage.xml 45 | *,cover 46 | .hypothesis/ 47 | 48 | # Translations 49 | *.mo 50 | *.pot 51 | 52 | # Django stuff: 53 | *.log 54 | local_settings.py 55 | 56 | # Flask stuff: 57 | instance/ 58 | .webassets-cache 59 | 60 | # Scrapy stuff: 61 | .scrapy 62 | 63 | # Sphinx documentation 64 | docs/_build/ 65 | 66 | # PyBuilder 67 | target/ 68 | 69 | # IPython Notebook 70 | .ipynb_checkpoints 71 | 72 | # pyenv 73 | .python-version 74 | 75 | # celery beat schedule file 76 | celerybeat-schedule 77 | 78 | # dotenv 79 | .env 80 | 81 | # virtualenv 82 | venv/ 83 | ENV/ 84 | 85 | # Spyder project settings 86 | .spyderproject 87 | 88 | # Rope project settings 89 | .ropeproject 90 | 91 | # Pycharm project settings 92 | .idea/ -------------------------------------------------------------------------------- /EXAMPLE.md: -------------------------------------------------------------------------------- 1 | Simple Command Injection Example 2 | 1) Download an old firmware version for a known vulnerable router, for example: 3 | https://www.netgear.com/support/product/R7000#Firmware%20Version%201.0.0.96%20(North%20America%20Only) 4 | 2) Mount the squashfs image. 5 | 3) Run Polar over the lib, sbin, usr 6 | 7 | 8 | ```from os import listdir 9 | from os.path import isfile, join, islink 10 | directories = ['/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/lib/' ,'/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/sbin/' ,'/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/usr/bin/' , '/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/usr/lib/', '/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/usr/sbin/'] 11 | for directory in directories: 12 | onlyfiles = [f for f in listdir(directory) if isfile(join(directory, f)) and not islink(join(directory, f))] 13 | for file in onlyfiles: 14 | get_import_export_radare(file,directory+file) 15 | ``` 16 | 4) Identify which files are calling to system, using a cyperQL query: 17 | 18 | `MATCH p = (n:Symbol{name:'system'})-[r:uses]-() RETURN p` 19 | 20 | ![Alt text](screenshots/Screenshot1.png?raw=true "Screenshot 1") 21 | 5) Decompile all the calls to system from the file httpd (for example): 22 | 23 | `getdisassemble_to_function('system','httpd','/_R7000-V1.0.0.96_1.0.15.chk.extracted/squashfs-root/usr/sbin/httpd')` 24 | 25 | 6) Make a cypherql query and expand the node: 26 | 27 | `MATCH p=(File{name:'httpd'})-[r:defines]->() RETURN p` 28 | 29 | ![Alt text](screenshots/Screenshot2.png?raw=true "Screenshot 2") 30 | 7) Take a look at the decompile and profit :-) 31 | ![Alt text](screenshots/Screenshot3.png?raw=true "Screenshot 3") 32 | 8) Or do complex queries, for example, whenever you have sprintf and system: 33 | 34 | `MATCH p=(File{name:'httpd'})-[r:defines]->()<-[q:imports]-(Symbol{name:'sprintf'}) return p limit 100` 35 | 36 | ![Alt text](screenshots/Screenshot4.png?raw=true "Screenshot 4") -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | Modified MIT License 2 | 3 | Copyright (c) 2018 Ezra Caltum 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | If you happen to meet one of the copyright holders in a bar you are encouraged 16 | to invite them a drink. 17 | 18 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 19 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 20 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 21 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 22 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 23 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 24 | SOFTWARE. 25 | -------------------------------------------------------------------------------- /Playbook: -------------------------------------------------------------------------------- 1 | Finding symbol usages 2 | 3 | MATCH (a:File)-->(b:Symbol) WHERE b.name in ['system', 'execve', 'popen' ] RETURN a,b 4 | 5 | Dissasemble a function using the symbol 6 | 7 | polar-disassemble -db "bolt://neo4j:ezra@localhost:7687" -f "usr/sbin/httpd:system" 8 | 9 | Finding usages on disassembled function 10 | MATCH (c:Function)-->(b:Symbol) WHERE b.name in ['system', 'execve', 'popen' ] return b,c 11 | 12 | Finding combination of function usages 13 | MATCH (b:Symbol)--(c:Function)<-[:defines]-(a:File), (c)-->(b2:Symbol) WHERE b.name =~ '.*system.*' and b2.name =~ '.*print.*' RETURN b,b2,c 14 | 15 | Finding combination of function usages and a string (remember that in R2 %s gets translated as __s) 16 | MATCH (b:Symbol)--(c:Function)<-[:defines]-(a:File), (c)-->(b2:Symbol) WHERE b.name =~ '.*system.*' and b2.name =~ '.*print.*' and c.decompilation CONTAINS '__s' RETURN b,b2,c 17 | 18 | Finding banned functions 19 | MATCH (a:File)-->(b:Symbol) WHERE b.name in ['strcpy','strcpyA','strcpyW','wcscpy','_tcscpy','_mbscpy','StrCpy','StrCpyA','StrCpyW','lstrcpy','lstrcpyA','lstrcpyW','_tccpy','_mbccpy','_ftcscpy','strncpy','wcsncpy','_tcsncpy','_mbsncpy','_mbsnbcpy','StrCpyN','StrCpyNA','StrCpyNW','StrNCpy','strcpynA','StrNCpyA','StrNCpyW','lstrcpyn','lstrcpynA','lstrcpynW','strcat','strcatA','strcatW','wcscat','_tcscat','_mbscat','StrCat','StrCatA','StrCatW','lstrcat','lstrcatA','lstrcatW','StrCatBuff','StrCatBuffA','StrCatBuffW','StrCatChainW','_tccat','_mbccat','_ftcscat','strncat','wcsncat','_tcsncat','_mbsncat','_mbsnbcat','StrCatN','StrCatNA','StrCatNW','StrNCat','StrNCatA','StrNCatW','lstrncat','lstrcatnA','lstrcatnW','lstrcatn','sprintfW','sprintfA','wsprintf','wsprintfW','wsprintfA','sprintf','swprintf','_stprintf','wvsprintf','wvsprintfA','wvsprintfW','vsprintf','_vstprintf','vswprintf','_snwprintf','_snprintf','_sntprintf','nsprintf','wvsprintf','wvsprintfA','wvsprintfW','vsprintf','_vstprintf','vswprintf','strncpy','wcsncpy','_tcsncpy','_mbsncpy','_mbsnbcpy','StrCpyN','StrCpyNA','StrCpyNW','StrNCpy','strcpynA','StrNCpyA','StrNCpyW','lstrcpyn','lstrcpynA','lstrcpynW','_fstrncpy','strncat','wcsncat','_tcsncat','_mbsncat','_mbsnbcat','StrCatN','StrCatNA','StrCatNW','StrNCat','StrNCatA','StrNCatW','lstrncat','lstrcatnA','lstrcatnW','lstrcatn','_fstrncat','alloca','_alloca','strlen','wcslen','_mbslen','_mbstrlen','StrLen','lstrlen','memcpy','RtlCopyMemory','CopyMemory','wmemcpy'] RETURN a,b limit 1000 20 | 21 | Finding most used functions 22 | MATCH (a:File)-[r:uses]->(b:Symbol) RETURN b, count(r) as usages order by usages desc 23 | 24 | Find network aware stuff 25 | MATCH (a:File)--(b:Symbol) WHERE b.name in ['accept', 'bind', 'listen', 'recv'] return a,b 26 | 27 | Experimental problematic fixed length buffers query 28 | MATCH (b:Symbol)<--(c:Function)<-[:defines]-(a:File{name:'httpd'}), (c)-->(b2:Symbol) WHERE b.name = 'memcpy' and b2.name <> 'strlen' RETURN c 29 | 30 | Only returning line number 31 | MATCH (b:Symbol)<--(c:Function)<-[:defines]-(a:File{name:'httpd'}), (c)-->(b2:Symbol) WHERE b.name = 'memcpy' and b2.name <> 'strlen' and c.name =~ 'sub.*' 32 | WITH [x in split(c.decompilation,'|')[0..-1] where x contains 'memcpy'] as n return n 33 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # POLAR - Path Of LeAst Resistance - (Work in progress.....) 2 | 3 | ## Introduction 4 | While performing binary analysis of a firmware, I had a scenario where multiple executables were compiled against multiple libraries. 5 | I was looking for a graphical view to understand the relationships between imported and exported symbols and it's usages. 6 | I didn't find anything that suits my needs. As such, I wrote a very simple parser, which can be useful for other people with the same needs. 7 | The flow is simple: 8 | - Using radare2, generate a list of imported exported symbols 9 | - Parse and insert them into a neo4j graph database. 10 | - If needed, decompile all the usages of a specific symbol, parse the calls and insert them to the graph. 11 | - python3 12 | 13 | ## Requirements: 14 | - neo4j graph database - https://github.com/neo4j/neo4j 15 | - neomodel - pip install neomodel 16 | - r2pipe - pip install r2pipe 17 | 18 | 19 | ## Usage: 20 | - To parse the imports/exports 21 | -- get_import_export_radare('filename','/path/to/filename') 22 | - To decompile a function 23 | -- getdisassemble_to_function('name_of_the_symbol','filename','/path/to/filename') 24 | 25 | 26 | 27 | 28 | ## Acknowledgements. 29 | 30 | Big thanks to @inbarraz for the support and convincing me to share my simple parser, and to @shiftred and @iiamit for feedback. 31 | 32 | 33 | 34 | ## Example usage 35 | 36 | Take a look at https://github.com/ezrac/POLAR/blob/master/polar-v1-public.pdf and download 37 | 38 | https://www.netgear.com/support/product/R7000#Firmware%20Version%201.0.0.96%20(North%20America%20Only) for the examples 39 | -------------------------------------------------------------------------------- /polar-v1-public.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezrac/POLAR/d7d38ca0c7752691259520015a93685c82b6a422/polar-v1-public.pdf -------------------------------------------------------------------------------- /polar/__init__.py: -------------------------------------------------------------------------------- 1 | import re 2 | import os 3 | import sys 4 | from os import path 5 | from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter 6 | 7 | # Radare 2 bindings in python 8 | import r2pipe 9 | 10 | # This is the DATABASE URL for the visualization 11 | from neomodel import config 12 | from neomodel import StringProperty, RelationshipTo, StructuredNode, RelationshipFrom 13 | 14 | __version__ = 0.1 15 | 16 | 17 | # Define an Object that stores the Symbol Properties. 18 | # A symbol can either be Used, Provided or Imported. 19 | 20 | class Symbol(StructuredNode): 21 | name = StringProperty(required=True) 22 | user = RelationshipFrom('File', 'uses') 23 | provider = RelationshipFrom('File', 'provides') 24 | 25 | 26 | # Define an Object that stores the File Properties. 27 | # A file has a path, hash, name and can use or provide symbols 28 | class File(StructuredNode): 29 | name = StringProperty(unique_index=True) 30 | path = StringProperty() 31 | hash = StringProperty() 32 | uses = RelationshipTo('Symbol', 'uses') 33 | provides = RelationshipTo('Symbol', 'provides') 34 | 35 | 36 | # Every function should have a name, and it's defined at a specific File 37 | # A function includes (as a property) the decompilation (optionally) 38 | class Function(StructuredNode): 39 | name = StringProperty(required=True) 40 | decompilation = StringProperty() 41 | imports_symbol = RelationshipTo('Symbol', 'imports') 42 | defined_at = RelationshipFrom('File', 'defines') 43 | 44 | 45 | # First parameter is the filename (the string that is stored, second argument is the path) 46 | # Were we will perform the activities 47 | 48 | def get_import_export_radare(filename, path): 49 | # We define the node or get it if already exists, for further operations. 50 | filenode = File.get_or_create({'name': filename})[0] 51 | # By using r2, we open the file 52 | r2 = r2pipe.open(path) 53 | # And *a*nalyze the *f*unctions 54 | r2.cmd('af') 55 | # and get *i*nformation, on the *i*mports in a *j*son format 56 | # parsing it with the json parser ( cmdj ) 57 | imports = r2.cmdj('iij') 58 | # get *i*nformation, on the *e*xports in a *j*son format 59 | # parsing it with the json parser ( cmdj ) 60 | exports = r2.cmdj('iEj') 61 | 62 | for symbolimport in imports: 63 | # Dirty hack.... 64 | if not symbolimport['type'] == 'NOTYPE': 65 | # We define the node or get it if already exists, for further operations. 66 | importedsymbol = Symbol.get_or_create({'name': symbolimport['name']})[0] 67 | # We create a user relationship on the file we defined previously 68 | importedsymbol.user.connect(filenode) 69 | 70 | for symbolexport in exports: 71 | # Dirty hack... 72 | if not symbolexport['size'] == 0: 73 | symbol = Symbol.get_or_create({'name': symbolexport['name']})[0] 74 | # We create a provider relationship on the file we defined previously 75 | symbol.provider.connect(filenode) 76 | 77 | 78 | def getdisassemble_to_function(function_name, filename, path): 79 | filenode = File.get_or_create({'name': filename})[0] 80 | r2 = r2pipe.open(path) 81 | r2.cmd("aaa") 82 | # e anal.jmptbl = true 83 | # e anal.hasnext = true 84 | function_calls = r2.cmd("axt @@ " + function_name).split('\n') 85 | for call in function_calls: 86 | if "[CALL]" in call.split(" ")[2]: 87 | if "(nofunc)" in call.split(" ")[0]: 88 | dissasembly = r2.cmd("pd @ " + call.split(" ")[1] + " -10") 89 | re.findall("bl\s(?:sym\.imp|sub)\.(.+?)\\s", dissasembly) 90 | else: 91 | dissasembly = r2.cmd("pdf @@ " + call.split(" ")[0]) 92 | re.findall("bl\s(?:sym\.imp|sub)\.(.+?)\\s", dissasembly) 93 | my_function = Function.get_or_create({'name': call.split(" ")[0], 'decompilation': dissasembly})[0] 94 | # filenode.defines.connect(function) 95 | for call in re.findall("bl\s(?:sym\.imp|sub)\.(.+?)\\s", dissasembly): 96 | symbol = Symbol.get_or_create({'name': call})[0] 97 | my_function.imports_symbol.connect(symbol) 98 | my_function.defined_at.connect(filenode) 99 | 100 | 101 | def parse(db_url, directories): 102 | config.DATABASE_URL = db_url 103 | for directory in directories: 104 | for dir_path, dir_names, file_names in os.walk(directory): 105 | for file_name in file_names: 106 | full_path = path.abspath(path.join(dir_path, file_name)) 107 | if os.path.islink(full_path) == False: 108 | get_import_export_radare(path.basename(full_path), full_path) 109 | 110 | 111 | def parse_main(args=None): 112 | if args is None: 113 | args = sys.argv[1:] 114 | 115 | parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) 116 | parser.add_argument("-v", "--version", action="version", version="%(prog)s {ver}".format(ver=__version__)) 117 | parser.add_argument("-db", "--neo4j-database", 118 | help="neo4j database url", 119 | dest="db_url", 120 | default="bolt://neo4j:neo4j@localhost:7687") 121 | 122 | parser.add_argument("-d", "--directories", 123 | help="Directory to parse", 124 | required=True, 125 | nargs='+') 126 | sys_args = vars(parser.parse_args(args=args)) 127 | 128 | parse(**sys_args) 129 | 130 | 131 | def disassemble(db_url, function_tuples): 132 | config.DATABASE_URL = db_url 133 | for function_tuple in function_tuples: 134 | file_path, function_name = function_tuple.rsplit(':', 1) 135 | full_path = path.abspath(file_path) 136 | getdisassemble_to_function(function_name, path.basename(full_path), full_path) 137 | 138 | 139 | def disassemble_main(args=None): 140 | if args is None: 141 | args = sys.argv[1:] 142 | 143 | parser = ArgumentParser(formatter_class=ArgumentDefaultsHelpFormatter) 144 | parser.add_argument("-v", "--version", action="version", version="%(prog)s {ver}".format(ver=__version__)) 145 | parser.add_argument("-db", "--neo4j-database", 146 | help="neo4j database url", 147 | dest="db_url", 148 | default="bolt://neo4j:neo4j@localhost:7687") 149 | 150 | parser.add_argument("-f", "--function-tuples", 151 | help="file:function tuples", 152 | required=True, 153 | nargs='+') 154 | sys_args = vars(parser.parse_args(args=args)) 155 | 156 | disassemble(**sys_args) 157 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | r2pipe >= 0.9.9 2 | neomodel >= 3.2.8 3 | -------------------------------------------------------------------------------- /screenshots/Screenshot1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezrac/POLAR/d7d38ca0c7752691259520015a93685c82b6a422/screenshots/Screenshot1.png -------------------------------------------------------------------------------- /screenshots/Screenshot2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezrac/POLAR/d7d38ca0c7752691259520015a93685c82b6a422/screenshots/Screenshot2.png -------------------------------------------------------------------------------- /screenshots/Screenshot3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezrac/POLAR/d7d38ca0c7752691259520015a93685c82b6a422/screenshots/Screenshot3.png -------------------------------------------------------------------------------- /screenshots/Screenshot4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ezrac/POLAR/d7d38ca0c7752691259520015a93685c82b6a422/screenshots/Screenshot4.png -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env python 2 | 3 | from os import path 4 | from setuptools import setup, find_packages 5 | 6 | __folder__ = path.dirname(__file__) 7 | 8 | with open(path.join(__folder__, 'README.md')) as ld_file: 9 | long_description = ld_file.read() 10 | ld_file.flush() 11 | 12 | setup( 13 | name='POLAR', 14 | version="0.1", 15 | description='POLAR - Path Of LeAst Resistance', 16 | long_description=long_description, 17 | author='ezrac', 18 | author_email='', 19 | packages=find_packages(), 20 | py_modules=['polar'], 21 | entry_points={ 22 | 'console_scripts': [ 23 | 'polar-parse = polar:parse_main', 24 | 'polar-disassemble = polar:disassemble_main', 25 | ] 26 | }, 27 | install_requires=[ 28 | 'r2pipe >= 0.9.9', 29 | 'neomodel >= 3.2.8', 30 | ], 31 | license="", 32 | platforms='any', 33 | url='https://github.com/ezrac/POLAR', 34 | classifiers=[ 35 | 'Environment :: Console', 36 | 'Intended Audience :: Science/Research', 37 | 'Natural Language :: English', 38 | 'Operating System :: MacOS :: MacOS X', 39 | 'Operating System :: Microsoft :: Windows', 40 | 'Operating System :: POSIX :: Linux', 41 | 'Programming Language :: Python :: 2', 42 | 'Topic :: Security', 43 | ] 44 | ) 45 | --------------------------------------------------------------------------------