gurudesh/pytracebugs huggingface dataset:
# Buggy code
def get_embedded_classes(self):
    """
    Get the list of Java classes from all DEX files.

    :return: list of Java classes
    """
    if self.classes is not None:
        return self.classes
    for dex_file in glob.iglob(os.path.join(self.apk_dir, "*.dex")):
        if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists(
            settings.BACKSMALI_BINARY
        ):
            bs_path = settings.BACKSMALI_BINARY
        else:
            bs_path = os.path.join(self.tools_dir, "baksmali-2.4.0.jar")
        args = [settings.JAVA_BINARY, "-jar", bs_path, "list", "classes", dex_file]
        classes = subprocess.check_output(args, universal_newlines=True).splitlines()
        if self.classes is not None:
            self.classes = self.classes + classes
        else:
            self.classes = classes
    return self.classes


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def get_embedded_classes(self):
    """
    Get the list of Java classes from all DEX files.

    :return: list of Java classes
    """
    if self.classes is not None:
        return self.classes
    for dex_file in glob.iglob(os.path.join(self.apk_dir, "*.dex")):
        if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists(
            settings.BACKSMALI_BINARY
        ):
            bs_path = settings.BACKSMALI_BINARY
        else:
            bs_path = os.path.join(self.tools_dir, "baksmali-2.4.0.jar")
        args = [find_java_binary(), "-jar", bs_path, "list", "classes", dex_file]
        classes = subprocess.check_output(args, universal_newlines=True).splitlines()
        if self.classes is not None:
            self.classes = self.classes + classes
        else:
            self.classes = classes
    return self.classes
# Buggy code
def is_internet_available():
    try:
        proxies, verify = upstream_proxy("https")
    except Exception:
        logger.exception("Setting upstream proxy")
    try:
        requests.get(settings.GOOGLE, timeout=5, proxies=proxies, verify=verify)
        return True
    except Exception:
        try:
            requests.get(settings.BAIDU, timeout=5, proxies=proxies, verify=verify)
            return True
        except Exception:
            return False
    return False


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def is_internet_available():
    try:
        proxies, verify = upstream_proxy("https")
    except Exception:
        logger.exception("Setting upstream proxy")
    try:
        requests.get(settings.GOOGLE, timeout=5, proxies=proxies, verify=verify)
        return True
    except Exception:
        try:
            requests.get(settings.BAIDU, timeout=5, proxies=proxies, verify=verify)
            return True
        except Exception:
            return False
# Buggy code
def check_basic_env():
    """Check if we have basic env for MobSF to run."""
    logger.info("MobSF Basic Environment Check")
    try:
        import http_tools  # noqa F401
    except ImportError:
        logger.exception("httptools not installed!")
        os.kill(os.getpid(), signal.SIGTERM)
    try:
        import lxml  # noqa F401
    except ImportError:
        logger.exception("lxml is not installed!")
        os.kill(os.getpid(), signal.SIGTERM)
    if not is_file_exists(settings.JAVA_BINARY):
        logger.error(
            "JDK 8+ is not available. "
            "Set JAVA_HOME environment variable"
            " or JAVA_DIRECTORY in MobSF/settings.py"
        )
        logger.info("Current Configuration: JAVA_DIRECTORY=%s", settings.JAVA_DIRECTORY)
        logger.info(
            "Example Configuration:"
            '\nJAVA_DIRECTORY = "C:/Program Files/'
            'Java/jdk1.7.0_17/bin/"'
            '\nJAVA_DIRECTORY = "/usr/bin/"'
        )
        os.kill(os.getpid(), signal.SIGTERM)
    get_adb()


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def check_basic_env():
    """Check if we have basic env for MobSF to run."""
    logger.info("MobSF Basic Environment Check")
    try:
        import http_tools  # noqa F401
    except ImportError:
        logger.exception("httptools not installed!")
        os.kill(os.getpid(), signal.SIGTERM)
    try:
        import lxml  # noqa F401
    except ImportError:
        logger.exception("lxml is not installed!")
        os.kill(os.getpid(), signal.SIGTERM)
    if not is_file_exists(find_java_binary()):
        logger.error(
            "JDK 8+ is not available. "
            "Set JAVA_HOME environment variable"
            " or JAVA_DIRECTORY in MobSF/settings.py"
        )
        logger.info("Current Configuration: JAVA_DIRECTORY=%s", settings.JAVA_DIRECTORY)
        logger.info(
            "Example Configuration:"
            '\nJAVA_DIRECTORY = "C:/Program Files/'
            'Java/jdk1.7.0_17/bin/"'
            '\nJAVA_DIRECTORY = "/usr/bin/"'
        )
        os.kill(os.getpid(), signal.SIGTERM)
    get_adb()
