# Buggy code
def get_env(request):
    """Get Dynamic Analysis Environment for Android"""
    logger.info("Setting up Dynamic Analysis Environment")
    try:
        if request.method == "POST":
            data = {}
            md5_hash = request.POST["md5"]
            package = request.POST["pkg"]
            launcher = request.POST["lng"]
            if re.findall(r";|\$\(|\|\||&&", package) or re.findall(
                r";|\$\(|\|\||&&", launcher
            ):
                logger.info("[ATTACK] Possible RCE")
                return HttpResponseRedirect("/error/")
            if re.match("^[0-9a-f]{32}$", md5_hash):
                base_dir = settings.BASE_DIR
                app_dir = os.path.join(
                    settings.UPLD_DIR, md5_hash + "/"
                )  # APP DIRECTORY
                app_file = md5_hash + ".apk"  # NEW FILENAME
                app_path = app_dir + app_file  # APP PATH
                adb = getADB()
                if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
                    proxy_ip = "127.0.0.1"
                else:
                    proxy_ip = settings.PROXY_IP  # Proxy IP
                start_proxy(settings.PORT, package)
                # vm needs the connect function
                try:
                    if not settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
                        connect()
                except Exception as exp:
                    data = {
                        "ready": "no",
                        "msg": "Cannot Connect to the VM/Device.",
                        "error": str(exp),
                    }
                    return HttpResponse(
                        json.dumps(data), content_type="application/json"
                    )
                # Change True to support non-activity components
                install_and_run(app_path, package, launcher, True)
                screen_width, screen_width = get_res()
                data = {
                    "ready": "yes",
                    "screen_witdth": screen_width,
                    "screen_height": screen_width,
                }
                return HttpResponse(json.dumps(data), content_type="application/json")
            else:
                return HttpResponseRedirect("/error/")
        else:
            return HttpResponseRedirect("/error/")
    except:
        PrintException("[ERROR] Setting up Dynamic Analysis Environment")
        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 get_env(request):
    """Get Dynamic Analysis Environment for Android"""
    logger.info("Setting up Dynamic Analysis Environment")
    try:
        if request.method == "POST":
            data = {}
            md5_hash = request.POST["md5"]
            package = request.POST["pkg"]
            launcher = request.POST["lng"]
            if re.findall(r";|\$\(|\|\||&&", package) or re.findall(
                r";|\$\(|\|\||&&", launcher
            ):
                return print_n_send_error_response(request, "Possible RCE Attack", True)
            if re.match("^[0-9a-f]{32}$", md5_hash):
                base_dir = settings.BASE_DIR
                app_dir = os.path.join(
                    settings.UPLD_DIR, md5_hash + "/"
                )  # APP DIRECTORY
                app_file = md5_hash + ".apk"  # NEW FILENAME
                app_path = app_dir + app_file  # APP PATH
                adb = getADB()
                if settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
                    proxy_ip = "127.0.0.1"
                else:
                    proxy_ip = settings.PROXY_IP  # Proxy IP
                start_proxy(settings.PORT, package)
                # vm needs the connect function
                try:
                    if not settings.ANDROID_DYNAMIC_ANALYZER == "MobSF_AVD":
                        connect()
                except Exception as exp:
                    data = {
                        "ready": "no",
                        "msg": "Cannot Connect to the VM/Device.",
                        "error": str(exp),
                    }
                    return HttpResponse(
                        json.dumps(data), content_type="application/json"
                    )
                # Change True to support non-activity components
                install_and_run(app_path, package, launcher, True)
                screen_width, screen_width = get_res()
                data = {
                    "ready": "yes",
                    "screen_witdth": screen_width,
                    "screen_height": screen_width,
                }
                return HttpResponse(json.dumps(data), content_type="application/json")
            else:
                return print_n_send_error_response(request, "Invalid Scan Hash", True)
        else:
            return print_n_send_error_response(request, "Only POST allowed", True)
    except:
        PrintException("Setting up Dynamic Analysis Environment")
        return print_n_send_error_response(request, "Environment Setup Failed", True)