0% found this document useful (0 votes)
15 views67 pages

Mobile App Secure Coding Guidelines

The Centre of Digital Innovation (CoDI) provides secure coding guidelines for developers creating mobile applications for UAE mGovernment app stores, focusing on best practices for security and privacy. The document outlines ten key security guidelines for native mobile applications, including secure data storage, protecting data transportation, and avoiding exploitable code errors. It emphasizes the importance of encryption, secure authentication, and minimizing risks associated with third-party code and sensitive information logging.

Uploaded by

epilef
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views67 pages

Mobile App Secure Coding Guidelines

The Centre of Digital Innovation (CoDI) provides secure coding guidelines for developers creating mobile applications for UAE mGovernment app stores, focusing on best practices for security and privacy. The document outlines ten key security guidelines for native mobile applications, including secure data storage, protecting data transportation, and avoiding exploitable code errors. It emphasizes the importance of encryption, secure authentication, and minimizing risks associated with third-party code and sensitive information logging.

Uploaded by

epilef
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Centre of Digital Innovation presents

Mobile application
secure coding
guidelines

Secure coding for developers by developers


Version 1.0
1
“The mantra of any good security engineer is: 'Security is a not a
Introduction product, but a process.' It's more than designing strong cryptography
into a system; it's designing the entire system such that all security
measures, including cryptography, work together.”
– Bruce Schneier
Scope and organization of the document

The Centre of Digital Innovation (CoDI) device. This is a guideline for developers
Secure Coding Guidelines is a resource and the information contained within is
intended to give developers a guide to considered best practice but may not be
build secure mobile applications that will recommended for all applications.
be deployed in UAE mGovernment app
stores. This document assists the mobile This is the first version of the coding

app developers in different areas of code guidelines focused on iOS and Android

security and privacy. platforms. This document will be updated


as more security information becomes
This guide is split into ten separate available and as mobile platforms become
sections based on the security and privacy more mature.
of data transmitted and stored on the

2
2
“Security is always excessive
Native application until it's not enough.”
security – Robbie Sinclair
Head of Security, Country Energy, Australia
Top ten mGovernment security guidelines for
native mobile application

1. Store local data securely 6. Protect from reverse engineering

2. Protect remote data transportation 7. Secure web services and servers

3. Implement appropriate authentication 8. Validate input and interprocess


communications
4. Audit third-party code and services
9. Avoid exploitable code errors
5. Respect user data
10. Distribute an application securely

4
2.1 Secure local data storage

It is the role of an application developer to make sure that the data is secure while the user
is interacting with an application and when an application is at rest.

The objectives of this policy are:

• Ensure that all locally stored sensitive data is encrypted at rest

• Maintain data security even if an attacker has access to the physical device

• Educate the reader on some of the automatic caching policies implemented by mobile
operating systems

5
Platform specific technologies
Will a user store
Mobile operating system vendors provide OS-level protection
sensitive information
and developer APIs to aid an application programmer by
in an application? If
providing easy to use security algorithms and interfaces that
so, the app should
can be utilised to increase the security of an application.
encrypt the contents
when the data is at These APIs allow developers to store sensitive data in an
rest encrypted container and utilise standard cryptography
algorithms.

Developers should avoid using non-standard cryptography


libraries. Creating secure cryptography algorithms is an
extremely advanced concept that is very easy to get wrong.

Apple iOS:

• Apple provides CommonCrypto libraries enabling developers


to utilise cryptography algorithms within their application.

• Keychain is a system level encrypted container used for


storage of passwords and cryptographic keys. Although the
keychain is accessible from every application, an application
will only have access to it’s own items.

• The keychain can view the items of another application if the


application has the correct keychain-access-group set and
has the correct entitlements. This means that applications
developed by the same group can share data within their
own applications.

Android:

• KeyStore is responsible for maintaining cryptographic keys


and their owners at a system-level. Although KeyStore has

6
been available since Android 1.6 (Donut), the public API only became available in 4.0
(ICS).

• [Link] is the package available for Android developers for simple off-the-shelf
encryption. [Link] is capable of both symmetrical and asymmetrical encryption
(AES and RSA respectively)

Identify sensitive data storage

When designing a mobile application, a development team needs to identify sensitive data
requiring storage in an encrypted container. This may include data from a server, keys
used for encryption or identification, user information and user input.

Examples of sensitive data may include:

• Password entered into a text field.

• User storing bank account details in a notes application.

• Encryption key used to encrypt data.

Password storage

• There are many different forms of authentication that will not require the user to store
their password (See 2.2 authentication and 2.7 secure servers and services). If possible, a
developer should try to use those methods for storage.

• Sensitive data, such as passwords and keys, must be stored in an encrypted container
such as the keychain or the keystore.

Any data stored in an OS encrypted container may be at risk of being unencrypted on a


jailbroken/rooted device, therefore an additional layer of encryption is recommended for
sensitive device data that may be used in multiple scenarios, such as a username and
password.

7
Use sandboxed storage

Applications on many mobile operating systems store data within a sandbox that is not
accessible to other applications. Some platforms also offer the options of storing data on
globally available internal or external media.

When storing information on a mobile device a developer should:

• Save sensitive information within an application sandbox (either encrypted or within an


encrypted container).

• Avoid storing sensitive data on unencrypted storage, such as an SD Card since


accessing this information is trivial to any attacker.

• (Android) When storing data, avoid using MODE_WORLD_WRITEABLE and


MODE_WORLD_READABLE flags as this allows external access to an application’s
sandbox.

Consider using an encrypted container

• Although application data may be stored on an encrypted filesystem - this container can
be unencrypted if an attacker can crack the password on the operating system. To
mediate this, a developer should consider creating an additional encrypted container.
The recommendation below assumes that there is no network connection and/or keys
can not can be stored remotely. For secure remote storage, see 2.2 authentication and
2.7 secure servers and services.

• The custom secure container should be encrypted with either AES128 or AES256
symmetrical encryption algorithms. The key used to encrypt the container should be a
password inputted by the user that has been hashed, salted and stretched.

• Cryptographic hash functions are designed to take a string and turn it into a fixed length
hash value (known as a message digest). These hash functions are considered one-way
which means that it is practically impossible to invert the string to its original form.
Examples of cryptographic hash functions are SHA256 and SHA512.

8
Platform SHA256 Library SHA256 Function

Objective-C CommonCrypto CC_SHA256()

[Link] [Link]
Android
Digest ("SHA-256")

[Link]
C# SHA256Managed
ography

• A salt is a random string that is prepended to the password


(fdndfsifdnsdfiodsndfo + Pa$$w0rd1). This salt should be
Be security aware of generated at runtime with a Cryptographically Secure
third party code. Pseudo-Random Number Generator (CSPRNG) and
prepended with a user password.
Many code examples
• Do not generate a static salt for all passwords or create your
use poor security
own individual random number generator. Use platform
techniques (such as
provided CSPRNG algorithms or proprietary
a hardcoded
encryption key) to
simplify their test Platform CSPRNG
app. Objective-C SecRandomCopyBytes()

Android [Link]*

[Link]
C#
toServiceProvider

* SecureRandom on Android may be insecure. Consult the


following articles to learn how to improve the security of this
library:
[Link]
[Link]
[Link]
[Link]

9
• The salt should be a long CSRPNG string generated at
runtime and stored remotely or in the keychain/keystore.

