Securing your Android apps

Go to the profile of Ali MuzaffarAli Muzaffar

Securing your Android apps #SecurityMatters

App developers tend to be quite reactive when it comes to app security. Sure there are apps out there that require security to be a focal point, but in reality, for most apps, security isn't big concern till something goes wrong. Here are a few tips I've found that you should keep in mind to help you pro-actively build secure apps.

Its nearly impossible for me to cover every scenario for you, most apps will have fairly distinctive security requirements, however we can follow the 80–20 rule and cover the most common app security aspects. That being said, I strongly recommend you read Android Security Tips.

App security falls largely into 3 categories:

  1. Networking
  2. On device storage
  3. Good coding practices

Networking

There are a few different ways in which a malicious hacker can get a hold of your data by exploiting network traffic, the most common ones are:

  • Trick your device into proxying through one of their servers to connect to your end-point. Not unlike the debugging proxies you may use while coding. The difference here is that he will emulate your end point with a valid certificate and once he has your data (API key, cookie and whatever else) he can connect to your API end-point and get more data. This sort of attack is easier than you think, you would simply have to set up “free WiFi” and configure the WiFi with a DNS server which resolves all domain names (or the domain names the hacker is interested in) to a malicious server. When you connect to the WiFi and try to access your site… boom, you’re compromised. This alone is a great reason to never trust free WiFi or do anything sensitive on public WiFi. There are a few different variants of this attack but the general concept is the same. This kind of attack is known as a Man-In-The-Middle (MITM) attack.
    I realize that SSL certificates will likely throw up errors in this scenario and the hacker will have to use a self signed certificates or certificates issues by a valid authority that don’t match the domain, however there are still scenarios (that I'm purposefully glancing over) in which your app can be compromised.
  • If your network traffic is not secured, a malicious hacker could simply sniff the network for traffic, he would really only have to listen for activity on certain ports such as 80, 443 or 8080 and he would pick up most unencrypted web traffic.
  • User can input malicious data in order to break your code.
How to protect your app

The absolute basics here are:

  1. Always use SSL connections if there is anything sensitive at all about your apps data.
  2. Never use self signed certificates in production. As a matter of fact, avoid them in testing as well.
  3. Disable HTTP redirects in your networking library/code. Some libraries disable this by default. Having these enabled can make MITM attacks a lot easier.
  4. If the user is inputting data, always escape it using URLEncoder.encode(userInput, “UTF-8”); if the data will be used as part of a URL.
    Side note: Its mentioned later, but always escape it, if its going to be used for DB queries as well as if you’re saving the input to a JSON or XML file.
  5. Set a maximum length on every field that requires user input.
  6. Validate the input.
Pro Tip for Networking

If you want to use self signed certificates securely and/or want protection against MITM attacks, you should be using a technique known as Certificate and public key pinning or some times referred to as Certificate pinning.

Normally certificates are validated by checking a signature hierarchy store on our device. MyCert is signed by IntermediateCert which is signed by RootCert, and RootCert is listed in your devices “certificates to trust” store.

Note: The problem that often comes up on Android is that the “certificates to trust” does not contain some well known certificate issuing authorities. This technique can help you bypass that problem as well.

In certificate pinning, you ignore the standard procedure of checking the signature hierarchy and tell your app to only trust a certain certificate. This means that if someone does a Man-In-The-Middle attack, your application will reject his certificate even if it is issues by the president of VeriSign himself.

Here are a few good resource on implementing this in Android.

On device storage

This area is covered well by Android Security Tips. The truth is, the most secure way to store data on a device, is to not save data on the device to start with. Unless you have a security team auditing your app looking for all possible loopholes, if possible, avoid storing truly sensitive data on the device. That being said, since I know you’re a renegade, there two main scenarios here:

  • Internal data storage.
  • External data storage.
Android external data storage

If security is essential, you should not store any data on external storage. The main reason for this is that data on external storage is globally readable and writeable.

If your app happens to be one that needs to store large quantities of encrypted data on the device, then you may not have the option to only use internal storage. Again, this is highly unlikely, because some full-HD games can store almost a gig of data on your phones internal storage. However, if you must use external storage, my advice is:

  • Use a binary serialized format (makes it much harder to access the data for the average user).
  • Secure sensitive data that does not need to be displayed (such as passwords) as a hash. A hash is one-way, it cannot be un-hashed or decrypted.
  • In your data, encrypt all sensitive information. You can secure the information inside your files or secure your entire file using something likeFacebook conceal library.
Android internal data storage

Android internal storage is fairly secure because of Android sand boxing its apps by implementing a UID level control on the files. However, because of issues such as rooting and ADB allowing developers to copy data off devices, internal storage is not as secure as some apps would like.

While a user having root level access on a device is not technically a threat, we should do out best to protect sensitive data.

Internal storage includes but is not limited to:

  • Files you choose to persist.
  • Temporary files / Cache
  • Database
  • SharedPreferences
Reading and writing files

The Android Security Tips covers how to deal with interprocess communication and reading writing files to internal storage.

What I would like to add, again, is a recommendation to save your data as a binary serialized format, considering compressing and encrypting the data. Something like Facebook Conceal can provide fast encryption and decryption of files. If you do implement AES, Blowfish or any other form of encryption yourself, generate your passphrase or key using a SecureRandom number generator and save your encryption key in something like KeyStore, if it needs to be reused.

Temporary files and cache

In general, you shouldn't cache or put into temporary storage anything sensitive. Temporary files and cache may include things like network images and HTTP cache. Most libraries should implement a certain amount a security for the HTTP cache and images are generally not a security issue. If either of these need to be secured, you should:

  • Clear cache when the app exits.
  • Configure a very short cache expiry.
SharedPreferences

This is perhaps the easiest way to persist data for your app. There are someimplementations of secured SharedPreferences on the internet that hash the key and encrypt the value. While this is better than nothing, I would recommend not storing sensitive data in SharedPreferences. If you must, using an implementation such as the one linked earlier and, do not hard code your security key in your code, instead use a SecureRandom number generator to create a random key and save your encryption key in something like KeyStore for reuse.

Database

Database encryption is a bit of a polarizing topic on-line. Generally people fall into one of three categories:

  1. Don’t put secure data into SQLite
  2. Only encrypt the sensitive data and, don’t encrypt data you need to query on, or if it’s sensitive, hash it instead of encrypting it.
  3. Use SQLCipher for everything.

This in general sums up the advice I could possibly have as well, I personally prefer the second approach. However, as mentioned earlier, the best way to secure data, is to not persist it to start with.

SQLCipher I personally have nothing against, however, as a developer, using SQLCipher and simply implementing it alone feels like overkills for most apps. It also bloats the size of your apk as it bundles a version of SQLite into your app.

SQLCipher is also fairly hard to work with with. Querying the database on a device adds a few steps and requires SQLCiphers tools. Overall, I really like SQLCipher as an option, but your data must be super sensitive to justify the development and code complexity overhead.

Good coding practices (Code goodly)

Through the course of this article, I've mentioned various things that technically come under the category of good coding practices. In this section I'm going to list as many of them as I can think off. Feel free to message me and ask me to add more or respond to this article with more best practices.

Validate and Escape user input

This was already covered to some extent.

Always set a maximum input size on all your fields. Validate the input to ensure that it matches your expectation (length, numeric, alpha numeric, etc.).

If user input is being used for URL parameter values, make sure to use URLEncode to escape user input.

If user input is being used for SQL queries, make sure to SQL escape the input if you are building the query yourself. Best way to avoid SQL injection attacks is to not build SQL queries yourself. Instead use the API provided by the framework.

If user input is being written to an XML or JSON file, make sure to escape it.

Pro tip: Apache commons has an StringEscapeUtils class that can escape strings for most common formats.

Do not hard code encryption keys

This is covered above a few times. If you are using AES, Blowfish or an other form of encryption that requires a pass phrase or encryption key, instead of hard coding it into your source, generate it with a SecureRandom number generator and store it in something like KeyStore for reuse.

Secure your Interprocess Communication

I would read Android Security Tips on this one as it cover the topic in good detail. I would however add that with Broadcasts, always useLocalBroadcastManager if you don’t want other apps to intercept your broadcasts. If your broadcast receiver does not need to intercept broadcasts from other apps, register and un-register them with the LocalBroadcastManager. If you want to listen to communication across different apps, then consider adding a permissionLevel=”signature” to your BroadcastReceiver.

Others
  • Do not persist sensitive data if you don't have to.
  • Make sure your web server sets short TTL or cache expiry time on sensitive data.
  • Clear your cache when the application exits (if it contains sensitive data).
  • Do not implement your own Cipher.

Finally

In order to build great Android apps, read more of my articles.


Yay! you made it to the end! We should hang out! feel free to follow me on Medium, LinkedInGoogle+ or Twitter.

RESPONSES

These are responses written or recommended by people you know on Medium, the author, or publication editors.

Great article with a summary of so many useful security tips

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1 目标检测的定义 目标检测(Object Detection)的任务是找出图像中所有感兴趣的目标(物体),确定它们的类别和位置,是计算机视觉领域的核心问题之一。由于各类物体有不同的外观、形状和姿态,加上成像时光照、遮挡等因素的干扰,目标检测一直是计算机视觉领域最具有挑战性的问题。 目标检测任务可分为两个关键的子任务,目标定位和目标分类。首先检测图像中目标的位置(目标定位),然后给出每个目标的具体类别(目标分类)。输出结果是一个边界框(称为Bounding-box,一般形式为(x1,y1,x2,y2),表示框的左上角坐标和右下角坐标),一个置信度分数(Confidence Score),表示边界框中是否包含检测对象的概率和各个类别的概率(首先得到类别概率,经过Softmax可得到类别标签)。 1.1 Two stage方法 目前主流的基于深度学习的目标检测算法主要分为两类:Two stage和One stage。Two stage方法将目标检测过程分为两个阶段。第一个阶段是 Region Proposal 生成阶段,主要用于生成潜在的目标候选框(Bounding-box proposals)。这个阶段通常使用卷积神经网络(CNN)从输入图像中提取特征,然后通过一些技巧(如选择性搜索)来生成候选框。第二个阶段是分类和位置精修阶段,将第一个阶段生成的候选框输入到另一个 CNN 中进行分类,并根据分类结果对候选框的位置进行微调。Two stage 方法的优点是准确度较高,缺点是速度相对较慢。 常见Tow stage目标检测算法有:R-CNN系列、SPPNet等。 1.2 One stage方法 One stage方法直接利用模型提取特征值,并利用这些特征值进行目标的分类和定位,不需要生成Region Proposal。这种方法的优点是速度快,因为省略了Region Proposal生成的过程。One stage方法的缺点是准确度相对较低,因为它没有对潜在的目标进行预先筛选。 常见的One stage目标检测算法有:YOLO系列、SSD系列和RetinaNet等。 2 常见名词解释 2.1 NMS(Non-Maximum Suppression) 目标检测模型一般会给出目标的多个预测边界框,对成百上千的预测边界框都进行调整肯定是不可行的,需要对这些结果先进行一个大体的挑选。NMS称为非极大值抑制,作用是从众多预测边界框中挑选出最具代表性的结果,这样可以加快算法效率,其主要流程如下: 设定一个置信度分数阈值,将置信度分数小于阈值的直接过滤掉 将剩下框的置信度分数从大到小排序,选中值最大的框 遍历其余的框,如果和当前框的重叠面积(IOU)大于设定的阈值(一般为0.7),就将框删除(超过设定阈值,认为两个框的里面的物体属于同一个类别) 从未处理的框中继续选一个置信度分数最大的,重复上述过程,直至所有框处理完毕 2.2 IoU(Intersection over Union) 定义了两个边界框的重叠度,当预测边界框和真实边界框差异很小时,或重叠度很大时,表示模型产生的预测边界框很准确。边界框A、B的IOU计算公式为: 2.3 mAP(mean Average Precision) mAP即均值平均精度,是评估目标检测模型效果的最重要指标,这个值介于0到1之间,且越大越好。mAP是AP(Average Precision)的平均值,那么首先需要了解AP的概念。想要了解AP的概念,还要首先了解目标检测中Precision和Recall的概念。 首先我们设置置信度阈值(Confidence Threshold)和IoU阈值(一般设置为0.5,也会衡量0.75以及0.9的mAP值): 当一个预测边界框被认为是True Positive(TP)时,需要同时满足下面三个条件: Confidence Score > Confidence Threshold 预测类别匹配真实值(Ground truth)的类别 预测边界框的IoU大于设定的IoU阈值 不满足条件2或条件3,则认为是False Positive(FP)。当对应同一个真值有多个预测结果时,只有最高置信度分数的预测结果被认为是True Positive,其余被认为是False Positive。 Precision和Recall的概念如下图所示: Precision表示TP与预测边界框数量的比值 Recall表示TP与真实边界框数量的比值 改变不同的置信度阈值,可以获得多组Precision和Recall,Recall放X轴,Precision放Y轴,可以画出一个Precision-Recall曲线,简称P-R
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值