8
8
Regular expressions in Ruby can use anchors to match the beginning and end of a string.
9
9
However, if the <code >^</code > and <code >$</code > anchors are used,
10
10
the regular expression can match a single line of a multi-line string.
11
+ This allows bad actors to bypass your regular expression checks and inject malicious input.
11
12
</p >
12
13
</overview >
13
14
14
15
<recommendation >
15
16
<p >
16
- Use the <code >\A</code > and <code >\z</code > anchors to match the beginning and end of a string,
17
- as these will always match the beginning and end of the string, even if the string contains newlines.
17
+ Use the <code >\A</code > and <code >\z</code > anchors since these anchors will always
18
+ match the beginning and end of the string, even if the string contains newlines.
18
19
</p >
19
20
</recommendation >
20
21
21
22
<example >
22
23
23
24
<p >
24
- The following example code uses a regular expression to check that a string contains only digits.
25
+ The following (bad) example code uses a regular expression to check that a string contains only digits.
25
26
</p >
26
27
27
- <sample language =" ruby" >
28
- def bad(input)
29
- raise "Bad input" unless input =~ /^[0-9]+$/
30
-
31
- # ....
32
- end
33
- </sample >
28
+ <sample src =" examples/missing_full_anchor_bad.rb" />
34
29
35
30
<p >
36
31
The regular expression <code >/^[0-9]+$/</code > will match a single line of a multi-line string,
37
32
which may not be the intended behavior.
38
- To match the entire string, the regular expression should be <code >\A[0-9]+\z</code >.
33
+ The following (good) example code uses the regular expression <code >\A[0-9]+\z</code > to match the entire input string .
39
34
</p >
40
35
41
- <sample language =" ruby" >
42
- def good(input)
43
- raise "Bad input" unless input =~ /\A[0-9]+\z/
44
-
45
- # ....
46
- end
47
- </sample >
36
+ <sample src =" examples/missing_full_anchor_good.rb" />
48
37
49
38
</example >
50
39
51
40
<references >
52
41
<li >
53
- RDoc Documentation : <a href =" https://ruby-doc.org/3.2.0/Regexp.html#class-Regexp-label-Anchors" >Anchors</a >
42
+ Ruby documentation : <a href =" https://ruby-doc.org/3.2.0/Regexp.html#class-Regexp-label-Anchors" >Anchors</a >
54
43
</li >
55
44
</references >
56
45
</qhelp >
0 commit comments