直接将污点数据作为参数传递给进行路径操作的库函数、API, 会为攻击者提供篡改系统路径的 机会。
对于禁止使用被污染的数据进行路径遍历的情况,示例1给出了不规范用法(C/C++ 语言)示例。 示例2、示例3给出了规范用法(C/C++ 语言)示例。
示例1:
void f(LPCTSTR IpTemplateDirectory,LPCTSTR lpNewDirectory,
LPSECURITY ATTRIBUTES IpSecurityAttributes){
scanf("%s",IpTemplateDirectory);
CreateDirectoryEx(IpTemplateDirectory,lpNewDirectory, IpSecurityAttributes);
在如上示例中,函数 CreateDirectoryEx()创建的路径参数为污点数据。
用明确的固定的数据来进行路径操作,如果路径操作的参数,确实需要从外界获取,在这种情况下, 需要注意设计并实现完备的验证机制。
示例2:
void f(LPCTSTR IpTemplateDirectory, LPCTSTR lpNewDirectory,
LPSECURITY ATTRIBUTES IpSecurityAttributes){
CreateDirectoryEx("C:/Temp",IpNewDirectory, IpSecurityAttributes);
在规范的代码示例2中,直接使用了绝对路径来替代用户输入的路径。
示例3:
bool isDirectoryValid(LPCTSTR IpTemplateDirectory){
// validate IpTemplateDirectory
return true;
void f(LPCTSTR IpTemplateDirectory,LPCTSTR IpNewDirectory,
LPSECURITY ATTRIBUTES IpSecurityAttributes){
scanf("%s", IpTemplateDirectory);
if(! isDirectoryValid(lpTemplateDirectory))
return;
CreateDirectoryEx(lpTemplateDirectory,IpNewDirectory, IpSecurityAttributes);
在规范的代码示例3中,调用相应接口验证了用户输入的路径是否合法。