gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_icon(apk_path, res_dir):
    """Returns a dict with isHidden boolean and a relative path
    path is a full path (not relative to resource folder)"""
    try:
        logger.info("Fetching icon path")
        a = apk.APK(apk_path)
        icon_resolution = 0xFFFE - 1
        icon_name = a.get_app_icon(max_dpi=icon_resolution)
        if icon_name:
            return {
                "path": os.path.join(os.path.dirname(apk_path), icon_name),
                "hidden": False,
            }
        return {"path": guess_icon_path(res_dir), "hidden": True}
    except:
        PrintException("[ERROR] Fetching icon function")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def get_icon(apk_path, res_dir):
    """Returns a dict with isHidden boolean and a relative path
    path is a full path (not relative to resource folder)"""
    try:
        logger.info("Fetching icon path")
        a = apk.APK(apk_path)
        icon_resolution = 0xFFFE - 1
        icon_name = a.get_app_icon(max_dpi=icon_resolution)
        if icon_name:
            return {
                "path": os.path.join(os.path.dirname(apk_path), icon_name),
                "hidden": False,
            }
        return {"path": guess_icon_path(res_dir), "hidden": True}
    except:
        PrintException("Fetching icon function")
# Buggy code
def get_manifest(app_path, app_dir, tools_dir, typ, binary):
    """Get the manifest file."""
    try:
        manifest = None
        dat = read_manifest(app_dir, app_path, tools_dir, typ, binary)
        try:
            logger.info("Parsing AndroidManifest.xml")
            manifest = minidom.parseString(dat)
        except:
            PrintException(
                "[ERROR] apktool failed to extract AndroidManifest.xml or parsing failed"
            )
            manifest = minidom.parseString(
                (
                    r'<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android='
                    r'"http://schemas.android.com/apk/res/android" android:versionCode="Failed"  '
                    r'android:versionName="Failed" package="Failed"  '
                    r'platformBuildVersionCode="Failed" '
                    r'platformBuildVersionName="Failed XML Parsing" ></manifest>'
                )
            )
            logger.warning("Using Fake XML to continue the Analysis")
        return manifest
    except:
        PrintException("[ERROR] Parsing Manifest file")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def get_manifest(app_path, app_dir, tools_dir, typ, binary):
    """Get the manifest file."""
    try:
        manifest = None
        dat = read_manifest(app_dir, app_path, tools_dir, typ, binary)
        try:
            logger.info("Parsing AndroidManifest.xml")
            manifest = minidom.parseString(dat)
        except:
            PrintException(
                "apktool failed to extract AndroidManifest.xml or parsing failed"
            )
            manifest = minidom.parseString(
                (
                    r'<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android='
                    r'"http://schemas.android.com/apk/res/android" android:versionCode="Failed"  '
                    r'android:versionName="Failed" package="Failed"  '
                    r'platformBuildVersionCode="Failed" '
                    r'platformBuildVersionName="Failed XML Parsing" ></manifest>'
                )
            )
            logger.warning("Using Fake XML to continue the Analysis")
        return manifest
    except:
        PrintException("Parsing Manifest file")
# Buggy code
def read_manifest(app_dir, app_path, tools_dir, typ, apk):
    """Read the manifest file."""
    try:
        dat = ""
        manifest = ""
        if apk:
            manifest = get_manifest_file(app_path, app_dir, tools_dir)
            if isFileExists(manifest):
                logger.info("Reading Android Manifest")
                with io.open(
                    manifest, mode="r", encoding="utf8", errors="ignore"
                ) as file_pointer:
                    dat = file_pointer.read()
        else:
            logger.info("Reading Manifest from Source")
            if typ == "eclipse":
                manifest = os.path.join(app_dir, "AndroidManifest.xml")
            elif typ == "studio":
                manifest = os.path.join(app_dir, "app/src/main/AndroidManifest.xml")
            with io.open(
                manifest, mode="r", encoding="utf8", errors="ignore"
            ) as file_pointer:
                dat = file_pointer.read()
        return dat
    except:
        PrintException("[ERROR] Reading Manifest file")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def read_manifest(app_dir, app_path, tools_dir, typ, apk):
    """Read the manifest file."""
    try:
        dat = ""
        manifest = ""
        if apk:
            manifest = get_manifest_file(app_path, app_dir, tools_dir)
            if isFileExists(manifest):
                logger.info("Reading Android Manifest")
                with io.open(
                    manifest, mode="r", encoding="utf8", errors="ignore"
                ) as file_pointer:
                    dat = file_pointer.read()
        else:
            logger.info("Reading Manifest from Source")
            if typ == "eclipse":
                manifest = os.path.join(app_dir, "AndroidManifest.xml")
            elif typ == "studio":
                manifest = os.path.join(app_dir, "app/src/main/AndroidManifest.xml")
            with io.open(
                manifest, mode="r", encoding="utf8", errors="ignore"
            ) as file_pointer:
                dat = file_pointer.read()
        return dat
    except:
        PrintException("Reading Manifest file")
