Skip to content

Kernel security

CHEF-KOCH edited this page Dec 10, 2015 · 23 revisions

❗ This article is far away from a final version. ❗

Index

An fantastic explanation and overview about Android's security mechanism can be found at the TheNewCircle [05.2013] or directly on source.android.com.

⚠️ This is a POC (Proof-of-Concept) and WIP (Work-in-process) article, it's not designed (and never will be) to explain everything or show every possible configuration (it's simply impossible) and is more designed to quickly show the most important configurations, tricks or researches.

Due the lack of security of the consumer devices is not necessarily Android's problem. So far, most problems come from OEM's customization, and third party malicious apps pretending to be good citizen. Hardening the kernel won't fix all of these problems. ⚠️

To prevent some of the latest networking attacks, you should try to keep your Kernel version current as soon as possible! This is the first and easiest step since a lot of modded/custom kernels are ready to download and flashable (.zip).

Introduction

AFWall+ is a only a GUI for IPTables and people may want to know more about how they can generally hardening the lowest-security-level on there devices (Kernel/ROM). As the kernel controls your device networking, it is important that it be very secure, and could not be compromised. If the kernel is already compromised most of all security related features could be bypassed without any notification or log entry.

The config file of your currently running kernel is also always available in your file system at /proc/config.gz.

The main benefit and the main goal is to secure the kernel, so that no external tools are necessary.

The Linux Kernel isn't exactly the Android Kernel, there are several things you can't find in the original Linux kernel, like OOM, Wakelocks, pmem, Binder, logger, ... - These features are unique to Android only systems.

Kind of attacks:

  • Offline attacks (physical attacks, side-loading, bypassing, off-device attacks ...[mostly needs root]).
  • Online attacks (on the network stack against malware, dos, ...) (optional - OS specific)
  • On Android 5+ the user password is now protected against ordinary brute-force attacks using scrypt and, if available, the key is bound to the hardware keystore to prevent off-device attacks (i.e. brute-force). As always, the Android screen lock secret and the device encryption key are not sent off the device or exposed to any application.
  • TLSv1.2 are now enabled by default. Look, here that also means that Forward secrecy is enabled too which is used in AES-GCM (needs Play-services 7.x+ installed). The weak and vulnerably cipher suites like MD5, 3DES are by default disabled. Some pages are still using vulnerable RC4 ciphers, you should avoid visiting them especially if you care about security.

Overview

Android use the standard process isolation to split application it therefore performs fork or exec when starting application. At the Unix level application are also, by default, run as different Unix users. This isolates application and protects applications from reading each-others data. By requesting permissions in the apk's AndroidManifest.xml it is possible to get those granted by the PackageManager. Such permissions can result in applications being run under the same user id as a other package or run with additional unix groups. Some group will give the application access to devices nodes or other files. Other Unix groups are mapped to Linux process capabilities being granted.

Binder: As packages by default are running as separate user + process when they need to communicate the need to use some form of Inter process communication. In Android the preferred communication mechanism is called "binder". When processes communicate with each-other using binder Android will allow the service side code code to check if package manager was granted certain permissions by calling checkCallingOrSelfPermission() of the context class. The implementation of this is done in the (native) service manager class. This class uses the service called “permission” that is implemented by the ActivityManagerService.java in the checkComponentPermission(permission, pid, uid, req-Uid) method and follow the following logic:

  • The root and system user will always be granted all permissions
  • If the permissions == NULL the permission will be granted
  • In the other situation a request is sent to the package manager to check the permission based on the user id of the package.

Permissions

They are located at frameworks/base/core/res/AndroidManifest.xml and they're also can be declared in other manifest files (malware use this in order to bypass this mechanism). Pre-defined rules are depending with the OS version under /etc/permissions/*.xml or frameworks/base/data/etc/platform.xml, all other .xml files are read during the runtime.

There are different Permission levels:

  • Level 0 protection normal (A lower-risk permission that gives an application access to isolated application-level features)
  • Level 1 protection dangerous (A higher-risk permission that would give a requesting application access to private user data or control over the device that can negatively impact the user)
  • Level 2 protection signature (A permission that the system is to grant only if the requesting application is signed with the same certificate as the application that declared the permission.)
  • Level 3 protection signature or system (A permission that the system is to grant only to packages in the Android system image or that are signed with the same certificates.)

