This is an automated email from the ASF dual-hosted git repository.

garydgregory pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/commons-bcel.git


The following commit(s) were added to refs/heads/master by this push:
     new 095e916c Fix Class2HTML report URLs for special-character class names
095e916c is described below

commit 095e916c1d8c6f3f481275f51374b8cc9c7e4d42
Author: Gary Gregory <[email protected]>
AuthorDate: Fri Nov 20 07:36:09 2026 -0500

    Fix Class2HTML report URLs for special-character class names
    
    Reject '#' and '%' in class names before creating report files.
    Percent-encode accepted names as UTF-8 filename components in links
    and frame sources across all five report writers. Encode spaces as
    %20 so leading spaces and HTML character references cannot change
    the target filename.
    
    Expand regression tests to round-trip class files through the parser
    and verify report file targets, exact rejection diagnostics, CLI
    propagation, and the absence of partial output.
---
 src/changes/changes.xml                            |   1 +
 .../java/org/apache/bcel/util/AttributeHTML.java   |  18 +--
 src/main/java/org/apache/bcel/util/Class2HTML.java |  38 +++--
 src/main/java/org/apache/bcel/util/CodeHTML.java   |  16 +-
 .../java/org/apache/bcel/util/ConstantHTML.java    |  14 +-
 src/main/java/org/apache/bcel/util/MethodHTML.java |   8 +-
 .../apache/bcel/util/Class2HTMLTraversalTest.java  | 162 ++++++++++++++++++---
 7 files changed, 199 insertions(+), 58 deletions(-)

diff --git a/src/changes/changes.xml b/src/changes/changes.xml
index 853f59f8..821494ea 100644
--- a/src/changes/changes.xml
+++ b/src/changes/changes.xml
@@ -64,6 +64,7 @@ The <action> type attribute can be add,update,fix,remove.
       <action                  type="fix" dev="ggregory" due-to="Naveed Khan, 
