Skip to content

Latest commit

 

History

History
1477 lines (1047 loc) · 52.1 KB

android_custom_os_setup.md

File metadata and controls

1477 lines (1047 loc) · 52.1 KB

Consolidated Guide: Installing and Configuring a Custom Android Environment for Daily + Advanced Use

This document consolidates the entire discussion into a single, fully detailed setup plan for running a custom Android OS (e.g., LineageOS) with strong isolation, full customization, and advanced tooling. It prioritizes daily usability while enabling advanced usage (pentesting, Linux tools, etc.). Every step is explicitly spelled out with explanations, not just mentions. It now also includes an alternative path for Jolla Community / Sony Xperia devices, and a conceptual guide to dual-booting Sailfish OS and LineageOS.


1. Choosing the OS: LineageOS

What LineageOS Is

  • LineageOS is an open-source Android distribution maintained by a large community.
  • It is based on the Android Open Source Project (AOSP) but strips away Google’s proprietary services, tracking, and pre-installed bloatware.
  • It provides a clean, stable, and flexible foundation for customization.
  • You can still add Google Apps (via GApps) if you need them, but you control whether they are present and how isolated they are.
  • LineageOS accepts rooting via Magisk easily, which allows modules like AFWall+, LSPosed, or BusyBox.
  • Daily-driver stability is a core design goal.

Pros

  • Stable and actively maintained for many modern phones (Pixel, Xiaomi, Samsung Galaxy, OnePlus, etc.).
  • Maintains Android app (APK) compatibility.
  • Gives you privacy control: no Google Play Services by default, unless you flash them.
  • Community-driven with many device-specific maintainers.

Cons

  • Camera drivers and biometrics may be less polished than stock firmware (depends on device).
  • May require unofficial builds if your device is not officially supported.
  • Google apps and services are optional add-ons but must be flashed separately.

2. Preparation (Linux Environment)

You’ll be working in Linux for flashing. Ensure you have the necessary tools:

Install Required Tools

sudo apt update
sudo apt install android-tools-adb android-tools-fastboot
  • adb = Android Debug Bridge (manage device, install packages, enable debugging).
  • fastboot = tool for flashing partitions while in bootloader mode.
  • Custom Recovery (e.g., TWRP or OrangeFox) must be downloaded.
  • ROM: LineageOS build for your device.
  • Optional packages:
    • GApps (NikGApps, MindTheGApps) → install only if you want Play Store.
    • Magisk ZIP + APK → for rooting and module support.

Device Preparation

  1. On the phone, go to Settings → About Phone → tap Build Number 7 times to enable Developer Options.
  2. In Developer Options: enable OEM Unlocking and USB Debugging.
  3. Connect device to PC, verify with:
adb devices

Unlock Bootloader

adb reboot bootloader
fastboot flashing unlock
  • Confirm on the phone screen.
  • Unlocking wipes all data, so back up first.

3. Flashing LineageOS

Steps

  1. Reboot into bootloader:
adb reboot bootloader
  1. Flash recovery image:
fastboot flash recovery twrp.img
  1. Reboot into recovery:
fastboot reboot recovery
  1. In recovery (TWRP/OrangeFox): Wipe partitions (Dalvik/ART Cache, System, Data, Cache).

  2. Sideload LineageOS:

adb sideload lineageos.zip
  1. (Optional) Sideload GApps:
adb sideload gapps.zip
  1. Reboot into LineageOS system.

4. Root + Magisk Modules

Root

  1. From recovery, sideload Magisk ZIP.
  2. Reboot system.
  3. Install Magisk Manager APK on the phone.
  4. Open app → verify root status.

Install Essential Modules

  • Riru – backend framework used by LSPosed.
  • LSPosed – Xposed framework for modifying apps.
  • Shizuku – allows apps to request elevated permissions.
  • BusyBox – standard Linux utilities missing on Android.
  • AFWall+ – firewall that controls which apps use WiFi/Mobile.
  • AdAway – system-wide ad blocker.
  • Kernel tools (EX Kernel Manager, SmartPack) – optional if tweaking CPU/GPU.

5. Profiles & App Isolation

Work Profile (via Island/Shelter)

  1. Install Island or Shelter from F-Droid.
  2. Create a Work Profile → isolated container.
  3. Inside Work Profile, install Google Drive, Microsoft Teams, Outlook, OneDrive.
  4. Apply AFWall+ and VPN rules to separate their traffic.

Main Profile (Personal)

  • Install Proton apps (Mail, VPN), Ente Auth, Discord with Vencord, Firefox.
  • Keep Google/MS apps out of personal profile.

Result

  • Work profile = Google/Microsoft only.
  • Personal profile = Proton/Ente/Discord.
  • Firefox PWAs = third instance of Google/MS apps (see section 8).

6. Networking & Privacy Controls

AFWall+ Setup (Step-by-Step)

  1. Open AFWall+, grant root.
  2. Enable per-profile control.
  3. Configure rules:
    • Work profile: allow Google/Microsoft apps → block Proton apps.
    • Personal profile: allow Proton/Discord apps → block Google/MS.
  4. Enable IPv4 and IPv6 support.
  5. Enable firewall logging to verify activity.

VPN Setup

  • Install ProtonVPN.
  • Assign:
    • Work profile → ProtonVPN limited to Google/MS apps.
    • Personal profile → ProtonVPN for Proton/Discord traffic.
  • In Android Settings: enable Always-on VPN + Block connections without VPN.