• It is quite common to hash a digest, and then hash that


digest, and then hash that digest and so on and so on, to
make a key more secure and slow down a potential attack.
This process is known as stretching. Developers should not
create their own stretching algorithm.

• PBKDF2 applies a pseudo-random function (usually HMAC-


SHA1) to the passphrase along with the salt value and
Mobile operating repeats the process multiple times in order to produce a
systems regularly derived key. This process was recommended to be done
cache information in 1000 times, however many vendors use 10,000 iterations.
order to improve the The unofficial rule is that PBKDF2 should take roughly one
performance and second to compute. The end result of this stretching is
experience of the called a derived key.
device.
• Some platforms, such as iOS provide optimisation functions
Be sure that
allowing an application to calculate how many PBKDF2
sensitive information
calculations can be performed within a given time in order to
is not leaked through
work out at runtime how many iterations should be used.
these methods.
This is useful for calculating a secure 1-second iteration
count, but also has the disadvantage of not being
compatible across different devices.

Platform PBKDF2

Objective-C CCKeyDerivationPBKDF()

Android [Link] *

C# [Link]

10
• *PBKDF2 has changed in Android 4.4 due to issue 40578
f o u n d h e re a n d c o m p a t i b i l i t y m a y b e a ffe c t e d :
[Link]

• The derived key should be used to encrypt the database


using AES128 or AES256.

• The password nor the derived key should be stored on the


device. When validating the password, retrieve the salt and
Log information may hash from the database. Prepend the password to the
reveal sensitive securely stored salt and hash with the same cryptographic
information. Avoid hash function and stretch the digest with the same amount
logs in a release of PBKDF2 iterations. If the results match, then the user is
product. authorised. Otherwise, the password does not match.

(iOS) Utilize Data Protection

When storing data in the keychain, utilise the correct Data


Protection class to protect the secrets of an application while
the phone is locked.

Availability File Data Protection Keychain Data Protection

While kSecAttrAccessbleWhen
NSFileProtectionComplete
unlocked Unlocked

NSFileProtectionComplete
While locked N/A
UnlessOpen

kSecAttrAccessibleAfterFirst
After first NSFileProtectionComplete
Unlock
unlock UntilFirstUserAuthentication

kSecAttrAccessibleAlways
Always NSFileProtectionNone

The default on iOS 7.0 is


NSFileProtectionCompleteUntilFirstUserAuthentication and
kSecAttrAccessibleAfterFirstUnlock

11
If the secret that is being stored in a keychain is linked with that specific device, then add
the suffix “ThisDeviceOnly” to the Keychain Data Protection Classes, e.g.
kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly

Encryption keys:

• Developers should not hardcode an encryption key into an application. A long string
found in a binary can be assumed and tested as an encryption key.

• Keys should be generated at runtime and stored securely in a secure storage area such
as the keychain for iOS or the KeyStore for Android.

• Many third-party libraries and code snippets use a hardcoded encryption key in order to
simplify the demonstration. Developers should be aware of this when using encryption
algorithms found online.

Minimise the risk of data stolen:

• In cases where it is not feasible to have data always encrypted, the data should be
unencrypted only when needed. Sensitive data and files should be encrypted when they
are not in use.

• Mobile applications have specific application states; developers should use these states
to dictate whether data is encrypted or not.

• If possible, the data should be unencrypted in memory only; this may not always be
feasible.

Avoid caching sensitive information

• When utilising web browsing services, ensure that an application is only caching
appropriate information.

• (iOS) For secure sessions, consider using an ephemeral session which can be
created with the NSURLSession class.

12
• (Android) Set appropriate cookie, cache, history and form data settings on a
WebView:
[Link]().setAcceptCookie(false);

! [Link]().
! ! setCacheMode([Link]().LOAD_NO_CACHE);
! [Link]().setAppCacheEnabled(false);
! [Link]();
! [Link](true);

! [Link](this).clearFormData()
! [Link]().setSavePassword(false);
! [Link]().setSaveFormData(false);

• (iOS) When an application is closed, the system takes a screenshot of the application at
the time the application was shut and stores it on the filesystem. If an application has
sensitive information on the screen when the application is shut, it is recommended that
the saved image is deleted and a replacement image is used instead. This can be
inserted as the application is going into the background
(application:didEnterBackground:), or in response to being pushed into a suspended
state using iOS’ background processing APIs.

- (void)applicationDidEnterBackground:(UIApplication *)application {
UIImageView *replacementImage = [[UIImageView alloc]
initWithImage:@"[Link]"];
[Link] = replacementImage;
[[Link] addSubview: replacementImage];
}

• Developers must be aware of systems that will cache keyboard input as these caches
may be available on devices that are compromised.

• (iOS) Keyboard information is cached in order to improve the autocorrect algorithm. It


does not cache keyboard information for secure textfields, however, if not implemented
correctly, secure information may still be stored such as pin numbers and credit card
information. The keyboard cache’s contents are not available to an application. Consider
using an in-house developed keyboard for sensitive information or set the
autocorrectionType property to UITextAutocorrectionNo.

13
• (Android) Saved words are cached in a user dictionary accessible to any application
without any specific permissions. Developers should consider using an in-house
developed keyboard for sensitive information to ensure the security of the data.

Avoid inappropriate logging

iOS logging information is available to anyone with physical access to the device.

Developers should use the following preprocessor macro in order to maximise log
information during development and disable all Log information during release.

#if TARGET_IPHONE_SIMULATOR

#define NSLog(fmt,...) NSLog((@"%s [Line %d] " fmt), __PRETTY_FUNCTION__, __LINE__, ##__VA_ARGS__);
#else
#define NSLog(...)
#endif

Android log files are available to any application with the readlogs permission. It is
recommended to use a Log extension class in order to control when logging is available.

[Link]

Make sure an application isn’t logging sensitive information, such as session information
or user data.

Crash log data may reveal information that an attacker can use. It is better to handle an
error safely using exceptions and report that an error occurred to a server rather than force
the application to crash.

Consider utilizing sensitive data in an ephemeral mode

If possible, only store contents in RAM or delete data when an application closes. This
minimises the risk of data being stolen from a compromised device.

14
(Android) Implement content providers securely

A content provider allows a structured storage mechanism that can be limited to a single
application or exported to allow access to other applications.

If a developer does not intend access to their content provider from other applications, the
developer must mark the content provider with android:exported=false in the
[Link]. If the content provider does not have android:exported explicitly
declared, the default value is true; this will allow other applications access to the content
provider. The default value of android:exported was changed to false in 4.2 (Jellybean).

Additional tips

• Developers must be aware of the security limitations for jailbroken/rooted devices and
assume the security of a device is compromised and the attacker has access to the
stored data of the device. What data is compromised? Does the stored data only
compromise one device or all devices running this application?

• Developers must be aware of security vulnerabilities for previous mobile OS versions.


Previous versions of iOS and Android may not have the same security features as the
current OS versions.

Developer resources

iOS Software Overview:

[Link]
Security_Overview/Introduction/[Link]

CommonCrypto Man Page:

[Link]
ManPages_iPhoneOS/man3/Common%[Link]#//apple_ref/doc/man/3cc/
CommonCrypto

