def add_bookshelves(new_bookshelves):
    """

    Get all books in bookshelf <name> and update metadata

    Args:
        new_bookshelves: a dictionary {bookshelf_name: {id of bookshelf's books}}

    Returns:
          None

    """
    assert isinstance(new_bookshelves, dict)
    bookshelves = defaultdict(lambda: set(), get_bookshelves())
    new_ids = set.union(*new_bookshelves.values())
    books = get_books(new_ids)
    new_books = create_metadata(new_ids - set(books))
    new_books = create_gutenberg_books(new_books, dic=True)
    books = dict(books.items() + new_books.items())
    for bookshelf, bookshelf_ids in new_bookshelves.items():
        bookshelves[bookshelf] = bookshelves[bookshelf] | bookshelf_ids
        for id in bookshelf_ids:
            books[id].add_bookshelf(bookshelf)
    add_books(books.values())
    path = os.path.dirname(HP.BOOK_SHELVES_PATH)
    if not os.path.exists(path):
        os.makedirs(path)
    with open(HP.BOOK_SHELVES_PATH, "wb") as f:
        pickle.dump(dict(bookshelves), f)
示例#2
0
def check_menu():
    bool = False

    while (not bool):
        print(
            '\nEnter a valid directory/.smali file path - absolute or relative -: \n'
        )
        target = input('>> ')

        if ((os.path.exists(target)) and (os.path.isdir(target) \
        or (os.path.isfile(target) and target.endswith('.smali')))):
            bool = True
            menu = '\nSearch for injected code: \n'

            if (os.path.isdir(target)):
                my_metadata = {}
                print('\n::INFO  Creation of metadata...')
                my_metadata = metadata.create_metadata(target)
                metadata.check_dir(os.path.basename(target), my_metadata)

            else:
                file_metadata = {}
                print('\n::INFO  Creation of metadata...')
                file_metadata = metadata.create_file_metadata(target)
                metadata.check_file(os.path.basename(target), file_metadata)

        else:
            print(
                '\n::WARN  {0} does not exist/is not valid, please try again... '
                .format(target))
            bool = False
示例#3
0
def treat_dir(target, code_to_inject):
	print('::INFO  Creation of metadata...')
	my_metadata = metadata.create_metadata(target)
	process.copy_smali_class_files(target)	
	args = parseArgs()
	
	if (args.keywords):
		keywords = args.keywords.split(',')
		process.process_dir(target, my_metadata, code_to_inject, keywords)
		
	else:		
		process.process_dir(target, my_metadata, code_to_inject)
		
	process.processed_dir_info(os.path.basename(target), code_to_inject, my_metadata)		
def add_books(books_list):
    """

    Add books to dataset

    Args:
        books_list: a set of books id or GutenbergBooks

    """
    gb_list = {book for book in books_list if isinstance(book, GutenbergBook)}
    id_list = {book for book in books_list if isinstance(book, int)}
    books = get_books()
    id_list = id_list - set(books)
    assert all([isvalid(i) for i in id_list])
    new_metadata_id = create_metadata(id_list)
    new_books = gb_list | create_gutenberg_books(new_metadata_id)
    for book in new_books:
        books[book.id] = book
    path = os.path.dirname(HP.BOOKS_DATA_PATH)
    if not os.path.exists(path):
        os.makedirs(path)
    pk = open(HP.BOOKS_DATA_PATH, "wb")
    pickle.dump(create_metadata(books.values()), pk)
    pk.close()