# Buggy code
def get_manifest_file(app_path, app_dir, tools_dir):
    """Get readable AndroidManifest.xml"""
    try:
        manifest = None
        if len(settings.APKTOOL_BINARY) > 0 and isFileExists(settings.APKTOOL_BINARY):
            apktool_path = settings.APKTOOL_BINARY
        else:
            apktool_path = os.path.join(tools_dir, "apktool_2.3.4.jar")
        output_dir = os.path.join(app_dir, "apktool_out")
        args = [
            settings.JAVA_PATH + "java",
            "-jar",
            apktool_path,
            "--match-original",
            "-f",
            "-s",
            "d",
            app_path,
            "-o",
            output_dir,
        ]
        manifest = os.path.join(output_dir, "AndroidManifest.xml")
        if isFileExists(manifest):
            # APKTool already created readable XML
            return manifest
        logger.info("Converting AXML to XML")
        subprocess.check_output(args)
        return manifest
    except:
        PrintException("[ERROR]Getting Manifest file")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def get_manifest_file(app_path, app_dir, tools_dir):
    """Get readable AndroidManifest.xml"""
    try:
        manifest = None
        if len(settings.APKTOOL_BINARY) > 0 and isFileExists(settings.APKTOOL_BINARY):
            apktool_path = settings.APKTOOL_BINARY
        else:
            apktool_path = os.path.join(tools_dir, "apktool_2.3.4.jar")
        output_dir = os.path.join(app_dir, "apktool_out")
        args = [
            settings.JAVA_PATH + "java",
            "-jar",
            apktool_path,
            "--match-original",
            "-f",
            "-s",
            "d",
            app_path,
            "-o",
            output_dir,
        ]
        manifest = os.path.join(output_dir, "AndroidManifest.xml")
        if isFileExists(manifest):
            # APKTool already created readable XML
            return manifest
        logger.info("Converting AXML to XML")
        subprocess.check_output(args)
        return manifest
    except:
        PrintException("Getting Manifest file")
# Buggy code
def valid_android_zip(app_dir):
    """Test if this is an valid android zip."""
    try:
        logger.info("Checking for ZIP Validity and Mode")
        # Eclipse
        man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml"))
        src = os.path.exists(os.path.join(app_dir, "src/"))
        if man and src:
            return "eclipse", True
        # Studio
        man = os.path.isfile(os.path.join(app_dir, "app/src/main/AndroidManifest.xml"))
        src = os.path.exists(os.path.join(app_dir, "app/src/main/java/"))
        if man and src:
            return "studio", True
        # iOS Source
        xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")]
        if xcode:
            return "ios", True
        return "", False
    except:
        PrintException("[ERROR] Determining Upload type")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def valid_android_zip(app_dir):
    """Test if this is an valid android zip."""
    try:
        logger.info("Checking for ZIP Validity and Mode")
        # Eclipse
        man = os.path.isfile(os.path.join(app_dir, "AndroidManifest.xml"))
        src = os.path.exists(os.path.join(app_dir, "src/"))
        if man and src:
            return "eclipse", True
        # Studio
        man = os.path.isfile(os.path.join(app_dir, "app/src/main/AndroidManifest.xml"))
        src = os.path.exists(os.path.join(app_dir, "app/src/main/java/"))
        if man and src:
            return "studio", True
        # iOS Source
        xcode = [f for f in os.listdir(app_dir) if f.endswith(".xcodeproj")]
        if xcode:
            return "ios", True
        return "", False
    except:
        PrintException("Determining Upload type")