15
Keychain Services Reference: (Android) KeyStore
[Link] [Link]
documentation/security/Reference/ java/security/[Link]
keychainservices/Reference/[Link]
(Android) Using Cryptography to store
Apple security resources credentials safely
[Link] [Link]
documentation/security/conceptual/ [Link]/2013/02/
Security_Overview/SeeAlso/[Link] using-cryptography-to-store-
[Link]
CCCryptor (AES encryption) wrappers for
iOS and Mac Conceal (Android Encryption Framework
[Link] written by Facebook)
[Link]
(iOS) iMAS Secure Foundation:
[Link] Additional reading
securefoundation
Salted Password Hashing - Doing it right
(iOS) Encrypted Core Data [Link]
[Link] [Link]
encrypted-core-data
Android Developers | Security Tips
(iOS) Encrypting images [Link]
[Link] articles/[Link]
ios-dev-encrypted-images-and-saving-
them-in-app-sandbox/ An empirical study of cryptographic
misuse in android applications
(iOS) Overcoming iOS Data protection to [Link]
re-enable iPhone forensics. doc/ccs13_cryptolint.pdf
[Link]
Critical crypto flaw on Android
Belenko/
[Link]
BH_US_11_Belenko_iOS_Forensics_WP.p
critical-crypto-flaw-android/
df

16
RFC
HMAC: [Link]

17
2.2 Protect remote data transportation

It is the role of an application developer to make sure that data is secure while the user is
interacting with either a server, a device on the same network or a device linked by a
means other than WiFi, such as Bluetooth and NFC.

The objectives of this policy are:

• Ensure that all sensitive data sent remotely is encrypted with proper SSL techniques

• Minimise data collected by network surveillance and spoofing attacks

• Validate traffic from inputs from network communication and device inputs such as NFC,
camera and Bluetooth.

18
Assume the network is not secure

Unlike applications designed for a controlled physical network, mobile applications can be
used anywhere on a wireless network that is controlled by anyone. Developers must never
assume the network an application is using is secure.

Many Wi-Fi networks are not secured with a password and therefore traffic sent on the
network is not encrypted. Many public Wi-Fi access points are available to join without a
password, but require authentication through a portal page. The traffic on these networks
is sent and received unencrypted since there is no 802.11 encryption. The ability to
intercept this traffic, and traffic sent via a WEP encryption is trivial to an attacker.

An attacker can perform packet sniffing and man-in-the-middle attacks even if the site is
secured with HTTPS if a specific mobile application does not correctly verify SSL
certificates. This will be discussed later in the chapter.

Since mobile devices may join these public networks and the user may not be aware of
the security risks of joining a public network, an application cannot be certain of the
security of the network.

Inform the user their traffic is secure

Unlike a web browser which is programmed to indicate a secure end to end connection,
with appropriate error notifications to the user if the connection is not secure; a mobile
application is responsible for handling all security checks and notification to the user if
suspicious activity is being performed on the network. The user does not know whether
they are secure or not and are forced to make an assumption.

If an application is communicating on a secure channel, the user should be informed in


order to understand that they are using the web in a secure manner.

Implement an end to end secure channel for sensitive data

• Sensitive data should connect to a server on a secure channel.

19
Secure Sockets Layer or SSL is a secure bidirectional tunnel for data between a client and
a server.

Transport Layer Security or TLS is a replacement of SSL after v3. Netscape developed
SSL and handed stewardship to IETF who upgraded it and renamed it to TLS 1.0. TLS 1.2
i s t h e l a t e s t v e r s i o n a s o f t h i s d o c u m e n t ’s p r o d u c t i o n .
See [Link] for more information.

HTTPS is HTTP over SSL/TLS, where a secure channel is established, and then HTTP
traffic occurs between client and server via the secure channel.

Verify the certificate with the certificate authority

When an application receives a reply and a certificate from a server, it is the responsibility
of the application developer to verify the certificate with a certificate authority. By default,
an application will accept all SSL certificates.

• Do not trust SSL certificates without first validating them from a Certificate Authority (CA)
or through certificate pinning (see below).

• For convenience, it is quite common to use a self-signed certificate during development


of a mobile application. Ensure that when an application is in release mode, certificate
validation is enabled.

Apple has source code available for server trust evaluation here:
[Link]
Introduction/[Link]

Google has source code and an article regarding SSL security here:
[Link]

20
Implement SSL Certificate Pinning

Pinning is the process of associating a host with their expected X509 certificate or public
key. Once a certificate or public key is known to the application, this is compared to the
certificate or public key from the host.

Multiple certificates can be pinned, also known as a ‘pinset’.

Certificate pinning should be used when a mobile application needs to communicate with
a well-defined set of servers over SSL.

• Developers can whitelist the expected X509 CA/anchor certificate, the server/leaf
certificate or any intermediate certificate for the specified domain.

• Developers can alternatively pin the subjectPublicKeyInfo or the RSAPublicKey/


DSAPublicKey.

• OWASP and iSecPartners have code examples of certificate pinning for various
platforms:

• (iOS) [Link]

• (iOS) [Link]

• (Android) [Link]

• (.NET) [Link]

Validate traffic received via NFC

• Applications must assume that data transferred by NFC is with a host that may be
compromised.

• Applications must validate input received from an NFC enabled transmission in order to
ensure that the source is trusted.

21
Bluetooth security

• Bluetooth is a peer to peer network technology with no centralized security


infrastructure.

• Bluesnarfing is the term used for stealing information through a bluetooth connection.

• According to Ellisys, pin-code based pairing is not secure since a 6-digit pin code can be
deduced in a few hundred milliseconds ([Link]
een_bt06.pdf). Pairing should be conducted with Simple Secure Pairing (SSP).

Don’t use localhost for handling sensitive IPC

• Utilising localhost for handling IPC is extremely insecure as these interfaces are available
to every application on a device. Developers can avoid this by using an Android IPC
mechanism where authentication is possible such as a service.

(Android) SMS may be insecure method of two factor authentication (2FA)

SMS is commonly used to receive a one-time authentication password sent by an


application server in order to confirm the identity of an account. A malicious application
may be able to intercept messages sent to an SMS phone by posing as an SMS app.
More on 2FA in 2.3.

Developer resources:

Analyzing the security of internet banking authentication mechanisms


[Link]
[Link]

Additional reading on bluetooth security


[Link]
[Link]

22
2.3 Implement appropriate authentication

Network traffic cannot be physically controlled when implementing a mobile system. A


developer must presume that every network a device may connect to is insecure and may
potentially be accessible by anyone. A user may also attempt to circumvent a strong
security policy with poor practices, this chapter refers to strong authentication practices
that helps balance security and convenience.

The objectives of this policy are:

• Ensure developers consider methods of authentication appropriate to the challenges of


mobile applications

• Making security and convenience go hand in hand.

23
Balance of security and convenience

From a user perspective, security can be seen as an inconvenience to access a service


that a user wants access to. If a security system is too complex for a user, the user may
choose to not use an application, or worse, a user may bypass or compromise a security
process in order to get access to the service. Examples of poor behaviour include:

• a user will use the same password for multiple services,

• a user will only use one gesture-based password,

• a password will be stored in unsecured storage, such as a notes app, post-it note or a
piece of paper.

This has the side-effect of potentially nullifying the security system implemented by an
organisation.

A security system must balance convenience and security to avoid users from performing
poor security practices. Many users do not like entering an extra secure password every
time they need to use an application.

