Esempio n. 1
0
 def __init__(self, name):
     vm = AndroguardS(name).get_vm()
     vma = analysis.uVMAnalysis(vm)
     self.classes = {
         dvclass.get_name(): DvClass(dvclass, vma)
         for dvclass in vm.get_classes()
     }
     util.merge_inner(self.classes)
Esempio n. 2
0
	def get_methods2(self) :
		## parse the apk file
		a = AndroguardS(self.__folder +"\\"+ self.__filename + '.apk')
		for method in a.get_methods() :
			class_name = method.get_class_name()
			method_name = method.get_name()
			## filter useless file
			if class_name.find('Landroid')==-1 and class_name.find('BuildConfig',0)==-1 and class_name.find('R$',0)==-1 and class_name.find('R;',0)==-1 and method_name.find('<clinit>',0)==-1:
				if self.getfolder().replace('\\','/') in class_name:
					method = '%s--->%s%s\n' %(class_name, method.get_name(), method.get_descriptor())
					self.__methods.append(method.replace(' ',''))	
				## record all methods
				
		with open(Constant.info_path+self.__filename+"\\"+Constant.method_file, 'w') as methods_write :
			for m in self.__methods:
				methods_write.write(m)
Esempio n. 3
0
 def get_methods(self):
     ## initial self.package
     self.get_package()
     ## parse the apk file
     a = AndroguardS(self.__path + self.__filename + '.apk')
     for method in a.get_methods():
         class_name = method.get_class_name()
         method_name = method.get_name()
         ## filter useless file
         if class_name.find('Landroid') == -1 and class_name.find(
                 'BuildConfig', 0) == -1 and class_name.find(
                     'R$', 0) == -1 and class_name.find(
                         'R;', 0) == -1 and method_name.find('<clinit>',
                                                             0) == -1:
             if self.getPackagePath() in class_name:
                 method = '%s--->%s%s' % (class_name, method.get_name(),
                                          method.get_descriptor())
                 self.__methods.append(method)
Esempio n. 4
0
    def run_loader(self):
        """
        Load the target APK and return
        the loaded instance, which will
        be stored as a global
        """

        print(
            t.green("[{0}] ".format(datetime.now()) + t.yellow("Loading : ") +
                    "{0}".format(self.apk)))

        return APK(self.apk), AndroguardS(self.apk)
Esempio n. 5
0
    def run_loader(self):
        """
        Load the target APK and return
        the loaded instance, which will
        be stored as a global
        """

        if self.args[0] == "apk":
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Loading : ") + "{0}".format(self.args[1])))
            try:
                apk = APK(self.args[1])
                return apk
            except IOError as e:
                raise e

        elif self.args[0] == "dex":
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Loading : ") + "{0}".format(self.args[1])))
            try:
                d = dvm.DalvikVMFormat(read(self.args[1], binary=False))
                return d
            except IOError as e:
                raise e

        else:
            print(
                t.green("[{0}] ".format(datetime.now()) +
                        t.yellow("Loading : ") + "{0}".format(self.args[0])))
            try:
                apk = APK(self.args[0])
                apks = AndroguardS(self.args[0])
                return apk, apks
            except struct.error:
                print(
                    t.red("[{0}] ".format(datetime.now())) + t.white(
                        "The application does not contain an executable file"))
                print(
                    t.red("[{0}] ".format(datetime.now())) +
                    t.white("Please load the application as an APK only"))
                sys.exit(1)
Esempio n. 6
0
#!/usr/bin/env python

import sys, hashlib

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)

from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis

TEST = 'examples/android/TestsAndroguard/bin/classes.dex'

a = AndroguardS(TEST)
x = analysis.VMAnalysis(a.get_vm())