Scheme:

  • A permission definition is declared in a manifest file. The manifest frameworks/base/core/res/AndroidManifest.xml)
  • A permission defines it’s own security level. contains many if not all of the platform permissions.
  • A permission belongs to a group of permissions (this is mostly used by the UI to tag permissions).
  • A permission belongs to a package and it has it’s certificate associated to it.

Feature implementations

The following examples show what can be integrated (of is already integrated) into the Kernel for security reasons:

  • grsecurity (not available for Android yet?!)
  • SELinux (introduced in Android 4.3.x -> Kernel 2.6+) up-to-date info is always available here
  • SecDroid (optional - deprecated)
  • CIS Benchmark (optional)
  • Pentests (optional - Penetrations tests are only for experts and can be used to find known holes, like Metasploit)
  • Bastille Linux (not available for Android yet)
  • IPTables (if not present AFWall+ brings them to your device!)
  • LIDS (not available for Android yet!)
  • Linux Security Modules (LSMs)
  • OpenSSL (integrated)
  • Cryptography, AES, RSA, DSA, and SHA + API's for SSL/TLS and HTTPS (since Android 3.0 but weak)
  • Encryption (since 3.0 but weak)
  • -> Known attacks can be found here [no direct links since they are mostly POC's and they of course will be fixed with next Android versions - so it's more for historical reasons]

Already implemented in every Android OS:

  • Basic Password protection
  • Process isolation like a Sandbox (Androids security model is based on application sandboxing)
  • Device Administration (Android 2.2+)
  • A permission model for each user like on UNIX
  • IPC security apps can explicitly share resources and data via Intents, ContentProviders, IPC and Binder and of course via the file system and local declared sockets)
  • (optional) The ability to remove apps/system related kernel parts which may be insecure by design (depending on needs)
  • Root ability (but restricted to the Kernel e.g netd + a view core applications)
  • (optional) Security Tips | Android Developers
  • Android supports many cryptographic and encryption tools and algorithms such as AES, RSA, DSA, SHA, CBC, and ESSIV:SHA256. See also here, here, here and here.
  • Another powerful security measure is that fact that the Android operating system (Linux kernel, libraries, app runtime + framework, etc.) is on its own partition that is read-only. Also, Android uses Unix-style file permissions (except for FAT32 filesystems). Due performance and security reasons it's recommend to use ext4 (because the integrated encryption works only with this and on Samsung devices it must be vfat).
  • It is interesting to know that most of Android's security is meant to protect itself, not your personal files. While both are secured, there are more security measures that protect the operating system than the personal files (like pictures, music, contacts, etc.).

For app developer:

  • SIM Card Access - Low level access to the SIM card is not available to third-party apps. The OS Handles all communication with the SIM Card.
  • Cost Sensitive APIs - Cost sensitive means using them might generate cost, thus android provides a protection in OS level. Applications must grant explicit permission to use these APIs. Mostly: SMS/MMS, Telephony, Network/Data, In-App Billing or NFC Access.
  • Sensitive Data Input Devices - Applications must grant an explicit permission to use input devices such as the Camera, GPS and the Microphone.
  • Device Metadata - Device information might contains user information, thus applications must grant to access the OS system logs, Browser history, Hardware (such as network identification information) and the Phone number.
  • Application Signing - ......
  • Storing Data - Internal Storage - By default, files that you create on internal storage are accessible only to your app, make sure you not use MODE_WORLD_READABLE & MODE_WORLD_WRITEABLE (Google Play Store also scans for this) + Use content provider for share and prefer encryption for additional protection
  • Storing Data - External Storage - Do not store executables or class files. + Always retrieve signed and verified files. See also here.
  • Android Resources/Assets - Please never share/store any sensitive information and if possible meta-data such as the keystore, keys,[...] because they can read and accessed by anyone.
  • Permission Model - If possible: Minimize the permission request and never request unless it's really needed or it would break your app. Protect the IPC via permissions to avoid leak permission-protected data.
  • Performing Input Validation - If possible beware of JavaScript injection and SQL injection and verify the format. + Make sure if native code is used that there are non potential secure issues.
  • Handling User Data - If a GUID is required, use UUID. Do not use phone identifiers.
  • WebView - ....
  • Handling Credentials - ...
  • Be aware of reverse engineering - The application apk can be exported easily. Apk itself is a zip folder and it is very easy to extract it (via apktool and others).
  • Be aware of app licensing - Google Play offers a licensing service that lets you enforce licensing policies for applications that you publish on Google Play. With Google Play Licensing, your application can query Google Play at run time to obtain the licensing status for the current user, then allow or disallow further use as appropriate.

