Root any android with adb

Root any android with adb Техника

Root any android with adb

Быстроman как получить root-права на Android смартфоне. Я буду использовать OnePlus 3 и Android 8.0, но инструкция должна подойти и к другим устройствам.

So, that’s it guys I hope you found this guide useful and you are able to root your phone. If you encounter any problems do not hesitate to ask anything in the comment section down below. And I will try my best to help you out.

See you in the next guide 🙂

Ezoic

Содержание
  1. Disclaimer
  2. Что такое Root?
  3. Зачем это нужно?
  4. Какие минусы и опасности получения прав суперпользователя?
  5. Как получить root на моем устройстве?
  6. Что делать, если Root так и не был получен?
  7. Feedback? Questions? Suggestions?
  8. Set the Android to insecure
  9. Is Your Phone Bootloader Unlockable?
  10. Steps- 1: Boot your phone into Bootloader Mode
  11. 1st Method: Boot your phone into Bootloader Mode
  12. 2nd Method: Boot your phone into Bootloader Mode
  13. Steps- 2: Connecting Phone to PC Using ADB and Fastboot commands
  14. Steps- 3: Unlocking the Bootloader of your phone
  15. Steps- 4: Rooting your phone
  16. Method-1: Rooting Android Using Boot Image Patching
  17. Method-2: Rooting Android Using TWRP Recovery
  18. Подготовка
  19. Open a root shell on you device
  20. Unpacking the root file system
  21. Unlock the Boot-loader
  22. Why root Android Phones?
  23. Install superuser
  24. Предисловие
  25. Install custom recovery
  26. Selinux
  27. Compile the boot image
  28. Install Android Oreo
  29. 1. Unlock bootloader
  30. No warranty after rooting the device
  31. Boot the device in Insecure mode
  32. Obtaining the boot image
  33. Unpacking the boot image
  34. How to gain root access on an Android device
  35. Steps
  36. Разблокировка загрузчика
  37. Download and install the device USB driver
  38. Pack the root file system
  39. It didn’t work?!
  40. Download ADB, Fastboot & phone’s USB drivers
  41. Table of Contents
  42. Conclusion
  43. Frequently Asked Questions
  44. Which Android devices are easy to root?
  45. Why would you root an Android?
  46. What are the risks of rooting a phone?
  47. Can you root an Android phone without a computer?
  48. how to root android phone without any app
  49. how to root Android phone without pc
  50. Can I root my phone for free?

Disclaimer

This tutorial is quite old and more to serve as inspiration, than a step by step guide. Much have changed in the Android system, and more potent tools are available nowadays (such as «abootimg» included in many GNU/Linux distributions).

Looking to root your Android phone? Learn how to safely and effectively root your device using Windows and Linux in this detailed guide.

Most of us can’t live a day without our phones. Especially for those using Android. After looking at the history of smartphones, we all get amazed at how quickly Google has developed such a powerful Operating system, Android. Today most of us have Android phones and use them as much as we can. Some even want to go beyond and root their Android phones to extend their functionalities.

So if you’re one of them and don’t like requesting somebody to “root Android phone”, here is the article. In this article, I’ll be talking about what is Android rooting, the benefits, and the steps to rooting your Android device.

Do you guys want to root your phone? Yes, then you are in the right place. Today in this article I will show you how you can Root any Android phone in 2023 and also we are going to look at how to root any Oneplus Google or Chinese or any other generic Android phone you might have.

I will show you two methods to root your phone in this guide the first method is by boot image patching which is a bit complicated process but safer and the other method is by using TWRP which is easier but less safe.

Please do note that throughout this guide I will make use of the terms fastboot and bootloader and you should keep in mind that they are basically the same thing and I may use anyone of the term to describe the same thing.

How To Root Any Android Phone

I have also used terms like terminal and minimal ADB and fastboot terminal is basically for a Mac and minimal ADB and fastboot is for Windows. So, if ever I say that open terminal that means you should open terminal if you are using a Mac, and if you are using a Windows then you should open minimal ADB and fastboot and vice versa.

Rooting Guides for Specific Devices

  • Is Your Phone Bootloader Unlockable?
  • Steps To Root Any Android Phone 2023
    • Steps- 1: Boot your phone into Bootloader Mode
    • Steps- 2: Connecting Phone to PC Using ADB and Fastboot commands
    • Steps- 3: Unlocking the Bootloader of your phone
    • Steps- 4: Rooting your phone
  • Wrapping Up

Регистрация: 6 лет назад

Регистрация: 6 лет назад

Регистрация: 6 лет назад

Получение ROOT прав на прошивке 4.4.4. программой newroot.exe для разблокированного (заблокированного) загрузчика.

Первоначально программа написана для Z1, но работает и на Z Ultra.

  • ADB драйвера для нашего устройства;
  • Настройки -> Функции для разработчиков -> Отладка по USB (должна стоять галочка);
  • Отключите антивирус на ББ;
  1. Скачать и распаковать программу (см. ниже);
  2. Подключите смартфон к ББ;
  3. Нажмите «Check this to root your phone»;
  4. Согласится со всеми условиями на экране смартфона;
  5. Дождаться перезагрузки смартфона. После перезагрузки у Вас появится приложение «Суперпользователь». Вам остается только установить SuperSU из Маркета и удалить «Суперпользователь»;
  6. Наслаждайтесь!

Регистрация: 6 лет назад

SRSRoot (получение рут для Android OS 1.5-4.2)

Очередная малоизвестная утилита для получения ROOT.

Файл загружен в архив, alstrive.ru

Получение ROOT Sanei N10-QM (Android 4.1.2)

Прошивка модуля связи: FW8955m-V1.1.7.0

Версия ядра: 3.4.0+

Номер сборки: V4.1.1.0-SANEI-V01

Root any android with adb

Регистрация: 6 лет назад

Root для ICS без бута, для всех смартфонов с андроид 4.0.X (самому проверить не на чем, так что надежда на вас, владельцы ICS).

Как получить ROOT-права

  1. Распаковываем архив на диск С в компьютере, подключаем смартфон.
  2. Запускаем bat файл
  3. Нажимаем Enter, тело перегружается
  4. Нажимаем еще раз Enter, и тело еще раз перезагружается
  5. Нажимаем в последний раз Enter, тело перезагружается уже с рутом.
    Клавишу Enter нажимать только после полной загрузки девайса.

p.s. Отладка по юсб и режим накопителя, а также установленные драйвера на ББ для вашего смартфона обязательны!

Регистрация: 6 лет назад

Root-права на Android 7 и Android 8

  1. Для начала (на некоторых моделях) следует ;
  2. В настройках смартфона, среди функций «режима разработчика» необходимо включить отладку по USB;
  3. Затем прошить в устройство кастомное рекавери (обычно TWRP — необходимо скачать версию именно для вашего устройства).
    Например, для моделей Samsung поможет — программа Odin;
  4. И на последнем шаге — установить файл для Root-прав (в основном это SuperSU.zip) с помощью установленного рекавери TWRP;
  5. смартфон или планшет — и теперь Вы администратор своего андроид-гаджета (рут установлен).

If I’m understanding your question correctly, you’re asking how to get root access automatically when you run adb shell, so that you don’t have to go into the shell and type su to execute a command as root on your phone.