for method in a.get_methods():
    g = x.get_method(method)

    if method.get_code() == None:
        continue

    idx = 0
    for i in g.basic_blocks.get():
        for ins in i.get_instructions():
            op_value = ins.get_op_value()

            # packed/sparse
            if op_value == 0x2b or op_value == 0x2c:
                special_ins = i.get_special_ins(idx)
                if special_ins != None:
                    print "\t %x" % idx, ins, special_ins, ins.get_name(
def display_SEARCH_METHODS(a, x, classes, package_name, method_name, descriptor):
    print("Search method", package_name, method_name, descriptor)
    analysis.show_Paths( a, x.get_tainted_packages().search_methods( package_name, method_name, descriptor) )

def display_PERMISSION(a, x, classes):
    # Show methods used by permission
    perms_access = x.get_tainted_packages().get_permissions( [] )
    for perm in perms_access:
        print("PERM : ", perm)
        analysis.show_Paths( a, perms_access[ perm ] )

def display_OBJECT_CREATED(a, x, class_name):
    print("Search object", class_name)
    analysis.show_Paths( a, x.get_tainted_packages().search_objects( class_name ) )

a = AndroguardS( TEST )
x = analysis.uVMAnalysis( a.get_vm() )

#print a.get_vm().get_strings()
print(a.get_vm().get_regex_strings( "access" ))
print(a.get_vm().get_regex_strings( "(long).*2" ))
print(a.get_vm().get_regex_strings( ".*(t\_t).*" ))

classes = a.get_vm().get_classes_names()
vm = a.get_vm()

display_CFG( a, x, classes )
display_STRINGS( vm, x, classes )
display_FIELDS( vm, x, classes )
display_PACKAGES( vm, x, classes )
display_PACKAGES_IE( vm, x, classes )
Esempio n. 8
0
        32768.5, 32767.5, 32766.5, -5, -65535, -65536,
        -123456789123456789.555555555, -123456789123456789.555555555,
        -606384730, -123456790519087104, 3.5
    ],
}


def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print '%s got: %s expected: %s' % (prefix, repr(got), repr(expected))


a = AndroguardS(TEST_CASE)

for method in a.get_methods():
    key = method.get_class_name() + " " + method.get_name(
    ) + " " + method.get_descriptor()

    if key not in VALUES:
        continue

    print method.get_class_name(), method.get_name(), method.get_descriptor()
    code = method.get_code()
    bc = code.get_bc()

    idx = 0
    for i in bc.get():
        #print "\t", "%x" % idx, i.get_name(), i.get_operands()
Esempio n. 9
0
        -123456789123456789.555555555,
        -606384730,
        -123456790519087104,
        3.5
        ],
}

def test(got, expected):
    if got == expected:
        prefix = ' OK '
    else:
        prefix = '  X '
    print('%s got: %s expected: %s' % (prefix, repr(got), repr(expected)))


a = AndroguardS( TEST_CASE )

for method in a.get_methods():
    key = method.get_class_name() + " " + method.get_name() + " " + method.get_descriptor()

    if key not in VALUES:
        continue

    print(method.get_class_name(), method.get_name(), method.get_descriptor())
    code = method.get_code()
    bc = code.get_bc()

    idx = 0
    for i in bc.get():
        #print "\t", "%x" % idx, i.get_name(), i.get_operands()
        if "const" in i.get_name():
Esempio n. 10
0
    def run_loader(self):
        """
        Load the target APK and return the loaded instance, which will be stored as a global
        """

        if self.args[0] == enum.apk:
            # Load APK without classes.dex
            # The second element in this array should be the file path
            if os.path.splitext(self.args[1])[1] != ".apk":
                print(
                    t.red("[{0}] ".format(datetime.now())) +
                    t.white(enum.NOT_AN_APK))
            else:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Loading : ") +
                            "{0}".format(self.args[1])))
                try:
                    # Return an APK object
                    apk = APK(self.args[1])
                    return apk
                except IOError as e:
                    raise e
        elif self.args[0] == enum.dex:
            # Load classes.dex
            # The second element in this array should be the file path
            if os.path.splitext(self.args[1])[1] != ".dex":
                print(
                    t.red("[{0}] ".format(datetime.now())) +
                    t.white(enum.NOT_A_DEX))
            else:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Loading : ") +
                            "{0}".format(self.args[1])))
                try:
                    # Return a DalvikVM object
                    d = dvm.DalvikVMFormat(read(self.args[1], binary=False))
                    return d
                except IOError as e:
                    raise e
        else:
            # Load APK with classes.dex
            # The first argument should be the file path
            if os.path.splitext(self.args[0])[1] != ".apk":
                print(
                    t.red("[{0}] ".format(datetime.now())) +
                    t.white(enum.NOT_AN_APK))
            else:
                print(
                    t.green("[{0}] ".format(datetime.now()) +
                            t.yellow("Loading : ") +
                            "{0}".format(self.args[0])))
                try:
                    # Return an APK and APKS object
                    apk = APK(self.args[0])
                    apks = AndroguardS(self.args[0])
                    return apk, apks
                except struct.error:
                    print(
                        t.red("[{0}] ".format(datetime.now())) +
                        t.white(enum.FILE_TYPE_ERROR))
                    print(
                        t.red("[{0}] ".format(datetime.now())) +
                        t.white(enum.APK_ONLY_ERROR))
                    sys.exit(1)
        with os.fdopen(file_handle, 'w') as file_obj:
            file_obj.write("\t\t" + "Analysis Result"+ "\n")
            # write app infomation
            fileUtils.write_app_info_to_file(appName, file_obj);
            fileUtils.write_app_activities_to_file(appName, file_obj);
            fileUtils.write_app_permissions_to_file(appName, file_obj);
            fileUtils.write_all_permissions_to_file(appName, file_obj);
            fileUtils.write_permissions_analysis_to_file(appName, file_obj);
            fileUtils.write_sensitive_apis_to_file(appName, file_obj);
            file_obj.close()


