# Path: mobsf/MobSF/utils.py
# def is_file_exists(file_path):
#     if os.path.isfile(file_path):
#         return True
#     # This fix situation where a user just typed "adb" or another executable
#     # inside settings.py/config.py
#     if shutil.which(file_path):
#         return True
#     else:
#         return False
# 
# def is_md5(user_input):
#     """Check if string is valid MD5."""
#     stat = re.match(r'^[0-9a-f]{32}$', user_input)
#     if not stat:
#         logger.error('Invalid scan hash')
#     return stat
# 
# def is_path_traversal(user_input):
#     """Check for path traversal."""
#     if (('../' in user_input)
#         or ('%2e%2e' in user_input)
#         or ('..' in user_input)
#             or ('%252e' in user_input)):
#         logger.error('Path traversal attack detected')
#         return True
#     return False
# 
# def is_safe_path(safe_root, check_path):
#     """Detect Path Traversal."""
#     safe_root = os.path.realpath(os.path.normpath(safe_root))
#     check_path = os.path.realpath(os.path.normpath(check_path))
#     return os.path.commonprefix([check_path, safe_root]) == safe_root
# 
# def print_n_send_error_response(request,
#                                 msg,
#                                 api=False,
#                                 exp='Description'):
#     """Print and log errors."""
#     logger.error(msg)
#     if api:
#         api_response = {'error': msg}
#         return api_response
#     else:
#         context = {
#             'title': 'Error',
#             'exp': exp,
#             'doc': msg,
#             'version': settings.MOBSF_VER,
#         }
#         template = 'general/error.html'
#         return render(request, template, context, status=500)
# 
# def read_sqlite(sqlite_file):
#     """Sqlite Dump - Readable Text."""
#     logger.info('Reading SQLite db')
#     table_dict = {}
#     try:
#         con = sqlite3.connect(sqlite_file)
#         cur = con.cursor()
#         cur.execute('SELECT name FROM sqlite_master WHERE type=\'table\';')
#         tables = cur.fetchall()
#         for table in tables:
#             table_dict[table[0]] = {'head': [], 'data': []}
#             cur.execute('PRAGMA table_info(\'%s\')' % table)
#             rows = cur.fetchall()
#             for sq_row in rows:
#                 table_dict[table[0]]['head'].append(sq_row[1])
#             cur.execute('SELECT * FROM \'%s\'' % table)
#             rows = cur.fetchall()
#             for sq_row in rows:
#                 tmp_row = []
#                 for each_row in sq_row:
#                     tmp_row.append(str(each_row))
#                 table_dict[table[0]]['data'].append(tmp_row)
#     except Exception:
#         logger.exception('Reading SQLite db')
#     return table_dict


import logging
import ntpath
import os
import io
import mobsf.MalwareAnalyzer.views.Trackers as Trackers
from django.conf import settings
from django.shortcuts import render
from django.template.defaulttags import register
from django.utils.html import escape
from mobsf.DynamicAnalyzer.views.android.analysis import (
    generate_download,
    get_screenshots,
    run_analysis,
)
from mobsf.DynamicAnalyzer.views.android.operations import (
    get_package_name,
)
from mobsf.DynamicAnalyzer.views.android.tests_xposed import (
    droidmon_api_analysis,
)
from mobsf.DynamicAnalyzer.views.android.tests_frida import (
    apimon_analysis,
    dependency_analysis,
)
from mobsf.MobSF.utils import (
    is_file_exists,
    is_md5,
    is_path_traversal,
    is_safe_path,
    print_n_send_error_response,
    read_sqlite,
)
        generate_download(app_dir, checksum, download_dir, package)
        images = get_screenshots(checksum, download_dir)
        context = {'hash': checksum,
                   'emails': analysis_result['emails'],
                   'urls': analysis_result['urls'],
                   'domains': domains,
                   'clipboard': analysis_result['clipboard'],
                   'xml': analysis_result['xml'],
                   'sqlite': analysis_result['sqlite'],
                   'others': analysis_result['other_files'],
                   'tls_tests': analysis_result['tls_tests'],
                   'screenshots': images['screenshots'],
                   'activity_tester': images['activities'],
                   'exported_activity_tester': images['exported_activities'],
                   'droidmon': droidmon,
                   'apimon': apimon,
                   'base64_strings': b64_strings,
                   'trackers': trackers,
                   'frida_logs': is_file_exists(fd_log),
                   'runtime_dependencies': deps,
                   'package': package,
                   'version': settings.MOBSF_VER,
                   'title': 'Dynamic Analysis'}
        template = 'dynamic_analysis/android/dynamic_report.html'
        if api:
            return context
        return render(request, template, context)
    except Exception as exp:
        logger.exception('Dynamic Analysis Report Generation')
        err = 'Error Generating Dynamic Analysis Report. ' + str(exp)