# Buggy code
def dex_2_smali(app_dir, tools_dir):
    """Run dex2smali."""
    try:
        logger.info("DEX -> SMALI")
        dexes = get_dex_files(app_dir)
        for dex_path in dexes:
            logger.info("Converting %s to Smali Code", filename_from_path(dex_path))
            if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists(
                settings.BACKSMALI_BINARY
            ):
                bs_path = settings.BACKSMALI_BINARY
            else:
                bs_path = os.path.join(tools_dir, "baksmali-2.4.0.jar")
            output = os.path.join(app_dir, "smali_source/")
            smali = [
                settings.JAVA_BINARY,
                "-jar",
                bs_path,
                "d",
                dex_path,
                "-o",
                output,
            ]
            trd = threading.Thread(target=subprocess.call, args=(smali,))
            trd.daemon = True
            trd.start()
    except Exception:
        logger.exception("Converting DEX to SMALI")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def dex_2_smali(app_dir, tools_dir):
    """Run dex2smali."""
    try:
        logger.info("DEX -> SMALI")
        dexes = get_dex_files(app_dir)
        for dex_path in dexes:
            logger.info("Converting %s to Smali Code", filename_from_path(dex_path))
            if len(settings.BACKSMALI_BINARY) > 0 and is_file_exists(
                settings.BACKSMALI_BINARY
            ):
                bs_path = settings.BACKSMALI_BINARY
            else:
                bs_path = os.path.join(tools_dir, "baksmali-2.4.0.jar")
            output = os.path.join(app_dir, "smali_source/")
            smali = [
                find_java_binary(),
                "-jar",
                bs_path,
                "d",
                dex_path,
                "-o",
                output,
            ]
            trd = threading.Thread(target=subprocess.call, args=(smali,))
            trd.daemon = True
            trd.start()
    except Exception:
        logger.exception("Converting DEX to SMALI")
# Buggy code
def apk_2_java(app_path, app_dir, tools_dir):
    """Run jadx."""
    try:
        logger.info("APK -> JAVA")
        args = []
        output = os.path.join(app_dir, "java_source/")
        logger.info("Decompiling to Java with jadx")

        if os.path.exists(output):
            shutil.rmtree(output)

        if len(settings.JADX_BINARY) > 0 and is_file_exists(settings.JADX_BINARY):
            jadx = settings.JADX_BINARY
        else:
            if platform.system() == "Windows":
                jadx = os.path.join(tools_dir, "jadx/bin/jadx.bat")
            else:
                jadx = os.path.join(tools_dir, "jadx/bin/jadx")
                # Set write permission, if JADX is not executable
                if not os.access(jadx, os.X_OK):
                    os.chmod(jadx, stat.S_IEXEC)
            args = [
                jadx,
                "-ds",
                output,
                "-q",
                "-r",
                "--show-bad-code",
                app_path,
            ]
            fnull = open(os.devnull, "w")
            subprocess.call(args, stdout=fnull, stderr=subprocess.STDOUT)
    except Exception:
        logger.exception("Decompiling to JAVA")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def apk_2_java(app_path, app_dir, tools_dir):
    """Run jadx."""
    try:
        logger.info("APK -> JAVA")
        args = []
        output = os.path.join(app_dir, "java_source/")
        logger.info("Decompiling to Java with jadx")

        if os.path.exists(output):
            shutil.rmtree(output)

        if len(settings.JADX_BINARY) > 0 and is_file_exists(settings.JADX_BINARY):
            jadx = settings.JADX_BINARY
        elif platform.system() == "Windows":
            jadx = os.path.join(tools_dir, "jadx/bin/jadx.bat")
        else:
            jadx = os.path.join(tools_dir, "jadx/bin/jadx")
        # Set execute permission, if JADX is not executable
        if not os.access(jadx, os.X_OK):
            os.chmod(jadx, stat.S_IEXEC)
        args = [
            jadx,
            "-ds",
            output,
            "-q",
            "-r",
            "--show-bad-code",
            app_path,
        ]
        fnull = open(os.devnull, "w")
        subprocess.call(args, stdout=fnull, stderr=subprocess.STDOUT)
    except Exception:
        logger.exception("Decompiling to JAVA")
