1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.bcel.util;
21
22 import static org.junit.jupiter.api.Assertions.assertFalse;
23 import static org.junit.jupiter.api.Assertions.assertTrue;
24
25 import java.io.File;
26 import java.nio.charset.StandardCharsets;
27 import java.nio.file.Files;
28
29 import org.apache.bcel.Const;
30 import org.apache.bcel.classfile.JavaClass;
31 import org.apache.bcel.generic.ClassGen;
32 import org.apache.bcel.generic.FieldGen;
33 import org.apache.bcel.generic.Type;
34 import org.junit.jupiter.api.Test;
35
36 class Class2HTMLXSSTest {
37
38
39
40
41
42 @Test
43 void testFieldNameIsEscaped() throws Exception {
44 final ClassGen cg = new ClassGen("Evil", "java.lang.Object", "Evil.java", Const.ACC_PUBLIC, null);
45 cg.addField(new FieldGen(Const.ACC_PUBLIC, Type.INT, "x<script>alert(1)</script>", cg.getConstantPool()).getField());
46 final JavaClass jc = cg.getJavaClass();
47
48 final File outputDir = new File("target/test-output/html-xss");
49 if (!outputDir.mkdirs()) {
50 assertTrue(outputDir.isDirectory());
51 }
52 new Class2HTML(jc, outputDir.getAbsolutePath() + File.separator);
53
54 final String methods = new String(Files.readAllBytes(new File(outputDir, "Evil_methods.html").toPath()), StandardCharsets.UTF_8);
55
56 assertFalse(methods.contains("\">x<script>"), "field name was emitted unescaped in text context");
57 assertTrue(methods.contains("<script>"), "expected the field name to be HTML-escaped");
58 }
59
60
61
62
63
64 @Test
65 void testFieldNameQuotesAreEscapedInAttributeContext() throws Exception {
66 final ClassGen cg = new ClassGen("Evil2", "java.lang.Object", "Evil2.java", Const.ACC_PUBLIC, null);
67 cg.addField(new FieldGen(Const.ACC_PUBLIC, Type.INT, "x\" onmouseover=\"alert(1)", cg.getConstantPool()).getField());
68 final JavaClass jc = cg.getJavaClass();
69
70 final File outputDir = new File("target/test-output/html-xss");
71 if (!outputDir.mkdirs()) {
72 assertTrue(outputDir.isDirectory());
73 }
74 new Class2HTML(jc, outputDir.getAbsolutePath() + File.separator);
75
76 final String methods = new String(Files.readAllBytes(new File(outputDir, "Evil2_methods.html").toPath()), StandardCharsets.UTF_8);
77 assertFalse(methods.contains("x\" onmouseover"), "field name broke out of the attribute context");
78 assertTrue(methods.contains("x" onmouseover"), "expected quotes in the field name to be escaped");
79 }
80 }