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.example; 16 17 import com.code_intelligence.jazzer.api.FuzzerSecurityIssueLow; 18 import com.code_intelligence.jazzer.api.HookType; 19 import com.code_intelligence.jazzer.api.MethodHook; 20 import java.lang.invoke.MethodHandle; 21 import java.lang.reflect.Field; 22 import java.util.regex.Pattern; 23 24 // This fuzzer verifies that: 25 // 1. a class referenced in a static initializer of a hook is still instrumented with the hook; 26 // 2. hooks that are not shipped in the Jazzer agent JAR can still instrument Java standard library 27 // classes. 28 public class HookDependenciesFuzzer { 29 private static final Field PATTERN_ROOT; 30 31 static { 32 Field root; 33 try { 34 root = Pattern.class.getDeclaredField("root"); 35 } catch (NoSuchFieldException e) { 36 root = null; 37 } 38 PATTERN_ROOT = root; 39 } 40 41 @MethodHook(type = HookType.AFTER, targetClassName = "java.util.regex.Matcher", 42 targetMethod = "matches", targetMethodDescriptor = "()Z", 43 additionalClassesToHook = {"java.util.regex.Pattern"}) 44 public static void matcherMatchesHook(MethodHandle method, Object alwaysNull, Object[] alwaysEmpty, int hookId, Boolean returnValue)45 matcherMatchesHook(MethodHandle method, Object alwaysNull, Object[] alwaysEmpty, int hookId, 46 Boolean returnValue) { 47 if (PATTERN_ROOT != null) { 48 throw new FuzzerSecurityIssueLow("Hook applied even though it depends on the class to hook"); 49 } 50 } 51 fuzzerTestOneInput(byte[] data)52 public static void fuzzerTestOneInput(byte[] data) { 53 try { 54 Pattern.matches("foobar", "foobar"); 55 } catch (Throwable t) { 56 if (t instanceof FuzzerSecurityIssueLow) { 57 throw t; 58 } else { 59 // Unexpected exception, exit without producing a finding to let the test fail due to the 60 // missing Java reproducer. 61 // FIXME(fabian): This is hacky and will result in false positives as soon as we implement 62 // Java reproducers for fuzz target exits. Replace this with a more reliable signal. 63 t.printStackTrace(); 64 System.exit(1); 65 } 66 } 67 } 68 } 69