如何修复ServletOutputStream中“网页中基于脚本的HTML标记的不正当中和(基本XSS)”

时间:2017-06-28 06:58:39

标签: java xss veracode

以下代码在out.write(outByte,0,iRead)行中给出了veracode漏洞“网页中与脚本相关的HTML标记的不正当中和”。 :

try {
    bytesImage = helper.getBlob(Integer.parseInt(id) );
    ByteArrayInputStream bin = new ByteArrayInputStream(bytesImage);
    ServletOutputStream out = response.getOutputStream();
    outByte = new byte[bytesImage.length];
    int iRead = 0;
    while ((iRead = bin.read(outByte)) > 0) {
        out.write(outByte,0,iRead); 
    }           


I found a lot of similar issues here but all with strings only. These coulde be fixed with something like this:

> out.write ( ESAPI.encoder().encodeForHTML(theSimpleString) );


but for the binary OutputStream this will not work.
Any hints how to get above veracode issue solved?

感谢

正如@sinkmanu所建议的,我试图将字节转换为String。然后应用ESAPI.encoder()。encodeForHTML()。

我添加了两种转换方法:

private static String base64Encode(byte[] bytes) {
   return new BASE64Encoder().encode(bytes);
}
private static byte[] base64Decode(String s) throws IOException {
   return new BASE64Decoder().decodeBuffer(s);
}        

然后尝试使用此代码:

...

bytes = helper.getBlob( inId );

// 1 -> this solves Veracode issue but image is not valid anymore
String encodedString = base64Encode(bytes) ; 
String safeString = ESAPI.encoder().encodeForHTML(encodedString);
safeBytes = base64Decode(safeString);

// 2 -> as written above, when i use the safe 'safeBytes' the Veracode flaw is gone but the app is not working anymore (image not ok)
// ByteArrayInputStream bin = new ByteArrayInputStream(safeBytes);
// outBytes = new byte[safeBytes.length];

// 3 -> just use the 'unsafe' bytes -> app is working but veracode flaw needs to be fixed!
ByteArrayInputStream bin = new ByteArrayInputStream(bytes);
outBytes = new byte[bytes.length];

int iRead=0;
ServletOutputStream out = response.getOutputStream();

while ((iRead = bin.read(outBytes)) > 0) {
    out.write(  outBytes, 0, iRead); 
}           

...

以上可以解决veracode问题(当2被取消注释时)但是图像似乎已经损坏(不能再进行处理了吗?)。 有什么提示我如何解决二进制流的veracode问题?

3 个答案:

答案 0 :(得分:1)

上面的解决方案是:

    String safeString = ESAPI.encoder().encodeForBase64(bytes,false);
    byte[] safeBytes = ESAPI.encoder().decodeFromBase64(safeString);

在ESAPI库中,还有从Base64编码和解码的方法。这是我的问题的解决方案。以上两行为veracode和使用" safeBytes"在以后的代码中,一切都很好......

答案 1 :(得分:0)

您可以使用以下功能验证文件: ESAPI.validator()。getValidFileContent()

答案 2 :(得分:0)

要清理字符串,您可以使用ESAPI库中的encodeForHTML或Apache中的StringEscapeUtils。

import static org.apache.commons.lang.StringEscapeUtils.escapeHtml;
String data = "<script>alert(document.cookie);</script>";
String escaped = escapeHtml(data);

如果您的数据不是String,则必须将其转换为String。此外,如果您确定您的数据已被转义,您可以忽略该警告,因为它是误报。