Extra Privacy Layers

  • AdAway blocks ads/trackers at system level.
  • LSPosed modules can spoof device info, block analytics.
  • Shizuku automation enforces firewall/VPN rules on boot.

7. Installing Core Apps

Firefox

  1. Download via F-Droid.
  2. Install Firefox Containers Add-on.
  3. Add uBlock Origin, HTTPS Everywhere, Cookie AutoDelete.

Discord + Vencord

  1. Install Discord APK.
  2. Install Vencord Installer APK.
  3. Patch Discord.
  4. Open Discord → verify Vencord enabled.
  5. Configure plugins/themes for usability.

Proton Suite

  • Install ProtonMail, ProtonVPN, Proton Bridge.
  • ProtonVPN set to Always-on in personal profile.

Ente Auth

  • Install APK, migrate/import 2FA codes.
  • Use as 2FA replacement instead of Google Authenticator.

Google/Microsoft Suite (Work Profile)

  1. Install Google Drive, OneDrive, Outlook, Teams inside work profile.
  2. Hide root for these apps via Magisk DenyList.
  3. If apps fail, spoof device fingerprint with LSPosed.

8. Running Multiple Accounts with PWAs

Instead of three installs of the same app, use PWAs (Progressive Web Apps):

  1. Open Firefox/IceRaven.
  2. Navigate to Google Drive.
  3. Use browser menu → “Install Site as App”.
  4. Repeat for Outlook, OneDrive, Teams.

Result:

  • Personal Google Drive = APK in personal profile.
  • Work Google Drive = APK in work profile.
  • Secondary Google Drive = Firefox PWA.

This provides 3 isolated instances without juggling multiple OS profiles.


9. Linux / Pentesting Environment

Termux Setup

  1. Install Termux via F-Droid.
  2. Install add-ons: Termux:API, Termux:Boot.
  3. Update system and install tools:
pkg update && pkg upgrade
pkg install nmap hashcat aircrack-ng python git

Kali Nethunter

  1. Download Nethunter rootfs.
  2. Import into Termux with proot-distro.
  3. Launch Nethunter shell for a full Kali environment.
  4. Run standard tools (nmap, hydra, metasploit, hashcat).
  5. Use VPN split tunneling to keep pentesting traffic isolated from personal apps.

10. Alternative Path: Jolla Community / Sony Xperia Devices

Why Xperia Devices Are Ideal

Sony’s Open Devices Program provides full kernel sources, device trees, and flashing documentation. Xperia models are fully AOSP-compatible with fastboot flashing, making them ideal for experimentation.

Advantages:

  • Official bootloader unlocking.
  • Kernel source access on Sony’s GitHub.
  • Active developer community (LineageOS, Sailfish, Ubuntu Touch, postmarketOS).
  • Predictable partition layout and easy recovery.

Recommended Models

  • Xperia 10 / 10 II / 10 III (Jolla’s main community phones)
  • Xperia XA2 / XA2 Ultra (older but stable)
  • Xperia X / XZ1 Compact (compact, budget)
  • Xperia 1 II / 5 II (flagships with long-term support)

Installing LineageOS or Other OSes

  1. Unlock the bootloader via Sony’s official site using IMEI.
  2. Flash TWRP or Lineage recovery.
  3. Wipe system/data/cache.
  4. Flash ROM (LineageOS, /e/OS, Ubuntu Touch, or Sailfish).
  5. Flash Magisk if rooting.
  6. Reboot and configure profiles as above.

Dual-Boot Possibility: Sailfish + LineageOS

While not officially supported, a dual-boot setup is technically possible because Sailfish OS and LineageOS share the same kernel base (Sony AOSP). Methods:

  1. Shared Bootloader Chain: Use a multiboot recovery like TWRP Multiboot or BootMenu to alternate system partitions.
  2. Partition Duplication: Create an additional system_b partition, flash Sailfish on one, LineageOS on the other.
  3. Boot Script Control: Modify init scripts or use bootctl set-active-boot-slot to toggle active systems.
  4. Waydroid or Chroot Approach: Alternatively, run one OS within the other (Sailfish with Waydroid or LineageOS with a Sailfish container).

Limitations: Dual-booting requires manual control of partitions and recovery; automatic switching is rare. Backup partitions before experimentation.

Benefit: You can maintain a full Linux (Sailfish) environment while retaining an Android-focused OS (Lineage) for app compatibility.


11. Final Setup Diagram

┌─────────────────────────────────────────────────┐
│                 Android Device                  │
│                                                 │
│ ┌──────────────┐   ┌──────────────┐             │
│ │ Work Profile │   │ Personal Prof│             │
│ │--------------│   │--------------│             │
│ │ Google Suite │   │ ProtonMail   │             │
│ │ MS Office    │   │ Ente Auth    │             │
│ │ Outlook      │   │ Discord+Venc │             │
│ │ Teams        │   │ Firefox+PWAs │             │
│ │ VPN (Proton) │   │ ProtonVPN    │             │
│ └──────────────┘   └──────────────┘             │
│         ↑                  ↑                    │
│         │                  │                    │
│   AFWall+ / NetGuard Firewall Rules             │
│        (Per-profile isolation)                  │
│                                                 │
│                 LineageOS + Magisk              │
│ ┌────────────────────────────────────────────┐  │
│ │ Modules: LSPosed, Riru, Shizuku, BusyBox,  │  │
│ │ AFWall+, AdAway, Kernel Auditor optional   │  │
│ └────────────────────────────────────────────┘  │
│                                                 │
│             Termux / Kali / Nethunter           │ 
│             (Pentesting / CLI tools)            │ 
└─────────────────────────────────────────────────┘