# Buggy code
def gen_downloads(app_dir, md5, icon_path=""):
    """Generate downloads for java and smali."""
    try:
        logger.info("Generating Downloads")
        # For Java
        directory = os.path.join(app_dir, "java_source/")
        dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-java.zip")
        zipf = zipfile.ZipFile(dwd_dir, "w")
        zipdir(directory, zipf)
        zipf.close()
        # For Smali
        directory = os.path.join(app_dir, "smali_source/")
        dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-smali.zip")
        zipf = zipfile.ZipFile(dwd_dir, "w")
        zipdir(directory, zipf)
        zipf.close()
        # Icon
        icon_path = icon_path.encode("utf-8")
        if icon_path:
            if os.path.exists(icon_path):
                shutil.copy2(
                    icon_path, os.path.join(settings.DWD_DIR, md5 + "-icon.png")
                )

    except:
        PrintException("[ERROR] Generating Downloads")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def gen_downloads(app_dir, md5, icon_path=""):
    """Generate downloads for java and smali."""
    try:
        logger.info("Generating Downloads")
        # For Java
        directory = os.path.join(app_dir, "java_source/")
        dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-java.zip")
        zipf = zipfile.ZipFile(dwd_dir, "w")
        zipdir(directory, zipf)
        zipf.close()
        # For Smali
        directory = os.path.join(app_dir, "smali_source/")
        dwd_dir = os.path.join(settings.DWD_DIR, md5 + "-smali.zip")
        zipf = zipfile.ZipFile(dwd_dir, "w")
        zipdir(directory, zipf)
        zipf.close()
        # Icon
        icon_path = icon_path.encode("utf-8")
        if icon_path:
            if os.path.exists(icon_path):
                shutil.copy2(
                    icon_path, os.path.join(settings.DWD_DIR, md5 + "-icon.png")
                )

    except:
        PrintException("Generating Downloads")
# Buggy code
def strings_jar(app_file, app_dir):
    """Extract the strings from an app."""
    try:
        logger.info("Extracting Strings from APK")
        dat = []
        apk_file = os.path.join(app_dir, app_file)
        and_a = apk.APK(apk_file)
        rsrc = and_a.get_android_resources()
        pkg = rsrc.get_packages_names()[0]
        rsrc.get_strings_resources()
        for i in rsrc.values[pkg].keys():
            string = rsrc.values[pkg][i].get("string")
            if string is None:
                return dat
            for duo in string:
                dat.append('"' + duo[0] + '" : "' + duo[1] + '"')
        return dat
    except:
        PrintException("[ERROR] Extracting Strings from APK")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def strings_jar(app_file, app_dir):
    """Extract the strings from an app."""
    try:
        logger.info("Extracting Strings from APK")
        dat = []
        apk_file = os.path.join(app_dir, app_file)
        and_a = apk.APK(apk_file)
        rsrc = and_a.get_android_resources()
        pkg = rsrc.get_packages_names()[0]
        rsrc.get_strings_resources()
        for i in rsrc.values[pkg].keys():
            string = rsrc.values[pkg][i].get("string")
            if string is None:
                return dat
            for duo in string:
                dat.append('"' + duo[0] + '" : "' + duo[1] + '"')
        return dat
    except:
        PrintException("Extracting Strings from APK")
# Buggy code
def win_fix_java(tools_dir):
    """Runn JAVA path fix in Windows"""
    try:
        logger.info("Running JAVA path fix in Windows")
        dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp")
        org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat")
        dat = ""
        with open(dmy, "r") as file_pointer:
            dat = file_pointer.read().replace("[xxx]", settings.JAVA_PATH + "java")
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except:
        PrintException("[ERROR] Running JAVA path fix in Windows")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def win_fix_java(tools_dir):
    """Runn JAVA path fix in Windows"""
    try:
        logger.info("Running JAVA path fix in Windows")
        dmy = os.path.join(tools_dir, "d2j2/d2j_invoke.tmp")
        org = os.path.join(tools_dir, "d2j2/d2j_invoke.bat")
        dat = ""
        with open(dmy, "r") as file_pointer:
            dat = file_pointer.read().replace("[xxx]", settings.JAVA_PATH + "java")
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except:
        PrintException("Running JAVA path fix in Windows")
