// 73-Labs/examples/chain-target/src/com/pentest/ch73/chain/VaultActivity.java
//
// Lab 02's target activity. DELIBERATELY INSECURE.
//
// Two of the chapter's planted findings live here:
//
//   Finding 1  an exported activity that changes behaviour on an Intent extra
//              no legitimate caller sets. This is the "debug flag left in"
//              pattern, and it is exploitable from `am start` with no
//              permission at all.
//   Finding 4  a key that is not a key. The vault "encrypts" its secret by
//              XOR-ing it with a constant that is compiled into the DEX, so
//              recovering it is a static exercise and needs no device.
//
// The lab asks you to find both statically, then confirm both dynamically, and
// to notice that the confirmation for finding 1 is trivial while the
// confirmation for finding 4 requires you to decide what "confirmed" means
// when the evidence is a constant in a file.
//
// AUTHORISED TESTING ONLY.

package com.pentest.ch73.chain;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.widget.TextView;

public class VaultActivity extends Activity {

    private static final String TAG = "ch73chain";

    // Finding 4. Sixteen bytes that a developer called a key. It is in the
    // DEX, in the clear, and `strings` finds it without a decompiler.
    private static final String OBFUSCATION_KEY = "ch73-not-a-key!!";

    // The extra that should never have shipped. Finding 1.
    private static final String EXTRA_UNLOCK = "com.pentest.ch73.chain.UNLOCK";

    private static final String PREFS = "vault";
    private static final String KEY_SECRET = "wrapped_secret";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        seedIfEmpty();

        boolean unlocked = getIntent() != null
                && getIntent().getBooleanExtra(EXTRA_UNLOCK, false);

        TextView view = new TextView(this);
        view.setPadding(48, 96, 48, 48);

        if (unlocked) {
            // No caller identity is checked. Not the calling package, not a
            // permission, not a signature. The extra is the whole gate.
            String secret = unwrap(readWrapped());
            Log.i(TAG, "vault opened via extra; secret=" + secret);
            view.setText("UNLOCKED\n\n" + secret);
        } else {
            Log.i(TAG, "vault locked; launched by "
                    + (getCallingPackage() == null ? "(unknown)" : getCallingPackage()));
            view.setText("LOCKED\n\nThis vault is closed.");
        }
        setContentView(view);
    }

    /** Writes the wrapped secret on first run so the provider has a row. */
    private void seedIfEmpty() {
        SharedPreferences prefs = getSharedPreferences(PREFS, Context.MODE_PRIVATE);
        if (prefs.contains(KEY_SECRET)) {
            return;
        }
        String plaintext = "CH73{the-chain-is-the-lesson}";
        prefs.edit().putString(KEY_SECRET, wrap(plaintext)).apply();
    }

    private String readWrapped() {
        return getSharedPreferences(PREFS, Context.MODE_PRIVATE)
                .getString(KEY_SECRET, "");
    }

    // "Encryption". A repeating-key XOR, then Base64 so it survives an XML
    // preferences file. This is finding 4: reversible with the constant above
    // and forty lines of any language.
    static String wrap(String plaintext) {
        byte[] in = plaintext.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        byte[] key = OBFUSCATION_KEY.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        byte[] out = new byte[in.length];
        for (int i = 0; i < in.length; i++) {
            out[i] = (byte) (in[i] ^ key[i % key.length]);
        }
        return Base64.encodeToString(out, Base64.NO_WRAP);
    }

    static String unwrap(String wrapped) {
        if (wrapped == null || wrapped.isEmpty()) {
            return "";
        }
        byte[] in = Base64.decode(wrapped, Base64.NO_WRAP);
        byte[] key = OBFUSCATION_KEY.getBytes(java.nio.charset.StandardCharsets.UTF_8);
        byte[] out = new byte[in.length];
        for (int i = 0; i < in.length; i++) {
            out[i] = (byte) (in[i] ^ key[i % key.length]);
        }
        return new String(out, java.nio.charset.StandardCharsets.UTF_8);
    }

    /** Unused by the app; kept so Lab 02 has something to find in a grep. */
    public static Intent unlockIntent() {
        Intent intent = new Intent();
        intent.setClassName("com.pentest.ch73.chain",
                "com.pentest.ch73.chain.VaultActivity");
        intent.putExtra(EXTRA_UNLOCK, true);
        return intent;
    }
}
