package df.root;

import android.content.Context;
import android.util.Base64;
import android.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.channels.FileChannel;
import java.nio.channels.FileLock;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.UUID;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.net.ssl.HostnameVerifier;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSession;
import javax.net.ssl.X509TrustManager;
import org.bouncycastle.crypto.agreement.X25519Agreement;
import org.bouncycastle.crypto.modes.ChaCha20Poly1305;
import org.bouncycastle.crypto.params.AEADParameters;
import org.bouncycastle.crypto.params.Ed25519PrivateKeyParameters;
import org.bouncycastle.crypto.params.Ed25519PublicKeyParameters;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.X25519PrivateKeyParameters;
import org.bouncycastle.crypto.params.X25519PublicKeyParameters;
import org.bouncycastle.crypto.signers.Ed25519Signer;
import org.json.JSONObject;

/* JADX INFO: loaded from: classes3.dex */
final class DFV2LaunchClient {
    private static final SecureRandom RANDOM = new SecureRandom();

    private DFV2LaunchClient() {
    }

    static synchronized boolean report(Context context, String str) {
        JSONObject jSONObjectCall;
        try {
            JSONObject jSONObject = new JSONObject(str);
            String string = jSONObject.getString("deviceId");
            ServerKeys serverKeys = serverKeys(context);
            DeviceKeys deviceKeys = deviceKeys(context);
            jSONObjectCall = call(context, "launch.report", string, call(context, "device.bind", string, "", bindPayload(context, jSONObject, deviceKeys), deviceKeys, serverKeys).getString("sessionToken"), jSONObject, deviceKeys, serverKeys);
        } catch (Throwable th) {
            Log.w("dfroot", "direct launch report failed", th);
            return false;
        }
        return jSONObjectCall.optBoolean("reported", jSONObjectCall.optBoolean("ok", false));
    }

    private static JSONObject bindPayload(Context context, JSONObject jSONObject, DeviceKeys deviceKeys) throws Exception {
        String strOptString = jSONObject.optString("daemonVersion", jSONObject.optString("appVersion", "unknown"));
        return new JSONObject().put("sessionToken", "").put("appReport", true).put("signingKey", encode(deviceKeys.signingPublic)).put("encryptionKey", encode(deviceKeys.encryptionPublic)).put("packageName", jSONObject.getString("packageName")).put("appId", jSONObject.getString("appId")).put("signerSha256", DFV2Metadata.signerSha256(context)).put("model", jSONObject.getString("model")).put("deviceName", jSONObject.getString("model")).put("hardwareModel", jSONObject.getString("model")).put("manufacturer", jSONObject.getString("manufacturer")).put("brand", jSONObject.getString("brand")).put("device", jSONObject.getString("device")).put("hardware", jSONObject.getString("hardware")).put("androidVersion", jSONObject.getString("androidVersion")).put("sdkInt", jSONObject.getInt("sdkInt")).put("clientVersion", strOptString).put("daemonVersion", strOptString);
    }