# Path: mobsf/MobSF/utils.py
# def is_file_exists(file_path):
#     if os.path.isfile(file_path):
#         return True
#     # This fix situation where a user just typed "adb" or another executable
#     # inside settings.py/config.py
#     if shutil.which(file_path):
#         return True
#     else:
#         return False
# 
# def is_md5(user_input):
#     """Check if string is valid MD5."""
#     stat = re.match(r'^[0-9a-f]{32}$', user_input)
#     if not stat:
#         logger.error('Invalid scan hash')
#     return stat
# 
# def is_path_traversal(user_input):
#     """Check for path traversal."""
#     if (('../' in user_input)
#         or ('%2e%2e' in user_input)
#         or ('..' in user_input)
#             or ('%252e' in user_input)):
#         logger.error('Path traversal attack detected')
#         return True
#     return False
# 
# def is_safe_path(safe_root, check_path):
#     """Detect Path Traversal."""
#     safe_root = os.path.realpath(os.path.normpath(safe_root))
#     check_path = os.path.realpath(os.path.normpath(check_path))
#     return os.path.commonprefix([check_path, safe_root]) == safe_root
# 
# def print_n_send_error_response(request,
#                                 msg,
#                                 api=False,
#                                 exp='Description'):
#     """Print and log errors."""
#     logger.error(msg)
#     if api:
#         api_response = {'error': msg}
#         return api_response
#     else:
#         context = {
#             'title': 'Error',
#             'exp': exp,
#             'doc': msg,
#             'version': settings.MOBSF_VER,
#         }
#         template = 'general/error.html'
#         return render(request, template, context, status=500)
# 
# def read_sqlite(sqlite_file):
#     """Sqlite Dump - Readable Text."""
#     logger.info('Reading SQLite db')
#     table_dict = {}
#     try:
#         con = sqlite3.connect(sqlite_file)
#         cur = con.cursor()
#         cur.execute('SELECT name FROM sqlite_master WHERE type=\'table\';')
#         tables = cur.fetchall()
#         for table in tables:
#             table_dict[table[0]] = {'head': [], 'data': []}
#             cur.execute('PRAGMA table_info(\'%s\')' % table)
#             rows = cur.fetchall()
#             for sq_row in rows:
#                 table_dict[table[0]]['head'].append(sq_row[1])
#             cur.execute('SELECT * FROM \'%s\'' % table)
#             rows = cur.fetchall()
#             for sq_row in rows:
#                 tmp_row = []
#                 for each_row in sq_row:
#                     tmp_row.append(str(each_row))
#                 table_dict[table[0]]['data'].append(tmp_row)
#     except Exception:
#         logger.exception('Reading SQLite db')
#     return table_dict


# Path: mobsf/DynamicAnalyzer/views/android/report.py
import logging
import ntpath
import os
import io
import mobsf.MalwareAnalyzer.views.Trackers as Trackers
from django.conf import settings
from django.shortcuts import render
from django.template.defaulttags import register
from django.utils.html import escape
from mobsf.DynamicAnalyzer.views.android.analysis import (
    generate_download,
    get_screenshots,
    run_analysis,
)
from mobsf.DynamicAnalyzer.views.android.operations import (
    get_package_name,
)
from mobsf.DynamicAnalyzer.views.android.tests_xposed import (
    droidmon_api_analysis,
)
from mobsf.DynamicAnalyzer.views.android.tests_frida import (
    apimon_analysis,
    dependency_analysis,
)
from mobsf.MobSF.utils import (
    is_file_exists,
    is_md5,
    is_path_traversal,
    is_safe_path,
    print_n_send_error_response,
    read_sqlite,
)

        generate_download(app_dir, checksum, download_dir, package)
        images = get_screenshots(checksum, download_dir)
        context = {'hash': checksum,
                   'emails': analysis_result['emails'],
                   'urls': analysis_result['urls'],
                   'domains': domains,
                   'clipboard': analysis_result['clipboard'],
                   'xml': analysis_result['xml'],
                   'sqlite': analysis_result['sqlite'],
                   'others': analysis_result['other_files'],
                   'tls_tests': analysis_result['tls_tests'],
                   'screenshots': images['screenshots'],
                   'activity_tester': images['activities'],
                   'exported_activity_tester': images['exported_activities'],
                   'droidmon': droidmon,
                   'apimon': apimon,
                   'base64_strings': b64_strings,
                   'trackers': trackers,
                   'frida_logs': is_file_exists(fd_log),
                   'runtime_dependencies': deps,
                   'package': package,
                   'version': settings.MOBSF_VER,
                   'title': 'Dynamic Analysis'}
        template = 'dynamic_analysis/android/dynamic_report.html'
        if api:
            return context
        return render(request, template, context)
    except Exception as exp:
        logger.exception('Dynamic Analysis Report Generation')
        err = 'Error Generating Dynamic Analysis Report. ' + str(exp)

        return print_n_send_error_response(request, err, api)