Networking:

  • CONFIG_FIREWALL
  • CONFIG_IP_FORWARD
  • CONFIG_SYN_COOKIES
  • CONFIG_IP_FIREWALL
  • CONFIG_IP_FIREWALL_VERBOSE
  • CONFIG_IP_NOSR
  • CONFIG_IP_MASQUERADE
  • CONFIG_IP_MASQUERADE_ICMP
  • CONFIG_IP_TRANSPARENT_PROXY
  • CONFIG_IP_ALWAYS_DEFRAG
  • CONFIG_NCPFS_PACKET_SIGNING
  • CONFIG_IP_FIREWALL_NETLINK

AID

  • AID_NET_BT
  • AID_NET_BT_ADMIN
  • AID_INET
  • AID_NET_RAW
  • AID_NET_ADMIN

The full list can be found over here.

Kernel Compiling hardening:

  • CONFIG_FILTER 1
  • net.core.bpf_jit_enable 0

SELinux

Read the following pages to better understand and possible solve SELinux related problems (scripts, binaries,..):

The IPTables/scripts should run at u:r:init:s0 to avoid possible security problems, since this is the only authorization we need.

Alternatives to SELinux (MAC) / DAC.

Role-based control:

  • Grsecurity RBAC which does not have that much metadata compared to SELinux and is around 30% faster.

MAC (pathname based access control)

  • APPAmor (not yet for Android?) but a similar function is introduced in Android 6.0 (see below).
  • Tomoyo (not yet for Android?)

Android Logging System