Gary Gregory">InstConstraintVisitor check objectref class in getfield and 
putfield verification (#547).</action>
       <action                  type="fix" dev="ggregory" due-to="hataehoon, 
Gary Gregory">Escape unknown method attribute names in Class2HTML code 
reports.</action>
       <action                  type="fix" dev="ggregory" due-to="Gary 
Gregory">Fix Class2HTML ArrayIndexOutOfBoundsException for unknown Code 
sub-attributes and render their descriptions with HTML escaping.</action>
+      <action                  type="fix" dev="ggregory" due-to="Gary 
Gregory">Reject class names containing '#' or '%' before generating Class2HTML 
reports, and encode report links for accepted names containing spaces, 
ampersands, and other special characters.</action>
       <!-- ADD -->
       <!-- UPDATE -->
       <action                  type="update" dev="ggregory" due-to="Gary 
Gregory">Bump org.apache.commons:commons-lang3 from 3.21.0 to 3.22.0.</action>
diff --git a/src/main/java/org/apache/bcel/util/AttributeHTML.java 
b/src/main/java/org/apache/bcel/util/AttributeHTML.java
index 950d74fd..95f24834 100644
--- a/src/main/java/org/apache/bcel/util/AttributeHTML.java
+++ b/src/main/java/org/apache/bcel/util/AttributeHTML.java
@@ -44,7 +44,7 @@ import org.apache.bcel.classfile.Utility;
  */
 final class AttributeHTML implements Closeable {
 
-    private final String className; // name of current class
+    private final String classNameRef; // encoded name for links to the 
current class
     private final PrintWriter printWriter; // file to write to
     private int attrCount;
     private final ConstantHTML constantHtml;
@@ -52,7 +52,7 @@ final class AttributeHTML implements Closeable {
 
     AttributeHTML(final String dir, final String className, final ConstantPool 
constantPool, final ConstantHTML constantHtml, final Charset charset)
         throws FileNotFoundException, UnsupportedEncodingException {
-        this.className = className;
+        this.classNameRef = Class2HTML.toHTMLRef(className);
         this.constantPool = constantPool;
         this.constantHtml = constantHtml;
         printWriter = new PrintWriter(dir + className + "_attributes.html", 
charset.name());
@@ -69,7 +69,7 @@ final class AttributeHTML implements Closeable {
     }
 
     private String codeLink(final int link, final int methodNumber) {
-        return "<A HREF=\"" + className + "_code.html#code" + methodNumber + 
"@" + link + "\" TARGET=Code>" + link + "</A>";
+        return "<A HREF=\"" + classNameRef + "_code.html#code" + methodNumber 
+ "@" + link + "\" TARGET=Code>" + link + "</A>";
     }
 
     void writeAttribute(final Attribute attribute, final String anchor) {
@@ -97,7 +97,7 @@ final class AttributeHTML implements Closeable {
             final Code c = (Code) attribute;
             // Some directly printable values
             printWriter.print("<UL><LI>Maximum stack size = " + 
c.getMaxStack() + "</LI>\n<LI>Number of local variables = " + c.getMaxLocals()
-                + "</LI>\n<LI><A HREF=\"" + className + "_code.html#method" + 
methodNumber + "\" TARGET=Code>Byte code</A></LI></UL>\n");
+                + "</LI>\n<LI><A HREF=\"" + classNameRef + "_code.html#method" 
+ methodNumber + "\" TARGET=Code>Byte code</A></LI></UL>\n");
             // Get handled exceptions and list them
             final CodeException[] ce = c.getExceptionTable();
             final int len = ce.length;
@@ -121,13 +121,13 @@ final class AttributeHTML implements Closeable {
             index = ((ConstantValue) attribute).getConstantValueIndex();
             // Reference _cp.html
             printWriter
-                .print("<UL><LI><A HREF=\"" + className + "_cp.html#cp" + 
index + "\" TARGET=\"ConstantPool\">Constant value index(" + index + 
")</A></UL>\n");
+                .print("<UL><LI><A HREF=\"" + classNameRef + "_cp.html#cp" + 
index + "\" TARGET=\"ConstantPool\">Constant value index(" + index + 
")</A></UL>\n");
             break;
         case Const.ATTR_SOURCE_FILE:
             index = ((SourceFile) attribute).getSourceFileIndex();
             // Reference _cp.html
             printWriter
-                .print("<UL><LI><A HREF=\"" + className + "_cp.html#cp" + 
index + "\" TARGET=\"ConstantPool\">Source file index(" + index + 
")</A></UL>\n");
+                .print("<UL><LI><A HREF=\"" + classNameRef + "_cp.html#cp" + 
index + "\" TARGET=\"ConstantPool\">Source file index(" + index + 
")</A></UL>\n");
             break;
         case Const.ATTR_EXCEPTIONS:
             // List thrown exceptions
@@ -135,7 +135,7 @@ final class AttributeHTML implements Closeable {
             printWriter.print("<UL>");
             for (final int indice : indices) {
                 printWriter
-                    .print("<LI><A HREF=\"" + className + "_cp.html#cp" + 
indice + "\" TARGET=\"ConstantPool\">Exception class index(" + indice + 
")</A>\n");
+                    .print("<LI><A HREF=\"" + classNameRef + "_cp.html#cp" + 
indice + "\" TARGET=\"ConstantPool\">Exception class index(" + indice + 
")</A>\n");
             }
             printWriter.print("</UL>\n");
             break;
@@ -160,8 +160,8 @@ final class AttributeHTML implements Closeable {
                 final int start = var.getStartPC();
                 final int end = start + var.getLength();
                 printWriter.println("<LI>" + 
Class2HTML.referenceType(signature) + "&nbsp;<B>" + 
Class2HTML.toHTML(var.getName()) + "</B> in slot %" + var.getIndex()
-                        + "<BR>Valid from lines <A HREF=\"" + className + 
"_code.html#code" + methodNumber + "@" + start + "\" TARGET=Code>" + start
-                        + "</A> to <A HREF=\"" + className + "_code.html#code" 
+ methodNumber + "@" + end + "\" TARGET=Code>" + end + "</A></LI>");
+                        + "<BR>Valid from lines <A HREF=\"" + classNameRef + 
"_code.html#code" + methodNumber + "@" + start + "\" TARGET=Code>" + start
+                        + "</A> to <A HREF=\"" + classNameRef + 
"_code.html#code" + methodNumber + "@" + end + "\" TARGET=Code>" + end + 
"</A></LI>");
             });
             printWriter.print("</UL>\n");
             break;
diff --git a/src/main/java/org/apache/bcel/util/Class2HTML.java 
b/src/main/java/org/apache/bcel/util/Class2HTML.java
index f48eb908..5b242395 100644
--- a/src/main/java/org/apache/bcel/util/Class2HTML.java
+++ b/src/main/java/org/apache/bcel/util/Class2HTML.java
@@ -23,6 +23,7 @@ import java.io.FileNotFoundException;
 import java.io.IOException;
 import java.io.PrintWriter;
 import java.io.UnsupportedEncodingException;
+import java.net.URLEncoder;
 import java.nio.charset.Charset;
 import java.nio.charset.StandardCharsets;
 import java.util.HashSet;
@@ -57,6 +58,7 @@ public class Class2HTML implements Constants {
 
     private static String classPackage; // name of package, unclean to make it 
static, but ...
     private static String className; // name of current class, ditto
+    private static String classNameRef; // encoded name for links to the 
current class
     private static ConstantPool constantPool;
     private static final Set<String> basicTypes = new HashSet<>();
     static {
@@ -73,18 +75,20 @@ public class Class2HTML implements Constants {
 
     /**
      * The class name comes from the attacker-controlled this_class constant 
of the parsed class file and is
-     * concatenated into the five output file paths ("dir + className + 
suffix"). Class file parsing only folds
-     * '/' into '.', so Windows separators ('\\'), drive designators (':') and 
".." segments survive and would
-     * let a crafted class file write its HTML output outside the target 
directory (CWE-22).
+     * concatenated into the five output file paths ("dir + className + 
suffix") and into the report's own
+     * self-referential links (HREF/SRC values). Class file parsing only folds 
'/' into '.', so Windows separators
+     * ('\\'), drive designators (':') and ".." segments survive and would let 
a crafted class file write its HTML
+     * output outside the target directory (CWE-22). The '#' and '%' 
characters are also rejected in output file names.
+     * Accepted names are encoded separately for use in the report's links.
      *
-     * @param name the class name about to be used as part of a file name.
+     * @param name the class name about to be used as part of a file name and 
of the report's own links.
      * @throws IOException Thrown if the name contains a path separator, a 
Windows-reserved file name character, a
-     *         control character, or a ".." sequence.
+     *         control character, a '#' or '%', or a ".." sequence.
      */
     private static void checkFileNameSafe(final String name) throws 
IOException {
         for (int i = 0; i < name.length(); i++) {
             final char c = name.charAt(i);
-            if (c < ' ' || "\\/:*?\"<>|".indexOf(c) >= 0) {
+            if (c < ' ' || "\\/:*?\"<>|#%".indexOf(c) >= 0) {
                 throw new IOException("Refusing to write HTML for a class 
whose name contains the unsafe character (0x"
                     + Integer.toHexString(c) + "): " + name);
             }
@@ -158,7 +162,7 @@ public class Class2HTML implements Constants {
         String str = constantPool.getConstantString(index, 
Const.CONSTANT_Class);
         str = Utility.compactClassName(str);
         str = Utility.compactClassName(str, classPackage + ".", true);
-        return "<A HREF=\"" + className + "_cp.html#cp" + index + "\" 
TARGET=ConstantPool>" + toHTML(str) + "</A>";
+        return "<A HREF=\"" + classNameRef + "_cp.html#cp" + index + "\" 
TARGET=ConstantPool>" + toHTML(str) + "</A>";
     }
 
     static String referenceType(final String type) {
@@ -210,12 +214,15 @@ public class Class2HTML implements Constants {
     }
 
     /**
-     * Escapes a class or type name taken from the constant pool for use as a 
relative link target inside an HREF
-     * attribute value. On top of the text escaping done by {@code 
toHTML(String)}, any ':' is replaced so an
-     * attacker-chosen name cannot smuggle a URL scheme such as "javascript:" 
into the generated link.
+     * Encodes a class or type name as a UTF-8 file name in an HTML link. 
Spaces use percent escapes rather than the form encoding's plus signs, and HTML
+     * metacharacters are percent-encoded as well. Any ':' is replaced so a 
name cannot introduce a URL scheme such as "javascript:".
      */
     static String toHTMLRef(final String str) {
-        return toHTML(str.replace(':', '_'));
+        try {
+            return URLEncoder.encode(str.replace(':', '_'), 
StandardCharsets.UTF_8.name()).replace("+", "%20");
+        } catch (final UnsupportedEncodingException ex) {
+            throw new IllegalStateException(ex);
+        }
     }
 
     private final JavaClass javaClass; // current class object
@@ -239,6 +246,7 @@ public class Class2HTML implements Constants {
         this.dir = dir;
         className = javaClass.getClassName(); // Remember full name
         checkFileNameSafe(className);
+        classNameRef = toHTMLRef(className);
         constantPool = javaClass.getConstantPool();
         // Get package name by tacking off everything after the last '.'
         final int index = className.lastIndexOf('.');
@@ -266,17 +274,17 @@ public class Class2HTML implements Constants {
                 + "<HEAD><TITLE>Documentation for " + toHTML(className) + 
"</TITLE></HEAD>\n"
                 + "<FRAMESET BORDER=1 cols=\"30%,*\">\n"
                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
-                + "<FRAME NAME=\"ConstantPool\" SRC=\"" + className + 
"_cp.html" + "\"\n"
+                + "<FRAME NAME=\"ConstantPool\" SRC=\"" + classNameRef + 
"_cp.html" + "\"\n"
                 + "MARGINWIDTH=\"0\" "
                 + "MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" SCROLLING=\"AUTO\">\n"
-                + "<FRAME NAME=\"Attributes\" SRC=\"" + className + 
"_attributes.html\"\n"
+                + "<FRAME NAME=\"Attributes\" SRC=\"" + classNameRef + 
"_attributes.html\"\n"
                 + " MARGINWIDTH=\"0\" MARGINHEIGHT=\"0\" FRAMEBORDER=\"1\" 
SCROLLING=\"AUTO\">\n"
                 + "</FRAMESET>\n"
                 + "<FRAMESET BORDER=1 rows=\"80%,*\">\n"
-                + "<FRAME NAME=\"Code\" SRC=\"" + className + "_code.html\"\n"
+                + "<FRAME NAME=\"Code\" SRC=\"" + classNameRef + 
"_code.html\"\n"
                 + " MARGINWIDTH=0 "
                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
-                + "<FRAME NAME=\"Methods\" SRC=\"" + className + 
"_methods.html\"\n"
+                + "<FRAME NAME=\"Methods\" SRC=\"" + classNameRef + 
"_methods.html\"\n"
                 + " MARGINWIDTH=0 "
                 + "MARGINHEIGHT=0 FRAMEBORDER=1 SCROLLING=\"AUTO\">\n"
                 + "</FRAMESET></FRAMESET></HTML>");
diff --git a/src/main/java/org/apache/bcel/util/CodeHTML.java 
b/src/main/java/org/apache/bcel/util/CodeHTML.java
index 71ab7ceb..07111bdf 100644
--- a/src/main/java/org/apache/bcel/util/CodeHTML.java
+++ b/src/main/java/org/apache/bcel/util/CodeHTML.java
@@ -45,6 +45,7 @@ final class CodeHTML {
 
     private static boolean wide;
     private final String className; // name of current class
+    private final String classNameRef; // encoded name for links to the 
current class
     // private Method[] methods; // Methods to print
     private final PrintWriter printWriter; // file to write to
     private BitSet gotoSet;
@@ -54,6 +55,7 @@ final class CodeHTML {
     CodeHTML(final String dir, final String className, final Method[] methods, 
final ConstantPool constantPool, final ConstantHTML constantHtml,
         final Charset charset) throws IOException {
         this.className = className;
+        this.classNameRef = Class2HTML.toHTMLRef(className);
 //        this.methods = methods;
         this.constantPool = constantPool;
         this.constantHtml = constantHtml;
@@ -243,7 +245,7 @@ final class CodeHTML {
             index = c1.getNameAndTypeIndex();
             final String fieldName = constantPool.constantToString(index, 
Const.CONSTANT_NameAndType);
             if (name.equals(className)) { // Local field
-                buf.append("<A 
HREF=\"").append(className).append("_methods.html#field").append(Class2HTML.toHTML(fieldName)).append("\"
 TARGET=Methods>")
+                buf.append("<A 
HREF=\"").append(classNameRef).append("_methods.html#field").append(Class2HTML.toHTML(fieldName)).append("\"
 TARGET=Methods>")
                     .append(Class2HTML.toHTML(fieldName)).append("</A>\n");
             } else {
                 
buf.append(constantHtml.referenceConstant(classIndex)).append(".").append(Class2HTML.toHTML(fieldName));
@@ -298,7 +300,7 @@ final class CodeHTML {
             signature = constantPool.constantToString(c2.getSignatureIndex(), 
Const.CONSTANT_Utf8);
             final String[] args = 
Utility.methodSignatureArgumentTypes(signature, false);
             final String type = Utility.methodSignatureReturnType(signature, 
false);
-            buf.append(name).append(".<A 
HREF=\"").append(className).append("_cp.html#cp").append(mIndex).append("\" 
TARGET=ConstantPool>").append(str)
+            buf.append(name).append(".<A 
HREF=\"").append(classNameRef).append("_cp.html#cp").append(mIndex).append("\" 
TARGET=ConstantPool>").append(str)
                 .append("</A>").append("(");
             // List arguments
             for (int i = 0; i < args.length; i++) {
@@ -316,12 +318,12 @@ final class CodeHTML {
         case Const.LDC_W:
         case Const.LDC2_W:
             index = bytes.readUnsignedShort();
-            buf.append("<A 
HREF=\"").append(className).append("_cp.html#cp").append(index).append("\" 
TARGET=\"ConstantPool\">")
+            buf.append("<A 
HREF=\"").append(classNameRef).append("_cp.html#cp").append(index).append("\" 
TARGET=\"ConstantPool\">")
                 .append(Class2HTML.toHTML(constantPool.constantToString(index, 
constantPool.getConstant(index).getTag()))).append("</a>");
             break;
         case Const.LDC:
             index = bytes.readUnsignedByte();
-            buf.append("<A 
HREF=\"").append(className).append("_cp.html#cp").append(index).append("\" 
TARGET=\"ConstantPool\">")
+            buf.append("<A 
HREF=\"").append(classNameRef).append("_cp.html#cp").append(index).append("\" 
TARGET=\"ConstantPool\">")
                 .append(Class2HTML.toHTML(constantPool.constantToString(index, 
constantPool.getConstant(index).getTag()))).append("</a>");
             break;
         /*
@@ -503,7 +505,7 @@ final class CodeHTML {
         // Get the method's attributes, the Code Attribute in particular
         final Attribute[] attributes = method.getAttributes();
         printWriter.print("<P><B><FONT COLOR=\"#FF0000\">" + access + 
"</FONT>&nbsp;<A NAME=method" + methodNumber + ">" + 
Class2HTML.referenceType(type)
-            + "</A>&nbsp<A HREF=\"" + className + "_methods.html#method" + 
methodNumber + "\" TARGET=Methods>" + htmlName + "</A>(");
+            + "</A>&nbsp<A HREF=\"" + classNameRef + "_methods.html#method" + 
methodNumber + "\" TARGET=Methods>" + htmlName + "</A>(");
         for (int i = 0; i < args.length; i++) {
             printWriter.print(Class2HTML.referenceType(args[i]));
             if (i < args.length - 1) {
@@ -518,7 +520,7 @@ final class CodeHTML {
             for (int i = 0; i < attributes.length; i++) {
                 byte tag = attributes[i].getTag();
                 if (tag != Const.ATTR_UNKNOWN) {
-                    printWriter.print("<LI><A HREF=\"" + className + 
"_attributes.html#method" + methodNumber + "@" + i + "\" TARGET=Attributes>"
+                    printWriter.print("<LI><A HREF=\"" + classNameRef + 
"_attributes.html#method" + methodNumber + "@" + i + "\" TARGET=Attributes>"
                         + Const.getAttributeName(tag) + "</A></LI>\n");
                 } else {
                     printWriter.print("<LI>" + 
Class2HTML.toHTML(String.valueOf(attributes[i])) + "</LI>");
@@ -531,7 +533,7 @@ final class CodeHTML {
                     for (int j = 0; j < attributes2.length; j++) {
                         tag = attributes2[j].getTag();
                         if (tag != Const.ATTR_UNKNOWN) {
-                            printWriter.print("<LI><A HREF=\"" + className + 
"_attributes.html#method" + methodNumber + "@" + i + "@" + j
+                            printWriter.print("<LI><A HREF=\"" + classNameRef 
+ "_attributes.html#method" + methodNumber + "@" + i + "@" + j
                                 + "\" TARGET=Attributes>" + 
Const.getAttributeName(tag) + "</A></LI>\n");
                         } else {
                             printWriter.print("<LI>" + 
Class2HTML.toHTML(String.valueOf(attributes2[j])) + "</LI>\n");
diff --git a/src/main/java/org/apache/bcel/util/ConstantHTML.java 
b/src/main/java/org/apache/bcel/util/ConstantHTML.java
index 953ee1f9..3d1272d5 100644
--- a/src/main/java/org/apache/bcel/util/ConstantHTML.java
+++ b/src/main/java/org/apache/bcel/util/ConstantHTML.java
@@ -41,6 +41,7 @@ import org.apache.bcel.classfile.Utility;
 final class ConstantHTML {
 
     private final String className; // name of current class
+    private final String classNameRef; // encoded name for links to the 
current class
     private final String classPackage; // name of package
     private final ConstantPool constantPool; // reference to constant pool
     private final PrintWriter printWriter; // file to write to
@@ -51,6 +52,7 @@ final class ConstantHTML {
     ConstantHTML(final String dir, final String className, final String 
classPackage, final Method[] methods, final ConstantPool constantPool,
         final Charset charset) throws FileNotFoundException, 
UnsupportedEncodingException {
         this.className = className;
+        this.classNameRef = Class2HTML.toHTMLRef(className);
         this.classPackage = classPackage;
         this.constantPool = constantPool;
         this.methods = methods;
@@ -142,12 +144,12 @@ final class ConstantHTML {
             buf.append(")");
             final String argTypes = buf.toString();
             if (methodClass.equals(className)) {
-                ref = "<A HREF=\"" + className + "_code.html#method" + 
getMethodNumber(methodName + signature) + "\" TARGET=Code>" + htmlMethodName + 
"</A>";
+                ref = "<A HREF=\"" + classNameRef + "_code.html#method" + 
getMethodNumber(methodName + signature) + "\" TARGET=Code>" + htmlMethodName + 
"</A>";
             } else {
                 ref = "<A HREF=\"" + Class2HTML.toHTMLRef(methodClass) + 
".html\" TARGET=_top>" + shortMethodClass + "</A>." + htmlMethodName;
             }
-            constantRef[index] = retType + "&nbsp;<A HREF=\"" + className + 
"_cp.html#cp" + classIndex + "\" TARGET=Constants>" + shortMethodClass
-                + "</A>.<A HREF=\"" + className + "_cp.html#cp" + index + "\" 
TARGET=ConstantPool>" + htmlMethodName + "</A>&nbsp;" + argTypes;
+            constantRef[index] = retType + "&nbsp;<A HREF=\"" + classNameRef + 
"_cp.html#cp" + classIndex + "\" TARGET=Constants>" + shortMethodClass
+                + "</A>.<A HREF=\"" + classNameRef + "_cp.html#cp" + index + 
"\" TARGET=ConstantPool>" + htmlMethodName + "</A>&nbsp;" + argTypes;
             printWriter.println("<P><TT>" + retType + "&nbsp;" + ref + 
argTypes + "&nbsp;</TT>\n<UL><LI><A HREF=\"#cp" + classIndex + "\">Class index("
                 + classIndex + ")</A>\n" + "<LI><A HREF=\"#cp" + nameIndex + 
"\">NameAndType index(" + nameIndex + ")</A></UL>");
             break;
@@ -168,8 +170,8 @@ final class ConstantHTML {
             } else {
                 ref = "<A HREF=\"" + Class2HTML.toHTMLRef(fieldClass) + 
".html\" TARGET=_top>" + shortFieldClass + "</A>." + htmlFieldName + "\n";
             }
-            constantRef[index] = "<A HREF=\"" + className + "_cp.html#cp" + 
classIndex + "\" TARGET=Constants>" + shortFieldClass + "</A>.<A HREF=\""
-                + className + "_cp.html#cp" + index + "\" 
TARGET=ConstantPool>" + htmlFieldName + "</A>";
+            constantRef[index] = "<A HREF=\"" + classNameRef + "_cp.html#cp" + 
classIndex + "\" TARGET=Constants>" + shortFieldClass + "</A>.<A HREF=\""
+                + classNameRef + "_cp.html#cp" + index + "\" 
TARGET=ConstantPool>" + htmlFieldName + "</A>";
             printWriter.println("<P><TT>" + ref + "</TT><BR>\n" + "<UL>" + 
"<LI><A HREF=\"#cp" + classIndex + "\">Class(" + classIndex + ")</A><BR>\n"
                 + "<LI><A HREF=\"#cp" + nameIndex + "\">NameAndType(" + 
nameIndex + ")</A></UL>");
             break;
@@ -181,7 +183,7 @@ final class ConstantHTML {
             shortClassName = Utility.compactClassName(shortClassName, 
classPackage + ".", true); // Remove class package prefix
             shortClassName = Class2HTML.toHTML(shortClassName);
             ref = "<A HREF=\"" + Class2HTML.toHTMLRef(className2) + ".html\" 
TARGET=_top>" + shortClassName + "</A>";
-            constantRef[index] = "<A HREF=\"" + className + "_cp.html#cp" + 
index + "\" TARGET=ConstantPool>" + shortClassName + "</A>";
+            constantRef[index] = "<A HREF=\"" + classNameRef + "_cp.html#cp" + 
index + "\" TARGET=ConstantPool>" + shortClassName + "</A>";
             printWriter.println("<P><TT>" + ref + "</TT><UL>" + "<LI><A 
HREF=\"#cp" + nameIndex + "\">Name index(" + nameIndex + ")</A></UL>\n");
             break;
         case Const.CONSTANT_String:
diff --git a/src/main/java/org/apache/bcel/util/MethodHTML.java 
b/src/main/java/org/apache/bcel/util/MethodHTML.java
index 8b43ea2d..b6759af9 100644
--- a/src/main/java/org/apache/bcel/util/MethodHTML.java
+++ b/src/main/java/org/apache/bcel/util/MethodHTML.java
@@ -36,14 +36,14 @@ import org.apache.bcel.classfile.Utility;
  */
 final class MethodHTML {
 
-    private final String className; // name of current class
+    private final String classNameRef; // encoded name for links to the 
current class
     private final PrintWriter printWriter; // file to write to
     private final ConstantHTML constantHtml;
     private final AttributeHTML attributeHtml;
 
     MethodHTML(final String dir, final String className, final Method[] 
methods, final Field[] fields, final ConstantHTML constantHtml,
         final AttributeHTML attributeHtml, final Charset charset) throws 
FileNotFoundException, UnsupportedEncodingException {
-        this.className = className;
+        this.classNameRef = Class2HTML.toHTMLRef(className);
         this.attributeHtml = attributeHtml;
         this.constantHtml = constantHtml;
         try (PrintWriter newPrintWriter = new PrintWriter(dir + className + 
"_methods.html", charset.name())) {
@@ -88,7 +88,7 @@ final class MethodHTML {
             if (attributes[i].getTag() == Const.ATTR_CONSTANT_VALUE) { // 
Default value
                 final String str = attributes[i].toString();
                 // Reference attribute in _attributes.html
-                printWriter.print("<TD>= <A HREF=\"" + className + 
"_attributes.html#" + Class2HTML.toHTML(name) + "@" + i + "\" 
TARGET=\"Attributes\">"
+                printWriter.print("<TD>= <A HREF=\"" + classNameRef + 
"_attributes.html#" + Class2HTML.toHTML(name) + "@" + i + "\" 
TARGET=\"Attributes\">"
                     + Class2HTML.toHTML(str) + "</TD>\n");
                 break;
             }
@@ -115,7 +115,7 @@ final class MethodHTML {
         access = Utility.replace(access, " ", "&nbsp;");
         final String htmlName = Class2HTML.toHTML(name);
         printWriter.print("<TR VALIGN=TOP><TD><FONT COLOR=\"#FF0000\"><A 
NAME=method" + methodNumber + ">" + access + "</A></FONT></TD>");
-        printWriter.print("<TD>" + Class2HTML.referenceType(type) + 
"</TD><TD><A HREF=\"" + className + "_code.html#method" + methodNumber + "\" 
TARGET=Code>"
+        printWriter.print("<TD>" + Class2HTML.referenceType(type) + 
"</TD><TD><A HREF=\"" + classNameRef + "_code.html#method" + methodNumber + "\" 
TARGET=Code>"
             + htmlName + "</A></TD>\n<TD>(");
         for (int i = 0; i < args.length; i++) {
             printWriter.print(Class2HTML.referenceType(args[i]));
diff --git a/src/test/java/org/apache/bcel/util/Class2HTMLTraversalTest.java 
b/src/test/java/org/apache/bcel/util/Class2HTMLTraversalTest.java
index 0a4cf2de..215365ac 100644
--- a/src/test/java/org/apache/bcel/util/Class2HTMLTraversalTest.java
+++ b/src/test/java/org/apache/bcel/util/Class2HTMLTraversalTest.java
@@ -19,41 +19,169 @@
 
 package org.apache.bcel.util;
 
+import static org.junit.jupiter.api.Assertions.assertEquals;
+import static org.junit.jupiter.api.Assertions.assertFalse;
+import static org.junit.jupiter.api.Assertions.assertNull;
 import static org.junit.jupiter.api.Assertions.assertThrows;
 import static org.junit.jupiter.api.Assertions.assertTrue;
 
+import java.io.ByteArrayInputStream;
 import java.io.File;
 import java.io.IOException;
+import java.io.StringReader;
+import java.net.URI;
+import java.nio.charset.StandardCharsets;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Set;
+import java.util.stream.Stream;
+
+import javax.swing.text.MutableAttributeSet;
+import javax.swing.text.html.HTML;
+import javax.swing.text.html.HTMLEditorKit;
+import javax.swing.text.html.parser.ParserDelegator;
 
 import org.apache.bcel.Const;
+import org.apache.bcel.classfile.ClassParser;
 import org.apache.bcel.classfile.JavaClass;
 import org.apache.bcel.generic.ClassGen;
-import org.junit.jupiter.api.Test;
+import org.apache.bcel.generic.ConstantPoolGen;
+import org.apache.bcel.generic.FieldGen;
+import org.apache.bcel.generic.InstructionConst;
+import org.apache.bcel.generic.InstructionFactory;
+import org.apache.bcel.generic.InstructionList;
+import org.apache.bcel.generic.MethodGen;
+import org.apache.bcel.generic.Type;
+import org.junit.jupiter.api.io.TempDir;
+import org.junit.jupiter.params.ParameterizedTest;
+import org.junit.jupiter.params.provider.Arguments;
+import org.junit.jupiter.params.provider.MethodSource;
+import org.junit.jupiter.params.provider.ValueSource;
 
 /**
- * Output file paths are built as "dir + className + suffix" from the 
attacker-controlled this_class constant.
- * Names carrying Windows separators, drive designators or ".." must be 
rejected, or a crafted class file writes
- * its HTML outside the target directory.
+ * Tests that unsafe class names are rejected before any report files are 
written and that accepted names produce working report links.
  */
 class Class2HTMLTraversalTest {
 
-    private static File outputDir() {
-        final File outputDir = new File("target/test-output/html-traversal");
-        if (!outputDir.mkdirs()) {
-            assertTrue(outputDir.isDirectory());
+    private static JavaClass createClass(final String className) throws 
IOException {
+        final ClassGen cg = new ClassGen(className, "java.lang.Object", 
"Example.java", Const.ACC_PUBLIC, null);
+        final ConstantPoolGen cp = cg.getConstantPool();
+        final FieldGen field = new FieldGen(Const.ACC_PUBLIC | 
Const.ACC_STATIC | Const.ACC_FINAL, Type.INT, "answer", cp);
+        field.setInitValue(42);
+        cg.addField(field.getField());
+        cg.addEmptyConstructor(Const.ACC_PUBLIC);
+        final InstructionFactory factory = new InstructionFactory(cg);
+        final InstructionList instructions = new InstructionList();
+        instructions.append(factory.createGetStatic(className, "answer", 
Type.INT));
+        instructions.append(InstructionConst.IRETURN);
+        final MethodGen read = new MethodGen(Const.ACC_PUBLIC | 
Const.ACC_STATIC, Type.INT, Type.NO_ARGS, null, "read", className, 
instructions, cp);
+        read.addLineNumber(instructions.getStart(), 1);
+        read.setMaxStack();
+        read.setMaxLocals();
+        cg.addMethod(read.getMethod());
+        instructions.dispose();
+        final InstructionList callerInstructions = new InstructionList();
+        callerInstructions.append(factory.createInvoke(className, "read", 
Type.INT, Type.NO_ARGS, Const.INVOKESTATIC));
+        callerInstructions.append(InstructionConst.IRETURN);
+        final MethodGen call = new MethodGen(Const.ACC_PUBLIC | 
Const.ACC_STATIC, Type.INT, Type.NO_ARGS, null, "call", className, 
callerInstructions, cp);
+        call.setMaxStack();
+        call.setMaxLocals();
+        cg.addMethod(call.getMethod());
+        callerInstructions.dispose();
+        return new ClassParser(new 
ByteArrayInputStream(cg.getJavaClass().getBytes()), "Example.class").parse();
+    }
+
+    private static List<String> getLinks(final String html) throws IOException 
{
+        final List<String> links = new ArrayList<>();
+        new ParserDelegator().parse(new StringReader(html), new 
HTMLEditorKit.ParserCallback() {
+            private void addLinks(final MutableAttributeSet attributes) {
+                for (final HTML.Attribute attribute : new HTML.Attribute[] 
{HTML.Attribute.HREF, HTML.Attribute.SRC}) {
+                    final Object value = attributes.getAttribute(attribute);
+                    if (value != null) {
+                        links.add(value.toString());
+                    }
+                }
+            }
+
+            @Override
+            public void handleSimpleTag(final HTML.Tag tag, final 
MutableAttributeSet attributes, final int position) {
+                addLinks(attributes);
+            }
+
+            @Override
+            public void handleStartTag(final HTML.Tag tag, final 
MutableAttributeSet attributes, final int position) {
+                addLinks(attributes);
+            }
+        }, true);
+        return links;
+    }
+
+    private static Stream<Arguments> unsafeClassNames() {
+        return Stream.of(
+            Arguments.of("C:pwn", "3a"),
+            Arguments.of("..\\..\\pwn", "5c"),
+            Arguments.of("Evil#Fragment", "23"),
+            Arguments.of("Evil%2FPath", "25"));
+    }
+
+    @ParameterizedTest
+    @ValueSource(strings = {"Example", "A&B C", "A&copy B", " LeadingSpace", 
"A'B", "A+B", "Euro€Class", "pkg.Dollar$Class"})
+    void testAcceptedClassNameLinks(final String className, @TempDir final 
Path outputDir) throws IOException {
+        new Class2HTML(createClass(className), outputDir + File.separator);
+        try (Stream<Path> files = Files.list(outputDir)) {
+            assertEquals(5, files.count());
+        }
+        final Set<String> expectedFiles = new HashSet<>();
+        for (final String suffix : new String[] {".html", "_attributes.html", 
"_code.html", "_cp.html", "_methods.html"}) {
+            expectedFiles.add(className + suffix);
         }
-        return outputDir;
+        final Set<String> referencedFiles = new HashSet<>();
+        for (final String fileName : expectedFiles) {
+            final String html = new 
String(Files.readAllBytes(outputDir.resolve(fileName)), StandardCharsets.UTF_8);
+            final List<String> links = getLinks(html);
+            assertFalse(links.isEmpty(), fileName);
+            for (final String link : links) {
+                assertEquals(link.trim(), link, "link must not lose leading 
spaces during URL parsing");
+                final int fragmentIndex = link.indexOf('#');
+                final URI uri = URI.create(fragmentIndex < 0 ? link : 
link.substring(0, fragmentIndex));
+                assertFalse(uri.isAbsolute(), link);
+                assertNull(uri.getRawAuthority(), link);
+                assertNull(uri.getRawQuery(), link);
+                final String target = uri.getPath();
+                if (!target.isEmpty() && 
!"java.lang.Object.html".equals(target)) {
+                    assertTrue(expectedFiles.contains(target), link);
+                    assertTrue(Files.isRegularFile(outputDir.resolve(target)), 
link);
+                    referencedFiles.add(target);
+                }
+            }
+        }
+        assertEquals(expectedFiles, referencedFiles);
     }
 
-    @Test
-    void testRejectsClassNameWithDriveDesignator() {
-        final JavaClass jc = new ClassGen("C:pwn", "java.lang.Object", 
"pwn.java", Const.ACC_PUBLIC, null).getJavaClass();
-        assertThrows(IOException.class, () -> new Class2HTML(jc, 
outputDir().getAbsolutePath() + File.separator));
+    @ParameterizedTest
+    @MethodSource("unsafeClassNames")
+    void testRejectsUnsafeClassName(final String className, final String 
codePoint, @TempDir final Path outputDir) throws IOException {
+        final JavaClass jc = createClass(className);
+        final IOException exception = assertThrows(IOException.class, () -> 
new Class2HTML(jc, outputDir + File.separator));
+        assertEquals("Refusing to write HTML for a class whose name contains 
the unsafe character (0x" + codePoint + "): " + className, 
exception.getMessage());
+        try (Stream<Path> files = Files.list(outputDir)) {
+            assertEquals(0, files.count(), "rejection must not leave partial 
reports");
+        }
     }
 
-    @Test
-    void testRejectsClassNameWithWindowsTraversal() {
-        final JavaClass jc = new ClassGen("..\\..\\pwn", "java.lang.Object", 
"pwn.java", Const.ACC_PUBLIC, null).getJavaClass();
-        assertThrows(IOException.class, () -> new Class2HTML(jc, 
outputDir().getAbsolutePath() + File.separator));
+    @ParameterizedTest
+    @MethodSource("unsafeClassNames")
+    void testRejectsUnsafeClassNameFromCli(final String className, final 
String codePoint, @TempDir final Path directory) throws IOException {
+        final Path input = directory.resolve("input.class");
+        createClass(className).dump(input.toString());
+        final Path outputDir = directory.resolve("reports");
+        final IOException exception = assertThrows(IOException.class, () -> 
Class2HTML.main(new String[] {"-d", outputDir.toString(), input.toString()}));
+        assertEquals("Refusing to write HTML for a class whose name contains 
the unsafe character (0x" + codePoint + "): " + className, 
exception.getMessage());
+        try (Stream<Path> files = Files.list(outputDir)) {
+            assertEquals(0, files.count(), "CLI rejection must not leave 
partial reports");
+        }
     }
 }

Reply via email to