12. Alternative Path: Jolla Community / Sony Xperia Devices

Why Xperia-Based Jolla Phones Are Ideal

Sony Xperia devices (especially those in Jolla’s Community Device lineup) are among the most developer-friendly phones available today. Through the Sony Open Devices Program (ODP), you get:

  • Official kernel source and vendor binaries for AOSP builds.
  • Official fastboot unlocking via Sony’s site.
  • Legal, fully documented methods for flashing and modifying the OS.
  • Active support for LineageOS, SailfishOS, Ubuntu Touch, /e/OS, and even postmarketOS.

This means you can replace or dual-boot operating systems with almost no proprietary lock-in or hidden risk.


Supported Models

Model ODP Support Notes
Xperia 10 / 10 II / 10 III ✅ Official Jolla community phones, Sailfish preinstalled
Xperia XA2 / XA2 Ultra ✅ Great LineageOS and Ubuntu Touch support
Xperia X / XZ1 Compact ✅ Small form factor, mature ROMs
Xperia 1 II / 5 II ✅ Flagships with long-term kernel updates

Flashing / Replacing SailfishOS with LineageOS

  1. Unlock Bootloader

    • Obtain unlock code from Sony’s developer site.

    • Enable OEM Unlocking and USB Debugging.

    • Connect via USB and execute:

      adb reboot bootloader
      fastboot oem unlock 0x<unlock_code>
  2. Flash Recovery

    • Download TWRP or Lineage Recovery for your Xperia model.

      fastboot flash recovery twrp.img
  3. Wipe Partitions

    • In recovery, wipe System, Data, Cache, and Dalvik.
  4. Install LineageOS

    adb sideload lineageos.zip
  5. Optional: Reinstall SailfishOS later

    • Jolla provides flashable Sailfish images with scripts for fastboot.
    • You can swap back and forth by re-flashing system partitions.

Flashing SailfishOS Over LineageOS

  1. Obtain a Sailfish image for your device from Jolla’s developer portal.

  2. Boot to fastboot mode.

  3. Execute the provided flash.sh script:

    ./flash.sh
  4. The script wipes LineageOS partitions and flashes Sailfish system + userdata.


Dual-Boot Concept (Experimental / Advanced)

Dual-booting Sailfish and Lineage is possible via careful partition management and the use of multi-boot recovery or boot managers.

⚙️ Conceptual Approach

  1. Resize userdata partition using parted from recovery to create ~4–6 GB of free space.

  2. Create an extra ext4 partition (e.g., /dev/block/sda64) for the secondary OS.

  3. Flash:

    • LineageOS to /system_a.
    • SailfishOS to /system_b (or the new partition).
  4. Use TWRP’s “Install Image” function to write each OS to its own slot.

  5. Configure boot control via:

    fastboot --set-active=a
    fastboot --set-active=b

    or install MultiROM (legacy) or a custom recovery script that lets you pick an OS on boot.

  6. Keep /data shared or separate (recommended: separate for stability).

🧩 Alternate Method: Waydroid Integration

Instead of dual-booting:

  • Keep SailfishOS as the host.

  • Use Waydroid (Android container) to run LineageOS-based Android inside it. This grants:

    • Full APK compatibility.
    • Seamless switch between Linux and Android sessions.
    • Fewer flashing risks.

⚠️ Notes on Dual-Boot Stability

  • Always back up the entire userdata and system partitions before experimenting.

  • Boot slots (_a/_b) differ by model; confirm partition maps with:

    fastboot getvar all
  • Jolla’s init scripts assume control over /system; modifying them can break OTA updates.

  • Ideal for tinkering or multi-environment setups, not for mission-critical daily use.


Advantages of Xperia / Jolla Path

Feature Benefit
Official Bootloader Unlock No shady exploits, fully reversible
Kernel Source Build and modify yourself
AOSP & Lineage Support Seamless porting between OSes
SailfishOS Base Linux-native stack with Waydroid
PostmarketOS Compatibility True Linux phone potential
Excellent Documentation Sony publishes flashing & recovery guides

Combined Daily/Advanced Use Setup

Layer OS/Tool Purpose
Host OS LineageOS or Sailfish Base platform
Root Framework Magisk Control + modules
Isolation Island/Shelter + PWAs Sandbox for work/personal
Pentesting Termux + Nethunter Advanced tools
Privacy AFWall+, AdAway, LSPosed Network & tracking control
Dual-boot or Waydroid Optional Switch or embed other OS
Apps Firefox, Discord+Vencord, Proton, Ente Daily driver suite

Summary: Why Consider Xperia/Jolla

  • You gain a fully open hardware stack, rare among modern smartphones.
  • Dual-booting or hybrid OS usage becomes realistic.
  • You can test or use Android, Sailfish, or Ubuntu Touch interchangeably.
  • Hardware (Snapdragon, modem, camera) is well-supported by the open community.
  • Long-term: this is the most modder-friendly and privacy-respecting hardware route for advanced mobile Linux/Android experimentation.

🧩 Appendix: Advanced Dual-Boot & Integration Techniques

This appendix details optional but powerful configurations for Sony Xperia and other Treble-compliant phones that allow true OS switching or hybridization between Android (LineageOS) and Linux (Sailfish, Ubuntu Touch, etc.). Proceed only if you’re comfortable manipulating partitions and bootloaders.


