[Root][4.4.2 ND7]GhettoRoot (Towelroot port) v0.3.2 - Verizon Samsung Galaxy Note II

GhettoRoot (Towelroot port) v0.3.0.1, v0.3.2 Testing (looking for new owner)
Code:
*** Disclaimer
This project is licensed under the GPLv3. Bundled third-party components
have different licenses, but these components are bundled or downloaded
as separate executables; all appropriate LICENSE files are included, along
with links to source code.
THIS UTILITY MAKES USE OF A KERNEL EXPLOIT TO GAIN ROOT PRIVILEGES
AND MAKE MODIFICATIONS TO YOUR DEVICE'S FILESYSTEM. IT WILL
PROBABLY WILL VOID YOUR WARRANTY. IF YOU DO NOT FOLLOW THE
INSTRUCTIONS, YOU COULD END UP WITH A BRICK. EVEN IF YOU DO
FOLLOW THE INSTRUCTIONS, YOU MIGHT END UP WITH A BRICK.
ROOTING IS A POTENTIALLY DANGEROUS PROCESS AND, WHILE I WILL TRY
TO HELP IF YOU HAVE TROUBLE, I CANNOT ACCEPT RESPONSIBILITY
FOR RANDOM MISFORTUNE, COSMIC RAYS, ETC.
Help Wanted
My activity with this project will be diminishing. As far as I know, everything as of now "just works" with the SCH-I605, and that's all I really wanted to accomplish from the start. I'm hoping someone will take it over -- ideally someone who'd be willing to look into fixing the code to support other devices. It's open-source, so you can start looking at it now and see if you're interested. Compiling is simple... Just install the NDK and use ndk-build, or 'make' in Linux.
If you'd like to take over the development, and you've worked on projects like this before, I'd greatly appreciate it; perhaps we can get a mod to transfer this thread to you, or you're free to start a new one. After a certain point, I'll stop monitoring threads and messages, so you're free to go ahead and take charge without waiting to hear from me, if you'd like.
Post elsewhere, if you'd like, to let people know that this code is available and might be adjustable for other devices. It really shouldn't be difficult for someone with a background with this stuff.
Problematic areas are likely the iov code (search "Not sure if this is entirely correct") and also the limit_offset stuff (search "ph->limit_offset != 0"), but I have no way of knowing for sure if there's anything wrong with limit_offset since I don't have an applicable Samsung device. There are scattered references to the sources I used to figure out some of this in the README and in ghettoroot.c itself.
That's all, folks. Thanks.
Introduction
This is an automatic root method for your Note 2 (or, potentially, other device) based on code for the CVE-2014-3153 exploit.Unlike towelroot, it is a tethered root in that it requires you to connect your device to a computer to perform the root. However, it only requires a computer the one time; root sticks.
This code appears to have been reverse-engineered from towelroot itself (but not the latest version), so Geohot gets the credit for this one. This is more like a bugfix which only works (for sure) with the Verizon Galaxy Note II so far. The changes from the towelroot-equivalent exploit code are incredibly minimal. Only a few lines of code need really be changed to get it working, but devices incompatible with towelroot are becoming ghetto, so there wasn't a lot of motivation for the problems to be investigated.
GhettoRoot attempts to walk you through the prerequisites for the rooting process and give you hints if there are problems; it does the dirty work itself.
Click to expand...
Click to collapse
Installation instructions
Please see the LICENSE file for details on copying and usage (GPLv3).
This software will attempt to root your device and might void its warranty.
Please BACK UP ANYTHING IMPORTANT before continuing.
Note: By default, v0.3.0.1 attempts to disable Knox and OTA update packages.
If you'd rather this not happen, scroll to CONFIGURATION.
Install USB drivers for your device if needed, for Windows.
Koush's drivers are a good bet. 'Download Windows Installer', and run:
https://github.com/koush/UniversalAdbDriver
Download the busybox-arm4vl binary. The installer will help you with this.
You can get it manually from http://www.busybox.net, specifically from
http://www.busybox.net/downloads/binaries/latest
Place the binary in the files/ folder. It will be automatically renamed
to 'busybox'.
Enable USB debugging. If necessary, go to 'About device' under Settings and tap
the Build number several times to enable the Developer options. Go back, and
go to Developer options, and enable USB debugging there.
Plug in your device to your computer.
Unlock your device's lockscreen if it is locked.
Manually choose a USB mode from the notification, or wait for the Installer mode
phase of USB to end, which takes about 30 seconds. If your device does not have
an Installer mode, skip this. If you're not sure, just wait the 30 seconds.
If/when a popup appears asking for authorization for your PC, allow it.
If a popup does not appear and has never appeared before, or you clicked Cancel,
or you're just having a lot of trouble, go to Developer option and toggle USB
debugging off and on again. Then, try again. You may need to disconnect and re-
connect your device or tap Revoke USB authorization if nothing seems to help.
On Linux or OS X, enter a terminal at the folder you extracted the zip file to,
and type chmod +x INSTALL.sh.
To run, execute INSTALL.cmd on Windows.
On Linux or OS X, type the following in the same terminal: ./INSTALL.sh
Follow the on-screen instructions.
Click to expand...
Click to collapse
Configuration
v0.3.2 config.txt details:
Code:
Open up config.txt, and customize as follows, adding or removing arguments
as you see fit. It should always start with ./root.sh
*** ENSURE THE CONTENTS OF config.txt IS A *SINGLE LINE*.
*** COMMENTS WITHIN config.txt ARE NOT PERMITTED.
Default: ./root.sh --root --deknox --deota --desurveillance
Former default: ./root.sh --root --disable-knox --disable-ota
Usage: ./root.sh [OPTION] [COMMAND]
With no arguments, --root is implied.
Main options
--root, --supersu Install SuperSU (permaroot)
--deknox Remove Knox (recommended)
--deota Remove OTA packages (recommended)
--debloat Remove Bloat (recommended)
--desurveillance Remove some surveillance (recommended)
--disable-ota Disable OTA update-related packages
--disable-knox Disable Knox packages
--really-remove Actually remove things instead of
putting them in $jaildir
--undo Try to undo the specified option.
If you had used --really-remove then
it won't work for deknox, debloat, deota.
Anti-convenience options
--no-mount-rw Don't mount / and /system read-write
--no-sepermissive Don't set SEAndroid to permissive
--no-chmod-scripts Don't chmod 0755 all scripts in
$TMPDIR
COMMAND: Command to be run after other options.
Arguments may follow.
If unspecified, will look for and run custom.sh.
ex. ./root.sh --root
./root.sh --root --undo
./root.sh --root --deknox --deota --debloat
./root.sh cp /sdcard/build.prop /system/build.prop
[/HIDE]
Thanks To/Credits
Code:
geohot for developing [URL="http://forum.xda-developers.com/showthread.php?t=2783157"][U]towelroot[/U][/URL], on which
this code is DIRECTLY based! Reverse-engineered/decompiled, but not by me.
I don't think anyone had a licensing claim on towelroot or this code so I made it GPLv3.
fi01 for his shared [URL="https://gist.github.com/fi01/a838dea63323c7c003cd"][U]exploit code[/U][/URL] on github:
tinyhack.com for the [URL="http://tinyhack.com/2014/07/07/exploiting-the-futex-bug-and-uncovering-towelroot/"][U]helpful post on the Futex bug[/U][/URL]:
chainfire, for [URL="http://forum.xda-developers.com/showthread.php?t=1538053"][U]SuperSU[/U][/URL]!
THANK YOU for the lenient distribution policy.
NetworkingPro at xda-developers for the assistance to all. :)
Other folks at xda-developers for testing and offering support.
Google, of course, and the Android Open Source Project.
Changelog & Download
A note on v0.3.2 Testing:
Code:
WARNING: ESPECIALLY with this version, PLEASE make sure you have backups of
your important applications and their data!
Alternatively, you might be safer changing config.txt to the
old value as listed below.
Code:
This version is called 'Testing' because I haven't really had time to test it
fully, and there's a bunch of new stuff, namely the de* (*-removal) scripts.
I DON'T KNOW HOW WELL THE DE* CODE WORKS. You may want to give me some time
to see how my device holds up before testing yourself, or check out
files/root.sh to see what the new stuff does, but I do need other people to
test as well, so I've changed the config.txt to include the new features,
sans --debloat.
If you DO NOT want to try the new features, change config.txt to the following:
./root.sh --root --disable-knox --disable-ota
However, even the --disable-knox and --disable-ota code has changed.
Your mileage may vary!
Search files/root.sh for ### DEBLOAT, ### DEKNOX, ### DEOTA, ## DESURVEILLANCE,
etc. to see exactly what they do.
Code:
Current changelog: [U][B][URL="http://forum.xda-developers.com/devdb/project/dl/?id=8457"]v0.3.2 [I]Testing[/I][/URL][/B][/U] (2014/09/08)
[fixed?] drowsy attempt to fix a silly bug with default modstring
[new] new default config.txt: --deknox, --deota, --desurveillance
[new] --deknox, --deota, --debloat, --desurveillance, --really-remove,
--undo features added. See README.txt or search files/root.sh
for ### DEBLOAT, ### DEKNOX, ### DEOTA, ## DESURVEILLANCE,
etc. to see exactly what they do.
[change] starting to change verbage from 'phone' to 'device'
[note] v0.3.1 would have been too confusing, so straight to v0.3.2.
[U][B][URL="http://forum.xda-developers.com/devdb/project/dl/?id=8439"]Download v0.3.0.1[/URL][/B][/U] (2014/09/07)
[fixed] Issue with find.exe when other find executables are in PATH.
[URL="http://forum.xda-developers.com/devdb/project/dl/?id=8438"]v0.3.0 (2014/09/07)[/URL]
[new] License: this project is licensed under GPLv3.
[new] Added ADB binaries for Linux and Mac OS X.
[note] This means we have experimental & untested support for Intel Macs
[changed] Restructuring of post-root procedures:
No more hard-coded commands for installing SuperSU, etc.
These things are present in files/root.sh instead, and
may be freely edited.
[changed] Command-line parameters have DRASTICALLY changed.
See the README.txt.
[new] Added modstrings.txt, config.txt
[changed] Busybox no longer bundled due to licensing concerns;
curl added for downloading busybox, instead.
Older changelogs:
Code:
v0.2.2 (2014/09/04)
Fixed INSTALL.cmd hanging when launching ADB, or not running
properly as an administrator.
Further improved error handling, with more detailed steps for
troubleshooting, and retries.
User acknowledgment now required for certain tasks with (Y/N).
Fixed date on previous update being in the future... Hmm...
v0.2.1 (2014/09/03)
** pulled, did not fix adb hang issue after all **
v0.2 (2014/09/03)
Code cleaned up a bit, but still gives verbose debug messages
since they might be important. Can disable those with --brief.
Some error handling in the install script.
Everything is orchestrated from a single batch file ("one-click",
though multiple scripts are still used internally).
Should work properly with Windows and Linux, and come
bundled with ADB for Windows. Thanks, NetworkingPro!
v0.1 (2014/08/31)
Initial release.
LINK TO FORMER THREAD HERE
Apologies in advance for any kind of faux pas I've made or rule I've broken. There always seems to be something...
Code:
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
* GhettoRoot is free software: you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation, either version 3 of the License, or *
* (at your option) any later version. *
* *
* GhettoRoot is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with GhettoRoot. If not, see <http://www.gnu.org/licenses/>. *
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *

hmmm
If I hadn't just killed my phone (perma red angry text of death) I would definitely help test. Of course you have me to thank as well. Why? Because I knew as soon as I broke my phone, or upgraded someone would come out with a root fix. So you're welcome. However there is still a good chance that the new "probably very used" replacement phone I get from Verizon will be 4.4.2 already so then I will try this out. Unless this is some sort of very cruel trick played on those of us that can't afford to upgrade our phones every other month, in which case shame on you, and I will still try it until I am blue in the face. And crying.

J_3dgar_H00v3r said:
If I hadn't just killed my phone (perma red angry text of death) I would definitely help test. Of course you have me to thank as well. Why? Because I knew as soon as I broke my phone, or upgraded someone would come out with a root fix. So you're welcome. However there is still a good chance that the new "probably very used" replacement phone I get from Verizon will be 4.4.2 already so then I will try this out. Unless this is some sort of very cruel trick played on those of us that can't afford to upgrade our phones every other month, in which case shame on you, and I will still try it until I am blue in the face. And crying.
Click to expand...
Click to collapse
Nope, not a trick! My username looks a bit dubious even to me, but it was randomly generated by KeePass.

I am getting, "error: device unauthorized. Please check the confirmation dialog on your device." I am not getting anything on my phone. Any thoughts?

Im testing this now. Will let you know in a few mins. So far, so good.
Edit: This worked like a champ for me. Root achieved. For anyone wanting to do this, please follow these steps:
Run clean.cmd
Run prepare.cmd
Run root.cmd
Do these in this order. I went ahead and added a pause to each batch (Except root.bat that already had one) to ensure everything was kicking off as expected. Sorry if this was outlined in the OP, but Im sort of a "D personality" and wont read a lot of fluff.
Thanks!

Seems to be running good here to ... some more fiddling and see how things go but I now have root on 4.4.2. Thanks
Update: no problems also Knox has NOT been tripped and no other issues.

Worked for me!
I tried this, and it worked like a charm. So far, no issues.
Thank you!!!

=D
i dont think i've been this excited since safestrap was in the works for the N2!!! cant wait to try this when i get home!!! thanks dev

I still don't have root. Not sure what went wrong. My phone restarted like it was supposed to but not root.