# 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 is_file_exists(settings.APKTOOL_BINARY):
            apktool_path = settings.APKTOOL_BINARY
        else:
            apktool_path = os.path.join(tools_dir, "apktool_2.4.1.jar")
        output_dir = os.path.join(app_dir, "apktool_out")
        args = [
            settings.JAVA_BINARY,
            "-jar",
            apktool_path,
            "--match-original",
            "--frame-path",
            tempfile.gettempdir(),
            "-f",
            "-s",
            "d",
            app_path,
            "-o",
            output_dir,
        ]
        manifest = os.path.join(output_dir, "AndroidManifest.xml")
        if is_file_exists(manifest):
            # APKTool already created readable XML
            return manifest
        logger.info("Converting AXML to XML")
        subprocess.check_output(args)
        return manifest
    except Exception:
        logger.exception("Getting Manifest file")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# 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 is_file_exists(settings.APKTOOL_BINARY):
            apktool_path = settings.APKTOOL_BINARY
        else:
            apktool_path = os.path.join(tools_dir, "apktool_2.4.1.jar")
        output_dir = os.path.join(app_dir, "apktool_out")
        args = [
            find_java_binary(),
            "-jar",
            apktool_path,
            "--match-original",
            "--frame-path",
            tempfile.gettempdir(),
            "-f",
            "-s",
            "d",
            app_path,
            "-o",
            output_dir,
        ]
        manifest = os.path.join(output_dir, "AndroidManifest.xml")
        if is_file_exists(manifest):
            # APKTool already created readable XML
            return manifest
        logger.info("Converting AXML to XML")
        subprocess.check_output(args)
        return manifest
    except Exception:
        logger.exception("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 Exception:
        logger.exception("Determining Upload type")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# 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
        # Relaxed iOS Source Check
        for x in os.listdir(app_dir):
            obj = os.path.join(app_dir, x)
            if not is_dir_exists(obj):
                continue
            if [f for f in os.listdir(obj) if f.endswith(".xcodeproj")]:
                return "ios", True
        return "", False
    except Exception:
        logger.exception("Determining Upload type")
# Buggy code
def win_fix_java(tools_dir):
    """Run 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_BINARY)
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except Exception:
        logger.exception("Running JAVA path fix in Windows")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def win_fix_java(tools_dir):
    """Run 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]", find_java_binary())
        with open(org, "w") as file_pointer:
            file_pointer.write(dat)
    except Exception:
        logger.exception("Running JAVA path fix in Windows")
# Buggy code
def convert_bin_xml(bin_xml_file):
    """Convert Binary XML to Readable XML."""
    try:
        plist_obj = readPlist(bin_xml_file)
        data = writePlistToString(plist_obj)
        return data
    except biplist.InvalidPlistException:
        logger.warning("Failed to convert plist")


# Traceback (FileNotFoundError)
MobSFy Android Instance Traceback (most recent call last): File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 408, in mobsfy_init self.mobsf_agents_setup('frida') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 418, in mobsf_agents_setup self.install_mobsf_ca('install') File "C:\Users\Lijoy KFH\Mobile-Security-Framework-MobSF-master\DynamicAnalyzer\views\android\environment.py", line 140, in install_mobsf_ca pem = open(get_ca_dir(), 'rb').read() FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Lijoy KFH\\.mitmproxy\\mitmproxy-ca-cert.pem' [ERROR] 12/Apr/2020 18:53:11 – Failed to MobSFy the instance [ERROR] 12/Apr/2020 18:53:11 – Internal Server Error: /android_dynamic/"

# Fixed code
def convert_bin_xml(bin_xml_file):
    """Convert Binary XML to Readable XML."""
    try:
        plist_obj = readPlist(bin_xml_file)
        data = writePlistToString(plist_obj)
        return data
    except InvalidPlistException:
        logger.warning("Failed to convert plist")
# Buggy code
def stop_avd():
    """Stop AVD"""
    logger.info("Stopping MobSF Emulator")
    try:
        adb_command(["emu", "kill"], silent=True)
    except:
        PrintException("[ERROR] Stopping MobSF Emulator")


# 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 stop_avd():
    """Stop AVD"""
    logger.info("Stopping MobSF Emulator")
    try:
        adb_command(["emu", "kill"], silent=True)
    except:
        PrintException("Stopping MobSF Emulator")