Consider alternate or enhanced methods of security other than the username / password
combination such as additional protection layers, 2 factor authentication or other
alternatives mentioned in this document.

Password policy suggestions

• If an application is utilising only a username/password combination as a security layer,


passwords should be a strong password, ideally with a capital letter, a number and a
punctuation mark.

• Passwords should not be stored on the device (See tokens later on in this topic) and
should be validated on a server through HTTPS (See 2.2). If an application needs to store
passwords, the password must be stored in an encrypted container and it is

24
recommended to encrypt the data further using appropriate encryption methods
protecting the secure data if it is stored on a compromised OS. (See 2.1)

• The user should be able to change their password from within the application. It is
essential that the user enters their previous password or a secret question/answer in
order to change their password as it cannot be guaranteed that the person using the app
is the owner.

• In case a device is compromised, the user should be notified via email or SMS that their
password has been changed.

• The more complex the password rules are, the more likely the user will try to circumvent
the security with insecure practices, such as substituting letters with numbers and
punctuation (turning password into Pa$$w0rd). A simple algorithm can be used to
circumvent these types of passwords with replacement characters during a brute force
attack. To prevent a user from creating simple passwords, some servers ban easy to
crack passwords; this usually causes the user to stop using the application or continue
to attempt many unsafe practices and combinations, such as adding additional numbers
(1Pa$$w0rd1234), until the user has circumvented the algorithm used to verify the
password.

• Developers should consider utilising a random number as the username instead of an


email address to avoid a user being attacked using credentials that are shared with
another service that has been compromised.

• Passwords should not be saved in clear text on the server. The server should generate a
long random salt using a CSPRNG (Cryptographically Secure Pseudo-Random Number
Generator). Prepend the password with the salt and hash the result with a standard
cryptographic hash function such as SHA256 or SHA512. Save both the salt and the
hash to the database with the user.

• When validating the password, retrieve the salt and hash from the database. Prepend the
password to the salt and hash with the same cryptographic hash function. If the results
match, then the user is authorised. Otherwise, the password does not match.

25
• Always hash on the server rather than on the client. If an application is on a web page,
there is no guarantee the user has JavaScript enabled or that the client network is safe. If
an application is a native application, a reverse engineering attempt, or packet sniffer will
likely detect the use of a hash and an attacker will only require the hash without having to
know the password of the user to log in.

• If the user has forgotten their password, an email should be sent prompting the user to
input further identifying information and allow the user to change their password.
Previous passwords should not be sent to the user since a web server should not have
access to the password. If the web server has access to a database of passwords, so
does a successful attacker.

Storing passwords

For more information on storing passwords, visit 2.1 (Secure local data storage).

• Developers should not hardcode passwords or secret keys within an application. These
can be gathered from the binary of an application and distributed online.

Password alternatives

• Single Sign On (SSO) is a popular technique used for a user to log in to a service using a
trusted service as an authentication technique. oAuth 2.0 and SAML are good examples
of SSO with oAuth 2.0 described in more detail later in the document.

• Utilising an oAuth service to log in such as Facebook, Google, Yahoo and OpenID allows
a user to authenticate using their oAuth service username and password. Utilizing oAuth
2.0 presents a security tradeoff that may or may not be appropriate for an application.
Authentication through a social network is not recommended for government
applications. If the application is a secure service such as a bank, then using an external
oAuth service is not appropriate for security because a bank’s security measures will
likely equal or better than a third-party website such as Facebook. However, if the
application is for a service that needs the ability to log in, but is not as sensitive such as
a photo sharing service, allowing the user to take advantage of a service’s security
infrastructure through oAuth 2.0 may be preferred.

26
• Developers should give the user a more convenient method of authentication once they
h a v e c o n fi r m e d t h e i r i d e n t i t y .
E.g. A bank may require a long password for the first log in of an application, and then
ask the user to set a 4-digit pin code to access the application for subsequent logins.
This design, coupled with other security layers, allows the login details, device and/or
application to be validated with the server. This delegates the security of the login with
the web service, adds a layer of convenience for the user and adds an additional layer of
security by not requiring the password to be stored on the device or continuously passed
between device and server.

• Some devices, such as the iPhone 5S and the Samsung Galaxy S5, ship with biometric
scanners which platforms use for authentication. These platforms may provide APIs to
allow applications to also have access to the biometric method. These scanners are
fooled by repeatable techniques and are recommended for convenience, and not as a
fool-proof layer of security.

Token terminology

• Authorisation code represents the intermediate result of a successful end-user


authorisation process. This code is a short-lived token created by an authorisation server
and passed to a client application. The client application sends the authorisation code to
the authorisation server to obtain an access token and optionally, a refresh token.
[Link]

• An Access token is a short lived token (minutes or hours) used by the client to make
authenticated connections to the resource server. Connections sent with an expired
access token will fail and a new access token will need to be obtained.

• A Refresh token may have an lifetime or set time expiry and explicitly revoked by the
server or the user. The client application stores the refresh token using it to obtain access
tokens. Not all oAuth 2.0 systems utilise refresh tokens, however this is considered good
practice for mobile application as statically declared keys are presumed insecure.

27
Consider utilising token-based authentication

• Instead of storing passwords on the device which may be gathered if a device is


compromised, a long term refresh token can be securely stored on the device (similar to
oAuth).

• The password can be initially sent using SSL/TLS. An access token is issued by the
backend service with a specific time expiry and is stored securely on the device. This
ensures that the password is not stored locally.

• This access token is required for all traffic between the device and server.

1. Send authentication (username/password) to verify user

Authorisation server

2. Send access token

Client

Resource server

3. Use access token

28
• The access token is a short-lived token, however a client may have a refresh token which
may never expire, or expiry manually which can be used to request an access token. This
token should be stored in a secure container as this token can be used to generate
access tokens.

• If the refresh token has expired or the access token has expired without a refresh token,
the user will need to authenticate again.

• For more information on the oAuth 2.0 standard, visit [Link]

Multi-factor authentication

Multi-factor authentication (2FA or TFA) is an extra layer of authentication in order to


confirm the identify of the user. Two factor authentication is commonly used to confirm
that a user actually owns a specific email address by sending an email, or a specific
device by sending an SMS. 2FA is typically used in conjunction with a password.

It is possible for an email address to be compromised and for a phone to be


compromised, rendering more traditional methods of 2FA to become less effective.

• RSA tokens can be used as a more secure two-factor authentication method than email
and SMS message. It can not be assumed that a user will know what an RSA token is
without training and education.

• Resetting a lost password should include something only the user would know, and that
knowledge known by the server must be treated with the same level of protection as a
password. An attacker may have access to a user’s phone, which means that an attacker
will have access to the user’s bank app, the user’s SMS application and the user’s email
address potentially rendering two-factor authentication useless.

• When a password is reset, a user should be notified through available service information
such as email or SMS that a change has occurred on their account along with contact
information allowing a user to contact support if the password reset was not conducted
by them.

29
• Passwords should never be recoverable. If a password is recoverable through a forgot
password mechanism, then an attacker can immediately identify that passwords are
insecurely stored.

Unpredictable session identifiers

Session identifiers should be sufficiently random with high entropy, otherwise it can be
possible to guess a secure key based on predictably random algorithms.

