Repository navigation
Added allowed url property to URLContextClassLoaderFactory #6527
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Changes from all commits
75ed067
4fc944e
ecd4104
7311ddb
29e5802
1351df7
49586e8
2e8e0b3
6a59c84
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -18,16 +18,25 @@ | |
| */ | ||
| package org.apache.accumulo.core.classloader; | ||
|
|
||
| import static com.google.common.base.Preconditions.checkArgument; | ||
|
|
||
| import java.io.IOException; | ||
| import java.io.UncheckedIOException; | ||
| import java.net.MalformedURLException; | ||
| import java.net.URI; | ||
| import java.net.URISyntaxException; | ||
| import java.net.URL; | ||
| import java.net.URLClassLoader; | ||
| import java.nio.file.Path; | ||
| import java.util.Arrays; | ||
| import java.util.regex.Pattern; | ||
|
|
||
| import org.apache.accumulo.core.conf.Property; | ||
| import org.apache.accumulo.core.spi.common.ContextClassLoaderEnvironment; | ||
| import org.apache.accumulo.core.spi.common.ContextClassLoaderFactory; | ||
| import org.apache.accumulo.core.util.cache.Caches; | ||
| import org.apache.accumulo.core.util.cache.Caches.CacheName; | ||
| import org.apache.hadoop.conf.Configuration; | ||
| import org.apache.hadoop.fs.FileSystem; | ||
| import org.slf4j.Logger; | ||
| import org.slf4j.LoggerFactory; | ||
|
|
||
|
|
@@ -42,26 +51,80 @@ public class URLContextClassLoaderFactory implements ContextClassLoaderFactory { | |
|
|
||
| private static final Logger LOG = LoggerFactory.getLogger(URLContextClassLoaderFactory.class); | ||
|
|
||
| public static final String URL_PATTERN_PROPERTY = | ||
| Property.GENERAL_ARBITRARY_PROP_PREFIX + "factory.class.loader.url.allowed.patterns"; | ||
|
|
||
| private static final Pattern ENCODED_PATH_TRAVERSAL = Pattern.compile("(?i)%(?:25|2e|2f|5c)"); | ||
|
|
||
| // Cache the class loaders for re-use | ||
| // WeakReferences are used so that the class loaders can be cleaned up when no longer needed | ||
| // Classes that are loaded contain a reference to the class loader used to load them | ||
| // so the class loader will be garbage collected when no more classes are loaded that reference it | ||
| private final Cache<String,URLClassLoader> classloaders = | ||
| Caches.getInstance().createNewBuilder(CacheName.CLASSLOADERS, true).weakValues().build(); | ||
|
|
||
| private volatile Pattern urlPattern = null; | ||
|
|
||
| @Override | ||
| public ClassLoader getClassLoader(String context) { | ||
| public void init(ContextClassLoaderEnvironment env) { | ||
| String urlPatternProperty = env.getConfiguration().get(URL_PATTERN_PROPERTY); | ||
| if (urlPatternProperty == null) { | ||
| LOG.warn("Property " + URL_PATTERN_PROPERTY + " not set, no contexts are allowed"); | ||
| } else { | ||
| urlPattern = | ||
| Pattern.compile(urlPatternProperty.replaceAll(":///", ":/").replaceAll("://", ":/")); | ||
|
Comment on lines
+74
to
+75
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think we should modify the user's configuration here. The pattern should be expected to validate against any normalized URL. If the user configures a pattern that isn't normalized, we shouldn't guess what they intended, and should just accept the pattern as-is, rejecting if needed. |
||
| } | ||
| } | ||
|
|
||
| // visible for tests | ||
| protected URL testContextAgainstPattern(String context) throws IOException, URISyntaxException { | ||
| final URI uri = new URI(context).normalize(); | ||
| URL url; | ||
| if ("file".equalsIgnoreCase(uri.getScheme())) { | ||
| // Match and return the actual filesystem target, not the possibly traversing URL spelling. | ||
| // toRealPath also resolves symbolic links, so an allowed path cannot escape via a symlink. | ||
|
Comment on lines
+84
to
+85
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I don't think this should be considered an escape. This prevents legitimate use cases for file system organization/management. If the pattern matches, it means we trust whatever is at that location... even if it's a symlink. This is no different than trusting an HTTP location that is a proxy for another location, or any other URL-redirect mechanism. Whether or not the resource at the given URL is the actual resource, or a proxy, is entirely dependent on the URL resolver. We don't need to complicate it... we can just trust the location or not, as it is specified. If we really want to avoid path traversal bugs, then we can address that with normalization: url.toURI().normalize().toURL(); |
||
| Path realPath = Path.of(uri).toRealPath(); | ||
| url = realPath.toUri().toURL(); | ||
| } else if ("hdfs".equalsIgnoreCase(uri.getScheme())) { | ||
| // Match and return the actual filesystem target, not the possibly traversing URL spelling. | ||
| // resolvePath also resolves symbolic links, so an allowed path cannot escape via a symlink. | ||
| // This may subsequently fail if the HdfsURLStreamHandlerProvider is not on the classpath | ||
| org.apache.hadoop.fs.Path resolved = | ||
| FileSystem.get(uri, new Configuration()).resolvePath(new org.apache.hadoop.fs.Path(uri)); | ||
| url = resolved.toUri().toURL(); | ||
|
Comment on lines
+88
to
+94
Member
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Same comment here. Also, there are some weird quirks with how some versions of Hadoop resolve paths as URIs (apache/hadoop#8307). I'm not sure this would handle path traversal avoidance through normalization better than just using URI.normalize. The comment also makes reference to a specific URLStreamHandlerProvider, but any URLStreamHandlerProvider for hdfs would work for converting it to a URL. |
||
| } else { | ||
| String rawPath = uri.getRawPath(); | ||
| checkArgument(rawPath == null || !ENCODED_PATH_TRAVERSAL.matcher(rawPath).find(), | ||
| "Context %s contains encoded path traversal characters in URL path (%s)", context, | ||
| rawPath); | ||
| url = uri.toURL(); | ||
| } | ||
| checkArgument(urlPattern.matcher(url.toExternalForm()).matches(), | ||
| "Context %s URL (%s) not allowed by pattern (%s)", context, url.toExternalForm(), | ||
| urlPattern.pattern()); | ||
| return url; | ||
| } | ||
|
|
||
| @Override | ||
| public ClassLoader getClassLoader(String context) throws ContextClassLoaderException { | ||
| if (urlPattern == null) { | ||
| throw new ContextClassLoaderException( | ||
| "Property " + URL_PATTERN_PROPERTY + " not set, no contexts are allowed"); | ||
| } | ||
|
|
||
| if (context == null) { | ||
| throw new IllegalArgumentException("Unknown context"); | ||
| } | ||
|
|
||
| return classloaders.get(context, k -> { | ||
| LOG.debug("Creating URLClassLoader for context, uris: {}", context); | ||
| return new URLClassLoader(Arrays.stream(context.split(",")).map(p -> { | ||
| return new URLClassLoader(Arrays.stream(context.split(",")).map(ctx -> { | ||
| try { | ||
| return URI.create(p).toURL(); | ||
| } catch (MalformedURLException e) { | ||
| return testContextAgainstPattern(ctx); | ||
| } catch (IOException e) { | ||
| throw new UncheckedIOException(e); | ||
| } catch (URISyntaxException e) { | ||
| throw new IllegalArgumentException(e); | ||
| } | ||
| }).toArray(URL[]::new), ClassLoader.getSystemClassLoader()); | ||
| }); | ||
|
|
||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,101 @@ | ||
| /* | ||
| * Licensed to the Apache Software Foundation (ASF) under one | ||
| * or more contributor license agreements. See the NOTICE file | ||
| * distributed with this work for additional information | ||
| * regarding copyright ownership. The ASF licenses this file | ||
| * to you under the Apache License, Version 2.0 (the | ||
| * "License"); you may not use this file except in compliance | ||
| * with the License. You may obtain a copy of the License at | ||
| * | ||
| * https://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, | ||
| * software distributed under the License is distributed on an | ||
| * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY | ||
| * KIND, either express or implied. See the License for the | ||
| * specific language governing permissions and limitations | ||
| * under the License. | ||
| */ | ||
| package org.apache.accumulo.core.classloader; | ||
|
|
||
| import static org.junit.jupiter.api.Assertions.assertEquals; | ||
| import static org.junit.jupiter.api.Assertions.assertNotNull; | ||
| import static org.junit.jupiter.api.Assertions.assertThrows; | ||
| import static org.junit.jupiter.api.Assertions.assertTrue; | ||
|
|
||
| import java.io.IOException; | ||
| import java.net.URL; | ||
| import java.nio.file.Files; | ||
| import java.nio.file.Path; | ||
| import java.util.Map; | ||
|
|
||
| import org.apache.accumulo.core.spi.common.ContextClassLoaderEnvironment; | ||
| import org.apache.accumulo.core.spi.common.ServiceEnvironment.Configuration; | ||
| import org.junit.jupiter.api.Test; | ||
| import org.junit.jupiter.api.io.TempDir; | ||
|
|
||
| public class URLContextClassLoaderFactoryTest { | ||
|
|
||
| @Test | ||
| public void test(@TempDir Path tempDir) throws Exception { | ||
| Path allowedDir = tempDir.resolve("allowed"); | ||
| Path allowedJars = allowedDir.resolve("application_jars"); | ||
| Files.createDirectories(allowedJars); | ||
| Path allowedJar = Files.createFile(allowedJars.resolve("allowed.jar")); | ||
| Path outsideJar = Files.createFile(tempDir.resolve("outside.jar")); | ||
|
|
||
| String allowedFilePattern = allowedDir.toUri().toURL().toExternalForm() + ".*"; | ||
| URLContextClassLoaderFactory factory = | ||
| factoryForPattern(allowedFilePattern + "|http://path/b/.*"); | ||
|
|
||
| // Existing allowed files pass, including paths with literal dot segments that normalize | ||
| // to an allowed file. | ||
| URL expectedCanonicalUrl = allowedJar.toRealPath().toUri().toURL(); | ||
| assertEquals(expectedCanonicalUrl, | ||
| factory.testContextAgainstPattern(allowedJar.toUri().toString())); | ||
| assertEquals(expectedCanonicalUrl, factory.testContextAgainstPattern( | ||
| allowedDir.toUri().toString() + "application_jars/../application_jars/allowed.jar")); | ||
| assertThrows(IOException.class, () -> factory | ||
| .testContextAgainstPattern(allowedJars.resolve("missing.jar").toUri().toString())); | ||
|
|
||
| // Traversal that resolves outside the allowed directory is rejected, whether written | ||
| // literally, percent-encoded, or reached through a symlink. | ||
| assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern(allowedDir.toUri() + "../outside.jar")); | ||
| assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern(allowedDir.toUri() + "%2e%2e/outside.jar")); | ||
| Path symlink = Files.createSymbolicLink(allowedDir.resolve("escape.jar"), outsideJar); | ||
| assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern(symlink.toUri().toString())); | ||
|
|
||
| // HTTP URLs retain literal dot-segment normalization, but encoded path delimiters, dots, and | ||
| // percent escapes that could be double-decoded are rejected as ambiguous. | ||
| assertNotNull(factory.testContextAgainstPattern("http:///path/b/application_jars/.*")); | ||
| assertNotNull(factory.testContextAgainstPattern("http:/path/c/../b/application_jars/.*")); | ||
| IllegalArgumentException iae = assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern("http:///path/b/%2e%2e/c/application_jars/.*")); | ||
| assertTrue(iae.getMessage().contains("encoded path traversal")); | ||
| assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern("http:///path/b/%2f../c/application_jars/.*")); | ||
| assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern("http:///path/b/%252e%252e/c/application_jars/.*")); | ||
|
|
||
| iae = assertThrows(IllegalArgumentException.class, | ||
| () -> factory.testContextAgainstPattern("http:///path/a/application_jars/.*")); | ||
| assertTrue(iae.getMessage().contains("not allowed by pattern")); | ||
| } | ||
|
|
||
| private URLContextClassLoaderFactory factoryForPattern(String pattern) { | ||
| URLContextClassLoaderFactory factory = new URLContextClassLoaderFactory(); | ||
| factory.init(new ContextClassLoaderEnvironment() { | ||
|
|
||
| @Override | ||
| public Configuration getConfiguration() { | ||
| return Configuration | ||
| .from(Map.of(URLContextClassLoaderFactory.URL_PATTERN_PROPERTY, pattern), false); | ||
| } | ||
|
|
||
| }); | ||
| return factory; | ||
| } | ||
| } |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The factory normalizes the context URL, so file:///opt/ctx/a.jar becomes file:/opt/ctx/a.jar, but the pattern is matched exactly as configured. An admin who sets file:///opt/ctx/.* gets:
user pattern matches: false -- and then contexts are denied, is this expected?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
The changes added in 2e8e0b3 should address this.