Beispiel #1
0
 def __init__(self, name):
     vm = auto_vm(name)
     if vm is None:
         raise ValueError('Format not recognised: %s' % name)
     self.vma = analysis.newVMAnalysis(vm)
     self.classes = dict((dvclass.get_name(), dvclass)
                         for dvclass in vm.get_classes())
Beispiel #2
0
def main():

	_args = _parseargs()
	
	_a = apk.APK(_args.file)
	print("Analyse file: {:s}".format(_args.file))
	print("Package name: {:s}".format(_a.get_package()))
	
	#print("Output : {}".format(_a.get_dex()))
	_vm = dvm.DalvikVMFormat(_a.get_dex())
	_vmx = newVMAnalysis(_vm)
	
	if 'android.permission.INTERNET' in _a.get_permissions():
		print "App requires INTERNET permission. Continue analysis..."
		
		_vmx.create_xref()
		_vm.set_vmanalysis(_vmx)
		_vm.create_python_export()
		#_vm.create_dref(_vmx)
		
		_result = {'trustmanager' : [], 'hostnameverifier' : [], 'onreceivedsslerror' : []}
		_result = _check_all(_vm, _vmx)
		
		if not _args.xml:
			_print_result(_result, _java=_args.java)
		else:
			_xml_result(_a, _result)
		
		if _args.dir:
			print "Store decompiled Java code in {:s}".format(_args.dir)
			_store_java(_vm, _args)
	else:
		print "App does not require INTERNET permission. No need to worry about SSL misuse... Abort!"
Beispiel #3
0
 def __init__(self, name):
     vm = auto_vm(name)
     if vm is None:
         raise ValueError('Format not recognised: %s' % name)
     self.vma = analysis.newVMAnalysis(vm)
     self.classes = dict((dvclass.get_name(), dvclass)
                         for dvclass in vm.get_classes())
Beispiel #4
0
def get_apis(path, filename):
    app = apk.APK(path)
    app_dex = dvm.DalvikVMFormat(app.get_dex())
    app_x = analysis.newVMAnalysis(app_dex)
    methods = set()
    cs = [cc.get_name() for cc in app_dex.get_classes()]

    for method in app_dex.get_methods():
        g = app_x.get_method(method)
        if method.get_code() == None:
            continue

        for i in g.get_basic_blocks().get():
            for ins in i.get_instructions():
                output = ins.get_output()
                match = re.search(r'(L[^;]*;)->[^\(]*\([^\)]*\).*', output)
                if match and match.group(1) not in cs:
                    methods.add(match.group())

    methods = list(methods)
    methods.sort()
    print("methods:" + "\n")
    print(methods)
    str = "Methods:"
    file = methods
    writeToTxt(str, file, filename)
    return methods
Beispiel #5
0
Datei: auto.py Projekt: wcx/DFFA
    def create_adex(self, log, dexobj):
        """
      This method is called in order to create a VMAnalysis object

      :param log: an object which corresponds to a unique app
      :param dexobj: a :class:`DalvikVMFormat` object

      :rytpe: a :class:`newVMAnalysis` object
    """
        vm_analysis = analysis.newVMAnalysis(dexobj)
        vm_analysis.create_xref()
        return vm_analysis
Beispiel #6
0
    def create_adex(self, log, dexobj):
        """
      This method is called in order to create a VMAnalysis object

      :param log: an object which corresponds to a unique app
      :param dexobj: a :class:`DalvikVMFormat` object

      :rytpe: a :class:`newVMAnalysis` object
    """
        vm_analysis = analysis.newVMAnalysis(dexobj)
        vm_analysis.create_xref()
        return vm_analysis
Beispiel #7
0
def _store_java(_vm, _args):
	_vmx = newVMAnalysis(_vm)
	_vmx.create_xref()
	_vm.set_vmanalysis(_vmx)
	_vm.create_python_export()
	#_vm.create_dref(_vmx)

	for _class in _vm.get_classes():
		try:
			_ms = decompile.DvClass(_class, _vmx)
			_ms.process()
			_f = _file_name(_class.get_name(), _args.dir)
			_ensure_dir(_f)
			with open(_f, "w") as f:
				_java = str(_ms.get_source())
				f.write(_java)
		except Exception, e:
			print("Could not process {:s}: {:s}".format(_class.get_name(), str(e)))