NetworkingPro said:
Im testing this now. Will let you know in a few mins. So far, so good.
Edit: This worked like a champ for me. Root achieved. For anyone wanting to do this, please follow these steps:
Run clean.cmd
Run prepare.cmd
Run root.cmd
Do these in this order. I went ahead and added a pause to each batch (Except root.bat that already had one) to ensure everything was kicking off as expected. Sorry if this was outlined in the OP, but Im sort of a "D personality" and wont read a lot of fluff.
Thanks!
Click to expand...
Click to collapse
Does clean.cmd wipe all data? I only ran root.cmd and the phone rebooted like it was supposed to, but Titanium Backup doesn't register my device as rooted.

Tkun said:
Does clean.cmd wipe all data? I only ran root.cmd and the phone rebooted like it was supposed to, but Titanium Backup doesn't register my device as rooted.
Click to expand...
Click to collapse
It just cleans up old root files that might have been part of previous root methods, or failed attempts.

NetworkingPro said:
It just cleans up old root files that might have been part of previous root methods, or failed attempts.
Click to expand...
Click to collapse
Thanks! Using your steps it worked and my phone is rooted!
Also, thanks OP for providing this solution! I was worried us 4.4.2 users would never again have root. I can finally backup and restore my apps again using Titanium Backup.

Tkun said:
Thanks! Using your steps it worked and my phone is rooted!
Also, thanks OP for providing this solution! I was worried us 4.4.2 users would never again have root. I can finally backup and restore my apps again using Titanium Backup.
Click to expand...
Click to collapse
Glad I could help, I went ahead and read through the source code before I did it, so had a pretty good idea of what it was doing.
---------- Post added at 10:38 PM ---------- Previous post was at 10:36 PM ----------
25yvdgpo06 said:
tl;dr: This is a modified version of [basically towelroot] to work with the Verizon Galaxy Note II (SCH-I605) VRUFND7 firmware.
Currently, a PC with the Prerequisites is required. If someone wants to package this into an APK, that's great and it may remove the PC requirement.
I'm too new to be allowed to post in the developer forums (which is probably for the best), and I don't consider myself much of a developer anyway, but with a couple sleepless nights, a little bit of determination, and a lot of sugar cereal (but not enough milk!!!!), I've modded some code based on Towelroot to get the CVE-2014-3153 exploit to work with our phone and its 3.0.31 kernel. Who knows - it might work with other phones, too, but this is the only one I have right now.
WARNINGS
YOUR MILEAGE MAY VARY. THIS WILL PROBABLY VOID YOUR WARRANTY. PLEASE BACK UP IMPORTANT FILES FIRST, JUST IN CASE AND AS A GOOD PRACTICE.
Your phone will reboot after rooting which could cause data loss if any apps are in the middle of writing data, so please close open apps and wait a few moments before rooting! If your phone is just starting up, give it some time to initialize before rooting. These recommendations should be followed prior to almost any automated reboot of your phone, but particularly when rooting.
This does not flash anything, so as far as I'm aware, it will not trip KNOX but I really don't know! It DOES try to disable KNOX, which might trip it. I don't know how any of that works.
There *shouldn't* be any problems with this, but if there are, keep in mind that you made the choice to try it, knowing it's relatively untested. As of first posting of the binary, I am the only person who has tested this.
PREREQUISITES
You will need access to a computer with the following things:
Android SDK
ADB in your PATH (in platform-tools at your Android SDK install path)
Your phone's USB drivers
USB debugging enabled
INSTRUCTIONS
Connect your phone to your computer.
Close any active applications on your phone so you don't lose data when your phone reboots. If your phone just started, give it time to initialize.
Once active apps are closed, wait 10-20 seconds or so for the phone to be done doing stuff.
With that out of the way, extract the zip file if you haven't already.
The procedure will execute immediately when running the scripts, so this is your last chance to back out! Do not proceed if you don't feel ready!
Run root.cmd on Windows, or root.sh on Linux and maybe OS X.
Allow your phone to reboot after the process, and enjoy root. Let me know if you got errors or it didn't work.
This has not happened to me (or anyone else to my knowledge, since I just released this), but if it goes into a loop trying to root and keeps failing, go ahead and CTRL-C to end it, and then close the command window. If worst comes to worst, shut off your phone or pull the battery.
QUESTIONS
Q. What's the difference between this and Towelroot, then?
A. There are a few modifications to the reverse-engineered source code of Towelroot, or at least I assume that's what the code is, since Towelroot isn't open source, as far as I know. There is a github link to that source at the top of ghettoroot.c, included in the zip file. You can do a diff comparing ghettoroot.c to the github code to see exactly what I changed.
Q. And this will get me rooted, even if I have a locked bootloader?
A. Yeah. It won't unlock your bootloader, though. If you find me some info on how the previous bootloader unlocks were found and/or what they involved, I might try to look into it...
Q. You mentioned command-line options. I tried out -? or --help and saw them but it's nearly impossible to read.
A. The help is a mess, but this usage message -- to be included in a future version -- should be more...useful.
The root.sh and root.cmd scripts should pass your arguments along to the ghettoroot binary, so where you see ghettoroot in the usage message, replace with ./root.sh (be sure to chmod +x it) or root.cmd.
Code:
Usage: ghettoroot METHOD ALIGN LIMIT_OFFSET HIT_IOV EXCLUDE_FEATURE
USERCMD USERARGV
All parameters are optional. The first non-number and following arguments
will be interpreted as the user command and user arguments.
ex. ghettoroot <-- runs with defaults, attempting to detect some settings
ghettoroot 0 1 0 4 0 <-- standard, default root for most phones.
ghettoroot mkdir /system/happyface <-- does everything, then that...
ghettoroot 0 1 0 4 7 cp /sdcard/build.prop /system/build.prop
^ copies a modified build.prop but does not permaroot, etc.
Formatting key: [Default value]PARAMETER NAME: value range: description
[0]METHOD: 0-sendmmsg, 1-recvmmsg, 2-sendmsg, 3-recvmsg:
This typically does not need to be changed.
[1]ALIGN: 0/1: attack all 8 IOVs hit with MAGIC
This behavior may/may not match up with original ALIGN behavior.
Currently, enabling this causes HIT_IOV to go unused.
[0]LIMIT_OFFSET: 0-8192: offset of addr_limit in thread_info, multiple of 4
If desperate, download manufacturer's kernel sources to check headers.
Rarely necessary, but 7380 is needed for newer Samsung phone models.
[4]HIT_IOV: 0-7: offset to rt_waiter in vulnerable futex_wait_requeue_pi.
see vulnerable futex_wait_requeue_pi function for your kernel if needed.
[0]EXCLUDE_FEATURE: 0-31: all features are enabled by default.
to disable, add up the numbers for any/all of the following features:
1 Install SuperSU
2 Disable Knox
4 Disable OTA Updates
8 SEAndroid Permissive (temporary)
16 Mount /, /system read-write (temporary)
Example values for EXCLUDE_FEATURE:
31 temp roots solely to run a user command, immediately after root.
Reboot is still required.
6 does *not* disable Knox or OTA, but installs SuperSU.
7 does *not* disable Knox or OTA updates, or install SuperSU.
Still remounts /, /system as rewrite and turns off SEAndroid.
Meant to be used with a user command, or else it is pointless.
USERCMD: Command to be run after all other enabled featuers, if any.
USERARGV: All further arguments are passed along to the user command.
I don't know how well any of those arguments are working. You shouldn't need any of them for this phone.
Q. I think ToiletRoot would have been a better name.
A. Hmm... Me too. Oh well.
CREDITS
GeoHot, developer of Towelroot, on which this is based, and without whom it would be impossible.
Chainfire, developer of SuperSU, which is bundled.
Somebody, developer/compiler of busybox, which is bundled. To be honest I don't know where it came from. It was lying around on my PC. I know, I know... just let me know if I really need to make my life revolve around fixing political issues like this and I will try.
fi01, person on Github sharing code publicly
Apologies in advance for some kind of faux pas I've made or rule I've broken. There always seems to be something(s).
Click to expand...
Click to collapse
Where did you pick this up at? I want to go ahead and rewrite it to be more efficient later tonight, but I kind of need to know where it came from?
---------- Post added at 10:39 PM ---------- Previous post was at 10:38 PM ----------
Oh well, screw it... I'll go ahead and clean it up later.

