Installing root certificate android

# Install System CA Certificate on Android Emulator

Since Android 7, apps ignore user provided certificates, unless they are configured to use them. As most applications do not explicitly opt in to use user certificates, we need to place our mitmproxy CA certificate in the system certificate store, in order to avoid having to patch each application, which we want to monitor.

Please note, that apps can decide to ignore the system certificate store and maintain their own CA certificates. In this case you have to patch the application.

# 1. Prerequisites

Android Studio/Android Sdk is installed (tested with Version 4.1.3 for Linux 64-bit)

An Android Virtual Device (AVD) was created. Setup documentation available here

  • The AVD must not run a production build (these will prevent you from using adb root )
  • The proxy settings of the AVD are configured to use mitmproxy. Documentation here

Emulator and adb executables from Android Sdk have been added to $PATH variable

  • emulator usually located at /home/ /Android/Sdk/emulator/emulator on Linux systems
  • adb usually located at /home/ /Android/Sdk/platform-tools/adb on Linux systems
  • I added these lines to my .bashrc

Mitmproxy CA certificate has been created

    Usually located in

/.mitmproxy/mitmproxy-ca-cert.cer on Linux systems

  • If the folder is empty or does not exist, run mitmproxy in order to generate the certificates
  • # 2. Rename certificate

    CA Certificates in Android are stored by the name of their hash, with a ‘0’ as extension (Example: c8450d0d.0 ). It is necessary to figure out the hash of your CA certificate and copy it to a file with this hash as filename. Otherwise Android will ignore the certificate. By default, the mitmproxy CA certificate is located in this file:

    # Instructions

    • Enter your certificate folder: cd

    /.mitmproxy/

  • Generate hash and copy certificate : hashed_name=`openssl x509 -inform PEM -subject_hash_old -in mitmproxy-ca-cert.cer | head -1` && cp mitmproxy-ca-cert.cer $hashed_name.0
  • # 3. Insert certificate into system certificate store

    Now we have to place our CA certificate inside the system certificate store located at /system/etc/security/cacerts/ in the Android filesystem. By default, the /system partition is mounted as read-only. The following steps describe how to gain write permissions on the /system partition and how to copy the certificate created in the previous step.

    # Instructions for API LEVEL > 28

    Starting from API LEVEL 29 (Android 10), it seems to be impossible to mount the “/” partition as read-write. Google provided a workaround for this issue using OverlayFS. Unfortunately, at the time of writing this (11. April 2021), the instructions in this workaround will result in your emulator getting stuck in a boot loop. Some smart guy on Stackoverflow found a way to get the /system directory writable anyway.

    Keep in mind: You always have to start the emulator using the -writable-system option if you want to use your certificate. Otherwise Android will load a “clean” system image.

    Читайте также:  Land cruiser prado 120 для андроид

    Tested on emulators running API LEVEL 29 and 30

    # Instructions

    • List your AVDs: emulator -list-avds (If this yields an empty list, create a new AVD in the Android Studio AVD Manager)
    • Start the desired AVD: emulator -avd -writable-system (add -show-kernel flag for kernel logs)
    • restart adb as root: adb root
    • disable secure boot verification: adb shell avbctl disable-verification
    • reboot device: adb reboot
    • restart adb as root: adb root
    • perform remount of partitions as read-write: adb remount . (If adb tells you that you need to reboot, reboot again adb reboot and run adb remount again.)
    • push your renamed certificate from step 2: adb push

    /system/etc/security/cacerts

  • set certificate permissions: adb shell chmod 664 /system/etc/security/cacerts/
  • reboot device: adb reboot
  • # Instructions for API LEVEL -writable-system option if you want to use your certificate. Otherwise Android will load a “clean” system image.

    /system/etc/security/cacerts

  • set certificate permissions: adb shell chmod 664 /system/etc/security/cacerts/
  • reboot device: adb reboot
  • Источник

    Installing a new trusted SSL root certificate on Android

    Jamie Holding

    It’s very trivial to install a user-trusted certificate on android. Under Settings -> Security you can install new trusted certificates. However, this creates a permanent «Your network could be monitored» warning in your task tray and forces you to have a lock-screen. In addition to this, in newer versions of Android, Android apps will by default only trust system certificates.

    By default, apps that target API level 24 will—by design—not honor such CAs unless the app explicitly opts in.

    So, ultimately if you want to be keeping an eye on what your phone is up to, you’re going to need to install a system trusted certificate come Android 7.0 onwards.

    This setup is largely inspired from http://wiki.pcprobleemloos.nl/android/cacert — but without the endless references to cacert, which we aren’t using.

    What you need

    • A rooted Android phone
    • ADB setup and ready to go
    • An SSL certificate in PEM form ** If you are using Charles Proxy, go to charlesproxy.com/getssl to download your certificate from your proxy in PEM form
    • OpenSSL command line tools ** On Linux, Google how to install for your distro ** On Windows, either setup Bash for Windows 10, or install OpenSSL and add the executable to your PATH environment variables

    Step 1 — Setup the certificate

    If your certificate isn’t in .PEM form, convert it from whatever format you currently have it in into .PEM first.

    As an example, if you have it in .CER format, use openssl x509 -inform der -in cert.cer -out cert.pem to get it into .PEM.

    You need to find the hash of your certificate first. To do this, run the following command on your certificate (mine is called cert.pem, replace as needed):

    You should get something like 5h543h5a.

    Write our .pem certificate to a new file with the hash name from above and the file extension .0 (replacing the hash with the result you had from above):

    Now we need to export the PEM information into the bottom of this new file.

    Now you have your .0 file ready for adding to the Android device!

    Step 2 — Setup the device

    Have the device plugged in and make sure you’ve enabled ADB debugging.

    Run the following to make sure we’re debugging as root on the device:

    If you have any issues here, you might need to enable root ADB in the developer options on the device. Google if you have other issues and then come back here when you’re set!

    Now you probably need to remount your device to get access to the system files for writing our certificate.

    Читайте также:  Отключение графического ключа android

    Push your new file to your device in the system certificates folder.

    Now open the shell by running adb shell and then run the following command to set the correct file permissions:

    Now reboot the phone and if you go to Settings -> Security you should be able to find your new system trusted certificate!

    Sign up for more like this.

    Nursery Night Sky Feature Wall

    My little baby girl is on her way (probably here by the time I publish this). We knew we wanted to theme her nursery to something cool. At one point it was going to be dinosaurs, because dinosaurs are awesome. But that sounded complicated and we are really after subtle

    Sometimes it’s handy to test triggering a mobile deep link to test some new integration. You may have tried typing the URL into your phone’s web browser (like Chrome) to trigger the app launching, however this doesn’t work! The link needs to be clicked to trigger. However, instead of creating

    Источник

    Установка собственного корневого сертификата в Android и запуск Citrix XenApp Web Interface

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

    Немножко предыстории:

    Стоит у нас в конторе Citrix XenApp для обеспечения удалённой работы из офиса. Что это за зверь и с чем его едят рассказывать не будем — кому это надо, те давно в курсе.
    В этой совместной с записи мы хотим рассказать об установке корневого сертификата и настройке клиентской части — Citrix Receiver для Android.

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

    Что же за проблемы могли возникнуть?

    Для организации такого рода архитектуры удалённого доступа довольно часто используются сертификаты, которые подписаны центрами не входящими в список стандартных. Почему Google такие нехорошие, и не включили в свою ОСь такую простую функцию, (наряду с такой, опять же, нужной функцией, как возможность прописать прокси-сервер) как установка дополнительных корневых сертификатов ЦА, тут мы обсуждать не собираемся.
    Первым признаком того, что сервер использует самоподписанный сертификат является то, что, когда Вы открываете, откуда бы то ни было веб-ресурс с помощью, например, браузера Mozilla Firefox, программа выдает сообщение о том, что не может сама принять решение о том доверять ли сертификату для установления защищённого соединения или нет — она предоставляет право выбора Вам.
    Если у вас наблюдается такая картина, то эта статья как раз для Вас!

    Так что же все-таки надо, чтобы запустить через Citrix Receiver приложения опубликованные на Citrix XanApp вашего предприятия?

    В первую очередь, как оказалось, необходимо установить Mozilla Firefox для Android. Очень странно, но ни один другой браузер не передаёт нужный для подключения файл (launch.ica) в программу-клиент. Знаем только то, что с Firefox все работает нормально.

    Во вторую очередь нужна сама программа-клиент. Тут на Android Market у нас есть выбор: стабильный Citrix Receiver, либо находящийся на этапе тестирования Citrix Labs Receiver. Второй у нас не захотел принимать сертификат ни в какую, первый же — стабильный, после бессонной ночи таки у нас и заработал.

    Читайте также:  Z3 android tv box a95x allwinner h6

    В-третьих, необходимо иметь root-доступ к вашему устройству, либо возможность извлекать и записывать обратно файлы через adb, хотя, в этом случае тоже требуется root-доступ (как его настроить Вы сможете узнать потратив немного времени на просмотр результатов, который выдал вам Google на запрос вида » root access howto» или » adb configure howto»).

    Вопросом настройки adb мы заморачиваться, опять таки, не стали, так как предпочитаем работать напрямую через файл-менеджеры с системой. В любом случае, в сети довольно много информации по этому поводу (русскоязычный ресурс, на котором больше всего информации такого плана — http://4pda.ru/forum, англоязычный — http://forum.xda-developers.com). В случае, если Вы будете использовать прямой доступ к системным файлам, то нужен файловый менеджер, который умеет использовать root-права (например, Root Explorer).

    В-четвертых, нужна машина с любым из популярных Linux-дистрибутивов и установленной Java-машиной от Oracle (мы использовали Ubuntu 10.10 с установленным JRE).

    И последнее в списке, но далеко не последнее по значимости — сам корневой сертификат центра сертификации (пусть он будет называться CompanyCA.crt).

    От требований (если они все выполнены) переходим к действию.

    Для удобства будем перечислять все по пунктам.

    1. Заходим с устройства на Android Market и устанавливаем Firefox.
    2. Заходим с устройства на Android Market и устанавливаем Citrix Receiver.
    3.1.1 (3.1.х для тех кто предпочитает прямой доступ) С помощью файлового менеджера копируем файл /system/etc/security/cacerts.bks cacerts.bks на карту SD.
    3.1.2 Подключаем устройство как накопитель к компьютеру с Linux.
    3.1.3 Копируем файл cacerts.bks с корня карточки в вашу домашнюю папку.
    3.2.1 (adb) копируем сертификат
    $ adb pull /system/etc/security/cacerts.bks cacerts.bks

    4. Этот пункт предполагает, что Вы уже установили и настроили JRE 1.6 и прописана переменная окружения JAVA_HOME (в моем случае JAVA_HOME=/usr/lib/jvm/java-6-sun/).
    Скачиваем пакет bouncycastle.org/download/bcprov-jdk16-146.jar и кидаем его в папку $JAVA_HOME/jre/lib/ext/
    Если у вас установлен JDK, то этот пакет, надо так же закинуть в папку /usr/lib/jvm/java-6-openjdk/jre/lib/ext
    wget bouncycastle.org/download/bcprov-jdk16-146.jar
    sudo cp bcprov-jdk16-146.jar $JAVA_HOME/jre/lib/ext/bcprov-jdk16-146.jar
    # или sudo cp bcprov-jdk16-146.jar /usr/lib/jvm/java-6-sun/jre/lib/ext/bcprov-jdk16-146.jar

    5. Кидаем файл сертификата CompanyCA.crt так же в домашнюю папку. Если его у Вас нет, но Вы соглашались принять сертификат при переходе на веб-интерфейс XenApp, то его можно экспортировать из Firefox. Как это сделать — подскажет Google. Можем лишь уточнить, что шифрование нужно X.509 PEM.

    6. Скачиваем и устанавливаем Android SDK (если Вы не планируете использовать adb, то этот шаг можно пропустить):
    wget dl.google.com/android/android-sdk_r10-linux_x86.tgz
    tar -xvzf android-sdk_r10-linux_x86.tgz
    sudo mv android-sdk-linux_x86 /usr/lib/android-sdk-linux_x86
    Запускать что-либо из комплекта для нашей задачи не требуется. Но нужно прописать исполняемые файлы SDK в переменных окружения export PATH=$:/usr/lib/android-sdk-linux_x86/tools.
    В нашем случае вопрос с переменными окружения решается добавлением в конец файла

    /.bashrc строчек
    export PATH=$:/usr/lib/android-sdk-linux_x86/tools
    export JAVA_HOME=/usr/lib/jvm/java-6-sun/jre

    7. Открываем консоль и выполняем команду
    keytool -keystore cacerts.bks -storetype BKS -provider org.bouncycastle.jce.provider.BouncyCastleProvider -storepass changeit -importcert -trustcacerts -alias CACERT -file CompanyCA.crt

    Будьте внимательны — не меняйте параметр -storepass changeit, там действительно такой пароль)

    В ответ на эту команду Вы должны получить информацию о сертификате и запрос «Trust this certificate? [no]: » — соответственно отвечаем «y».
    Все, наш файл подготовлен. Теперь нужно загрузить его на устройство.

    8.1.1 (прямой доступ) Подключаем устройство как накопитель к компьютеру;
    8.1.2 Загружаем на карту файл cacerts.bks;
    8.1.3 Переносим с помощью менеджера файлов cacerts.bks из папки /sdcard в папку /system/etc/security/, предварительно примонтировав её для записи;
    8.2.1 (adb) Монтируем систему для записи:
    $ adb shell mount -o remount,rw /system;
    8.2.2 Загружаем файл:
    $ adb push cacerts.bks /system/etc/security/;
    8.2.2 Монтируем систему только для чтения:
    $ adb shell mount -o remount,ro /system.

    На этом трудная часть пройдена. Осталась пара «финтов ушами».

    9. Перезагружаем устройство.

    10. Запускаем Firefox и открываем страницу веб-доступа.
    Появится приблизительно такая картина:

    Тут нам надо нажать на ссылку «Already installed» в верхней части экрана;

    11. Выбираем приложение из списка и пробуем запустить;

    Источник

    Оцените статью