A1. Partition Inspection & Backups

Before attempting any partitioning or flashing, inspect your layout and back up everything.

adb reboot bootloader
fastboot getvar all | grep partition

You’ll see something like:

(boot_a), (boot_b)
(system_a), (system_b)
(vendor_a), (vendor_b)
(userdata)

Backup System and Data

fastboot flash recovery twrp.img
adb reboot recovery
adb pull /dev/block/bootdevice/by-name/system_a system_a.img
adb pull /dev/block/bootdevice/by-name/userdata userdata.img

Keep these images safe—they allow a full rollback.


A2. Partition Resizing (Creating Space for a Secondary OS)

Use TWRP’s terminal or an attached Linux host to resize the userdata partition:

  1. Identify your block device (e.g., /dev/block/sda).

  2. Launch parted:

    parted /dev/block/sda
  3. Print and note partitions:

    print
  4. Resize userdata:

    resizepart <partition_number> <new_end_value>
    mkpart ext4 secondos <new_start_value> <new_end_value>
  5. Format the new partition:

    mkfs.ext4 /dev/block/sda64

Now /dev/block/sda64 will be your second OS slot (for Sailfish, Ubuntu Touch, or another Android ROM).


A3. Flashing Secondary OS to New Partition

Example: Flash SailfishOS as Secondary

  1. Extract Sailfish image from flash.sh package.

  2. Identify the system image file (sailfish.img).

  3. Flash manually:

    fastboot flash system_b sailfish.img
    fastboot --set-active=b
    fastboot reboot

To switch back:

fastboot --set-active=a
fastboot reboot

A4. Using Dual Slots (A/B Partition Devices)

Modern Xperia devices use A/B partitioning for seamless updates. You can exploit this for dual-booting.

Steps

  1. Flash LineageOS to slot a and SailfishOS to slot b.

  2. Use fastboot to switch between them:

    fastboot getvar current-slot
    fastboot --set-active=a  # Switch to Lineage
    fastboot --set-active=b  # Switch to Sailfish
  3. Boot normally—the chosen slot determines which OS loads.

🧠 Tip: Keep /data common only if both OSes use Android’s encryption schema; otherwise, keep separate partitions for stability.


A5. MultiROM or Custom Boot Selector

The legacy MultiROM boot manager can be ported to some Xperia devices, or you can use TWRP’s “Install Image” to maintain multiple system images and flash them dynamically.

Simplified Manual Selector

  1. Push both OS images (system_lineage.img, system_sailfish.img) to /sdcard.

  2. Use TWRP’s terminal:

    dd if=/sdcard/system_lineage.img of=/dev/block/bootdevice/by-name/system_a
    dd if=/sdcard/system_sailfish.img of=/dev/block/bootdevice/by-name/system_b
  3. Reboot into desired slot.

For more automation, you can flash a small bootmenu binary that lists slots and runs the corresponding fastboot command—several examples exist on XDA.


A6. Waydroid Integration (Android Inside Linux)

If you prefer one OS hosting another instead of dual-booting, Waydroid gives you Android within Sailfish or Ubuntu Touch.

Installation (on Sailfish / Ubuntu Touch)

  1. Connect to your device shell (SSH or terminal).

  2. Add Waydroid repositories:

    sudo zypper ar https://repo.waydroid.org/ waydroid
    sudo zypper refresh
    sudo zypper install waydroid
  3. Initialize the container:

    sudo waydroid init -s GAPPS
  4. Start the Android container:

    sudo systemctl start waydroid-container
    waydroid session start

You’ll now have a Lineage-based Android session running side-by-side with Sailfish Linux, complete with GUI apps, root control, and networking.


A7. Integrating VPN, Firewall, and Termux Between OSes

Component Location Notes
VPN (Proton/OpenVPN) Per-OS Keep independent configs for each OS to prevent leak crossover
AFWall+ / iptables Android side Handles app-level firewall
UFW / nftables Sailfish/Linux side Manages global networking
Termux / chroot tools Android side Full CLI control
SSH between OSes Both Use to exchange scripts and logs securely

A8. Boot Recovery, Rollback, and Maintenance

To recover from errors:

adb reboot bootloader
fastboot --set-active=a
fastboot flash recovery twrp.img
fastboot reboot recovery

In TWRP, restore your backups of system_a, system_b, and userdata. Always verify slot activation before OTA or manual updates.


A9. Example Workflow Summary

Initial:  LineageOS → slot_a
Add:      Sailfish  → slot_b
Switch:   fastboot --set-active=b
Work:     Sailfish + Waydroid container
Switch:   fastboot --set-active=a
Daily:    Lineage + Magisk + Island

A10. Closing Notes

  • Dual-booting is experimental but reliable when done with caution on Xperia devices.
  • Waydroid offers a safer, containerized alternative with nearly the same flexibility.
  • Always maintain full images and understand the implications of shared encryption keys.
  • Combined with your Lineage/Magisk stack, Xperia hardware can become a truly modular, privacy-centric mobile workstation.

🧾 Appendix A11: Xperia Partition Reference Table

⚠️ Note: Always verify exact names on your device using fastboot getvar all or ls /dev/block/bootdevice/by-name/ — firmware updates can slightly alter naming or add new partitions.


📱 Xperia XA2 / XA2 Ultra (H3113–H3223 series)