# Buggy code
def win_fix_python3(tools_dir):
    """Runn Python 3 path fix in Windows."""
    try:
        logger.info("Running Python 3 path fix in Windows")
        python3_path = ""
        if len(settings.PYTHON3_PATH) > 2:
            python3_path = settings.python3_path
        else:
            pathenv = os.environ["path"]
            if pathenv:
                paths = pathenv.split(";")
                for path in paths:
                    if "python3" in path.lower():
                        python3_path = path
        python3 = '"' + os.path.join(python3_path, "python") + '"'
        dmy = os.path.join(tools_dir, "enjarify/enjarify.tmp")
        org = os.path.join(tools_dir, "enjarify/enjarify.bat")
        dat = ""
        with open(dmy, "r") as file_pointer:
            dat = file_pointer.read().replace("[xxx]", python3)
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except:
        PrintException("[ERROR] Running Python 3 path fix in Windows")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def win_fix_python3(tools_dir):
    """Runn Python 3 path fix in Windows."""
    try:
        logger.info("Running Python 3 path fix in Windows")
        python3_path = ""
        if len(settings.PYTHON3_PATH) > 2:
            python3_path = settings.python3_path
        else:
            pathenv = os.environ["path"]
            if pathenv:
                paths = pathenv.split(";")
                for path in paths:
                    if "python3" in path.lower():
                        python3_path = path
        python3 = '"' + os.path.join(python3_path, "python") + '"'
        dmy = os.path.join(tools_dir, "enjarify/enjarify.tmp")
        org = os.path.join(tools_dir, "enjarify/enjarify.bat")
        dat = ""
        with open(dmy, "r") as file_pointer:
            dat = file_pointer.read().replace("[xxx]", python3)
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except:
        PrintException("Running Python 3 path fix in Windows")
# Buggy code
def strings_on_ipa(bin_path):
    """Extract Strings from IPA"""
    try:
        logger.info("Running strings against the Binary")
        unique_str = []
        unique_str = list(set(strings_util(bin_path)))  # Make unique
        unique_str = [escape(ip_str) for ip_str in unique_str]  # Escape evil strings
        return unique_str
    except:
        PrintException("[ERROR] - Running strings against the Binary")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def strings_on_ipa(bin_path):
    """Extract Strings from IPA"""
    try:
        logger.info("Running strings against the Binary")
        unique_str = []
        unique_str = list(set(strings_util(bin_path)))  # Make unique
        unique_str = [escape(ip_str) for ip_str in unique_str]  # Escape evil strings
        return unique_str
    except:
        PrintException("Running strings against the Binary")
# Buggy code
def hash_gen(app_path) -> tuple:
    """Generate and return sha1 and sha256 as a tupel."""
    try:
        logger.info("Generating Hashes")
        sha1 = hashlib.sha1()
        sha256 = hashlib.sha256()
        block_size = 65536
        with io.open(app_path, mode="rb") as afile:
            buf = afile.read(block_size)
            while buf:
                sha1.update(buf)
                sha256.update(buf)
                buf = afile.read(block_size)
        sha1val = sha1.hexdigest()
        sha256val = sha256.hexdigest()
        return sha1val, sha256val
    except:
        PrintException("[ERROR] Generating Hashes")


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def hash_gen(app_path) -> tuple:
    """Generate and return sha1 and sha256 as a tupel."""
    try:
        logger.info("Generating Hashes")
        sha1 = hashlib.sha1()
        sha256 = hashlib.sha256()
        block_size = 65536
        with io.open(app_path, mode="rb") as afile:
            buf = afile.read(block_size)
            while buf:
                sha1.update(buf)
                sha256.update(buf)
                buf = afile.read(block_size)
        sha1val = sha1.hexdigest()
        sha256val = sha256.hexdigest()
        return sha1val, sha256val
    except:
        PrintException("Generating Hashes")
