ContentProvider路径遍历漏洞

时间:2018-04-13 08:37:42

标签: android android-contentprovider

Google警告ContentProvider中的路径遍历漏洞 https://support.google.com/faqs/answer/7496913

他们的例子(来自上面的链接):

public ParcelFileDescriptor openFile (Uri uri, String mode)
 throws FileNotFoundException {
 File f = new File(DIR, uri.getLastPathSegment());
  if (!f.getCanonicalPath().startsWith(DIR)) {
    throw new IllegalArgumentException();
  }
 return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
}

DIR指的是什么?我如何实施正确的修复?

1 个答案:

答案 0 :(得分:1)

DIR指的是您应用程序内部存储中要共享文件的目录。

这可能是:

File fd = getContext().getFilesDir();
String DIR = fd.getAbsolutePath() + "/public";

(结果:/data/user/0/[APPLICATION_ID]/files/public

修复:

要解决此问题,您必须确保攻击者无法使用包含路径遍历字符(例如“ ../”)的恶意URI访问内部存储中的意外文件。

(例如,您在/data/user/0/[APPLICATION_ID]/databases中的数据库文件是“意外文件”。)

按照Google的建议,您可以通过检查文件的规范路径来做到这一点。规范路径是绝对路径,不包含“。”。或“ ..”了。 (如果文件的规范路径以您的目录路径开头,则一切正常。)

示例:

  • 恶意URI:content://[APPLICATION_ID]/public/../../databases/database.db
  • 恶意路径:/data/user/0/[APPLICATION_ID]/files/public/../../databases/database.db
  • 规范路径:/data/user/0/[APPLICATION_ID]/databases/database.db

因此,这是完整的解决方法:

private String DIR; 

@Override
public boolean onCreate() {
    File fd = getContext().getFilesDir();
    DIR = fd.getAbsolutePath() + "/public";
    return true;
}

@Override
public ParcelFileDescriptor openFile(Uri uri, String mode)
        throws FileNotFoundException {
    File f = new File(DIR, uri.getLastPathSegment());
    if (!f.getCanonicalPath().startsWith(DIR)) {
        throw new IllegalArgumentException();
    }
    return ParcelFileDescriptor.open(f, ParcelFileDescriptor.MODE_READ_ONLY);
}

(旁注:DIR应该为dir,因为它不是常数。)

相关问题