The Android system has a logging facility that allows system wide logging of information, from applications and system components. This is separate from the Linux kernel's own logging system, which is accessed using 'dmesg' or '/proc/kmsg'. However, the logging system does store messages in kernel buffers.

  • The Kernel driver is called logger
  • Application Log is used by android.util.Log class
  • System log is used to keep their messages separate from the application log messages system
  • Event log are created by using android.util.EventLog class
  • ADB (Android Debug Bridge) reference page is available over here (if ADB is not global wide disabled it's the easiest way to logcat the necessary stuff you want to see)

We have four log buffers:

  • events : System event related information /dev/log/main
  • main : The main application log
  • radio : Phone/radio related information
  • system : Low-level system messages (for e.g. debugging reasons)

GSM security

Android use the following Global System for Mobile Communications specifications:

  • A5/0 was disabled in Europe by most providers
  • Encryption is based on A5/1 (known as vulnerable + Security) The key length is 128 bit, it's widely used in North America.
  • A5/2 seems also deprecated
  • A5/3 is mostly used
  • UMTS-Communication use Signalling System 7 (SS7) which can be bypassed via side-channel attacks
  • NSA and others are able to crack it + Full Story
  • Handy-Jammer are often used to block UTMS signals, so that the lower bandwidth e.g. over GPRS will be used instead - because the basic station force the connectivity. After that it's possible to enable the bull-encryption option.
  • Some provider claim to use a more secure A5/3 instead of A5/1 or A5/2, needs confirmation (country specific).
  • The full specifications for all networks can be found over here

LTE Vs. GSM

In fact the new LTE is less secure since there is no common used standard which makes it possible to get the data via e.g. Ethernet-Uplink. Some providers saying that they use a strong encryption via digital signatures, the problem is that there is no proof if they really use such security gateway (because the LTE standard does not require such gateway).

How the NSA/GCHQ crack it?

Research:

Detectors:

⚠️ Actually there is no tool/app/API which protects against this known weaknesses, all apps only warn about possible problems but they're not able to fix them! ⚠️

Disable binaries

Each application is given its own Linux User ID (UID) and group ID, besides this indication some apps need the following binaries to work, so removing them blocks possible attacks direct on the device (Offline).

  • irsii
  • bash (optional, default removed)
  • SQL
  • nano
  • nc (net cat)
  • netserver
  • netperf
  • opcontrol
  • rsync
  • scp
  • sdptest
  • ssh
  • sshd
  • strace
  • tcpdump
  • vim
  • ping (needs root)
  • pm (needs root)
  • adbd (needs root -> adb deamon)
  • ...

Security Tricks

Some applications require more permissions (e.g. Flashlight) than they really need. You can alter the set of permissions granted to an application by editing /data/system/pacakges.xml. After editing you need to reboot the device, because it gets overwritten by the system again. All changes will be read at system boot.

On some external ROMs, there is also an GUI for this, it's called Privacy Guard which first was introduced in CyanogenMod 11. This makes it easier for users to disable critical permissions on an app-by-app basis. An alternative on newer system seems XPrivacy (includes a basic firewall) or AppOps.

Protection against spoofing attacks

#Global via sysctl
net.ipv4.conf.all.rp_filter=1
#net.ipv6.conf.all.rp_filter=1

#Via iptables (for e.g. logging) [this solution is better]
iptables -t raw -I PREROUTING -m rpfilter --invert -j DROP

SMS: With Android 4.2, the user gets a notification when the SMS feature is used, then user decides to whether send the message or not.

Application Signing: Never ever forget your keystore. Send it via email to yourself to keep it. If you lose your keystore, you won't be able to get it back and you cannot update your application anymore.

General Security tips:

Protection against other attacks

Bruteforce

A lot of wrong statements are on the internet to stop e.g. bruteforce by simply using a blacklist. In fact if you use iptables as a blacklist you will suffering from the following problems:

  • /var may become full because everything will be logged in here (e.g. in the attacker is pounding our server)
  • The attack may already got your IP address which allows to send packets with a spoofed source header, overall that would mean you get locked out of the server
  • Higher memory usage

To solve this you can work with SSH keys, which are not affected by the above two mentioned problems. So we can use:

iptables -N SSH_IN
iptables -A INPUT -p tcp --dport ssh -m conntrack --ctstate NEW -j SSH_IN
iptables -A SSH_IN -m recent --name ssh --rttl --rcheck --hitcount 5 --seconds 15 -j DROP
iptables -A SSH_IN -m recent --name ssh --rttl --rcheck --hitcount 6 --seconds 1200 -j DROP 
iptables -A SSH_IN -m recent --name ssh --set -j ACCEPT

This was original taken from here.

Android Marshmallow

Official supported devices

With Android Marshmallow (Kernel 4.1+) (API level 23) a lot of under the hood changes are coming to the user including a new permission controlling system that works similar compared to AppOps and integrates an user interface that allow to control most of all permissions. Compared to Android 4/Lollipop that means you don't have only two options (take it and accept it or simply do not install it) - now you now can just install everything and change e.g. the camera permission to avoid that your new installed application (or existent) can take control over that. See, also the Preview Overview article.

In fact that makes more or less most of security apps obsolete since the user can control what permission which app can really use. Except the internet stuff (since Google simply never wants it, because ads reasons,[...]) which overall means firewalls have still a solid standing.

The same principle as a firewall can be used to control the permission (whitelist/revoke access), which possible FC some apps first that are not updated. For malware reasons that means using AFWall+ & the new system it would be a lot harder to bypass all of these protections (of course the existent apps need a small update to support that feature).

Firewall specific: Under Android M, app data will be automatically backed-up onto Google Drive on a daily basis, when the phone is connected to WiFi and power (opt-out option), that may lead in more traffic if the user forgets to disable it, so it's highly recommend to check this setting. See also AOSP Network Security Policy, over here.

HTTPS: application android:usesCleartextTraffic = "false” / will prevent any component in the app from performing any network I/O over unencrypted socket connections (supports HTTP, FTP, WebSockets, IMAP, SMTP & XMPP). This was designed for third party libraries that use insecure channels of communication. In fact that could be bypassed in the future.

Android N

Android N is coming 2016 and will bring a lot of changes, it get Chrome OS parts and possible break a lot of AFWall+ related stuff, which we need to track down to get it work again.

Physical security

  • Strong disk encryption (but also comes with major weaknesses, speed/memory or lockdown problems)
  • Bootloaders (by default coming with a signature), see also magic boot
  • Syslinux to protect the bootloader with a password, this is obsolete since Android 5.x (as also only experimental because no official Android support)
  • Apps like Cerberus to find your device in case it gets stolen (must be running all the time in the background and not protects against bootload attacks). I doubt that any attack is that stupid to not remove the battery or replace the app under CWM/TWRP or simply flash another Kernel/ROM to bypass it.

Useful links

Feed:

Security focused forums and discussions:

PDF:

Android Vulnerability List:

Online Analyzers:

Android Testing:

Hooks (may unstable, all of them requires root):

Forensics tools:

Todo:

  • add example malware app on android to show possible holes (low-prio), most known and popular vulnerable app seems InsecureBank V2
  • Sort vuln. via own categories
  • Complete the article somehow
  • add things user report via eMail