# Buggy code
def refresh_avd():
    """Refresh AVD"""

    # Before we load the AVD, check paths
    for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]:
        if not path:
            logger.error(
                "AVD binaries not configured, please refer to the official documentation"
            )
            return False

    logger.info("Refreshing MobSF Emulator")
    try:
        # Stop existing emulator
        stop_avd()

        # Check if configuration specifies cold or warm boot
        if settings.AVD_COLD_BOOT:
            if start_avd_cold():
                logger.info("AVD has been started successfully")
                return True
        else:
            if not settings.AVD_SNAPSHOT:
                logger.error("AVD not configured properly - AVD_SNAPSHOT is missing")
                return False
            if start_avd_from_snapshot():
                logger.info("AVD has been loaded from snapshot successfully")
                return True
        return False

    except:
        PrintException("[ERROR] Refreshing MobSF VM")
        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 refresh_avd():
    """Refresh AVD"""

    # Before we load the AVD, check paths
    for path in [settings.AVD_EMULATOR, settings.ADB_BINARY]:
        if not path:
            logger.error(
                "AVD binaries not configured, please refer to the official documentation"
            )
            return False

    logger.info("Refreshing MobSF Emulator")
    try:
        # Stop existing emulator
        stop_avd()

        # Check if configuration specifies cold or warm boot
        if settings.AVD_COLD_BOOT:
            if start_avd_cold():
                logger.info("AVD has been started successfully")
                return True
        else:
            if not settings.AVD_SNAPSHOT:
                logger.error("AVD not configured properly - AVD_SNAPSHOT is missing")
                return False
            if start_avd_from_snapshot():
                logger.info("AVD has been loaded from snapshot successfully")
                return True
        return False

    except:
        PrintException("Refreshing MobSF VM")
        return False
# Buggy code
def clip_dump(request):
    """Dump Android ClipBoard"""
    logger.info("Starting Clipboard Dump Service in VM/Device")
    try:
        data = {}
        if request.method == "POST":
            adb = getADB()
            args = ["am", "startservice", "opensecurity.clipdump/.ClipDumper"]
            try:
                adb_command(args, True)
                data = {"status": "success"}
            except:
                PrintException("[ERROR] Dumping Clipboard")
                data = {"status": "error"}
        else:
            data = {"status": "failed"}
        return HttpResponse(json.dumps(data), content_type="application/json")
    except:
        PrintException("[ERROR] Dumping Clipboard")
        return HttpResponseRedirect("/error/")


# 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 clip_dump(request):
    """Dump Android ClipBoard"""
    logger.info("Starting Clipboard Dump Service in VM/Device")
    try:
        data = {}
        if request.method == "POST":
            adb = getADB()
            args = ["am", "startservice", "opensecurity.clipdump/.ClipDumper"]
            try:
                adb_command(args, True)
                data = {"status": "success"}
            except:
                PrintException("Dumping Clipboard")
                data = {"status": "error"}
        else:
            data = {"status": "failed"}
        return HttpResponse(json.dumps(data), content_type="application/json")
    except:
        PrintException("Dumping Clipboard")
        return print_n_send_error_response(request, "Error Dumping Clipboard", True)
# Buggy code
def touch(request):
    """Sending Touch Events"""
    logger.info("Sending Touch Events")
    try:
        data = {}
        if (
            (request.method == "POST")
            and (is_number(request.POST["x"]))
            and (is_number(request.POST["y"]))
        ):
            x_axis = request.POST["x"]
            y_axis = request.POST["y"]
            adb = getADB()
            args = ["input", "tap", x_axis, y_axis]
            data = {"status": "success"}
            try:
                adb_command(args, True)
            except:
                data = {"status": "error"}
                PrintException("[ERROR] Performing Touch Action")
        else:
            data = {"status": "failed"}
        return HttpResponse(json.dumps(data), content_type="application/json")
    except:
        PrintException("[ERROR] Sending Touch Events")
        return HttpResponseRedirect("/error/")


# 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 touch(request):
    """Sending Touch Events"""
    logger.info("Sending Touch Events")
    try:
        data = {}
        if (
            (request.method == "POST")
            and (is_number(request.POST["x"]))
            and (is_number(request.POST["y"]))
        ):
            x_axis = request.POST["x"]
            y_axis = request.POST["y"]
            adb = getADB()
            args = ["input", "tap", x_axis, y_axis]
            data = {"status": "success"}
            try:
                adb_command(args, True)
            except:
                data = {"status": "error"}
                PrintException("Performing Touch Action")
        else:
            data = {"status": "failed"}
        return HttpResponse(json.dumps(data), content_type="application/json")
    except:
        PrintException("Sending Touch Events")
        return print_n_send_error_response(request, "Error Sending Touch Events", True)
