def main(queue):
	global parser
	global tree
	results = []
	count = 0

	if common.minSdkVersion<19:
		weak_rng_warning(results)
	find_key_files(results)
	for j in common.java_files:
		count = count + 1
		pub.sendMessage('progress', bar='Crypto issues', percent=round(count*100/common.java_files.__len__()))
		try:
			tree=parser.parse_file(j)
			if tree is not None:
				#if re.search(r'\.getInstance\(',str(tree)):
				#	print "YES"
				for type_decl in tree.type_declarations:
					if type(type_decl) is m.ClassDeclaration:
						for t in type_decl.body:
							try:
								recursive_ecb_check(t,j,results)
								#fixedSeedCheck(t,j)
							except Exception as e:
								common.logger.debug("Error running recursive_ecb_check in cryptoFlaws.py: " + str(e))
								report.write("parsingerror-issues-list", "Error running recursive_ecb_check in cryptoFlaws.py: " + str(e), "strong")

		except Exception as e:
			common.logger.debug("Unable to create tree for " + str(j))
			report.write("parsingerror-issues-list", "Unable to create tree for " + str(j), "strong")
	queue.put(results)
	return
def validate(queue,height):
    """
    Validates common pitfalls for certificate validation logic
    """
    #writer1 = common.Writer((0, height))
    results = []
    global tree
    global parser
    global filename
    global warningGiven
    global sslSessions
    count = 0

    for j in common.java_files:
        sslSessions=[]
        count = count + 1
        pub.sendMessage('progress', bar='X.509 Validation', percent=round(count*100/common.java_files.__len__()))
        filename=str(j)
        try:
            tree=parser.parse_file(j)
        except Exception as e:
            continue
            # No need to log this since we now warn potential parsing errors on screen and provide details in the report.
        if tree is None:
            results.append("Some files may not be parsed correctly. For a list of such files, please review the final report.")
        else:
            try:
                for type_decl in tree.type_declarations:
                    if type(type_decl) is m.ClassDeclaration:
                        for t in type_decl.body:
                            try:
                                recursive_insecure_trust_manager(t,j,results)
                            except Exception as e:
                                common.logger.error("Unable to run recursive_insecure_trust_manager in certValidation.py: " + str(e))
                            try:
                                recursive_allow_all_hostname_verifier(t,j,results)
                            except Exception as e:
                                common.logger.error("Unable to run recursive_allow_all_hostname_verifier in certValidation.py: " + str(e))
                            try:
                                recursive_ssl_session(t,j,results)
                            except Exception as e:
                                common.logger.error("Unable to run recursive_ssl_session in certValidation.py: " + str(e))
            except Exception as e:
                if common.source_or_apk==2:
                    common.logger.error("Error in validate function of certValidation.py: " + str(e))
                else:
                    common.logger.error("Bad file: " + str(j) + ", this is not uncommon")
            try:
                recursive_find_verify(None,j,results)
            except Exception as e:
                common.logger.error("Problem in findVerify function of certValidation.py: " + str(e))
        warningGiven=False
    unverified_sessions(results)
    queue.put(results)
    return
def text_scan(file_list,rex_n):
    """
    Given a list of files, search content of each file by the regular expression and return a list of matches
    """
    result_list=[]
    result_list.append([])
    count = 0
    for x in file_list:
        count = count + 1
        pub.sendMessage('progress', bar='Webview checks', percent=round(count*100/common.java_files.__len__()))
        result=common.read_files(x,rex_n)
        if len(result)>0:
            result_list.append([result,x])
    return result_list
def procyon(path,dirname):
	"""
	calls the procyon decompiler from command line
	"""
	process = subprocess.Popen(["java","-jar", common.rootDir + "/lib/procyon/procyon-decompiler-0.5.30.jar", path, "-o ", dirname+"2"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	try:
		while True:
			line = process.stdout.readline()
			if not line:
				break
			if "Decompiling" in line:
				common.counter2 = common.counter2 + 1
				pub.sendMessage('decompile', procyon=round(common.counter2*100/common.count))
	except Exception as e:
		logger.debug(e.message)
def cfr(path,dirname):
	"""
	calls the cfr decompiler from command line
	"""
	process = subprocess.Popen(["java","-jar", common.rootDir + "/lib/cfr_0_115.jar", path, "--outputdir", dirname+"1"], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
	try:
		while True:
			line = process.stdout.readline()
			if not line:
				break
			if "Processing" in line:
				common.counter1 = common.counter1 + 1
				pub.sendMessage('decompile', cfr=round(common.counter1*100/common.count))
				pub.sendMessage('decompile', jdcore=round(common.counter1*100/common.count))
	except Exception as e:
		logger.debug(e.message)
def main(queue):
	global current_file
	global parser
	global tree
	results = []
	count = 0

	common.logger.debug("Checking for any broadcasts sent from this app......")
	for j in common.java_files:
		count = count + 1
		pub.sendMessage('progress', bar="Broadcast issues", percent=round(count*100/common.java_files.__len__()))
		current_file=j
		try:
			tree=parser.parse_file(j)
			if type(tree) is not None:
				if hasattr(tree,'type_declarations'):
					for type_decl in tree.type_declarations:
						if type(type_decl) is m.ClassDeclaration:
							for t in type_decl.body:
								try:
									recursive_broadcast_finder(t,results)
								except Exception as e:
									common.parsingerrors.add(str(j))
									common.logger.debug("Unable to process recursive_broadcast_finder in findBroadcasts.py: " + str(e))
						elif type(type_decl) is list:
							for y in type_decl:
								recursive_broadcast_finder(y,results)
						elif hasattr(type_decl,'_fields'):
							for d in type_decl._fields:
								recursive_broadcast_finder(getattr(type_decl,d),results)
			else:								
				common.logger.debug("Unable to create tree for " + str(j))
		except Exception as e:
			common.logger.debug("Tree exception during broadcast processing: " + str(e))
			common.parsingerrors.add(str(j))
	queue.put(results)
	return
def start(queue,height):
	"""
	Start finding pending intents
	"""
	results = []
	global tree
	global current_file
	count = 0

	#TODO - Look for use of fillIn method which can make this a much more exploitable condition
	for j in common.java_files:
		count = count + 1
		pub.sendMessage('progress', bar='Pending Intents', percent=round(count*100/common.java_files.__len__()))
		current_file=j
		try:
			tree=parser.parse_file(j)
		except ValueError as e:
			continue
		#TODO - Need to add scanning of the imports, to see if Intent or PendingIntent is extended, was working on it, 
		#but the one issue where it arose was non-trivial, so I gave up for now
		if hasattr(tree,'type_declarations'):
			for type_decl in tree.type_declarations:
				if type(type_decl) is m.ClassDeclaration:
					for t in type_decl.body:
						for f in t._fields:
							#dynamically parse each token where is f is the field and t is the token
							try:
								recurse(f,t,results)
							except Exception as e:
								common.logger.debug("Problem in recurse function of findPending.py: " + str(e))
								common.parsingerrors.add(str(current_file))

		else:
			common.logger.debug("No type declarations: " + str(j))
			report.write("parsingerror-issues-list", str(current_file), "strong")
	queue.put(results)
	return