示例#5
0
def inject_submenu(target, code_to_inject):
    class_file_path = None
    bool = False
    menu =  '\nSelect an injection option: \n' + \
      '\t1)  Inject everywhere \n' + \
      '\t2)  Inject into specific methods \n'

    while (not bool):
        print(menu)
        choice = input('>> ')

        if (choice == '1'):
            bool = True

            print('\n::INFO  Creation of metadata...')

            if (os.path.isdir(target)):
                my_metadata = metadata.create_metadata(target)
                class_file_path = process.copy_class_file(target)
                process.process_dir(target, class_file_path, my_metadata,
                                    code_to_inject)
                process.processed_dir_info(os.path.basename(target),
                                           code_to_inject, my_metadata)

            else:
                print(target)
                file_metadata = metadata.create_file_metadata(target)
                class_file_path = process.copy_class_file(
                    os.path.dirname(target))
                process.process_file(target, file_metadata, code_to_inject)
                process.processed_file_info(os.path.basename(target),
                                            code_to_inject, file_metadata)

        elif (choice == '2'):
            keywords = []
            networking_kws_list = [
                'apache', 'bouncycastle', 'cert', 'client', 'http', 'inet',
                'network', 'socket', 'ssl', 'url', 'x509'
            ]
            bool = True
            submenu= '\nEnter a keywords list - a list of method names, for example - separated by the \',\' char, or use a pre-compiled list: \n'  + \
               '-------------------------\n' + \
               'Pre-compiled lists: \n' + \
               '\t1) Networking \n' + \
               '-------------------------\n'

            print(submenu)
            choice = input('>> ')

            print('\n::INFO  Creation of metadata...')

            if (choice == '1' and choice.isdigit()):
                keywords = networking_kws_list

                if (os.path.isdir(target)):
                    my_metadata = metadata.create_metadata(target)
                    class_file_path = process.copy_class_file(target)
                    process.process_dir(target, class_file_path, my_metadata,
                                        code_to_inject, keywords)
                    process.processed_dir_info(os.path.basename(target),
                                               code_to_inject, my_metadata)

                else:
                    file_metadata = metadata.create_file_metadata(target)
                    class_file_path = process.copy_class_file(
                        os.path.dirname(target))
                    process.process_file(target, file_metadata, code_to_inject,
                                         keywords)
                    process.processed_file_info(os.path.basename(target),
                                                code_to_inject, file_metadata)

            else:
                keywords = choice.split(',')

                if (os.path.isdir(target)):
                    my_metadata = metadata.create_metadata(target)
                    class_file_path = process.copy_class_file(target)
                    process.process_dir(target, class_file_path, my_metadata,
                                        code_to_inject, keywords)
                    process.processed_dir_info(os.path.basename(target),
                                               code_to_inject, my_metadata)

                else:
                    file_metadata = metadata.create_file_metadata(target)
                    class_file_path = process.copy_class_file(
                        os.path.dirname(target))
                    process.process_file(target, file_metadata, code_to_inject,
                                         keywords)
                    process.processed_file_info(os.path.basename(target),
                                                code_to_inject, file_metadata)

        else:
            bool = False
