View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one
3    * or more contributor license agreements.  See the NOTICE file
4    * distributed with this work for additional information
5    * regarding copyright ownership.  The ASF licenses this file
6    * to you under the Apache License, Version 2.0 (the
7    * "License"); you may not use this file except in compliance
8    * with the License.  You may obtain a copy of the License at
9    *
10   *   https://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing,
13   * software distributed under the License is distributed on an
14   * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15   * KIND, either express or implied.  See the License for the
16   * specific language governing permissions and limitations
17   * under the License.
18   */
19  
20  package org.apache.bcel.util;
21  
22  import static org.junit.jupiter.api.Assertions.assertNull;
23  import static org.junit.jupiter.api.Assertions.assertThrows;
24  
25  import java.io.ByteArrayInputStream;
26  import java.io.InputStream;
27  
28  import org.apache.bcel.Const;
29  import org.apache.bcel.generic.ClassGen;
30  import org.junit.jupiter.api.Test;
31  
32  /**
33   * A class file served under one name whose this_class declares another name must not be returned or cached:
34   * repositories key their caches on the parsed name, so accepting the mismatch lets attacker bytes squat on
35   * an arbitrary class name JVM-wide (including the static org.apache.bcel.Repository facade and the
36   * VerifierFactory verdict cache).
37   */
38  class RepositoryNameMismatchTest {
39  
40      private static byte[] classBytes(final String className) {
41          return new ClassGen(className, "java.lang.Object", className + ".java", Const.ACC_PUBLIC, null).getJavaClass().getBytes();
42      }
43  
44      @Test
45      void testClassLoaderRepositoryRejectsMismatchedName() {
46          final byte[] bytes = classBytes("evil.Squatter");
47          final ClassLoader loader = new ClassLoader(getClass().getClassLoader()) {
48              @Override
49              public InputStream getResourceAsStream(final String name) {
50                  return "victim/Innocent.class".equals(name) ? new ByteArrayInputStream(bytes) : super.getResourceAsStream(name);
51              }
52          };
53          final ClassLoaderRepository repository = new ClassLoaderRepository(loader);
54          assertThrows(ClassNotFoundException.class, () -> repository.loadClass("victim.Innocent"));
55          assertNull(repository.findClass("evil.Squatter"), "mismatched class must not be cached under its declared name");
56          assertNull(repository.findClass("victim.Innocent"), "mismatched class must not be cached under the requested name");
57      }
58  }