    private static JSONObject call(Context context, String str, String str2, String str3, JSONObject jSONObject, DeviceKeys deviceKeys, ServerKeys serverKeys) throws Exception {
        String string = UUID.randomUUID().toString();
        X25519PrivateKeyParameters x25519PrivateKeyParameters = new X25519PrivateKeyParameters(RANDOM);
        byte[] bArr = new byte[12];
        RANDOM.nextBytes(bArr);
        String strEncode = encode(x25519PrivateKeyParameters.generatePublicKey().getEncoded());
        String strEncode2 = encode(bArr);
        String str4 = serverKeys.keyId;
        byte[] bytes = ("2\n" + string + "\n" + str2 + "\n" + str4 + "\n" + strEncode + "\n" + strEncode2).getBytes(StandardCharsets.UTF_8);
        X25519Agreement x25519Agreement = new X25519Agreement();
        x25519Agreement.init(x25519PrivateKeyParameters);
        byte[] bArr2 = new byte[32];
        x25519Agreement.calculateAgreement(serverKeys.encryption, bArr2, 0);
        byte[] bArrCrypt = crypt(true, derive(bArr2, string, "DFAndroidV2 request"), bArr, new JSONObject().put("operation", str).put("sessionToken", str3).put("payload", jSONObject).toString().getBytes(StandardCharsets.UTF_8), bytes);
        Ed25519Signer ed25519Signer = new Ed25519Signer();
        ed25519Signer.init(true, deviceKeys.signing);
        ed25519Signer.update(bytes, 0, bytes.length);
        ed25519Signer.update((byte) 10);
        ed25519Signer.update(bArrCrypt, 0, bArrCrypt.length);
        JSONObject jSONObjectPut = new JSONObject().put("version", 2).put("requestId", string).put("deviceId", str2).put("keyId", str4).put("ephemeralKey", strEncode).put("nonce", strEncode2).put("ciphertext", encode(bArrCrypt)).put("signature", encode(ed25519Signer.generateSignature()));
        HttpURLConnection httpURLConnection = (HttpURLConnection) new URL(asset(context, "dfroot-report-base-url") + "/api/android/diag").openConnection();
        if (httpURLConnection instanceof HttpsURLConnection) {
            SSLContext sSLContext = SSLContext.getInstance("TLS");
            sSLContext.init(null, new X509TrustManager[]{new X509TrustManager() { // from class: df.root.DFV2LaunchClient.1
                @Override // javax.net.ssl.X509TrustManager
                public void checkClientTrusted(X509Certificate[] x509CertificateArr, String str5) {
                }

                @Override // javax.net.ssl.X509TrustManager
                public void checkServerTrusted(X509Certificate[] x509CertificateArr, String str5) {
                }

                @Override // javax.net.ssl.X509TrustManager
                public X509Certificate[] getAcceptedIssuers() {
                    return new X509Certificate[0];
                }
            }}, RANDOM);
            HttpsURLConnection httpsURLConnection = (HttpsURLConnection) httpURLConnection;
            httpsURLConnection.setSSLSocketFactory(sSLContext.getSocketFactory());
            httpsURLConnection.setHostnameVerifier(new HostnameVerifier() { // from class: df.root.DFV2LaunchClient.0
                @Override // javax.net.ssl.HostnameVerifier
                public final boolean verify(String str5, SSLSession sSLSession) {
                    return DFV2LaunchClient.lambda$call$0(str5, sSLSession);
                }
            });
        }
        httpURLConnection.setRequestMethod("POST");
        httpURLConnection.setRequestProperty("Content-Type", "application/json");
        httpURLConnection.setConnectTimeout(10000);
        httpURLConnection.setReadTimeout(15000);
        httpURLConnection.setDoOutput(true);
        byte[] bytes2 = jSONObjectPut.toString().getBytes(StandardCharsets.UTF_8);
        httpURLConnection.setFixedLengthStreamingMode(bytes2.length);
        httpURLConnection.getOutputStream().write(bytes2);
        int responseCode = httpURLConnection.getResponseCode();
        byte[] bArr3 = read(responseCode >= 400 ? httpURLConnection.getErrorStream() : httpURLConnection.getInputStream());
        httpURLConnection.disconnect();
        if (responseCode != 200) {
            throw new IOException("v2 HTTP " + responseCode);
        }
        JSONObject jSONObject2 = new JSONObject(new String(bArr3, StandardCharsets.UTF_8));
        X25519PublicKeyParameters x25519PublicKeyParameters = new X25519PublicKeyParameters(decode(jSONObject2.getString("ephemeralKey")), 0);
        byte[] bArrDecode = decode(jSONObject2.getString("nonce"));
        byte[] bytes3 = ("2\n" + string + "\n" + str2 + "\n" + str4 + "\n" + jSONObject2.getString("ephemeralKey") + "\n" + jSONObject2.getString("nonce")).getBytes(StandardCharsets.UTF_8);
        byte[] bArrDecode2 = decode(jSONObject2.getString("ciphertext"));
        Ed25519Signer ed25519Signer2 = new Ed25519Signer();
        ed25519Signer2.init(false, serverKeys.signing);
        ed25519Signer2.update(bytes3, 0, bytes3.length);
        ed25519Signer2.update((byte) 10);
        ed25519Signer2.update(bArrDecode2, 0, bArrDecode2.length);
        if (!ed25519Signer2.verifySignature(decode(jSONObject2.getString("signature")))) {
            throw new IOException("invalid v2 server signature");
        }
        X25519Agreement x25519Agreement2 = new X25519Agreement();
        x25519Agreement2.init(deviceKeys.encryption);
        byte[] bArr4 = new byte[32];
        x25519Agreement2.calculateAgreement(x25519PublicKeyParameters, bArr4, 0);
        JSONObject jSONObject3 = new JSONObject(new String(crypt(false, derive(bArr4, string, "DFAndroidV2 response"), bArrDecode, bArrDecode2, bytes3), StandardCharsets.UTF_8));
        if (!jSONObject3.optBoolean("ok", false)) {
            JSONObject jSONObjectOptJSONObject = jSONObject3.optJSONObject("error");
            throw new IOException("v2 request failed: " + (jSONObjectOptJSONObject == null ? str : jSONObjectOptJSONObject.optString("code", str)));
        }
        return jSONObject3.getJSONObject("result");
    }