# -- comment -- create database with name is the name of the input file --
#createDatabase(analysis_init_default_value.APP_NAME)

a = AndroguardS( TEST )

x = analysis.uVMAnalysis( a.get_vm() )
#print a.get_vm().get_strings()

print a.get_vm().get_regex_strings( "access" )
print a.get_vm().get_regex_strings( "(long).*2" )
print a.get_vm().get_regex_strings( ".*(t\_t).*" )

classes = a.get_vm().get_classes_names()
vm = a.get_vm()

display_STRINGS( vm, x, classes )
#display_PERMISSION( vm, x, classes )
#display_PACKAGES( vm, x, classes )
Esempio n. 12
0
#!/usr/bin/env python

import sys, hashlib

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)

from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis
from androguard.core.bytecodes import dvm

TEST = 'examples/android/TestsAndroguard/bin/classes.dex'

a = AndroguardS(TEST)
x = analysis.VMAnalysis(a.get_vm())

# CFG
for method in a.get_methods():
    g = x.get_method(method)

    # Display only methods with exceptions
    if method.get_code() == None:
        continue

    if method.get_code().tries_size <= 0:
        continue

    print method.get_class_name(), method.get_name(), method.get_descriptor(
    ), method.get_code().get_length(), method.get_code().registers_size

    idx = 0
 def analysis_apk(self, apkpath):#apk dex analysis
     self.a = AndroguardS(apkpath)
     self.x = analysis.VMAnalysis(self.a.get_vm())
     self.classes = self.a.get_vm().get_classes_names()
