Code Injection in Mobile Apps — What It Is, Attack Types and Protection

Author: IT Sectr Published: 2026-04-04 Reading time: 10 min

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 — an attack where malicious code is passed through user input and executed in the context of the application or server.
  • SQL Injection — injection of SQL code into database queries, allowing reading, modifying or deleting data without authorization.
  • Cross-Site Scripting — injection of JavaScript code into WebView that executes in the browser context of other users.
  • Command Injection — execution of system commands through unsanitized shell calls from a mobile application.
  • Input Validation — a fundamental defense method: validation, sanitization and parameterization of all input data.

What is Code Injection?

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.

Main Types of Code Injection in Mobile Apps

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 in Mobile Apps

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.

Cross-Site Scripting (XSS) in WebView

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 through Intent and Shell

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.

How Code Injection Works on Android and iOS

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.

Code Examples: Vulnerable and Secure Implementations

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.

SQL Injection: Vulnerable Code in Kotlin

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.

kotlin
// 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))
}

XSS Protection in WebView: Swift for iOS

The second example demonstrates incorrect and correct loading of user HTML content in WKWebView. Using SwiftSoup allows removing malicious scripts before rendering.

swift
// 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)

Command Injection: Protection from Shell Attacks in Kotlin

The third example is the danger of calling Runtime.exec() with user arguments and a secure alternative through a library with a fixed API.

kotlin
// 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()
}

Methods of Protecting Mobile Apps from Injections

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

What is Code Injection in simple terms?

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.

How is SQL Injection different from XSS?

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.

How to protect an Android app from Code Injection?

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.

Can an iOS app be vulnerable to injections?

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.

How to detect Code Injection vulnerabilities in an application?

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

  • Code Injection — a class of critical vulnerabilities where malicious code is injected through untrusted application input data.
  • SQL Injection — the most common type of injection, prevented by parameterized queries and ORM libraries.
  • XSS in WebView — injection of JavaScript code into HTML content, blocked by sanitization via SwiftSoup or Jsoup.
  • Command Injection — execution of shell commands through unsanitized calls, protected by argument isolation and avoiding Runtime.exec().
  • Four levels of protection — validation, sanitization, privilege minimization, and monitoring — reduce attack risk by 94%.
  • Android and iOS share common injection vectors but differ in protection mechanisms: iOS sandbox vs Android permission model.
  • Regular testing with SAST and DAST tools is essential for maintaining application security.

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.

Discuss the project

Read also