# Buggy code
def check_config():
    try:
        for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]:
            if not path:
                logger.error(
                    "ADB binary not configured, please refer to the official documentation"
                )
                return False
        if settings.ANDROID_DYNAMIC_ANALYZER != "MobSF_AVD":
            logger.error(
                "Wrong configuration - ANDROID_DYNAMIC_ANALYZER, please refer to the official documentation"
            )
            return False
        return True
    except:
        PrintException("[ERROR] check_config")
        return False


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def check_config():
    try:
        for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]:
            if not path:
                logger.error(
                    "ADB binary not configured, please refer to the official documentation"
                )
                return False
        if settings.ANDROID_DYNAMIC_ANALYZER != "MobSF_AVD":
            logger.error(
                "Wrong configuration - ANDROID_DYNAMIC_ANALYZER, please refer to the official documentation"
            )
            return False
        return True
    except:
        PrintException("check_config")
        return False
# Buggy code
def help_boot_avd():
    try:
        emulator = get_identifier()

        # Wait for the adb to answer
        args = [settings.ADB_BINARY, "-s", emulator, "wait-for-device"]
        logger.info("help_boot_avd: wait-for-device")
        subprocess.call(args)

        # Make sure adb running as root
        logger.info("help_boot_avd: root")
        adb_command(["root"])

        # Make sure adb running as root
        logger.info("help_boot_avd: remount")
        adb_command(["remount"])

        # Make sure the system verity feature is disabled (Obviously, modified the system partition)
        logger.info("help_boot_avd: disable-verity")
        adb_command(["disable-verity"])

        # Make SELinux permissive - in case SuperSu/Xposed didn't patch things right
        logger.info("help_boot_avd: setenforce")
        adb_command(["setenforce", "0"], shell=True)

        logger.info("help_boot_avd: finished!")
        return True
    except:
        PrintException("[ERROR] help_boot_avd")
        return False


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def help_boot_avd():
    try:
        emulator = get_identifier()

        # Wait for the adb to answer
        args = [settings.ADB_BINARY, "-s", emulator, "wait-for-device"]
        logger.info("help_boot_avd: wait-for-device")
        subprocess.call(args)

        # Make sure adb running as root
        logger.info("help_boot_avd: root")
        adb_command(["root"])

        # Make sure adb running as root
        logger.info("help_boot_avd: remount")
        adb_command(["remount"])

        # Make sure the system verity feature is disabled (Obviously, modified the system partition)
        logger.info("help_boot_avd: disable-verity")
        adb_command(["disable-verity"])

        # Make SELinux permissive - in case SuperSu/Xposed didn't patch things right
        logger.info("help_boot_avd: setenforce")
        adb_command(["setenforce", "0"], shell=True)

        logger.info("help_boot_avd: finished!")
        return True
    except:
        PrintException("help_boot_avd")
        return False
# Buggy code
def start_avd():
    try:
        if platform.system() == "Darwin":
            # There is a strage error in mac with the dyld one in a while..
            # this should fix it..
            if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()):
                del os.environ["DYLD_FALLBACK_LIBRARY_PATH"]

        args = [
            settings.AVD_EMULATOR,
            "-avd",
            settings.AVD_NAME,
            "-writable-system",
            "-no-snapshot-load",
            "-port",
            str(settings.AVD_ADB_PORT),
        ]
        logger.info("starting emulator: \r\n" + " ".join(args))
        subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except:
        PrintException("[ERROR] start_avd")
        return False


# Traceback (KeyError)
[INFO] 08/Feb/2019 16:17:54 - VM Starting
[INFO] 08/Feb/2019 16:17:55 - "POST /DynamicAnalyzer/ HTTP/1.1" 200 32400
[INFO] 08/Feb/2019 16:17:55 - "GET /static/css/devices.min.css HTTP/1.1" 200 44241
[INFO] 08/Feb/2019 16:17:55 - "GET /download/screen/screen.png HTTP/1.1" 302 0
[DEBUG] 08/Feb/2019 16:17:55 - Exception while resolving variable 'exp' in template 'general/error.html'.
Traceback (most recent call last):
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/base.py", line 829, in _resolve_lookup
current = current[bit]
File "/home/userhome/Mobile-Security-Framework-MobSF/venv/lib/python3.6/site-packages/django/template/context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'exp'

During handling of the above exception, another exception occurred:

# Fixed code
def start_avd():
    try:
        if platform.system() == "Darwin":
            # There is a strage error in mac with the dyld one in a while..
            # this should fix it..
            if "DYLD_FALLBACK_LIBRARY_PATH" in list(os.environ.keys()):
                del os.environ["DYLD_FALLBACK_LIBRARY_PATH"]

        args = [
            settings.AVD_EMULATOR,
            "-avd",
            settings.AVD_NAME,
            "-writable-system",
            "-no-snapshot-load",
            "-port",
            str(settings.AVD_ADB_PORT),
        ]
        logger.info("starting emulator: \r\n" + " ".join(args))
        subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        return True
    except:
        PrintException("start_avd")
        return False
# Buggy code
def on_treeWidget_itemChanged(self, item, column):
    if item is self.treeWidget.selectedItems()[0] and column == 0:
        newText = str(item.text(0))
        if ui_common.validate(
            not ui_common.EMPTY_FIELD_REGEX.match(newText),
            "The name can't be empty.",
            None,
            self.window(),
        ):
            self.window().app.monitor.suspend()
            self.stack.currentWidget().set_item_title(newText)
            self.stack.currentWidget().rebuild_item_path()

            persistGlobal = self.stack.currentWidget().save()
            self.window().app.monitor.unsuspend()
            self.window().app.config_altered(persistGlobal)

            self.treeWidget.sortItems(0, Qt.AscendingOrder)
        else:
            item.update()


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def on_treeWidget_itemChanged(self, item, column):
    if item is self._get_current_treewidget_item() and column == 0:
        newText = str(item.text(0))
        if ui_common.validate(
            not ui_common.EMPTY_FIELD_REGEX.match(newText),
            "The name can't be empty.",
            None,
            self.window(),
        ):
            self.window().app.monitor.suspend()
            self.stack.currentWidget().set_item_title(newText)
            self.stack.currentWidget().rebuild_item_path()

            persistGlobal = self.stack.currentWidget().save()
            self.window().app.monitor.unsuspend()
            self.window().app.config_altered(persistGlobal)

            self.treeWidget.sortItems(0, Qt.AscendingOrder)
        else:
            item.update()
# Buggy code
def on_new_folder(self):
    parent_item = self.treeWidget.selectedItems()[0]
    self.__createFolder(parent_item)


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def on_new_folder(self):
    parent_item = self._get_current_treewidget_item()
    self.__createFolder(parent_item)
# Buggy code
def on_paste(self):
    parent_item = self.treeWidget.selectedItems()[0]
    parent = self.__extractData(parent_item)
    self.window().app.monitor.suspend()

    new_items = []
    for item in self.cutCopiedItems:
        if isinstance(item, model.Folder):
            new_item = ak_tree.FolderWidgetItem(parent_item, item)
            ak_tree.WidgetItemFactory.process_folder(new_item, item)
            parent.add_folder(item)
        elif isinstance(item, model.Phrase):
            new_item = ak_tree.PhraseWidgetItem(parent_item, item)
            parent.add_item(item)
        else:
            new_item = ak_tree.ScriptWidgetItem(parent_item, item)
            parent.add_item(item)

        item.persist()

        new_items.append(new_item)

    self.treeWidget.sortItems(0, Qt.AscendingOrder)
    self.treeWidget.setCurrentItem(new_items[-1])
    self.on_treeWidget_itemSelectionChanged()
    self.cutCopiedItems = []
    for item in new_items:
        item.setSelected(True)
    self.window().app.monitor.unsuspend()
    self.window().app.config_altered(False)


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def on_paste(self):
    parent_item = self._get_current_treewidget_item()
    parent = self.__extractData(parent_item)
    self.window().app.monitor.suspend()

    new_items = []
    for item in self.cutCopiedItems:
        if isinstance(item, model.Folder):
            new_item = ak_tree.FolderWidgetItem(parent_item, item)
            ak_tree.WidgetItemFactory.process_folder(new_item, item)
            parent.add_folder(item)
        elif isinstance(item, model.Phrase):
            new_item = ak_tree.PhraseWidgetItem(parent_item, item)
            parent.add_item(item)
        else:
            new_item = ak_tree.ScriptWidgetItem(parent_item, item)
            parent.add_item(item)

        item.persist()

        new_items.append(new_item)

    self.treeWidget.sortItems(0, Qt.AscendingOrder)
    self.treeWidget.setCurrentItem(new_items[-1])
    self.on_treeWidget_itemSelectionChanged()
    self.cutCopiedItems = []
    for item in new_items:
        item.setSelected(True)
    self.window().app.monitor.unsuspend()
    self.window().app.config_altered(False)
