Mobile App Secure Coding Guidelines
Mobile App Secure Coding Guidelines
Mobile application
secure coding
guidelines
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
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
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.
• 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.
Apple iOS:
Android:
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)
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.
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.
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.
• 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
[Link] [Link]
Android
Digest ("SHA-256")
[Link]
C# SHA256Managed
ography
Android [Link]*
[Link]
C#
toServiceProvider
9
• The salt should be a long CSRPNG string generated at
runtime and stored remotely or in the keychain/keystore.
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]
While kSecAttrAccessbleWhen
NSFileProtectionComplete
unlocked Unlocked
NSFileProtectionComplete
While locked N/A
UnlessOpen
kSecAttrAccessibleAfterFirst
After first NSFileProtectionComplete
Unlock
unlock UntilFirstUserAuthentication
kSecAttrAccessibleAlways
Always NSFileProtectionNone
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.
• 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.
• 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.
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.
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.
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?
Developer resources
[Link]
Security_Overview/Introduction/[Link]
[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.
• Ensure that all sensitive data sent remotely is encrypted with proper SSL techniques
• 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.
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.
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.
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).
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.
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.
• OWASP and iSecPartners have code examples of certificate pinning for various
platforms:
• (iOS) [Link]
• (iOS) [Link]
• (Android) [Link]
• (.NET) [Link]
• 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
• 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).
• 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.
Developer resources:
22
2.3 Implement appropriate authentication
23
Balance of security and convenience
• 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.
• 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.
• 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
• 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
• 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.
Authorisation server
Client
Resource server
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.
Multi-factor authentication
• 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.
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.
• 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.
• 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]
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.
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.
• 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
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.
• 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.
34
• For more information on the positives and negatives of automatic source code analysers,
visit [Link]
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.
• Ensure that mobile applications are utilising the data for the benefit of the user
• User data is not leaked via side channels or third party services
36
Avoid using phone identifiers
37
remotely, how the data will be used and who the data is
shared with.
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.
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:
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.
40
(iOS) Implement jailbreak detection and anti-analysis
techniques
41
See project-imas for more information:
[Link]
#define PT_DENY_DEBUGGING 31
ptrace(PT_DENY_DEBUGGING,0,0,0);
[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.
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.
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.
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.
43
References:
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).
• 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.
• 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
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]
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.
47
Use PHPSecInfo to discover potentially vulnerabilities in a php configuration
[Link]
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.
in this case our file is called [Link]. Ideally the name of the file should be
48
[server name].key
In this step a developer will use the private key that was created in the last step. In this
case it is [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.
49
At this point 2 files will have been generated:
[Link]
[Link]
cp [Link] [Link]
openssl rsa -in [Link] -out [Link]
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.
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.
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.
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.
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.
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.
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
53
Secure PHP configuration
[Link]
[Link]
Web vulnerabilities
[Link]
[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.
• Validate traffic received via new sources such as NFC & Camera (QR)
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.
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.
• 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.
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]
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.
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:
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:
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.
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.
62
Application signing
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.”
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.
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.
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
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
65
[Link]
CodeSigningGuide/AboutCS/[Link]#//apple_ref/doc/uid/TP40005929-CH3-SW3
Android security:
[Link]
66