Partition Function Notes
boot_a, boot_b Boot image (kernel + ramdisk) Dual-slot (A/B) for seamless updates
system_a, system_b Main OS (LineageOS, Sailfish, etc.) Each slot can hold one OS image
vendor_a, vendor_b Vendor blobs (drivers, HALs) Usually identical between slots
userdata /data partition Shared between OSes unless split manually
recovery TWRP / Lineage recovery May be absent if boot.img contains recovery
dtbo_a, dtbo_b Device tree overlays Rarely modified manually
modem_a, modem_b Baseband firmware Never flash unless using official images
persist Calibrations, camera, fingerprint Always back up before flashing
misc Boot flags Controls active slot state

📱 Xperia 10 / 10 II / 10 III

Partition Function Notes
boot_a, boot_b Boot image Same as XA2
system_a, system_b OS partitions Primary location for ROM flashing
vendor_a, vendor_b Vendor partition Required for hardware functionality
userdata User data Encrypted, shared by default
super Logical volume container (Android 10+) Contains dynamic partitions (system, vendor)
recovery Optional standalone recovery Usually embedded
dtbo_a, dtbo_b Device tree overlays Leave untouched
modem_a, modem_b Modem firmware Flash only from official firmware
persist Fingerprint, calibration Must preserve when dual-booting
metadata Encryption keys / FBE Do not mix between OSes

💡 These models often use Dynamic Partitions, meaning system, vendor, and others live inside a shared super partition. Use lpdump or fastboot getvar super-partition-name to inspect subvolumes before resizing.


📱 Xperia X / XZ1 / XZ1 Compact

Partition Function Notes
boot Boot image Single-slot (non-A/B) layout
system OS image Flash custom ROMs here
vendor Hardware abstraction layer Matches OS version
userdata User data Can be split manually
recovery Recovery partition Required for TWRP
modem Radio firmware Leave untouched
persist Calibration data Always back up
cache Legacy system cache Can be repurposed for second OS

🧠 Tip: These older models are simpler for dual-boot experiments — you can repurpose the cache or create a new system2 partition for a secondary OS.


⚙️ Slot Management Commands Reference

Action Command
Check current slot fastboot getvar current-slot
Set active slot A fastboot --set-active=a
Set active slot B fastboot --set-active=b
Verify partitions `fastboot getvar all grep slot`
Reboot into recovery fastboot reboot recovery
List partitions adb shell ls /dev/block/bootdevice/by-name/

🛡️ Backup & Restore Scripts (Example)

Backup all key partitions

for part in boot_a system_a vendor_a persist modem_a; do
  fastboot getvar $part 2>&1 | grep OKAY
  fastboot flash $part backup/${part}.img
done

Restore from saved images

for part in boot_a system_a vendor_a; do
  fastboot flash $part backup/${part}.img
done

🧩 Best Practice: Always back up persist and modem partitions before experimenting. Losing them can permanently break fingerprint or connectivity.


🧠 Notes on Dynamic Partitions (Xperia 10 III, Xperia 5 II+)

Modern Xperias use Dynamic Partitions (super.img):

  • system, vendor, product, and odm exist as subpartitions inside a single logical super.

  • You can manipulate them using lpunpack/lpmake tools:

    lpunpack super.img ./super_parts/
    lpmake --metadata-size 65536 --super-name super_new.img ...
    fastboot flash super super_new.img
  • This allows building custom split or merged system layouts for Lineage + Sailfish coexistence.


🔍 Validation Checklist Before Flashing

✅ Bootloader unlocked ✅ TWRP or Lineage Recovery functional ✅ Full backup of system/vendor/persist/modem ✅ Verified slot map (fastboot getvar all) ✅ Battery ≥ 60% ✅ USB 3.0 cable / stable connection ✅ ROM images verified with sha256sum


🧩 In Practice: Dual-Boot Plan Summary (Example for Xperia 10 II)

Slot OS Kernel Status
A LineageOS 21 (Android 13) Magisk + AFWall+ Daily driver
B SailfishOS 4.x Stock kernel Experimental
Shared userdata, persist VPN configs / calibration Backed up separately

Switch with:

fastboot --set-active=a   # LineageOS
fastboot --set-active=b   # Sailfish

⚙️ Appendix A12: Automation & Integrity Scripts

These scripts are designed to run from your Linux workstation and streamline common flashing and verification tasks for Xperia or Treble-based phones.

💡 All commands assume you’ve installed android-tools-adb and android-tools-fastboot. Use chmod +x scriptname.sh to make them executable.


🔁 A12.1 — OS Slot Switcher

File: switch_os.sh

#!/bin/bash
# Simple slot toggler for Xperia dual-slot devices

set -e

current=$(fastboot getvar current-slot 2>&1 | grep -oE "[ab]")
echo "Current active slot: $current"

if [ "$current" == "a" ]; then
    echo "Switching to slot B (e.g., SailfishOS)..."
    fastboot --set-active=b
else
    echo "Switching to slot A (e.g., LineageOS)..."
    fastboot --set-active=a
fi

fastboot getvar current-slot
echo "Rebooting..."
fastboot reboot

Usage:

adb reboot bootloader
./switch_os.sh

This will toggle between slot A (LineageOS) and slot B (SailfishOS) automatically.


🧩 A12.2 — Full Partition Integrity Checker

File: verify_partitions.sh

#!/bin/bash
# Checks hashes for critical partitions and compares with stored references

mkdir -p hashes

