Mejores prácticas - Desarrollo móvil para Android y iOS


Published on

  • Thanks Carlos. We've also posted an updated version of this on our website, which is also now editable by the community through github:
    Are you sure you want to  Yes  No
    Your message goes here
  • Be the first to like this

Mejores prácticas - Desarrollo móvil para Android y iOS

  1. 1. INNOVATIVE DIGITAL SECURITY AND FORENISCS BEST PRACTICES 42+ Secure mobile development for iOS and AndroidAt viaForensics we spend a lot of time attacking mobile apps. Hacking. Breaking encryption,finding flaws, pen testing and looking for sensitive data stored insecurely. We do it for theright reasons – to help companies make their apps more secure.In our R&D and project work, we find many security gaps. While some problems are big,others represent data leakage or provide potential vectors that aid malicious attackers. Inour engagements we always provide concrete recommendations for remediating securityissues. This document represents some of the wisdom we share with our clients andpartners. We are driven to improve the state of mobile security and we hope by setting thisinformation free, we are making a valuable contribution to the community.The descriptions of attacks and security recommendations in this report are not exhaustiveor perfect, and are likely to evolve and get corrected as needed. We reserve the right torelease updated recommendations. If you have questions or feedback please let us know.© Copyright 2012 viaForensics, all rights reserved.No distribution or republication without permission.
  2. 2. 42+ Best Practices: Secure mobile development for iOS and AndroidAbout viaForensicsviaForensics is an innovative digital forensics and security firm providing services tocorporations, law firms and law enforcement/government agencies. Our areas of focusinclude computer and mobile forensics, mobile app security, and proactive enterprisesecurity.About the AuthorsAndrew Hoog is the co-founder of viaForensics and a leading mobile security and forensicsresearcher. He recently published the book Android Forensics and Mobile Security, andalong with Katie Strzempka co-authored iPhone and iOS Forensics.Jonathan Zdziarski is Sr. Research Scientist, and a pioneer in the field of Apple iOS forensicsand security. He has authored numerous books on iPhone development and forensics forO’Reilly Media, most recently Hacking and Securing iOS Applications.Thomas Cannon is Director of Research and Development for viaForensics. He is a notedAndroid security and malware expert with extensive experience in risk mitigation, securityassessment, digital investigation and secure development.Jared Carlson is a Senior Engineer at viaForensics focused on mobile devices, developingtools for file system analysis, reverse engineering and other security topics. His experienceincludes algorithm development for fluid dynamics and defense systems.Ted Eull is VP of Technology Services for viaForensics, managing delivery of mobileapplication security assessments, mobile device security audits and other services. He is anexperienced IT developer, project manager, and security analyst.Sales PitchIf you find our 42+ Best Practices for Secure Mobile Development useful, you might want totake a look at appSecure®, our mobile application security assessment and certificationservice. In addition, we are launching the Santoku Linux project, a free mobile security,malware and forensics platform.viaForensics is partnering with IT certification and education leader CompTIA to createcertifications in secure development for iOS and Android. These certifications are scheduledto be available later in 2012, so stay tuned. © Copyright 2012 viaForensics, all rights reserved. 1 No distribution or republication without permission.
  3. 3. 42+ Best Practices: Secure mobile development for iOS and AndroidMobile Security PrimerMobile security entails many of the challenges of Web security – a wide audience, rapiddevelopment, and continuous network connectivity – combined with the risks common tomore traditional fat client applications such as buffer management, local encryption, andmalware. One of the unique features to the mobile environment is the prevalence ofinstalled applications coming from unknown developers who should be considered“untrusted.”Anatomy of a Mobile AttackAs illustrated below, a mobile attack can involve the device layer, the network layer, the datacenter, or a combination of these. Inherent platform vulnerabilities and social engineeringcontinue to pose major opportunities for cyber thieves and thus significant challenges forthose looking protect user data. [Click the image to view a larger version on our Web site.] © Copyright 2012 viaForensics, all rights reserved. 2 No distribution or republication without permission.
  4. 4. 42+ Best Practices: Secure mobile development for iOS and AndroidAttack VectorsThere are three points in the mobile technology chain where malicious parties may exploitvulnerabilities to launch malicious attacks:  The device  The network  The data centerThe DeviceMobile devices pose significant risks for sensitive corporate information (SCI); key risksinclude data loss and compromised security. Whether iPhone, Android or other smartphone,attackers targeting the device itself can use a variety of entry points:  Browser, mail, or other preloaded applications  Phone/SMS  Third-party applications (apps)  Operating system  RF such as Baseband, Bluetooth and other comm channelsBrowser-based attacksBrowser-based points of attack can include:Phishing - Involves acquiring personal information such as usernames, passwords, and creditcard details by masquerading as a trusted entity through e-mail spoofing. Research hasshown that mobile users are three times more likely than desktop users to submit personalinformation to phishing websites. This is, in part, likely due to the scaled down environmenta mobile browser runs in, which displays only small portions of URLs due to limited screenreal-estate, limited warning dialogs, scaled down secure lock icons, and foregoes many userinterface indicators such as large STOP icons, highlighted address bars, and other visualindicators.Framing - Framing involves delivery of a Web/WAP site in an iFrame, which can enable“wrapper” site to execute clickjacking attacks.Clickjacking - Also known as UI redressing, clickjacking involves tricking users into revealingconfidential information or taking control of their device when a user clicks on a seeminglyinnocuous link or button. This attack takes the form of embedded code or scripts thatexecute without user knowledge. Clickjacking has been exploited on sites including Facebookto steal information or direct users to attack sites. © Copyright 2012 viaForensics, all rights reserved. 3 No distribution or republication without permission.
  5. 5. 42+ Best Practices: Secure mobile development for iOS and AndroidDrive-by Downloading - Android in particular has been vulnerable to this attack, where aWeb site visit causes a download to occur without user knowledge, or by tricking the userwith a deceptive prompt. The download can be a malicious app, and the user then may beprompted automatically by the device to install the app. When Android devices are set toallow apps from “unknown sources” the installation is allowed.Man-in-the-Mobile (MitMo) - Allows malicious users to leverage malware placed on mobiledevices to circumvent password verification systems that send codes via SMS text messagesto users phones for identity confirmation.Phone/SMS-based attacksPhone/SMS points of attack can include:Baseband attacks – Attacks that exploit vulnerabilities found in a phones GSM/3GPPbaseband processor, which is the hardware that sends and receives radio signals to celltowers.SMiShing – Similar to phishing, but uses cell phone text messages in place of e-mail messagesin order to prompt users to visit illegitimate websites and enter sensitive information such asusernames, passwords and credit card numbers.RF Attacks - Bluejacking, NFC attacks and other RF exploits find vulnerabilities on variousperipheral communication channels that are typically used in nearby device-to-devicecommunications.Application-based attacksApp-based points of attack can include:Sensitive Data Storage – A 2011 viaForensics study found 83% of popular apps sampled storedata insecurely.No Encryption/weak encryption – Apps that allow the transmission of unencrypted orweakly encrypted data are vulnerable to attack.Improper SSL validation – Bugs in an app’s secure socket layer (SSL) validation process mayallow data security breaches.Config manipulation – Includes gaining unauthorized access to administration interfaces,configuration stores, and retrieval of clear text configuration data. © Copyright 2012 viaForensics, all rights reserved. 4 No distribution or republication without permission.
  6. 6. 42+ Best Practices: Secure mobile development for iOS and AndroidDynamic runtime injection – Allows an attacker to manipulate and abuse the runtime of anapplication to bypass security locks, bypass logic checks, access privileged parts of anapplication, and even steal data stored in memory.Unintended permissions – Misconfigured apps can sometimes open the door to attackers bygranting unintended permissions.Escalated privileges – Exploits a bug, design flaw or configuration oversight in order to gainaccess to resources normally protected from an application or user.OS-based attacksOperating system-based points of attack can include:No passcode – Many users choose not to set a passcode, or use a weak PIN, passcode orpattern lock.iOS jailbreaking - “Jailbreaking” is a term for removing the security mechanisms put forth bythe manufacturer and carrier that prevent unauthorized code from running on the device.Once these restrictions are removed the device can become a gateway for malware andother attacks.Android rooting – Similar to ‘jailbreaking’, rooting allows Android users to alter or replacesystem applications and settings, run specialized apps that require administrator-levelpermissions. Like jailbreaking, it can result in the exposure of sensitive data.Passwords and data accessible - Devices such as Apples line of iOS devices, have knownvulnerabilities in their cryptographic mechanisms for storing encrypted passwords and data.An attacker with knowledge of these vulnerabilities can decrypt the devices keychain,exposing user passwords, encryption keys, and other private data.Carrier-loaded software – Software pre-installed on devices can contain security flaws.Recently, some pre-loaded apps on Android handsets were found to contain securityvulnerabilities that could be used to wipe the handset, steal data, and even eavesdrop oncalls.Zero-day exploits - Attacks often occur during the window between when a vulnerability isfirst exploited and when software developers are able to issue a release addressing the issue. © Copyright 2012 viaForensics, all rights reserved. 5 No distribution or republication without permission.
  7. 7. 42+ Best Practices: Secure mobile development for iOS and AndroidThe NetworkNetwork-based points of attack can include:Wi-Fi (weak encryption/no encryption) - Applications failing to implement encryption, whenused across a Wi-Fi network run the risk of data being intercepted by a malicious attackereavesdropping on the wireless connection. Many applications utilize SSL/TLS, which providessome level of protection; however some attacks against SSL/TLS have also been proven toexpose critical user data to an attacker.Rogue access points – Involves physically installing an unauthorized wireless access pointthat grants parties access to a secure network.Packet sniffing – Allows a malicious intruder to capture and analyze network traffic, whichtypically includes username and password information transmitted in clear text.Man-in-the-Middle (MITM) – Involves eavesdropping on an existing network connection,intruding into that connection, intercepting messages, and modifying select data.SSLStrip – A form of the man-in-the-middle attack that exploits weakness in the SSL/TLSimplementation on Web sites, which can rely on the user verifying that an HTTPS connectionis present. The attack invisibly downgrades connections to HTTP, without encryption, and isdifficult for users to detect in mobile browsers.Session hijacking – Involves exploitation of a session key to gain unauthorized access to userand network information.DNS poisoning – Exploiting network DNS can be used to direct users of a website to anothersite of the attackers choosing. In some cases attacks can also inject content through apps.Fake SSL certificates – Another man-in-the-middle attack that involves issuing fake SSLcertificates that allow a malicious user to intercept traffic on a supposedly secure HTTPSconnection. © Copyright 2012 viaForensics, all rights reserved. 6 No distribution or republication without permission.
  8. 8. 42+ Best Practices: Secure mobile development for iOS and AndroidThe Data CenterAttackers targeting the data center use two main points of entry:  Web server  DatabaseWeb server-based attacksWeb server-based attacks and vulnerabilities include:Platform vulnerabilities - Vulnerabilities in the operating system, server software, orapplication modules running on the web server can be exploited by an attacker.Vulnerabilities can sometimes be uncovered by monitoring the communication between amobile device and the web server to find weaknesses in the protocol or access controls.Server misconfiguration - A poorly configured web server may allow unauthorized access toresources that normally would be protected.Cross-site scripting (XSS) – Cross-site scripting is an attack that involves injecting maliciousJavaScript code into a website. Pages that are vulnerable to this type of attack return userinput to the browser without properly sanitizing it. This attack is often used to run codeautomatically when a user visits a page, taking control of a users browser. After control ofthe browser has been established, the attacker can leverage that control into a variety ofattacks, such as content injection or malware propagation.Cross-site Request Forgery (CSRF) – Cross-site request forgery involves an attacker creatingHTTP (Web) requests based on knowledge of how a particular web application functions, andtricking a user or browser into submitting these requests. If a Web app is vulnerable, theattack can execute transactions or submissions that appear to come from the user. CSRF isnormally used after an attacker has already gained control of a users session, either throughXSS, social engineering, or other methods.Weak input validation - Many Web services overly trust the input coming from mobileapplications, relying on the application to validate data provided by the end user. However,attackers can forge their own communication to the web server or bypass the applicationslogic checks entirely, allowing them to take advantage of missing validation logic on theserver to perform unauthorized actions.Brute-force attacks – A brute-force attack simply tries to guess the valid inputs to a field,often using a high rate of attempts and dictionaries of possible values. The most common © Copyright 2012 viaForensics, all rights reserved. 7 No distribution or republication without permission.
  9. 9. 42+ Best Practices: Secure mobile development for iOS and Androidusage of a brute-force attack is on authentication, but it can also be used to discover othervalid values in a Web app.Database attacksDatabase attacks and vulnerabilities include:SQL injection - Interfaces that dont properly validate user input can result in SQL beinginjected into an otherwise innocuous application query, causing the database to expose orotherwise manipulate data that should normally be restricted from the user or application.OS command execution - Similar to SQL injection, certain database systems provide a meansof executing OS-level commands. An attacker can inject such commands into a query,causing the database to execute these commands on the server, providing the attacker withadditional privileges, up to and including root level system access.Privilege escalation – This occurs when an attack leverages some exploit to gain greateraccess. On databases this can lead to theft of sensitive data.Data dumping - An attacker causes the database to dump some or all data within a database,exposing sensitive records.Types of Mobile AppsMobile applications typically fall under three operational categories:Web – Apps that operate via a general purpose web browser. Sometimes referred to as WAPor Mobile Sites, these are the mobile equivalent to functional web applications that haveproliferated in the past decade offering many capabilities such as online banking andshopping. Although regular web sites can be used in mobile web browsers, many companiesnow create a separate mobile web app to optimize for mobile attributes, such as smallerscreen size, touch-based navigation and availability of GPS location.Native – Installed apps that operate off the native mobile device operating system, compiledfor the specific mobile platform and leveraging its APIs. These are typically (though notalways) downloaded and installed via an app market.Wrapper – Apps that operate by leveraging web pages inside a dedicated native applicationwrapper, also sometimes referred to as “shell apps” or “hybrid apps.” While appearing as anative app to the end user, the web-based functionality can result in different vulnerabilitiesthan are found in fully native coded apps. © Copyright 2012 viaForensics, all rights reserved. 8 No distribution or republication without permission.
  10. 10. 42+ Best Practices: Secure mobile development for iOS and AndroidUnderstanding NAND Flash MemoryUnlike RAM, NAND flash is non-volatile and thus data is preserved even when the device iswithout power or rebooted. The NAND flash is used to store not only system files, but alsoany user data written to disk.NAND flash memory has characteristics very different from the magnetic media found inmodern hard drives. These properties make NAND flash ideal storage for mobile devices,while at the same time presenting a number of challenges for secure development (andopportunities for forensic analysts).One significant issue is that each block has a limited lifespan of write/erase cycles. NANDflash controllers have generally been designed not to overwrite the same block often, in aprocess called wear leveling, and in many cases avoid erasing blocks unless forced to do so,to avoid wearing out blocks too quickly. Therefore, in many cases data on these devices canretain deleted data longer than it would be on traditional hard disks.Understanding EncryptionMany applications utilize encryption to protect sensitive data, however many flaws in thetechnique allow an attacker to retrieve or deduce the key, or extract the key from theoperating system. With the master key, all sensitive data can be decrypted by an attacker, orthe application can be manipulated to decrypt the data for the attacker, further speeding anattack.Applications utilizing encryption frequently suffer from one or more of the following flaws:Storing the master key - Applications storing a master key on disk expose themselves to anattack if they fail to encrypt it with a user-supplied passphrase. If the key itself is intercepted,it can be used to decrypt all sensitive data without any passphrase supplied by the user,effectively turning a passphrase into a UI lock only. This flaw is based on the developers trustthat the master key is stored securely on the device, however many of the securitymechanisms of operating systems such as iOS have known compromises, such as the abilityto decrypt data stored on the keychain.Failure to use key derivation functions - Applications that do encrypt the master key with auser passphrase expose themselves to attack if they fail to use a key derivation function, or ifthey use a weak implementation that can be easily brute forced. It is common practice formany applications to simply use an MD5 hash or a single pass of one type of encryption toencrypt a master key, making it easy to brute force the master key encryption using crackingtools or rainbow tables. Key derivation functions are designed to use large amounts of © Copyright 2012 viaForensics, all rights reserved. 9 No distribution or republication without permission.
  11. 11. 42+ Best Practices: Secure mobile development for iOS and Androidcomputing resources to derive a key from a passphrase, making it more difficult to launchbrute force attacks.Runtime attacks - Applications that encrypt data internally, where a user passphrase is notincorporated into the encryption, are potentially exposed to runtime attacks, where theinternal logic of an application can be bypassed causing the application itself to automaticallyload the master key and decrypt user data, sometimes even providing GUI access to theattacker. This is commonly the case with portions of the application that are used internally,such as server credentials or other internally encrypted data, although sometimes sensitiveuser data is also stored in this fashion. © Copyright 2012 viaForensics, all rights reserved. 10 No distribution or republication without permission.
  12. 12. 42+ Best Practices: Secure mobile development for iOS and Android Best Practices: Securing Android and iOS apps When it comes to achieving app security, there is no silver bullet. Rather, one must take an approach that encompasses a number of defensive measures designed to protect data and systems from a variety of different attack methods. Accomplishing this goal means taking proactive steps before your app hits the market. Important Note: Every recommendation in this document is not appropriate for every app. In general, the more sensitive the data and need for security, the more attention these practices require. The more essential recommendations are listed first, with the first 10 representing the more fundamental security practices that all developers should follow. Securing the application layer Securing the application layer involves a number of practices, broadly:  Storing sensitive data securely, or not at all  Handling authentication and sessions properly  Designing and coding the app to use security and encryption mechanisms correctly  Avoiding unintended information leakage  Resisting runtime manipulation  Leveraging code obfuscation and anti-tampering to complicate reverse engineering The following best practices cover these areas in more detail, in some cases to the level of code examples. Mobile apps provide the opportunity to add security measures, but also require proper engineering and code to avoid vulnerabilities. Read on for the specifics.1 Avoid storing sensitive data on the device If possible, do not store sensitive data on the device. Consider that nearly any data stored locally, even if encrypted, could be compromised – only store data if essential. For many applications, it is functionally and technically possible to simply not store sensitive data. If sensitive data must be stored locally, use properly implemented encryption. While not 100% secure, it can add significant complexity to an attack. A master key should be encrypted with a user passphrase, using a key derivation function, such as PBKDF2, with a very high number of iterations to consume enough CPU so as to make a brute force attempt very computationally time consuming, even on a faster platform. © Copyright 2012 viaForensics, all rights reserved. 11 No distribution or republication without permission.
  13. 13. 42+ Best Practices: Secure mobile development for iOS and Android Options to reduce the storage of user information include: 1. Transmit and display but do not persist to memory. This requires special attention as well, to ensure that an analog leak does not present itself, where screenshots of the data are written to disk. 2. Store only in RAM (clear at application close) 3. Encrypt the data using strong encryption, combined with a master key encrypted with a passphrase required when the application starts Other options such as using a local file and then clearing or deleting it upon application exit are not sufficient for preventing the recovery of data.2 Avoid caching app data on the device Data can be captured in a variety of artifacts – many unintended. Developers often overlook some of the ways data can be stored including log/debug files, cookies, web history, web cache, property lists, files and SQLite databases. Prevent HTTP caching. Developers can configure iOS to not cache web data, particularly HTTPS traffic. Look into implementing an NSURLConnection delegate and disabling newCachedResponse. In addition, we recommend that steps be taken to avoid caching of URL history and page data for any Web process such as registration. HTTP Caching headers are important in this, and are configured on the web server. The HTTP protocol supports a “no-store” directive in a response header that instructs the browser that it must not store any part of either the response or the request that elicited it. Additional information on caching headers may be found here: For Web applications, HTML form inputs can use the autocomplete=off setting to instruct browsers not to cache values. The avoidance of caching should be validated through forensic examination of device data after app utilization.3 Avoid use of query string for sensitive data A major bank breach was executed with a simple query string modification “attack”. Query string parameters are more visible and can often be unexpectedly cached (web history, webserver or proxy logs, etc.) Using an unencrypted query sting for meaningful data should be avoided. © Copyright 2012 viaForensics, all rights reserved. 12 No distribution or republication without permission.
  14. 14. 42+ Best Practices: Secure mobile development for iOS and Android Instead, use secure POST to send user data, with XSRF token protection. POST data is not logged by default in areas where query string data can be found. If credentials are transmitted as query string parameters, as opposed to in the body of a POST request, then these are liable to be logged in various places — for example, within the user’s browser history, within the Web server logs, and within the logs of any reverse proxies employed within the hosting infrastructure. If an attacker succeeds in compromising any of these resources, then he may be able to escalate privileges by capturing the user credentials stored there. Pinto, Marcus (2007). The Web Application Hackers Handbook: Discovering and Exploiting Security Flaws (Kindle Locations 2813-2816). Wiley. Kindle Edition Whether POST or GET, temporary session cookies should be used. Encrypting data using a non-zero initialization vector and temporary session keys can also help prevent a replay attack. If necessary, query string data can be encrypted using a temporary session key negotiated between hosts using secure algorithms, such as Diffie-Hellman.4 Avoid crash logs If an app crashes, the resulting log can provide valuable info to an attacker. Ensure apps are built without warnings and are thoroughly tested to avoid crashes. This is certainly always the goal and worth mentioning due to the value of a crash log. Consider disabling NSAssert for iOS. This setting will cause an app to crash immediately if an assertion fails. It is more graceful to handle the failed assertion than to crash and generate the crash log.5 Fully validate SSL/TLS Many apps do not properly validate SSL certificates, leaving them susceptible to man-in-the- middle attacks. Certificates should be fully validated by the client and signed by a trusted root CA. Lower levels of encryption (such as export-grade 40-bit encryption) should be disabled on the server (see Network). In addition to protecting the SSL session by ensuring it is valid, ensure that the URLs being accessed are not stored in an easily modifiable form in the binary itself. By simply modifying the URL in the binary, an attacker could change the domain in the URL to their own, for which they may possess a valid SSL certificate. © Copyright 2012 viaForensics, all rights reserved. 13 No distribution or republication without permission.
  15. 15. 42+ Best Practices: Secure mobile development for iOS and Android On WAP sites, check HTTPS and host address. Although less tamper-proof than native app code, client-side JavaScript can be used to check for presence of https, proper host URL, and acceptable host IP address. As an improvement, browsers are beginning to implement the Strict Transport Security HTTP Header, which causes the browser to require HTTPS for a site once the header has been received. From a user interface perspective, WAP sites can encourage users to install a more secure native mobile app. Developers should avoid the temptation to display a lock icon or “secure” verbiage that does not depend on any actual security mechanism, as this can encourage a false sense of trust. In many cases, it is not necessary to use certificates from a public certificate authority, as these were designed for systems where the client did not know whether the system it was connecting to was trusted. Since applications know exactly where they are connecting to, and inherently trust the infrastructure they are connecting to, it is acceptable (and often more secure) to use a "private" public key infrastructure, separate from public certificate authorities. This way, an attacker would require the private keys from the server side in order to perform a MITM attack or other such types of attacks.6 Institute Local Session Timeout Mobile devices are frequently lost or stolen, and an app which can be leveraged to access sensitive data, execute transactions, or research a device owner’s accounts should require login after a short time of inactivity. Any time the app is not actively utilized for more than 5 minutes, the active session should terminate and the user should be required to re-enter credentials. When an applications session is timed out, the application should also discard and clear all memory associated with the user data, and any master keys used to decrypt data. A skilled attacker operating on a stolen device could potentially steal this data from memory if it is not cleared.7 Disable debug logs Debug logs can store sensitive data. Ensure debug logs are not enabled in production build. Disabling the NSLog statements on iOS will remove potentially sensitive information which can be intercepted and slightly increase the performance of the app. © Copyright 2012 viaForensics, all rights reserved. 14 No distribution or republication without permission.
  16. 16. 42+ Best Practices: Secure mobile development for iOS and Android The Android system log typically used by apps for outputting debug messages is a circular log of a few kilobytes living in memory. On device reboot it is cleared, but until then any Android app with the readlogs permission can interrogate the logs.8 Hide account numbers and use tokens Many apps store complete account numbers in the various screens. Given the widespread use of mobile apps in public places, displaying partial numbers (e.g. ***9881) can help ensure maximum privacy for this information. Unless there is a need to store the complete number on the device, store the partially hidden numbers. Often, account numbers are used to reference server-side account data; this data can easily be stolen from memory, or in some cases manipulated to work with accounts that the user should not have the permission to access. It is recommended that instead of account numbers, tokens be assigned to each account and provided to the client. These tokens, which should not be deducible by the user, have server-side mapping to an actual account. Should the application data be stolen, the users account numbers will not be exposed, and an attacker will also not be able to reference account numbers directly, but must first determine the token that maps back to the account.9 Use SECURE setting for Cookies The Set-Cookie headers should use the SECURE setting. If a cookie is marked as secure, it will only be transmitted if the session with the host is secure. In other words, it will only be transmitted over an HTTPS connection. This setting should be applied to all cookies for apps leveraging HTTPS.10 Limit caching of username When the user enables the “Save this User ID” feature, the username is cached within the CredentialsManager object on iOS. At runtime, the username is loaded into memory before any type of authentication occurs, allowing potential for a malicious process to intercept the username. It is difficult to offer the user convenience of a stored username while avoiding leakage of such information either through insecure storage or potential interception at runtime. Although not as sensitive as the password, username is private data that should be protected. © Copyright 2012 viaForensics, all rights reserved. 15 No distribution or republication without permission.
  17. 17. 42+ Best Practices: Secure mobile development for iOS and Android One potential method that offers a cached username option with higher security is to store a masked username instead of the actual username, and replace the username value in authentication with a hash value. The hash value can be created including a unique device token stored on registration. The benefit of a process that uses a hash and device token is that the actual username is not stored locally or loaded into memory unprotected, and the value copied to another device or used on Web would not be adequate. A malicious user would have to uncover more information to successfully steal the authentication username.11 Implement code complexity and obfuscations Complicate the reverse engineering of your code, increasing the overall skill level and time required to attack it. Reverse engineering apps can provide valuable insight into how your app works. By making them more complex internally, an attacker is at a disadvantage to seeing the clear cut operation of the app, which may reduce the number of attack vectors. Reverse engineering of an Android app (.apk file) is achieved rather easily and the internal workings of the application can then be examined. It is recommended that the code be obfuscated to increase the difficulty of examination by malicious users, as described in this Android developer reference: iOS applications are also susceptible to reverse engineering attacks due to the way they are designed. An app’s classes and protocols are stored within the object file, allowing an attacker to fully map out the applications design. Objective-C itself is a reflective language, capable of perceiving and modifying its own state; an attacker with the right tools can perceive and modify the state of an application in the same way that the runtime manages the application. Objective-C incorporates a simplistic messaging framework that is very easily traceable and can be manipulated to intercept or even tamper with the runtime of an application. Relatively simple attacks can be used to manipulate the Objective-C runtime to bypass authentication and policy checks, internal application sanity checks, or the kind of logic checks that police the policies of an application. If the application handles highly sensitive data, consider implementing anti-debug techniques. Various techniques exist which can increase the complexity of reverse engineering your code. One technique is to use C/C++ to limit any runtime manipulation by the attacker. There are ample C and C++ libraries that are very mature and easy to integrate with Objective-C. Consider writing critical portions of code in low-level C to avoid exposure © Copyright 2012 viaForensics, all rights reserved. 16 No distribution or republication without permission.
  18. 18. 42+ Best Practices: Secure mobile development for iOS and Android and manipulation by the Objective-C runtime and by Objective-C reverse engineering tools such as class-dump, class-dump-z, and Cycript. Restricting debuggers - By incorporating a system call, an application can specify that the operating system should not permit a debugger to attach to the process. By preventing a debugger from attaching, the capabilities of an attacker to interfere with the low-level runtime are limited. An attacker must first circumvent the debugging restrictions in order to attack the application on a low level. This adds further complexity to an attack. Android applications should have android:debuggable="false" set in the application manifest to prevent easy run time manipulation by an attacker or malware. Trace Checking - An application can determine whether or not it is currently being traced by a debugger or other debugging tool. If being traced, the application can perform any number of possible attack response actions, such as discarding encryption keys to protect user data, notifying a server administrator, or other such type responses in an attempt to defend itself. Optimizations - To hide advanced mathematical computations and other types of complex logic, utilizing compiler optimizations can help obfuscate the object code so that it cannot easily be disassembled by an attacker, making it more difficult for an attacker to gain an understanding of the particular code. In Android this can more easily be achieved by utilizing natively compiled libraries with the NDK. Stripping binaries - Stripping native binaries is an effective way to increase the amount of time and skill level required of an attacker in order to view the makeup of your application’s low level functions. By stripping a binary, the symbol table of the binary is stripped, so that an attacker cannot easily debug or reverse engineer an application. Stripping binaries does not discard the Objective-C class and object mapping data on iOS. iOS binaries in applications distributed in the AppStore are encrypted, adding another layer of complexity. While tools exist to strip the digital rights management (DRM) encryption from these binaries, this layer of DRM increases the amount of time and proficiency level required to attack the binary. The encryption used in AppStore application can, however, be stripped by a skilled attacker by dumping the memory from which an application is loaded directly from a devices memory when run.12 Use Address Space Layout Randomization ASLR, a free new security feature introduced in iOS 4.3, randomizes how an app is loaded and maintained in memory. ASLR randomizes the address space used in the application, making it difficult to execute malicious code without first causing the application to crash. It also complicates the process of dumping allocated memory of the application. © Copyright 2012 viaForensics, all rights reserved. 17 No distribution or republication without permission.
  19. 19. 42+ Best Practices: Secure mobile development for iOS and Android Since iOS now support ASLR, applications should take advantage of this. For full ASLR protection, the application must be compiled with support for PIE (position-independent executable). PIE can be enabled when compiling by command line with option –fPIE Caveat: Applications compiled with -fPIE enabled will only run on iOS 4.3 and greater. This should be a concern for maintaining legacy applications. Attackers may look to target applications that have not been recompiled with the new PIE feature. This issue has been widely publicized, increasing the likelihood of non-PIE applications being targeted. This issue was covered in an article in CNNMoneyTech as follows: Apple introduced an important security feature in the latest version of the iPhones software, yet it is rarely used by third-party applications, leaving users vulnerable to a targeted attack. The feature, known as address space layout randomization, or ASLR, randomizes key pieces of data in the iPhone, making it difficult for attackers to find where theyre stored. One component of ASLR, known as position-independent executable, or PIE, hides executable code that hackers can use to carry out attacks. When enabled, those tools can help protect the iPhone from being remotely exploited by a hacker. Newer versions of the Android OS support ASLR to a certain degree, but there are no specific options for a developer of a typical Android application to enable or disable it.13 Avoid simple logic Simple logic tests in code are more susceptible to attack. Example: if sessionIsTrusted == 1 This is a simple logic test and if an attacker can change that one value, they can circumvent the security controls. Apple iOS has been attacked using this type of weakness and Android apps have had their Dalvik binaries patched to circumvent various protection mechanisms. These logic tests are easy to circumvent on many levels. On an assembly level, an attacker can attack an iOS application using only a debugger to find the right CBZ (compare-and- branch-on-zero) or CBNZ (compare-and-branch-on-nonzero) instruction and reverse it. This can be performed in the runtime as well by simply traversing the object’s memory address © Copyright 2012 viaForensics, all rights reserved. 18 No distribution or republication without permission.
  20. 20. 42+ Best Practices: Secure mobile development for iOS and Android and changing its instance variable as the application runs. On Android the application can be decompiled to SMALI and the branch condition patched before recompiling. Consider a better programming paradigm, where privileges are enforced by the server when the session is not trusted, or by preventing certain data from being decrypted or otherwise available until the application can determine that the session is trusted using challenge/response, OTP, or other forms of authentication. In addition, it is recommended to declare all sanity check functions static inline. With this approach they are compiled inline, making it more difficult to patch out (i.e. an attacker cannot simply override a function or patch one function). This technique would require the attacker to seek out and patch every instance of the check from the application, increasing the required complexity of an attack. For highly sensitive apps, more sophisticated approaches founded in secure coding principles may be worth further investigation. Integrating techniques such as encryption, timed callbacks and flow-based programming can add complexity for an attacker.14 Avoid simple logic variables In the same vein, simple logic variables stored in an object can be easily manipulated by an attacker. Example: session.trusted = TRUE Such values can be both read and written to by an attacker within the instance of a class currently in use by the application. On iOS by manipulating the Objective-C runtime, these variables can be manipulated so that the next time they are referenced by the application, any manipulated values will be read instead.15 Be aware of the keyboard cache iOS logs what users type in order to provide features such as customized auto-correct and form completion, but sensitive data may also be stored. Almost every non-numeric word is cached in the keyboard cache in the order it was typed; the cache’s contents are beyond the administrative privileges of the application, and so the data cannot be removed from the cache by the application. Disable the auto-correct feature for any sensitive information, not just for password fields. Since the keyboard caches sensitive information, it may be recoverable. For UITextField, look into setting the autocorrectionType property to UITextAutocorrectionNo to disable © Copyright 2012 viaForensics, all rights reserved. 19 No distribution or republication without permission.
  21. 21. 42+ Best Practices: Secure mobile development for iOS and Android caching. These setting may change over time as the SDK updates so ensure it is fully researched. Add an enterprise policy to clear the keyboard dictionary at regular intervals. This can be done by the end user by simply going to the Settings application, General > Reset > Reset Keyboard Dictionary. Android contains a user dictionary, where words entered by a user can be saved for future auto correction. This user dictionary is available to any app without special permissions. For higher security, consider implementing a custom keyboard (and potentially PIN) which can disable caching and provide additional protection against malware.16 Be aware of copy/paste iOS now supports copy/paste. Sensitive data may be stored and recoverable from clipboard in clear text, regardless of whether the data was initially encrypted. The copy/paste API is still maturing and may leak sensitive data. Android also supports copy/paste by default and the clipboard can be accessed by any application. Where appropriate, disable copy/paste for areas handling sensitive data. Eliminating the option to copy can help avoid data exposure.17 Test third-party libraries Developers rely heavily on third-party libraries. It is important to thoroughly probe and test this as you test your code. Third-party libraries can contain vulnerabilities and weaknesses. Many developers assume third-party libraries are well developed and tested, however issues can exist in their code. Security auditing must thoroughly test third-party libraries and functionality as well. This should include core iOS and Android code/libraries. Upgrading to a new version of a third-party library (or OS version) should be treated as version of your app. An updated third-party library (or new OS version) can contain new vulnerabilities or expose issues in your code. They should be tested just like you test new code for your app. On iOS, statically compile third-party libraries to avoid LD_PRELOAD attacks; in such attacks a library and its functions can be swapped out for an attacker’s library with functions replaced with malicious code. Android is not vulnerable to LD_PRELOAD attacks. © Copyright 2012 viaForensics, all rights reserved. 20 No distribution or republication without permission.
  22. 22. 42+ Best Practices: Secure mobile development for iOS and Android18 Use geolocation carefully Android and iOS can use GPS to accurately determine location. Consider implications of using and avoid storing GPS data. For better privacy use the most coarse-grained location services, if possible. Unless required, do not log or store GPS information. While it may be useful to use GPS for certain applications, it is rarely necessary to log and store the data. Avoiding this prevents many privacy and security issues. GPS positioning information is often cached for a time within the locationd caches on iOS and various caches on Android. Some applications use GPS automatically. One example is the Camera which often geo-tags images. If this is a concern, make sure to strip the EXIF data from the image. When working in secure locations, remember that GPS data may be reported back to Apple and Google servers to increase accuracy. Apple is also known to capture information about nearby access points in range, regardless of whether the device is connected to them. Do not activate GPS in applications that will run at or near secure locations, whose coordinates or wireless network topology should not be reported back to vendors. In addition to this, knowledge of a single access point’s hardware address could be used by an attacker to simulate the secure wireless environment and return GPS coordinates of the environment from Apple or Google.19 iOS: Avoid cached application snapshots In order to provide the visual transitions in the interface, iOS has been proven to capture and store snapshots (screenshots or captures) as images stored in the file system portion of the device NAND flash. This occurs when a device suspends (rather than terminates), when either the home button is pressed, or a phone call or other event temporarily suspends the application. These images can often contain user and application data, and in one published case contained the user’s full name, DOB, address, employer, and credit scores. To protect sensitive data, block caching of application snapshots using API configuration or code. Use willEnterBackground API - When an iOS app is going to be sent to the background, ensure the app is not displaying any sensitive information. Create a splash screen for the app and display this as it moves into the background. © Copyright 2012 viaForensics, all rights reserved. 21 No distribution or republication without permission.
  23. 23. 42+ Best Practices: Secure mobile development for iOS and Android20 Android: implement file permissions carefully Do not create files with permissions of MODE_WORLD_READABLE or MODE_WORLD_WRITABLE unless it is required as any app would be able to read or write the file even though it may be stored in the app’s private data directory.21 Android: implement Intents carefully Intents are used for inter-component signaling and can be used:  To start an Activity, typically opening a user interface for an app  As broadcasts to inform the system and apps of changes  To start, stop, and communicate with a background service  To access data via ContentProviders  As callbacks to handle events Components accessed via Intents can be public or private. The default is dependent on the intent-filter and it is easy to mistakenly allow the component to be or become public. It is possible to set component as android:exported=false in the app’s Manifest to prevent this. Public components declared in the Manifest are by default open so any application can access them. If a component does not need to be accessed by all other apps, consider setting a permission on the component declared in the Manifest. Data received by public components cannot be trusted and must be scrutinized.22 Android: Check Activities Typically in Android applications an Activity is a “Screen” in an app. An activity can be invoked by any application if it is exported. Some things to watch for:  If you define an Intent filter for an Activity it will automatically make it public and accessible by other applications  Even if an Activity is not public it can still be invoked with root privileges. This could allow an attacker to jump around an application in a way the developer did not intend such as jumping past a password lock screen to access the data. To prevent this the Activity can check to see if the app is in the “unlocked” state and if not jump back to the lock screen.  Regardless of what Intent filters are defined, publicly accessible Activities can be directly invoked with bad data so input validation is important. © Copyright 2012 viaForensics, all rights reserved. 22 No distribution or republication without permission.
  24. 24. 42+ Best Practices: Secure mobile development for iOS and Android  Do not put sensitive data into Intents used to start Activities. A malicious program can insert an Intent filter with higher priority and grab the data.23 Android: implement Broadcasts carefully When sending a broadcast Intent the developer can set a permission on the broadcast so that only specific apps can receive the Intent. If no permission is set, then any unprivileged app can receive the Intent unless it has an explicit destination. Also consider that if you are sending sensitive information via a broadcast Intent to a 3rd party component then the component could have been replaced by a malicious install. There is no restriction on a malicious developer creating an app with the exact same component name as a legitimate component, and as long as the namespace is not in use already the malicious app will install.24 Android: implement PendingIntents carefully PendingIntents allow apps to pass execution to another app which can then call the Intent specified as though they were the originating app. This allows external apps to call back to private components. The external app, if malicious, may try to influence the destination and or data/integrity. It is best to use PendingIntents as delayed callbacks to private Broadcast Receivers/Activities and explicitly specify the component name as one of your components in the base Intent.25 Android: validate Services Services are typically used for background processing. Similar to Activities and Broadcast Receivers, Services can be invoked by external applications and should be protected by permissions and export flags as appropriate. A service may have more than one method which can be invoked from an external caller. It is possible to define arbitrary permissions for each method and check if the calling package has the corresponding permission with checkPermission(). Alternately, you could define separate services and secure access with permissions only in the Manifest. When calling a service with sensitive data you may need to validate the service is the correct one and not a malicious service. If you know the exact name of the component you are trying to connect to you can specify that in the Intent used to connect. Otherwise you can use checkPermission() again to verify if the calling package has the particular permission needed to receive your Intent. It is up to the user at install time to grant the permission to the app. © Copyright 2012 viaForensics, all rights reserved. 23 No distribution or republication without permission.
  25. 25. 42+ Best Practices: Secure mobile development for iOS and Android26 Android: avoid intent sniffing When an activity is started by another application using a Broadcast Intent the data passed in the Intent can be read by a malicious app. The malicious app can also read a list of recent Intents for an application. For example, when the Android Web browser is invoked by an app which passes it a URL, that URL can be sniffed. It is recommended that sensitive data should not be passed between apps using Broadcast Intents.27 Android: implement Content Providers carefully ContentProviders are a standard way for apps to share data using a URI addressing scheme and relational DB model. They can also be used as a means to access “files” via the URI scheme. ContentProviders can declare permissions and can separate read and write access. Do not enable write access if not needed. Enable permissions to prevent any unprivileged app from reading the ContentProvider unless required. ContentProviders also allow record level delegation in order to share a specific record (or “file”) without sharing the entire database. Use this feature to provide the minimum access required for an operation. For example, you could share a single “Instant Message” with an external application which emails it to a contact, without the external app having access to all messages. When the external app returns to the originating app the delegation ends.28 Android: WebView best practices WebViews can introduce a number of security concerns and should be implemented carefully.  Disable JavaScript and Plugin support if they are not needed. They are disabled by default but it is good practice to explicitly set these.  Disable local file access. This restricts access to the app’s resource and asset directory and mitigates against an attack from a web page which seeks to gain access to other locally accessible files.  Prevent loading content from 3rd party hosts. This is tricky to completely prevent from within an app but a developer can override shouldOverrideUrlLoading and shouldInterceptRequest to intercept, inspect, and validate most requests initiated from within a WebView. © Copyright 2012 viaForensics, all rights reserved. 24 No distribution or republication without permission.
  26. 26. 42+ Best Practices: Secure mobile development for iOS and Android  A whitelist scheme can also be implemented by using the URI class to inspect the components of a URI and ensure it matches a whitelist of approved resources. For more information see: with-android-webviews/29 Android: avoid storing cached camera images Many remote deposit capture apps leave check image data the NAND memory even after it is deleted. It is recommended that a different approach be used that will avoid leaving any check image artifacts on the device. One possible approach is to:  Create a SurfaceView and have it display a Camera Preview, or a live preview of what the camera is seeing.  Insert a button, and when it is pressed, program it to return the Camera Preview as a pixel array. This can then be converted to a bitmap, compressed to JPG, base64 encoded and submitted to the remote site all in RAM.30 Android: Avoid GUI objects caching On Android, application screens are retained in memory and entire applications can be retained in memory because of multitasking. An attacker who finds or steals a device is able to navigate directly to previously used screens that are still retained and see any data still shown on the GUI. An example of this would be a banking application where a user views their transaction history and then “logs out” of the application. By launching the transaction view activity directly the attacker can see the previous transactions that were displayed. To counter this, a developer has three common options: 1) Quit the app entirely when the user logs out. It is against Android design principles to quit your own app but it is more secure as the GUI gets destroyed/recycled. 2) Perform a test at the start of each Activity/screen to check if the user is in a logged in state, if not, switch to the login screen. 3) Nullify the data on a GUI screen when leaving the screen or logging out.31 iOS: Use the Keychain carefully iOS provides the Keychain for secure data storage, however, in several scenarios, the keychain can be compromised and subsequently decrypted. © Copyright 2012 viaForensics, all rights reserved. 25 No distribution or republication without permission.
  27. 27. 42+ Best Practices: Secure mobile development for iOS and Android In all versions of iOS up to and including iOS 5, Apple created a situation where the keychain file may be stored in an encrypted but breakable manner in iTunes backups. In such cases, an attacker will likely be successful in compromising the keychain. Recent advances in iOS forensic and security tools now allow the Keychain to be cracked. While the attacker must have physical access to the iOS device and specialized software, the Keychain is now exposed. There are open source, downloadable tools to decrypt an iOS 4 and iOS 5 keychain. For highly sensitive data, consider avoiding use of the keychain. Instead, rely upon the user to enter application passphrases when the application starts, or with encryption keys sent from the server after a user authenticates.32 Implement secure data storage Storing data securely on a mobile device requires proper technique. Whenever possible, simply do not store/cache data. This is the only way to completely avoid data compromise on the device. Custom Encryption – For storing sensitive data, include your own or third-party cryptographic functions. By using your own codebase, you have more control over the implementation and attacks focused on the main iOS data-protection classes (which are now compromised) will not target your application directly. This approach has the drawback of being more complex and, if implemented poorly, can actually reduce security posture. Apple and Android’s common cryptographic libraries provide a number of standard cryptographic functions which, if implemented properly, can provide a reasonably secure cryptography implementation. Whenever encrypting user data, be sure to encrypt it using a randomly generated master key, which is also encrypted using a passphrase supplied by the user whenever data is accessed. This will prevent data from being easily recovered should an attacker extract the master key from the device. Due to the number of vulnerabilities in Apples data-protection APIs and keychain and the lack of device encryption on the majority of Android handsets, it is not recommended that the master key or a passphrase be stored on the device at all. iOS - The Data Protection APIs built into iOS, combined with a complex passphrase can provide an additional layer of data protection, but are not as secure as implementing custom cryptography. To leverage this, files must be specifically marked for protection. Any data not specifically encrypted using Apple’s data protection APIs is stored unencrypted. © Copyright 2012 viaForensics, all rights reserved. 26 No distribution or republication without permission.
  28. 28. 42+ Best Practices: Secure mobile development for iOS and Android Android - In Android remember that the external storage such as SD Card has no fine grained permissions and that any app by default has read access to the storage and can read all files. Android implements standard crypto libraries such as AES that can be used to secure data. Remember that data encrypted with this method is only as secure as the password used to derive the key and key management. Consider the password policy, length and complexity versus user convenience, and how the encryption key is stored in memory. With root access it is easy to dump the memory of a running process and search it for encryption keys. Also note that using the standard cryptographic provider “AES” will default to the less secure AES-ECB. It is recommended to specify AES-CBC with a 256bit key and a random IV generated by SecureRandom. It is recommended that the key be derived from a passphrase using the well tested PBKDF2 (Password-Based Key Derivation Function).33 Limitations of UUID Most mobile devices have a unique ID (UUID) created at the time of manufacturing for identification purposes. The ability to uniquely identify a device is often important to procure, manage and secure data. Developers quickly adopted the UUID for device identification thus making it a foundation of security for many systems. Unfortunately, there are several privacy and security issues with this approach. First, many online systems have connected the UUID of a device to an individual user which can enable tracking across applications, even when the user is not logged into the app. This advanced ability to track a user has become a major privacy concern. Beyond that, apps which identify a person through the UUID risk exposing the data of the previous device owner to a new user. In one test example, after re-setting an iPhone, we were able to gain access to an online music service even though all user data had been erased. This can be both a privacy issue as well as a security threat since it is quite easy for an attacker to fake a UUID. Apple has recognized both the privacy and security risks of UUID and has removed developer access. However, developers have found other means to uniquely identify a unit, such as the MAC address of the wireless network interface. A MAC address is also quite easy to spoof and thus does not represent a more reliable approach. We recommend that developers avoid using any device-provided identifier to identify the device, especially if integral to an implementation of device authentication. Instead, we recommend the creation of an app-unique “device factor” at registration, installation or when the app is first run. This app-unique device factor would be required later along with © Copyright 2012 viaForensics, all rights reserved. 27 No distribution or republication without permission.
  29. 29. 42+ Best Practices: Secure mobile development for iOS and Android user authentication to create a session. The device factor could also be used as part of an encryption factor. Since it is not relying on predictable, device supplied data, exploitation becomes more difficult. By leveraging a challenge-response approach, the server and device can authenticate each other prior to user authentication. To gain system access an attacker would have to exploit both factors. Developers can also implement a feature where the device factor is reset on the client or server side, forcing a more stringent re-authentication of the user and device.34 Tamper checking Secure apps contain anti-tamper techniques which prevent them from running if tampered with. This is often found in highly secure applications, such as those used by the military. However, the concepts can also be integrated into commercial apps. Using checksums, digital signatures and other validation mechanisms on files used in the application can help detect whether data files have been tampered with in an attempt to manipulate the application, and can also ensure any data files are authentic by enforcing a signature embedded within the application. Note that such checks can be bypassed by an attacker, however such a check can not only further complicate the time required to breach the application, but may also frustrate an attacker should the application silently wipe its user data keys or other important data whenever tampering is detected. Similarly, applications which have detected tampering can notify an administrator. On Android, the public key used to sign an app can be read from the app’s certificate and used to verify the application was signed with the developer’s private key. This is especially useful to try and detect if the app has been backdoored and resigned by an attacker. Such attacks are becoming prevalent in popular apps and financial apps which are having malicious code automatically inserted and then being published to alternative markets.35 Implement enhanced / two-factor authentication A password should not be simplistic. Support or require complex passwords, including length of at least 6 alphanumeric characters (more is always stronger). Adding a secret word/icon selection which user does not create helps protect users in case their (same) password was compromised on a different service. In some cases a username and password does not provide sufficient security for a mobile app. When sensitive data or transactions are involved, implement two-factor authentication. This may not be feasible for every login but can be used at intervals or when accessing © Copyright 2012 viaForensics, all rights reserved. 28 No distribution or republication without permission.
  30. 30. 42+ Best Practices: Secure mobile development for iOS and Android selected functions. Step-up authentication allows normal access to non-transactional areas and requires a second layer of authentication for sensitive functions. Options for enhanced authentication include: 1. Additional secret word 2. Additional code provided by SMS or email – but be aware that an attacker will likely have access to both on a stolen device 3. Password plus additional user-known value (e.g. last four SSN) 4. Security question/answer, set by user in advance (e.g. during registration) For highest security, the use of one-time passwords (OTP) requires the user of the application to not only possess the correct credentials, but also a physical token containing the one time password.36 Protect application settings iOS developers often store application settings in plist files which can be compromised in some situations. Similarly, Android developers often store settings in a shared prefs XML file or SQLite DB, which are not encrypted by default and can be read or even modified with root permissions. Compile settings into the code when possible. There is little benefit to configuring an app via plist file on iOS since changes must be bundled and deployed as a new app anyway. Instead, include configuration inside app code which requires more time and skill for attackers to modify. Don’t store any critical settings in dictionaries or other files unless encrypted first. Ideally, encrypt all configuration files using a master key encrypted with a passphrase that is supplied by the user, or with a key provided remotely when a user logs into a system.37 Securely store sensitive data in RAM When using sensitive data such as decryption keys, do not keep them in RAM longer than required. Variables holding keys can be nullified after use. On Android, because an application stays in memory after use until the memory needs to be reclaimed, encryption keys can linger in the background. An attacker who finds or steals the device can attach a debugger and dump the memory from the application, or load a kernel module to dump the entire contents of the RAM. © Copyright 2012 viaForensics, all rights reserved. 29 No distribution or republication without permission.
  31. 31. 42+ Best Practices: Secure mobile development for iOS and Android38 Understand secure deletion of data On Android calling file.delete() will not securely erase the file and as long as it is not overwritten it can be carved from a physical image of the device. Traditional approaches to overwriting a file generally do not work on mobile devices due to the aggressive management of the NAND Flash memory. A developer should assume that any data written to a device can be recovered. In some instances, encryption might add an additional layer of protection. In addition, while not advisable for most applications, it may be possible to delete a file and then overwrite all available space (create a large file) which would force the NAND Flash to erase all unallocated space. The drawbacks to this technique include wearing out the NAND Flash, causing the app and the entire device to respond slowly, and significant power consumption. As stated earlier, the best approach is to avoid storing sensitive information on the device.39 Avoid use of MEID as user identifier Although convenient for identifying the “same device” across multiple sessions, there are two key problems with the MEID. First, there is a privacy issue because the MEID is considered by many to be personal information, and a key identifier that could be used to track an individual’s activity (GPS location, purchases, etc.) by companies without user knowledge. Second, the MEID is considered compromised because it is available to many apps, and it can be spoofed on a device. In consideration of these issues, an alternative option is to create a unique device token on installation/activation of the app for a particular device. Such token would not store any user information, but can be used across sessions to identify the “activated” device in transactions. Securing the network layer Mobile devices like smart phones tend to be promiscuous – they connect to a variety of Wi-Fi networks without much thought about security. Such networks can be monitored or host devices or users launching attacks. While SSL remains the standard for securing Web communications, it has proven vulnerable in a number of ways. Developers can strengthen their apps to protect against attacks that target these vulnerabilities. © Copyright 2012 viaForensics, all rights reserved. 30 No distribution or republication without permission.
  32. 32. 42+ Best Practices: Secure mobile development for iOS and Android Protect against SSLStrip40 This MITM attack is difficult to prevent on mobile Web apps. It transparently hijacks HTTP traffic on a network, monitors for HTTPS requests and then eliminates the SSL leaving the client on an unsecured connection. SSLStrip is a difficult attack to prevent in a Web app, but there are several steps which can be taken to mitigate this risk. First, if possible eliminate all HTTP traffic for your secured application. This will not eliminate the risk but help set the proper foundation. Second, have the client validate that SSL is active. This is straight forward in fully native apps. In mobile Web apps, this can be achieved through JavaScript and if an HTTPS connection is not detected, the client can redirect to HTTPS. An example of a basic check for HTTPS is as follows: <script type="text/javascript"> if (document.location.protocol != "https:") { document.location.href = "" + document.location.pathname; }; </script> A more reliable means of requiring SSL has been designed – the Strict Transport Security HTTP Header. This header causes the browser to require HTTPS for a site once the header has been received. However, browsers are just beginning to implement the Strict Transport Security HTTP Header, and mobile browser support is lagging. Avoid icons/language that assures user of secure connection but which does not depend on validated HTTPS session. Finally, user education is an important component in reducing the risk of SSLStrip attacks. Reinforce the importance of HTTPS on all user-facing documentation, communication, training, etc.41 Certificate Pinning If your app makes calls to your servers over SSL there is no reason to rely on CA signatures to validate the authenticity of the connection (which is the default behavior). CA certificates are for general purpose network communication where you don’t know the destinations ahead of time. Because you know the server address the app will connect to, you can validate the certificate presented to your app is actually the correct certificate. This is called certificate pinning and will prevent against CA compromises such as the well-publicized DigiNotar and Comodo incidents. © Copyright 2012 viaForensics, all rights reserved. 31 No distribution or republication without permission.
  33. 33. 42+ Best Practices: Secure mobile development for iOS and Android Google already does this in their Chrome browser for Google services and the official Android Twitter client includes certificate pinning. More information here: Securing the data center layer The data center is the ultimate goal of many Web and mobile attacks, because that is where the larger stores of valuable data reside. With mobile apps, some developers forget that they are still exposing public Web services and must secure servers that provide the back-end for mobile apps. Following best practices for security in the data center layer can help avoid costly breaches of databases or Web servers, while also protecting individual app users.42 Validate input from client Like good Web app security, all input from the client should be untrusted. Services must thoroughly filter and validate input from the app. Even if data is coming from your app, it is possible to intercept and manipulate. This could include attacks that cause the app to crash (generating a key crash log), buffer overflows, SQL Injection, and other attacks. Properly sanitize all user input before transmitting. In addition to this, do not embed logic checks within the application, as these logic checks can be bypassed by an attacker with control over your application. Implement these logic checks on the server side.43 Web server: check session settings Sessions for users are maintained on most apps via a cookie, which can be vulnerable. Web languages (e.g. Java, .NET) offer session management, which is well-developed and security tested. Keep server software up-to-date with security patches. Rolling your own session management is more risky; undertake only with significant expertise. Ensure size of session cookie is sufficient. Short or predictable session cookies make it possible for an attacker to predict, highjack or perform other attacks against the session. Use high-security settings in session configuration.44 Prevent framing and clickjacking Framing involves delivery of a Web/WAP site in an iFrame, which can enable “wrapper” site to execute clickjacking attacks. Clickjacking is a very real threat that has been exploited on sites including Facebook to steal information or direct users to attack sites. © Copyright 2012 viaForensics, all rights reserved. 32 No distribution or republication without permission.
  34. 34. 42+ Best Practices: Secure mobile development for iOS and Android One avenue for the prevention of framing leverages client-side JavaScript. Most Web sites are no longer designed or able to run without JavaScript, so the implementation of security measures in JavaScript (and disabling site without it) is an option. Though client-side and therefore not impervious to tampering, this layer does raise the bar significantly for the attacker. Below is an example of JavaScript code that forces the site to the “top” frame, thereby “busting” a frame which had loaded the site. if( self != top ) { top.location = self.location ; } There are additional steps an attacker can add to their frame to attempt to prevent the frame busting code, such as an alert to the user on unload asking them not to exit. More complex JavaScript may be able to counter such techniques. The inclusion of at least basic frame busting code makes simple framing a much more difficult process. X-FRAME-OPTIONS HEADER - A new and better anti-framing option has recently been implemented in some browsers, based on an HTTP Header sent in the response. By configuring this header at the Webserver level, the browser is instructed not to display the response content in a frame or iFrame. An example implementation of this in an Apache config file is as follows: Header add X-FRAME-OPTIONS "DENY" Another option is to set this value to “SAMEORIGIN” which will only allow a frame from the same domain. This header has been tested on various browsers including Safari on iOS 4 and confirmed to prevent the display of a page in an iFrame. Provided that no requirements exist for deliver y in an iFrame, the recommendation is to use DENY. More information on the X-FRAME-OPTIONS header can be found here: Web server configuration Certain settings on a web server can increase security. One commonly overlooked vulnerability on a Web server is information disclosure. Information disclosure can lead to serious problems, because every piece of information attackers can gain from a server makes staging an attack easier. © Copyright 2012 viaForensics, all rights reserved. 33 No distribution or republication without permission.
  35. 35. 42+ Best Practices: Secure mobile development for iOS and Android A simple way to reduce information disclosure is to disable verbose errors. Verbose errors can be useful in a development environment, but in a production environment can leak critical information such as Web framework information and versions. Attackers can use this information to target attacks that are designed to exploit implementation-specific flaws. Another simple way to reduce information disclosure is to return the minimum amount of information in server responses. By default, Apache will return its version number, the OS it is running on, and the plugins that it has running. By changing a single line in the configuration file, this can be pared down to only disclosing that the server is running Apache. One configuration change in servers that can greatly improve security is to change any default directories. Attackers frequently look through the Internet for sites with “low- hanging fruit,” such as default logins, easily guessable admin interfaces, and simple naming schemes for “hidden” directories. It is a good policy to obfuscate the locations of any sensitive pages on a server that need to be Web-accessible. Administration or other restricted areas should not be publicly Web-accessible unless necessary, and must be resistant to brute force attacks. HTTP authentication or forms authentication without lockout protection can (and will) be attacked by brute force.46 SSL Configuration Ensure SSL certificates are properly installed and configured for highest encryption possible. Many web servers allow lower encryption settings, such as the very weak export-grade 40-bit encryption. Enable only strong ciphers (128-bit and up) and SSLv3/TLSv1. TLSv1 is more than 10 years old and was found vulnerable to a “renegotiation attack” in 2009. Most servers using TLSv1 have been patched to close this vulnerability, but this should be verified. The TLSv1 protocol has been updated and the more current TLSv1.2 offers the latest technology and strongest encryption ciphers available. Updating to the newer version of TLS should harden and future-proof the application.47 Protect against CSRF with form tokens CSRF (Cross-site Request Forgery) relies on known or predictable form values and a logged-in browser session. Each form submission should contain a token which was loaded with the form or at the beginning of a user session. Check this token on server when receiving POST to ensure user originated it. This capability is provided with major Web platforms, and can be implemented on forms with minimal custom development. © Copyright 2012 viaForensics, all rights reserved. 34 No distribution or republication without permission.
  36. 36. 42+ Best Practices: Secure mobile development for iOS and Android48 Protect and pen test Web services In general, the production Web server must be thoroughly tested and hardened against malicious attack. A compromised server has the potential to intercept user credentials and launch other attacks against app users. Production server software should be updated to current secure versions, and hardened to prevent information disclosures regarding server software and interfaces. Authentication forms should not reflect whether a username exists. If an attacker has a method to determine valid usernames, they have a starting point for brute-force and phishing attacks. Prevent username harvesting by providing the same response back to the client for both “invalid user/pass combination” and “no such username found.” All login forms and forms/pages exchanging sensitive data should implement and require HTTPS. Web servers should not allow client connections without SSL for such resources. Turn off verbose errors, remove any legacy unnecessary sites or pages, and continually harden Web resources against potential attacks.49 Protect internal resources Resources for internal use such as administration login forms should be blocked from external access. Such resources frequently leverage authentication that is not resistant to brute force, such as HTTP or forms authentication without lockout. Compromise of administration or other internal resources can lead to extensive data loss and other damage. Any resource that does not require public Internet access should be restricted using firewall rules and network segmentation. If a login page, admin area or other resource is accessible externally, assume it will be discovered by malicious users and attacked by brute force. © Copyright 2012 viaForensics, all rights reserved. 35 No distribution or republication without permission.
  37. 37. 42+ Best Practices: Secure mobile development for iOS and AndroidDON’T PANICSecuring applications has always been challenging; mobile app are even more difficult.However, the sky is not falling and we should heed the sage advice DON’T PANIC because:It is possible to secure mobile apps.We hope our 42+ Best Practices: Secure mobile development for iOS and Android providesdevelopment and security teams with empirical knowledge in meeting this challenge.Through awareness, education, knowledge sharing and a focus on security, we can all enjoy asafer mobile environment.If you find our 42+ Best Practices for Secure Mobile Development useful, you might want totake a look at appSecure®, our mobile application security audit and certification program. Inaddition, you’ll probably find Santoku Linux, our free mobile security, malware and forensicsplatform quite helpful.viaForensics is partnering with IT certification and education leader CompTIA to createcertifications in secure development for iOS and Android. These certifications are scheduledto be available later in 2012, so stay tuned. © Copyright 2012 viaForensics, all rights reserved. 36 No distribution or republication without permission.