def get_feature_vector(path, external_api_dict):


  feature_vector = np.zeros((max_calls,len(external_api_dict),max_h),dtype=int)

  call_no = 0
  seq_no = 0

  if path.endswith('.apk'):
      app = apk.APK(path)
      app_dex = dvm.DalvikVMFormat(app.get_dex())
  else: 
      app_dex = dvm.DalvikVMFormat(open(path, "rb").read())

  app_x = analysis.newVMAnalysis(app_dex)


  cs = [cc.get_name() for cc in app_dex.get_classes()]


  # print len(app_dex.get_methods())
  for method in app_dex.get_methods():
    g = app_x.get_method(method)


    if method.get_code() == None:
      continue
  

    # print "***********"
    # print "method beeing investigated - ", g


    for i in g.get_basic_blocks().get():


      # print "i.childs : " ,i.childs

      if(i.childs!=[] and seq_no<max_h):

        call_no = 0
        for ins in i.get_instructions():

          output = ins.get_output()
          

          match = re.search(r'(L[^;]*;)->[^\(]*\([^\)]*\).*', output)
          if match and match.group(1) not in cs:
            
            # print "instruction : ", ins.get_basic_blocks()
            # print "output : ", output
            # print "external api detected: ", match.group()
            

            # if(i.childs!=[]):
              # print "-------->",i.childs[0][2].childs
              # break
            feature_vector[call_no,external_api_dict[match.group()],seq_no] = 1
            call_no+=1
     

        
        rand_child_selected = np.random.randint(len(i.childs))
        # print rand_child_selected

        traverse_graph(i.childs[rand_child_selected][2],feature_vector,cs,call_no,seq_no,external_api_dict)
        seq_no+=1

  return feature_vector
def gen_dict(list_path):

    file = open("error_files.txt", "w")

    external_api_dict = {}

    for path1 in list_path:

        count = 0

        for f in os.listdir(path1):

            # print count

            count += 1

            if (count == 300):
                break

            path = os.path.join(path1, f)
            print(path)

            try:
                if path.endswith('.apk'):
                    app = apk.APK(path)
                    app_dex = dvm.DalvikVMFormat(app.get_dex())
                else:
                    app_dex = dvm.DalvikVMFormat(open(path, "rb").read())
                app_x = analysis.newVMAnalysis(app_dex)

                methods = []
                cs = [cc.get_name() for cc in app_dex.get_classes()]

                ctr = 0
                # print len(app_dex.get_methods())
                for method in app_dex.get_methods():
                    g = app_x.get_method(method)

                    if method.get_code() == None:
                        continue

                    for i in g.get_basic_blocks().get():

                        for ins in i.get_instructions():
                            # This is a string that contains methods, variables, or
                            # anything else.

                            output = ins.get_output()

                            match = re.search(r'(L[^;]*;)->[^\(]*\([^\)]*\).*',
                                              output)
                            if match and match.group(1) not in cs:
                                methods.append(match.group())
                                # print "instruction : ", ins.get_basic_blocks()

                                # print "external api detected: ", match.group()
                                if (not external_api_dict.has_key(
                                        match.group())):
                                    external_api_dict[match.group()] = len(
                                        external_api_dict)
            except:

                file.write(path)

    file.close()

    return external_api_dict