This is controlled by a flag in your boot partition, which most custom ROMs have modified to allow root permission by default. If you get dropped to a $ when you use adb shell then you have two permanent options and one temporary one (temporary meaning that it doesn’t stick if you reboot):

  1. Flash a ROM that includes the modification
  2. Create a custom boot.img and flash it to your phone
  3. Restart adbd on your device with root permissions

Number 2 is actually not that difficult, but it can be somewhat dangerous if you’re careless. There is a wiki article here which explains the process and includes a couple of Perl scripts to help you. These instructions assume a Linux/Unix environment. I have personally used these instructions on Fedora Linux and can tell you that they work, but I do not know about other *nix environments like Macs. I also do not know of any similar Windows instructions, but I could try to track some down if you are on Windows. The exact commands will vary somewhat from phone to phone since different devices use different partition tables.

Generally speaking, though, you need to pull your current boot.img from your phone, unpack it, extract the ramdisk, and find the default.prop file. This is a plaintext file, which you need to open in a text editor and then find the line that contains the value ro.secure. If the line says ro.secure=1 then you need to change it to ro.secure=0. After that you can re-pack the ramdisk and boot.img, then flash it to your phone. Once you reboot, you will be greeted with a # prompt whenever you perform adb shell without having to run su.

Alternatively, if you are using a custom ROM but it doesn’t have this modification, you can just unzip the ROM and modify the boot.img that is included with it using the above steps. Then you can zip up the ROM with the newly modified boot.img and flash the zip file as you normally would.

This probably goes without saying, but be careful when doing this. Messing with your boot partition can quite easily wreck your phone and force you to recover via HBoot. I would highly recommend testing Fastboot to makes sure you can use extended Fastboot commands and perform a recovery. This varies a bit based on your model, but most phones have some sort of desktop software that can be run to reflash the phone as well.


Уровень сложности: для продвинутых. Несмотря на то, что операционная система Android является гораздо более открытой, чем большинство конкурентов, все же в ней тоже существуют свои запреты и ограничения. Обычному пользователю не позволят бесцеремонно вмешиваться в работу системных программ, удалять важные файлы или делать потенциально опасные настройки. Однако, все эти возможности становятся доступны в том случае, если владелец получает права суперпользователя или так называемый root. В этой статье мы расскажем, какие дополнительные возможности это дает, чем опасно и как это сделать.

Что такое Root?

Рутирование устройства означает получение прав суперпользователя, что примерно соответствует аналогичному понятию из мира Linux. Благодаря этому вы сможете выполнять практически любые действия, в том числе потенциально опасные. Другими словами, это получение полного контроля над своим устройством.

Зачем это нужно?

Среди преимуществ можно выделить следующее:

  • получение доступа и возможность изменения системных файлов и приложений;
  • возможность установки множества приложений, которые требуют для своей работы root:
  • установка сторонних прошивок и модов;
  • удаление предустановленных программ и прочего мусора;
  • активация многих дополнительных функций Android;
  • увеличение производительности и автономности с помощью специальных программ и твиков.

Какие минусы и опасности получения прав суперпользователя?

В Интернете достаточно страшилок по этому поводу и некоторые из них имеют под собой почву. Итак, среди недостатков root замечены следующие:

  • это лишает вас гарантии (на самом деле все признаки этой операции можно устранить);
  • вы не сможете получать обновления по воздуху от производителя;
  • в некоторых случаях процедура получения прав суперпользователя грозит выходом из строя вашего устройства (но чаще всего гаджет можно оживить).

Как получить root на моем устройстве?

Процедура получения прав суперпользователя, как правило, не сложная и при внимательном выполнении всех инструкций проходит без всяких проблем. Более того, создано несколько универсальных утилит, которые автоматизируют этот процесс и делают доступным даже самым начинающим пользователям. Одной из самых известных является Framaroot. Эта программа позволяет рутировать очень большое количество разных устройств. И даже если название вашего гаджета отсутствует в списке поддерживаемых, все равно имеет смысл попробовать, так как есть довольно большая вероятность получения root, а негативных последствий точно не будет.

Итак, для получения root с помощью программы Framaroot необходимо выполнить следующие действия.

2. Установите программу из загруженного apk-файла на свое устройство.

Как получить Root в Android и стоит ли это делать

3. Запустите утилиту. В том случае, если устройство поддерживается программой, то на главном экране вы увидите выпадающий список возможных действий, среди которых есть варианты для получения и удаления root. Кроме этого, чуть ниже имеется одно или несколько названий эксплоитов, которые доступны для применения.

Как получить Root в Android и стоит ли это делать

4. Тапните по одному из доступных эксплоитов и через пару секунд появится подсказка, описывающая результаты его работы. Если один способ не срабатывает, то попробуйте другой. Иногда бывает, что при получении прав суперпользователя Framaroot аварийно закрывается. В этом случае просто перезапустите программу и попробуйте еще раз.

Как получить Root в Android и стоит ли это делать

5. Как только вы получите подсказку, что устройство успешно рутировано, следует перезагрузить устройство.

Что делать, если Root так и не был получен?

Framaroot является достаточно универсальной программой, но даже она не может обеспечить успешную работу на всем спектре Android-устройств. В этом случае посетите форум нашего сайта, найдите тему, посвященную вашему устройству и там вы, скорее всего, обнаружите очень подробные и действенные инструкции, посвященные получению прав суперпользователя именно на вашем смартфоне или планшете.

ADB — приятно познакомиться!
добавлен документ Adobe Acrobat (.pdf) с картинками ввода команд :good:

В жизни андроида есть две немаловажные вещи, Точнее режима — ADB и Fastboot.

ADB — режим, который доступен вам, как говорилось выше, из-под Android SDK. Выполняет он много функций

Начнем с установки и настройки ADB. И все что вам пригодится в этом деле:
Как установить ADB/USB драйвера для Android устройств

Настройка Android SDK

Скачиваем файл (sdk) выше
Распаковываем на рабочий стол
Берем «android-sdk-windows» папку и кидаем ее в корень вашего системного диска (C:\)

Правый клик на «Мой компьютер» и жмем на свойства
Выбираем закладку «Дополнительно» либо «Дополнительные настройки» (или что-то в этом роде) (Vista/Windows 7)
Там выбираем «Переменные среды» (англ. — Environment Variables)
Нажимаем создать

Название переменной: adb
Значение: C:\android-sdk-windows\tools

Подготовка вашего телефона к ADB

В вашем телефоне идем в настройки (Settings)
Выбираем Приложения (Applications)
Выбираем Разработка (Development)
Убедитесь что ‘USB Debugging’ отмечено галочкой (Т.е. включено)

Подключите ваш телефон через USB и НЕ МОНТИРУЙТЕ SD!
Ваш компьютер должен обноружить новое устройство, после чего он сам попытается установить Android 1.0 driver
Пускай он это сделает
Если же не находит, то нажмите «Установить драйвер вручную»
Драйвер который нам необходим расположен в папке с вашим Android SDK 1.5r2 (C:\android-sdk-windows\usb_driver)
После чего ваше устройство ADB Android должно быть установленно! Возьмите с полки пирожок
Для Android SDK 1.5r3+

Дополнительно:  Common Latin and Greek Word Roots

