rainmakerho / Vulnerability-Analysis

多收集一些資安檢測問題, 來跟大家討論它是否真的需要修正, 或是用什麼方式俢正會來得比較好。
Apache License 2.0
1 stars 0 forks source link

Stored_Path_Traversal - Checkmarx V 9.4.5.1009 #7

Closed rainmakerho closed 1 year ago

rainmakerho commented 1 year ago

環境

Checkmarx V 9.4.5.1009 HF22 CSharp\Cx\CSharp_Medium_Threat\Stored_Path_Traversal C#

說明

讀取檔案到 byte array 之中,再透過 MemoryStream 判斷 big5 / utf8 編碼,再透過 StreamReader 給正確編碼, 呼叫 ReadToEnd 取出字串。

Source

string xdiFileName = @"c:\abc.dl";
byte[] difileByte = System.IO.File.ReadAllBytes(xdiFileName);

//compId 是 client 給的值
string di2html = TransformBLL.Di2HTML(compId, difileByte);

//TransformBLL.Di2HTML method 如下,
public static string Di2HTML(string compId, byte[] fileByte)
{
    using (Stream fileStream = new MemoryStream(fileByte))
    {
        return Di2HTML(compId, fileStream);
    }
}

public static string Di2HTML(string compId, Stream fileStream)
{
    compId = Cx_PreventPathTraversal(compId);
    IFileAccess fileAccess = SpringContext.GetObject<IFileAccess>();
    string inputXml = string.Empty;

    Encoding encoding = fileAccess.IsBIG5(fileStream) ? 
                            Encoding.GetEncoding(950) :
                            Encoding.UTF8;

    //參考網址:http://www.dotblogs.com.tw/rainmaker/archive/2013/05/20/104547.aspx
    //Stream stream = new MemoryStream(fileAccess.ReadFile(filePath));
    //using (StreamReader sr = new StreamReader(fileStream, Encoding.Default, true))
    using (StreamReader sr = new StreamReader(fileStream, encoding, true))
    {
        fileStream.Seek(0, SeekOrigin.Begin);
        inputXml = sr.ReadToEnd();
        sr.Close();
    }
    return inputXml ;
}

Checkmarx 判斷 起源是在 byte[] difileByte = System.IO.File.ReadAllBytes(xdiFileName); 目的是在 inputXml = sr.ReadToEnd();

rainmakerho commented 1 year ago

似乎是 Checkmarx 的 Bug,原廠有回覆再更新。 看程式碼,後面的 I/O 似乎是要取得正確的字串(BIG5/UTF8/UTF8 BOM), 可以參考 透過比較編碼的 Byte 數,取得 BIG5/UTF8/UTF8 BOM 檔案正確的內容 直接取回正確的字串來避掉後面的 I/O 。

//var filePath = @"c:\temp\utf8.txt";
var filePath = @"c:\temp\utf8BOM.txt";
//var filePath = @"c:\temp\big5.txt";
var fileBytes = System.IO.File.ReadAllBytes(filePath);
//判斷是否為 Big5 編碼
var big5 = Encoding.GetEncoding(950);
var utf8 = Encoding.UTF8;
var big5String = big5.GetString(fileBytes);
var isBig5 = fileBytes.Length == big5.GetByteCount(big5String);
//取出正確的內容
var fileContent = isBig5 ?
    big5String :
    utf8.GetString(fileBytes);
Console.WriteLine(fileContent);