• OWASP recommends a random number seeded with a combination of the date and
time, the phone temperature sensor and the current x,y and z magnetic fields. In using
and combining these values, well-tested algorithms which maximise entropy should be
chosen, such as SHA1.

Visual and gesture-based passwords

• Gesture based passwords are vulnerable to “smudge attacks”, allowing an attacker to


guess a password with greater ease.

• If a user already utilised a gesture password for a device, the user is more likely to use
the same gesture password for an application. Developers should consider this before
deciding to use gesture based authentication for an app.

• Other visual based passwords can be used if the password has a high entropy. OWASP
recommends developers read [Link]
[Link] for more information on visual passwords.

Make sure application can handle excessive failed attempts

• It’s possible to attempt at least 350,000 passwords / second on a user account on


randomised IP addresses. Developers should use this scenario as a generic benchmark
when designing the security for their web services against brute force attacks.

• The server should be able to suspend access to a device that consistently inputs an
incorrect password too many times in sufficient succession. This can be done in a way

30
that the actual user does not notice, or the application’s server may want to notify the
user when their account is potentially under attack.

• If feasible, establish trust with any new device and inform the user of logins from any new
devices.

• This will help protect the user and the web server against brute force attacks.

oAuth Resources

[Link]

[Link]

Secure Salted Password Hashing - How to do it properly


[Link]

31
2.4 Audit third-party code and services

Many developers are encouraged to utilise commercial and open source third party tools
to help with the development of mobile applications. Github, Stack Overflow and git
submodule are all common terms when developing a mobile application. Many developers
publishing on GitHub, StackOverflow and other services create projects that make a
developer’s job easier and do not consider security during development of their open
source tool.

The objectives of this policy are:

• Track security issues from third party services

• Audit the source code of open source third party services

• Audit the activity of proprietary third party services

32
Github and Stack Overflow and other third-party code sources

There are a significant amount of open source software repositories dedicated to iOS and
Android modules and even entire applications which allow a developer to easily integrate
code into their own source tree to utilize a set of third-party features. Developers regularly
host these code repositories on Github. A repository stored on Github is referred to as a
git repository.

Stack Overflow is an extremely popular developer forum for questions and answers with a
vibrant mobile developer community.

Security is not the main concern for developers that are submitting answers on forums or
source code highlighting a new or fixed feature. Developers will regularly submit the
quickest method for creating a solution rather than the most secure way.

• Source code obtained from Github or Stack Overflow must be treated as though it was
created for convenience and must be audited for vulnerabilities manually, and through a
static code analyser.

Use popular repositories

• When considering using open source code, a developer needs to analyse the frequency
of message traffic, release, patches, stars and watches. Developers should avoid
projects that do not have an active developer support community since all additional
features and security patches will likely need to be implemented internally.

• Ensure the licensing of the source code is considered and checked as not all open-
source projects have the same software license and may require a developer to
additionally acknowledge and reference the usage of the source, or the license may
dictate that a developer must open source any additional changes. Each repository is
responsible for it’s own license terms.

33
Audit closed-source proprietary tools

• Developers must check what additional entitlements/permissions are required for


proprietary third party code and investigate what purposes these will be used for.

• Developers must run network checks on closed-source proprietary tools to discover


what information is being sent back to a server.

Track status of third-party tools

Third party tools may regularly updates to their source code and tools with additional
features and security enhancements.

• If a project uses third-party code from GitHub or another centralised git repository
system, those repositories should be watched using submodules, or a system’s “watch
repository” feature.

• Subscribe to messages from the vendor regarding updates of their tools and implement
any security enhancements issued by those vendors.

• Follow and read issues stored on GitHub or repository equivalent. If a library has a
security vulnerability that requires patching, the issue may be published publicly.

Source code analysers

• Commercial source code analysers such as Checkmarx, HP Fortify Static Analyzer and
Veracode are an excellent method of testing mobile application source code for security
errors.

• Open source analysers are also programmed to pick up some security bugs, but are not
widely used on smaller open source projects.