Проверяем обнаруживает ли ADB ваш телефон:

Открываем команандную строку (Выполнить -> cmd -> enter)
И введите:

Введите в cmd команду adb (без ничего), и нажмите enter. Ниже вы увидите все команды доступные в данном режиме
Поздравляю! Вы закончили с установкой и с настройкой ADB !:-)
Список всех ADB команд:
-d — directs command to the only connected USB devic
e
returns an error if more than one USB device is
present.
-e — directs command to the only running emulator.
returns an error if more than one emulator is r
unning.
-s <serial number> — directs command to the USB device or emulator w
ith
the given serial number
-p <product name or path> — simple product name like ‘sooner’, or
a relative/absolute path to a product
out directory like ‘out/target/product/sooner’.

If -p is not specified, the ANDROID_PRODUCT_OUT

environment variable is used, which must
be an absolute path.
devices — list all connected devices

adb help — show this help message
adb version — show version num

— If <directory> is not specified, both /system and /data partitions will be u
pdated.

— If it is «system» or «data», only the corresponding partition
is updated.

Пример ввода команд

adb push
Пример — adb push c:\app.apk /data/app

adb pull
Пример — adb pull /data/app_s/Stock.apk

adb install
Пример — adb install c:/apps/apps2sd.apk

adb uninstall
Пример — adb uninstall linda.apk

Как сохранить заводскую прошивку?!
ИНСТРУКЦИЯ:
Как сделать бэкап прошивки (например, чтобы сохранить заводскую): (ТЕЛО ДОЛЖНО БЫТЬ )

В папке ADB находится файл backup.bat

Выставить на теле USB debug -> ON
Так же желательно включить на телефоне режим, при котором экран не гаснет при зарядке (там же, где включается USB debug)

Присоединить тело по USB.
Запустить backup.bat

Подтвердить на теле Root Access.
После этого через пару минут на Sd карте — файлы Вашей прошивки!

Теперь необходимо запаковать полученные файлы factoryfs.rfs, zImage и modem.bin в архив tar.
В этот же tar можно запихнуть файл datafs.rfs, взятый из любой прошивки (желательно того-же «поколения» 2.1 или 2.2, что и Ваша )
В результате получится TAR, полностью совместимый с флэштулом ODIN и в любой момент Вы можете вернуть телефон в девственное состояние.
На всякий случай после прошивки желательно сделать вайп или из рекавери, чтобы отформатировать кэш (cache)

Как запихивать в TAR :

Я делаю ТАРы Cygwin-ом.Но можно извратиться следующим способом.
В TotalCommander ставим плагин для TAR.Открываем ЛЮБОЙ готовый TAR. Добавляем СВОЙ файл, а всё остальное — удаляем!

То же самое можно сделать из Терминала или Putty (по SSH):
Для этого в папке ADB есть скрипт backup.sh

Скопировать его на тело в /data

В Терминале или Putty:

su (только для Терминала!)
chmod 755 /data/backup.sh/data/backup.sh

СПОСОБ ДЛЯ ТЕХ, КТО «НИ БУМ-БУМ» в ADB, но умеет набирать текст на клавиатуре.

Все делается прямо на телефоне через Эмулятор Терминала. Описано шаг за шагом. НЕ СПЕШИ, А ТО УСПЕЕШЬ!
Что нужно: Root, эмулятор терминала, свободное место на SD Card >300 Mb.
Требование к пользователю: Руки хотя бы мутно напоминающие прямоту, Спокойное расположение духа, Сосредоточенность.
При вводе команд в терминале всегда дожидайтесь ответа терминала (на каждую команду он всегда отвечает). Пока не дождались — не вводите ничего. Просто ждите.

Итак, приступим. (Учитывая что уже есть Root и Эмулятор Терминала на телефоне)

Если сильно за него боитесь, то заныкайте несколько копий в разные места.

FAQ «Как восстановить заводскую прошивку»

Что нужно: Odin Multi Downloader, любая официальная прошивка запакованная одним TAR-архивом, файлы бэкапа вашей заводской прошивки (файлы zImage, modem.bin, factoryfs.rfs)
Требование к пользователю: Руки хотя бы мутно напоминающие прямоту, Спокойное расположение духа, Сосредоточенность.
Итак, приступим.

Прикрепленные файлы
Прикрепленный файл Better_Terminal_Emulator_Pro_v4.04.apk
Прикрепленный файл jackpal.AndroidTerminalEmulator.1.0.21.apk

Прикрепленный файлРабота с ADB.pdf ( 447.42 КБ )

Сообщение отредактировал sask — 14.03.18, 14:44

Для того, чтобы в телефон можно было заливать модифицированные образы нужно разблокировать бутлоадер.

ВНИМАНИЕ!! при разблокировке или блокировке бутлоадера пользовательские данные теряются!!!!

Устанавливаем adb-tools

sudo apt-get install android-tools-adb android-tools-fastboot

Включаем в Developer Options опцию USB Debugging.

В Developer Options включаем OEM Unlocking.

Включаем телефон и подключаем к компу. Телефон спросит — можно ли использовать с этим компьютером USB Debug — отвечаем Yes.

Теперь перезагружаем телефон в режим бутлоадера. Для этого при подключенном к компу телефоне (включенном) выполняем

adb reboot-bootloader

Либо выключаем телефон, зажимаем Vol+ и PowerButton. Появится меню, в котором кнопкой Vol+ нужно выбрать fastboot и нажать Vol-.

После того, как на телефоне появится надпись FASTBOOT MODE на компе выполняем:

fastboot oem unlock

В результате компьютер скажет:

(bootloader) Start unlock flow
OKAY

То есть теперь бутлоадер разлочен и мы можем прошивать новые прошивки через него.

Перезагружаем телефон в режим бутлоадера (fastboot):

adb reboot-bootloader

Например, для того, чтобы прошить flash-блок system (в котором лежит собственно android) — подключаем аппарат к компу и выполняем:

fastboot flash system system.img

Эта команда прошьет блок с названием system файлом-образом system.img из текущего каталога. Аналогично прошиваются recovery и boot:

fastboot flash boot boot.img
fastboot flash recovery recovery.img
fastboot reboot

Или перезагружаем его в recovery

fastboot reboot recovery

Для того, чтобы можно было загружать модицицированный system.img, нужно отключить проверку образа dm-verity. Это делается путем редактирования образа boot.img.
Распаковываем boot.img с помощью AIK-Linux:

./unpackimg.sh ./boot.img

Из распакованного ramdisk удаляем файл verity_key

sudo rm ./ramdisk/verity_key

В файле ./ramdisk/fstab.mt6735 отключаем verify:

sudo sed -i '/\/system/ s/,verify//' ./ramdisk/fstab.mt6735

В файле ./ramdisk/default.prop меняем значение параметра ro.secure=1 на 0, меняем ro.debuggable=0 на 1 и добавляем строку ro.config.dmverity=false:

sudo sed -i '/ro.secure/ s/1/0/' ./ramdisk/default.prop
sudo sed -i '/ro.debuggable/ s/0/1/' ./ramdisk/default.prop
echo 'ro.config.dmverity=false' | sudo tee -a ./ramdisk/default.prop
sudo ./repackimg.sh

И прошиваем в телефон:

adb reboot-bootloader
fastboot flash boot ./image-new.img
fastboot reboot
wget https://storage.googleapis.com/google-code-archive-downloads/v2/code.google.com/android-serialport-api/android_bootimg_tools.tar.gz
tar -xvf ./android_bootimg_tools.tar.gz
mkdir ./boot
./unpackbootimg -i ./boot.img -o ./boot/

В результате в папке ./boot будут файлики. И среди них два:

Чтобы распаковать ram-диск делаем так:

gunzip -c boot.img-ramdisk.gz | cpio -i
cd
find . | cpio -o -H newc | gzip > ../newramdisk.cpio.gz
./unpackbootimg -i ./boot.img -o ./boot
cd boot
mkdir ./ramdisk
cp ./boot.img-ramdisk.gz ./ramdisk/
cd ramdisk/
gunzip -c boot.img-ramdisk.gz | cpio -i
rm -f ./boot.img-ramdisk.gz
sed -i '/\/system/ s/,verify//' ./fstab.mt6735
rm -f ../boot.img-ramdisk.gz
find . | cpio -o -H newc | gzip > ../boot.img-ramdisk.gz

В файлике default.prop нужно сделать так:

ro.secure=0
ro.debuggable=1
persist.service.adb.enable=1

Выполняется как-то так:

./mkbootimg --kernel ./boot.img-zImage --ramdisk ./boot.img-ramdisk.gz --base 40078000 --cmdline 'bootopt=64S3,32N2,64N2' --pagesize 2048 -o ../newboot.img

boot.img перепакованый таким образом нормально загружается, (даже не подписаный сертификатом) только в том случае, если не вносились изменения (не перепаковывался) initrd.img. Это значит, что secureboot проверяет initrd.img.

sudo apt-get install abootimg
abootimg -x ./boot.img
abootimg-unpack-initrd

Команда abootimg-unpack-initrd распакует файл initrd.img из текущей директории в папку ramdisk. После внесения изменений в файлы можно упаковать все обратно.

rm ./initrd.img
abootimg-pack-initrd

Команда abootimg-pack-initrd упакует содержимое папки ramdisk в файл ./initrd.img

Теперь можно всё собрать обратно в newboot.img.

abootimg --create newboot.img -f ./bootimg.cfg -k ./zImage -r ./initrd.img
abootimg -x ./boot.img
abootimg-unpack-initrd
#sed -i '/\/system/ s/,verify//' ./ramdisk/fstab.mt6735
rm ./initrd.img
abootimg-pack-initrd
abootimg --create newboot.img -f ./bootimg.cfg -k ./zImage -r ./initrd.img
openssl genrsa -f4 -out verifiedboot.pem 2048
openssl pkcs8 -in verifiedboot.pem -topk8 -outform DER -out verifiedboot.pk8 -nocrypt
openssl req -new -x509 -sha256 -key verifiedboot.pem -out verifiedboot.x509.pem
openssl x509 -outform DER -in verifiedboot.x509.pem -out verifiedboot.x509.der
java -jar BootSignature.jar /boot newboot.img verifiedboot.pk8 verifiedboot.x509.der boot_signed.img
java -jar BootSignature.jar -verify boot_signed.img
adb reboot-bootloader
fastboot flash boot ./boot_signed.img
fastboot reboot

Скачиваем отсюда super-su: https://download.chainfire.eu/supersu-stable

http://www.mtkfirmware.com/content/linux-commands-instructions-tools-unpacking-and-repacking-system-images-mtk-devices-ext4-and

http://www.mtkfirmware.com/sites/default/files/dev-tools/img-tools_0.zip

http://4pda.ru/forum/lofiversion/index.php?t660562-40.html

https://www.tinkerboarding.co.uk/forum/thread-347-post-1216.html

https://tinkerboarding.co.uk/forum/archive/index.php/thread-264.html

https://nelenkov.blogspot.ru/2014/05/using-kitkat-verified-boot.html#!/2014/05/using-kitkat-verified-boot.html — вот тут про verity.

https://forum.xda-developers.com/android/general/cofface-filecontexts-bin-filecontexts-t3669824

При внедрении в образ system.img файлов SuperSU нужно прописать их в SELinux. База данных SELinux хранится в образе boot.img, в файлике file_contexts.bin. После извлечения, файл file_contexts.bin нужно распаковать для внесения в него изменений с помощью утилиты sefcontext, а затем запаковать обратно и пересобрать образ boot.img.

Образ system.img нужно распаковать с помощью img-tools, смонтировать образ и добавить в него файлы SuperSU, а затем запаковать его обратно.

Итак.

В отдельную папку (меня это пака ~/AIK-Linux)распаковываем Android Image Kitchen кладем туда boot.img и распаковываем его:

./unpackimg.sh ./boot.img

Из папки ./ramdisk забираем файлик file_contexts.bin и кладем его в папку с утилитами img-tools, sefcontext и образом system.img — у меня это папка ~/s30mini/.

cp ./ramdisk/file_contexts.bin ../s30mini/

Теперь с помощью скрипта перепаковываем system.img и вносим изменения в file_contexts.bin:

#!/bin/bash
SuperSU_PATH="/mnt/hdd/Downloads/UPDATE-SuperSU-v2.82-20170528234214"
cd ~/img-tools/
./simg2img ./system.img ./system.raw
sudo mkdir /system
sudo mount -t ext4 -o loop ./system.raw /system/
mkdir boot
cp ./boot.img ./boot/
cp ./unpackbootimg ./boot/
cd ./boot
./unpackbootimg -i ./boot.img -o ./
gunzip -c boot.img-ramdisk.gz | cpio -i
cd ..
./sefcontext -o ./file_contexts ./boot/file_contexts.bin
sudo mkdir --parents /system/app/SuperSU && sudo cp $SuperSU_PATH/common/Superuser.apk /system/app/SuperSU/SuperSU.apk
sudo chmod 0644 /system/app/SuperSU/SuperSU.apk
echo "/system/app/SuperSU/SuperSU.apk u:object_r:system_file:s0" >> ./file_contexts
sudo cp $SuperSU_PATH/common/install-recovery.sh /system/etc/install-recovery.sh
sudo chmod 0755 /system/etc/install-recovery.sh
echo "/system/etc/install-recovery.sh u:object_r:toolbox_exec:s0" >> ./file_contexts
sudo cp $SuperSU_PATH/arm64/su /system/xbin/su
sudo chmod 0755 /system/xbin/su
sed -i '/^\/system\/xbin\/su/d' ./file_contexts
echo "/system/xbin/su u:object_r:system_file:s0" >> ./file_contexts
sudo mkdir /system/bin/.ext
sudo cp $SuperSU_PATH/arm64/su /system/bin/.ext/.su
sudo chmod 0755 /system/bin/.ext/.su
echo "/system/bin/.ext/.su u:object_r:system_file:s0" >> ./file_contexts
sudo cp /system/xbin/su /system/xbin/daemonsu
echo "/system/xbin/daemonsu u:object_r:system_file:s0" >> ./file_contexts
sudo cp /system/xbin/su /system/xbin/sugote
echo "/system/xbin/sugote u:object_r:zygote_exec:s0" >> ./file_contexts
sudo cp $SuperSU_PATH/arm64/supolicy /system/xbin/supolicy
sudo chmod 0755 /system/xbin/supolicy
echo "/system/xbin/supolicy u:object_r:system_file:s0" >> ./file_contexts
sudo cp $SuperSU_PATH/arm64/libsupol.so /system/lib64/libsupol.so
sudo chmod 0755 /system/lib64/libsupol.so
echo "/system/lib\(64\)/libsupol.so u:object_r:system_file:s0" >> ./file_contexts
sudo touch /system/etc/.installed_su_daemon
sudo chmod 0644 /system/etc/.installed_su_daemon
echo "/system/etc/.installed_su_daemon u:object_r:system_file:s0" >> ./file_contexts
sudo cp /system/bin/sh /system/xbin/sugote-mksh
sudo chmod 0755 /system/xbin/sugote-mksh
echo "/system/xbin/sugote-mksh u:object_r:system_file:s0" >> ./file_contexts
sudo cp /system/bin/app_process32 /system/bin/app_process32_original
sudo chmod 0755 /system/bin/app_process32_original
echo "/system/bin/app_process32_original u:object_r:zygote_exec:s0" >> ./file_contexts
sudo mv /system/bin/app_process /system/bin/app_process_original
sudo chmod 0755 /system/bin/app_process_original
echo "/system/bin/app_process_original u:object_r:zygote_exec:s0" >> ./file_contexts
sudo mv /system/bin/app_process32 /system/bin/app_process_init
sudo chmod 0755 /system/bin/app_process_init
echo "/system/bin/app_process_init u:object_r:system_file:s0" >> ./file_contexts
sudo mv /system/bin/app_process64 /system/bin/app_process64_original
sudo chmod 0755 /system/bin/app_process64_original
echo "/system/bin/app_process64_original u:object_r:zygote_exec:s0" >> ./file_contexts
sudo ln -s /system/xbin/daemonsu /system/bin/app_process
sudo ln -s /system/xbin/daemonsu /system/bin/app_process32
sudo ln -s /system/xbin/daemonsu /system/bin/app_process64
sudo rm -f /system/bin/install-recovery.sh
sudo ln -s /system/etc/install-recovery.sh /system/bin/install-recovery.sh
SYSTEM_RAW_SIZE=$(stat --printf="%s" ./system.raw)
sudo ./make_ext4fs -s -l $SYSTEM_RAW_SIZE -S ./file_contexts -a system newsystem.img /system/
sudo umount /system
sudo chmod a+rw ./newsystem.img
sudo rm -f ./system.raw
sudo rm -Rf ./boot
sudo rm -f ./file_contexts
sudo rm -Rf /system

Переносим новый file_contexts.bin в рамдиск boot.img и упаковывавем boot.img.

echo '' | sudo tee ~/AIK-Linux/ramdisk/file_contexts.bin
sudo dd if=./new_file_contexts.bin of=~/AIK-Linux/ramdisk/file_contexts.bin

Feedback? Questions? Suggestions?

This tutorial too basic? Too complicated? Inaccuracies? Did not work as expected?

Please feel free send me a mail!

/By Mikael Q Kuisma

Set the Android to insecure

Android got a security feature you can turn on or off. Usually this should be enabled for production environment and disabled for development devices. By turning security off, you can gain root access.

  • Edit /default.prop in the root file system and set the property "ro.secure=0".

Is Your Phone Bootloader Unlockable?

Now you must check whether your phone is bootloader unlockable or not so make sure that you have read this article on how to check if your phone is bootloader unlockable or not also make sure that you have installed the USB drivers and also have set up ADB and fastboot on your Windows or Mac.

Once you know that your phone is spooler unlockable then you should continue with this tutorial or else you can ask for help in the comment section down below.

Please note that unlocking bootloader may void your warranty and will wipe all the data on your phone. so, make sure that you have made a backup before proceeding.

Now let’s see how to unlock the bootloader on your phone.

Below I have shown you step by step procedure to root any Android phone that supports Bootloader unlocking.

Steps- 1: Boot your phone into Bootloader Mode

  • The first thing you do is you need to open your phone and then Go to Settings.
  • Then go to About Phone and then look for Build Number and tap seven times on Build Number to Enable the Developer Options.
  • Now go back to Settings and then go to Developer Options and Enable OEM Unlocking to enter the password if it asks you for a password.
  • Scroll down and you will also see an option called USB debugging tap on it to enable it.
  • Now once you have done that you need to boot your phone into bootloader mode so follow the below steps.
  • First Power Off your phone.

1st Method: Boot your phone into Bootloader Mode

  • Now here comes the tricky our different phones will have different but in combination to boot into bootloader mode. So, you need to find the right combination for your phone for most phones out there the button combination is Volume Up + Power Button.
  • While for some other phones it is Volume Down + Power Button or if you don’t want to use any button combination you can just use the ADB command to boot your phone directly to boot the Bootloader mode.

2nd Method: Boot your phone into Bootloader Mode

  • Connect your phone to the PC.
  • Then you need to open the terminal and type the below command.
adb reboot bootloader
  • Hit enter and this will ask you for permission on your phone then just allow the permission.
  • Now it should boot your phone into bootloader mode.

However, if you are using the button combination then you need to do is you need to press the Power button + Volume Up button or Power button + Volume Down button whichever works for your phone.

Now for some phones, this button combination will not directly take them to the bootloader mode instead it will take them to the boot menu. So, if you end up in the boot menu then you should look for the option called boot into bootloader.

Then you should use your volume keys to browse through the option and then select the option which says reboot into bootloader and select with the power button and it should boot your phone into bootloader mode.

If you have any problems then please ask me in the comment section down below.

Steps- 2: Connecting Phone to PC Using ADB and Fastboot commands

  • Now once your phone is in the fastboot mode Connect your phone to your PC.
  • Make sure that you have already installed all the USB drivers. so, you don’t have any problem connecting your phone. But if you’re using a Mac you don’t need to install any drivers.
  • Once your phone is connected to your PC. You need to open the terminal on Mac or open minimal ADB and fastboot on Windows and type
fastboot devices
  • Hit enter this should return a list of devices that are connected to your computer.
  • And you will see your devices there with an ID this means that your phone is properly connected to your PC in fastboot mode and if it doesn’t show your device and it means that your phone is not connected and it could be that your phone is not in fastboot mode or you’d have an installed USB driver.
  • If you’re using Windows now once your phone is properly connected you can also type.
fastboot flashing get_unlock_ability
  • This is to check if your phone is unlockable or not. if it will be returned a code of 1 if it’s not then it will return a code of
    0. Now, this command may or may not work for your phone you don’t need to worry about that you can also type.
fastboot oem device-info
  • This command is to check all the information about your phone and as you can see in this example it says device unlock false which means it’s not unlocked it also says that device critical unlock which means that there’s another layer of lock on this phone.
  • This means that we need to unlock both of these layers on this phone.
  • Now this command may also not work for your phone it depends on what type of when you’re using.
Дополнительно:  How to Fix Username is not in the sudoers file. This incident will be reported

Steps- 3: Unlocking the Bootloader of your phone

  • Now there are three commands to unlock the bootloader on your phone. For different phones, different commands will work but the most common command is.