parts=("boot_a" "system_a" "vendor_a" "boot_b" "system_b" "vendor_b" "persist" "modem_a")

for part in "${parts[@]}"; do
    echo "Dumping and hashing $part..."
    fastboot get_staged $part || fastboot flash $part /dev/null 2>/dev/null || true
    fastboot getvar $part >/dev/null 2>&1 || continue
    fastboot flash $part /dev/null 2>/dev/null || true
    fastboot dump $part > /tmp/$part.img 2>/dev/null || echo "Skipped $part"
    sha256sum /tmp/$part.img | tee hashes/${part}.sha256
done

You can later re-run it to verify no unexpected modifications:

sha256sum -c hashes/*.sha256

💾 A12.3 — Complete Backup Script

File: backup_all.sh

#!/bin/bash
# Creates a complete backup of essential partitions

mkdir -p backup

for part in boot_a boot_b system_a system_b vendor_a vendor_b persist modem_a; do
    echo "Backing up $part..."
    fastboot getvar $part 2>&1 | grep OKAY || true
    fastboot flash $part backup/${part}.img 2>/dev/null || fastboot get_staged $part > backup/${part}.img
done

echo "Backup complete: $(ls backup)"

You can restore using:

for part in boot_a system_a vendor_a; do fastboot flash $part backup/${part}.img; done

🧠 A12.4 — Slot Verification and Health Summary

File: device_status.sh

#!/bin/bash
# Summarizes slot, partition health, and current OS version

echo "=== DEVICE STATUS ==="
fastboot getvar product
fastboot getvar current-slot
fastboot getvar is-userspace
fastboot getvar version-baseband
fastboot getvar version-bootloader
fastboot getvar unlocked
fastboot getvar secure
echo "Partition list:"
fastboot getvar all | grep "partition"

Run this before and after flashing for full sanity checks.


🧭 Appendix A13: Simplified Architecture & Process Diagrams

These ASCII diagrams map your entire system build process, linking back to earlier sections for clarity.


🧱 A13.1 — Base Setup Overview (Sections 1–4)

┌───────────────────────────────────────────────┐
│ Linux Workstation (Section 2)                 │
│  ├─ adb / fastboot                            │
│  ├─ TWRP / Recovery Images                    │
│  ├─ LineageOS + GApps + Magisk packages       │
│                                               │
│ Flash Process (Section 3):                    │
│  adb reboot bootloader → fastboot flash recov │
│  adb sideload lineageos.zip                   │
│                                               │
│ Rooting (Section 4):                          │
│  adb sideload Magisk.zip → Reboot → Verify    │
└───────────────────────────────────────────────┘

🧩 A13.2 — Logical System Layout (Sections 5–7)

┌────────────────────────────────────────────────────────────┐
│  LineageOS (Base OS)                                       │
│   ├─ Magisk + Modules (AFWall+, LSPosed, Shizuku)          │
│   ├─ Work Profile (Google/MS Apps) → AFWall+ + VPN rules   │
│   ├─ Personal Profile (Proton, Ente, Discord+Vencord)      │
│   └─ PWA Instances (Firefox) for isolated extra accounts   │
│                                                            │
│  Isolation & Privacy Layers:                               │
│   AFWall+  → Section 6                                     │
│   Shelter/Island → Section 5                                │
│   Magisk DenyList → Section 7                              │
└────────────────────────────────────────────────────────────┘

🧠 A13.3 — Linux Toolchain Layer (Section 9)

┌──────────────────────────────────────────────┐
│  Termux (Android App)                        │
│   ├─ nmap, hashcat, aircrack-ng, git, python │
│   └─ proot-distro import Kali Nethunter      │
│                                              │
│  Optional: Nethunter RootFS → Full Kali Env  │
│  Network isolation via VPN split tunneling   │
└──────────────────────────────────────────────┘

🔁 A13.4 — Xperia / Jolla Dual-Path Diagram (Section 12)

┌──────────────────────────────────────────────┐
│ Xperia or Jolla Community Device             │
│  ├─ Bootloader Unlocked (Sony ODP)           │
│  ├─ Slot A: LineageOS (rooted, daily use)    │
│  ├─ Slot B: SailfishOS (Linux-native, test)  │
│  ├─ fastboot --set-active=a/b toggles OS     │
│  └─ Backup scripts maintain parity           │
│                                              │
│ Alt: Sailfish Host + Waydroid (Android-in-Lin)│
└──────────────────────────────────────────────┘

⚙️ A13.5 — Workflow Summary (Full Path Reference)

[Linux Host]
   ↓
(Section 2–3) → Flash LineageOS via adb/fastboot
   ↓
(Section 4–6) → Root with Magisk + configure privacy layers
   ↓
(Section 7–8) → Install apps & PWAs with sandboxed profiles
   ↓
(Section 9) → Deploy Termux/Kali for pentesting tools
   ↓
(Section 12) → Optional switch to Xperia path
   ↓
(Section A12–A13) → Automate slot switching & integrity checks

🧱 A13.6 — Data Flow Isolation Summary

                        ┌──────────────┐
                        │ VPN Tunnel 1 │ (Proton, Personal)
                        └──────────────┘
                              ↑
 [Personal Profile] ---- AFWall+ Rules ---- Firefox / Proton / Discord+Vencord
                              ↓
                        ┌──────────────┐
                        │ VPN Tunnel 2 │ (Work, Google/MS)
                        └──────────────┘
                              ↑
 [Work Profile] ------- AFWall+ Rules ---- Drive / Outlook / Teams
                              ↓
                  [Waydroid Container or Slot B OS]
                              ↓
                  Linux Tools / Sailfish Integration

📜 A13.7 — Reference Summary

Section Focus Summary
1–4 Base OS Install Flash LineageOS, Magisk root
5–6 Privacy & Isolation Shelter, AFWall+, VPN
7–8 App Ecosystem PWAs, Discord+Vencord, Proton/Ente
9 Pentesting Tools Termux + Nethunter setup
10–11 System Diagram & Summary Recap of build
12 Xperia/Jolla Alternative Hardware path, Sailfish integration
A1–A10 Dual-Boot Mechanics Partition, flashing, Waydroid
A11 Partition Reference Safe flashing tables
A12 Automation Scripts Slot, verification, backup
A13 Visual Overview System architecture diagrams

⚠️ Appendix A14 — Troubleshooting & Recovery Cases

This appendix covers repair, rescue, and diagnostic routines for your dual-system Android environment. All procedures assume you’re operating from a Linux host with ADB + Fastboot installed and that critical partitions are already backed up (see Appendix A12).


🧱 A14.1 — Bootloop / Soft-Brick Recovery

Symptoms

  • Device stuck at boot logo or endless animation
  • Can enter fastboot or recovery, but OS won’t start
  • Magisk module caused crash after flashing

Fix Path

  1. Force reboot into bootloader

    adb reboot bootloader
    
  2. Temporarily boot into recovery without flashing:

    fastboot boot twrp.img
    
  3. Mount and remove problem modules (if rooted):

    adb shell
    su
    mount /data
    cd /data/adb/modules
    mv <problem-module> /data/adb/modules_disabled/
    exit
    
  4. Wipe Dalvik / Cache in recovery → reboot.

  5. If the system slot itself is corrupted:

    fastboot flash system_a lineageos.zip
    fastboot reboot
    
  6. If you have a second slot intact, switch:

    fastboot --set-active=b
    fastboot reboot
    

🔐 A14.2 — Encryption / Decryption Failures

Symptoms

  • TWRP/OrangeFox prompts for password but cannot decrypt /data
  • Boot hangs after enabling File-Based Encryption (FBE)

Resolution

  1. Backup any recoverable data via adb pull /sdcard/.

  2. Format /data (not just wipe):

    adb reboot recovery
    → Wipe → Format Data → type “yes”
    
  3. Re-flash ROM and Magisk.

  4. Avoid incompatible kernels; verify your device’s fstab entries allow fileencryption=aes-256-xts.

  5. Optional: disable forced encryption (advanced users only):

    • Patch /vendor/etc/fstab.* via Magisk module (use FBE Disabler).

🧩 A14.3 — SafetyNet / Play Integrity Failures

If Google-dependent apps refuse to run after root:

Fix

  1. In Magisk, enable:

    • Zygisk
    • Enforce DenyList
  2. Add the following to DenyList:

    • com.google.android.gms
    • com.android.vending
    • All Google Pay / Banking apps
  3. Install Magisk module: Universal SafetyNet Fix v2.x.

  4. Clear Play Store + Play Services data:

    adb shell pm clear com.android.vending
    adb shell pm clear com.google.android.gms
    
  5. Reboot and check SafetyNet in Magisk’s “Check Integrity” section.


🌐 A14.4 — Network / VPN Routing Errors

Symptoms

  • AFWall+ blocks all traffic
  • VPN fails to tunnel specific profile

Recovery

  1. Reset AFWall+ rules:

    su
    iptables -F
    ip6tables -F
    

    Then reopen AFWall+ → Menu → Reset rules → Apply.

  2. Verify UID separation:

    adb shell dumpsys user
    

    Ensure Work/Profile UIDs are different.

  3. In Proton VPN:

    • Disable “Always-on”
    • Connect manually, verify logs
    • Re-enable “Always-on + Block Without VPN” afterwards.

💿 A14.5 — Dual-Boot Slot Conflicts (Xperia / Treble Devices)

Problem

Booting Sailfish (slot B) overwrites recovery or vendor image needed for Lineage (slot A).

Prevention / Repair

  1. Before flashing Sailfish:

    fastboot --set-active=b
    fastboot flash system_b sailfish.img
    
  2. Lock vendor partitions:

    fastboot erase vendor_b
    fastboot flash vendor_b vendor_sailfish.img
    fastboot --set-active=a
    
  3. If Sailfish overwrites shared partitions:

    • Boot to Linux host

    • Re-flash TWRP to both slots:

      fastboot flash recovery_a twrp.img
      fastboot flash recovery_b twrp.img
      

🧰 A14.6 — Waydroid / Container Boot Failure (in Sailfish Path)

Symptoms

  • waydroid status = “container stopped”
  • GUI app not opening under Sailfish OS

Fix

sudo systemctl enable --now waydroid-container
sudo waydroid init -s GAPPS
sudo waydroid session start

If device manager error appears:

sudo rm -rf /var/lib/waydroid/*
sudo waydroid init

Then re-import your Android image and relink user permissions.


🧠 A14.7 — Termux / Nethunter Package Corruption

If apt or pkg fails inside Termux:

rm -rf $PREFIX/var/lib/apt/lists/*
pkg update
pkg upgrade
pkg install termux-tools

To repair broken Nethunter environment:

proot-distro remove kali
proot-distro install kali

🪫 A14.8 — Battery / Thermal Management Issues After Root

  1. Disable thermal-blocking Magisk modules.

  2. Install EX Kernel Manager → set:

    • Scheduler = cfq or noop
    • Governor = interactive
  3. Re-calibrate battery:

    adb shell dumpsys battery reset
    
  4. Wipe batterystats.bin:

    adb shell rm /data/system/batterystats.bin
    
  5. Reboot and charge fully.


🧩 A14.9 — Missing Camera / Biometrics on LineageOS

  1. Confirm vendor image version matches your ROM base (check release notes).

  2. Flash original vendor:

    fastboot flash vendor vendor_stock.img
    
  3. Reboot → test camera and fingerprint.

  4. Optionally flash Open Camera or ANX Camera port.

  5. For biometrics, enable proprietary blobs via Magisk module miui-fp-service (device-specific).


🧯 A14.10 — Emergency Unbrick (EDL Mode / Huawei / Xiaomi)

If fastboot no longer works and device shows only a black screen:

  1. Enter EDL mode (hold Vol+ + Vol– while plugging in USB).

  2. On host:

    sudo apt install python3-serial
    sudo python3 edl.py info
    
  3. Flash raw firmware package (from manufacturer or XDA).

  4. Boot → relock bootloader if required.


🧾 A14.11 — General Verification Checklist

After each recovery, verify with:

adb shell getprop ro.build.display.id
adb shell getprop ro.boot.slot_suffix
adb shell getprop ro.boot.verifiedbootstate
adb shell getprop ro.product.device

Expected:

ro.boot.verifiedbootstate=orange   # (unlocked)
Slot suffix matches intended OS

Run integrity script from A12 to confirm SHA-256 matches.


🧩 A14.12 — Suggested Rescue Toolkit

Tool Purpose Notes
TWRP / OrangeFox Flashing, backup, restore Keep both slot copies
ADB & Fastboot Device control Use latest Android SDK platform-tools
Magisk Manager Root management Disable modules in Safe Mode if needed
AFWall+ & AdAway Firewall / DNS control Reset via Safe Mode if bootloop
Heimdall / Odin Samsung rescue flashing Non-fastboot devices
Xperia FlashTool Sony firmware repair For unbootable slots
EDL Tools Deep recovery (Xiaomi/Huawei) Requires USB debugging off

✅ A14.13 — Preventive Practices

  • Always back up /persist and /modem before any cross-flashing.
  • Use Appendix A12 scripts after every major change.
  • Keep one known-good bootable slot untouched.
  • Avoid OTA updates unless you re-sign with Magisk’s “Preserve Force Encryption / Preserve AVB”.
  • Document each flash and store logs in /mnt/data/device-logs/.

🧾 A14.14 — Closing Notes

With these repair strategies and verification routines, your LineageOS + Sailfish dual-environment can be maintained indefinitely, even through experimental Magisk, LSPosed, or kernel tweaks. Treat the process like managing two Linux distros on shared hardware: verify, snapshot, test, and roll back.


📝 Appendix A15 — Quick-Reference Recovery & Flashing Commands

Task / Problem Command / Action Notes / Section Reference
Reboot to bootloader adb reboot bootloader Sections 2, A14.1
Unlock bootloader fastboot oem unlock 0x<unlock_code> Section 2, 12
Flash recovery fastboot flash recovery twrp.img Sections 3, 12
Boot recovery temporarily fastboot boot twrp.img Section A14.1
Sideload ROM adb sideload lineageos.zip Sections 3, 12
Flash GApps adb sideload gapps.zip Section 3
Flash Magisk adb sideload Magisk.zip Section 4
Toggle dual-slot OS fastboot --set-active=a/b Section 12, A12.1
Check current slot fastboot getvar current-slot Sections 12, A12.4
Backup system partition fastboot flash <part> backup/<part>.img Section A12.3
Restore partition from backup fastboot flash <part> backup/<part>.img Section A12.3
List all partitions adb shell ls /dev/block/bootdevice/by-name/ Sections A11, A13
Reset AFWall+ rules su → iptables -F; ip6tables -F Section A14.4
Verify SHA-256 integrity sha256sum -c hashes/*.sha256 Section A12.2
Reboot recovery from fastboot fastboot reboot recovery Sections 3, A14.1
Check device properties adb shell getprop ro.build.display.id
adb shell getprop ro.boot.slot_suffix
adb shell getprop ro.boot.verifiedbootstate
Section A14.11
Format /data (fix decryption) Recovery → Wipe → Format Data Section A14.2
Re-flash system (slot-specific) fastboot flash system_a lineageos.zip Sections 3, A14.1, 12
Backup persist/modem fastboot flash <part> backup/<part>.img Sections A12.3, A14.14
Reset Termux/Nethunter environment rm -rf $PREFIX/var/lib/apt/lists/*
proot-distro remove kali
proot-distro install kali
Section A14.9
Start Waydroid container sudo systemctl start waydroid-container
waydroid session start
Section A14.7
Check VPN / Network status AFWall+ logs
adb shell dumpsys user
Section A14.4
Reboot device fastboot reboot or adb reboot General

💡 Usage Tips

  1. Keep this table open on your Linux workstation during flashing or experimentation.
  2. Always verify active slot before flashing any system image.
  3. Use backup and hash verification commands after every major change to prevent accidental bricking.
  4. Combine these with the automation scripts in Appendix A12 for semi-automated maintenance.