This rule detects potential NoSQL injection vulnerabilities in iOS applications using the Realm database. The vulnerability occurs when a Realm query predicate is constructed by concatenating a static string with untrusted user input.
An attacker could provide specially crafted input that alters the logic of the NoSQL query. A successful exploit could allow the attacker to bypass authentication, access or modify sensitive data, or disrupt the application’s functionality.
To remediate this, avoid building queries using string concatenation. Instead, use parameterized queries with NSPredicate, which safely separates the query logic from user-provided values. For example, use NSPredicate(format: "name = %@", userInput) instead of "name = '\(userInput)'".
Non-Compliant Code Examples
importRealmSwiftclassUser:Object{@objcdynamicvarusername=""@objcdynamicvarisAdmin=false}funcfindUser(username:String){letrealm=try!Realm()// --- NON-COMPLIANT ---// The query predicate is built by concatenating a string with user input// *directly inside the filter call*. This pattern is detected by the rule.letresults=realm.objects(User.self).filter("username = '"+username+"'")print("Found \(results.count) users.")}// Example usagefindUser(username:"guest' OR isAdmin = true")
Compliant Code Examples
importFoundationimportRealmSwiftclassUser:Object{@objcdynamicvarusername=""@objcdynamicvarisAdmin=false}funcfindUserSafely(username:String){letrealm=try!Realm()// --- COMPLIANT ---// The query uses NSPredicate, which safely handles user input.// There is no `additive_expression` here for the rule to find.letsafePredicate=NSPredicate(format:"username = %@",username)letresults=realm.objects(User.self).filter(safePredicate)print("Found \(results.count) users.")}// Example usagefindUserSafely(username:"guest' OR isAdmin = true")
Seamless integrations. Try Datadog Code Security
Datadog Code Security
Try this rule and analyze your code with Datadog Code Security
How to use this rule
1
2
rulesets:- swift-security # Rules to enforce Unknown security.
Create a static-analysis.datadog.yml with the content above at the root of your repository
Use our free IDE Plugins or add Code Security scans to your CI pipelines