fastboot oem unlock
  • Hit enter, now this will unlock the bootloader on your phone if it doesn’t and if it fails that means that you need to use another command than you should type.
fastboot flashing unlock
  • And Hit enter, now depending on what phone you’re using now if you may directly start unlocking your phone or it may show you a bootloader unlock the screen.
  • If you see a bootloader unlock screen then you should use your volume keys to highlight and choose unlock the bootloader or choose something like yes allowed bootloader or yes or no or whatever the options your phone is showing you.
  • And when you choose the option just press the volume key or power button to confirm your choice and it should start unlocking your bootloader.
  • Now as we have seen in an example your device might also have an extra layer of law which is critical law.
  • So for that, you need to boot your phone into bootloader mode again and type.
fastboot flashing unlock_critical
  • And follow the same unlock process as before.

Steps- 4: Rooting your phone

Now once your phone bootloader is unlocked. let’s talk about the root methods now there are two ways to root your phone one is using TWRP and the other is without using TWRP.

The TWRP method is easier but not all the phones have TWRP available for them. And if you can’t find TWRP for your phone then you can still root your phone as long as you have an unlocked bootloader.

Now before we talk about the two methods in detail we should first find a TWRP for your phone and then you can decide which method you should use.

  • So first you go to the TWRP website and search for your phone using the phone name or phone’s code name.
  • Once you see your device in the list click on it and download it.
  • If you don’t find TWRP Recovery for your device then you can simply go to xda-developers
  • Go to your phone section and look for TWRP or search for TWRP and download it from there.
  • Now if you don’t find a TWRP there as well then you can go to this website and look for TWRP for your phone there.
  • And even if you don’t find a TWRP for your phone you will still be able to Root your phone using other methods.

Now let’s talk about the two methods, the first method is using TWRP you can use this method if you manage to find a TWRP for your phone or if you want to install a custom recovery along with rooting your phone.

The other method is boot image patching you should use this method if you didn’t find a TWRP or you just want to root your phone without TWRP.

Method-1: Rooting Android Using Boot Image Patching

  • For this method, you need two files one is your current boot image file and the other is Magisk App.
  • To get the boot image file for your phone, first of all, we need to check which ROM version your phone is running.
  • For that just go to settings go to About and check the Build Number of your phone.
  • Now you will have to download the firmware file for your phone of the same Build Number that you are running on your phone.
  • So I will suggest you update your phone to the latest build version and download the latest firmware build.

Sometimes it’s hard to find older builds. You can find the ROM file from your phone manufacturer’s website like for OnePlus we can find it from the OnePlus website for Google you can find it from google website and etc.

But if you are using a Chinese phone or some other phone then you may find it hard to find the firmware for your phone. So you can just go to this website and look for your phone and download the file.

  • Now once you have downloaded the firmware file you need to extract the boot image file from the firmware file.
  • And then copy the boot image file to your phone.
  • I will recommend you copy it to the download folder.
  • Now go ahead and download Magisk Manager Apk and install it on your phone.
  • Then open Magisk Manager App and tap on install then install.
  • Now Select and patch a file and select your stock boot image file.
  • Magisk Manager will install Magisk to your boot image and store it in the download folder as magisk_patched.img.
  • Now all you have to do is copy this file from your phone to your PC.
  • And boot your phone into fastboot mode again and connect your phone to your PC.
  • Now open the terminal on Mac or open minimal ADB and fastboot on Windows and type.
fastboot devices
  • And Hit enter, to check if your phone is properly connected.
  • Now you have to type.
fastboot flash boot /path of the image file/
  • If you cannot type the path just drag and drop the file to the terminal and it should enter the path of the file automatically.
  • Hit enter, and it should start flashing the file.
  • Now once that’s done you need to type.
fastboot continue
  • Hit enter, and that’s it now it will reboot your phone. And your phone should be rooted.
  • Once your phone boots up open Magisk Manager App and you should check and verify if it’s rooted.

Method-2: Rooting Android Using TWRP Recovery

Now before we begin I just want to make clear that in this method I will only show you the way to Root your phone using TWRP and I may not show how to install TWRP as it’s not the purpose of this tutorial and the process can get a bit complicated considering a different type of phones out there.

So I had covered the complete process of installing TWRP in this article. In this guide, we will only focus on the reading process rather than installing the process of the TWRP and will only cover as much as needed.

The first thing you need to do is you need to make sure that you have already downloaded the TWRP image file for your phone on your computer. You also need to download Magisk Zip file. You can either download this on your phone or on your PC.

  • First, you need to boot your phone into fastboot mode as we did before.
  • Connect your phone to your computer using a USB cable and open the terminal and type.
 fastboot devices
  • And Hit enter, to check if your phone is properly connected.
  • Now type.
fastboot boot /path of the image file/
  • Again you can also drag and drop and it will automatically enter the path of the image file.
  • Hit enter, and it should boot your phone into TWRP recovery mode.

  • Now, do note that since we use the boot command to boot into the recovery it only temporarily boots us to TWRP recovery and it didn’t install it so once you boot into recovery mode you will see a screen like this.
  • It says unmodified system partition where you need to select keep read-only.
  • Now there are three ways to flash Mgisk Zip file one is via PC using ADB sideload other is flashing images from the internal storage of your phone and the other is using OTG.
  • To install Magisk from PC
  • First, go to TWRP >> Go to advance and go to ADB Sideload.
  • And swipe to start to sideload. Make sure your phone is connected to your PC.
  • Now open the terminal and type.
adb sideload /path of the zip file/
  • Hit enter, and it should start flashing the Magisk Zip file to your phone. If your file is internal storage.
  • Go to install and browse for matches in the file select the file and swipe to flash it.
  • Once it’s done flashing your phone is rooted and now you can reboot your phone.

You can also confirm root by checking the Magisk Manager app on your phone and if the app is not there then you can easily install it from here.

Подготовка

Для начала, надо на компьютер установить adb и fastboot. Это утилитки из Android SDK для работы с подключенным по USB телефоном.

Для Windows есть удобный установщик adb, fastboothttps://forum.xda-developers.com/showthread.php?t=2317790

Вот здесь официальные дистрибутивы под все платформы — https://developer.android.com/studio/#downloads

Далее качаем TWRP. Это что-то типа livecd для телефона. Образ некой системы, в которой загрузится телефон, и в ней мы установим приложение Magisk.

TWRP (я брал версию 3.1.0-0-twrp.img) — https://dl.twrp.me/twrp/

Если у вас OnePlus, вот TWRP для них — https://eu.dl.twrp.me/oneplus3/ (надо брать этот twrp если вылетает ошибка dtb not fount)

Magisk — это open source приложение, которое дает рут права на телефон, и позволяет скрывать наличие рута от других приложений, чтобы работал Android Pay. Также, обновления системы, которые прилетают “по воздуху”, не должны сломаться. Лучше использовать Magisk, а не SuperSU.

Magiskhttps://github.com/topjohnwu/Magisk/releases

Теперь включим режим разработчика на телефоне. Для этого в настройках, в разделе “О телефоне”, надо несколько раз нажать на “Номер сборки”. После раза 10-го, появится сообщение “Теперь вы разработчик”, и в настройках появится новый пункт “Для разработчиков”.

Open a root shell on you device