class AssDexAnalysis(AssModule):
    def init(self, argv):
        super(AssDexAnalysis, self).init(argv)
        self.analysis_apk(self.apk_file)

    def analysis_apk(self, apkpath):#apk dex analysis
        self.a = AndroguardS(apkpath)
        self.x = analysis.VMAnalysis(self.a.get_vm())
        self.classes = self.a.get_vm().get_classes_names()


    def search_method_withparams(self, class_name, method_namelist, descriptor, param_list):#search a method that have params
        pathdic = {}
        for method_name in method_namelist:
            paths = analysis.get_Paths(self.a, self.x.get_tainted_packages().search_methods( class_name, method_name, descriptor))
            for path in paths:
                pathset = path['src'].split(' ', 2)
                method_class_set = self.a.get_vm().get_methods_class(pathset[0])
                for method in method_class_set:
                    if method.get_name() == pathset[1] and method.get_descriptor() == pathset[2]:
                        code = method.get_code()
                        if code == None:
                            continue
                        bc = code.get_bc()
                        instructions = [i for i in bc.get_instructions()]
                        for instruction in instructions:
                            if self.check_params(instruction, param_list):
                                pathdic[pathset[0][:-1]] = pathset[0][:-1] + "/" + pathset[1]
        return  pathdic.values()

    def check_params(self, instruction, param_list):#match the param
        if isinstance(instruction,Instruction21c) and instruction.get_op_value()==0x1A:
            outputset = instruction.get_output(-1)
            for listItem in param_list:
                if listItem in outputset:
                    return True
        return False

    def search_method_noparams(self, class_name, method_namelist, descriptor):#search a method that have no param
        pathdic = {}
        for method_name in method_namelist:
            #print "search method", package_name, method_name, descriptor
            #analysis.show_Paths(self.a, self.x.get_tainted_packages().search_methods( package_name, method_name, descriptor) )
            paths = analysis.get_Paths(self.a, self.x.get_tainted_packages().search_methods( class_name, method_name, descriptor))
            # for path in paths:
            #     pathset = path['src'].split(' ')
            #     if class_name == pathset[0][0:-1]:
            #         pathdic[pathset[0][:-1]] = pathset[0][:-1] + "/" + pathset[1]
            #     elif class_name == "all":
            #         pathdic[pathset[0][:-1]] = pathset[0][:-1] + "/" + pathset[1]
            #     else:
            #         continue
            for path in paths:
                pathset = path['src'].split(' ')
                pathdic[pathset[0][:-1]] = pathset[0][:-1] + "/" + pathset[1]
        return pathdic.values()


    def search_str(self,stringItem):#search all strings
        for s, _ in self.x.get_tainted_variables().get_strings():
            if stringItem == _:
                return s.get_paths()
        return None

    def match_str(self,keywordlist):#match the specific string
        strDict = {}
        for keyword in keywordlist:
            stringset = self.a.get_vm().get_regex_strings(keyword)
            for stringsetItem in stringset:
                pathInfo = self.search_str(stringsetItem)
                if pathInfo == None:
                    continue
                strDict[stringsetItem] = []
                for path in pathInfo:
                    access, idx = path[0]
                    m_idx = path[1]
                    method = self.a.get_vm().get_cm_method(m_idx)
                    strDict[stringsetItem].append("{:s}->{:s} {:s}".format(method[0], method[1], method[2][0] + method[2][1]))
        vadlist = []
        for va in strDict.values():
            vadlist.extend(va)
        return vadlist

    def run(self):
        print "dex analysis  begin"
        super(AssDexAnalysis, self).run()
        for keyworddict in keyword_list:
            print keyworddict['id']
            riskdic = {"strrisk":[], "methNoParam":[], "methWithParam":[]}
            n = 1
            for type in keyworddict['type']:
                pkey = 'key'
                pclass = 'class'
                pparam = 'param'
                if type == '0':
                    strkey  = keyworddict[ pkey + str(n) ]
                    riskdic["strrisk"].extend(self.match_str(strkey))
                    n = n + 1
                elif type == '1':
                    methnokey = keyworddict[ pkey + str(n) ]
                    methnoclass = keyworddict[ pclass + str(n) ]
                    riskdic["methNoParam"].extend(self.search_method_noparams(methnoclass, methnokey, "."))
                    n = n + 1
                else:
                    methwithkey = keyworddict[ pkey + str(n) ]
                    methwithclass = keyworddict[ pclass + str(n) ]
                    methwithparam = keyworddict[ pparam + str(n) ]
                    riskdic["methWithParam"].extend(self.search_method_withparams(methwithclass, methwithkey, ".", methwithparam))
                    n = n + 1
            flag = self.judge_rule(riskdic, "or" , keyworddict['type'])
            if keyworddict.has_key('not'):
                flag = not flag
            if flag:
                account,riskString = self.convertDictToStr(riskdic)
                #self.report.setItem(keyworddict['id'], self.convertDictToStr(riskdic))
                self.report.setItem(keyworddict['id'], riskString,account)
        print "dex analysis  end"

    def convertDictToStr(self, dict):
        num = 0
        Tostr = ""
        if dict["strrisk"] != None and len(dict["strrisk"]) != 0:
            for i in dict["strrisk"]:
                print "**************************************************"
                print type(i)
                Tostr += (i + "\n")
            num += len(dict["strrisk"])
            print num

        if dict["methNoParam"] != None and len(dict["methNoParam"]) != 0:
            for i in dict["methNoParam"]:
                print "**************************************************"
                print type(i)
                Tostr += (i + "\n")
            num += len(dict["methNoParam"])
            print num
        if dict["methWithParam"] != None and len(dict["methWithParam"]) != 0:
            for i in dict["methWithParam"]:
                print "**************************************************"
                print type(i)
                Tostr += (i + "\n")
            num += len(dict["methWithParam"])
            print num
        print num
        restr = "风险数量:"+ str(num) + "\n" + Tostr
        return (num,restr)
        #return restr
        #return Tostr

    def judge_rule(self, dic , rule , type):
        b1 = b2 = b3 = 0
        if "0" in type:
            if dic.has_key("strrisk") and len(dic["strrisk"]) == 0 :
                b1 = -1 # no risk
            else:
                b1 = 1 #exist risk
        if "1" in type:
            if dic.has_key("methNoParam") and len(dic["methNoParam"]) == 0:
                b2 = -1
            else:
                b2 = 1
        if "2" in type:
            if dic.has_key("methWithParam") and len(dic["methWithParam"]) == 0:
                b3 = -1
            else:
                b3 = 1
        if rule == "or":
            return b1 > 0 or b2 > 0 or b3 > 0