• If an application is developed using a language that is easy to reverse engineer (such as


Java or c#), a developer must assume that attackers have access to a binary source
code and that they are using commercial and open source tools as one of the first ways
of checking for vulnerabilities within an application.

34
• For more information on the positives and negatives of automatic source code analysers,
visit [Link]

Report vulnerabilities in open source projects

• If a developer discovers a security vulnerability in an open source project, they should


report the flaw as a bug privately to the developers before posting it publicly so that it can
be fixed without alerting attackers to the flaw. Work with the developers of the repository
to patch the flaw.

Resources

(iOS) The problem with using third party libraries for securing your apps
[Link]
with-using-third-party-libraries-for-securing-your-apps/

35
2.5 Respect user data

The amount of personal and work data that lives on a person’s mobile device is greater
than it ever has been in history; a mobile phone knows the life of a person more than the
spouse of a person. Applications use this data in order to add extra convenience to the
user, however this data can be misused if not respected and the user will become
suspicious of an offending application.

The objectives of this policy are:

• Ensure that mobile applications are utilising the data for the benefit of the user

• Correct reporting is given to the user

• User data is not leaked via side channels or third party services

36
Avoid using phone identifiers

Phone identifiers allow developers and advertisers to track


phones across multiple applications and vendors and track a
pattern of behaviour for their own gains. Apple has removed
access to unique device identifiers for developers and other
platforms are also tightening privacy controls in favor of the
user.

iOS does not allow


• Developers should generate a unique identifier specifically
developers access to
for an application rather than using the phone’s identity.
any identifier that
Some mobile platforms may provide a programming
may link a user to interface to do this.
the phone. This
includes the UDID • Using a unique application identifier avoids using the IMEI/
and the MAC MEID/MAC address permission.
address.
• (iOS) Developers can use the keychain to share secrets
between applications of the same vendor, this can allow a
As of iOS 8, MAC developer to securely store a unique identifier for a set of
addresses on iOS applications.
devices are
randomised to Submit and comply with a privacy policy
prevent external
Committing to a privacy policy allows an interested user to
hardware from
understand what data is being collected, why it is being
tracking a user (in
collected and what an organisation will do with the data once
certain
it is collected.
circumstances).
• Provide users with a privacy policy accessible within the
application and on an organisation’s website.

• The privacy policy should be clear how an application is


gathering information, if and how the information is stored

37
remotely, how the data will be used and who the data is
shared with.

Audit third party services

Many third party cloud services, including analytics and crash


report engines, make use of additional permissions in order to
gather data from the user.

All platforms are • Developers should audit these third-party services to ensure
tightening privacy user data is not being syphoned unnecessarily.
controls for the
users • Third party services may also use incorrect protocols (http
instead of https) for transferring sensitive data across a
network.

• Analytic services are able to develop a digital fingerprint of a


user based on data collected from the device without
needing a UDID. Developers should attempt to send as little
data to an analytics platform as possible.

• Ensure third party services and libraries comply to the


application’s privacy policy and notify the user of the
service’s disclosures regarding user data.

• Minimise the access to data and resources granted to apps.


For Android applications, developers must audit the
[Link] closely, particularly when using an third
party app creators.

Inform the user when their data is being used

• Inform a user why an application requires specific


permissions and access to data.

38
• Define what data is being collected and used in a privacy policy

• (iOS) In iOS 8, it is mandatory to inform the user why an application is using location data

Resources:

(iOS) Best practices for maintaining user privacy


[Link]
iphoneosprogrammingguide/AppDesignBasics/[Link]

39
2.6 Protect from reverse engineering

Many developers are unaware of how simple it is to reverse engineer an application and
assume that once an application is built and compiled, then it is all 1s and 0s and
impossible to interpret for anything other than a computer. However, any program that can
be interpreted by a computer that was written by a human, can be turned into something
readable by a human.

The objectives of this policy are:

• Implement techniques to detect and deter applications run on a jailbroken/rooted device

• Implement anti-analysis techniques to deter potential intruders

• Implement reflection to deter intruders

40
(iOS) Implement jailbreak detection and anti-analysis
techniques

Project-imas has an excellent tool for jailbreak detection and


anti-analysis
[Link]

It is very difficult to stop an attacker from cracking an


application, the best a developer can do is make it as hard as
It is very difficult to
possible.
stop an attacker from
cracking an (iOS) Understand static inline functions
application, the best
a developer can do is Static inline functions are a feature of the C programming
make it as hard as language that can slow down an attacker’s ability to patch an
possible for a application.
potential attacker
Functions declared as static inline functions are expanded at
compile time in every instance where the code is called. To
simplify, this function is no longer a function from the
application binary’s point of view: the code gets pasted into
the machine code whenever it is called.

Above description is from Mathieu Renard:


h t t p : / / re v e r s e . p u t . a s / w p - c o n t e n t / u p l o a d s / 2 0 1 1 / 0 6 /
GreHack-2012-paper-Mathieu_Renard_-
_Practical_iOS_Apps_hacking.pdf

Every time an application calls a function, the compiler


creates the function each time. Rather than an attacker having
to crack one function which works everywhere in the program
where it is called, the attacker will be forced to crack every
instance of the function created at compile time.

41
See project-imas for more information:
[Link]

(iOS) Use C based functions for sensitive algorithms

At runtime, objective-C and swift uses objc_msgSend() for all


method calls, which uses a string to describe the function
being called. This makes it easier for an attacker to
understand the flow of an application and is considered less
All Android
secure than calling a C function. Sensitive functions should be
applications should
implemented using C functions that are declared as static
ship with obfuscated
inline.
code. It makes it
harder for an (iOS) Disable debugging
attacker to read the
code and may make Disable debugging in the application with a preprocessor
an application macro and a function in the main function. This should be in

execute faster the release version of the application.

Note: This is included as part of the protection in the


previously mentioned security check project by project-imas.

#define PT_DENY_DEBUGGING 31
ptrace(PT_DENY_DEBUGGING,0,0,0);

(Android) Check for rooted device

It can be difficult to detect if an Android device is running on a


rooted device as a user can setup a sandbox environment
around an application to make it seem like it is in a non-rooted
environment.

RootTools has a good set of tests for checking for a rooted


android device.

[Link]

42
(Android) Use obfuscation to slow down an attacker

Obfuscation is the process of changing many of the functions and variables from readable
code to code that is more difficult to read.

ProGuard is a free obfuscation tool that all Android applications should use as minimum
obfuscation protection.

DexGuard is a commercial obfuscation tool with additional features such as string


encryption that will deter an attacker.

Obscurity is a thin security layer and attackers will still be able to understand what the
code is doing based on the code that cannot be obfuscated.

(Android) Consider using reflection for sensitive applications

Reflection gives developers the flexibility to inspect and determine API characteristics at
runtime, instead of compile time.

Combine reflection with obfuscation with tools like ProGuard or DexGuard and it will make
it more difficult for an attacker to reverse engineer an application.

Assume an attacker will decompile the app

When developing an application, a developer must assume the worst case scenario; an
attacker has access to the source code and functions of an application. Although a
developer can make it more difficult for an attacker, assume the attacker can
• read anything embedded in an application
• reverse the backend API
• has a working example of code calling the backend API and storing the data locally.

Developers should use these assumptions when programming an application.

43
References:

(Android) Reflection API:


[Link]
[Link]
mobile-3203

44
2.7 Secure services and servers

A secure application protects a single user / many single users of an application. However,
when a server becomes compromised then all people are at risk. This section will outline
server security suggestions, specifically targeting services (API) and servers (box).

The objectives of this policy are:

• Secure the common LAMP stack.

• Correct configuration of SSL certificates.

• Inform the reader of common web vulnerabilities which may affect a native or hybrid
mobile application.

45
Difference between services and servers

Services are the software programs running an application (APIs and webpages) and
servers is the infrastructure and device settings that services run on.

This guideline currently focus on LAMP (Linux, Apache, MySQL, PHP) instances. Details
for more configurations and languages may be added in the future.

Securely configure Apache

• Strong password for admin / root. This is essential because as soon as a hacker has
access to root, the site is compromised.

• Apache needs to be run as a non-root user such as apache or www. All files and
directories should be owned by non-root user (such as Apache)

• Directories that will be written to must be owned by the same user the web server is
being run as.

When setting permissions for unix files and directories the following basic combinations
are used.

• Read = 4
• Write = 2
• Execute = 1
The combination of these number provide a unique number which identifies how the file
behaves. These are grouped by Owner, Group and Everyone or World

As an example 755 = rwxr-xr-x

The following configurations comply with the above formate. This is by no means an
exhaustive description of unix operating system permissions. The unix man pages or a
unix guide should be consulted for further information.

46
• Script directories must have execute privilege in order to be usable and therefore should
allow the owner read-write-execute privileges, and read-execute privileges for all other
users (755 or rwxr-xr-x).

• Scripts within those directories are run, are not executed and therefore should be set to
read only for all users 444 (r--r--r--) or read-write for owner only 644(rw-r--r--). These
scripts do not require execute privilege.

• Documents that can be accessed by users should be set to read-write for owner access,
read-only for group access and no access to everyone else 640 (rw-r-----).

• Documents not to be accessed by users should be set to read-write for owner only and
no access for everyone 600 (rw-------).

• Developers should consider using FastCGI or suPHP as the PHP handler as both use a
user other than apache to run a PHP script. These handlers will use more resources than
other less-secure PHP handlers such as mod_php (DSO) and CGI and may not be
appropriate for every type of web server.

• Follow the documentation given by the above PHP handlers as they may recommend a
different permission model for the filesystem.

• Extra documentation for setting up a strong apache setup can be found here:
[Link]
[Link]
[Link]

Securely configure [Link]

Many system administrators and developers leave [Link] in its default configuration since
they are unaware of the various options available within [Link]. Below are two PHP
hardening guide focusing on configuration.

Hardening PHP from [Link]


[Link]

47
Use PHPSecInfo to discover potentially vulnerabilities in a php configuration
[Link]

Configure SSL certificates

SSL makes use of what is known as asymmetric cryptography, commonly referred to as


public key cryptography (PKI). With public key cryptography, two keys are created, one
public, one private. Anything encrypted with either key can only be decrypted with its
corresponding key. Thus if a message or data stream were encrypted with the server's
private key, it can be decrypted only using its corresponding public key, ensuring that the
data only could have come from the server.

There are two types of certificates that can be created, A self-signed certificate and a
regular SSL certificate.

Self-signed certificates are SSL certificates that are usually created for testing or internal
purposes where the audience for the service, usually employees or users that know about
the service. Regular SSL certificates, like those used when users connect to a secure web
site such as banking, or where a user is required secure access to information, are verified
by known Certificate Authorities (CA) such as verisign, or other authorities when the
verified SSL certificate was purchased. The main difference for the end user is that with a
verified certificate, the connection to the specified server is done automatically as the CA
is embedded in the browser, so the certificate is automatically verified. With a self signed
certificate, as there is no reference CA, the user is asked if they would like to connect or
verify the certificate manually.

Regardless whether a developer wants to create a self signed certificate or purchase a


verified certificate, there are a number of steps that are common.

Step 1 - Create a private key.

openssl genrsa -des3 -out [Link] 2048

in this case our file is called [Link]. Ideally the name of the file should be

48
[server name].key

Step 2 - Create a CSR (Certificate Signing Request)

In this step a developer will use the private key that was created in the last step. In this
case it is [Link].

openssl req -new -key [Link] -out [Link]

A developer will need to enter some information about an organisation so that it can be
verified by the CA, if purchasing a verified SSL certificate is chosen. The first thing a
developer will be asked is to enter the passphrase to be created in the private key files.
The following is an example of the steps.

Enter pass phrase for [Link]:


You are about to be asked to enter information that will be incorporated
into your certificate request.
What you are about to enter is what is called a Distinguished Name or a DN.
There are quite a few fields but you can leave some blank
For some fields there will be a default value,
If you enter '.', the field will be left blank.
-----
Country Name (2 letter code) [AE]:AE
State or Province Name (full name) [Some-State]:Dubai
Locality Name (eg, city) []:Mamzar
Organization Name (eg, company) []:CoDI
Organizational Unit Name (eg, section) []:mLab
Common Name (e.g. server FQDN or YOUR name) []:CoDI
Email Address []:example@[Link]

Please enter the following 'extra' attributes


to be sent with your certificate request
A challenge password []: NOTE: Leave this blank
An optional company name []:

49
At this point 2 files will have been generated:
[Link]
[Link]

Step 3 - remove the passphase from the key


One of the issues of having the passphase is that each time a developer start a web server
or service using the certificate, the server administrator will need to enter the passphrase
each time. We need to remove this.

cp [Link] [Link]
openssl rsa -in [Link] -out [Link]

Step 4 - Generate a self signed certificate

To generate the self-signed certificate ([Link]) a developer must run the following
command.

openssl x509 -req -days 365 -in [Link] -signkey [Link] -out
[Link]

Depending on the service, the certificates may need to be copied to locations such as
below:

cp [Link] /usr/local/apache/conf/[Link]
cp [Link] /usr/local/apache/conf/[Link]

When a user connects to the service over https, they will be asked to verify or continue
with the certificate. The user will then have an encrypted SSL data connection between
their client and the server.

Steps to creating a verified certificate

If an organisation wants to have a verified certificate, they will need to select a vendor that
acts as a Certificate Authority.

50
Usually the steps are to copy the contents of a CSR file including the BEGIN and END
tags into the vendors website. This will prompt the vendor to provide appropriate files that
can be placed in the web server or SSL service being provided.

When clients connect to the service, there will be no request to verify the SSL certificate
since the certificate has been issued by a certificate authority.

To check a SSL configuration use:


[Link]

Validate data going in, validate data going out

Many service vulnerabilities can be prevented by assuming that all data going in is trying
to attack the server, and all data going out is going to attack the client.

• Always validate input for suspicious characters and use escaped strings when executing
code containing input from an unknown source.

• Never run unvalidated code using eval()

For more information on validation:


[Link]
[Link]

Most common site vulnerabilities

Cross site scripting (XSS)

Cross site scripting occurs when a web application issues a malicious script to a user’s
browser executing code not originally intended by the web application. This malicious
script is sent to or stored the server and the malicious data is included in dynamic content
sent to a user’s browser.

The most common form of XSS is a non-persistent vulnerability which requires the user to
click on a URL with malicious query parameters or from data which is then executed on
the client machine if the server does not sanitise the input correctly.

51
The more devastating form of XSS is a persistent vulnerability when an attacker has stored
the malicious script on the server and is executed whenever a page delivers that specific
output to a user. When successful, an XSS attack can affect many users at once and the
result of an XSS attack is limitless. XSS attacks are usually used to transmit private data
from the client computer, perform session hijacking or redirect the user to malicious
websites for further attacks.

OWASP has an excellent XSS prevention cheat sheet as well as a XSS Filter evasion cheat
sheet:
[Link]
[Link]

SQL Injections

SQL injection attacks can occur when a developer has not validated an input string
correctly and an attacker can inject their own SQL query into a developer’s SQL query.
This can be used for CRUD queries (Create, Read, Update, Delete) or potentially execute
administrative operations on the database.

• Utilise escaped strings and prepared statements when using SQL libraries.

• Validate all input, and blacklist specific SQL and system commands.

For more information on SQL Injection and for a prevention guide:


[Link]
[Link]

Remote code execution / Code Injection

Similar to SQL injection, code injection comes from unvalidated malicious code that has
been injected and run as server-side code.

register_globals in php allows for super-global variables to be used within php, allowing
php to get data from anywhere in the program easily. However, this led to many vulnerable
sites and register_globals has now been turned off by default since 4.2, deprecated in 5.3

52
and will be removed in 5.4.

For more information on register_globals:


[Link]

The worst form of code injection is command injection where a malicious piece of code is
allowed to execute within a shell environment compromising the entire server.

For more information on code injection:


[Link]

Cross-site request forgery

Cross site request forgery (CSRF) is an attack, usually orchestrated through social
engineering, that tricks the user of an authenticated web application into executing actions
of an attacker’s choosing, such as changing the password or address of a user.

Sometimes a CSRF can be stored can be stored on the vulnerable site itself, usually as an
img or an iFrame, allowing for potentially all visitors to be susceptible to the attack.

Information leakage

Revealing system or debugging information can help an attacker work out a potential
vector for attack based on the information leaked. If a server leaks what type of CMS,
database or system version is being used, the attacker can take advantage of any known
vulnerabilities in that particular version.

[Link]

Resources

OWASP Web Services


[Link]

Browser security handbook


[Link]

53
Secure PHP configuration
[Link]
[Link]

Best PHP web practices


[Link]
[Link]

Web vulnerabilities
[Link]
[Link]

How to create a self-signed SSL certificate


[Link]

54
2.8 Validate input and interprocess
communications

Validating input is the process of verifying that input that is inputted by a user is
considered to be functionally correct, and if not properly implemented, input can be used
to maliciously attack users. This is true for interprocess communications too.

The objectives of this policy are:

• Avoid code injection

• Avoid buffer overflow attacks

• Validate traffic received via new sources such as NFC & Camera (QR)

• Encourage the use of Fuzz testing during development and testing

55
Identify entry points for untrusted data

• A developer should identify all points of an application that can receive input from either
the user or from the system. This may be a textfield, commands from a URL, push
notification, multimedia file, intent (android), content providers (android), Open In... (iOS),
AirDrop (iOS), along with many other potential sources.

• Entry points can also be hardware based, such as a QR code via the camera, Bluetooth,
NFC, iBeacon.

• The data from these entry points must be validated to exclude suspicious characters to
protect against buffer overflow attacks, format string attacks or SQL injection. See next
chapter for more details.

• If there is also a server component for the untrusted data, developers must perform client
side and server side validation as an attacker may attempt to exploit the API backend.

URL handling

Applications can be opened with a registered URL scheme. This has the side effect
allowing any application to open the application with varied potential input values.

Applications should not accept commands that include URLs to execute. This may lead to
a malicious page within the application.

If an application accepts parameters in a URL command, the data needs to be validated


against potential buffer overflow attacks through format strings, injection attacks or even
social engineering attacks where a user is tricked into seeing a webpage they believe is
safe inside of an application.

Modifications to serialized data

Object serialization and deserialization is the process of turning storing objects stored in
memory at runtime directly to disk (serialization) and from stored data to memory

56
(deserialization). The data is stored in a special format that makes it easier for a computer
to load back into memory.

Object serialization is problematic from a security perspective as files could be modified


without the user’s knowledge and the files could be read back into memory quite easily.

• Keep a secure local checksum of serialized objects and compare the checksum of the
stored value with the current value. If it is possible to have a storage and comparison of
the file checksum performed remotely, this is considered to be more secure.

Implement fuzz testing as part of a security audit

Fuzz testing randomly alters valid data and passes it to a program to assess the
consequences of sending random data that is still potentially valid. This is used quite
heavily by attackers looking for potential attack vectors such as format string and SQL
injection attacks.

Developers must ensure when inspecting their program to think like an attacker and use
similar tools that an attacker would use to find vulnerabilities in their application.

An attacker will not only attempt to fuzz a mobile application, but any web services an
application uses in order to find vulnerabilities that can be exploited to create cross-site
scripting attacks or making an application hand helping cause a denial of service attack.

OWASP has a list of fuzz testing applications that are available to use. Assume that an
attacker will be using a commercial fuzzer in order to find vulnerabilities in an application
and within the application’s backend.
[Link]

Other fuzzing resources:

Intent Fuzzer for Android:


[Link]

57
Mutation vs Generational fuzzing:
[Link]

58
2.9 Avoid exploitable code

Many developers are unaware of how simple it is to reverse engineer an application and
assume that once an application is built and compiled, then it is all 1s and 0s and only a
computer can process the binary information. This misconception ignores that any
program that can be interpreted by a computer, can be turned into something readable by
a computer.

The objectives of this policy are:

• Prevent potential buffer overflows errors

• Recognise the importance of input validation

• Encourage the use of static analysers

59
(Objective-C) Preventing format string attacks

Developers commonly take shortcuts when utilising format strings in multiple formats
however it is important to protect format strings. Consider the example below:

NSString *myString = [Link];


NSLog(myString);

This is susceptible to a buffer overflow attack as the string can be tricked into accepting a
string acting like a format string. Developers should always protect a format string:

NSString *myString = [Link];


NSLog(@"%@",myString);

Preventing URL handling attacks

URL handling is one way that applications are opened from external applications. If an
application calls a URL with a prefix other than http:, such as mailto: indicates to the
operating system that another application should handle this URL and the parameters
associated with it.

This can lead to errors or malicious behaviour, such as the user pressing a button on a
website which initiates a malicious Skype call which could automatically dial if the Skype
app does not validate input received from the skype:// URL.

Input gathered from a URL handling query string needs to be verified as valid data and
actions should be verified by the user before any additional action is performed. Skype
accepts phone numbers from query strings passed from skype://, but requires the user to
confirm the number before initiating a phone call.

Utilise static code analysis tools

Static code analysis tools are an excellent automated way to check for potentially
exploitable coding errors that may lead to buffer overflow attacks or identify a low entropy
random function. Examples of free static code analysis tool are as Clang for Objective-C,
FindBugs for Java and Fxcop for C#.

60
A list of static code analysers can be found at:
[Link]

UAE government entities have access to advanced code analysis through the Centre of
Digital Innovation.

61
2.10 Distribute an application securely

The role of a developer is to create code to make an application work, once that part is
finished, the developer may consider the job done with no regard to the release process
and security. A button is pressed which pushes the application to the app store or
internally as quickly as possible. This section outlines some of the additional measures
that developers should consider when building a release version of the application.

The objectives of this policy are:

• Ensure correct setting are set when deploying an application

• Best practices for certificate management

62
Application signing

Code signing is a security technique to determine whether the


code has been modified by someone other than the original
signer. Platforms that enforce code signing, such as iOS and
Android, will not run unsigned or applications with corrupted
signatures.

Code signing ensures that a piece of code has not been


altered, identifies code as coming from a specific developer/
signer and helps determine whether code is trustworthy for a
specific purpose (such as access to secure storage).

Code signing uses a cryptographic hash to guarantee that the


software code has not been altered since the application was
initially signed. The developer will generate a key to sign the
application, or obtain one from a trusted certificate authority
iOS and Android depending on the platform.
devices will not
execute applications
that are not signed.

63
iOS documentation states that “Apple’s code signature consists of three parts:

• A seal, which is a collection of checksums or hashes of the various parts of the code,
such as the identifier, the [Link], the main executable, the resource files and so on.
The seal can be used to detect alterations to the code and to the app identifier.

• A digital signature, which signs the seal to guarantee its integrity. The signature includes
information that can be used to determine who signed the code and whether the
signature is valid.

• A unique identifier, which can be used to identify the code or to determine to which
groups or categories the code belongs. this identifier can be derived from the contents of
the [Link] for the app, or can be provided explicitly by the signer.”

Android documentation states that “the Android system requires that all application be
digitally signed with a certificate whose private key is held by the application’s developer.
The Android system uses the certificate as a means of identifying the author of an
application and establishing trust between the developer’s applications.”

Keep private keys secure

Private keys are the keys to applications and need to be kept secret at all times. If a
developer is creating a self-signed application, ensure the keystore is protected with a
lengthy password and kept on a non-networked computer. Developers must not distribute
it as part of their code repository in case the repository is targeted and compromised.

Submit a properly signed APK

Novice developers may not understand how application signing works, however, since
their test application runs on a device, that developer may attempt to submit a debug
version of their application onto the store, or internally within their organisation.

• When creating a release version of an application, it must be signed with a self-signed


release certificate or a certificate signed by a certified authority.

64
• Visit the link below for a step-by-step guide to creating a
suitable private key to create a signed APK:
h t t p : / / d e v e l o p e r. a n d ro i d . c o m / t o o l s / p u b l i s h i n g / a p p -
[Link]#releasemode

Remove log statements

It is not necessary to log the same amount of information for a


release build as it is for a debug build. All unnecessary log
Android developers
information should be removed or disabled for a release build.
must keep their
private key for 25 Utilise obfuscation tools to make an application harder to
years if they want to reverse engineer
update their
application. See 2.6 for more information.

(Android) Only enable permissions needed


A lost key means an
app cannot be Android has an accept all permissions / deny application
updated. security setting for applications. Users get “permission
fatigue” by allowing many permissions that they should not.

A stolen key means • Government applications should only define the permissions
that the system can that are required for that application to function.
be tricked into
upgrading with Developer resources:
additional malware
iOS code signing under the hood:
distributed within the
[Link]
app
the-hood

Code Signing Guide:


[Link]
security/conceptual/CodeSigningGuide/AboutCS/
[Link]

65
[Link]
CodeSigningGuide/AboutCS/[Link]#//apple_ref/doc/uid/TP40005929-CH3-SW3

Android code signing:


[Link]

Android security:
[Link]

66

You might also like