$ adb shell
root@android:/ #

You are now root! Do whatever you want, e.g. installing a su program in /system/bin etc. Remember to remount /system in read/write mode before you can write anything there.

Because you did not flash your device with the insecure boot image, the next time you reboot it, security will be turned on again, for your protection. The modifications you’ve done on /system are of course still there.

$ fastboot flash boot my_boot.img

I don’t recommend using ro.secure=0 as default, though, but there may be other changes you want to apply to the root disk.

Unpacking the root file system

# mkdir rootfs
# cd rootfs
# gzip -cd ../initramfs.cpio.gz | cpio -i

Now the file system is unpacked in the directory «rootfs».

Unlock the Boot-loader

This tutorial assumes you have a device with either an unlocked or unlockable bootloader. This is the most common today. The phone is shipped with the bootloader locked (i.e. tamper proof), but the manufacturer gives you the option to unlock it. This is usually at the cost of the the Digital Rights Manager data (DRM) and also often limits the warranty. This is quite understandable, since you can easily damage the unlocked device for example by overclocking it beyond its thermal capacity, melting the CPU, to mention a worst case scenario.

With the bootloader unlocked, you are able to both boot the device, and/or flash the internal disk, using custom root file system images.

Make sure your vendor allows you to unlock your device before continuing this tutorial. You may wait with the actual unlocking until you created your new boot image, though. If you can’t find any information about the state of your bootloader, just try booting you device with the image you’ll build here. Either it works, or your device politely refuses it.

Why root Android Phones?

why root android phone

Install superuser

adb reboot recovery

Relax! That’s it. Your device is now rooted and you can do things that you could never do otherwise. You can install the custom ROMs available for your device and make it better and faster.

Предисловие

Все действия вы выполняете на свой страх и риск. При неправильной последовательности, можно потерять данные или превратить телефон в кирпич. Также, важно понимать, что рутованный девайс, кроме некоторых удобств, несет в себе риски безопасности. Будьте внимательны.

Install custom recovery

Second, we’ll install TWRP recovery. Download the recovery from twrp.me. Keep your device connected and reboot your device in the bootloader.

Дополнительно:  Tree Data Structure

adb reboot bootloader

fastboot flash twrp-3.1.1-0-oneplus2.img

Selinux

Modern Android devices may run selinux. This will most likely prevent execution of the rootsh above. If this is the case, try disable selinux by setting property "androidboot.selinux=disabled" and report back to me if it did the trick. 😉

Compile the boot image

Now we build the new insecure boot image. Use the same parameters unmkbootimg suggested to get base address and so correct. If unmkbootimg didn’t print out any base address, it’s because default is used, and you won’t need to specify it to mkbootimg neither.

$ mkbootimg --kernel kernel.gz --ramdisk insecure_initramfs.cpio.gz --base 0x20000000 --cmdline 'no_console_suspend=1' -o insecure_boot.img

Please note that the kernel file may be called «kernel.gz«, «zImage» or similar depending on what tools used extracting it from the original boot image.

(instead of mkbootimg you may use the tool abootimg found in some Linux distributions, e.g. Debian and Ubuntu)

Install Android Oreo

As I mentioned after you root your Android device, you have more control over your smartphone, you can even change the Android version that came preinstalled with your smartphone. For example, I bought NextBit Robin and it shipped with Android 6 preinstalled. What I did, I rooted it and installed Android 7 (Nougat). So I enjoyed the latest version even though the manufacturer had not released Nougat for the device.

Another device I have that I’ve rooted and installed Android Oreo is Oneplus 2. Though there is no news of Android Oreo being released for Oneplus 2. I’m enjoying Android 8 on Oneplus 2.

  1. Unlock bootloader
  2. Install custom recovery
  3. Install the superuser management application

1. Unlock bootloader

The very first step is to unlock the bootloader of your Android phone. And remember that not all device manufacturers will allow you to do this. So before you start this process, check if your device is unlockable.

No warranty after rooting the device

There are three types of phone manufacturers. The first are those who don’t allow you to unlock the bootloader at all. The second are those who allow you to unlock the bootloader but they void the warranty of the device. And the third types of manufacturer are those that allow you to unlock your device bootloader and do not even void any warranty of the device.

So it is very necessary if your particular device model is unlockable and does not void any warranty. There are few manufacturers who don’t void the warranty but they exist. Both my primary phones are awesome. Nextbit Robin, the company has been sold out but it had not void warranty even after unlocking it. Similarly, the Oneplus 2 warranty does not void even after the device is rooted.

Boot the device in Insecure mode

  • Device powered off. Press and hold Volume-UP during power on.
  • Device powered off. Press and hold Volume-UP and insert USB cable connected to computer.

If this doesn’t work, Google «fastboot» plus your device name.

Once in fastboot, boot the phone using the fastboot command, supplied with the Android SDK.

$ fastboot boot insecure_boot.img

Now the phone will (hopefully) start and look as usual. The only difference is that security is turned off.

Obtaining the boot image

Now you’ll need to get hold your original boot image. You can either extract this from the device itself, get it from your manufacturer or from some trusted source on the Internet providing original images. Often the original distribution is a zip archive (but not necessary with the .zip extension). Unzip it to get the boot.img file.

Unpacking the boot image

The boot image (boot.img) is composed of both the kernel and the initial root file system (initramfs). To split this, you’ll need some utility. I’ve written such tool here below. There are several other, often script based, tools out there as well.

How to gain root access on an Android device

Root any android with adb

Here I describe the generic way to gain root access on an Android device. This description applies to any Android device using a bootloader that is possible to unlock. Most vendors today ship their bootloaders locked with the option to unlocking them, most often voiding the warranty.

If you got a well known and/or not brand new device, there probably already exists ready-made one-click tools rooting your device much easier than this. This tutorial is if you don’t got such a tool, or for some reason don’t want to use them — or if you simply are curious about the methods used.

All tools used here assumes you are using a GNU/Linux environment such as Debian, Ubuntu or so.

Steps

  • Unlock the bootloader
  • Obtain your boot image
  • Unpack the boot image
  • Unpack initramfs root file system
  • Enable insecure mode
  • Pack initramfs
  • Pack boot image
  • Fastboot device using own boot image
  • adb shell to the device

Разблокировка загрузчика

Разблокировка загрузчика удаляет все данные с телефона и sd-карты

Разблокировка загрузчика без установленного далее Magisk, может сломать Android Pay.

  1. В настройках “Для разработчиков” включаем “Отладка по USB”, “Заводская разблокировка” и “Варианты перезагрузки”
    Oneplus menu
    Oneplus menu

  2. Загружаемся в fastboot mode. Для этого зажимаем кнопку выключения, выбираем “Перезагрузка” и далее “Загрузчик”
    Oneplus reboot mode
    Второй способ — выключить телефон, зажать клавишу громкости вверх и клавишу включения. Через несколько секунд появится fastboot mode
    Oneplus fastboot mode

  3. Подключаем телефон по USB-кабелю, и проверяем что устройство доступно в системе. Для этого выполняем:

     fastboot devicesfa______d fastboot

    В списке должен быть телефон

  4. ПОСЛЕ ЭТОЙ КОМАНДЫ ТЕЛЕФОН ПЕРЕЗАГРУЗИТСЯ И ВСЕ ДАННЫЕ БУДУТ УДАЛЕНЫ. Делайте бэкапы всех данных до этого шага.

    На телефоне выбираем качелькой громкости Yes, подтверждаем клавишей питания. При загрузке появится меню с выбором режима, выбираем качелькой просто Start, и подтверждаем клавишей питания. Телефон долго будет перезагружаться, и загрузится сброшенным в заводское состояние.