Esempio n. 15
0
#!/usr/bin/env python

import sys

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)

from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis

TEST = 'examples/android/TestsAndroguard/bin/classes.dex'

a = AndroguardS( TEST )
x = analysis.VMAnalysis( a.get_vm() )

for method in a.get_methods() :
    g = x.get_method( method )

    if method.get_code() == None :
      continue

    idx = 0
    for i in g.basic_blocks.get() :
        for ins in i.get_instructions() :   
            op_value = ins.get_op_value()
            
            # packed/sparse
            if op_value == 0x2b or op_value == 0x2c :
                special_ins = i.get_special_ins(idx)
                if special_ins != None :
                    print "\t %x" % idx, ins, special_ins, ins.get_name(), ins.get_output(), special_ins.get_values()
Esempio n. 16
0
        if key not in values:
            continue

        print "CHECKING ...", method.get_class_name(), method.get_name(
        ), method.get_descriptor()
        code = method.get_code()
        bc = code.get_bc()

        idx = 0
        for i in bc.get():
            #            print "\t", "%x(%d)" % (idx, idx), i.get_name(), i.get_operands()
            if idx in values[key]:
                elem = values[key][idx]

                val1 = i.get_name() + "%s" % i.get_operands()
                val2 = elem[0] + "%s" % elem[1]

                test(val1, val2)

                del values[key][idx]

            idx += i.get_length()


for i in TESTS_CASES:
    a = AndroguardS(i)
    check(a, VALUES[i])

    x = analysis.VMAnalysis(a.get_vm())
    print x
Esempio n. 17
0
#!/usr/bin/env python

import sys, hashlib

PATH_INSTALL = "./"
sys.path.append(PATH_INSTALL)

from androguard.core.androgen import AndroguardS
from androguard.core.analysis import analysis
from androguard.core.bytecodes import dvm

TEST = 'examples/android/TestsAndroguard/bin/classes.dex'

a = AndroguardS( TEST )
x = analysis.VMAnalysis( a.get_vm() )


# CFG
for method in a.get_methods():
    g = x.get_method( method )

    # Display only methods with exceptions
    if method.get_code() == None:
      continue

    if method.get_code().tries_size <= 0:
      continue

    print method.get_class_name(), method.get_name(), method.get_descriptor(), method.get_code().get_length(), method.get_code().registers_size

    idx = 0
Esempio n. 18
0
        if key not in values :
            continue

        print "CHECKING ...", method.get_class_name(), method.get_name(), method.get_descriptor()
        code = method.get_code()
        bc = code.get_bc()

        idx = 0
        for i in bc.get() :
#            print "\t", "%x(%d)" % (idx, idx), i.get_name(), i.get_operands()
            if idx in values[key] :
                elem = values[key][idx]

                val1 = i.get_name() + "%s" % i.get_operands()
                val2 = elem[0] + "%s" % elem[1]

                test(val1, val2)

                del values[key][idx]

            idx += i.get_length()


for i in TESTS_CASES :
    a = AndroguardS( i )
    check( a, VALUES[i] )

    x = analysis.VMAnalysis( a.get_vm() )
    print x
Esempio n. 19
0
 def __init__(self, name):
     vm = AndroguardS(name).get_vm()
     vma = analysis.uVMAnalysis(vm)
     self.classes = {dvclass.get_name(): DvClass(dvclass, vma)
                                     for dvclass in vm.get_classes()}
     util.merge_inner(self.classes)
Esempio n. 20
0
    for method in a.get_methods():
        key = method.get_class_name() + " " + method.get_name(
        ) + " " + method.get_descriptor()

        if key not in modif:
            continue

        print "MODIFYING ...", method.get_class_name(), method.get_name(
        ), method.get_descriptor()
        code = method.get_code()

        for i in modif[key]:
            getattr(code, i[0])(*i[1:])


a = AndroguardS(TEST_CASE)

### INIT CHECK ###
check(a, VALUES, BRANCH2_JVM_OPCODES)
### APPLY MODIFICATION ###
modify(a, MODIF)
### CHECK IF MODIFICATION IS OK ###
check(a, VALUES, BRANCH2_JVM_OPCODES)

modify(a, MODIF2)
check(a, VALUES, BRANCH2_JVM_OPCODES)

modify(a, MODIF3)
check(a, VALUES3, BRANCH2_JVM_OPCODES)

modify(a, MODIF4)