Beispiel #10
0
def run(sampleFile, workingDir):
    if misc_config.ENABLE_STOPPING_TIME and misc_config.LOGFILE_STOPPING_FILE:
        time_analysis_start = time.time()

    if misc_config.ENABLE_CLEAR_OLD_FILES: clearOldFiles(workingDir)

    logFile = createLogFile(workingDir)
    PREFIX = workingDir
    unpackLocation = '{}/{}'.format(PREFIX, settings.DEFAULT_NAME_DIR_UNPACK)

    if (PREFIX[-1:] != "/"):
        PREFIX += "/"
    if (unpackLocation[-1:] != "/"):
        unpackLocation += "/"

    if not os.path.exists(PREFIX):
        errorMessage("Targed path %s could not be found !" % PREFIX +
                     "\nTerminating...")
        exit(1)

    if not os.path.exists(sampleFile):
        errorMessage("Could not find APK file %s !" % sampleFile +
                     "\nTerminating...")
        exit(1)

    try:
        a = apk.APK(sampleFile)
    except zipfile.BadZipfile:
        errorMessage("Encountered BadZipfile\nTerminating...")
        return

    dv = dvm.APK(sampleFile)
    d = dvm.DalvikVMFormat(a.get_dex())
    vmx = analysis.newVMAnalysis(d)

    print "get sample info..."
    appInfos = getSampleInfo(sampleFile, logFile, a)
    print 'Got Sample Information for Sample with SHA256: {}'.format(
        appInfos['sha256'])
    print "extract manifest..."
    getManifest(PREFIX, dv)
    print "unpacking sample..."
    unpack(sampleFile, PREFIX)
    print "extracting source files..."
    if misc_config.ENABLE_EXTRACT_SOURCES: extractSourceFiles(PREFIX, d, vmx)
    print "get providers..."
    appProviders = getProviders(logFile, a)
    print "get permissions..."
    appPermissions = getPermission(logFile, a)
    print "get activities..."
    appActivities = getActivities(a)
    print "get features..."
    appFeatures = usedFeatures(logFile, a)
    print "get intents..."
    appIntents = getIntents(logFile, a)
    print "get files in src..."
    if misc_config.ENABLE_EXTRACT_SOURCES:
        appFilesSrc = getFilesInsideApkSrc(workingDir)
    else:
        appFilesSrc = []
    print "get files in APK..."
    appFiles = getFilesExtendedInsideApk(a)
    print "get service and receivers"
    serviceANDreceiver = getServiceReceiver(logFile, a)
    print "get (dangerous) api calls and ad-networks..."
    (api_dict, ads_dict) = getAPICallsADs(workingDir, logFile, d)
    print "get urls and ips..."
    appUrls = parseURLs(workingDir, logFile)
    print "extract certificate information"
    cert = getCertificate(a)

    dict_dex = {'strings': [], 'fields': [], 'classes': [], 'methods': []}
    print 'get strings, fields, classes, methods...'
    if misc_config.ENABLE_PARSING_STRINGS:
        dict_dex['strings'] = list(set([x.strip() for x in d.get_strings()]))
    if misc_config.ENABLE_PARSING_FIELDS:
        dict_dex['fields'] = list(
            set([field.get_name().strip() for field in d.get_all_fields()]))
    if misc_config.ENABLE_PARSING_CLASSES:
        dict_dex['classes'] = list(
            set([x.get_name().strip() for x in d.get_classes()]))
    if misc_config.ENABLE_PARSING_METHODS:
        dict_dex['methods'] = list(
            set([x.get_name().strip() for x in d.get_methods()]))
    print "create json report..."
    createOutput(workingDir, appProviders, appPermissions, appFeatures,
                 appIntents, serviceANDreceiver, ads_dict, appUrls, appInfos,
                 api_dict, appFilesSrc, appActivities, cert, appFiles,
                 dict_dex)
    print "copy icon image..."
    copyIcon(PREFIX, workingDir)
    print "closing log-file..."
    closeLogFile(logFile)
Beispiel #11
0
                    required=True)
args = parser.parse_args()
apk_file = file_path = args.in_apk

for one in xrange(0, 1):
    log.log("starting analysis of %s" % apk_file)

    a = apk.APK(file_path)
    d = dvm.DalvikVMFormat(a.get_dex())

    log.log("completed base analysis")

    for method in d.get_methods():
        print method

    dx = analysis.newVMAnalysis(d)
    d.set_vmanalysis(dx)

    log.log("creating xrefs")
    dx.create_xref()

    class_name = "Ljava/lang/Runtime;"
    func_name = "exec"
    func_proto = "(Ljava/lang/String;)V"
    # method = dx.get_method_by_name(class_name, func_name, func_proto)

    break

    # print dir()
    # for class_str, class_obj in dx.classes.iteritems():
    # 	print class_str
Beispiel #12
0
 def __init__(self, apkpath):
     self.a = apk.APK(apkpath)
     self.d = dvm.DalvikVMFormat(self.a.get_dex())
     self.vmx = analysis.newVMAnalysis(self.d)
Beispiel #13
0
 def testDex(self):
     with open("examples/android/TestsAndroguard/bin/classes.dex", "r") as fd:
         d = dvm.DalvikVMFormat(fd.read())
         dx = analysis.newVMAnalysis(d)
         self.assertTrue(dx)
Beispiel #14
0
import os
import sys

sys.path.append('../')
from androguard.core.bytecodes import apk, dvm
from androguard.core.analysis import analysis

if __name__ == '__main__':
    for root, dirs, files in os.walk('../input'):
        for current_apk_file in files:
            cwd = os.path.abspath("../input")
            current_apk_file = cwd + os.sep + current_apk_file
            if current_apk_file.endswith(".apk"):
                print 'Current Apk file name is: ' + current_apk_file
                a = apk.APK(current_apk_file)
                if a.is_valid_apk():
                    vm = dvm.DalvikVMFormat(a.get_dex())
                    vmx = analysis.newVMAnalysis(vm)
                    vmx.explicit_icfg()
                else:
                    print 'Invalid Apk'
                    exit()

Beispiel #15
0
 def testDex(self):
     with open("examples/android/TestsAndroguard/bin/classes.dex",
               "r") as fd:
         d = dvm.DalvikVMFormat(fd.read())
         dx = analysis.newVMAnalysis(d)
         self.assertTrue(dx)
	def __init__(self, apkpath):
		self.a = apk.APK(apkpath)
		self.d = dvm.DalvikVMFormat(self.a.get_dex())
		self.vmx = analysis.newVMAnalysis(self.d)