Search code examples
c#asp.netstatic-code-analysisveracode

Veracode - XSS Attack on HttpResponse BinaryWrite. How should it be fixed?


The following is the c# code in a aspx file that gets a pdf file and downloads it. To generate the pdf, the API server is given a html template content.

using (HttpClient client = new HttpClient())
{

    var apiUrl = <APIServer> + "/api/GetPdfByteData";
    client.BaseAddress = new Uri(apiUrl);

    Template template = GetTemplate(); //Body property has got the HTML template
    string templateBody = template.Body;//html template 

    var values = new Dictionary<string, string>();
    values.Add("html", templateBody);

    var jsonStr = JsonConvert.SerializeObject(values);
    var stringContent = new StringContent(jsonStr, Encoding.UTF8, "application/json");

    //uses an API service to get the pdf content for the template 
    var response = client.PostAsync(apiUrl, stringContent).Result; //VERACODE - Basic XSS STARTED here
    var pdfContent = response.Content.ReadAsByteArrayAsync().Result;

    if (response.IsSuccessStatusCode)
    {
        Response.ContentType = "application/octet-stream";
        Response.Clear();
        Response.BinaryWrite(pdfContent);//VERACODE - this line has been highlighted for the XSS ENDED HERE 
        Response.AddHeader("Content-Length", pdfContent.Length.ToString());
        Response.AppendHeader("content-disposition", string.Format("attachment;FileName=\"testfile.pdf\""));
        Response.End();
    }
}

The following is the medium severity warning.

CWD ID:80 Exploitability: Neutral Category: Improper Neutralization of Script-Related HTML Tags in a Web Page (Basic XSS)

The application also has got a Content Security Policy set for all the responses.

How should the API response with a byte array be handled safely for file download without any security vulnerability?


Solution

  • I have added a piece of code to store the data in a secured temporary directory and do a scan on the files in the directory. This is to ensure there is no vulnerable or unwanted data, before streaming the file for download operation.

    This mitigated the issue highlighted by Veracode Analysis and the fix already passed the Static Code Analysis.