# Buggy code
def on_rename(self):
    widget_item = self.treeWidget.selectedItems()[0]
    self.treeWidget.editItem(widget_item, 0)


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def on_rename(self):
    widget_item = self._get_current_treewidget_item()
    self.treeWidget.editItem(widget_item, 0)
# Buggy code
def on_save(self):
    logger.info("User requested file save.")
    if self.stack.currentWidget().validate():
        self.window().app.monitor.suspend()
        persist_global = self.stack.currentWidget().save()
        self.window().save_completed(persist_global)
        self.set_dirty(False)

        item = self.treeWidget.selectedItems()[0]
        item.update()
        self.treeWidget.update()
        self.treeWidget.sortItems(0, Qt.AscendingOrder)
        self.window().app.monitor.unsuspend()
        return False

    return True


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def on_save(self):
    logger.info("User requested file save.")
    if self.stack.currentWidget().validate():
        self.window().app.monitor.suspend()
        persist_global = self.stack.currentWidget().save()
        self.window().save_completed(persist_global)
        self.set_dirty(False)
        item = self._get_current_treewidget_item()
        item.update()
        self.treeWidget.update()
        self.treeWidget.sortItems(0, Qt.AscendingOrder)
        self.window().app.monitor.unsuspend()
        return False

    return True
# Buggy code
def save(self, item):
    item.modes.append(model.TriggerMode.HOTKEY)

    # Build modifier list
    modifiers = self.build_modifiers()

    if self.key in self.REVERSE_KEY_MAP:
        key = self.REVERSE_KEY_MAP[self.key]
    else:
        key = self.key

    if key is None:
        raise RuntimeError("Attempt to set hotkey with no key")
    logger.info(
        "Item {} updated with hotkey {} and modifiers {}".format(item, key, modifiers)
    )
    item.set_hot_update_key(modifiers, key)


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def save(self, item):
    item.modes.append(model.TriggerMode.HOTKEY)

    # Build modifier list
    modifiers = self.build_modifiers()

    if self.key in self.REVERSE_KEY_MAP:
        key = self.REVERSE_KEY_MAP[self.key]
    else:
        key = self.key

    if key is None:
        raise RuntimeError("Attempt to set hotkey with no key")
    logger.info(
        "Item {} updated with hotkey {} and modifiers {}".format(item, key, modifiers)
    )
    item.set_hotkey(modifiers, key)
# Buggy code
def __init__(self):
    super(PhrasePage, self).__init__()
    self.setupUi(self)

    self.initialising = True
    l = list(model.SEND_MODES.keys())
    l.sort()
    for val in l:
        self.sendModeCombo.addItem(val)
    self.initialising = False


# Traceback (IndexError)
2019-05-21 21:45:48,995 DEBUG - service - Raw key: 's', modifiers: [<Key.CONTROL: '<ctrl>'>], Key: s
2019-05-21 21:45:48,995 DEBUG - root.Qt-GUI.System-tray-notifier - Show tray icon enabled in settings: True
2019-05-21 21:45:48,997 DEBUG - service - Window visible title: 'AutoKey', Window class: 'autokey-qt.autokey-qt'
2019-05-21 21:45:48,997 INFO - root.Qt-GUI.System-tray-notifier - Rebuilding model item actions, adding all items marked for access through the tray icon.
2019-05-21 21:45:48,998 DEBUG - phrase-menu - Sorting phrase menu by usage count
Traceback (most recent call last):
File "/usr/lib/python3/dist-packages/autokey/qtui/centralwidget.py", line 402, in on_save
item = self.treeWidget.selectedItems()[0]
IndexError: list index out of range
Fatal Python error: Aborted

# Fixed code
def __init__(self):
    super(PhrasePage, self).__init__()
    self.setupUi(self)

    self.initialising = True
    self.current_phrase = None  # type: model.Phrase

    for val in sorted(model.SEND_MODES.keys()):
        self.sendModeCombo.addItem(val)
    self.initialising = False