1 // Copyright 2021 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.FuzzerSecurityIssueHigh; 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 java.lang.invoke.MethodHandle; 22 import java.nio.file.InvalidPathException; 23 import java.nio.file.Path; 24 import java.nio.file.Paths; 25 26 public class ExamplePathTraversalFuzzerHooks { 27 private static final String publicFilesRootPath = "/app/upload/"; 28 29 @MethodHook(type = HookType.BEFORE, targetClassName = "java.io.File", targetMethod = "<init>", 30 targetMethodDescriptor = "(Ljava/lang/String;)V") 31 public static void fileConstructorHook(MethodHandle handle, Object thisObject, Object[] args, int hookId)32 fileConstructorHook(MethodHandle handle, Object thisObject, Object[] args, int hookId) { 33 String path = (String) args[0]; 34 Path normalizedPath; 35 try { 36 normalizedPath = Paths.get(path).normalize(); 37 } catch (InvalidPathException e) { 38 // Invalid paths are correctly rejected by the application. 39 return; 40 } 41 if (!normalizedPath.startsWith(publicFilesRootPath)) { 42 // Simply throwing an exception from here would not work as the calling code catches and 43 // ignores all Throwables. Instead, use the Jazzer API to report a finding from a hook. 44 Jazzer.reportFindingFromHook(new FuzzerSecurityIssueHigh( 45 "Path traversal discovered: '" + path + "' --> '" + normalizedPath + "'")); 46 } 47 } 48 } 49