NetworkingPro said:
Glad I could help, I went ahead and read through the source code before I did it, so had a pretty good idea of what it was doing.
---------- Post added at 10:38 PM ---------- Previous post was at 10:36 PM ----------
Where did you pick this up at? I want to go ahead and rewrite it to be more efficient later tonight, but I kind of need to know where it came from?
---------- Post added at 10:39 PM ---------- Previous post was at 10:38 PM ----------
Oh well, screw it... I'll go ahead and clean it up later.
Click to expand...
Click to collapse
It is the first link at the top of ghettoroot.c, fi01's cube-towel.c page. (Every page linked in ghettoroot.c was helpful.)
I am planning to clean it up a bit myself this evening, but if someone wants to repackage the entire thing and re-post to a new thread, go for it! Or you can wait until I clean things up a little bit and then do it... Or just not. Whatever you want to do. I'm not very concerned about who gets credit for what, though a mention of my randomly-generated name might be nice.
Thanks to those who've helped others so far, and those who've shared success/failure.
EDIT: Wanted to point out that there were very few changes from fi01's original cube-towel.c code that were necessary to get the exploit itself to work. The rest is fluffy stuff, in addition to execution of useful commands once root was gained rather than being a proof-of-concept alone.
Here is *exactly* what was changed in the exploit code. Very minimal, you will see.
Setting of processor affinity added as recommended at tinyhack.com's "Exploiting the Futex Bug and uncovering Towelroot" post, and called in main():
Code:
void setaffinity()
{
pid_t pid = syscall(__NR_getpid);
int mask=1;
int syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallres)
{
printf("Error in the syscall setaffinity: mask=%d=0x%x err=%d=0x%x", mask, mask, errno, errno);
sleep(2);
printf("This could be bad, but what the heck... We'll try continuing anyway.");
sleep(2);
}
}
Change to IOV code, also using tinyhack.com recommendations:
From:
Code:
if (ph->l2 == 0) {
for (i = 0; i < 8; i++) {
msg_iov[i].iov_base = (void *)MAGIC;
msg_iov[i].iov_len = MAGIC_ALT;
}
}
else {
for (i = 0; i < 8; i++) {
msg_iov[i].iov_base = (void *)MAGIC;
msg_iov[i].iov_len = 0x10;
}
}
To:
Code:
// tbh i'm not really sure how this is supposed to look or work
// but it is working with note 2 as is with modstring 0 1 0 4
// and that is all i care about right now.
// see http://tinyhack.com/2014/07/07/exploiting-the-futex-bug-and-uncovering-towelroot/
for (i = 0; i < 8; i++) {
iov[i].iov_base = (void *)MAGIC;
if (ph->align == 0) {
if (i==ph->hit_iov) {
iov[i].iov_len = MAGIC_ALT;
}
else {
iov[i].iov_len = 0x10;
}
}
else {
iov[i].iov_len = MAGIC_ALT;
}
}
When searching through task structures for a credential to overwrite (to get us root), verify that the credential is in kernel address space, the same way the other pointers are verified. Otherwise, we're not in the right place in memory yet...
From:
Code:
if (task->cpu_timers[0].next == task->cpu_timers[0].prev && (unsigned long)task->cpu_timers[0].next > KERNEL_START
&& task->cpu_timers[1].next == task->cpu_timers[1].prev && (unsigned long)task->cpu_timers[1].next > KERNEL_START
&& task->cpu_timers[2].next == task->cpu_timers[2].prev && (unsigned long)task->cpu_timers[2].next > KERNEL_START
&& task->real_cred == task->cred) {
To:
Code:
if (task->cpu_timers[0].next == task->cpu_timers[0].prev && (unsigned long)task->cpu_timers[0].next > KERNEL_START
&& task->cpu_timers[1].next == task->cpu_timers[1].prev && (unsigned long)task->cpu_timers[1].next > KERNEL_START
&& task->cpu_timers[2].next == task->cpu_timers[2].prev && (unsigned long)task->cpu_timers[2].next > KERNEL_START
&& task->real_cred == task->cred && (unsigned long)task->cred > KERNEL_START) {
That's all that needed to be changed, keeping in mind none of us have seen the actual towelroot source code so some of these things may not even be necessary or may already be present there, leaving it up in the air why towelroot doesn't work for us. I would guess the IOVs were the issue, somehow, but at least with this code, the credential needed to be checked to be in kernel space as well. Did not test without setaffinity.

Droc1983 said:
I still don't have root. Not sure what went wrong. My phone restarted like it was supposed to but not root.
Click to expand...
Click to collapse
I had to Uninstall towel root apk. Now I have root access. Thank you.

My apologies...
alkitchen said:
I am getting, "error: device unauthorized. Please check the confirmation dialog on your device." I am not getting anything on my phone. Any thoughts?
Click to expand...
Click to collapse
My apologies, disregard my post... I ran it again this evening and it WORKED!! Thanks so much.
Now to try Safestrap...

25yvdgpo06 said:
It is the first link at the top of ghettoroot.c, fi01's cube-towel.c page. (Every page linked in ghettoroot.c was helpful.)
I am planning to clean it up a bit myself this evening, but if someone wants to repackage the entire thing and re-post to a new thread, go for it! Or you can wait until I clean things up a little bit and then do it... Or just not. Whatever you want to do. I'm not very concerned about who gets credit for what, though a mention of my randomly-generated name might be nice.
Thanks to those who've helped others so far, and those who've shared success/failure.
EDIT: Wanted to point out that there were very few changes from fi01's original cube-towel.c code that were necessary to get the exploit itself to work. The rest is fluffy stuff, in addition to execution of useful commands once root was gained rather than being a proof-of-concept alone.
Here is *exactly* what was changed in the exploit code. Very minimal, you will see.
Setting of processor affinity added as recommended at tinyhack.com's "Exploiting the Futex Bug and uncovering Towelroot" post, and called in main():
Code:
void setaffinity()
{
pid_t pid = syscall(__NR_getpid);
int mask=1;
int syscallres = syscall(__NR_sched_setaffinity, pid, sizeof(mask), &mask);
if (syscallres)
{
printf("Error in the syscall setaffinity: mask=%d=0x%x err=%d=0x%x", mask, mask, errno, errno);
sleep(2);
printf("This could be bad, but what the heck... We'll try continuing anyway.");
sleep(2);
}
}
Change to IOV code, also using tinyhack.com recommendations:
From:
Code:
if (ph->l2 == 0) {
for (i = 0; i < 8; i++) {
msg_iov[i].iov_base = (void *)MAGIC;
msg_iov[i].iov_len = MAGIC_ALT;
}
}
else {
for (i = 0; i < 8; i++) {
msg_iov[i].iov_base = (void *)MAGIC;
msg_iov[i].iov_len = 0x10;
}
}
To:
Code:
// tbh i'm not really sure how this is supposed to look or work
// but it is working with note 2 as is with modstring 0 1 0 4
// and that is all i care about right now.
// see http://tinyhack.com/2014/07/07/exploiting-the-futex-bug-and-uncovering-towelroot/
for (i = 0; i < 8; i++) {
iov[i].iov_base = (void *)MAGIC;
if (ph->align == 0) {
if (i==ph->hit_iov) {
iov[i].iov_len = MAGIC_ALT;
}
else {
iov[i].iov_len = 0x10;
}
}
else {
iov[i].iov_len = MAGIC_ALT;
}
}
When searching through task structures for a credential to overwrite (to get us root), verify that the credential is in kernel address space, the same way the other pointers are verified. Otherwise, we're not in the right place in memory yet...
From:
Code:
if (task->cpu_timers[0].next == task->cpu_timers[0].prev && (unsigned long)task->cpu_timers[0].next > KERNEL_START
&& task->cpu_timers[1].next == task->cpu_timers[1].prev && (unsigned long)task->cpu_timers[1].next > KERNEL_START
&& task->cpu_timers[2].next == task->cpu_timers[2].prev && (unsigned long)task->cpu_timers[2].next > KERNEL_START
&& task->real_cred == task->cred) {
To:
Code:
if (task->cpu_timers[0].next == task->cpu_timers[0].prev && (unsigned long)task->cpu_timers[0].next > KERNEL_START
&& task->cpu_timers[1].next == task->cpu_timers[1].prev && (unsigned long)task->cpu_timers[1].next > KERNEL_START
&& task->cpu_timers[2].next == task->cpu_timers[2].prev && (unsigned long)task->cpu_timers[2].next > KERNEL_START
&& task->real_cred == task->cred && (unsigned long)task->cred > KERNEL_START) {
That's all that needed to be changed, keeping in mind none of us have seen the actual towelroot source code so some of these things may not even be necessary or may already be present there, leaving it up in the air why towelroot doesn't work for us. I would guess the IOVs were the issue, somehow, but at least with this code, the credential needed to be checked to be in kernel space as well. Did not test without setaffinity.
Click to expand...
Click to collapse
I'll wait til you clean it up and then repackage. I don't care about credit either. I'll pm you my gtalk shortly.

I would like to try this. I have downloaded the SDK, however I do not have any idea what the ADB step means. Basically, I have no idea what I am doing and would appreciate a little help as far as making sure I have everything that needs downloaded. Thanks.
edit: Got it figured out!

Having trouble with safestrap. I installed apk and ran install recovery and grant root access but it says recovery not installed in the app.

Not working...
I'm seeing:
Unable to chmod /data/local/tmp/busybox: no such file or directory
sh: /data/local/tmp/busybox: not found
Could not find/unzip SuperSU: Success
Please place an UPDATE-SU-*.zip file in the mail folder before running the install script
Click to expand...
Click to collapse
Any help would be appreciated.

Related

[Q] Writing to and reading from /data/local?

I am creating a little app that will let a user read what's in a certain textfile in /data/local, edit it, and then save it. I have gotten everything to work by using some tutorials here and there, but there's still something not working.
Root access has been achieved, and writing/reading the file is done too, but when pressing the "Write" button, I get a toast saying "open failed: EACCES (Permission denied)". Google unfortunately didn't help me much on this one. Also, I am using the WRITE_EXTERNAL_STORAGE permission.
Code:
Code:
package bas.sie.hai;
import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.actionbarsherlock.app.SherlockActivity;
public class DataLocalActivity extends SherlockActivity {
EditText txtData;
Button btnReadSDFile;
Button btnWriteSDFile;
Button btnReadSkipFile;
Button btnWriteSkipFile;
Button btnClearScreen;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Process p;
try {
// Preform su to get root privledges
p = Runtime.getRuntime().exec("su");
// Attempt to write a file to a root-only
DataOutputStream os = new DataOutputStream(p.getOutputStream());
os.writeBytes("echo \"Do I have root?\" >/system/sd/temporary.txt\n");
// Close the terminal
os.writeBytes("exit\n");
os.flush();
try {
p.waitFor();
if (p.exitValue() != 255) {
// TODO Code to run on success
Toast.makeText(this, "root", Toast.LENGTH_LONG);
}
else {
// TODO Code to run on unsuccessful
Toast.makeText(this, "No root", Toast.LENGTH_LONG);
}
} catch (InterruptedException e) {
// TODO Code to run in interrupted exception
Toast.makeText(this, "No root", Toast.LENGTH_LONG);
}
} catch (IOException e) {
// TODO Code to run in input/output exception
Toast.makeText(this, "NO root", Toast.LENGTH_LONG);
}
if(!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())){
Toast.makeText(this, "External SD card not mounted", Toast.LENGTH_LONG).show();
}
txtData = (EditText) findViewById(R.id.txtData);
btnReadSDFile = (Button) findViewById(R.id.btnReadSDFile);
btnReadSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/move_cache.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading from SD: 'move_cache.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnWriteSDFile = (Button) findViewById(R.id.btnWriteSDFile);
btnWriteSDFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/move_cache.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing to SD: 'move_cache.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnReadSkipFile = (Button) findViewById(R.id.btnReadSkipFile);
btnReadSkipFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/skip_apps.txt");
FileInputStream fIn = new FileInputStream(myFile);
BufferedReader myReader = new BufferedReader(
new InputStreamReader(fIn));
String aDataRow = "";
String aBuffer = "";
while ((aDataRow = myReader.readLine()) != null) {
aBuffer += aDataRow + "\n";
}
txtData.setText(aBuffer);
myReader.close();
Toast.makeText(getBaseContext(),
"Done reading from SD: 'skip_apps.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnWriteSkipFile = (Button) findViewById(R.id.btnWriteSkipFile);
btnWriteSkipFile.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// write on SD card file data in the text box
try {
File myFile = new File("/data/local/skip_apps.txt");
myFile.createNewFile();
FileOutputStream fOut = new FileOutputStream(myFile);
OutputStreamWriter myOutWriter = new OutputStreamWriter(
fOut);
myOutWriter.append(txtData.getText());
myOutWriter.close();
fOut.close();
Toast.makeText(getBaseContext(),
"Done writing to SD: 'skip_apps.txt'",
Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(getBaseContext(), e.getMessage(),
Toast.LENGTH_SHORT).show();
}
}
});
btnClearScreen = (Button) findViewById(R.id.btnClearScreen);
btnClearScreen.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// clear text box
txtData.setText("");
}
});
}// onCreate
}
Thanks in advance,
Bas
Dooder
1. Chaper 8. Have mercy on yourself.
2. coloredlogcat.py
3. why not
Code:
e.printStackTrace()
but
Code:
Toast.LENGTH_SHORT
is beyond me
4.
Code:
android.permissions.WRITE_EXTERNAL_STORAGE
does not equal permissions to write to
Code:
/data/local
5.
Google unfortunately didn't help me much on this one
Click to expand...
Click to collapse
Moment of honesty. G-FU sucks or you just gave up?
I am an a-hole for a reason here. All you need to know is out there. No one else will hit you harder on the head with a RTFM board than a coder.
el_bhm said:
Dooder
1. Chaper 8. Have mercy on yourself.
2. coloredlogcat.py
3. why not
Code:
e.printStackTrace()
but
Code:
Toast.LENGTH_SHORT
is beyond me
4.
Code:
android.permissions.WRITE_EXTERNAL_STORAGE
does not equal permissions to write to
Code:
/data/local
5.
Moment of honesty. G-FU sucks or you just gave up?
I am an a-hole for a reason here. All you need to know is out there. No one else will hit you harder on the head with a RTFM board than a coder.
Click to expand...
Click to collapse
The code is mostly from a tutorial, with a few edits. Why use stackTrace on a test? Also, I test on the device for reliability and root access. It's easier to see a Toast there, so didn't remove it.
About the Chapter 8: Yes, onClickListener is not the best way (skimmed over it, it's 1:26 AM here), but here too: optimizations later.
About Google: I Googled, didn't find anything that really could help me along so that I understood, asked in three other places. SO was someone who didn't reply later on, Google Groups said my permission was wrong, as I said WRITE_TO_EXTERNAL_STORAGE. I corrected that, saying I had the right permission but I wrote down the wrong one (hastily. Stupid, I know...), and here, on XDA, you're the only post yet. I have waited between posts to post it on all those boards, as I'm not an a**hole.
If any more information is needed, just tell me.
Bas
EDIT: Missed a bit. About the writing: I know now, it's just that I have no idea how to proceed from root access to writing there. And I do hope to learn how to do it.
1. You'd rather want to write into
Code:
/data/data/[package]/
Is there any particular reason you want to write directly to local? Some "system wide" app? From code I understand this is some tabbed app(?). Or is it just test for root?
Unless you have somewhat extensive knowledge of Linux and programming, don't go into root access. Make yourself a favour and get as much knowledge of objective programming first. It seems it was inspired by Outler doing root in part two. He's doing ADK in part 3. These are not easy things.
2. Are you sure you are writing anything? With this code I am getting nowhere actually.
I have not written anything with root (main reason it caught my attention). My best guess is though, permissions are not escalated for objects you are creating while setting up listeners for buttons.
From brief reading of the code and documentation it seems that you are escalating permissions for Process p which you works in conjunction with DataOutputStream. While setting up listeners you are not doing anything with p anymore.
My best guess permissions escalation would apply to the whole package, but as I see it, it does not happen.
EDIT: Besides, keep in mind you are writing a file via echoing through shell. Which is not equivalent of writing through instances of classes in onClickListeners
3. As to why printStackTrace()
Unless you are running Windows(which for Android development I really feel you should not) with coloredlogcat.py you'll have much more comprehensive output to troubleshoot the app. Line where problem occurs. Where it originates, where it goes, etc.
There should be some interpreter of python for Windows, but I don't know how the script will behave though.
4. Inserting logcat output is always helpful.
Providing the layout is always helpful.
el_bhm said:
1. You'd rather want to write into
Code:
/data/data/[package]/
Is there any particular reason you want to write directly to local? Some "system wide" app? From code I understand this is some tabbed app(?). Or is it just test for root?
Unless you have somewhat extensive knowledge of Linux and programming, don't go into root access. Make yourself a favour and get as much knowledge of objective programming first. It seems it was inspired by Outler doing root in part two. He's doing ADK in part 3. These are not easy things.
2. Are you sure you are writing anything? With this code I am getting nowhere actually.
I have not written anything with root (main reason it caught my attention). My best guess is though, permissions are not escalated for objects you are creating while setting up listeners for buttons.
From brief reading of the code and documentation it seems that you are escalating permissions for Process p which you works in conjunction with DataOutputStream. While setting up listeners you are not doing anything with p anymore.
My best guess permissions escalation would apply to the whole package, but as I see it, it does not happen.
EDIT: Besides, keep in mind you are writing a file via echoing through shell. Which is not equivalent of writing through instances of classes in onClickListeners
3. As to why printStackTrace()
Unless you are running Windows(which for Android development I really feel you should not) with coloredlogcat.py you'll have much more comprehensive output to troubleshoot the app. Line where problem occurs. Where it originates, where it goes, etc.
There should be some interpreter of python for Windows, but I don't know how the script will behave though.
4. Inserting logcat output is always helpful.
Providing the layout is always helpful.
Click to expand...
Click to collapse
The files I'm writing are supposed to be in /data/local. Writing anywhere else would obviously kind of defeat the purpose.
I don't really have knowledge of Linux, didn't know you had to to be able to write a file. On the other hand, I had basically no knowledge of Android when I started writing my first app, and that worked out quite well, if I do say so myself.
About the permissions for the writing: I think you are right about that. I simply followed a tutorial, added SU permission check, and changed the path. Then tried to get that working.
I am running Windows. I do have Ubuntu on a bootable USB and on my HDD, but on the stick it has a low res and doesn't save any configs (which is not that weird), and on my HDD it suddenly fails to boot, and WUBI won't let me uninstall...
Plus, too much fiddling. Why is it so hard to get Flash installed, for God's sake?
About the LogCat output: I'm not really one to hook my phone up to my PC for that, unless no other solution is possible. Not because I'm lazy, but because my PC generally takes a couple of minutes to recognize the phone, open Explorer, etc. when I am doing a couple of other things.
I guess I'll just give up. Do you have any sites/places where I can gain some valuable knowledge about this?
Bas
About that permission check. Well, it passes the test. Thing is, there is no
Code:
/system/sd/temporary.txt
after I drop to adb shell.
Is that path the one you had set? IIRC Samsung does something funky with internal/external memory mounts in their devices. Is that path valid at all?
I'm guessing echo fails but passes the su test. So permissions are good, it seems.
Theoretically you can try parsing contents you need to that command you are basically executing. If there is a file in
Code:
/system/sd/
You could write file you need as temps wherever you have rights, then gain permissions and copy the contents via
Code:
cat [path_to_temp_file] > /data/local/file
Going offtopic.
Never. Ever use WUBI. Seriously. Just read about install process. If it fails on normal CD, download alternate. A bit more daunting but still should be manageable. Or get other distro like Mint.
It's enough to copy file to
Code:
~/.mozilla/plugins
. FF and Opera should easily use it.
Or just install
Code:
ubuntu-restricte-extras
. It should have flash.
You can also get to your phone over wifi. Just get adbWireless from market.
Knowledge? On what?
Programming? Read documentation of android. Many tutorials. Really easy to read (compared to other OS docs), extensively described.
Stackoverflow
Get any O'reily books.
Android? See above.
Linux? Stop expecting from any distro to behave like Windows and use it as you would know nothing about PC. You'll save yourself much time and frustration.
webup8, omgubuntu, planet-ubuntu. Enough there to start.
el_bhm said:
About that permission check. Well, it passes the test. Thing is, there is no
Code:
/system/sd/temporary.txt
after I drop to adb shell.
Is that path the one you had set? IIRC Samsung does something funky with internal/external memory mounts in their devices. Is that path valid at all?
I'm guessing echo fails but passes the su test. So permissions are good, it seems.
Theoretically you can try parsing contents you need to that command you are basically executing. If there is a file in
Code:
/system/sd/
You could write file you need as temps wherever you have rights, then gain permissions and copy the contents via
Code:
cat [path_to_temp_file] > /data/local/file
Going offtopic.
Never. Ever use WUBI. Seriously. Just read about install process. If it fails on normal CD, download alternate. A bit more daunting but still should be manageable. Or get other distro like Mint.
It's enough to copy file to
Code:
~/.mozilla/plugins
. FF and Opera should easily use it.
Or just install
Code:
ubuntu-restricte-extras
. It should have flash.
You can also get to your phone over wifi. Just get adbWireless from market.
Knowledge? On what?
Programming? Read documentation of android. Many tutorials. Really easy to read (compared to other OS docs), extensively described.
Stackoverflow
Get any O'reily books.
Android? See above.
Linux? Stop expecting from any distro to behave like Windows and use it as you would know nothing about PC. You'll save yourself much time and frustration.
webup8, omgubuntu, planet-ubuntu. Enough there to start.
Click to expand...
Click to collapse
Well, this is intended for AOSP ROMs, so I was thinking that there shouldn't be any problem in trying to write a file in that directory. But yes, Samsung does do some weird things...
About the copying and then moving from there: Might be a good idea if I can figure it out. However, do you think that will suddenly work?
The install at first was planned to be from the bootable stick I have, but when I read about WUBI, it seemed so easy. Easy to deinstall Ubuntu, too. Anyhow, I think a friend kind of borked it not too long ago. Pressed the wrong button somewhere, might have slightly affected the MBR (Windows boot animation is also gone now, back to Vista ).
Could you explain a bit more about the Flash install? It seemed (and truly was) so tedious at the time for something that was still slow and laggy... In my experience, don't get me wrong.
I have used AirDroid for example for reaching my phone, good suggestion there.
On the topic of developing (circling back around ), I will be looking into your suggestions. I do use Google and tutorials a lot, and SO has been quite a good help in that. Also, asking people to help personally (GTalk, for example, or PM on a forum), has got me quite a long way.
And using Ubuntu like I know nothing: It was quite different . I noticed that almost all of my knowledge was rendered useless in a matter of minutes haha. Bad thing is I did still think I knew, I guess. Led to frustration over it being so annoying. I guess it takes a lot of getting used to.
If that "temporary.txt" file is created, I don't see why it should fail since it passes the Root check.
instead of
Code:
cat
you may as well use
Code:
cp
which is basically command for copy.
About Flash (on which even Adobe is dropping a ball since they have balls to finally admit it's a joke anyway) you can read here.
https://help.ubuntu.com/community/RestrictedFormats
Alternate version of installer never failed me so far.
el_bhm said:
If that "temporary.txt" file is created, I don't see why it should fail since it passes the Root check.
instead of
Code:
cat
you may as well use
Code:
cp
which is basically command for copy.
About Flash (on which even Adobe is dropping a ball since they have balls to finally admit it's a joke anyway) you can read here.
https://help.ubuntu.com/community/RestrictedFormats
Alternate version of installer never failed me so far.
Click to expand...
Click to collapse
I'll take a look at using cp. However, it might be some time before I pick this up again. My earlier project has almost been accepted by the person who asked me to make it, so first I'll be busy on that.
But the basic thing here is to create it somewhere else and copy it, right? Let's hope that works, then .
Also, I'll be looking at your suggestions for Flash and the alternate installer, thanks a lot!
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums & Read the Forum Rules
Moving to Q&A

Huawei Open-Source Release - Broadcom DHD Open-Source Driver for S7 Froyo Working

Found this on Huawei's webpage: http://www.huaweidevice.com/worldwi...=toDownloadFile&flay=software&softid=NDcwODE=
open source_wlan.tar_S7_Android2.2
Would be nice if someone has the time to look at this.
The binary file that shipped with my Huawei firmware has version 4.218.248.17
Edit:
Tested and working. Forgot to update text here.
Mirrored the file for convenience for everyone who wants this. The first link actually was wrong, so I changed it.
Put this in an Android tree (such as /hardware/broadcom), do breakfast/lunch after envsetup, and perform 'make dhdko' with the kernel files present at /kernel. This is for Froyo. To build for Gingerbread, LOCAL_MODULE_TAGS cannot be equal to 'user', so you need to change Android.mk to say 'optional' instead. That's if you want to use Android.mk to build. If you are not building the whole tree, remember to make a folder /lib/modules/, or dhd.ko will not copy from the product obj folder properly.
Not sure how this will build for ICS/Jellybean, but at least now we have the source code that actually builds a proper module.
Kernel objects need to be in the right place. I did something to the effect of:
make -C kernel O=/sources/aosp/out/target/product/s7/obj/KERNEL_OBJ ARCH=arm CROSS_COMPILE=arm-eabi-
Built module works fine and is the same version shipped with Android 2.2 (4.218.248.17).
The driver is actually eerily similar to the bcm4329 kernel 3.4 bcm4329 driver. So much so i figured out what caused the sdio timeout.
Offending code causing emulate domain manager error om 2.6.35 when removed, sdio timeout when added:
dhd_linux.c:
Code:
static int
dhd_watchdog_thread(void *data)
{
dhd_info_t *dhd = (dhd_info_t *)data;
/* This thread doesn't need any user-level access,
* so get rid of all our resources
*/
#ifdef DHD_SCHED
if (dhd_watchdog_prio > 0) {
struct sched_param param;
param.sched_priority = (dhd_watchdog_prio < MAX_RT_PRIO)?
dhd_watchdog_prio:(MAX_RT_PRIO-1);
setScheduler(current, SCHED_FIFO, &param);
}
#endif /* DHD_SCHED */
DAEMONIZE("dhd_watchdog");
/* Run until signal received */
while (1) {
if (down_interruptible (&dhd->watchdog_sem) == 0) {
offender---------> dhd_os_sdlock(&dhd->pub);
if (dhd->pub.dongle_reset == FALSE) {
For kernels : http://threader.zapto.org/experimental/s7/wifi/bcm4329-30-09-13.tar.bz2

[LineageOS][OTA][PHP] Open Source REST Server for you

Hi guys,
today I would like to present to you a simple project that was born on this thread to accomplish a very simple task: since there are thousand of Custom ROMs around here, so much of them are LineageOS based, and because of this their forced to build every time all the ROM and post updates here. Users are also forced to check if their preferred ROM was updated or not. That's why I decided to understand how LineageOS OTA Updater System App works. Because of this I've wrote a simple REST Server API emulation that fully works with your ROM (if integrated of course). How? Continue reading down here.
How does it work?
Of course is as simple as it should be. Clone the repo (is a simple PHP website that you can host on any shared hosting*/VPS that you like) and upload it into your preferred hosting. That's it. If you point your web browser to that address the App is already working.
After, you have to upload all your build to the _builds/ folder, and you're done.
The two already working calls /api and /api/v1/build/get_delta should answer correctly the updater app to make it work (remember that visiting it as a browser is not sufficent).
How to integrate it with my ROM?
You have two options:
- Declare cm.updater.uri on your own build.prop file with the value of you own server URL where you have deployed it (This can be done also by the user with any Android App from the Market)
- Replace the string conf_update_server_url_def value inside values.xml of the OTA App source code (COMPILE TIME ONLY!)
Which builds does it support?
Anything that will be borned by the official guide on how to build your custom LineageOS ROM! So, in poor words will be: stable, rcs, nightly and snapshots (likely called EXPERIMENTAL), from CM7 to CM14.
Delta updates SHOULD work too. Just try it and tell me if they works
How can I debug it?
You can use this simple UnitTest that I've already pushed into my GitHub. Feel free to use it everytime you need. It's based upon NodeJS and Unirest.
Is it free?
"Free software is a matter of liberty, not price. To understand the concept, you should think of free as in free speech, not as in free beer."
—Richard Stallman
Click to expand...
Click to collapse
Use it as you want, do anything you want with it as it's MIT licensed.
Is it free of bugs?
That's why I'm here Only you can help me to squash all the remaining bugs!
I hope this will be useful to anyone of you, helping the ROM community providing a simple OTA updater that already works on LineageOS official ROMs.
Greets.
---
Project Home: https://github.com/julianxhokaxhiu/LineageOTA
More about the study: http://blog.julianxhokaxhiu.com/how-the-cm-ota-server-works-and-how-to-implement-and-use-ours
Changelog Build Scripts ( thanks to @Deltadroid ): https://github.com/syphyr/cm_build_scripts/blob/master/make_changelog
* On a Shared Hosting you can ONLY provide a FULL ROM download, NOT DELTAs!
---
Donators:
- @BlueFlame4 x2
Hey, I'm having trouble using your docker image behind a Nginx https reverse proxy. The server is correctly answering the requests:
Code:
{
"id":null,
"response":[
{
"incremental":"",
"api_level":"",
"url":"http:\/\/MYDOMAIN\/\/builds\/full\/lineage-17.1-20200830-UNOFFICIAL-lavender.zip",
"timestamp":1598774045,
"md5sum":"718fb89f935b979edd57b2642234d1fa",
"changes":"",
"channel":"unofficial",
"filename":"lineage-17.1-20200830-UNOFFICIAL-lavender.zip",
"romtype":"unofficial",
"datetime":1598774045,
"version":"17.1",
"id":"50533a894b2ab0d9b2711444ca4f2b530a8ff2389723ea2bd7ada6e029599e2c",
"size":914450521
}
],
"error":null
}
But the returned `url` is http-only and the updater can't download it (throws error). WhenI try to curl it without `-L` I only get `301 Moved Permanently`. Only when I append `-L` I get the correct binary response over https. I'm pretty sure this is a redirecting issue.
Here's my Nginx config:
Code:
server{
server_name MYDOMAIN;
server_tokens off;
listen 80;
listen [::]:80 ipv6only=on;
# Redirect all HTTP requests to HTTPS with a 301 Moved Permanently response.
return 301 https://$host$request_uri;
}
server {
server_name MYDOMAIN;
server_tokens off;
listen 443 ssl http2;
listen [::]:443 ssl http2 ipv6only=on;
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_set_header X-NginX-Proxy true;
proxy_pass http://127.0.0.1:24087;
proxy_redirect off;
proxy_http_version 1.1;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
}
add_header Strict-Transport-Security "max-age=15768000; includeSubdomains; preload";
add_header Referrer-Policy same-origin;
add_header X-Content-Type-Options nosniff;
add_header X-Frame-Options DENY;
add_header X-Xss-Protection "1; mode=block";
[...]
Any idea what I'm doing wrong?
Basically I want to know how to force the `url` response in the JSON to be `https` instead of `http`. (At least that's what I think is the reason for the updater not being able to download the image.)
Code:
08-30 16:00:19.407 7025 7025 D UpdaterController: Starting 50533a894b2ab0d9b2711444ca4f2b530a8ff2389723ea2bd7ada6e029599e2c
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: Error downloading file
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: java.io.IOException: Cleartext HTTP traffic to MYDOMAIN not permitted
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: at com.android.okhttp.HttpHandler$CleartextURLFilter.checkURLPermitted(HttpHandler.java:124)
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:462)
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: at com.android.okhttp.internal.huc.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:131)
08-30 16:00:19.409 7025 7921 E HttpURLConnectionClient: at org.lineageos.updater.download.HttpURLConnectionClient$DownloadThread.run(HttpURLConnectionClient.java:250)
08-30 16:00:19.409 7025 7921 E UpdaterController: Download failed
EDIT: Solved!
Code:
location / {
proxy_pass http://127.0.0.1:24087;
proxy_http_version 1.1;
proxy_cache_bypass $http_upgrade;
proxy_set_header Upgrade $http_upgrade;
proxy_set_header Connection "upgrade";
#proxy_set_header Host $host;
proxy_set_header Host $http_host;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-Host $host;
proxy_set_header X-Forwarded-Port $server_port;
proxy_set_header X-NginX-Proxy true;
}
Not sure if this project is still supported, but with build.prop change, it just checks for updates forever on phone. When I try debugging with the UnitTest script, I get "Not Found The requested URL /CyanogenModOTA/api was not found on this server." (definitely server-related) I've gotten this working before on another VPS, so I'm wondering why it's not on my build server.
Are there any specific packages I need to install to get this working?
Here is my php config: http://hongbuild.ddns.net:81/test.php
klvnhng said:
Not sure if this project is still supported, but with build.prop change, it just checks for updates forever on phone. When I try debugging with the UnitTest script, I get "Not Found The requested URL /CyanogenModOTA/api was not found on this server." (definitely server-related) I've gotten this working before on another VPS, so I'm wondering why it's not on my build server.
Are there any specific packages I need to install to get this working?
Here is my php config: http://hongbuild.ddns.net:81/test.php
Click to expand...
Click to collapse
Since build.prop is in the system.new.dat file in lollipop builds, I just started copying it over from my build server and modified the Build.php file to look for the file instead of inside the zip. I just got this working on my web server. Only issue I'm having is related to change logs but I'm going to try and figure that one out later.
Here are the changes I did to get this working with CyanogenMod 12 (all changes will be assumed from the CyanogenModOTA directory):
- mkdir -p builds/buildprop <-- this is where you copy your build.prop from each build (they go in a folder with the same name as the build zip e.x. cm-12-20150103-NIGHTLY)
- mkdir -p builds/changelog <-- this will have your change logs (name them the same as the build zip except with a .txt extension)
- update setConfig( 'basePath', 'CyanogenModOTA' ) to setConfig( 'basePath', 'http://wfhome.net/CyanogenModOTA' ) in index.php (that is my server)
- change the Build constructor function to this (I updated the preg_match_all line, added the buildPropFolder variable, updated the $this->buildProp line, and changed the changeLogUrl line):
Code:
private $buildPropFolder = '';
public function __construct($fileName, $physicalPath) {
/*
$tokens Schema:
array(
1 => [CM VERSION] (ex. 10.1.x, 10.2, 11, etc.)
2 => [DATE OF BUILD] (ex. 20140130)
3 => [CHANNEL OF THE BUILD] (ex. RC, RC2, NIGHTLY, etc.)
4 => [MODEL] (ex. i9100, i9300, etc.)
)
*/
preg_match_all( '/cm-([0-9\.]+-)(\d+-)?([a-zA-Z0-9]+-)?([a-zA-Z0-9]+).zip/', $fileName, $tokens );
$tokens = $this->removeTrailingDashes( $tokens );
$this->filePath = $physicalPath . '/' . $fileName;
$this->buildPropFolder = str_replace('/full', '/buildprop', $physicalPath) . '/' . preg_replace('/\\.[^.\\s]{3,4}$/', '', $fileName);
$this->buildProp = explode( "\n", file_get_contents($this->buildPropFolder . '/build.prop') );
$this->channel = $this->_getChannel( str_replace( range( 0 , 9 ), '', $tokens[3] ) );
$this->filename = $fileName;
$this->url = $this->_getUrl( '', Flight::cfg()->get('buildsPath') );
$this->changelogUrl = str_replace('/full', '/changelog', $this->_getChangelogUrl());
$this->timestamp = filemtime( $this->filePath );
$this->incremental = $this->getBuildPropValue( 'ro.build.version.incremental' );
$this->apiLevel = $this->getBuildPropValue( 'ro.build.version.sdk' );
$this->model = $this->getBuildPropValue( 'ro.cm.device' );
}
Also he has memcached setup in there, so you might make sure you have memcache installed and set to run on startup on your server. You also need xdelta3 to create delta builds although, I don't think it is working ( I compiled the latest version of xdelta3 and it doesn't appear to do anything as there are not any files being created in the delta folder).
Hope that helps.
Thanks for the help (I'll definitely need it when I actually want to start USING the server), but it seems you've misunderstood me. Right now, I can't even get the rest server running properly-that's why I'm getting a 404 error.
Notice you get an output when you go to http://wfhome.net/CyanogenModOTA/api, I don't get anything!
klvnhng said:
Thanks for the help (I'll definitely need it when I actually want to start USING the server), but it seems you've misunderstood me. Right now, I can't even get the rest server running properly-that's why I'm getting a 404 error.
Notice you get an output when you go to http://wfhome.net/CyanogenModOTA/api, I don't get anything!
Click to expand...
Click to collapse
Ah sorry. First thing I see is that you need mod_rewrite installed in apache.
Code:
sudo a2enmod rewrite
sudo service apache2 restart
Need help with development
First I would like to thank you for using this product and playing with it (which involves patching, testing, etc.).
Since the first post I've made here in XDA the project evolved a little since I rewrote entirely the project to make it composer friendly. Rather than that, the Delta build process is actually non working (I tried to create a ZIP but I don't have enough knowledge in ROM development to tell if it's enough or not) so it's just a WIP layer that should be addressed and fixed (I've already found a Python project which does this already but I'm of the idea that this should be somehow not be a bloated software that needs to install binaries here and there to make it working).
So, actually I'm not really working in this project but It's in my TODO list, meanwhile I'll be very happy to have pull requests with useful patches to make this KK, LL and more compatible So feel free to contribute and thanks again for using it!
JulianXhokaxhiu said:
First I would like to thank you for using this product and playing with it (which involves patching, testing, etc.).
Since the first post I've made here in XDA the project evolved a little since I rewrote entirely the project to make it composer friendly. Rather than that, the Delta build process is actually non working (I tried to create a ZIP but I don't have enough knowledge in ROM development to tell if it's enough or not) so it's just a WIP layer that should be addressed and fixed (I've already found a Python project which does this already but I'm of the idea that this should be somehow not be a bloated software that needs to install binaries here and there to make it working).
So, actually I'm not really working in this project but It's in my TODO list, meanwhile I'll be very happy to have pull requests with useful patches to make this KK, LL and more compatible So feel free to contribute and thanks again for using it!
Click to expand...
Click to collapse
Thank YOU for making it! Really appreciate the time and effort you've put into this project.
rjwil1086 said:
Ah sorry. First thing I see is that you need mod_rewrite installed in apache.
Code:
sudo a2enmod rewrite
sudo service apache2 restart
Click to expand...
Click to collapse
That did it, thanks :good:
I've also implemented your changes, but when I check for updates on my phone, I still get "No new updates found". I've copied my new build over to builds/full, and the build.prop to builds/buildprop/cm*
rjwil1086 thank you very much for your help and suggestions, I made my own server http://paksman.ddns.net/cyanogenmodota, edited build.prop for cm updater to look for server url, made all the changes as you but I always get "No new updates found". Not sure if there is a problem with my server or with this project in general. Have you made any success to make this work?
I have it working. I'll upload mine to github tonight
Think I solved my own problem. My builds were all tagged as 'UNOFFICIAL'. When I changed this to 'NIGHTLY' (for the build and build.prop folder respectively ) they finally started to be recognised by cm updater app. JulianXhokaxhiu and rjwil1086, thank you so much for your effort,your work is being much appreciated.
Packsman said:
Think I solved my own problem. My builds were all tagged as 'UNOFFICIAL'. When I changed this to 'NIGHTLY' (for the build and build.prop folder respectively ) they finally started to be recognised by cm updater app. JulianXhokaxhiu and rjwil1086, thank you so much for your effort,your work is being much appreciated.
Click to expand...
Click to collapse
Yup. Sorry. I knew that but forgot to mention it. That's an issue with the CMUpdater app more than it is with the REST implementation. It doesn't look for unofficial files
Packsman said:
Think I solved my own problem. My builds were all tagged as 'UNOFFICIAL'. When I changed this to 'NIGHTLY' (for the build and build.prop folder respectively ) they finally started to be recognised by cm updater app. JulianXhokaxhiu and rjwil1086, thank you so much for your effort,your work is being much appreciated.
Click to expand...
Click to collapse
Awesome! This fixed it for me as well. Thanks to everyone for the help
[CyanogenMod][OTA][PHP] Open Source REST Server for you
Hi, I have been tested server code with a free host (000webhost) then accessed the web, I received messages:
Warning: Unexpected character in input: '\' (ASCII=92) state=1 in /home/a5885282/public_html/index.php on line 27
Parse error: syntax error, unexpected T_STRING, expecting T_CONSTANT_ENCAPSED_STRING or '(' in /home/a5885282/public_html/index.php on line 27
The line 27 of index.php is "use \JX\CmOta\CmOta;". But I don't know about PHP. Please help me solve this issue.
@rjwil1086 , @klvnhng , @Packsman please help me to solve following error:
$ node index.js
<h1>500 Internal Server Error</h1><h3>Undefined offset: 0 (8)</h3><pre>#0 /var/www/CyanogenModOTA/src/Helpers/Build.php(214): flight\Engine->handleError(8, 'Undefined offse...', '/var/www/Cyanog...', 214, Array)
#1 /var/www/CyanogenModOTA/src/Helpers/Build.php(63): JX\CmOta\Helpers\Build->removeTrailingDashes(Array)
#2 /var/www/CyanogenModOTA/src/Helpers/Builds.php(115): JX\CmOta\Helpers\Build->__construct('cm-11-20140103-...', '/var/www/Cyanog...')
#3 /var/www/CyanogenModOTA/src/Helpers/Builds.php(49): JX\CmOta\Helpers\Builds->getBuilds()
#4 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Loader.php(123): JX\CmOta\Helpers\Builds->__construct()
#5 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Loader.php(80): flight\core\Loader->newInstance('\JX\CmOta\Helpe...', Array)
#6 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/Engine.php(69): flight\core\Loader->load('builds', true)
#7 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(191): flight\Engine->__call('builds', Array)
#8 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(191): flight\Engine->builds()
#9 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/Flight.php(43): flight\core\Dispatcher::invokeMethod(Array, Array)
#10 /var/www/CyanogenModOTA/src/CmOta.php(97): Flight::__callStatic('builds', Array)
#11 /var/www/CyanogenModOTA/src/CmOta.php(97): Flight::builds()
#12 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(160): JX\CmOta\{closure}()
#13 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(143): flight\core\Dispatcher::callFunction(Object(Closure), Array)
#14 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/Engine.php(310): flight\core\Dispatcher::execute(Object(Closure), Array)
#15 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(191): flight\Engine->_start()
#16 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(142): flight\core\Dispatcher::invokeMethod(Array, Array)
#17 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(48): flight\core\Dispatcher::execute(Array, Array)
#18 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/Engine.php(64): flight\core\Dispatcher->run('start', Array)
#19 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(191): flight\Engine->__call('start', Array)
#20 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/core/Dispatcher.php(191): flight\Engine->start()
#21 /var/www/CyanogenModOTA/vendor/mikecao/flight/flight/Flight.php(43): flight\core\Dispatcher::invokeMethod(Array, Array)
#22 /var/www/CyanogenModOTA/src/CmOta.php(80): Flight::__callStatic('start', Array)
#23 /var/www/CyanogenModOTA/src/CmOta.php(80): Flight::start()
#24 /var/www/CyanogenModOTA/index.php(35): JX\CmOta\CmOta->run()
#25 {main}</pre>
Thank you so much.
Thanks all, I fixed.
[CyanogenMod][OTA][PHP] Open Source REST Server for you
I have just creat susscess a server. Thanks.
But, now I want creat a update OTA app for other AOSP ( andoird L) and using that server which I have just creat.
Can I using CMupdater for it? Can you give me some suggest?
Hi, need help to understand!
First of all, i want to say Thank You! For this great job!
I installed server, activated mod rewrite in apache2, apt-get install memcached, made chown for all files to www-data in CyanogenModOTA directory
created directories builds/buildprop, builds/changelog
created file romname.txt in changelog
copied file rom archive to build/full directory
and when i open in browser my ota site: http ota.mydomain.com i see the dir listing as described above
when i try to open url http ota.mydomain.com/api - i see the 404 error.
what exactly i have to do as the next step?
is any json file missed in web root directory (in same place as index.php) ?
and I leave index.php almost unchanged (as in the repository) - just changed string: ->setConfig( 'basePath', '/' )
Thank You once again!
vvzar said:
First of all, i want to say Thank You! For this great job!
I installed server, activated mod rewrite in apache2, apt-get install memcached, made chown for all files to www-data in CyanogenModOTA directory
created directories builds/buildprop, builds/changelog
created file romname.txt in changelog
copied file rom archive to build/full directory
and when i open in browser my ota site: http ota.mydomain.com i see the dir listing as described above
when i try to open url http ota.mydomain.com/api - i see the 404 error.
what exactly i have to do as the next step?
is any json file missed in web root directory (in same place as index.php) ?
and I leave index.php almost unchanged (as in the repository) - just changed string: ->setConfig( 'basePath', '/' )
Thank You once again!
Click to expand...
Click to collapse
Are you sure that modrewrite is working? Can you share a working URL?
lingak said:
I have just creat susscess a server. Thanks.
But, now I want creat a update OTA app for other AOSP ( andoird L) and using that server which I have just creat.
Can I using CMupdater for it? Can you give me some suggest?
Click to expand...
Click to collapse
Honestly I don't know, we have to check if OTA app is the same in Lollipop and works of course the same. If so, we're already safe and yes it can work out of the box. If not, we have to fix it. If you already have a working example, feel free to do a pull request
JulianXhokaxhiu said:
Are you sure that modrewrite is working? Can you share a working URL?
[email protected]:/home/user# a2enmod rewrite
Module rewrite already enabled
[email protected]:/home/user#
.htaccess:
[email protected]:/home/user# cat /var/www/html/CyanogenModOTA/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
[email protected]:/home/user#
Is any other rules i have to check?
What about statement <Directory /var/www/html/CyanogenModOTA> ?
Is enouph AllowOverride All and Allow from all ?
test url : http ota.smylink.org
Click to expand...
Click to collapse
vvzar said:
JulianXhokaxhiu said:
Are you sure that modrewrite is working? Can you share a working URL?
[email protected]:/home/user# a2enmod rewrite
Module rewrite already enabled
[email protected]:/home/user#
.htaccess:
[email protected]:/home/user# cat /var/www/html/CyanogenModOTA/.htaccess
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
[email protected]:/home/user#
Is any other rules i have to check?
What about statement <Directory /var/www/html/CyanogenModOTA> ?
Is enouph AllowOverride All and Allow from all ?
test url : http ota.smylink.org
Click to expand...
Click to collapse
Technically it should be enough but the order of where you placed it is important too.
Anyway, going to your URL is just making me think that the PHP code is running well (the redirect to builds folder is triggered by CMOTA Rest Code). You're just missing the htaccess rules.
I'm quite sure you just have to figure out your own server setup to understand if mod_rewrite is properly working (allowing htaccess files to be read and parsed).
Click to expand...
Click to collapse

[KERNEL] Power over OTG host mod.

[From my README]
A mod for the Oneplus One DWC3 otg module. This allows for charging and host mode simultaneously, inspired by Ziddey's msm_otg mod for the Nexus 4/7 (2013). Functionality was ported over from his kernel hack to the DWC3 USB driver which now handles the MSM8974 USB controller.
The hack works through setting a custom module parameter I've added to allow 'ACA' host mode. This flag effectively turns on ID_A host mode while disabling VBUS power going to the hosted device. I've uploaded the modded dwc3_otg.c file that you can replace in your Oneplus One(bacon) kernel source of choice. It'll be located in the drivers/usb/dwc3/ directory. I've also uploaded my personal kernel image with this hack built on top of Franco's kernel. It also has other modules built into it, mainly DRM/Devtmpfs/Cifs/NFS/NTFS/Alsa Sequencer/Usbip/Binfmt/loadable modules/etc... It was compiled with GCC 4.9 NDK version.
Usage: First you'll need either a generic Y split USB OTG cable or a powered USB hub connected to regular OTG(I've only tested the Y cable).
With the modified kernel flashed, open a terminal shell and as root, enter the following command: "echo Y > /sys/module/dwc3/parameters/aca_enable"
This activates the 'ACA' host mode hack.
[UPDATE]
Wiggling the cord is not needed anymore. I've updated the code so that the phone automatically accepts a charge on entering host mode.
The tricky part is now getting your Y-OTG adapter to send power to the phone. First with power cable and USB device(s) connected the adapter, plug the Y cable into the phone. Test that the phone reads the device. Now, unplug the cable from the phone, leaving the USB device and power cord plugged into the OTG adapter. Gently wiggle the cable slightly while slowly pushing it back into the phone's port, wait for the charge indicator to come on. Once the phone detects the charge, you can push the cable in all the way. The phone should be charging at max current rate while retaining host mode.
Please, if you can test the powered hub method or have improvements to this hack, feel free to share! Also, the standard legal disclaimer applies here that by using this mod/code/kernel in anyway is completely your responsibility. I'm not liable for any possible damages to your devices.
Links:
DWC3 OTG Modification For OnePlus One
https://github.com/sollapse/opo_dwc3_otg/
Ziddey's Original ACA hack for Mako
https://github.com/ziddey/mako/commits/nightlies-4.3-JSS
Franco's Oneplus One Kernel Source
https://github.com/franciscofranco/one_plus_one
Hi sollapse, thank you a lot for this patch, i modified it a little for my xperia z2, it seems to be working just fine, it detects when power is disconnected and switches back to OTG_STATE_A_IDLE automatically, anyway, the only thing that i couldnt get to work is once it is on host mode, when i connect the power it doesnt start charging, perhaps you can find a way to get it working, here's my patch:
Code:
--- dwc3_otg.c 2015-09-22 14:44:45.115324661 -0300
+++ dwc3_otg.c.new 2015-09-22 14:47:40.950239287 -0300
@@ -45,6 +45,12 @@ static void dwc3_otg_reset(struct dwc3_o
static void dwc3_otg_notify_host_mode(struct usb_otg *otg, int host_mode);
static void dwc3_otg_reset(struct dwc3_otg *dotg);
+/*OTG charging hack*/
+static bool aca_enable = 0;
+static bool enable_otg_charge = 0;
+module_param(enable_otg_charge, bool, S_IRUGO | S_IWUSR);
+MODULE_PARM_DESC(enable_otg_charge, "Force ACA host mode to allow charging and host.");
+
/**
* dwc3_otg_set_host_regs - reset dwc3 otg registers to host operation.
*
@@ -204,41 +210,45 @@ static int dwc3_otg_start_host(struct us
if (!dwc->xhci)
return -EINVAL;
-
- if (!dotg->vbus_otg) {
- dotg->vbus_otg = devm_regulator_get(dwc->dev->parent,
- "vbus_dwc3");
- if (IS_ERR(dotg->vbus_otg)) {
- dev_err(dwc->dev, "Failed to get vbus regulator\n");
- ret = PTR_ERR(dotg->vbus_otg);
- dotg->vbus_otg = 0;
- return ret;
- }
- }
-
+
+ if(!aca_enable){
+ if (!dotg->vbus_otg) {
+ dotg->vbus_otg = devm_regulator_get(dwc->dev->parent,
+ "vbus_dwc3");
+ if (IS_ERR(dotg->vbus_otg)) {
+ dev_err(dwc->dev, "Failed to get vbus regulator\n");
+ ret = PTR_ERR(dotg->vbus_otg);
+ dotg->vbus_otg = 0;
+ return ret;
+ }
+ }
+ }
+
if (on) {
dev_dbg(otg->phy->dev, "%s: turn on host\n", __func__);
dwc3_otg_notify_host_mode(otg, on);
-
- /* register ocp notification */
- if (ext_xceiv && ext_xceiv->otg_capability &&
- ext_xceiv->ext_ocp_notification.notify) {
- ret = regulator_register_ocp_notification(
- dotg->vbus_otg,
- &ext_xceiv->ext_ocp_notification);
- if (ret)
- dev_err(otg->phy->dev,
- "unable to register ocp\n");
- }
-
- ret = regulator_enable(dotg->vbus_otg);
- if (ret) {
- dev_err(otg->phy->dev, "unable to enable vbus_otg\n");
- dwc3_otg_notify_host_mode(otg, 0);
- return ret;
- }
-
+
+ if(!aca_enable){
+ /* register ocp notification */
+ if (ext_xceiv && ext_xceiv->otg_capability &&
+ ext_xceiv->ext_ocp_notification.notify) {
+ ret = regulator_register_ocp_notification(
+ dotg->vbus_otg,
+ &ext_xceiv->ext_ocp_notification);
+ if (ret)
+ dev_err(otg->phy->dev,
+ "unable to register ocp\n");
+ }
+
+ ret = regulator_enable(dotg->vbus_otg);
+ if (ret) {
+ dev_err(otg->phy->dev, "unable to enable vbus_otg\n");
+ dwc3_otg_notify_host_mode(otg, 0);
+ return ret;
+ }
+ }
+
/* The delay between enabling regulator and adding the
platform device is needed to succeed in the enumeration
for certain devices. */
@@ -269,7 +279,9 @@ static int dwc3_otg_start_host(struct us
dev_err(otg->phy->dev,
"%s: failed to add XHCI pdev ret=%d\n",
__func__, ret);
- regulator_disable(dotg->vbus_otg);
+ if(!aca_enable)
+ regulator_disable(dotg->vbus_otg);
+
dwc3_otg_notify_host_mode(otg, 0);
return ret;
}
@@ -279,24 +291,27 @@ static int dwc3_otg_start_host(struct us
dwc3_otg_reset(dotg);
} else {
dev_dbg(otg->phy->dev, "%s: turn off host\n", __func__);
-
- ret = regulator_disable(dotg->vbus_otg);
- if (ret) {
- dev_err(otg->phy->dev, "unable to disable vbus_otg\n");
- return ret;
- }
-
- /* unregister ocp notification */
- if (ext_xceiv && ext_xceiv->otg_capability &&
- ext_xceiv->ext_ocp_notification.notify) {
- ret = regulator_register_ocp_notification(
- dotg->vbus_otg, NULL);
- if (ret)
- dev_err(otg->phy->dev,
- "unable to unregister ocp\n");
- }
-
- dwc3_otg_notify_host_mode(otg, on);
+
+ if(!aca_enable){
+ ret = regulator_disable(dotg->vbus_otg);
+ if (ret) {
+ dev_err(otg->phy->dev, "unable to disable vbus_otg\n");
+ return ret;
+ }
+
+ /* unregister ocp notification */
+ if (ext_xceiv && ext_xceiv->otg_capability &&
+ ext_xceiv->ext_ocp_notification.notify) {
+ ret = regulator_register_ocp_notification(
+ dotg->vbus_otg, NULL);
+ if (ret)
+ dev_err(otg->phy->dev,
+ "unable to unregister ocp\n");
+ }
+ }
+
+ if(!aca_enable)
+ dwc3_otg_notify_host_mode(otg, on);
platform_device_del(dwc->xhci);
/*
@@ -341,8 +356,11 @@ static int dwc3_otg_set_host(struct usb_
* required for XHCI controller before setting OTG Port Power
* TODO: Tune this delay
*/
- msleep(300);
- dwc3_otg_set_host_power(dotg);
+
+ msleep(300);
+ if(!aca_enable){
+ dwc3_otg_set_host_power(dotg);
+ }
} else {
otg->host = NULL;
}
@@ -972,7 +990,17 @@ static void dwc3_otg_sm_work(struct work
dev_dbg(phy->dev, "vbus_drop_det\n");
/* staying on here until exit from A-Device */
} else {
- phy->state = OTG_STATE_A_HOST;
+ //if we have power and enable_otg_charge, force charging on
+ if (test_bit(B_SESS_VLD, &dotg->inputs) && enable_otg_charge){
+ if(charger){
+ dev_info(phy->dev, "OTG charging is ON!!!\n");
+ aca_enable = 1;
+ charger->chg_type =DWC3_SDP_CHARGER;
+ dwc3_otg_set_power(phy, DWC3_IDEV_CHG_MAX);
+ }
+ } else
+ aca_enable = 0;
+ phy->state = OTG_STATE_A_HOST;
ret = dwc3_otg_start_host(&dotg->otg, 1);
if ((ret == -EPROBE_DEFER) &&
dotg->vbus_retry_count < 3) {
@@ -1000,7 +1028,15 @@ static void dwc3_otg_sm_work(struct work
break;
case OTG_STATE_A_HOST:
- if (test_bit(ID, &dotg->inputs)) {
+ if (enable_otg_charge){
+ //detect power change and switch back to OTG_STATE_A_IDLE
+ if(!test_bit(B_SESS_VLD, &dotg->inputs)){
+ dev_info(phy->dev, "Power disconnected, charging disabled!!!\n");
+ dwc3_otg_start_host(&dotg->otg, 0);
+ phy->state = OTG_STATE_A_IDLE;
+ work = 1;
+ }
+ } else if (test_bit(ID, &dotg->inputs)) {
dev_dbg(phy->dev, "id\n");
dwc3_otg_start_host(&dotg->otg, 0);
phy->state = OTG_STATE_B_IDLE;
I've updated my code a couple of days ago to automatically apply power during the state change, assuming a charger is connected to the y cable (USB devices would not power otherwise). In your mod, it seems you're attempting to detect a charge using the 'B' mode state, but by that time with the aca flag enabled, the USB controller should be in ID_A host mode instead of B_SESS_VLD. The driver's 'set_power' function already checks the line for current automatically. Please look at the updated code to see what I did during the state change. It should all work utilizing the one parameter flag.
I tested this with a patched sultanXDA CAF kernel (since the .c source file was slightly different, I was careful to only merge the relevant changes), and a powered USB HUB. It works perfectly! Thanks.
Phoenix Wright said:
I tested this with a patched sultanXDA CAF kernel (since the .c source file was slightly different, I was careful to only merge the relevant changes), and a powered USB HUB. It works perfectly! Thanks.
Click to expand...
Click to collapse
That's great! I'm pretty certain with the push to USB Type C and potential USB 3.1 support, that the DWC3 driver will be used across most devices for now on. This code should merge well with them if ACA is absent (Zenphone 2 is the only exception I've found so far since Intel enabled it in the driver).
Can someone post a modded CAF kernel for the opo? I am having issues building a kernel as I currently only have a windows box.
snekiam said:
Can someone post a modded CAF kernel for the opo? I am having issues building a kernel as I currently only have a windows box.
Click to expand...
Click to collapse
Latest Sultanxda kernel (as of 10/4), with the CAF dwc_otg modified with sollapse's patches. His sources are here: https://github.com/sultanxda/android_kernel_oneplus_msm8974
I used Google GCC 4.8, which is the same one he uses, as far as I could tell.
View attachment sultan10-4_otg-y.7z
@sollapse I noticed a bug. I made two widgets with an app on Play Store (to enable and disable this hack). I disabled this by mistake while the OTG device and charge were still inserted, and after I removed them I got a kernel panic, could this be fixed?
I should be able to fix it. I'll look at it again and will try to clean up the state change code.
Kernel
Can someone please upload a kernel .img?
I am not able to compile a kernel on my own....
@sollapse I fixed the kernel panics, and also another bug (when the aca_enable parameter was on, you couldn't charge at full speed with a wall charger - not in host mode, just simple charging). I've done all possible status changes (set aca_enable to on, insert otg-y cable + device, turn aca_enable off, unplug device; aca_enable is off, plug regular otg cable + device, turn aca_enable on, unplug device, set aca_enable to off, re-plug). These two situations respectively gave these results: kernel panic and inability to use regular otg again.
Turns out that the issues were with "regulator_disable", now it's executed when the regulator is enabled, regardless of the aca_enable parameter.
Another fix for incorrect usage: if you connected a regular OTG cable+device while aca_enable was set to Y, it would show the charging icon, and it would even stay there after the device was disconnected! Sadly I can't prevent the charging icon from appearing (as this hack basically forces all the "unknown" chargers to be reported as USB - as opposed to AC - chargers... and the weird part is that the charge coming from OTG-Y is an "unknown charger"... but the charge (?) coming from a regular OTG device is an "unknown charger" too! XD, if there's a way it's out of reach for me), but I managed to make it go away after disconnection. Basically, it doesn't force "unknown" to USB if the function gets called to *disable* charging. I guess this is the best I can do for this kernel mod ^_^
It looks I was wrong, after lots of debugging of dwc3_otg I learned how it works, so I overhauled the patch. It works more cleanly now: it actually properly detects the charger (no more phantom notifications, faster charging rates if it's allowed by the charger), supports unplugging and replugging of the power cord while using OTG-Y, and unplugging of the device after power was unplugged, fixes all sorts of race conditions and wrong usages of the aca_enable parameter (I'm not sure if it's all of them, but I've been testing and fixing things for a while).
I attach a .diff for CAF kernels. Take note that to use the fix for plugging OTG devices in sleep mode you need to patch the charger driver: https://github.com/sultanxda/androi...mmit/7b023b295fdfa4789c93aee8b04f5d2a9b52dbba
Wow, I've completely abandoned this hack since it's worked well enough for me . Also haven't had much time due to work and other necessities. Thanks for the patches @Phoenix Wright for cleaning up this hack! This should be a standard addition to all future Android kernels.
sollapse said:
Wow, I've completely abandoned this hack since it's worked well enough for me . Also haven't had much time due to work and other necessities. Thanks for the patches @Phoenix Wright for cleaning up this hack! This should be a standard addition to all future Android kernels.
Click to expand...
Click to collapse
Yeah, I wonder why they haven't implemented the feature officially, as it can be done just fine
And many thanks for developing this
By the way, I realized the reboots when inserting an OTG-Y device in deep sleep were not actually fixed, as I got a reboot yesterday, my bad (sultanxda fixed the issues with doing it with regular OTG, but it seems the issue with OTG-Y was different). It seems it's fixed properly this time though. Same patch as yesterday, just a two line difference.
Thanks for the original mod, sollapse, and thanks for your patches and all the updates, Phoenix. Just to confirm: this mod requires that on every kernel update via Sultan's OTA, the kernel source be pulled, patched, flashed onto your OPO, and finally activated using the aca command?
I'm off to go learn how to build a kernel from this handy guide, if anyone else is interested in jumping on this exciting bandwagon.
http://forum.xda-developers.com/android/software/ultimate-guide-compile-android-kernel-t2871276
EDIT: Thought I'd keep everyone abrest of my progress as a total newbie trying this out. I've used Ubunutu before, but had a lot of headaches trying to get my network working properly.
5:00pm: started the downloads of Ubuntu and Virtualbox. I have Hyper-V support (which is supposedly faster) on my desktop rig, but it has network issues, so I went with Virtualbox. Apparently, one of the things needed to create a kernel is a "toolchain". The guide uses "arm-eabi-4.33", but Phoenix and apparently sultan use gcc 4.8, so we'll go with that. But, how do I replace them? Can I just switch the git urls with this one I found of Google's toolchain?
5:30pm: got Ubuntu's 15.10 iso downloaded and VirtualBox installed. We'll figure out the toolchains later.
5:45pm: OK, Ubuntu is installing. I did the default on everything (2GB RAM, 8GB virtual hard disk). Booted up, installed it, and rebooted. "SQUASHFS errors" on first Ubuntu boot. The issues begin early, lol.
5:50pm: Checked the iso's MD5, matches up. Google'd around, but only random fixes that don't really fit (updating my BIOS? on a virtualbox?!). OK, let's try again with 3GB of RAM (my rig has 8GB) and 12GB of disk space.
5:55pm: "SquashFS errors" again. Whhhhhhhyyyy, Ubuntu, whyyyyyyyyy.
5:56pm: Hmm, what if I just shut down the virtual box and just try starting Ubuntu again?
5:57pm: HOLYCOWITWORKED. Thank you, Ubuntu--I love you.
5:58pm: Why is the resolution so small even though Ubuntu is installed? Everything is huge and my mouse is a little laggy.
6:05pm: OK, from a StackExchange post: you need "Guest Additions" to change the resolution. In the VirtualBox window (not in Ubuntu), you just click "Install Guest Additions" and it does its thing. It actually inserts the files as a virtual CD, haha. That's neat.
6:15pm: Trying to get the hang of "Right Control" as "host key". But, wait, why can't I copy/paste between my host and guest (copying all the commands from the guide linked above)? I feel like I had that last time I used VirtualBox. The Firefox in Ubunutu is really slow, too, and troubleshooting is mostly through Google right now, lol, and I don't want slow troubleshooting.
6:20pm: Oh, bidirectional copy/paste needs to be enabled. I see....
6:22pm: I FEEL LIKE A GOD NOW. I can copy and paste between TWO operating systems running my PC. WOWZA....I don't know what enromous amount of engineering that required, but it is a killer feature.
6:26pm: I'm trying to learn all the commands that the guide is using, just in case I mess up somewhere. What does the "-y" do in apt-get?
6:26:15pm: Thank you, random internet stranger many years ago, about telling me what a "man page" is. It's a simple website/HTML document that will actually explain all the arguments of a command. Great in interpreting the exotic arguments of cerebral StackExchange users....and what "-y" does in apt-get....
6:26:30pm: "-y" just hits "yes" to any prompts or whatever that apt-get invokes. Nice noob feature for people like me, haha. All right, I'm OK with that argument, let's do it!
6:30pm: Next, "mkdir"....well, that makes sense. But, where is it making this folder? How does it know where to put it????
6:33pm: Ah, so there is a "Home" folder that is the default folder. That's where it puts things. I made like 15 folders using "mkdir" and they all appear there.
6:40pm: Let's start! First, I need to grab sultan's kernel. OK, "git clone", let's do it!
6:41pm: "Git is not installed". These errors freak me out, but at least this one is minor, lol. OK: step zero, install git.
6:42pm: THE COMMAND WORKED! First success. But, wow, the kernel is a huge download (300MB+). Damn, wish I started this earlier in the background.
6:44pm: I wonder if I can start installing the other things, too. But, how? Can I open another terminal window?
6:45pm: Yes, you can open another terminal window and even a tab. But, should I install other things? Might that interfere with "git clone"? Why risk it? I mean, it took two hours to get just here...
6:46pm: Throwing caution to the wind. Opening TWO terminal windows and starting apt-get with the other stuff.
6:50pm: No errors so far...
6:55pm: woot! Everything downloaded, nice, nice. OK, the last thing: those toolchains. What even is a toolchain?
6:56pm: OK, a toolchain is basically like a list of directories and their location? Or something? It's like a default variable location "list" or something. Hmm...OK, Phoenix used gcc 4.8, so that's what we'll do!
6:58pm: But, wait, the instructions at the gcc toolchain page say I need the "Android GCC repository" and even more dependencies. But, the guide doesn't mention any of that. Is this specific to the Google one? Looks like more downloading...
6:59pm: Err, hold on. I don't want to BUILD the toolchain. I just want it cloned to my system....I don't need to build the toolchain, right? OK, let's just get the gcc repo first and then we'll see.
7:05pm: Ugh, another huge download. I'm down to 180MB of free space! What? How did I use 12GB already?
7:06pm: Oh, the HDD is only 9.6GB. I guess formatting takes away some of it and Ubuntu's install, too. OK, we'll resize the partition and call it night. To be continued later...
A brief update, as I'm too tired to annotate everything today, haha. The reason the guide uses Doom's toolchains is because they're prebuilt. So, I guess, we'll use those. I'm creating the updated dwc3_otg.c from all the patches, but the hunks are failing after the first patch. Will troubleshoot today by looking at the reject file and see what's being moved around.
EDIT: OK, I actually just opened the patch files. Looks like I just need the latest one to apply to sollapse's original patch. Patches 1/2 are almost identical (and sans full overhaul). Patch 3 is superseded by patch 4. So, just patch 4 is the one you need. Huh. Let's do it! ;D
This guide is great for understanding patch files.
sollapse said:
Wow, I've completely abandoned this hack since it's worked well enough for me . Also haven't had much time due to work and other necessities. Thanks for the patches @Phoenix Wright for cleaning up this hack! This should be a standard addition to all future Android kernels.
Click to expand...
Click to collapse
thanks for your work, it's awesome feature
is there some solution without a kernel compiling ? some custom rom or kernel image
stadnyuk said:
thanks for your work, it's awesome feature
is there some solution without a kernel compiling ? some custom rom or kernel image
Click to expand...
Click to collapse
Its already there in my kernel called lightning kernel check tht sig for the link and if you are on cm then there is another thread in original android dev section
nikhil18 said:
Its already there in my kernel called lightning kernel check tht sig for the link and if you are on cm then there is another thread in original android dev section
Click to expand...
Click to collapse
Thank you, I'll check it. I've installed sultanxda ROM with hope for future kernel updates, but there is some bugs and I think to return to stock CM
nikhil18 said:
Its already there in my kernel called lightning kernel check tht sig for the link and if you are on cm then there is another thread in original android dev section
Click to expand...
Click to collapse
Hi again, I'm stuck with lightning kernel(((
Can't flash it. I'm starting to think I'm completely noon.
Flashing over night build of CM12 the cm version of kernel(V15)
Wipe, flash, wipe
The result - stuck on one plus logo
Flashing again sultanxda ROM, wipe, kernel, gapps
The result - boot loop
Where is the problem? What I'm doing wrong?
Now I'm on a last night build, am I right that I need V15 cm version?
Thank you for helping
PS: I've realized I was flashing cm13 kernel version with cm12 ROM, so flashed sultanxda 12, v33 kernel version - loop boot

Android 6.0 Kernel root requirements.

Have a feeling I will figure this out before answered and probably some snide smartest person in the room syndrome remarks but could help save me and some others time so going to bite the bullet and ask anyway. With Android 6.0 what makes some Kernels compatible for root and others not. Have read some tidbits in otherwise unreliable sources it has to do with Selinux being set for permissive mode. If true is this in the Kernel or can it be set in the Ramdisk? Link to a commit would be extremely helpful.
Otherwise have 3 builds going now. If correct pretty sure one of the 3 will work but confirmation makes me feel better.
chairshot215 said:
Have a feeling I will figure this out before answered and probably some snide smartest person in the room syndrome remarks but could help save me and some others time so going to bite the bullet and ask anyway. With Android 6.0 what makes some Kernels compatible for root and others not. Have read some tidbits in otherwise unreliable sources it has to do with Selinux being set for permissive mode. If true is this in the Kernel or can it be set in the Ramdisk? Link to a commit would be extremely helpful.
Otherwise have 3 builds going now. If correct pretty sure one of the 3 will work but confirmation makes me feel better.
Click to expand...
Click to collapse
https://github.com/Elite-Kernels/elite_shamu/commit/c91d04bb34b327d66212090a0de36aa29bd6840b
Done in kernel
Sent from my Nexus 6 using Tapatalk
buckmarble said:
https://github.com/Elite-Kernels/elite_shamu/commit/c91d04bb34b327d66212090a0de36aa29bd6840b
Done in kernel
Sent from my Nexus 6 using Tapatalk
Click to expand...
Click to collapse
Thanks had worked out in one of the three I was testing using SuperSu 5.1. Why I am trying to school myself on new changes it seems I am now encrypted by default using the same files (fstab.shamu) that I used in 5.1.1. Are you aware of any changes now required for 6.0? admittedly am using the same Anykernel set up as I had with Lollipop and am new to using the Anykernel method for flashing kernels as in the past would just compile the boot.img. Honestly had been used to releasing my own Roms and not just Kernels so some of these things are new.
Sorry I am not ashamed to admit when something simple is throwing me for a loop and ask even if makes me look like a dumb ars.
chairshot215 said:
Thanks had worked out in one of the three I was testing using SuperSu 5.1. Why I am trying to school myself on new changes it seems I am now encrypted by default using the same files (fstab.shamu) that I used in 5.1.1. Are you aware of any changes now required for 6.0? admittedly am using the same Anykernel set up as I had with Lollipop and am new to using the Anykernel method for flashing kernels as in the past would just compile the boot.img. Honestly had been used to releasing my own Roms and not just Kernels so some of these things are new.
Sorry I am not ashamed to admit when something simple is throwing me for a loop and ask even if makes me look like a dumb ars.
Click to expand...
Click to collapse
to remove force encryption you need to change "forceencrypt" to "encryptable" in the fstab for userdata. This will not automagically decrypt you, so if you flashed factory images, you will be encrypted again. You will need to format data in TWRP to decrypt again.
I just pushed my anykernel to Github so could post but is pretty much what I had done. what I had done was working after either format data or performing a factory reset with 5.1.1. Starting to think maybe my factory image flash had gone wrong. Could just be a change I am not aware of but did not see the optimizing apps screen after wiping. What I had essentially done is after flashing factory image rebooted bootloader and before booting the first time flashed TWRP installed my Kernel, flashed SuperSu 5.1 and then did a full cache and data wipe.
Admittedly with anykernel I had started by downloading another Kernel, forget which one and then removed or adding what I believed should for my Kernel. So far besides the little encryption issue seems to be working out OK. Trying to keep the Kernel as effective as possible with the fewest possible trade off’s. Not much original work in the sense a lot has already been done but have done lots of testing for efficiency.
Anykernel
https://github.com/Starship-Android/anykernel
chairshot215 said:
Have a feeling I will figure this out before answered and probably some snide smartest person in the room syndrome remarks but could help save me and some others time so going to bite the bullet and ask anyway. With Android 6.0 what makes some Kernels compatible for root and others not. Have read some tidbits in otherwise unreliable sources it has to do with Selinux being set for permissive mode. If true is this in the Kernel or can it be set in the Ramdisk? Link to a commit would be extremely helpful.
Otherwise have 3 builds going now. If correct pretty sure one of the 3 will work but confirmation makes me feel better.
Click to expand...
Click to collapse
buckmarble said:
https://github.com/Elite-Kernels/elite_shamu/commit/c91d04bb34b327d66212090a0de36aa29bd6840b
Done in kernel
Click to expand...
Click to collapse
That is actually a *really bad hack*, since it disables selinux rather than manipulating the policy in an appropriate manner to make root usage possible.
The correct changes are actually *outside* of the kernel itself, in the sepolicy file in the ramdisk.
That sepolicy file is generated based primarily on what is in these repositories;
https://android.googlesource.com/platform/external/sepolicy/
https://android.googlesource.com/device/moto/shamu/+/master/sepolicy/
You see, there are some interesting commits, like this; https://android.googlesource.com/pl...243e5cf4f8898b7acedc24efd58fdcd163e3048^!/#F0
What that one does, is it tells selinux to never allow the sepolicy to be reloaded from the system_server context.
Or this one here, which does the same for the init context;
https://android.googlesource.com/pl...cy/+/6d0e9c8f4ee4f326b2c2851fa2851193fec33a4e
But note: partially reverted here;
https://android.googlesource.com/pl...abd409af0e7d7fb908e5f04fa1ed946e2996dce^!/#F0
That partial reversion actually provides a very useful HINT about it;
# Note: this requires the following allow rule
# allow init kernel:security load_policy;
# which can be configured on a device-by-device basis if needed.
In other words, add that line to this file;
https://android.googlesource.com/device/moto/shamu/+/master/sepolicy/init.te
Then *init* will re-gain the ability to change and reload selinux policies.
HOWEVER, instead of doing that, you might consider going a little further, by enabling THIS in a sortof-user-build;
https://android.googlesource.com/platform/external/sepolicy/+/master/su.te
... and adding domain_auto_trans from untrusted_app to su, and various other adjustments/tweaks.
I think that there is a neverallow rule in there somewhere that will complain if you make that change, so you'll have to kill the neverallow rule... yep, app domain:
https://android.googlesource.com/platform/external/sepolicy/+/master/app.te#286
**note: a neverallow rule is NOT a runtime enforcement directive. selinux defaults to block until a positive allow rule is created. The neverallow rules are used to annoy you when you try to build an sepolicy from source that violates something.
What *I* would do first, is fix that neverallow rule in app, add the auto-transition to su, and run a make bootimg for *USERDEBUG*. You probably should also edit the fstab a bit while you are at it to kill the "verify" parameter from /system, and swap the "forceencrypt" to "encryptable" for /data.
ALL of the changes (besides removing the neverallow rule) can be made in the shamu device tree.
This should produce a boot.img that relaxes selinux a bit to allow su. And from there, the su binary can be root.root/6755, WITH the file context set to su_exec, and you should have root back.... note: su daemon should *NOT* be required with these changes. In fact, you could even proof of concept using "cp /system/bin/sh /system/bin/su; chown root.root /system/bin/su; chmod 6755 /system/bin/su; chcon su_exec /system/bin/su" <-- you will have to look more at the chcon first parameter though, I haven't actually had to use it though, so I'm not entirely sure of what it expects as input. Note the boldness of "proof of concept"... it would be very... unsafe... to actually keep it like that on any device that you actually need to trust.
phhusson's new fork of superuser *should* be able to handle the job, with only minor adjustments to su.c's su_main() function where it is deciding to run connect_daemon() or su_main_nodaemon(). It would need to run su_main_nodaemon() with these changes.
So I've actually been working on this myself, since it is impossible to trust chainfire or his new employer (who is systematically buying up ALL of the root provisioning software for Android), and I have come up with this as an interim step;
Code:
diff --git a/app.te b/app.te
index 40de074..98bb663 100644
--- a/app.te
+++ b/app.te
@@ -283,7 +283,7 @@ neverallow appdomain { domain -appdomain }:process
# Transition to a non-app domain.
# Exception for the shell domain and the su domain, can transition to runas,
# etc.
-neverallow { appdomain -shell userdebug_or_eng(`-su') } { domain -appdomain }:process
+neverallow { appdomain -untrusted_app -shell userdebug_or_eng(`-su') } { domain -appdomain }:process
{ transition dyntransition };
# Write to rootfs.
diff --git a/domain.te b/domain.te
index 0f6c6da..b1d7c41 100644
--- a/domain.te
+++ b/domain.te
@@ -396,7 +396,7 @@ neverallow domain { file_type fs_type dev_type }:{ lnk_file fifo_file sock_file
# Nobody should be able to execute su on user builds.
# On userdebug/eng builds, only dumpstate, shell, and
# su itself execute su.
-neverallow { domain userdebug_or_eng(`-dumpstate -shell -su') } su_exec:file no_x_file_perms;
+neverallow { domain -init -untrusted_app userdebug_or_eng(`-dumpstate -shell -su') } su_exec:file no_x_file_perms;
# Do not allow the introduction of new execmod rules. Text relocations
# and modification of executable pages are unsafe.
diff --git a/init.te b/init.te
index 41eafe2..e7dd87a 100644
--- a/init.te
+++ b/init.te
@@ -123,7 +123,7 @@ allow init security_file:dir { create setattr };
# Reload policy upon setprop selinux.reload_policy 1.
# Note: this requires the following allow rule
-# allow init kernel:security load_policy;
+allow init kernel:security load_policy;
# which can be configured on a device-by-device basis if needed.
r_dir_file(init, security_file)
@@ -283,4 +283,5 @@ neverallow init shell_data_file:lnk_file read;
neverallow init app_data_file:lnk_file read;
# init should never execute a program without changing to another domain.
-neverallow init { file_type fs_type }:file execute_no_trans;
+allow init { file_type fs_type }:file execute_no_trans;
+allow init kernel:security read_policy;
diff --git a/keystore.te b/keystore.te
index 83a0e85..d742d30 100644
--- a/keystore.te
+++ b/keystore.te
@@ -24,7 +24,7 @@ selinux_check_access(keystore)
###
neverallow { domain -keystore } keystore_data_file:dir ~{ open create read getattr setattr search relabelto ioctl };
-neverallow { domain -keystore } keystore_data_file:notdevfile_class_set ~{ relabelto getattr };
+neverallow { domain -keystore -init } keystore_data_file:notdevfile_class_set ~{ relabelto getattr };
neverallow { domain -keystore -init } keystore_data_file:dir *;
neverallow { domain -keystore -init } keystore_data_file:notdevfile_class_set *;
diff --git a/su.te b/su.te
index d4a488b..1d1f6da 100644
--- a/su.te
+++ b/su.te
@@ -7,6 +7,7 @@ userdebug_or_eng(`
# wrapped to ensure that it does not exist at all on -user builds.
type su, domain, mlstrustedsubject;
domain_auto_trans(shell, su_exec, su)
+ domain_auto_trans(untrusted_app, su_exec, su)
# Allow dumpstate to call su on userdebug / eng builds to collect
# additional information.
diff --git a/vold.te b/vold.te
index b22436f..fa1a879 100644
--- a/vold.te
+++ b/vold.te
@@ -164,7 +164,7 @@ allow vold self:capability sys_chroot;
allow vold storage_file:dir mounton;
neverallow { domain -vold } vold_data_file:dir ~{ open create read getattr setattr search relabelto ioctl };
-neverallow { domain -vold } vold_data_file:notdevfile_class_set ~{ relabelto getattr };
+neverallow { domain -vold -init } vold_data_file:notdevfile_class_set ~{ relabelto getattr };
neverallow { domain -vold -init } vold_data_file:dir *;
neverallow { domain -vold -init } vold_data_file:notdevfile_class_set *;
neverallow { domain -vold -init } restorecon_prop:property_service set;
Some of those are what reverse engineering I've managed to accomplish on the policy changes required for supersu, and some of them are working towards a better root control infrastructure.
In any case, if you patch platform/external/sepolicy with that, then run a "make bootimage", it *WILL* actually work with supersu.
** note: make sure that you repo init against the android-6.0.0_r1 release branch if you want it to actually be compatible with factory builds. Master has a LOT of MAJOR changes since then and it does not work.
Also note: don't forget to patch platform/device/moto/shamu/fstab.shamu to kill the verify and optionally forceencrypt parameters.
I'm just going to leave these two links right here....
https://github.com/lbdroid/AOSP-SU-PATCH
https://github.com/phhusson/Superuser
That will yield an ENFORCING, and NON-RELOADABLE selinux policy, allowing root, and all bundled into the boot.img in order to maintain the integrity (dm-verity) of the system image!
Take THAT Coding Code Mobile Technology LLC!!!!!
And for people who want to know the true history of things (rather than worshiping people who distribute binaries....), please read this; http://www.koushikdutta.com/2008/11/fixing-su-security-hole-on-modified.html and then look at the github label (that says "forked from") on the Superuser repository I linked above.
doitright said:
I'm just going to leave these two links right here....
https://github.com/lbdroid/AOSP-SU-PATCH
https://github.com/phhusson/Superuser
That will yield an ENFORCING, and NON-RELOADABLE selinux policy, allowing root, and all bundled into the boot.img in order to maintain the integrity (dm-verity) of the system image!
Take THAT Coding Code Mobile Technology LLC!!!!!
And for people who want to know the true history of things (rather than worshiping people who distribute binaries....), please read this; http://www.koushikdutta.com/2008/11/fixing-su-security-hole-on-modified.html and then look at the github label (that says "forked from") on the Superuser repository I linked above.
Click to expand...
Click to collapse
Thanks I have been bed ridden for a bit but will look over all these things. In short my last build I first flashed chainfires boot.img and rooted before flashing my Kernel. Was able to do this without putting my Kernel into permissive mode. Had also unpacked the chainfire boot.img and used a few things in my boot image and used Meld and made a few other edits based on chainfires boot.img. Still having an issue with encryption being forced that just has me baffled. Was otherwise a temporary quick fix for not having to put the Kernel into permissive mode.
Definitely appreciate all the feedback and am learning allot so thanks for that everyone.
Otherwise the Encryption is driving me mentally insane. Like straitjacket throwing myself around a small room with rubber walls and a door with a slot that keeps opening with a tray of drugs and food sliding in insane. It has become so frustrating.
this is the fstab I am using and see know issue. Have also tried Despair, Vortex and the fed_patcher patch not to mention Chainfires Kernel for Root and no matter how many times I wipe data or factory reset it is always encrypted. If it was not knowing the encryption is done via software would swear something is wrong with the phone. Have also changed up TWRP 3 times as noticed I no loner see updating apps but that is also the same in that encription is still forced
https://github.com/Chairshot215/anykernel/blob/master/ramdisk/fstab.shamu
The problem you are running into, is that recovery doesn't actually *format* the userdata partition, which means that a factory reset from recovery won't *remove* the encryption. The reason it doesn't format is to prevent the deletion of /data/media directory, which gets mapped to /sdcard.
What you need to do, is reboot to bootloader, and run "fastboot format userdata".
If you aren't permissive, then the big thing you must have taken from chainfire's boot.img, is the sepolicy file. He only actually changed two files; sepolicy and fstab.shamu.
The thing to be aware of, though, is that his supersu, despite running selinux enforcing, is actually putting a lot of domains into permissive. When you go through your kernel audit log, you should pay attention to the end of the audit log where it says "permissive=1" or "permissive=0". You will find a lot of "permissive=1". Using *my* sepolicy, which is NOT compatible with his supersu, you will find that ALL domains remain enforcing, yet we aren't increasing the authority of any domain besides the "su" domain, AND, there will actually be far fewer denials against root/su. On top of that, I actually block the su domain from messing with kernel security. In other words, we do NOT allow the su domain to change selinux to permissive, OR to reload the policy. Both of those ARE permitted in chainfire supersu, which is incredibly dangerous, given how root is typically used on Android.
To put that into perspective, the ability to change the enforcement status or reload the policy, makes it possible for a malicious application to modify the boot.img to disable dmverity on the system partition, and compromise the system partition. My approach makes it possible to maintain the integrity of the boot partition and therefore maintain dmverity on the system partition, while providing root access. This makes unauthorized changes to the system partition immediately obvious and ineffective, since dmverity will refuse to read changed data, instead returning an i/o error.
The verity keys are actually stored on the boot.img, which means that it is still possible to make *intentional* changes to the system partition (through regenerating the key), and prevent unauthorized changes.
I've been considering adding a new domain to the effect of "su_sensitive" that will enforce strong password input for every authorization request in order to grant kernel security permission, but it remains to be seen if this would even be helpful to anyone.
How do you even edit a kernel? If you could explain, please do so.

Categories

Resources