# Buggy code
def execute_adb(request):
    """Execute ADB Commands"""
    logger.info("Executing ADB Commands")
    try:
        if request.method == "POST":
            data = {}
            cmd = request.POST["cmd"]
            resp = "error"
            try:
                resp = adb_command(cmd.split(" "))
            except:
                PrintException("[ERROR] Executing ADB Commands")
            data = {"cmd": "yes", "resp": resp.decode("utf8", "ignore")}
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return HttpResponseRedirect("/error/")
    except:
        PrintException("[ERROR] Executing ADB Commands")
        return HttpResponseRedirect("/error/")


# 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 execute_adb(request):
    """Execute ADB Commands"""
    logger.info("Executing ADB Commands")
    try:
        if request.method == "POST":
            data = {}
            cmd = request.POST["cmd"]
            resp = "error"
            try:
                resp = adb_command(cmd.split(" "))
            except:
                PrintException("Executing ADB Commands")
            data = {"cmd": "yes", "resp": resp.decode("utf8", "ignore")}
            return HttpResponse(json.dumps(data), content_type="application/json")
        else:
            return print_n_send_error_response(request, "Only POST allowed", True)
    except:
        PrintException("Executing ADB Commands")
        return print_n_send_error_response(request, "Error running ADB commands", True)
# Buggy code
def capfuzz_start(request):
    """Start CapFuzz UI"""
    logger.info("Starting CapFuzz Web UI")
    try:
        stop_capfuzz(settings.PORT)
        start_fuzz_ui(settings.PORT)
        time.sleep(3)
        logger.info("CapFuzz UI Started")
        if request.GET["project"]:
            project = request.GET["project"]
        else:
            project = ""
        return HttpResponseRedirect(
            "http://localhost:" + str(settings.PORT) + "/dashboard/" + project
        )
    except:
        PrintException("[ERROR] Starting CapFuzz Web UI")
        return HttpResponseRedirect("/error/")


# 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 capfuzz_start(request):
    """Start CapFuzz UI"""
    logger.info("Starting CapFuzz Web UI")
    try:
        stop_capfuzz(settings.PORT)
        start_fuzz_ui(settings.PORT)
        time.sleep(3)
        logger.info("CapFuzz UI Started")
        if request.GET["project"]:
            project = request.GET["project"]
        else:
            project = ""
        return HttpResponseRedirect(
            "http://localhost:" + str(settings.PORT) + "/dashboard/" + project
        )
    except:
        PrintException("Starting CapFuzz Web UI")
        return print_n_send_error_response(request, "Error Starting CapFuzz UI")
# Buggy code
def get_res():
    """Get Screen Resolution or Device or VM"""
    logger.info("Getting Screen Resolution")
    try:
        adb = getADB()
        resp = subprocess.check_output(
            [adb, "-s", get_identifier(), "shell", "dumpsys", "window"]
        )
        resp = resp.decode("utf-8").split("\n")
        res = ""
        for line in resp:
            if "mUnrestrictedScreen" in line:
                res = line
                break
        res = res.split("(0,0)")[1]
        res = res.strip()
        res = res.split("x")
        if len(res) == 2:
            return res[0], res[1]
            # width, height
        return "", ""
    except:
        PrintException("[ERROR] Getting Screen Resolution")
        return "", ""


# 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_res():
    """Get Screen Resolution or Device or VM"""
    logger.info("Getting Screen Resolution")
    try:
        adb = getADB()
        resp = subprocess.check_output(
            [adb, "-s", get_identifier(), "shell", "dumpsys", "window"]
        )
        resp = resp.decode("utf-8").split("\n")
        res = ""
        for line in resp:
            if "mUnrestrictedScreen" in line:
                res = line
                break
        res = res.split("(0,0)")[1]
        res = res.strip()
        res = res.split("x")
        if len(res) == 2:
            return res[0], res[1]
            # width, height
        return "", ""
    except:
        PrintException("Getting Screen Resolution")
        return "", ""
# Buggy code
def get_identifier():
    """Get Device Type"""
    try:
        if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE":
            return settings.DEVICE_IP + ":" + str(settings.DEVICE_ADB_PORT)
        elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
            return "emulator-" + str(settings.AVD_ADB_PORT)
        else:
            return settings.VM_IP + ":" + str(settings.VM_ADB_PORT)
    except:
        PrintException("[ERROR] Getting ADB Connection Identifier for Device/VM")


