1 // Copyright 2022 Code Intelligence GmbH
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 //      http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14 
15 package com.code_intelligence.jazzer.sanitizers
16 
17 import com.code_intelligence.jazzer.api.FuzzerSecurityIssueLow
18 import com.code_intelligence.jazzer.api.HookType
19 import com.code_intelligence.jazzer.api.Jazzer
20 import com.code_intelligence.jazzer.api.MethodHook
21 import com.code_intelligence.jazzer.api.MethodHooks
22 import java.lang.invoke.MethodHandle
23 import java.util.regex.Pattern
24 import java.util.regex.PatternSyntaxException
25 
26 // message introduced in JDK14 and ported back to previous versions
27 private const val STACK_OVERFLOW_ERROR_MESSAGE = "Stack overflow during pattern compilation"
28 
29 @Suppress("unused_parameter", "unused")
30 object RegexInjection {
31     /**
32      * Part of an OOM "exploit" for [java.util.regex.Pattern.compile] with the
33      * [java.util.regex.Pattern.CANON_EQ] flag, formed by three consecutive combining marks, in this
34      * case grave accents: ◌̀.
35      * See [compileWithFlagsHook] for details.
36      */
37     private const val CANON_EQ_ALMOST_EXPLOIT = "\u0300\u0300\u0300"
38 
39     /**
40      * When injected into a regex pattern, helps the fuzzer break out of quotes and character
41      * classes in order to cause a [PatternSyntaxException].
42      */
43     private const val FORCE_PATTERN_SYNTAX_EXCEPTION_PATTERN = "\\E]\\E]]]]]]"
44 
45     @MethodHook(
46         type = HookType.REPLACE,
47         targetClassName = "java.util.regex.Pattern",
48         targetMethod = "compile",
49         targetMethodDescriptor = "(Ljava/lang/String;I)Ljava/util/regex/Pattern;",
50     )
51     @JvmStatic
compileWithFlagsHooknull52     fun compileWithFlagsHook(method: MethodHandle, alwaysNull: Any?, args: Array<Any?>, hookId: Int): Any? {
53         val pattern = args[0] as String?
54         val hasCanonEqFlag = ((args[1] as Int) and Pattern.CANON_EQ) != 0
55         return hookInternal(method, pattern, hasCanonEqFlag, hookId, *args)
56     }
57 
58     @MethodHooks(
59         MethodHook(
60             type = HookType.REPLACE,
61             targetClassName = "java.util.regex.Pattern",
62             targetMethod = "compile",
63             targetMethodDescriptor = "(Ljava/lang/String;)Ljava/util/regex/Pattern;",
64         ),
65         MethodHook(
66             type = HookType.REPLACE,
67             targetClassName = "java.util.regex.Pattern",
68             targetMethod = "matches",
69             targetMethodDescriptor = "(Ljava/lang/String;Ljava/lang/CharSequence;)Z",
70         ),
71     )
72     @JvmStatic
patternHooknull73     fun patternHook(method: MethodHandle, alwaysNull: Any?, args: Array<Any?>, hookId: Int): Any? {
74         return hookInternal(method, args[0] as String?, false, hookId, *args)
75     }
76 
77     @MethodHooks(
78         MethodHook(
79             type = HookType.REPLACE,
80             targetClassName = "java.lang.String",
81             targetMethod = "matches",
82             targetMethodDescriptor = "(Ljava/lang/String;)Z",
83         ),
84         MethodHook(
85             type = HookType.REPLACE,
86             targetClassName = "java.lang.String",
87             targetMethod = "replaceAll",
88             targetMethodDescriptor = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
89         ),
90         MethodHook(
91             type = HookType.REPLACE,
92             targetClassName = "java.lang.String",
93             targetMethod = "replaceFirst",
94             targetMethodDescriptor = "(Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;",
95         ),
96         MethodHook(
97             type = HookType.REPLACE,
98             targetClassName = "java.lang.String",
99             targetMethod = "split",
100             targetMethodDescriptor = "(Ljava/lang/String;)Ljava/lang/String;",
101         ),
102         MethodHook(
103             type = HookType.REPLACE,
104             targetClassName = "java.lang.String",
105             targetMethod = "split",
106             targetMethodDescriptor = "(Ljava/lang/String;I)Ljava/lang/String;",
107         ),
108     )
109     @JvmStatic
stringHooknull110     fun stringHook(method: MethodHandle, thisObject: Any?, args: Array<Any?>, hookId: Int): Any? {
111         return hookInternal(method, args[0] as String?, false, hookId, thisObject, *args)
112     }
113 
hookInternalnull114     private fun hookInternal(
115         method: MethodHandle,
116         pattern: String?,
117         hasCanonEqFlag: Boolean,
118         hookId: Int,
119         vararg args: Any?,
120     ): Any? {
121         if (hasCanonEqFlag && pattern != null) {
122             // With CANON_EQ enabled, Pattern.compile allocates an array with a size that is
123             // (super-)exponential in the number of consecutive Unicode combining marks. We use a mild case
124             // of this as a magic string based on which we trigger a finding.
125             // Note: The fuzzer might trigger an OutOfMemoryError or NegativeArraySizeException (if the size
126             // of the array overflows an int) by chance before it correctly emits this "exploit". In that
127             // case, we report the original exception instead.
128             if (pattern.contains(CANON_EQ_ALMOST_EXPLOIT)) {
129                 Jazzer.reportFindingFromHook(
130                     FuzzerSecurityIssueLow(
131                         """Regular Expression Injection with CANON_EQ
132 When java.util.regex.Pattern.compile is used with the Pattern.CANON_EQ flag,
133 every injection into the regular expression pattern can cause arbitrarily large
134 memory allocations, even when wrapped with Pattern.quote(...).""",
135                     ),
136                 )
137             } else {
138                 Jazzer.guideTowardsContainment(pattern, CANON_EQ_ALMOST_EXPLOIT, hookId)
139             }
140         }
141         try {
142             return method.invokeWithArguments(*args).also {
143                 // Only submit a fuzzer hint if no exception has been thrown.
144                 if (!hasCanonEqFlag && pattern != null) {
145                     Jazzer.guideTowardsContainment(pattern, FORCE_PATTERN_SYNTAX_EXCEPTION_PATTERN, hookId)
146                 }
147             }
148         } catch (e: Exception) {
149             if (e is PatternSyntaxException && !(e.message ?: "").startsWith(STACK_OVERFLOW_ERROR_MESSAGE)) {
150                 Jazzer.reportFindingFromHook(
151                     FuzzerSecurityIssueLow(
152                         """Regular Expression Injection
153 Regular expression patterns that contain unescaped untrusted input can consume
154 arbitrary amounts of CPU time. To properly escape the input, wrap it with
155 Pattern.quote(...).""",
156                         e,
157                     ),
158                 )
159             }
160             throw e
161         }
162     }
163 }
164