示例#6
0
def main():
	args = parseArgs()
	
	if (args.graph):
		graphic_interface.main_menu()

	elif (args.app and args.code_to_inject):
		app = os.path.abspath(args.app)
		
		if (os.path.isfile(app) and app.endswith('.apk')):
			inject_user_input = args.code_to_inject
			code_to_inject = check_inject_arg(inject_user_input)
			head, tail = os.path.split(app)
			tail = os.path.splitext(tail)[0]
			
			if (code_to_inject):				
				if (not os.getenv('JAVA_HOME') or (os.getenv('JAVA_HOME') not in os.getenv('PATH'))):
					nenv = os.environ.copy()
					nenv['JAVA_HOME'] = 'C:/Program Files/Java/jdk1.8.0_45'
					nenv['PATH'] += ';C:/Program Files/Java/jdk1.8.0_45/bin'
				
				print('\n::INFO  Disassembly {0}...\n'.format(tail))
				sp = subprocess.Popen([	'java', '-jar', os.path.join('modules', 'baksmali.jar'), 
										'-p', app, '-o', os.path.join('smali', tail)], shell=True, env=nenv)
				sp.wait()	
				
				if (args.target):
					# For the target to be ./smali/skandiabanken-smali-mod/se just enter --target se
					target = os.path.join('smali', tail + '-mod', args.target)
					helper.copy(os.path.join('smali', tail ), os.path.join('smali', tail + '-mod'))	
					
					if ((os.path.exists(target)) and (os.path.isdir(target) \
					or (os.path.isfile(target) and target.endswith('.smali')))):
						if (os.path.isdir(target)):
							treat_dir(target, code_to_inject)
						else:
							treat_file(target, code_to_inject)
					
					else:
						print('\n::WARN  {0} does not exist/is not valid, please try again... \n' .format(target))
						sys.exit(0)
						
				else:
					target = os.path.join('smali', tail + '-mod')
					helper.copy(os.path.join('smali', tail), target)	
					treat_dir(target, code_to_inject)
				
				
				print('::INFO  Assembly {0} into classes.dex...'.format(os.path.join('smali', tail + '-mod')))
				sp1 = subprocess.Popen(['java', '-jar', os.path.join('modules', 'smali.jar'), os.path.join('smali', tail + '-mod'), 
										'-o', os.path.join('apps', 'classes.dex')], shell=True, env=nenv)
				sp1.wait()
				
				# We create an app-mod folder and erase its certificates
				zfile = zipfile.ZipFile(app).extractall(os.path.join('apps', tail + '-mod'))
				
				for root, subdirs, files in os.walk(os.path.join('apps', tail + '-mod', 'META-INF')):
					for file in files:
						file_path = os.path.join('apps', tail + '-mod', 'META-INF', file)
						if (file != 'MANIFEST.MF' and ('.RSA' in file or '.SF' in file)):
							os.remove(os.path.abspath(file_path))
				
				# We move the new classes.dex to the app-mod folder
				helper.move(os.path.join('apps' ,'classes.dex'), os.path.join('apps', tail + '-mod', 'classes.dex'))
				
				# We create the app-mod.zip, rename it to  app-mod.apk and remove the app-mod folder
				shutil.make_archive(os.path.join('apps', tail + '-mod'), 'zip', os.path.join('apps', tail + '-mod'))
				helper.move(os.path.join('apps', tail + '-mod.zip'), os.path.join('apps', tail + '-mod.apk'))
				shutil.rmtree(os.path.join('apps', tail + '-mod'))
				
				# We sign the app-mod.apk with our certificate
				print('::INFO  Signing {0}... \n'.format(tail + '-mod.apk'))
				sp1 = subprocess.Popen(['jarsigner', '-verbose', '-sigalg', 'SHA1withRSA', 
										'-digestalg', 'SHA1', '-keystore', './modules/my-release-key.keystore', 
										'-storepass', 'password', os.path.join('apps', tail + '-mod.apk'), 
										'alias_name'], shell=True, stdout=subprocess.DEVNULL, env=nenv)
				sp1.wait()
				
			else:
				print('\n::WARN  Incorrect usage [-i]: smali-code-injector -h for help \n')
				sys.exit(0)		
		
		else:
			print('::WARN  {0} does not exist/is not valid, please try again... \n' .format(app))
			sys.exit(0)
		
	elif (args.target and args.code_to_inject):
		target = args.target
		
		if ((os.path.exists(target)) and (os.path.isdir(target) or \
		(os.path.isfile(target) and target.endswith('.smali')))):
			inject_user_input = args.code_to_inject
			code_to_inject = check_inject_arg(inject_user_input)
			
			if (code_to_inject):			
				if (os.path.isdir(target)):
					treat_dir(target, code_to_inject)
				else:
					treat_file(target, code_to_inject)		
					
			else:
				print('Incorrect usage [-i]: smali-code-injector -h for help\n')
				sys.exit(0)	
				
		else:
			print('\n::WARN  {0} does not exist/is not valid, please try again... \n' .format(target))
			sys.exit(0)
	
	elif (args.target and args.check):
		target = args.target
		
		if ((os.path.exists(target)) and (os.path.isdir(target) or (os.path.isfile(target) and target.endswith('.smali')))):
			if (os.path.isdir(target)):
				print('\n::INFO  Creation of metadata...')
				my_metadata = metadata.create_metadata(target)
				metadata.check_dir(os.path.basename(target), my_metadata)
	
			else:
				print('\n::INFO  Creation of metadata...')
				file_metadata = metadata.create_file_metadata(target)
				metadata.check_file(os.path.basename(target), file_metadata)
				
	else:
		print('::WARN  Incorrect usage: smali-code-injector -h for help \n')
		sys.exit(0)