- ‘SAW’-ing through the UI: Android overlay malware and the System Alert Window permission explained
- What is Android screen overlay and what’s it for?
- The System Alert Window Android App Permission
- Mobile App Vetting for Supply Chain
- Potential abuses of the System Alert Window permission
- Android overlay attacks and ransomware
- How can I protect myself against abuse of the System Alert Window permission?
- Подготовка приложения к Android Q. Часть 1
- 1) Конфиденциальность и безопасность
- а) Запуск фоновых Activity
- б) Аппаратные идентификаторы
- в) Фоновое определение локации
‘SAW’-ing through the UI: Android overlay malware and the System Alert Window permission explained
Over the past month, we’ve talked about a troublesome Android app permission called `SYSTEM_ALERT_WINDOW` a couple of times in our weekly #MobSec5 news digest — subscribe here. This week, researchers from University of California Santa Barbara and Georgia Institute of Technology released details about “Cloak and Dagger” a collection of attacks that take advantage of this permission. Customers 1 have asked me about `SYSTEM_ALERT_WINDOW` (abbreviated SAW for the purposes of my oh-so-witty headline) a nd how malware might abuse the Android overlay view to steal log-in credentials and the like from Android users. I wanted to explain the Android app permission in plain language, how it might be abused, and finally what people can do to mitigate the risk.
What is Android screen overlay and what’s it for?
A screen overlay in Android, also referred to as “Draw On Top”, allows an app to display content over another app. The Android app permission SYSTEM_ALERT_WINDOW makes this possible. If you’ve ever used an app like Facebook Messenger or Lastpass, you’ve experienced screen overlay in action. Basically, the permission allows a developer to display content on the screen of your Android device after some trigger event.
For example, you may have seen the cute notification bubble in Facebook Messenger (also called a “chat head” — see the screenshot above) that includes a contact’s photo. If you tap the chat head, it leads to a pop-out version of the Messenger app. Have you noticed that you never gave Facebook Messenger permission to display that bubble?
The System Alert Window Android App Permission
Android Marshmallow (specifically Android 6 API Level 23), introduced the requesting of permissions at runtime. If an app wanted to access your calendar, camera, and other functionalities, the user needed to grant the permission. Unfortunately, that’s not always true of SYSTEM_ALERT_WINDOW . If a developer targets a lower API level like API level 22 in Android 5 (Lollipop), the Google Play store grants the permission without a runtime prompt. If your device uses Android 6.0.1 or higher and you install an app requesting the SYSTEM_ALERT_WINDOW permission, it’s granted by default! What this all means is that the only time a user will manually grant the “Draw Over App” permission is if they run Android 6.0.0 and the app is built for API level 23 or above, or when side-loading an app from a third party Android app store (something we usually recommend against for security’s sake).
This blows my mind, because if someone were so inclined, they could potentially compromise a user’s phone with the SYSTEM_ALERT_WINDOW permission using Android overlay malware. Overlay malware is not a new concept, and the Google Play Store has published a number of malicious apps that abused the Android screen overlay. The apps typically pose as something harmless. In one example of Android overlay malware discovered by ESET, a malicious flashlight app actually turned out to be banking trojan malware.
Mobile App Vetting for Supply Chain
Potential abuses of the System Alert Window permission
Generally, these attacks play out something like this
- A user downloads the malicious app
- A trigger activates the use of the SYSTEM_ALERT_WINDOW permission to display content over the top of the UI
- The screen asks the user for information, such as credentials, and the user divulges that information to make the screen overlay go away
The SYSTEM_ALERT_WINDOW permission makes a number of attacks possible, but overlay attacks seem to be the most prominent at this time. Once a malicious app has been installed on your device, the app will wait for the user to launch a target app. When the target app is launched, the malicious app produces an overlay to trick users into entering their credentials into a phony login screen. The user’s credentials are then sent to the attacker’s server.
The animation below demonstrates what an attack might look like on a victim’s phone. You can find the sample malware I used for the demonstration on Github: https://github.com/geeksonsecurity/android-overlay-malware-example.
Here’s what you’re seeing in the video:
- The user launches the Skype app
- The phony login screen is overlaid on top of the authentic login page
- After information is entered into the malicious screen, you see the actual Skype login page
Android overlay attacks and ransomware
With ransomware concerns rising in the wake of the WannaCry attack earlier this month, there have been some suggestions that overlay screens could be used to launch a ransomware attack on Android devices. This is pure speculation, but malware could potentially display an overlay screen demanding credit card information to make it go away. It’s possible some users will fall for the ploy when in reality their files weren’t encrypted or inaccessible and they could have exited the app via other means.
With that said, the Cloak and Dagger researchers have published a video demonstration of a clickjacking attack that might make such an attack possible. An overlay screen is displayed on top of the UI that includes “holes” that a user can be persuaded to click. Essentially, the user is “clicking through” the overlay screen to certain areas of a UI behind it. The clickjacking technique leverages both the SYSTEM_ALERT_WINDOW and BIND_ACCESSIBILITY_SERVICE . Such a technique could be repeated multiple times resulting in the user unknowingly clicking the settings interface to grant an app enough permissions culminating in the complete takeover of an Android device.
Also of concern is that nothing currently indicates to an app that another app is overlaying its UI. And this may be possible via apps published on the Google Play store, not a third party app store. While it might be tempting to call this a bug that can be patched, it seems like a fundamental flaw in Android’s permissions design.
How can I protect myself against abuse of the System Alert Window permission?
According to the Cloak and Dagger paper, an estimated 10 percent of apps on the Google Play store use the SYSTEM_ALERT_WINDOW permission. While an administrator might tempted to prohibit users from installing apps that request SYSTEM_ALERT_WINDOW , doing so would likely result in a staff revolt.
Some of the most popular apps on the store call on the SYSTEM_ALERT_WINDOW — not just malware. Users can see what apps have the permission using the instructions in the table below (instructions may not apply to all devices).
Version | How to review apps with Draw Over Other Apps permission |
---|---|
Android 7 | Settings > Apps > “Gear symbol” > Special Access > Draw over other apps |
Android 6 | Settings > Apps > “Gear symbol” > Draw over other apps |
Android 5 | Settings > Apps > Select app and look for “draw over other apps” |
In addition, before downloading an app, you can check to see if the app uses the `SYSTEM_ALERT_WINDOW` permission by reading the “Permission Details” on the app’s page in the Google Play Store and looking for a “draw over other apps” bullet.
What makes these `SYSTEM_ALERT_WINDOW`-based attacks so scary is Google’s app vetting process has failed to identify a few of these apps before they’re published on the public app store. Google has, however, started tackling this issue in Android O. There are reports that the beta version of Android O includes a mechanism that will notify users that app overlay is taking place. While this is a step in the right direction, Google might need to consider treating the overlay permission in the same way it treats camera permissions. Still, users stuck on older versions of Android could still fall victim.
1 Special thanks to Dan Dumitrescu, security specialist at a financial institution.
What to read next:
Mobile banking Trojans: What can financial institutions do?
A seeming resurgence in mobile banking Trojans has financial institutions asking questions. NowSecure CTO David Weinstein has answers.
Источник
Подготовка приложения к Android Q. Часть 1
Перевод статьи подготовлен специально для студентов курса «Android-разработчик. Базовый курс». Также напоминаем о том, что мы продолжаем набор на расширенный курс «Специализация Android-разработчик»
Мы находимся на 10-м году разработки Android (Android Q должен быть версией 10.0). В соответствии с Beta 4, официально у Android Q 29-й уровень API. Несмотря на то, что уже есть Beta 5 и ожидается Beta 6, API был помечен как окончательный, и сейчас самое время посмотреть, как Android Q повлияет на приложения и какие изменения нужно внести, чтобы полностью поддерживать Android Q.
Важные изменения (не все), представленные в Android Q, можно разделить на две категории: а) Конфиденциальность и безопасность, б) User Experience.
От переводчика: «Мы разделили перевод на две части соответствующие данным категориям. Соответственно в первой части поговорим о конфиденциальности и безопасности».
1) Конфиденциальность и безопасность
а) Запуск фоновых Activity
Больше нельзя запустить Activity, когда ваше приложение находится в фоновом режиме.
- На что влияет: Все приложения, работающие на Q (независимо от целевого SDK). Генерируется исключение, если Android Q — целевая версия приложения; и Activity просто не запустится, если Android Q — не целевая версия SDK для приложения, но оно работает на устройстве с Android Q.
- Исключения: Привязанные службы, такие как специальные возможности, автозаполнение и т. д. Если приложение получает PendingIntent от системы, мы можем использовать его для запуска Activity. Если у приложения есть разрешение SYSTEM_ALERT_WINDOW (удалено в Android GO) или приложение недавно вызывало finish() для Activity (не рекомендуется на это полагаться. «Недавно» может быть очень неоднозначным), тогда ваше приложение свободно от этого ограничения.
- Рекомендуемый подход: Уведомление, запускающее Activity
Добавьте Fullscreen PendingIntent к уведомлению. Теперь, когда уведомление сработает, система запустит полноэкранный Intent.
Поэтому, если мы хотим запустить Activity из фонового режима, сначала создайте уведомление, которое будет показываться пользователю. В этом уведомлении добавьте Fullscreen PendingIntent . Кроме того, добавьте разрешение USE_FULL_SCREEN_INTENT в свой манифест. Теперь, когда уведомление сработает, система запустит полноэкранный Intent.
- Подводные камни: Система решает, когда показывать уведомление и когда показывать Activity. Если пользователь активно использует устройство, то отображается всплывающее уведомление. Если устройство в состоянии покоя или когда пользователь взаимодействует с уведомлением, запускается полноэкранное Activity. Например, как при получении телефонного звонка (всплывающие уведомления во время использования телефона, в противном случае полноэкранное Activity).
б) Аппаратные идентификаторы
Доступ к несбрасываемым идентификаторам устройства был отменен в Android Q.
- На что влияет: Все приложения, работающие на Q (независимо от целевого SDK). Генерируется исключение, если Q — это целевое SDK; и возвращается null , если целевое SDK меньше Q
- Избегайте: Mac-адрес теперь рандомизирован, а IMEI ( TelephonyManager.getDeviceId() ) и серийный номер больше не доступны. Теперь они являются «привилегированными разрешениями» и доступны только для приложений операторов.
- Рекомендуемый подход: используйте сбрасываемые идентификаторы, такие как Advertising ID, Instance ID или Globally-unique ID (GUID). См. Best practices for unique identifiers (Лучшие практики по использованию уникальных идентификаторов) для получения дополнительной информации о том, какой идентификатор использовать в каком случае.
в) Фоновое определение локации
Начиная с Android Q, система будет различать запросы местоположения, сделанные на переднем плане и в фоне.
Запрос на разрешение доступа к местоположению теперь будет иметь 3 варианта: Разрешать все время, Разрешать только при использовании приложения (доступ только на переднем плане) и Запретить (нет доступа).
- На что влияет: Это зависит от целевого SDK. Если Q — это целевое SDK для приложения, то вам нужно запросить новое разрешение на определение местоположения в фоновом режиме. Если у приложения другое целевое SDK, оно автоматически получит это разрешение, если уже имело права доступа к местоположению.
Изображение взято из документации для разработчиков Android
- Рекомендуемый подход: если приложению требуется однократный доступ к местоположению пользователя для выполнения некоторых задач, используйте службу переднего плана с параметром foregroundServiceType, заданным как location в файле манифеста приложения.
Если приложению необходим постоянный доступ к местоположению устройства, например, для геозонирования, то оно может настроить запрос на разрешение доступа к местоположению в фоновом режиме. Другие аспекты приложения (например, как местоположение извлекается аи используется) менять не нужно. Чтобы запросить доступ к местоположению в фоновом режиме, добавьте в манифест разрешение ACCESS_BACKGROUND_LOCATION :
Запрос доступа к местоположению в фоновом режиме
Напоминание, показываемое системой, о доступе к местоположению в фоновом режиме
Несколько важных вещей, о которых следует помнить: пользователь может получить напоминание после предоставления приложению доступа к местоположению устройства в фоновом режиме, и, как и любое другое разрешение, пользователь может отозвать разрешение на него. Это особенно важно для приложений, у которых Q не является целевым SDK, но работающих на устройствах с Android Q, поскольку оно получило бы фоновое разрешение по умолчанию, если бы у него было разрешение на определение местоположения. Убедитесь, что приложение изящно обрабатывает такие сценарии. По этой причине всякий раз, когда приложение запускает службу или запрашивает местоположение, проверьте, позволяет ли пользователь по-прежнему получать приложению доступ к информации о местоположении.
На этом первая часть статьи подошла к концу.А о User Experiences, как и обещали, поговорим во второй части.
Источник