mirror of
https://github.com/github/codeql.git
synced 2025-12-17 01:03:14 +01:00
Merge pull request #13470 from geoffw0/swiftregex
Swift: Regular expressions library.
This commit is contained in:
@@ -864,6 +864,9 @@ module Make<RegexTreeViewSig TreeImpl> {
|
||||
*/
|
||||
RegExpTerm getRepr() { result = repr }
|
||||
|
||||
/**
|
||||
* Holds if the term represented by this state is found at the specified location offsets.
|
||||
*/
|
||||
predicate hasLocationInfo(string file, int line, int column, int endline, int endcolumn) {
|
||||
repr.hasLocationInfo(file, line, column, endline, endcolumn)
|
||||
}
|
||||
|
||||
6
swift/ql/lib/change-notes/2023-06-19-regex-library.md
Normal file
6
swift/ql/lib/change-notes/2023-06-19-regex-library.md
Normal file
@@ -0,0 +1,6 @@
|
||||
---
|
||||
category: feature
|
||||
---
|
||||
|
||||
* Added new libraries `Regex.qll` and `RegexTreeView.qll` for reasoning about regular expressions
|
||||
in Swift code and places where they are evaluated.
|
||||
134
swift/ql/lib/codeql/swift/regex/Regex.qll
Normal file
134
swift/ql/lib/codeql/swift/regex/Regex.qll
Normal file
@@ -0,0 +1,134 @@
|
||||
/**
|
||||
* Provides classes and predicates for reasoning about regular expressions.
|
||||
*/
|
||||
|
||||
import swift
|
||||
import codeql.swift.regex.RegexTreeView
|
||||
private import codeql.swift.dataflow.DataFlow
|
||||
private import internal.ParseRegex
|
||||
|
||||
/**
|
||||
* A data flow configuration for tracking string literals that are used as
|
||||
* regular expressions.
|
||||
*/
|
||||
private module RegexUseConfig implements DataFlow::ConfigSig {
|
||||
predicate isSource(DataFlow::Node node) { node.asExpr() instanceof StringLiteralExpr }
|
||||
|
||||
predicate isSink(DataFlow::Node node) { node.asExpr() = any(RegexEval eval).getRegexInput() }
|
||||
|
||||
predicate isAdditionalFlowStep(DataFlow::Node nodeFrom, DataFlow::Node nodeTo) {
|
||||
// flow through `Regex` initializer, i.e. from a string to a `Regex` object.
|
||||
exists(CallExpr call |
|
||||
(
|
||||
call.getStaticTarget().(Method).hasQualifiedName("Regex", ["init(_:)", "init(_:as:)"]) or
|
||||
call.getStaticTarget()
|
||||
.(Method)
|
||||
.hasQualifiedName("NSRegularExpression", "init(pattern:options:)")
|
||||
) and
|
||||
nodeFrom.asExpr() = call.getArgument(0).getExpr() and
|
||||
nodeTo.asExpr() = call
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
private module RegexUseFlow = DataFlow::Global<RegexUseConfig>;
|
||||
|
||||
/**
|
||||
* A string literal that is used as a regular expression in a regular
|
||||
* expression evaluation. For example the string literal `"(a|b).*"` in:
|
||||
* ```
|
||||
* Regex("(a|b).*").firstMatch(in: myString)
|
||||
* ```
|
||||
*/
|
||||
private class ParsedStringRegex extends RegExp, StringLiteralExpr {
|
||||
RegexEval eval;
|
||||
|
||||
ParsedStringRegex() {
|
||||
RegexUseFlow::flow(DataFlow::exprNode(this), DataFlow::exprNode(eval.getRegexInput()))
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a call that evaluates this regular expression.
|
||||
*/
|
||||
RegexEval getEval() { result = eval }
|
||||
}
|
||||
|
||||
/**
|
||||
* A call that evaluates a regular expression. For example, the call to `firstMatch` in:
|
||||
* ```
|
||||
* Regex("(a|b).*").firstMatch(in: myString)
|
||||
* ```
|
||||
*/
|
||||
abstract class RegexEval extends CallExpr {
|
||||
/**
|
||||
* Gets the input to this call that is the regular expression being evaluated.
|
||||
*/
|
||||
abstract Expr getRegexInput();
|
||||
|
||||
/**
|
||||
* Gets the input to this call that is the string the regular expression is evaluated on.
|
||||
*/
|
||||
abstract Expr getStringInput();
|
||||
|
||||
/**
|
||||
* Gets a regular expression value that is evaluated here (if any can be identified).
|
||||
*/
|
||||
RegExp getARegex() { result.(ParsedStringRegex).getEval() = this }
|
||||
}
|
||||
|
||||
/**
|
||||
* A call to a function that always evaluates a regular expression.
|
||||
*/
|
||||
private class AlwaysRegexEval extends RegexEval {
|
||||
Expr regexInput;
|
||||
Expr stringInput;
|
||||
|
||||
AlwaysRegexEval() {
|
||||
this.getStaticTarget()
|
||||
.(Method)
|
||||
.hasQualifiedName("Regex", ["firstMatch(in:)", "prefixMatch(in:)", "wholeMatch(in:)"]) and
|
||||
regexInput = this.getQualifier() and
|
||||
stringInput = this.getArgument(0).getExpr()
|
||||
or
|
||||
this.getStaticTarget()
|
||||
.(Method)
|
||||
.hasQualifiedName("NSRegularExpression",
|
||||
[
|
||||
"numberOfMatches(in:options:range:)", "enumerateMatches(in:options:range:using:)",
|
||||
"matches(in:options:range:)", "firstMatch(in:options:range:)",
|
||||
"rangeOfFirstMatch(in:options:range:)",
|
||||
"replaceMatches(in:options:range:withTemplate:)",
|
||||
"stringByReplacingMatches(in:options:range:withTemplate:)"
|
||||
]) and
|
||||
regexInput = this.getQualifier() and
|
||||
stringInput = this.getArgument(0).getExpr()
|
||||
or
|
||||
this.getStaticTarget()
|
||||
.(Method)
|
||||
.hasQualifiedName("BidirectionalCollection",
|
||||
[
|
||||
"contains(_:)", "firstMatch(of:)", "firstRange(of:)", "matches(of:)",
|
||||
"prefixMatch(of:)", "ranges(of:)",
|
||||
"split(separator:maxSplits:omittingEmptySubsequences:)", "starts(with:)",
|
||||
"trimmingPrefix(_:)", "wholeMatch(of:)"
|
||||
]) and
|
||||
regexInput = this.getArgument(0).getExpr() and
|
||||
stringInput = this.getQualifier()
|
||||
or
|
||||
this.getStaticTarget()
|
||||
.(Method)
|
||||
.hasQualifiedName("RangeReplaceableCollection",
|
||||
[
|
||||
"replace(_:maxReplacements:with:)", "replace(_:with:maxReplacements:)",
|
||||
"replacing(_:maxReplacements:with:)", "replacing(_:subrange:maxReplacements:with:)",
|
||||
"replacing(_:with:maxReplacements:)", "replacing(_:with:subrange:maxReplacements:)",
|
||||
"trimPrefix(_:)"
|
||||
]) and
|
||||
regexInput = this.getArgument(0).getExpr() and
|
||||
stringInput = this.getQualifier()
|
||||
}
|
||||
|
||||
override Expr getRegexInput() { result = regexInput }
|
||||
|
||||
override Expr getStringInput() { result = stringInput }
|
||||
}
|
||||
1226
swift/ql/lib/codeql/swift/regex/RegexTreeView.qll
Normal file
1226
swift/ql/lib/codeql/swift/regex/RegexTreeView.qll
Normal file
File diff suppressed because it is too large
Load Diff
1049
swift/ql/lib/codeql/swift/regex/internal/ParseRegex.qll
Normal file
1049
swift/ql/lib/codeql/swift/regex/internal/ParseRegex.qll
Normal file
File diff suppressed because it is too large
Load Diff
@@ -6,6 +6,7 @@ dbscheme: swift.dbscheme
|
||||
upgrades: upgrades
|
||||
library: true
|
||||
dependencies:
|
||||
codeql/regex: ${workspace}
|
||||
codeql/mad: ${workspace}
|
||||
codeql/ssa: ${workspace}
|
||||
codeql/tutorial: ${workspace}
|
||||
|
||||
@@ -11,6 +11,7 @@ import codeql.swift.dataflow.FlowSources
|
||||
import codeql.swift.security.SensitiveExprs
|
||||
import codeql.swift.dataflow.DataFlow
|
||||
import codeql.swift.dataflow.TaintTracking
|
||||
import codeql.swift.regex.Regex
|
||||
|
||||
/**
|
||||
* A taint configuration for tainted data reaching any node.
|
||||
@@ -56,6 +57,8 @@ predicate statistic(string what, string value) {
|
||||
what = "Dataflow nodes (tainted)" and value = taintedNodesCount().toString()
|
||||
or
|
||||
what = "Taint reach (per million nodes)" and value = taintReach().toString()
|
||||
or
|
||||
what = "Regular expression evals" and value = count(RegexEval e).toString()
|
||||
}
|
||||
|
||||
from string what, string value
|
||||
|
||||
6485
swift/ql/test/library-tests/regex/parse.expected
Normal file
6485
swift/ql/test/library-tests/regex/parse.expected
Normal file
File diff suppressed because it is too large
Load Diff
27
swift/ql/test/library-tests/regex/parse.ql
Normal file
27
swift/ql/test/library-tests/regex/parse.ql
Normal file
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* @kind graph
|
||||
*/
|
||||
|
||||
import swift
|
||||
import codeql.swift.regex.Regex as RE
|
||||
|
||||
query predicate nodes(RE::RegExpTerm n, string attr, string val) {
|
||||
attr = "semmle.label" and
|
||||
val = "[" + concat(n.getAPrimaryQlClass(), ", ") + "] " + n.toString()
|
||||
or
|
||||
attr = "semmle.order" and
|
||||
val =
|
||||
any(int i |
|
||||
n =
|
||||
rank[i](RE::RegExpTerm t, string fp, int sl, int sc, int el, int ec |
|
||||
t.hasLocationInfo(fp, sl, sc, el, ec)
|
||||
|
|
||||
t order by fp, sl, sc, el, ec, t.toString()
|
||||
)
|
||||
).toString()
|
||||
}
|
||||
|
||||
query predicate edges(RE::RegExpTerm pred, RE::RegExpTerm succ, string attr, string val) {
|
||||
attr in ["semmle.label", "semmle.order"] and
|
||||
val = any(int i | succ = pred.getChild(i)).toString()
|
||||
}
|
||||
580
swift/ql/test/library-tests/regex/redos_variants.swift
Normal file
580
swift/ql/test/library-tests/regex/redos_variants.swift
Normal file
@@ -0,0 +1,580 @@
|
||||
|
||||
// --- stubs ---
|
||||
|
||||
struct URL {
|
||||
init?(string: String) {}
|
||||
}
|
||||
|
||||
struct AnyRegexOutput {
|
||||
}
|
||||
|
||||
protocol RegexComponent {
|
||||
}
|
||||
|
||||
struct Regex<Output> : RegexComponent {
|
||||
struct Match {
|
||||
}
|
||||
|
||||
init(_ pattern: String) throws where Output == AnyRegexOutput { }
|
||||
|
||||
func firstMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
func prefixMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
func wholeMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
|
||||
typealias RegexOutput = Output
|
||||
}
|
||||
|
||||
extension String {
|
||||
init(contentsOf: URL) {
|
||||
let data = ""
|
||||
self.init(data)
|
||||
}
|
||||
}
|
||||
|
||||
// --- tests ---
|
||||
//
|
||||
// the focus for these tests is different vulnerable and non-vulnerable regexp strings.
|
||||
|
||||
func myRegexpVariantsTests(myUrl: URL) throws {
|
||||
let tainted = String(contentsOf: myUrl) // tainted
|
||||
|
||||
// basic cases:
|
||||
// attack string: "a" x lots + "!"
|
||||
|
||||
_ = try Regex(".*").firstMatch(in: tainted) // $ regex=.* input=tainted
|
||||
|
||||
_ = try Regex("a*b").firstMatch(in: tainted) // $ regex=a*b input=tainted
|
||||
_ = try Regex("(a*)b").firstMatch(in: tainted) // $ regex=(a*)b input=tainted
|
||||
_ = try Regex("(a)*b").firstMatch(in: tainted) // $ regex=(a)*b input=tainted
|
||||
_ = try Regex("(a*)*b").firstMatch(in: tainted) // $ regex=(a*)*b input=tainted redos-vulnerable=
|
||||
_ = try Regex("((a*)*b)").firstMatch(in: tainted) // $ regex=((a*)*b) input=tainted redos-vulnerable=
|
||||
|
||||
_ = try Regex("(a|aa?)b").firstMatch(in: tainted) // $ regex=(a|aa?)b input=tainted
|
||||
_ = try Regex("(a|aa?)*b").firstMatch(in: tainted) // $ regex=(a|aa?)*b input=tainted redos-vulnerable=
|
||||
|
||||
// from the qhelp:
|
||||
// attack string: "_" x lots + "!"
|
||||
|
||||
_ = try Regex("^_(__|.)+_$").firstMatch(in: tainted) // $ regex=^_(__|.)+_$ input=tainted redos-vulnerable=
|
||||
_ = try Regex("^_(__|[^_])+_$").firstMatch(in: tainted) // $ regex=^_(__|[^_])+_$ input=tainted
|
||||
|
||||
// real world cases:
|
||||
|
||||
// Adapted from marked (https://github.com/markedjs/marked), which is licensed
|
||||
// under the MIT license; see file licenses/marked-LICENSE.
|
||||
// GOOD
|
||||
_ = try Regex(#"^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)"#).firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
// BAD
|
||||
// attack string: "_" + "__".repeat(100)
|
||||
_ = try Regex(#"^\b_((?:__|[\s\S])+?)_\b|^\*((?:\*\*|[\s\S])+?)\*(?!\*)"#).wholeMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
// Adapted from marked (https://github.com/markedjs/marked), which is licensed
|
||||
// under the MIT license; see file licenses/marked-LICENSE.
|
||||
_ = try Regex(#"^\b_((?:__|[^_])+?)_\b|^\*((?:\*\*|[^*])+?)\*(?!\*)"#).firstMatch(in: tainted)
|
||||
|
||||
// GOOD - there is no witness in the end that could cause the regexp to not match
|
||||
// Adapted from brace-expansion (https://github.com/juliangruber/brace-expansion),
|
||||
// which is licensed under the MIT license; see file licenses/brace-expansion-LICENSE.
|
||||
_ = try Regex("(.*,)+.+").firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: " '" + "\\\\".repeat(100)
|
||||
// Adapted from CodeMirror (https://github.com/codemirror/codemirror),
|
||||
// which is licensed under the MIT license; see file licenses/CodeMirror-LICENSE.
|
||||
_ = try Regex(#"^(?:\s+(?:"(?:[^"\\]|\\\\|\\.)+"|'(?:[^'\\]|\\\\|\\.)+'|\((?:[^)\\]|\\\\|\\.)+\)))?"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
// Adapted from jest (https://github.com/facebook/jest), which is licensed
|
||||
// under the MIT license; see file licenses/jest-LICENSE.
|
||||
_ = try Regex(#"^ *(\S.*\|.*)\n *([-:]+ *\|[-| :]*)\n((?:.*\|.*(?:\n|$))*)\n*"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "/" + "\\/a".repeat(100)
|
||||
// Adapted from ANodeBlog (https://github.com/gefangshuai/ANodeBlog),
|
||||
// which is licensed under the Apache License 2.0; see file licenses/ANodeBlog-LICENSE.
|
||||
_ = try Regex(#"\/(?![ *])(\\\/|.)*?\/[gim]*(?=\W|$)"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "##".repeat(100) + "\na"
|
||||
// Adapted from CodeMirror (https://github.com/codemirror/codemirror),
|
||||
// which is licensed under the MIT license; see file licenses/CodeMirror-LICENSE.
|
||||
_ = try Regex(#"^([\s\[\{\(]|#.*)*$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" + "[]".repeat(100) + ".b\n"
|
||||
// Adapted from Knockout (https://github.com/knockout/knockout), which is
|
||||
// licensed under the MIT license; see file licenses/knockout-LICENSE
|
||||
_ = try Regex(#"^[\_$a-z][\_$a-z0-9]*(\[.*?\])*(\.[\_$a-z][\_$a-z0-9]*(\[.*?\])*)*$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "[" + "][".repeat(100) + "]!"
|
||||
// Adapted from Prototype.js (https://github.com/prototypejs/prototype), which
|
||||
// is licensed under the MIT license; see file licenses/Prototype.js-LICENSE.
|
||||
_ = try Regex(#"(([\w#:.~>+()\s-]+|\*|\[.*?\])+)\s*(,|$)"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "'" + "\\a".repeat(100) + '"'
|
||||
// Adapted from Prism (https://github.com/PrismJS/prism), which is licensed
|
||||
// under the MIT license; see file licenses/Prism-LICENSE.
|
||||
_ = try Regex(#"("|')(\\?.)*?\1"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// more cases:
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(\r\n|\r|\n)+"#).firstMatch(in: tainted)
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("(a|.)*").firstMatch(in: tainted)
|
||||
|
||||
// BAD - testing the NFA
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("^([a-z]+)+$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex("^([a-z]*)*$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"^([a-zA-Z0-9])(([\\.-]|[_]+)?([a-zA-Z0-9]+))*(@){1}[a-z0-9]+[.]{1}(([a-z]{2,3})|([a-z]{2,3}[.]{1}[a-z]{2,3}))$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex("^(([a-z])+.)+[A-Z]([a-z])+$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex("(b|a?b)*c").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(.|\n)*!"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "\n".repeat(100) + "."
|
||||
_ = try Regex(#"(?s)(.|\n)*!"#).firstMatch(in: tainted) // $ hasParseFailure MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"([\w.]+)*"#).firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex(#"([\w.]+)*"#).wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex(#"(([\s\S]|[^a])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - there is no witness in the end that could cause the regexp to not match
|
||||
_ = try Regex(#"([^"']+)*"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex(#"((.|[^a])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"((a|[^a])*)""#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex(#"((b|[^a])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "G" x lots + "!"
|
||||
_ = try Regex(#"((G|[^a])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"(([0-9]|[^a])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD [NOT DETECTED]
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"(?:=(?:([!#\$%&'\*\+\-\.\^_`\|~0-9A-Za-z]+)|"((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"])*)"))?"#).firstMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD [NOT DETECTED]
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#""((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"])*)""#).firstMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#""((?:\\[\x00-\x7f]|[^\x00-\x08\x0a-\x1f\x7f"\\])*)""#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "d" x lots + "!"
|
||||
_ = try Regex(#"(([a-z]|[d-h])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "_" x lots
|
||||
_ = try Regex(#"(([^a-z]|[^0-9])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"((\d|[0-9])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"((\s|\s)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "G" x lots + "!"
|
||||
_ = try Regex(#"((\w|G)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"((\s|\d)*)""#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "5" x lots + "!"
|
||||
_ = try Regex(#"((\d|\d)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"((\d|\w)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "5" x lots + "!"
|
||||
_ = try Regex(#"((\d|5)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\u{000C}" x lots + "!",
|
||||
_ = try Regex(#"((\s|[\f])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"((\s|[\v]|\\v)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\u{000C}" x lots + "!",
|
||||
_ = try Regex(#"((\f|[\f])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"((\W|\D)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex(#"((\S|\w)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex(#"((\S|[\w])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "1s" x lots + "!"
|
||||
_ = try Regex(#"((1s|[\da-z])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"((0|[\d])*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"(([\d]+)*)""#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - there is no witness in the end that could cause the regexp to not match
|
||||
_ = try Regex(#"(\d+(X\d+)?)+"#).firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"(\d+(X\d+)?)+"#).wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD - there is no witness in the end that could cause the regexp to not match
|
||||
_ = try Regex("([0-9]+(X[0-9]*)?)*").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex("([0-9]+(X[0-9]*)?)*").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("^([^>]+)*(>|$)").firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "##".repeat(100) + "\na"
|
||||
_ = try Regex("^([^>a]+)*(>|$)").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"(\n\s*)+$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"^(?:\s+|#.*|\(\?#[^)]*\))*(?:[?*+]|\{\d+(?:,\d*)?})"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"\{\[\s*([a-zA-Z]+)\(([a-zA-Z]+)\)((\s*([a-zA-Z]+)\: ?([ a-zA-Z{}]+),?)+)*\s*\]\}"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a+|b+|c+)*c").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(((a+a?)*)+b+)").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a+)+bbbb").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("(a+)+aaaaa*a+").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a+)+aaaaa*a+").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a+)+aaaaa$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(\n+)+\n\n"#).firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"(\n+)+\n\n"#).wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "\n" x lots + "."
|
||||
_ = try Regex(#"(\n+)+\n\n$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: " " x lots + "X"
|
||||
_ = try Regex("([^X]+)*$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex("(([^X]b)+)*$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("(([^X]b)+)*($|[^X]b)").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex("(([^X]b)+)*($|[^X]b)").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "b" x lots + "!"
|
||||
_ = try Regex("(([^X]b)+)*($|[^X]c)").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("((ab)+)*ababab").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)+)*ababab").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("((ab)+)*abab(ab)*(ab)+").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)+)*abab(ab)*(ab)+").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("((ab)+)*").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)+)*").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)+)*$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("((ab)+)*[a1][b1][a2][b2][a3][b3]").firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)+)*[a1][b1][a2][b2][a3][b3]").wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"([\n\s]+)*(.)"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - any witness passes through the accept state.
|
||||
_ = try Regex("(A*A*X)*").firstMatch(in: tainted)
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"([^\\\]]+)*"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
_ = try Regex(#"(\w*foobarbaz\w*foobarbaz\w*foobarbaz\w*foobarbaz\s*foobarbaz\d*foobarbaz\w*)+-"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
// (these regexs explore a query performance issue we had at one point)
|
||||
_ = try Regex(#"(\w*foobarfoobarfoobarfoobarfoobarfoobarfoobarfoobar)+"#).firstMatch(in: tainted)
|
||||
_ = try Regex(#"(\w*foobarfoobarfoobar)+"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD (but cannot currently construct a prefix)
|
||||
// attack string: "aa" + "b" x lots + "!"
|
||||
_ = try Regex("a{2,3}(b+)+X").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD (and a good prefix test)
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"^<(\w+)((?:\s+\w+(?:\s*=\s*(?:(?:"[^"]*")|(?:'[^']*')|[^>\s]+))?)*)\s*(\/?)>"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(a+)*[\s\S][\s\S][\s\S]?"#).firstMatch(in: tainted)
|
||||
|
||||
// GOOD - but we fail to see that repeating the attack string ends in the "accept any" state (due to not parsing the range `[\s\S]{2,3}`).
|
||||
_ = try Regex(#"(a+)*[\s\S]{2,3}"#).firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
|
||||
// GOOD - but we spuriously conclude that a rejecting suffix exists (due to not parsing the range `[\s\S]{2,}` when constructing the NFA).
|
||||
_ = try Regex(#"(a+)*([\s\S]{2,}|X)$"#).firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(a+)*([\s\S]*|X)$"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex(#"((a+)*$|[\s\S]+)"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - but still flagged. The only change compared to the above is the order of alternatives, which we don't model.
|
||||
_ = try Regex(#"([\s\S]+|(a+)*$)"#).firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("((;|^)a+)+$").firstMatch(in: tainted)
|
||||
|
||||
// BAD (a good prefix test)
|
||||
// attack string: "00000000000000" + "e" x lots + "!"
|
||||
_ = try Regex("(^|;)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(0|1)(e+)+f").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// atack string: "ab" + "c" x lots + "!"
|
||||
_ = try Regex("^ab(c+)+$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"(\d(\s+)*){20}"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - but we spuriously conclude that a rejecting suffix exists.
|
||||
_ = try Regex(#"(([^/]|X)+)(\/[\s\S]*)*$"#).firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
|
||||
// GOOD - but we spuriously conclude that a rejecting suffix exists.
|
||||
_ = try Regex("^((x([^Y]+)?)*(Y|$))").firstMatch(in: tainted) // $ SPURIOUS: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"foo([\w-]*)+bar"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("((ab)*)+c").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a?a?)*b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("(a?)*b").firstMatch(in: tainted)
|
||||
|
||||
// BAD - but not detected
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex("(c?a?)*b").firstMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(?:a|a?)+b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD - but not detected.
|
||||
// attack string: "ab" x lots + "!"
|
||||
_ = try Regex("(a?b?)*$").firstMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex("PRE(([a-c]|[c-d])T(e?e?e?e?|X))+(cTcT|cTXcTX$)").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex(#"^((a)+\w)+$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "bbbbbbbbbb." x lots + "!"
|
||||
_ = try Regex("^(b+.)+$").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD - all 4 bad combinations of nested * and +
|
||||
// attack string: "a" x lots + "!"
|
||||
_ = try Regex("(a*)*b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex("(a+)*b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex("(a*)+b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex("(a+)+b").firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex("(a|b)+").firstMatch(in: tainted)
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"(?:[\s;,"'<>(){}|\[\]@=+*]|:(?![/\\]))+"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD?
|
||||
// (no confirmed attack string)
|
||||
_ = try Regex(#"^((?:a{|-)|\w\{)+X$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"^((?:a{0|-)|\w\{\d)+X$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"^((?:a{0,|-)|\w\{\d,)+X$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"^((?:a{0,2|-)|\w\{\d,\d)+X$"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"^((?:a{0,2}|-)|\w\{\d,\d\})+X$"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "a" x lots
|
||||
_ = try Regex(#"X(\u0061|a)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\u0061|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "a" x lots
|
||||
_ = try Regex(#"X(\U00000061|a)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\U00000061|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "a" x lots
|
||||
_ = try Regex(#"X(\x61|a)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\x61|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "a" x lots
|
||||
_ = try Regex(#"X(\x{061}|a)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\x{061}|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "7" x lots
|
||||
_ = try Regex(#"X(\p{Digit}|7)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\p{Digit}|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "b" x lots
|
||||
_ = try Regex(#"X(\P{Digit}|b)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\P{Digit}|7)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD
|
||||
// attack string: "X" + "7" x lots
|
||||
_ = try Regex(#"X(\p{IsDigit}|7)*Y"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\p{IsDigit}|b)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// BAD - but not detected
|
||||
// attack string: "X" + "a" x lots
|
||||
_ = try Regex(#"X(\p{Alpha}|a)*Y"#).firstMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"X(\p{Alpha}|7)+Y"#).firstMatch(in: tainted)
|
||||
|
||||
// GOOD
|
||||
_ = try Regex(#"("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)"#).firstMatch(in: tainted)
|
||||
// BAD
|
||||
// attack string: "##" x lots + "\na"
|
||||
_ = try Regex(#"("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)"#).wholeMatch(in: tainted) // $ MISSING: redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "/" + "\\/a" x lots
|
||||
_ = try Regex(#"/("[^"]*?"|[^"\s]+)+(?=\s*|\s*$)X"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"/("[^"]*?"|[^"\s]+)+(?=X)"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// BAD
|
||||
// attack string: "0" x lots + "!"
|
||||
_ = try Regex(#"\A(\d|0)*x"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"(\d|0)*\Z"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
_ = try Regex(#"\b(\d|0)*x"#).firstMatch(in: tainted) // $ redos-vulnerable=
|
||||
|
||||
// GOOD - possessive quantifiers don't backtrack
|
||||
_ = try Regex("(a*+)*+b").firstMatch(in: tainted) // $ hasParseFailure
|
||||
_ = try Regex("(a*)*+b").firstMatch(in: tainted) // $ hasParseFailure
|
||||
_ = try Regex("(a*+)*b").firstMatch(in: tainted) // $ hasParseFailure
|
||||
|
||||
// BAD - but not detected due to the way possessive quantifiers are approximated
|
||||
// attack string: "aab" x lots + "!"
|
||||
_ = try Regex("((aa|a*+)b)*c").firstMatch(in: tainted) // $ hasParseFailure MISSING: redos-vulnerable=
|
||||
}
|
||||
2
swift/ql/test/library-tests/regex/regex.expected
Normal file
2
swift/ql/test/library-tests/regex/regex.expected
Normal file
@@ -0,0 +1,2 @@
|
||||
failures
|
||||
testFailures
|
||||
52
swift/ql/test/library-tests/regex/regex.ql
Normal file
52
swift/ql/test/library-tests/regex/regex.ql
Normal file
@@ -0,0 +1,52 @@
|
||||
import swift
|
||||
import codeql.swift.regex.Regex
|
||||
private import codeql.swift.regex.internal.ParseRegex
|
||||
private import codeql.swift.regex.RegexTreeView::RegexTreeView as TreeView
|
||||
import codeql.regex.nfa.ExponentialBackTracking::Make<TreeView>
|
||||
import TestUtilities.InlineExpectationsTest
|
||||
|
||||
bindingset[s]
|
||||
string quote(string s) { if s.matches("% %") then result = "\"" + s + "\"" else result = s }
|
||||
|
||||
module RegexTest implements TestSig {
|
||||
string getARelevantTag() { result = ["regex", "input", "redos-vulnerable", "hasParseFailure"] }
|
||||
|
||||
predicate hasActualResult(Location location, string element, string tag, string value) {
|
||||
exists(TreeView::RegExpTerm t |
|
||||
hasReDoSResult(t, _, _, _) and
|
||||
location = t.getLocation() and
|
||||
element = t.toString() and
|
||||
tag = "redos-vulnerable" and
|
||||
value = ""
|
||||
)
|
||||
or
|
||||
exists(RegexEval eval, RegExp regex |
|
||||
eval.getARegex() = regex and
|
||||
regex.failedToParse(_) and
|
||||
location = eval.getLocation() and
|
||||
element = eval.toString() and
|
||||
tag = "hasParseFailure" and
|
||||
value = ""
|
||||
)
|
||||
}
|
||||
|
||||
predicate hasOptionalResult(Location location, string element, string tag, string value) {
|
||||
exists(RegexEval eval, Expr input |
|
||||
eval.getStringInput() = input and
|
||||
location = input.getLocation() and
|
||||
element = input.toString() and
|
||||
tag = "input" and
|
||||
value = quote(input.toString())
|
||||
)
|
||||
or
|
||||
exists(RegexEval eval, RegExp regex |
|
||||
eval.getARegex() = regex and
|
||||
location = eval.getLocation() and
|
||||
element = eval.toString() and
|
||||
tag = "regex" and
|
||||
value = quote(regex.toString().replaceAll("\n", "NEWLINE"))
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
import MakeTest<RegexTest>
|
||||
199
swift/ql/test/library-tests/regex/regex.swift
Normal file
199
swift/ql/test/library-tests/regex/regex.swift
Normal file
@@ -0,0 +1,199 @@
|
||||
|
||||
// --- stubs ---
|
||||
|
||||
struct Locale {
|
||||
}
|
||||
|
||||
struct AnyRegexOutput {
|
||||
}
|
||||
|
||||
protocol RegexComponent<RegexOutput> {
|
||||
associatedtype RegexOutput
|
||||
}
|
||||
|
||||
struct Regex<Output> : RegexComponent {
|
||||
struct Match {
|
||||
}
|
||||
|
||||
init(_ pattern: String) throws where Output == AnyRegexOutput { }
|
||||
|
||||
func firstMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
func prefixMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
func wholeMatch(in string: String) throws -> Regex<Output>.Match? { return nil}
|
||||
|
||||
typealias RegexOutput = Output
|
||||
}
|
||||
|
||||
extension RangeReplaceableCollection {
|
||||
mutating func replace<Replacement>(_ regex: some RegexComponent, with replacement: Replacement, maxReplacements: Int = .max) where Replacement : Collection, Replacement.Element == Character { }
|
||||
func replacing<Replacement>(_ regex: some RegexComponent, with replacement: Replacement, maxReplacements: Int = .max) -> Self where Replacement: Collection, Replacement.Element == Character { return self }
|
||||
mutating func trimPrefix(_ regex: some RegexComponent) { }
|
||||
}
|
||||
|
||||
extension StringProtocol {
|
||||
func range<T>(of aString: T, options mask:String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil, locale: Locale? = nil) -> Range<Self.Index>? where T : StringProtocol { return nil }
|
||||
func replacingOccurrences<Target, Replacement>(of target: Target, with replacement: Replacement, options: String.CompareOptions = [], range searchRange: Range<Self.Index>? = nil) -> String where Target : StringProtocol, Replacement : StringProtocol { return "" }
|
||||
}
|
||||
|
||||
extension String : RegexComponent {
|
||||
typealias CompareOptions = NSString.CompareOptions
|
||||
typealias Output = Substring
|
||||
typealias RegexOutput = String.Output
|
||||
}
|
||||
|
||||
class NSObject {
|
||||
}
|
||||
|
||||
class NSString : NSObject {
|
||||
struct CompareOptions : OptionSet {
|
||||
var rawValue: UInt
|
||||
|
||||
static var regularExpression: NSString.CompareOptions { get { return CompareOptions(rawValue: 1) } }
|
||||
}
|
||||
|
||||
convenience init(string aString: String) { self.init() }
|
||||
|
||||
func range(of searchString: String, options mask: NSString.CompareOptions = []) -> NSRange { return NSRange(location: 0, length: 0) }
|
||||
func replacingOccurrences(of target: String, with replacement: String, options: NSString.CompareOptions = [], range searchRange: NSRange) -> String { return "" }
|
||||
|
||||
var length: Int { get { return 0 } }
|
||||
}
|
||||
|
||||
class NSMutableString : NSString {
|
||||
}
|
||||
|
||||
struct _NSRange {
|
||||
init(location: Int, length: Int) { }
|
||||
}
|
||||
|
||||
typealias NSRange = _NSRange
|
||||
|
||||
func NSMakeRange(_ loc: Int, _ len: Int) -> NSRange { return NSRange(location: loc, length: len) }
|
||||
|
||||
class NSTextCheckingResult : NSObject {
|
||||
}
|
||||
|
||||
class NSRegularExpression : NSObject {
|
||||
struct Options : OptionSet {
|
||||
var rawValue: UInt
|
||||
}
|
||||
|
||||
struct MatchingOptions : OptionSet {
|
||||
var rawValue: UInt
|
||||
}
|
||||
|
||||
init(pattern: String, options: NSRegularExpression.Options = []) throws { }
|
||||
|
||||
// some types have been simplified a little here
|
||||
func numberOfMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> Int { return 0 }
|
||||
func enumerateMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, using block: (Int, Int, Int) -> Void) { }
|
||||
func matches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> [NSTextCheckingResult] { return [] }
|
||||
func firstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSTextCheckingResult? { return nil }
|
||||
func rangeOfFirstMatch(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange) -> NSRange { return NSRange(location: 0, length: 0) }
|
||||
func replaceMatches(in string: NSMutableString, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> Int { return 0 }
|
||||
func stringByReplacingMatches(in string: String, options: NSRegularExpression.MatchingOptions = [], range: NSRange, withTemplate templ: String) -> String { return "" }
|
||||
}
|
||||
|
||||
// --- tests ---
|
||||
//
|
||||
// the focus for these tests is different ways of evaluating regexps.
|
||||
|
||||
func myRegexpMethodsTests(b: Bool, str_unknown: String) throws {
|
||||
let input = "abcdef"
|
||||
let regex = try Regex(".*")
|
||||
|
||||
// --- Regex ---
|
||||
|
||||
_ = try regex.firstMatch(in: input) // $ regex=.* input=input
|
||||
_ = try regex.prefixMatch(in: input) // $ regex=.* input=input
|
||||
_ = try regex.wholeMatch(in: input) // $ regex=.* input=input
|
||||
|
||||
// --- RangeReplaceableCollection ---
|
||||
|
||||
var inputVar = input
|
||||
inputVar.replace(regex, with: "") // $ regex=.* input=&...
|
||||
_ = input.replacing(regex, with: "") // $ regex=.* input=input
|
||||
inputVar.trimPrefix(regex) // $ regex=.* input=&...
|
||||
|
||||
// --- StringProtocol ---
|
||||
|
||||
_ = input.range(of: ".*", options: .regularExpression, range: nil, locale: nil) // $ MISSING: regex=.* input=input
|
||||
_ = input.replacingOccurrences(of: ".*", with: "", options: .regularExpression) // $ MISSING: regex=.* input=input
|
||||
|
||||
// --- NSRegularExpression ---
|
||||
|
||||
let nsregex = try NSRegularExpression(pattern: ".*")
|
||||
_ = nsregex.numberOfMatches(in: input, options: [], range: NSRange(location: 0, length: input.utf16.count)) // $ regex=.* input=input
|
||||
nsregex.enumerateMatches(in: input, range: NSMakeRange(0, input.utf16.count), using: {a, b, c in } ) // $ regex=.* input=input
|
||||
_ = nsregex.matches(in: input, range: NSMakeRange(0, input.utf16.count)) // $ regex=.* input=input
|
||||
_ = nsregex.firstMatch(in: input, range: NSMakeRange(0, input.utf16.count)) // $ regex=.* input=input
|
||||
_ = nsregex.rangeOfFirstMatch(in: input, range: NSMakeRange(0, input.utf16.count)) // $ regex=.* input=input
|
||||
_ = nsregex.replaceMatches(in: NSMutableString(string: input), range: NSMakeRange(0, input.utf16.count), withTemplate: "") // $ regex=.* input="call to NSString.init(string:)"
|
||||
_ = nsregex.stringByReplacingMatches(in: input, range: NSMakeRange(0, input.utf16.count), withTemplate: "") // $ regex=.* input=input
|
||||
|
||||
// --- NSString ---
|
||||
|
||||
let inputNS = NSString(string: "abcdef")
|
||||
_ = inputNS.range(of: "*", options: .regularExpression) // $ MISSING: regex=.* input=inputNS
|
||||
_ = inputNS.replacingOccurrences(of: ".*", with: "", options: .regularExpression, range: NSMakeRange(0, inputNS.length)) // $ MISSING: regex=.* input=inputNS
|
||||
|
||||
// --- flow ---
|
||||
|
||||
let either_regex = try Regex(b ? ".*" : ".+")
|
||||
_ = try either_regex.firstMatch(in: input) // $ regex=.* regex=.+ input=input
|
||||
|
||||
let base_str = "a"
|
||||
let appended_regex = try Regex(base_str + "b")
|
||||
_ = try appended_regex.firstMatch(in: input) // $ input=input MISSING: regex=ab
|
||||
|
||||
let multiple_evaluated_regex = try Regex(#"([\w.]+)*"#)
|
||||
try _ = multiple_evaluated_regex.firstMatch(in: input) // $ input=input regex=([\w.]+)*
|
||||
try _ = multiple_evaluated_regex.prefixMatch(in: input) // $ input=input regex=([\w.]+)*
|
||||
try _ = multiple_evaluated_regex.wholeMatch(in: input) // $ input=input regex=([\w.]+)* MISSING: redos-vulnerable=
|
||||
|
||||
// --- escape sequences ---
|
||||
|
||||
_ = try Regex("\n").firstMatch(in: input) // $ regex=NEWLINE input=input
|
||||
_ = try Regex("\\n").firstMatch(in: input) // $ regex=\n input=input
|
||||
_ = try Regex(#"\n"#).firstMatch(in: input) // $ regex=\n input=input
|
||||
|
||||
// --- interpolated values ---
|
||||
|
||||
let str_constant = "aa"
|
||||
_ = try Regex("\(str_constant))|bb").firstMatch(in: input) // $ input=input MISSING: regex=aa|bb
|
||||
_ = try Regex("\(str_unknown))|bb").firstMatch(in: input) // $ input=input
|
||||
|
||||
// --- multi-line ---
|
||||
|
||||
_ = try Regex("""
|
||||
aa|bb
|
||||
""").firstMatch(in: input) // $ input=input regex=aa|bb
|
||||
|
||||
_ = try Regex("""
|
||||
aa|
|
||||
bb
|
||||
""").firstMatch(in: input) // $ input=input regex=aa|NEWLINEbb
|
||||
|
||||
// --- exploring parser correctness ---
|
||||
|
||||
// ranges
|
||||
_ = try Regex("[a-z]").firstMatch(in: input) // $ input=input regex=[a-z]
|
||||
_ = try Regex("[a-zA-Z]").firstMatch(in: input) // $ input=input regex=[a-zA-Z]
|
||||
|
||||
// character classes
|
||||
_ = try Regex("[a-]").firstMatch(in: input) // $ input=input regex=[a-]
|
||||
_ = try Regex("[-a]").firstMatch(in: input) // $ input=input regex=[-a]
|
||||
_ = try Regex("[-]").firstMatch(in: input) // $ input=input regex=[-]
|
||||
_ = try Regex("[*]").firstMatch(in: input) // $ input=input regex=[*]
|
||||
_ = try Regex("[^a]").firstMatch(in: input) // $ input=input regex=[^a]
|
||||
_ = try Regex("[a^]").firstMatch(in: input) // $ input=input regex=[a^]
|
||||
_ = try Regex(#"[\\]"#).firstMatch(in: input) // $ input=input regex=[\\]
|
||||
_ = try Regex(#"[\\\]]"#).firstMatch(in: input) // $ input=input regex=[\\\]]
|
||||
_ = try Regex("[:]").firstMatch(in: input) // $ input=input regex=[:]
|
||||
_ = try Regex("[:digit:]").firstMatch(in: input) // $ input=input regex=[:digit:] SPURIOUS: $hasParseFailure
|
||||
_ = try Regex("[:alnum:]").firstMatch(in: input) // $ input=input regex=[:alnum:] SPURIOUS: $hasParseFailure
|
||||
|
||||
// invalid (Swift doesn't like these regexs)
|
||||
_ = try Regex("[]a]").firstMatch(in: input) // this is valid in other regex implementations, and is likely harmless to accept
|
||||
_ = try Regex("[:aaaaa:]").firstMatch(in: input) // $ hasParseFailure
|
||||
}
|
||||
@@ -0,0 +1,72 @@
|
||||
// these tests require Swift 5.7 or so, and currently require the
|
||||
// `-enable-bare-slash-regex` compiler flag.
|
||||
|
||||
// --- stubs ---
|
||||
|
||||
struct AnyRegexOutput {
|
||||
}
|
||||
|
||||
protocol RegexComponent<RegexOutput> {
|
||||
associatedtype RegexOutput
|
||||
}
|
||||
|
||||
struct Regex<Output> : RegexComponent {
|
||||
struct Match {
|
||||
}
|
||||
|
||||
init(_ pattern: String) throws where Output == AnyRegexOutput { }
|
||||
|
||||
func firstMatch(in string: String) throws -> Regex<Output>.Match? { return nil }
|
||||
|
||||
typealias RegexOutput = Output
|
||||
}
|
||||
|
||||
extension BidirectionalCollection {
|
||||
func contains(_ regex: some RegexComponent) -> Bool { return false }
|
||||
func firstMatch<Output>(of r: some RegexComponent<Output>) -> Regex<Output>.Match? { return nil } // slightly simplified
|
||||
func firstMatch<Output>(of r: some RegexComponent) -> Regex<Output>.Match? where SubSequence == Substring { return nil }
|
||||
func firstRange(of regex: some RegexComponent) -> Range<Self.Index>? { return nil }
|
||||
func matches<Output>(of r: some RegexComponent<Output>) -> [Regex<Output>.Match] { return [] } // slightly simplified
|
||||
func prefixMatch<R>(of regex: R) -> Regex<R.RegexOutput>.Match? where R: RegexComponent { return nil }
|
||||
func ranges(of regex: some RegexComponent) -> [Range<Self.Index>] { return [] }
|
||||
func starts(with regex: some RegexComponent) -> Bool { return false }
|
||||
func trimmingPrefix(_ regex: some RegexComponent) -> Self.SubSequence { return self.suffix(0) }
|
||||
func split(separator: some RegexComponent, maxSplits: Int = .max, omittingEmptySubsequences: Bool = true) -> [Self.SubSequence] { return [] }
|
||||
}
|
||||
|
||||
extension String : RegexComponent {
|
||||
typealias Output = Substring
|
||||
typealias RegexOutput = String.Output
|
||||
}
|
||||
|
||||
// --- tests ---
|
||||
|
||||
func myRegexpMethodsTests() throws {
|
||||
let input = "abcdef"
|
||||
let regex = try Regex(".*")
|
||||
|
||||
// --- BidirectionalCollection ---
|
||||
|
||||
_ = input.contains(regex)
|
||||
_ = input.firstMatch(of: regex)
|
||||
_ = input.firstRange(of: regex)
|
||||
_ = input.matches(of: regex)
|
||||
_ = input.prefixMatch(of: regex)
|
||||
_ = input.ranges(of: regex)
|
||||
_ = input.starts(with: regex)
|
||||
_ = input.trimmingPrefix(regex)
|
||||
_ = input.split(separator: regex)
|
||||
|
||||
// --- compile time regexps ---
|
||||
|
||||
let regex2 = /a*b*/
|
||||
_ = try regex2.firstMatch(in: input)
|
||||
|
||||
let regex3 = /(?<varname>a*)*b/
|
||||
_ = try regex3.firstMatch(in: input)
|
||||
|
||||
let regex4 = #/a*b*/#
|
||||
_ = try regex4.firstMatch(in: input)
|
||||
|
||||
_ = input.contains(/a*b*/)
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "{}"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright {yyyy} {name of copyright owner}
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (C) 2017 by Marijn Haverbeke <marijnh@gmail.com> and others
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT LICENSE
|
||||
|
||||
Copyright (c) 2012 Lea Verou
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,16 @@
|
||||
Copyright (c) 2005-2010 Sam Stephenson
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,21 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2013 Julian Gruber <julian@juliangruber.com>
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,23 @@
|
||||
MIT License
|
||||
|
||||
For Jest software
|
||||
|
||||
Copyright (c) 2014-present, Facebook, Inc.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,22 @@
|
||||
The MIT License (MIT) - http://www.opensource.org/licenses/mit-license.php
|
||||
|
||||
Copyright (c) Steven Sanderson, the Knockout.js team, and other contributors
|
||||
http://knockoutjs.com/
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
@@ -0,0 +1,43 @@
|
||||
# License information
|
||||
|
||||
## Contribution License Agreement
|
||||
|
||||
If you contribute code to this project, you are implicitly allowing your code
|
||||
to be distributed under the MIT license. You are also implicitly verifying that
|
||||
all code is your original work. `</legalese>`
|
||||
|
||||
## Marked
|
||||
|
||||
Copyright (c) 2011-2018, Christopher Jeffrey (https://github.com/chjj/)
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
## Markdown
|
||||
|
||||
Copyright © 2004, John Gruber
|
||||
http://daringfireball.net/
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
|
||||
* Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
|
||||
* Neither the name “Markdown” nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
|
||||
|
||||
This software is provided by the copyright holders and contributors “as is” and any express or implied warranties, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose are disclaimed. In no event shall the copyright owner or contributors be liable for any direct, indirect, incidental, special, exemplary, or consequential damages (including, but not limited to, procurement of substitute goods or services; loss of use, data, or profits; or business interruption) however caused and on any theory of liability, whether in contract, strict liability, or tort (including negligence or otherwise) arising in any way out of the use of this software, even if advised of the possibility of such damage.
|
||||
148
swift/ql/test/library-tests/regex/test_the_tests.swift.disabled
Normal file
148
swift/ql/test/library-tests/regex/test_the_tests.swift.disabled
Normal file
@@ -0,0 +1,148 @@
|
||||
// This program tests the regular expressions from the tests to figure out which ones are really
|
||||
// vulnerable to various attack strings with the Swift `Regex` implementation. We also confirm
|
||||
// all really are valid Swift regular expressions.
|
||||
//
|
||||
// The program works by searching the test source file (or part of it) for regular expressions in
|
||||
// the form `Regex("...")` or `Regex(#"..."#)`. A drawback of this approach is that it doesn't
|
||||
// process escape characters in the way Swift does, so it's best not to use them in non-trivial
|
||||
// test cases (use Swift #""# strings to avoid needing escape sequences).
|
||||
|
||||
import Foundation
|
||||
|
||||
class TestCase: Thread {
|
||||
var regex: Regex<AnyRegexOutput>
|
||||
var regexStr: String
|
||||
var targetString: String
|
||||
var wholeMatch: Bool
|
||||
var matched: Bool
|
||||
var done: Bool
|
||||
|
||||
init(regex: Regex<AnyRegexOutput>, regexStr: String, targetString: String, wholeMatch: Bool) {
|
||||
self.regex = regex
|
||||
self.regexStr = regexStr
|
||||
self.targetString = targetString
|
||||
self.wholeMatch = wholeMatch
|
||||
self.matched = false
|
||||
self.done = false
|
||||
}
|
||||
|
||||
override func main() {
|
||||
// run the regex on the target string
|
||||
do
|
||||
{
|
||||
if (wholeMatch) {
|
||||
if let _ = try regex.wholeMatch(in: targetString) {
|
||||
matched = true
|
||||
//print(" wholeMatch \(regexStr) on \(targetString)")
|
||||
}
|
||||
} else {
|
||||
if let _ = try regex.firstMatch(in: targetString) {
|
||||
matched = true
|
||||
//print(" firstMatch \(regexStr) on \(targetString)")
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
print("WEIRD FAILURE")
|
||||
}
|
||||
done = true
|
||||
}
|
||||
}
|
||||
|
||||
let attackStrings = [
|
||||
String(repeating: "a", count: 100) + "!",
|
||||
String(repeating: "b", count: 100) + "!",
|
||||
String(repeating: "d", count: 100) + "!",
|
||||
String(repeating: "G", count: 100) + "!",
|
||||
String(repeating: "0", count: 100) + "!",
|
||||
String(repeating: "5", count: 100) + "!",
|
||||
String(repeating: "ab", count: 100) + "!",
|
||||
String(repeating: "aab", count: 100) + "!",
|
||||
String(repeating: "1s", count: 100) + "!",
|
||||
String(repeating: "\n", count: 100) + ".",
|
||||
|
||||
"_" + String(repeating: "__", count: 100) + "!",
|
||||
" '" + String(repeating: #"\\\\"#, count: 100),
|
||||
"/" + String(repeating: "\\/a", count:100),
|
||||
"/" + String(repeating: "\\\\/a", count:100),
|
||||
String(repeating: "##", count: 100) + "\na",
|
||||
"a" + String(repeating: "[]", count: 100) + ".b\n",
|
||||
"[" + String(repeating: "][", count: 100) + "]!",
|
||||
"'" + String(repeating: "\\a", count: 100) + "\"",
|
||||
"'" + String(repeating: "\\\\a", count: 100) + "\"",
|
||||
String(repeating: "\u{000C}", count: 100) + "!",
|
||||
"00000000000000" + String(repeating: "e", count: 100) + "!",
|
||||
"aa" + String(repeating: "b", count: 100) + "!",
|
||||
"ab" + String(repeating: "c", count: 100) + "!",
|
||||
String(repeating: " X", count: 100) + "!",
|
||||
String(repeating: "bbbbbbbbbb.", count: 100) + "!",
|
||||
|
||||
"X" + String(repeating: "a", count: 100),
|
||||
"X" + String(repeating: "b", count: 100),
|
||||
"X" + String(repeating: "7", count: 100),
|
||||
]
|
||||
|
||||
print("testing regular expressions...")
|
||||
print()
|
||||
|
||||
var tests: [TestCase] = []
|
||||
|
||||
let lineRegex = try Regex(".*Regex\\(#*\"(.*)\"#*\\).*") // matches `Regex("...")`, `Regex(#"..."#)` etc.
|
||||
|
||||
// read source file, process it line by line...
|
||||
let wholeFile = try String(contentsOfFile: "redos_variants.swift")
|
||||
var lines = wholeFile.components(separatedBy: .newlines)
|
||||
|
||||
// filter lines (running more than a few thousand test cases at once is not recommended)
|
||||
lines = Array(lines[1 ..< 120])
|
||||
|
||||
var regexpCount = 0
|
||||
for line in lines {
|
||||
|
||||
// check if the line matches the line regex...
|
||||
if let match = try lineRegex.wholeMatch(in: line) {
|
||||
if let regexSubstr = match.output[1].substring {
|
||||
let regexStr = String(regexSubstr)
|
||||
//print("regex: \(regexStr)")
|
||||
|
||||
// create the regex
|
||||
if let regex = try? Regex(regexStr) {
|
||||
// create test cases
|
||||
for attackString in attackStrings {
|
||||
tests.append(TestCase(regex: regex, regexStr: regexStr, targetString: attackString, wholeMatch: true))
|
||||
tests.append(TestCase(regex: regex, regexStr: regexStr, targetString: attackString, wholeMatch: false))
|
||||
}
|
||||
regexpCount += 1
|
||||
} else {
|
||||
print("FAILED TO PARSE \(regexStr)")
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// run the tests...
|
||||
// (in parallel, because each test doesn't necessarily terminate and we have no easy way to force
|
||||
// them to terminate short of ending the process as a whole)
|
||||
print("\(regexpCount) regular expression(s)")
|
||||
print("\(tests.count) test case(s)")
|
||||
for test in tests {
|
||||
test.start()
|
||||
}
|
||||
|
||||
// wait...
|
||||
Thread.sleep(forTimeInterval: 20.0)
|
||||
|
||||
// report those cases that are still running
|
||||
print("incomplete after 20 seconds:")
|
||||
for test in tests {
|
||||
if test.done == false {
|
||||
var str = test.targetString
|
||||
str = str.replacingOccurrences(of: "\n", with: "\\n")
|
||||
if str.count > 35 {
|
||||
str = str.prefix(15) + " ... " + str.suffix(15)
|
||||
}
|
||||
let match = test.wholeMatch ? "wholeMatch" : "firstMatch"
|
||||
print(" \(test.regexStr) on \(str) (\(match))")
|
||||
}
|
||||
}
|
||||
|
||||
print("end.")
|
||||
Reference in New Issue
Block a user