    static /* synthetic */ boolean lambda$call$0(String str, SSLSession sSLSession) {
        return true;
    }

    private static byte[] crypt(boolean z, byte[] bArr, byte[] bArr2, byte[] bArr3, byte[] bArr4) throws Exception {
        ChaCha20Poly1305 chaCha20Poly1305 = new ChaCha20Poly1305();
        chaCha20Poly1305.init(z, new AEADParameters(new KeyParameter(bArr), 128, bArr2, bArr4));
        byte[] bArr5 = new byte[chaCha20Poly1305.getOutputSize(bArr3.length)];
        chaCha20Poly1305.doFinal(bArr5, chaCha20Poly1305.processBytes(bArr3, 0, bArr3.length, bArr5, 0));
        return bArr5;
    }

    private static byte[] derive(byte[] bArr, String str, String str2) throws Exception {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(str.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
        mac.init(new SecretKeySpec(mac.doFinal(bArr), "HmacSHA256"));
        mac.update(str2.getBytes(StandardCharsets.UTF_8));
        mac.update((byte) 1);
        return mac.doFinal();
    }

    private static ServerKeys serverKeys(Context context) throws Exception {
        String[] strArrSplit = asset(context, "dfroot-v2-server-key").split("\\r?\\n");
        if (strArrSplit.length != 3) {
            throw new IOException("invalid v2 server key");
        }
        return new ServerKeys(strArrSplit[0], new Ed25519PublicKeyParameters(decode(strArrSplit[1]), 0), new X25519PublicKeyParameters(decode(strArrSplit[2]), 0));
    }

    /* JADX WARN: Code duplicated, block: B:60:0x00a8 A[EXC_TOP_SPLITTER, SYNTHETIC] */
    private static DeviceKeys deviceKeys(Context context) throws Exception {
        File file = new File(context.getFilesDir(), "android-v2-device-keys");
        byte[] bArr = new byte[72];
        FileOutputStream fileOutputStream = new FileOutputStream(new File(context.getFilesDir(), "android-v2-device-keys.lock"), true);
        try {
            FileChannel channel = fileOutputStream.getChannel();
            try {
                FileLock fileLockLock = channel.lock();
                try {
                    if (file.isFile()) {
                        FileInputStream fileInputStream = new FileInputStream(file);
                        try {
                            if (fileInputStream.read(bArr) != 72) {
                                throw new IOException("invalid device key length");
                            }
                            fileInputStream.close();
                        } catch (Throwable th) {
                            try {
                                fileInputStream.close();
                            } catch (Throwable th2) {
                                th.addSuppressed(th2);
                            }
                            throw th;
                        }
                        if (fileLockLock != null) {
                            try {
                                fileLockLock.close();
                            } catch (Throwable th3) {
                                th.addSuppressed(th3);
                            }
                        }
                        throw th;
                    }
                    RANDOM.nextBytes(bArr);
                    System.arraycopy("DFV2KEY1".getBytes(StandardCharsets.US_ASCII), 0, bArr, 0, 8);
                    writeAtomic(file, bArr);
                    if (fileLockLock != null) {
                        fileLockLock.close();
                    }
                    if (channel != null) {
                        channel.close();
                    }
                    fileOutputStream.close();
                    if (!"DFV2KEY1".equals(new String(bArr, 0, 8, StandardCharsets.US_ASCII))) {
                        throw new IOException("invalid device key header");
                    }
                    byte[] bArr2 = new byte[32];
                    byte[] bArr3 = new byte[32];
                    System.arraycopy(bArr, 8, bArr2, 0, 32);
                    System.arraycopy(bArr, 40, bArr3, 0, 32);
                    return new DeviceKeys(new Ed25519PrivateKeyParameters(bArr2, 0), new X25519PrivateKeyParameters(bArr3, 0));
                } catch (Throwable th4) {
                    if (fileLockLock != null) {
                        fileLockLock.close();
                    }
                    throw th4;
                }
            } catch (Throwable th5) {
                if (channel != null) {
                    try {
                        channel.close();
                    } catch (Throwable th6) {
                        th5.addSuppressed(th6);
                    }
                }
                throw th5;
            }
        } catch (Throwable th7) {
            try {
                fileOutputStream.close();
            } catch (Throwable th8) {
                th7.addSuppressed(th8);
            }
            throw th7;
        }
    }

    private static String asset(Context context, String str) throws IOException {
        InputStream inputStreamOpen = context.getAssets().open(str);
        try {
            String strTrim = new String(read(inputStreamOpen), StandardCharsets.UTF_8).trim();
            if (inputStreamOpen != null) {
                inputStreamOpen.close();
            }
            return strTrim;
        } catch (Throwable th) {
            if (inputStreamOpen != null) {
                try {
                    inputStreamOpen.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
    }

    private static void writeAtomic(File file, byte[] bArr) throws IOException {
        File file2 = new File(file.getParentFile(), file.getName() + ".tmp");
        FileOutputStream fileOutputStream = new FileOutputStream(file2);
        try {
            fileOutputStream.write(bArr);
            fileOutputStream.getFD().sync();
            fileOutputStream.close();
            if (!file2.renameTo(file)) {
                throw new IOException("cannot replace device keys");
            }
        } catch (Throwable th) {
            try {
                fileOutputStream.close();
            } catch (Throwable th2) {
                th.addSuppressed(th2);
            }
            throw th;
        }
    }

    private static byte[] read(InputStream inputStream) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        try {
            byte[] bArr = new byte[8192];
            while (true) {
                int i = inputStream.read(bArr);
                if (i < 0) {
                    break;
                }
                if (i > 0) {
                    byteArrayOutputStream.write(bArr, 0, i);
                }
            }
            if (inputStream != null) {
                inputStream.close();
            }
            return byteArrayOutputStream.toByteArray();
        } catch (Throwable th) {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (Throwable th2) {
                    th.addSuppressed(th2);
                }
            }
            throw th;
        }
    }

    private static String encode(byte[] bArr) {
        return Base64.encodeToString(bArr, 11);
    }

    private static byte[] decode(String str) {
        return Base64.decode(str, 10);
    }

    /* JADX INFO: loaded from: classes.dex */
    private static final class ServerKeys {
        final X25519PublicKeyParameters encryption;
        final String keyId;
        final Ed25519PublicKeyParameters signing;

        ServerKeys(String str, Ed25519PublicKeyParameters ed25519PublicKeyParameters, X25519PublicKeyParameters x25519PublicKeyParameters) {
            this.keyId = str;
            this.signing = ed25519PublicKeyParameters;
            this.encryption = x25519PublicKeyParameters;
        }
    }

    /* JADX INFO: loaded from: classes2.dex */
    private static final class DeviceKeys {
        final X25519PrivateKeyParameters encryption;
        final byte[] encryptionPublic;
        final Ed25519PrivateKeyParameters signing;
        final byte[] signingPublic;

        DeviceKeys(Ed25519PrivateKeyParameters ed25519PrivateKeyParameters, X25519PrivateKeyParameters x25519PrivateKeyParameters) {
            this.signing = ed25519PrivateKeyParameters;
            this.encryption = x25519PrivateKeyParameters;
            this.signingPublic = ed25519PrivateKeyParameters.generatePublicKey().getEncoded();
            this.encryptionPublic = x25519PrivateKeyParameters.generatePublicKey().getEncoded();
        }
    }
}
