- # Install System CA Certificate on Android Emulator
- # 1. Prerequisites
- # 2. Rename certificate
- # Instructions
- # 3. Insert certificate into system certificate store
- # Instructions for API LEVEL > 28
- # Instructions
- # Instructions for API LEVEL -writable-system option if you want to use your certificate. Otherwise Android will load a “clean” system image.
- Установка собственного корневого сертификата в Android и запуск Citrix XenApp Web Interface
- Немножко предыстории:
- Что же за проблемы могли возникнуть?
- Так что же все-таки надо, чтобы запустить через Citrix Receiver приложения опубликованные на Citrix XanApp вашего предприятия?
- От требований (если они все выполнены) переходим к действию.
- Importing private CA certificates in Android
- Errors and Notes
# 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
# 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/
# 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.
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
# 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
Источник
Установка собственного корневого сертификата в 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. Второй у нас не захотел принимать сертификат ни в какую, первый же — стабильный, после бессонной ночи таки у нас и заработал.
В-третьих, необходимо иметь 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=$
В нашем случае вопрос с переменными окружения решается добавлением в конец файла
/.bashrc строчек
export PATH=$
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. Выбираем приложение из списка и пробуем запустить;
Источник
Importing private CA certificates in Android
Internal encryption in company networks is important and something that’s done relatively easy. By creating your own certificate authority (CA) and signing your server certificates with it, you can establish a centralized point of trust on all your devices, making it much more easy for you to maintain your network encryption. Plus, it doesn’t cost a dime in licenses if you use free solutions such as openssl and you are much more flexible than with paid certificates.
When you are using your own domains, such as yourcompany.local, your own CA is a great way to provide trusted certificates for all your applications. The only requirement is that your CA certificate is imported on all devices that connect to those services. Let’s see how we can import your CA certificate into the Android certificate store.
On Android, importing system wide certificates is fairly straight forward. Just open your settings, scroll down to Security and tap the Install from storage option.
Browse to the location of your CA certificate and tap the file to import it. After naming your imported certificate authority and specifying what it should be used for, your should get a success message and the certificate should now be listed in the User tab.
Errors and Notes
The following screenshots show three minor things we encountered.
First, if you get the error message No certificate to install shown above, your certificate is most likely formatted incorrectly. Android requires .DER formatted certificates to be able to import them. You can convert your certificate easily with the following command.
Your certificate might already be called ca_cert.pem , which would indicate that it’s PEM formatted, however the ending .crt is not only used for .DER certificates but sometimes as a file extension for certificates in general, which can result in the wrong assumption that it is a .DER file, when it fact it might not be.
You can check the format with the following commands.
The first command tries to import the certificate as DER file. Since it fails, we now know that it’s not a DER formatted file. The second command tries to import the same certificate as PEM file. The command is successful and shows us the content of the certificate, which indicates that this must be a PEM formatted file.
Once you have converted your certificate, you should be able to import it and be presented with success message (see above).
The second thing we encountered was that if you use neither a PIN, nor a password to unlock your device, importing a CA certificate might require you to improve your device security first. Just set a pin or password, or if you have already but are using a «auto-unlock» app for your home network, simply disable WIFI temporarily and you should be good to go.
Last but not least, since a custom CA allows the owner of the CA to create valid certificates for any website on your device (even google.com, facebook.com, etc.), you should get the following info message. Only ever allow certificates you have good reason to trust in, especially when it comes to CA certificates.
Hopefully you enjoyed this little excourse into the Android certificate store. Leave a comment if you think we should also cover other devices such as iOS, Windows Phone, Linux, Mac and Windows and Mozilla applications, which all keep their own certificate store?
Источник