title: Veracode - XSS Attack on HttpResponse BinaryWrite. How should it be fixed?
body: <p>The following is the <strong>c#</strong> 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.</p>
  
  <pre><code>using (HttpClient client = new HttpClient())
  {
  
      var apiUrl = &lt;APIServer&gt; + "/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&lt;string, string&gt;();
      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();
      }
  }
  </code></pre>
  
  <p>The following is the medium severity warning.</p>
  
  <blockquote>
    <p>CWD ID:80 Exploitability: Neutral Category: Improper Neutralization of
    Script-Related HTML Tags in a Web Page (Basic XSS)</p>
  </blockquote>
  
  <p>The application also has got a <em>Content Security Policy</em> set for all the responses. </p>
  
  <p>How should the API response with a byte array be handled safely for file download without any security vulnerability?</p>