# 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_identifier():
    """Get Device Type"""
    try:
        if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_REAL_DEVICE":
            return settings.DEVICE_IP + ":" + str(settings.DEVICE_ADB_PORT)
        elif settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
            return "emulator-" + str(settings.AVD_ADB_PORT)
        else:
            return settings.VM_IP + ":" + str(settings.VM_ADB_PORT)
    except:
        PrintException("Getting ADB Connection Identifier for Device/VM")
# Buggy code
def adb_command(cmd_list, shell=False, silent=False):
    emulator = get_identifier()
    adb = getADB()

    args = [adb, "-s", emulator]
    if shell:
        args += ["shell"]
    args += cmd_list

    try:
        result = subprocess.check_output(args)
        return result
    except:
        if not silent:
            PrintException("[ERROR] adb_command")
        return None


# 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 adb_command(cmd_list, shell=False, silent=False):
    emulator = get_identifier()
    adb = getADB()

    args = [adb, "-s", emulator]
    if shell:
        args += ["shell"]
    args += cmd_list

    try:
        result = subprocess.check_output(args)
        return result
    except:
        if not silent:
            PrintException("Running ADB Command")
        return None
# Buggy code
def install_and_run(apk_path, package, launcher, is_activity):
    """Install APK and Run it"""
    logger.info("Starting App for Dynamic Analysis")
    try:
        adb = getADB()
        logger.info("Installing APK")
        adb_command(["install", "-r", apk_path])
        if is_activity:
            run_app = package + "/" + launcher
            logger.info("Launching APK Main Activity")
            adb_command(["am", "start", "-n", run_app], True)
        else:
            logger.info("App Doesn't have a Main Activity")
            # Handle Service or Give Choice to Select in Future.
        logger.info("Testing Environment is Ready!")
    except:
        PrintException("[ERROR]  Starting App for Dynamic Analysis")


# 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 install_and_run(apk_path, package, launcher, is_activity):
    """Install APK and Run it"""
    logger.info("Starting App for Dynamic Analysis")
    try:
        adb = getADB()
        logger.info("Installing APK")
        adb_command(["install", "-r", apk_path])
        if is_activity:
            run_app = package + "/" + launcher
            logger.info("Launching APK Main Activity")
            adb_command(["am", "start", "-n", run_app], True)
        else:
            logger.info("App Doesn't have a Main Activity")
            # Handle Service or Give Choice to Select in Future.
        logger.info("Testing Environment is Ready!")
    except:
        PrintException("Starting App for Dynamic Analysis")
# Buggy code
def refresh_vm(uuid, snapshot_uuid, vbox_exe):
    """Refresh VirtualBox based VMs"""
    logger.info("Refreshing MobSF VM")
    try:
        if not vbox_exe:
            logger.error(
                "VirtualBox not found, Manually set VBOXMANAGE_BINARY in settings.py"
            )
        # Close VM
        args = [vbox_exe, "controlvm", uuid, "poweroff"]
        subprocess.call(args)
        logger.info("VM Closed")
        time.sleep(3)
        # Restore Snapshot
        args = [vbox_exe, "snapshot", uuid, "restore", snapshot_uuid]
        subprocess.call(args)
        logger.info("VM Restore Snapshot")
        # Start Fresh VM
        args = [vbox_exe, "startvm", uuid]
        if settings.VBOX_HEADLESS:
            args += ["--type", "headless"]
        subprocess.call(args)
        logger.info("VM Starting")
    except:
        PrintException("[ERROR] Refreshing MobSF VM")


# 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 refresh_vm(uuid, snapshot_uuid, vbox_exe):
    """Refresh VirtualBox based VMs"""
    logger.info("Refreshing MobSF VM")
    try:
        if not vbox_exe:
            logger.error(
                "VirtualBox not found, Manually set VBOXMANAGE_BINARY in settings.py"
            )
        # Close VM
        args = [vbox_exe, "controlvm", uuid, "poweroff"]
        subprocess.call(args)
        logger.info("VM Closed")
        time.sleep(3)
        # Restore Snapshot
        args = [vbox_exe, "snapshot", uuid, "restore", snapshot_uuid]
        subprocess.call(args)
        logger.info("VM Restore Snapshot")
        # Start Fresh VM
        args = [vbox_exe, "startvm", uuid]
        if settings.VBOX_HEADLESS:
            args += ["--type", "headless"]
        subprocess.call(args)
        logger.info("VM Starting")
    except:
        PrintException("Refreshing MobSF VM")