### BEFORE Hook for Runtime.exec Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use a BEFORE hook to intercept calls to Runtime.exec. This example guides the fuzzer towards command injection patterns and reports findings. ```java import com.code_intelligence.jazzer.api.HookType; import com.code_intelligence.jazzer.api.Jazzer; import com.code_intelligence.jazzer.api.MethodHook; import com.code_intelligence.jazzer.api.FuzzerSecurityIssueMedium; import java.lang.invoke.MethodHandle; public class CustomHooks { // BEFORE hook - runs before target method @MethodHook( type = HookType.BEFORE, targetClassName = "java.lang.Runtime", targetMethod = "exec" ) public static void checkExec( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { if (arguments.length > 0 && arguments[0] instanceof String) { String command = (String) arguments[0]; // Guide fuzzer toward dangerous characters Jazzer.guideTowardsContainment(command, ";|`$", hookId); // Report if dangerous pattern found if (command.contains(";") || command.contains("|")) { Jazzer.reportFindingFromHook( new FuzzerSecurityIssueMedium("Command Injection: " + command)); } } } // REPLACE hook - replaces target method entirely @MethodHook( type = HookType.REPLACE, targetClassName = "java.security.SecureRandom", targetMethod = "nextInt" ) public static int replaceSecureRandom( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Return deterministic value for reproducibility return 42; } // AFTER hook - runs after target method with return value @MethodHook( type = HookType.AFTER, targetClassName = "java.sql.Connection", targetMethod = "prepareStatement" ) public static void afterPrepareStatement( MethodHandle method, Object thisObject, Object[] arguments, int hookId, Object returnValue) { if (arguments.length > 0 && arguments[0] instanceof String) { String sql = (String) arguments[0]; // Log or analyze SQL queries System.out.println("SQL: " + sql); } } // Hook with method descriptor for overloaded methods @MethodHook( type = HookType.BEFORE, targetClassName = "java.lang.String", targetMethod = "getBytes", targetMethodDescriptor = "(Ljava/lang/String;)[B" // getBytes(String charset) ) public static void hookGetBytesWithCharset( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Only hooks String.getBytes(String), not String.getBytes() } // Hook with additional classes to instrument @MethodHook( type = HookType.BEFORE, targetClassName = "java.net.URLConnection", targetMethod = "connect", additionalClassesToHook = {"sun.net.www.protocol.http.HttpURLConnection"} ) public static void hookConnect( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Hook is applied to URLConnection and HttpURLConnection } } ``` -------------------------------- ### AFTER Hook for Connection.prepareStatement Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use an AFTER hook to execute code after the target method completes. This example logs the SQL query passed to prepareStatement. ```java // AFTER hook - runs after target method with return value @MethodHook( type = HookType.AFTER, targetClassName = "java.sql.Connection", targetMethod = "prepareStatement" ) public static void afterPrepareStatement( MethodHandle method, Object thisObject, Object[] arguments, int hookId, Object returnValue) { if (arguments.length > 0 && arguments[0] instanceof String) { String sql = (String) arguments[0]; // Log or analyze SQL queries System.out.println("SQL: " + sql); } } ``` -------------------------------- ### Fuzz Test with FuzzedDataProvider Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md This example demonstrates a simple fuzz test using FuzzedDataProvider. It consumes the remaining input as a string and asserts equality after encoding and decoding. ```java import com.code_intelligence.jazzer.api.FuzzedDataProvider; import com.code_intelligence.jazzer.junit.FuzzTest; class ParserTests { @Test void unitTest() { assertEquals("foobar", SomeScheme.decode(SomeScheme.encode("foobar"))); } @FuzzTest void fuzzTest(FuzzedDataProvider data) { String input = data.consumeRemainingAsString(); assertEquals(input, SomeScheme.decode(SomeScheme.encode(input))); } } ``` -------------------------------- ### Instrumenting Additional Classes Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use the additionalClassesToHook parameter to apply a hook to multiple classes. This example hooks both URLConnection.connect and HttpURLConnection.connect. ```java // Hook with additional classes to instrument @MethodHook( type = HookType.BEFORE, targetClassName = "java.net.URLConnection", targetMethod = "connect", additionalClassesToHook = {"sun.net.www.protocol.http.HttpURLConnection"} ) public static void hookConnect( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Hook is applied to URLConnection and HttpURLConnection } ``` -------------------------------- ### Complete Jazzer FuzzTest Example with ValuePool Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Demonstrates a comprehensive fuzz test method utilizing multiple ValuePool configurations for different parameters, including supplier methods, file patterns, mutation probability, and nested type constraints. ```java class MyFuzzTest { static Stream edgeCases() { Map map = new HashMap<>(); map.put("one", 1); map.put("two", 2); return Stream.of( "", // Strings "null", "alert('xss')", 0, // Integers -1, Integer.MAX_VALUE, new byte[] {0x00, 0x7F}, // A byte array map); // A Map } static Stream justStrings() { return Stream.of("{\"hello\": \"json\"}", "{\"__proto__\": {\"test\": \"value\"}}"); } @FuzzTest @ValuePool( value = {"edgeCases"}, files = {"test-inputs/*.bin"}, p = 0.25) // Use pool values 25% of the time void testParser( @ValuePool("justStrings") String input, Map config, byte[] data) { // All three parameters get values from the pool: // - 'input' gets Strings from two suppliers: 'edgeCases()' and 'justStrings()' // - 'config' keys get Strings, values get Integers, Map itself gets the `map` objects, all from supplier method 'edgeCases()' // - 'data' gets byte arrays from both edgeCases() and *.bin files // In addition, the Integer values of the Map 'config' have a different configuration: // the values from the value pool will be taken with probability 0.01, // and at most 10 mutations will be applied on top of those values. } } ``` -------------------------------- ### Run Jazzer Standalone via Binary Source: https://github.com/codeintelligencetesting/jazzer/blob/main/README.md Execute Jazzer using the standalone binary. This method starts its own JVM configured for fuzzing. Ensure `JAVA_HOME` is set correctly if `libjvm.so` is not found. ```shell ./jazzer --cp= --target_class= ``` -------------------------------- ### Example: Autofuzz Method Reference Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/arguments-and-configuration-options.md The autofuzz option accepts a fully qualified method reference, optionally including its signature, to specify a method for automatic fuzzing. ```java java.lang.System.out::println ``` ```java java.lang.String::new(byte[]) ``` -------------------------------- ### REPLACE Hook for SecureRandom.nextInt Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use a REPLACE hook to substitute the original method implementation. This example returns a deterministic value for reproducible fuzzing. ```java // REPLACE hook - replaces target method entirely @MethodHook( type = HookType.REPLACE, targetClassName = "java.security.SecureRandom", targetMethod = "nextInt" ) public static int replaceSecureRandom( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Return deterministic value for reproducibility return 42; } ``` -------------------------------- ### JavaBean Constructor-Based Approach Examples Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Illustrates JavaBeans for constructor-based fuzzing. 'PropertyNamesBean' uses a standard constructor. 'ConstructorPropertiesBean' uses @ConstructorProperties to map constructor arguments to property names. 'FallbackTypeBean' shows a fallback scenario. ```java public static class PropertyNamesBean { private final String bar; public PropertyNamesBean(String bar) { this.bar = bar; } public String getBar() { return bar; } } ``` ```java public static class ConstructorPropertiesBean { private final String foo; @ConstructorProperties({"bar"}) public PropertyNamesBean(String foo) { this.bar = foo; } public String getBar() { return foo; } } ``` ```java public static class FallbackTypeBean { private final String foo; public PropertyNamesBean(String foo) { this.bar = foo; } public String getSomething() { return foo; } } ``` ```java @FuzzTest public void testBeans(PropertyNamesBean propertyNamesBean, ConstructorPropertiesBean constructorPropertiesBean, FallbackTypeBean fallbackTypeBean) { // ... } ``` -------------------------------- ### Example: additional_classes_excludes Environment Variable Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/arguments-and-configuration-options.md Use the JAZZER_ADDITIONAL_CLASSES_EXCLUDES environment variable to specify glob patterns for classes that should be excluded from instrumentation. Multiple patterns are separated by colons. ```bash JAZZER_ADDITIONAL_CLASSES_EXCLUDES=org.example.NotHere:org.example.AlsoNotBelow.** ``` -------------------------------- ### Hooking Overloaded Methods with Descriptors Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Specify the target method descriptor to hook specific overloaded methods. This example targets String.getBytes(String charset). ```java // Hook with method descriptor for overloaded methods @MethodHook( type = HookType.BEFORE, targetClassName = "java.lang.String", targetMethod = "getBytes", targetMethodDescriptor = "(Ljava/lang/String;)[B" // getBytes(String charset) ) public static void hookGetBytesWithCharset( MethodHandle method, Object thisObject, Object[] arguments, int hookId) { // Only hooks String.getBytes(String), not String.getBytes() } ``` -------------------------------- ### Use Complex Data Types in Fuzz Tests with Mutation Framework Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md This example demonstrates how to use a record with multiple fields as a parameter in a fuzz test. The mutation framework automatically handles the creation and mutation of the `SimpleTypesRecord`. ```java record SimpleTypesRecord(boolean bar, int baz) { } @FuzzTest public void testSimpleTypeRecord(SimpleTypesRecord record) { doSomethingWithRecord(record); } ``` -------------------------------- ### Write a Basic Fuzz Test with JUnit 5 Source: https://github.com/codeintelligencetesting/jazzer/blob/main/README.md Annotate a method with @FuzzTest to enable Jazzer to generate and mutate inputs for its parameters. This example fuzzes a decoding function. ```java package org.example; import com.code_intelligence.jazzer.junit.FuzzTest; import com.code_intelligence.jazzer.mutation.annotation.NotNull; import com.code_intelligence.jazzer.mutation.annotation.InRange; import com.code_intelligence.jazzer.mutation.annotation.WithUtf8Length; import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class ParserTests { @Test void unitTest() { assertEquals("foobar", SomeScheme.decode(SomeScheme.encode("foobar"))); } @FuzzTest void fuzzTest_decode(@NotNull String input) { assertEquals(input, SomeScheme.decode(SomeScheme.encode(input))); } @FuzzTest void fuzzTest_decodeWithN(@NotNull @WithUtf8Length(min=10, max=200) String input, @InRange(min=-10, max=10) int n) { assertEquals(input, SomeScheme.decode(SomeScheme.encode(input))); assertTrue(n >= -10 && n <= 10); } } ``` -------------------------------- ### JavaBean Setter-Based Approach Example Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Defines a simple JavaBean 'FooBean' with a default constructor and a property 'foo' accessible via getter and setter. This structure is required for Jazzer's setter-based JavaBean support. ```java public static class FooBean { private String foo; public String getFoo() { return foo; } public void setFoo(String foo) { this.foo = foo; } } @FuzzTest public void testFooBean(FooBean fooBean) { // ... } ``` -------------------------------- ### Example: Disabling Specific Hooks with Environment Variable Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/arguments-and-configuration-options.md To disable specific built-in sanitizers or custom hooks, use the JAZZER_DISABLED_HOOKS environment variable with a colon-separated list of fully qualified class names. ```bash JAZZER_DISABLED_HOOKS=com.code_intelligence.jazzer.sanitizers.ServerSideRequestForgery:com.code_intelligence.jazzer.sanitizers.RegexInjection ``` -------------------------------- ### Build and Run Jazzer from Source Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Clone the Jazzer repository, navigate to the directory, and build/run Jazzer using Bazel. Use '--' to pass arguments to Jazzer. ```bash git clone https://github.com/CodeIntelligenceTesting/jazzer cd jazzer # Note the double dash used to pass to Jazzer rather than Bazel. bazel run //:jazzer -- ``` -------------------------------- ### Build and Run Fuzz Tests with Bazel and cifuzz Source: https://github.com/codeintelligencetesting/jazzer/blob/main/selffuzz/README.md Use these commands to build all targets in the Bazel workspace and then run a specific fuzz test case using cifuzz. Ensure the test case name is correctly specified. ```shell bazel build //... ``` ```shell cifuzz run "" ``` -------------------------------- ### Guiding Fuzzing with @ValuePool on Parameter Type Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Applies @ValuePool to a specific parameter type to guide fuzzing with custom values from a supplier. Values are routed to mutators based on type. ```java @FuzzTest void fuzzTest(Map<@ValuePool(value = {"mySupplier"}) String, Integer> foo) { // Strings from mySupplier feed the Map's String mutator } ``` -------------------------------- ### Configure Bazel Disk Cache Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Enable Bazel's disk cache by creating a .bazelrc file in your home directory. This speeds up incremental builds and tests. ```bash common --disk_cache=/.cache/bazel-disk ``` -------------------------------- ### Example: Turning Off All Instrumentation Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/arguments-and-configuration-options.md Set the JAZZER_HOOKS environment variable to 0 to disable all fuzzing instrumentation. This can be useful for running non-fuzzing tests with Jazzer. ```bash JAZZER_HOOKS=0 ``` -------------------------------- ### JSON payload supplier Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Provides a stream of JSON strings, including empty, simple, and prototype-polluted examples. Useful for fuzzing JSON parsers. ```java static Stream jsonPayloads() { return Stream.of( "{}", "{\"key\": \"value\"}", "{\"__proto__\": {}}" ); } ``` -------------------------------- ### Build Jazzer for Android Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Build Jazzer for Android by setting ANDROID_HOME and ANDROID_NDK_HOME environment variables, then running the bazel build command. ```bash bazel build //launcher/android:jazzer_android ``` -------------------------------- ### Build Jazzer Release Binaries Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Build the release binaries for Jazzer using the 'bazel build //:jazzer_release' command. The output is a tar.gz file. ```bash bazel build //:jazzer_release ``` -------------------------------- ### Jazzer JVM Debug Flags Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Configure JVM debug flags to start Jazzer in debug mode, suspending execution until a debugger connects on port 5005. ```java -agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=5005 ``` -------------------------------- ### Run fuzz tests with Gradle Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Execute fuzz tests using Gradle, enabling fuzzing mode with `JAZZER_FUZZ=1`. ```bash # Run with Gradle JAZZER_FUZZ=1 ./gradlew test --tests "ParserTests" ``` -------------------------------- ### Combine Value Suppliers and File Patterns Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Integrate both value supplier methods and file glob patterns within a single ValuePool annotation to provide diverse input sources. ```java @ValuePool(value = {"mySupplier"}, files = {"test-data/*.json"}) ``` -------------------------------- ### Run All Jazzer Tests Source: https://github.com/codeintelligencetesting/jazzer/blob/main/CONTRIBUTING.md Execute all tests in the Jazzer repository using the 'bazel test //...' command. Consider using '--config=fail-fast' to stop after the first failure. ```bash bazel test //... ``` -------------------------------- ### Generate Human-Readable Coverage Report Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Use the `--coverage_report=` flag to generate a human-readable report of branch and line coverage. ```bash --coverage_report=coverage.txt ``` -------------------------------- ### Guiding Fuzzing with @ValuePool on Test Method Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Applies @ValuePool to the test method itself, propagating custom values to all matching types across all parameters. This provides broad guidance for fuzzing. ```java @FuzzTest @ValuePool(value = {"mySupplier"}) void yetAnotherFuzzTest(Map foo, String bar) { // Values propagate to ALL matching types: // - String mutator for Map keys in 'foo' // - String mutator for 'bar' // - Integer mutator for Map values in 'foo' // - Map mutator would use supplier values if it contained any Map objects } ``` -------------------------------- ### Enable Value Profiling Mode Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Activate libFuzzer's value profiling mode with the `-use_value_profile=1` flag to associate feedback with bytecode locations for enhanced coverage. ```bash -use_value_profile=1 ``` -------------------------------- ### Guiding Fuzzing with @ValuePool on Parameter Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Uses @ValuePool on a parameter to provide custom values for multiple types within that parameter. Type matching ensures values are sent to the correct mutators. ```java @FuzzTest void anotherFuzzTest(@ValuePool(value = {"mySupplier"}) Map foo) { // Strings from mySupplier feed the Map's String mutator // Integers from mySupplier feed the Map's Integer mutator // Map mutator would use supplier values if it contained any Map objects } ``` -------------------------------- ### Configure Keep Going Fuzzing Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Use `--keep_going=N` to continue fuzzing until N unique stack traces are encountered. Set to 0 to run until another stop condition is met. Ignore specific stack traces using `--ignore=,`. ```bash --keep_going=10 ``` ```bash --ignore=TOKEN1,TOKEN2 ``` -------------------------------- ### JUnit Seed Inputs with @MethodSource Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use @MethodSource to provide seed inputs for @FuzzTest. This guides fuzzing towards specific code paths. The seed provider must return a Stream. ```java import com.code_intelligence.jazzer.junit.FuzzTest; import com.code_intelligence.jazzer.mutation.annotation.NotNull; import org.junit.jupiter.params.provider.Arguments; import org.junit.jupiter.params.provider.MethodSource; import java.util.List; import java.util.stream.Stream; import static java.util.Arrays.asList; import static org.junit.jupiter.params.provider.Arguments.arguments; class SeededFuzzTest { // Seed input provider - returns Stream static Stream parseJsonSeeds() { return Stream.of( arguments("{}"), arguments("{\"key\": \"value\"}"), arguments("{\"nested\": {\"deep\": true}}"), arguments("[1, 2, 3]"), arguments("null") ); } @MethodSource("parseJsonSeeds") @FuzzTest void fuzzJsonParser(@NotNull String json) { // In regression mode: runs once per seed // In fuzzing mode: seeds are mutated to find new inputs JsonParser.parse(json); } // Multiple parameters with seeds static Stream multiParamSeeds() { return Stream.of( arguments(asList("admin", "user"), 0), arguments(asList("guest"), 100), arguments(asList("root", "sudo", "admin"), -1) ); } @MethodSource("multiParamSeeds") @FuzzTest void fuzzWithMultipleParams( @NotNull List<@NotNull String> roles, int accessLevel) { checkAccess(roles, accessLevel); } } ``` -------------------------------- ### Export coverage report Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Generate a coverage report and dump coverage data using `--coverage_report` and `--coverage_dump`. ```bash # Export coverage report ./jazzer --cp=app.jar \ --target_class=com.example.FuzzTest \ --coverage_report=coverage.txt \ --coverage_dump=jacoco.exec ``` -------------------------------- ### Pass JVM Arguments via --jvm_args Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Supply JVM arguments to Jazzer using the `--jvm_args` flag. Arguments are delimited by the classpath separator (`;` on Windows, `:` on Linux/macOS). Arguments provided here take precedence over JAVA_OPTS. ```bash # Windows --jvm_args=--enable-preview;-Xmx1000m ``` ```bash # Linux & macOS --jvm_args=--enable-preview:-Xmx1000m ``` -------------------------------- ### Run standalone Jazzer binary Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Execute Jazzer directly using its binary, specifying classpath, target class, and method. ```bash # Standalone Jazzer binary ./jazzer --cp=target/classes:target/test-classes \ --target_class=com.example.ParserTests \ --target_method=fuzzTest ``` -------------------------------- ### Enable value profiling in Jazzer Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Enhance coverage by enabling value profiling with the `-use_value_profile=1` flag. ```bash # Enable value profiling for better coverage ./jazzer --cp=app.jar \ --target_class=com.example.FuzzTest \ -use_value_profile=1 ``` -------------------------------- ### Run Jazzer Standalone via Main Class Source: https://github.com/codeintelligencetesting/jazzer/blob/main/README.md Use this command to run Jazzer standalone by directly calling its main class. Ensure the Jazzer JARs and project classpath are correctly specified. Optional Jazzer arguments use double dashes, while libFuzzer arguments use single dashes. ```shell java -cp ;; com.code_intelligence.jazzer.Jazzer --target_class= [args...] ``` -------------------------------- ### Configure Git for Jazzer Input Directories Source: https://github.com/codeintelligencetesting/jazzer/blob/main/README.md Mark Jazzer input and corpus directories as binary in `.gitattributes` to prevent Git from interfering with their content. This is crucial for maintaining the integrity of fuzzing inputs and generated corpora. ```gitattributes src/test/resources/** binary .cifuzz-corpus/** binary ``` -------------------------------- ### Fuzz Test with Simple Type Record Parameter Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Demonstrates fuzzing a List of a custom record type with size constraints. Ensure the record type is defined and the `doSomethingWithRecord` method is implemented. ```java record SimpleTypesRecord(boolean bar, int baz) {} @FuzzTest public void testSimpleTypeRecord(@NotNull @WithSize(min = 3, max = 100) List records) { doSomethingWithRecord(record); } ``` -------------------------------- ### Load Files with Glob Patterns in ValuePool Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Use glob patterns in the 'files' field to load byte arrays from files for fuzzing. Supports various glob syntaxes for different file types and locations. ```java @ValuePool(files = {"*.jpeg"}) // All JPEGs in working dir @ValuePool(files = {"**.xml"}) // All XMLs recursively @ValuePool(files = {"/absolute/path/**"}) // All files from absolute path @ValuePool(files = {"*.jpg", "**.png"}) // Multiple patterns ``` -------------------------------- ### Combine suppliers and files for fuzzing Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Combines a static supplier method ('edgeCases') with data loaded from binary files in 'corpus/'. The combined pool is used 30% of the time for the 'input' byte array parameter. ```java @FuzzTest @ValuePool(value = {"edgeCases"}, files = {"corpus/*.bin"}, p = 0.3) void testCombined(byte[] input) { processInput(input); } ``` -------------------------------- ### Allow all network connections Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Use this to temporarily allow all network connections within a specific scope. Ensure to close the scope to revert to default network restrictions. ```java import com.code_intelligence.jazzer.api.BugDetectors; import com.code_intelligence.jazzer.api.SilentCloseable; import com.code_intelligence.jazzer.junit.FuzzTest; import java.nio.file.Path; import java.nio.file.Paths; class SanitizerConfigExamples { // Allow all network connections @FuzzTest void testWithNetworkAccess(byte[] data) { try (SilentCloseable unused = BugDetectors.allowNetworkConnections()) { // Network connections allowed in this block sendToServer(data); } // Network connections blocked again - SSRF detection active processLocally(data); } // Allow specific network connections only @FuzzTest void testWithFilteredNetwork(String host, int port, byte[] payload) { try (SilentCloseable unused = BugDetectors.allowNetworkConnections( (h, p) -> h.equals("api.example.com") && p == 443)) { // Only connections to api.example.com:443 are allowed connectTo(host, port, payload); } } // Configure file path traversal detection @FuzzTest void testFileAccess(String filename) { // Set custom traversal target try (SilentCloseable unused = BugDetectors.setFilePathTraversalTarget( () -> Paths.get("/etc/passwd"))) { // Finding reported if path resolves to /etc/passwd readFile(filename); } } // Custom file path validation @FuzzTest void testWithPathValidation(String userPath) { Path allowedBase = Paths.get("/app/data"); try (SilentCloseable unused = BugDetectors.setFilePathTraversalAllowPath( path -> path.normalize().startsWith(allowedBase))) { // Only paths under /app/data are allowed // Any path outside triggers a finding processFile(Paths.get(userPath)); } } // Nested scoped configuration @FuzzTest void testNestedScopes(byte[] imageData, String uploadUrl) { // Parse image - no network allowed Image image = parseImage(imageData); // Upload phase - limited network access try (SilentCloseable outer = BugDetectors.allowNetworkConnections( (host, port) -> host.endsWith(".example.com"))) { // Specific upload endpoint try (SilentCloseable inner = BugDetectors.allowNetworkConnections( (host, port) -> host.equals("upload.example.com") && port == 443)) { uploadImage(image, uploadUrl); } // Back to *.example.com allowed notifyService(image.getId()); } // All network blocked again } } ``` -------------------------------- ### Define Supplier Methods for ValuePool Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Specify static methods that return Stream to provide values for fuzzing. Fully qualified names can be used for methods in other classes. ```java // The supplier methods mySupplier and anotherSupplier should be in the class of the fuzz test method // Supplier methods from other classes can be used by giving fully qualified names: // com.example.MyClass#mySupplierMethod and com.example.OuterClass$InnerClass#mySupplierMethod @ValuePool(value = {"mySupplier", "anotherSupplier", "com.example.MyClass#mySupplierMethod", "com.example.OuterClass$InnerClass#mySupplierMethod"}) ``` -------------------------------- ### Specify Method for Autofuzz Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/autofuzz.md Use the `--autofuzz` flag followed by a fully qualified method reference to enable fuzzing for a specific method. This is useful when you want to target a particular method for fuzzing. ```bash --autofuzz=org.apache.commons.imaging.Imaging::getBufferedImage ``` -------------------------------- ### Jazzer Configuration Options Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/arguments-and-configuration-options.md Details on how Jazzer's configuration options can be set and their order of precedence. ```APIDOC ## Jazzer Configuration Options Jazzer provides numerous configuration settings that can be managed through various sources. The precedence order for these settings, from lowest to highest, is: 1. **Default value**: The built-in default for the option. 2. **`META-INF/MANIFEST.MF` attribute**: An attribute named `Jazzer-` within the manifest file on the classpath. 3. **Environment variable**: An environment variable named `JAZZER-`. 4. **System property**: A Java system property named `jazzer.`. 5. **JUnit configuration parameter**: A parameter named `jazzer.` in a `junit-platform.properties` file. 6. **CLI parameter**: A command-line argument prefixed with `--` when running standalone Jazzer (e.g., `--some_opt`). Some options are specific to standalone Jazzer execution (*standalone only*), only relevant in fuzzing mode (*fuzzing only*), or are exclusively environment variables (*environment variable only*). ### Configuration Options - **additional_classes_excludes** [list, separator=`':'`, default=""] - Glob patterns matching names of classes from Java that are not in your jar file, but may be included in your program. Example: `JAZZER_ADDITIONAL_CLASSES_EXCLUDES=org.example.NotHere:org.example.AlsoNotBelow.**` - **additional_jvm_args** [list, separator=`':'`, default=""] (*standalone only*) - Additional arguments to pass to the JVM (separator can be escaped with `\`) - **agent_path** [string, default=""] (*standalone only*) - Custom path to `jazzer_agent_deploy.jar` - **android_bootpath_classes_overrides** [string, default=""] - Used for fuzzing classes loaded in through the bootstrap class loader on Android. Full path to jar file with the instrumented versions of the classes you want to override. - **android_init_options** [string, default=""] (*standalone only*) - Which libraries to use when initializing ART - **asan** [bool, default="false"] - Allow fuzzing of native libraries compiled with `-fsanitize=address`. See [here](advanced.md#native-libraries) for more details. - **autofuzz** [string, default=""] (*DEPRECATED*) - Fully qualified reference (optionally with a Javadoc-style signature) to a method on the class path to be fuzzed with automatically generated arguments - Examples: `java.lang.System.out::println`, `java.lang.String::new(byte[])` - **autofuzz_ignore** [list, separator=`','`, default=""] (*DEPRECATED*) - Fully qualified names of exception classes to ignore during fuzzing - **command_line** [bool, default="false"] - Whether Jazzer is running a JUnit fuzz test from the command line - **conditional_hooks** [bool, default="false"] - Whether hook instrumentation should add a check for JazzerInternal#hooksEnabled before executing hooks. Used to disable hooks during non-fuzz JUnit tests. - **coverage_dump** [string, default=""] - Path to write a JaCoCo `.exec` file to when the fuzzer exits (if non-empty). See [here](advanced.md#export-coverage-information) for more details. - **coverage_report** [string, default=""] - Path to write a human-readable coverage report to when the fuzzer exits (if non-empty) - **cp** [list, separator=`':'`, default=""] (*standalone only*) - The class path to use for fuzzing - **custom_hooks** [list, separator=`':'`, default=""] - Names of classes to load custom hooks from - **custom_hook_excludes** [list, separator=`':'`, default=""] - Glob patterns matching names of classes that should not be instrumented with hooks (custom and built-in) - **custom_hook_includes** [list, separator=`':'`, default=""] - Glob patterns matching names of classes to instrument with hooks (custom and built-in) - **dedup** [bool, default="true"] - Compute and print a deduplication token for every finding - **disabled_hooks** [list, separator=`':'`, default=""] - Names of classes from which hooks (custom or built-in) should not be loaded from - Example: to disable the `ServerSideRequestForgery` and `RegexInjection` sanitizers use this environment variable when running Jazzer: - `JAZZER_DISABLED_HOOKS=com.code_intelligence.jazzer.sanitizers.ServerSideRequestForgery:com.code_intelligence.jazzer.sanitizers.RegexInjection` - **dump_classes_dir** [string, default=""] - Directory to dump instrumented `.class` files into (if non-empty) - **fuzz** [bool, default=`false`] - Run in fuzzing mode (use `true`) or regression mode (use `false`). Defaults to `true` in *standalone* mode - **help** [bool, default="false"] (*standalone only*) - Show the list of all available arguments - **hooks** [bool, default="true"] - Apply fuzzing instrumentation (use 'trace' for finer-grained control) - Example: `JAZZER_HOOKS=0` - to turn off all instrumentation - **hwasan** [bool, default="true"] - Allow fuzzing of native libraries compiled with hwasan - **id_sync_file** [string, default=""] - A file used by Jazzer subprocesses to coordinate coverage instrumented. If not set, Jazzer will create a temporary file and pass it to subprocesses. ``` -------------------------------- ### Fuzzing with Lombok @SuperBuilder Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Shows how to fuzz a class that extends another class, both generated with Lombok's @SuperBuilder. Use for hierarchical class structures built with builders. ```java class SimpleClassFuzzTests { @SuperBuilder static class ParentClass { String foo; } @SuperBuilder static class ChildClass extends ParentClass { List bar; } @FuzzTest void fuzzChildClassFunction(@NotNull ChildClass childClass) { someChildFunctionToFuzz(childClass); } } ``` -------------------------------- ### Configure Trace Instrumentation Types Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Specify instrumentation types using the `--trace` flag. Combine multiple types with a colon (Linux/macOS) or semicolon (Windows). Available types include 'cov', 'cmp', 'div', 'gep', 'indir', and 'all'. ```bash --trace=cov:cmp:div ``` -------------------------------- ### Configure parallel fuzzing in Jazzer Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Run fuzzing in parallel by specifying the number of forks and jobs. ```bash # Parallel fuzzing ./jazzer --cp=app.jar \ --target_class=com.example.FuzzTest \ -fork=4 -jobs=8 ``` -------------------------------- ### Run Jazzer with instrumentation filters Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Control which classes are instrumented during fuzzing using `instrumentation_includes` and `instrumentation_excludes`. ```bash # With instrumentation filters ./jazzer --cp=app.jar \ --target_class=com.example.FuzzTest \ --instrumentation_includes="com.example.**" \ --instrumentation_excludes="com.example.thirdparty.**" ``` -------------------------------- ### Generate JaCoCo HTML Report Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Use the JaCoCo CLI tool to generate an HTML report from coverage data. Specify class files, source files, and output directory. ```shell java -jar path/to/jacococli.jar report coverage.exec \ --classfiles classes.jar \ --sourcefiles some/path/to/sources \ --html report \ --name FuzzCoverageReport ``` -------------------------------- ### Configure Mutation Probability in ValuePool Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Control the likelihood of using values from the pool versus other mutation strategies using the 'p' field. The default is 0.1 (10%). ```java @ValuePool(value = {"mySupplier"}, p = 0.3) T // Use pool values 30% of the time ``` -------------------------------- ### Dump JaCoCo Coverage Data Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Use the `--coverage_dump=` flag to generate a binary `.exec` file containing JaCoCo coverage data. ```bash --coverage_dump=jacoco.exec ``` -------------------------------- ### Load values from files for fuzzing Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Fuzzes using data loaded from XML files in 'testdata/' and JSON files in 'samples/'. The loaded data populates the 'data' byte array parameter. ```java @FuzzTest @ValuePool(files = {"testdata/*.xml", "samples/**/*.json"}) void testWithFiles(byte[] data) { // data is populated from matching files parseDocument(data); } ``` -------------------------------- ### Specify Constructor for Autofuzz Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/autofuzz.md To autofuzz a constructor, use the `ClassType::new` format. This allows Jazzer to fuzz the instantiation process of a class. ```bash --autofuzz=com.example.MyClass::new ``` -------------------------------- ### Keep fuzzing after finding bugs Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Continue fuzzing even after bugs are found by using the `--keep_going` flag. ```bash # Keep fuzzing after finding bugs ./jazzer --cp=app.jar \ --target_class=com.example.FuzzTest \ --keep_going=10 ``` -------------------------------- ### Run fuzz tests in fuzzing mode Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Enable active input generation for fuzz testing by setting the `JAZZER_FUZZ` environment variable. ```bash # Run in fuzzing mode - actively generate new inputs JAZZER_FUZZ=1 mvn test -Dtest=ParserTests ``` -------------------------------- ### Fuzzing with Lombok @Builder Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/mutation-framework.md Illustrates fuzzing a class generated with Lombok's @Builder annotation. This is suitable for classes constructed via a builder pattern. ```java class SimpleClassFuzzTests { @Builder static class SimpleClass { String foo; List bar; boolean baz; } @FuzzTest void fuzzSimpleClassFunction(@NotNull SimpleClass simpleClass) { someFunctionToFuzz(simpleClass); } } ``` -------------------------------- ### Specify Method with Signature for Autofuzz Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/autofuzz.md When a method has multiple overloads, you can specify the exact signature to fuzz using the format `ClassName::methodName(param1,param2)`. This ensures Jazzer targets the intended method overload. ```bash --autofuzz=org.apache.commons.imaging.Imaging::getBufferedImage(java.io.InputStream,java.util.Map) ``` -------------------------------- ### Gradle Configuration for Jazzer Source: https://context7.com/codeintelligencetesting/jazzer/llms.txt Configure Jazzer in Gradle's build.gradle by adding jazzer-junit as a test dependency and setting the JAZZER_FUZZ environment variable. JVM arguments for better fuzzing can also be specified. ```groovy plugins { id 'java' } repositories { mavenCentral() } dependencies { testImplementation 'com.code-intelligence:jazzer-junit:0.24.0' testImplementation 'org.junit.jupiter:junit-jupiter:5.9.2' } test { useJUnitPlatform() // Pass environment variables environment 'JAZZER_FUZZ', System.getenv('JAZZER_FUZZ') ?: 'false' // JVM args for better fuzzing jvmArgs '-XX:-OmitStackTraceInFastThrow' jvmArgs '-XX:+UseParallelGC' } ``` -------------------------------- ### Restrict Class Instrumentation with Glob Patterns Source: https://github.com/codeintelligencetesting/jazzer/blob/main/docs/advanced.md Use `--instrumentation_includes` and `--instrumentation_excludes` flags with colon-separated glob patterns to control which classes are instrumented. Excludes JVM-internal and standard library classes by default. ```bash --instrumentation_includes=com.my_com.**:com.other_com.** --instrumentation_excludes=com.my_com.crypto.** ```