- Disk On Key
- Смотреть что такое «Disk On Key» в других словарях:
- Извлечение аппаратного ключа полнодисковой защиты в телефонах Android на процессорах Qualcomm
- Эксплоит опубликован на Github
- Keys, Credentials and Storage on Android
- Account Manager
- The Keychain
- The KeyStore
- Generate a New Random Key
- Encrypting Data
- Decrypting to a Byte Array
- Testing the Example
- Using RSA Asymmetric Keys for Older Devices
- Conclusion
Disk On Key
Универсальный англо-русский словарь . Академик.ру . 2011 .
Смотреть что такое «Disk On Key» в других словарях:
disk-on-key — n. (Computers) disc on key, USB drive, flash drive, Plug and Play compact mobile device that uses flash memory and is light enough to carry on a key chain … English contemporary dictionary
Disk encryption — uses disk encryption software or hardware to encrypt every bit of data that goes on a disk or disk volume. Disk encryption prevents unauthorized access to data storage. The term full disk encryption (or whole disk encryption) is often used to… … Wikipedia
Disk encryption theory — Disk encryption is a special case of data at rest protection when the storage media is a sector addressable device (e.g., a hard disk). This article presents cryptographic aspects of the problem. For discussion of different software packages and… … Wikipedia
Disk Utility — Developer(s) Apple Inc … Wikipedia
Disk cloning — is the process of copying the contents of one computer hard disk to another disk or to an image file. Often, the contents of the first disk are written to an image file as an intermediate step, and the second disk is loaded with the contents of… … Wikipedia
Disk-drive performance characteristics — are the attributes which control the time it takes to transfer (read or write) data between a computer and a data storage device (most typically disk storage) starting with the initial command from the computer or host until the storage device… … Wikipedia
Key disclosure law — Key disclosure laws, also known as mandatory key disclosure, is legislation that require individuals to surrender cryptographic keys to law enforcement. The purpose is to allow access to material for confiscation or digital forensics purposes and … Wikipedia
disk — [ dısk ] noun count ** ▸ 1 for computer information ▸ 2 flat circular object ▸ 3 between bones of back ▸ 4 a record ▸ 5 CD 1. ) a small flat circular object in a square plastic case that can be used for storing information from a computer and can … Usage of the words and phrases in modern English
Disk laser — Not to be confused with Laserdisc. Fig.1. An optically pumped disk laser (active mirror). A disk laser or active mirror (Fig.1.) is a type of solid state laser characterized by a heat sink and laser output that are realized on opposite sides of a … Wikipedia
Disk encryption software — To protect confidentiality of the data stored on a computer disk a computer security technique called disk encryption is used. This article discusses software that is used to implement the technique (for cryptographic aspects of the problem see… … Wikipedia
Key (lock) — A cut key A key is an instrument that is used to operate a lock. A typical key consists of two parts: the blade, which slides into the keyway of the lock and distinguishes between different keys, and the bow, which is left protruding so that… … Wikipedia
Источник
Извлечение аппаратного ключа полнодисковой защиты в телефонах Android на процессорах Qualcomm
Эксплоит опубликован на Github
Компания Google начала внедрять полное шифрование диска (Full Disk Encryption, FDE) по умолчанию с версии Android 5.0 Lollipop. В первое время, когда шифрование реализовали в устройствах Nexus 6, многие пользователи жаловались на снижение производительности при чтении и записи данных на накопитель, но с версии Android 6.0 эту проблему вроде бы решили.
Полное шифрование диска защищает всю информацию на телефоне даже в том случае, если устройство попало в руки правоохранительных органов или других злоумышленников.
При включенном шифровании любая информация на телефоне автоматически на лету шифруется ключом AES перед записью на носитель. И наоборот, при считывании информации она автоматически расшифровываются этим ключом.
На устройствах iOS 9 этот ключ является производной функцией от пользовательского пароля и уникального 256-битного аппаратного ключа, зашитого в смартфон на заводе. Взломать шифрование такого уровня с помощью брутфорса не может даже ФБР, как известно из недавней истории со смартфоном стрелка из Сан-Бернардино, из-за которого ФБР и Apple дошли до суда. В итоге ФБР всё-таки сумело взломать телефон с помощью неизвестной 0day-уязвимости. Как можно понять из слов главы госструктуры, за обход защиты ФБР пришлось заплатить хакерам более миллиона долларов.
Полное шифрование диска в iOS
Таким образом, брутфорс FDE возможен только с использованием конкретного аппаратного устройства. Это значительно затрудняет проведение атаки. В обычном случае можно было бы создать миллион копий и распараллелить брутфорс в облачном сервисе, что позволяет очень быстро подобрать 99% реальных паролей. Но в данном случае приходится ограничиваться единственным устройством, на котором Apple добавляет ещё и дополнительные помехи — задержки между попытками ввода пароля, ограничение на максимальное количество попыток и т.д. Вот почему для спецслужб исключительно важно найти способ извлечения аппаратного UID, тогда брутфорс пароля становится банальной технической задачей.
Полное шифрование диска в Android 5.0+ реализовано несколько иначе, чем в iOS 9, и подробно описано в блоге Николая Еленкова и в официальной документации Android.
Здесь ключ шифрования тоже является производной функцией от обычно слабого пользовательского пароля, но также от случайным образом сгенерированного 128-битного мастер-ключа (Device Encryption Key — DEK) и случайно сгенерированной 128-битной соли. Поле генерации DEK защищается с помощью тщательно продуманной схемы, в которой используются введённые пользователем значения — пинкод/пароль/паттерн (графический ключ) для входа. Затем зашифрованный DEK помещается в специальное зашифрованное хранилище под названием crypto footer. Все эти уровни шифрования нужно преодолеть, прежде чем расшифровать DEK, а затем любую информацию, записанную на накопителе.
Как и в случае с iOS 9, в операционной системе Android реализована привязка схемы шифрования к конкретному аппаратному обеспечению, чтобы не допустить брутфорса на копиях операционной системы. Функцию аппаратной привязки выполняет специальное аппаратное хранилище — KeyMaster, которое работает в особом окружении Trusted Execution Environment (TEE), полностью независимом от операционной системы Android. Защищённость ключей в окружении KeyMaster имеет важнейшее значение. Только это защищает систему полного шифрования диска от проведения эффективного брутфорса в параллельных потоках на копиях ОС.
В устройствах Android изолированное окружение никогда не выдаёт свой собственный ключ наружу в «небезопасную» среду. Наоборот, модуль KeyMaster получает из небезопасной среды «блоб ключа» (key blob), расшифровывает хранящийся там ключ — и отдаёт его обратно. Другими словами, работа системы шифрования возможна только непосредственно на аппаратном устройстве, но не в виртуальной среде на другом компьютере.
В общем весь процесс схематично можно изобразить на такой диаграмме, которую приводит Николай Еленков.
Защиту окружения KeyMaster и выполнение команд на выделенном безопасном процессоре обеспечивает защищённая среда, предоставленная производителем оборудования. В Случае с Qualcomm это среда QSEE (Qualcomm Secure Execution Environment). Она допускает к исполнению на выделенном процессоре только отдельные маленькие приложения, которые называются «трастлеты» (trustlets). Один из таких трастлетов — KeyMaster. В исходном коде Android есть инструкции для обращения к приложению KeyMaster. На самом деле трастлет поддерживает всего четыре инструкции:
KeyMaster работает в точности как описано выше: он получает блоб ключа, вычисляет подпись и помещает её в буфер.
И вот теперь мы подошли именно к тому этапу, на котором действует новый эксплоит, который появился в открытом доступе 30 июня (репозиторий на Github). Эксплоит использует недавно найденные уязвимости CVE-2015-6639 и CVE-2016-2431.
Автор эксплоита, специалист по безопасности Гал Беньямини (Gal Beniamini) написал поддельную версию приложения QSEE и с помощью вышеупомянутых уязвимостей сумел загрузить её в защищённое окружение, тем самым осуществив повышение полномочий и взломав защиту окружения QSEE, которое участвует в процессе генерации ключа для шифрования диска.
Таким образом, гипотетический злоумышленник может «подделать» аппаратную составляющую ключа шифрования и осуществить брутфорс остальных компонентов, обойдя защиту Android на количество повторных попыток. Остаётся только подобрать перебором пользовательский пинкод/пароль.
Кстати говоря, для того редкого случая, когда пользователь установил для шифрования по-настоящему сложный пароль с высокой энтропией и его не удаётся подобрать брутфорсом за приемлемое время, есть запасной план. Если взломать шифрование действительно крайне необходимо, то можно найти точно такой же телефон, той же модели, с такими же царапинами и защитным корпусом — и запрограммировать его на отправку пароля, как только жертва введёт его. Этот поддельный аппарат подкладывается жертве вместо оригинального. Чтобы избежать раскрытия и одновременно устранить риск введения жертвой неправильного пароля с первой попытки, телефон должен быть запрограммирован на то, что никакой введённый пароль он не принимает как правильный.
Но это уже крайний случай, конечно. Обычные пинкоды и пароли на самом деле подобрать довольно просто, если нет аппаратных ограничений на брутфорс.
Есть интересный момент. Защищённую среду на мобильных устройствах устанавливает не сама компания Qualcomm, а OEM-производители. Они могут сотрудничать с правоохранительными органами той страны, в юрисдикции которой находятся, и выполнять требования судебных запросов. Соответственно, если подобная криптографическая схема будет реализована российским производителем, то информация на смартфоне будет рассекречена по запросу российского суда.
И ещё один интересный момент. Несмотря на то, что Гал Беньямини несколько месяцев обсуждал данные уязвимости с Qualcomm и Google, исправить их не так просто — здесь недостаточно программного апгрейда (для двух уязвимостей патчи для Android вышли в январе и мае), а может понадобиться аппаратный апгрейд. Дело в том, что если злоумышленник получит устройство, то теоретически может откатить программный апгрейд, вернуть аппарат на уязвимую версию и провести атаку.
Как уже говорилось выше, код эксплоита опубликован на Github. Вот схема его работы.
Гал Беньямини написал несколько скриптов на Python, которые упрощают брутфорс после срабатывания эксплоита. В комментариях к его блогозаписи коллеги выразили желание помочь в портировании скрипта на мощнейшую платформу для брутфорса hashcat/oclHashcat.
Беньямини предполагает, что компания Google вместе с OEM-сборщиками выработают новую абсолютно надёжную схему аппаратно-программного шифрования, которую даже теоретически невозможно будет взломать.
Будем надеется, что такую схему реализуют на новом поколении Android-устройств.
Источник
Keys, Credentials and Storage on Android
In the previous post on Android user data security, we looked at encrypting data via a user-supplied passcode. This tutorial will shift the focus to credential and key storage. I’ll begin by introducing account credentials and end with an example of protecting data using the KeyStore.
Often, when working with a third-party service, there will be some form of authentication required. This may be as simple as a /login endpoint that accepts a username and password.
It would seem at first that a simple solution is to build a UI that asks the user to log in, and then capture and store their login credentials. However, this isn’t the best practice because our app shouldn’t need to know the credentials for a third-party account. Instead, we can use the Account Manager, which delegates handling that sensitive information for us.
Account Manager
The Account Manager is a centralized helper for user account credentials so that your app does not have to deal with passwords directly. It often provides a token in place of the real username and password that can be used to make authenticated requests to a service. An example is when requesting an OAuth2 token.
Sometimes, all the required information is already stored on the device, and other times the Account Manager will need to call a server for a refreshed token. You may have seen the Accounts section in your device’s Settings for various apps. We can get that list of available accounts like this:
The code will require the android.permission.GET_ACCOUNTS permission. If you’re looking for a specific account, you can find it like this:
Once you have the account, a token for the account can be retrieved by calling the getAuthToken(Account, String, Bundle, Activity, AccountManagerCallback, Handler) method. The token can then be used to make authenticated API requests to a service. This could be a RESTful API where you pass in a token parameter during an HTTPS request, without ever having to know the user’s private account details.
Because each service will have a different way of authenticating and storing the private credentials, the Account Manager provides authenticator modules for a third-party service to implement. While Android has implementations for many popular services, it means you can write your own authenticator to handle your app’s account authentication and credential storage. This allows you to make sure the credentials are encrypted. Keep in mind, this also means that credentials in the Account Manager that are used by other services may be stored in clear text, making them visible to anyone who has rooted their device.
Instead of simple credentials, there are times when you will need to deal with a key or a certificate for an individual or entity—for example, when a third party sends you a certificate file which you need to keep. The most common scenario is when an app needs to authenticate to a private organization’s server.
In the next tutorial, we will be looking at using certificates for authentication and secure communications, but I still want to address how to store these items in the meantime. The Keychain API was originally built for that very specific use—installing a private key or certificate pair from a PKCS#12 file.
The Keychain
Introduced in Android 4.0 (API Level 14), the Keychain API deals with key management. Specifically, it works with PrivateKey and X509Certificate objects and provides a more secure container than using your app’s data storage. That’s because permissions for private keys only allow for your own app to access the keys, and only after user authorization. This means that a lock screen must be set up on the device before you can make use of the credential storage. Also, the objects in the keychain may be bound to secure hardware, if available.
The code to install a certificate is as follows:
The user will be prompted for a password to access the private key and an option to name the certificate. To retrieve the key, the following code presents a UI that lets the user choose from the list of installed keys.
Once the choice is made, a string alias name is returned in the alias(final String alias) callback where you can access the private key or certificate chain directly.
Armed with that knowledge, let’s now see how we can use the credential storage to save your own sensitive data.
The KeyStore
In the previous tutorial, we looked at protecting data via a user-supplied passcode. This kind of setup is good, but app requirements often steer away from having users log in each time and remember an additional passcode.
That’s where the KeyStore API can be used. Since API 1, the KeyStore has been used by the system to store WiFi and VPN credentials. As of 4.3 (API 18), it allows you to work with your own app-specific asymmetric keys, and in Android M (API 23) it can store an AES symmetric key. So while the API doesn’t allow storing sensitive strings directly, these keys can be stored and then used to encrypt strings.
The benefit to storing a key in the KeyStore is that it allows keys to be operated on without exposing the secret content of that key; key data does not enter the app space. Remember that keys are protected by permissions so that only your app can access them, and they may additionally be secure hardware-backed if the device is capable. This creates a container that makes it more difficult to extract keys from a device.
Generate a New Random Key
For this example, instead of generating an AES key from a user-supplied passcode, we can auto-generate a random key that will be protected in the KeyStore. We can do this by creating a KeyGenerator instance, set to the «AndroidKeyStore» provider.
Important parts to look at here are the .setUserAuthenticationRequired(true) and .setUserAuthenticationValidityDurationSeconds(120) specifications. These require a lock screen to be set up and the key to be locked until the user has authenticated.
Looking at the documentation for .setUserAuthenticationValidityDurationSeconds() , you will see that it means the key is only available a certain number of seconds from password authentication, and that passing in -1 requires fingerprint authentication every time you want to access the key. Enabling the requirement for authentication also has the effect of revoking the key when the user removes or changes the lock screen.
Because storing an unprotected key alongside the encrypted data is like putting a house key under the doormat, these options attempt to protect the key at rest in the event a device is compromised. An example might be an offline data dump of the device. Without the password being known for the device, that data is rendered useless.
The .setRandomizedEncryptionRequired(true) option enables the requirement that there is enough randomization (a new random IV each time) so that if the same data is encrypted a second time around, that encrypted output will still be different. This prevents an attacker from gaining clues about the ciphertext based on feeding in the same data.
Another option to note is setUserAuthenticationValidWhileOnBody(boolean remainsValid) , which locks the key once the device has detected it is no longer on the person.
Encrypting Data
Now that the key is stored in the KeyStore, we can create a method that encrypts data using the Cipher object, given the SecretKey . It will return a HashMap containing the encrypted data and a randomized IV that will be needed to decrypt the data. The encrypted data, along with the IV, can then be saved to a file or into the shared preferences.
Decrypting to a Byte Array
For decryption, the reverse is applied. The Cipher object is initialized using the DECRYPT_MODE constant, and a decrypted byte[] array is returned.
Testing the Example
We can now test our example!
Using RSA Asymmetric Keys for Older Devices
This is a good solution to store data for versions M and higher, but what if your app supports earlier versions? While AES symmetric keys are not supported under M, RSA asymmetric keys are. That means we can use RSA keys and encryption to accomplish the same thing.
The main difference here is that an asymmetric keypair contains two keys, a private and a public key, where the public key encrypts the data and the private key decrypts it. A KeyPairGeneratorSpec is passed into the KeyPairGenerator that is initialized with KEY_ALGORITHM_RSA and the «AndroidKeyStore» provider.
To encrypt, we get the RSAPublicKey from the keypair and use it with the Cipher object.
Decryption is done using the RSAPrivateKey object.
One thing about RSA is that encryption is slower than it is in AES. This is usually fine for small amounts of information, such as when you’re securing shared preference strings. If you find there is a performance problem encrypting large amounts of data, however, you can instead use this example to encrypt and store just an AES key. Then, use that faster AES encryption that was discussed in the previous tutorial for the rest of your data. You can generate a new AES key and convert it to a byte[] array that is compatible with this example.
To get the key back from the bytes, do this:
That was a lot of code! To keep all of the examples simple, I have omitted thorough exception handling. But remember that for your production code, it’s not recommended to simply catch all Throwable cases in one catch statement.
Conclusion
This completes the tutorial on working with credentials and keys. Much of the confusion around keys and storage has to do with the evolution of the Android OS, but you can choose which solution to use given the API level your app supports.
Now that we have covered the best practices for securing data at rest, the next tutorial will focus on securing data in transit.
Источник