package fuzion24.device.vulnerability.vulnerabilities.framework.media;

import android.content.Context;
import android.util.Log;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import fuzion24.device.vulnerability.util.CPUArch;
import fuzion24.device.vulnerability.vulnerabilities.VulnerabilityTest;
import fuzion24.device.vulnerability.vulnerabilities.helper.TestResult;

import static fuzion24.device.vulnerability.vulnerabilities.helper.BinaryAssets.extractAsset;
import static fuzion24.device.vulnerability.vulnerabilities.helper.CrashCheck.execute;

public class CVE_2015_6602 implements VulnerabilityTest {

    private static final String TAG = "cve-2015-6602";

    public CVE_2015_6602() {}

    @Override
    public List<CPUArch> getSupportedArchitectures() {
        ArrayList<CPUArch> archs = new ArrayList<CPUArch>();
        archs.add(CPUArch.ARM7);
        archs.add(CPUArch.ARM);
        return archs;
    }

    @Override
    public String getCVEorID() {
        return "CVE-2015-6602";
    }

    @Override
    public boolean isVulnerable(Context context) throws Exception {
        String binaryTester = extractBinary(context);
        TestResult result = execute(context, 5, binaryTester);
        Log.d(TAG, "Test result: " + result.toString());
        if (result.isOk()) {
            return result.getCode() != 0;
        } else if (result == TestResult.CRASH) {
            return true;
        } else if (result == TestResult.HANG) {
            throw new Exception("Test is hanging");
        } else if (result == TestResult.ERROR) {
            throw new Exception("Test error");
        }
        throw new Exception("Unknown test result");
    }

    private String extractBinary(Context context) throws IOException {
        File dataDir = context.getFilesDir();

        final String extractedBinaryTester = dataDir.getAbsolutePath() + File.separator + getNativeAppName();
        extractAsset(context, "stagefright" + File.separator + getNativeAppName(),
                extractedBinaryTester);
        Runtime.getRuntime().exec("chmod 744 " + extractedBinaryTester);

        return extractedBinaryTester;
    }

    public static String getNativeAppName() {
        return "utilcheck-pie";
    }
}

@@ -2082,16 +2082,28 @@
 %0A       
+ Process p =
  Runtime
@@ -2133,10 +2133,10 @@
 od 7
-44
+00
  %22 +
@@ -2160,16 +2160,66 @@
 ester);%0A
+        try %7B p.waitFor(); %7D catch (Exception e)%7B%7D
 %0A       

Change to proper permissions and clean up race condition