Swift: Add qhelp and examples.

This commit is contained in:
Geoffrey White
2023-07-03 13:25:49 +01:00
parent 4cdc257a06
commit 373eb00975
3 changed files with 75 additions and 0 deletions

View File

@@ -0,0 +1,50 @@
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
Constructing a regular expression with unsanitized user input is dangerous,
since a malicious user may be able to modify the meaning of the expression. In
particular, such a user may be able to provide a regular expression fragment
that takes exponential time in the worst case, and use that to perform a Denial
of Service attack.
</p>
</overview>
<recommendation>
<p>
Before embedding user input into a regular expression, use a sanitization
function such as <code>NSRegularExpression::escapedPattern(for:)</code> to escape
meta-characters that have special meaning.
</p>
</recommendation>
<example>
<p>
The following examples construct regular expressions from user input without
sanitizing it first:
</p>
<sample src="RegexInjectionBad.swift" />
<p>
If user input is used to construct a regular expression it should be sanitized
first. This ensures that the user cannot insert characters that have special
meanings in regular expressions.
</p>
<sample src="RegexInjectionGood.swift" />
</example>
<references>
<li>
OWASP:
<a href="https://www.owasp.org/index.php/Regular_expression_Denial_of_Service_-_ReDoS">Regular expression Denial of Service - ReDoS</a>.
</li>
<li>
Wikipedia: <a href="https://en.wikipedia.org/wiki/ReDoS">ReDoS</a>.
</li>
<li>
Swift: <a href="https://developer.apple.com/documentation/foundation/nsregularexpression/1408386-escapedpattern">NSRegularExpression.escapedPattern(for:)</a>.
</li>
</references>
</qhelp>

View File

@@ -0,0 +1,12 @@
func processRemoteInput(remoteInput: String) {
...
# BAD: Unsanitized user input is used to construct a regular expression
let regex1 = try Regex(remoteInput)
# BAD: Unsanitized user input is used to construct a regular expression
let regexStr = "abc|\(remoteInput)"
let regex2 = try NSRegularExpression(pattern: regexStr)
...
}

View File

@@ -0,0 +1,13 @@
func processRemoteInput(remoteInput: String) {
...
# GOOD: Regular expression is not derived from user input
let regex1 = try Regex(myRegex)
# GOOD: Sanitized user input is used to construct a regular expression
let escapedInput = NSRegularExpression.escapedPattern(for: remoteInput)
let regexStr = "abc|\(escapedInput)"
let regex2 = try NSRegularExpression(pattern: regexStr)
...
}