Теперь загрузчик разблокирован.

  1. Подключаем телефон к компьютеру в режиме передачи файлов MTP
  2. Заливаем на телефон zip-файл Magisk, скачанный выше из github
  3. Загружаемся в TWRP. Для этого перезагружаем телефон в fastboot mode (см. пункт 2 инструкции выше как разблокировать загрузчик) и на компьютере выполняем:
     fastboot boot twrp.imgfinished. total time: 1.044s

    Oneplus TWRP

  4. В TWRP выбираем Install, и устанавливаем залитый на телефон zip Magisk.
    Oneplus TWRP install magisk
  5. После установки TWRP предлагает очистить кэш (wipe). Это не нужно, просто ребутаем
  6. После ребута появляется приложение Magisk Manager. Если этого не произошло, попробуйте взять другую версию TWRP и повторить процесс.
    Oneplus magisk

Все, теперь с помощью Magisk Manager можно выдавать root-овые права приложениям, которые их запрашивают, а также скрывать от других приложений, что этот девайс рутованный, чтобы не сломать Android pay.

Download and install the device USB driver

In order to detect your device properly by ADB, install your device’s USB drivers on your computer. You can easily find your device drivers from the official website of your smartphone. You can also google your phone model + USB drivers and get the results.

We’re all ready!

And once you’ve downloaded ADB and installed USB drivers, you’re all ready to dive in. Let’s unlock the bootloader.

Enable developer’s options from Android settings
Enable android developer options
enable oem unlocking
enable usb debugging
connect mobile to laptop
cd into adb directory

Step 2. Enable OEM unlocking & USB debugging from Settings > System > Developer options > Enable OEM unlocking & USB debugging

Now connect your mobile with your computer.

If your device is not detected then make sure you’ve properly installed USB drivers for your device. When your device is detected, it’s time to unlock the bootloader.

Step 5. Unlock the bootloader.

fastboot oem unlock

And that’s it. Your device bootloader has been unlocked.

Pack the root file system

All done, now we only have to repack everything again. Pack the root file system.

# cd rootfs
# find . | cpio -o -H newc | gzip > ../insecure_initramfs.cpio.gz
# cd ..

It didn’t work?!

Some devices seems not to honor the ro.secure property — but despair not, we still can fix this. We just have to install a root shell in the root file system instead. Back at your computer, cd to your rootfs directory from above and make sure your device is connected via the USB cable and up and running. Then issue the commands below to perform this.

root@ubuntu:~/rootfs# adb pull /system/bin/sh sbin/rootsh
root@ubuntu:~/rootfs# chmod a+x sbin
root@ubuntu:~/rootfs# chown root sbin/rootsh
root@ubuntu:~/rootfs# chgrp 2000 sbin/rootsh
root@ubuntu:~/rootfs# chmod 4750 sbin/rootsh 

Now go back and continue from «Pack the root file system» above to create a new boot image. Once the device is booted using this new image you can execute your root shell to gain root.

root@ubuntu:~# adb shell
shell@android:/$ /sbin/rootsh +p
# 

You are now root.

Download ADB, Fastboot & phone’s USB drivers

Download ADB and fastboot

ADB for Windows ADB for Linux ADB for Mac

Table of Contents

Conclusion

Frequently Asked Questions

Which Android devices are easy to root?

The ease of rooting Android devices can vary depending on the manufacturer, model, and the specific version of Android running on the device. However, it’s important to note that rooting a device typically voids the manufacturer’s warranty and can potentially lead to security risks or functional issues if not done properly. With that in mind, here are some Android devices that have historically been considered relatively easy to root:

1. Google Pixel and Nexus devices: Google’s own devices, such as the Pixel and Nexus series, have often been popular among the rooting community. They generally have good support from the developer community, making it easier to find rooting methods and custom ROMs.
2. OnePlus devices: OnePlus has gained a reputation for being developer-friendly, and many of their devices have good support for rooting and custom ROMs. However, it’s important to check the specific model and version of Android to ensure compatibility.
3. Xiaomi devices: Xiaomi offers a wide range of devices, and some of them have been known to have good support for rooting. Popular models like the Xiaomi Mi series and Poco series have often been favored by the rooting community.
4. Samsung devices (older models): Certain older Samsung devices, particularly those with Exynos processors, have historically been easier to root compared to their newer counterparts. However, rooting methods can vary between different models and Android versions.
5. HTC devices: HTC devices have traditionally had a strong developer community, making them relatively easier to root. However, their popularity has decreased in recent years.

Why would you root an Android?

What are the risks of rooting a phone?

Rooting a phone comes with certain risks and potential drawbacks. Here are some of the common risks associated with rooting an Android device:

1. Voiding warranty
: Rooting usually voids the manufacturer’s warranty of the device. Once you root your phone, the manufacturer may refuse to provide free repairs or support, even for unrelated issues. However, in some cases, unrooting the device may reinstate the warranty.
2. Security vulnerabilities: Rooting bypasses some of the built-in security measures of the Android operating system, exposing your device to potential security risks. Malicious apps or unauthorized modifications to system files can compromise the security of your device and personal data. It’s essential to exercise caution when granting root access to apps and ensure that you only download and install software from trusted sources.
3. Stability and performance issues: Incorrect rooting methods or incompatible modifications can lead to stability and performance problems. System crashes, boot loops, freezes, and other issues may occur if root access is mishandled or if incompatible software is installed. Additionally, certain apps or features that rely on the device’s security mechanisms may no longer function properly on a rooted device.
4. No OTA updates: Once your device is rooted, installing official over-the-air (OTA) updates from the manufacturer may become problematic or impossible. OTA updates typically verify the integrity of the system files and may fail if modifications have been made. To receive official updates, you may need to unroot your device and return it to its original state.
5. Brick risk: While rare, there is a small possibility of bricking your device during the rooting process or when applying custom modifications. “Bricking” refers to rendering the device inoperable, essentially turning it into a “brick.” This can occur due to errors in the rooting process or if you make incorrect modifications to critical system files.

Can you root an Android phone without a computer?

Yes, it is possible to root an Android phone without using a computer. There are several rooting methods available that allow you to root your device directly from the phone itself. However, it’s important to note that the availability and success of these methods can vary depending on the device model, Android version, and specific rooting tools or apps.

Here are a few common methods to root an Android phone without a computer:

how to root android phone without any app

Keep in mind that the process may vary depending on your phone model and Android version. It’s crucial to research and finds specific instructions tailored to your device to ensure a successful root. Additionally, rooting your phone may void the warranty and could potentially lead to security risks if not done correctly.

how to root Android phone without pc

Can I root my phone for free?

Yes, you can root your phone for free. Rooting allows you to gain privileged access to the operating system, giving you more control over your device. There are various methods available for rooting, and many of them can be done without any cost.

Оцените статью
Master Hi-technology