Code Injection is a type of attack where an attacker passes malicious code through application input data to perform unauthorized operations. According to OWASP, 2024, injections are among the top three most critical vulnerabilities. Understanding code injection mechanisms allows developers to design secure systems from day one of development.
Key Takeaways
Code Injection is a class of attacks where an attacker injects executable code into an application through untrusted input data. In mobile applications, the attack is possible through input fields, deep links, push notifications, QR codes, and file exchange.
Unlike OS-level attacks, Code Injection exploits logical errors in the application's own code: lack of escaping, unsafe string concatenation, or trust in external data sources. According to a Positive Technologies report (2025), injections account for 23% of all vulnerabilities in mobile applications in the financial sector.
The main danger of Code Injection is complete data compromise: an attacker can gain access to the database, device file system, or other users' accounts. For mobile applications handling payment data or medical information, the consequences can be critical.
Developers need to understand the types of injections and apply protective mechanisms at all levels — from data input to display and storage. Modern frameworks provide built-in security tools, but their use requires a conscious approach.
The classification of Code Injection includes three main types of attacks in the context of mobile development. Each type exploits different application components and requires specific protection methods.
SQL Injection (SQLi) is the injection of malicious SQL code through query parameters to a local or remote database. In mobile applications, the vulnerability occurs when working unsafely with SQLite on the device or when building HTTP requests to REST API with string concatenation.
A typical attack vector is a search or filter field whose value is directly substituted into an SQL query. If the developer uses raw concatenation instead of parameterized queries, an attacker can pass a string like 1' OR '1'='1. According to OWASP Mobile Top 10 (2024), SQL Injection remains the second most frequent critical vulnerability in mobile applications in the insecure data storage category.
Protection against SQLi is built on three levels: using parameterized queries (PreparedStatement in Java, rawQuery with bindArgs in Android), input validation on the client and server side, and minimum database privileges.
XSS attacks in mobile applications target the WebView component — a built-in browser that displays HTML content. If an application loads data from external sources into WebView without sanitization, an attacker can inject JavaScript code that executes in the application context.
There are two subtypes of XSS: Stored XSS — the malicious script is saved on the server and executed on every page view, and Reflected XSS — code is passed through URL or POST parameters and executed once. In mobile applications, Stored XSS through comments, reviews, or user content displayed in WebView to other users is particularly dangerous.
Protection includes disabling JavaScript in WebView if not required, using Content Security Policy (CSP), and sanitizing HTML content through libraries like Jsoup for Android or SwiftSoup for iOS.
Command Injection is the execution of system commands on the device through unsanitized calls to Runtime.exec(), ProcessBuilder, or NSTask. In mobile applications, the attack is possible if the application passes user data into shell commands or Intents with actions.
The most vulnerable areas are file conversion functions, media processing (ffmpeg, ImageMagick), and third-party library installation. An attacker can pass a command with a pipe or redirect character that executes arbitrary code on the device. Android partially restricts shell access through the sandbox, but applications with root access or PrivEsc exploits can be compromised.
Recommended protection is a complete rejection of Runtime.exec() for processing user data, using libraries with a safe API, and strict isolation of external processes.
The mechanism of Code Injection differs on Android and iOS platforms due to architectural differences. On Android, injections are often associated with Intent — a system message passed between application components. An attacker can send a malicious Intent with extra data containing SQL code or shell commands.
On iOS, attacks more often occur through the Interprocess Communication (XPC) mechanism, Universal Links, and URL Scheme handling. An application that accepts data from external sources without validation becomes vulnerable to injections. According to Apple Security Research (2025), about 12% of vulnerabilities in iOS applications are related to insufficient input data sanitization.
A common vector for both platforms is an attack through local storage (SQLite, Realm, UserDefaults). If a malicious application can write data to a shared directory, it can inject code that will be executed by the target application upon reading.
A typical attack process includes three stages: reconnaissance — analysis of application entry points (forms, deep links, files), injection — delivery of malicious payload through the found entry point, and exploitation — execution of the injection to gain access to data or functionality. Understanding this cycle helps developers design protection at each stage.
Let’s look at specific examples of Code Injection in Kotlin for Android and Swift for iOS. Each example shows a vulnerable pattern and its secure alternative.
The first example is direct string concatenation of a query with user input. With the value userInput = "1' OR '1'='1", the query returns all table rows instead of one.
// VULNERABLE: string concatenation
fun getUserById(userInput: String): List<User> {
val db = openOrCreateDatabase()
val query = "SELECT * FROM users WHERE id = " + userInput
return db.rawQuery(query, null)
}
// SECURE: parameterized query
fun getUserByIdSafe(userInput: String): List<User> {
val db = openOrCreateDatabase()
val query = "SELECT * FROM users WHERE id = ?"
return db.rawQuery(query, arrayOf(userInput))
}
The second example demonstrates incorrect and correct loading of user HTML content in WKWebView. Using SwiftSoup allows removing malicious scripts before rendering.
// VULNERABLE: direct HTML loading
let webView = WKWebView()
let html = "<div>\(userComment)</div>"
webView.loadHTMLString(html, baseURL: nil)
// SECURE: sanitization via SwiftSoup
import SwiftSoup
let cleanHtml = try SwiftSoup.clean(
userComment,
Whitelist.basic()
)
webView.loadHTMLString(cleanHtml, baseURL: nil)
The third example is the danger of calling Runtime.exec() with user arguments and a secure alternative through a library with a fixed API.
// VULNERABLE: shell command with user input
fun convertVideo(inputPath: String) {
val cmd = "ffmpeg -i $inputPath -vcodec libx264 output.mp4"
Runtime.getRuntime().exec(cmd)
}
// SECURE: argument isolation
fun convertVideoSafe(inputPath: String) {
val cmd = listOf(
"ffmpeg", "-i", inputPath,
"-vcodec", "libx264", "output.mp4"
)
ProcessBuilder(cmd).start()
}
Protection against Code Injection requires a systematic approach covering code, infrastructure, and development processes. No single method guarantees complete security — a combination of practices is necessary.
The first level is prevention: strict validation of all input data. Every field that the application receives from a user, another application, or the network must be checked for type, length, and format. Libraries like OWASP ESAPI provide ready-made validators for common scenarios.
The second level is sanitization and escaping: transforming data before using it in SQL queries, HTML templates, or shell commands. Parameterized queries completely eliminate SQL Injection, and HTML escaping prevents XSS. On Android, use Room for working with SQLite — an ORM that automatically applies bind parameters.
The third level is privilege minimization: the application should operate with the minimum necessary permissions. Use the principle of least privilege for the database, file system, and interprocess communication. iOS implements this principle through the application sandbox, and Android through the permission model and process isolation.
The fourth level is monitoring and response: logging suspicious operations, anomaly detection, and automatic blocking when attacks recur. Tools like Firebase App Check help detect fake requests to the backend from compromised clients. Integration of RASP (Runtime Application Self-Protection) allows blocking injections at runtime.
According to a Google Project Zero study (2025), the combination of these four levels reduces the risk of a successful Code Injection attack by 94%. Developers are recommended to implement protection mechanisms at the architecture design stage, rather than adding them after vulnerability discovery.
Frequently Asked Questions
Code Injection is when an attacker passes not data but code to an application. For example, instead of a username, they send an SQL query that the application executes in its database, gaining access to other records.
SQL Injection attacks the database through SQL queries, allowing reading and modifying records. XSS injects JavaScript code into WebView for execution in the user’s browser. Different targets, but the same mechanism — insufficient input validation.
Use Room with parameterized queries for SQLite, disable JavaScript in WebView, apply ProGuard/R8 for code obfuscation, and never pass user data to Runtime.exec(). Regularly update dependencies with security patches.
Yes, iOS applications are vulnerable to SQL Injection through Core Data (raw queries), XSS through WKWebView, and Command Injection through Process. The iOS sandbox limits the scale of the attack but does not prevent it completely. Always sanitize data before use.
Use SAST (Static Analysis) — tools like SonarQube, MobSF or QARK for source code scanning. Additionally, use DAST scanners for testing the running application: enter specially crafted strings (‘, OR 1=1, <script>) into all input fields.
Summary
We will develop a mobile application turnkey
IT Sectr creates iOS and Android applications for startups and businesses since 2017. We will advise you and propose the best solution.
Read also