Skip to content

Commit

Permalink
Merge pull request #8315 from eclipse/jetty-10.0.x-8296-AliasChecking
Browse files Browse the repository at this point in the history
Issue #8296 and #8259 -  AllowedResourceAliasChecker improvements
  • Loading branch information
lachlan-roberts committed Aug 8, 2022
2 parents b7d8635 + 7d7dd41 commit 998bc8c
Show file tree
Hide file tree
Showing 9 changed files with 382 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -271,8 +271,8 @@ public ContextHandler createContextHandler(final App app) throws Exception
// Resource aliases (after getting name) to ensure baseResource is not an alias
if (resource.isAlias())
{
file = new File(resource.getAlias()).toPath().toRealPath().toFile();
resource = Resource.newResource(file);
resource = Resource.resolveAlias(resource);
file = resource.getFile();
if (!resource.exists())
throw new IllegalStateException("App resource does not exist " + resource);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.function.Supplier;

import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.component.AbstractLifeCycle;
Expand All @@ -43,26 +44,39 @@ public class AllowedResourceAliasChecker extends AbstractLifeCycle implements Co
protected static final LinkOption[] NO_FOLLOW_LINKS = new LinkOption[]{LinkOption.NOFOLLOW_LINKS};

private final ContextHandler _contextHandler;
private final Supplier<Resource> _resourceBaseSupplier;
private final List<Path> _protected = new ArrayList<>();
private final AllowedResourceAliasCheckListener _listener = new AllowedResourceAliasCheckListener();
private boolean _initialized;
protected Path _base;

/**
* @param contextHandler the context handler to use.
*/
public AllowedResourceAliasChecker(ContextHandler contextHandler)
{
this(contextHandler, contextHandler::getBaseResource);
}

public AllowedResourceAliasChecker(ContextHandler contextHandler, Resource baseResource)
{
this(contextHandler, () -> baseResource);
}

public AllowedResourceAliasChecker(ContextHandler contextHandler, Supplier<Resource> resourceBaseSupplier)
{
_contextHandler = Objects.requireNonNull(contextHandler);
_resourceBaseSupplier = Objects.requireNonNull(resourceBaseSupplier);
}

protected ContextHandler getContextHandler()
{
return _contextHandler;
}

protected void initialize()
private void extractBaseResourceFromContext()
{
_base = getPath(_contextHandler.getBaseResource());
_base = getPath(_resourceBaseSupplier.get());
if (_base == null)
return;

Expand All @@ -84,6 +98,12 @@ protected void initialize()
}
}

protected void initialize()
{
extractBaseResourceFromContext();
_initialized = true;
}

@Override
protected void doStart() throws Exception
{
Expand All @@ -106,6 +126,8 @@ protected void doStop() throws Exception
@Override
public boolean check(String pathInContext, Resource resource)
{
if (!_initialized)
extractBaseResourceFromContext();
if (_base == null)
return false;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import java.nio.file.Path;

import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.util.resource.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Expand All @@ -37,6 +38,11 @@ public SymlinkAllowedResourceAliasChecker(ContextHandler contextHandler)
super(contextHandler);
}

public SymlinkAllowedResourceAliasChecker(ContextHandler contextHandler, Resource baseResource)
{
super(contextHandler, baseResource);
}

@Override
protected boolean check(String pathInContext, Path path)
{
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -859,8 +859,13 @@ protected void doStart() throws Exception
throw new IllegalStateException("Null contextPath");

if (getBaseResource() != null && getBaseResource().isAlias())
{
// We may have symlink to baseResource, try to resolve symlink if possible.
_baseResource = Resource.resolveAlias(_baseResource);

LOG.warn("BaseResource {} is aliased to {} in {}. May not be supported in future releases.",
getBaseResource(), getBaseResource().getAlias(), this);
}

_availability.set(Availability.STARTING);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,31 @@ public static boolean getDefaultUseCaches()
return __defaultUseCaches;
}

/**
* Attempt to resolve the real path of a Resource to potentially remove any symlinks causing the Resource to be an alias.
* @param resource the resource to resolve.
* @return a new Resource resolved to the real path of the original Resource, or the original resource if it was not an alias.
*/
public static Resource resolveAlias(Resource resource)
{
if (!resource.isAlias())
return resource;

try
{
File file = resource.getFile();
if (file != null)
return Resource.newResource(file.toPath().toRealPath());
}
catch (IOException e)
{
if (LOG.isDebugEnabled())
LOG.debug("resolve alias failed", e);
}

return resource;
}

/**
* Construct a resource from a uri.
*
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
//
// ========================================================================
// Copyright (c) 1995-2022 Mort Bay Consulting Pty Ltd and others.
//
// This program and the accompanying materials are made available under the
// terms of the Eclipse Public License v. 2.0 which is available at
// https://www.eclipse.org/legal/epl-2.0, or the Apache License, Version 2.0
// which is available at https://www.apache.org/licenses/LICENSE-2.0.
//
// SPDX-License-Identifier: EPL-2.0 OR Apache-2.0
// ========================================================================
//

package org.eclipse.jetty.test;

import java.io.File;
import java.net.URI;
import java.net.URL;
import java.nio.file.Files;
import java.nio.file.Path;

import org.eclipse.jetty.client.HttpClient;
import org.eclipse.jetty.client.api.ContentResponse;
import org.eclipse.jetty.http.HttpStatus;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.server.ServerConnector;
import org.eclipse.jetty.server.SymlinkAllowedResourceAliasChecker;
import org.eclipse.jetty.server.handler.ContextHandler;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.util.IO;
import org.eclipse.jetty.util.resource.PathResource;
import org.eclipse.jetty.util.resource.Resource;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import static org.junit.jupiter.api.Assertions.assertNotNull;

public class AliasCheckerMultipleResourceBasesTest
{
private Server _server;
private ServerConnector _connector;
private HttpClient _client;
private ServletContextHandler _context;
private Path _webRootPath;
private Path _altDir1Symlink;
private Path _altDir2Symlink;

private static Path getResource(String path) throws Exception
{
URL url = AliasCheckerMultipleResourceBasesTest.class.getClassLoader().getResource(path);
assertNotNull(url);
return new File(url.toURI()).toPath();
}

private static void delete(Path path)
{
IO.delete(path.toFile());
}

private void setAliasCheckers(ContextHandler.AliasCheck... aliasChecks)
{
_context.clearAliasChecks();
if (aliasChecks != null)
{
for (ContextHandler.AliasCheck aliasCheck : aliasChecks)
{
_context.addAliasCheck(aliasCheck);
}
}
}

@BeforeEach
public void before() throws Exception
{
_webRootPath = getResource("webroot");

_altDir1Symlink = _webRootPath.resolve("../altDir1Symlink");
delete(_altDir1Symlink);
Path altDir1 = _webRootPath.resolve("../altDir1").toAbsolutePath();
Files.createSymbolicLink(_altDir1Symlink, altDir1).toFile().deleteOnExit();

_altDir2Symlink = _webRootPath.resolve("../altDir2Symlink");
delete(_altDir2Symlink);
Path altDir2 = _webRootPath.resolve("../altDir2").toAbsolutePath();
Files.createSymbolicLink(_altDir2Symlink, altDir2).toFile().deleteOnExit();

// Create and start Server and Client.
_server = new Server();
_connector = new ServerConnector(_server);
_server.addConnector(_connector);
_context = new ServletContextHandler();

_context.setContextPath("/");
_context.setBaseResource(new PathResource(_webRootPath));
_context.setWelcomeFiles(new String[]{"index.html"});
_context.getMimeTypes().addMimeMapping("txt", "text/plain;charset=utf-8");
_server.setHandler(_context);
_context.clearAliasChecks();

_client = new HttpClient();
_client.start();
}

@AfterEach
public void after() throws Exception
{
Files.delete(_altDir1Symlink);
Files.delete(_altDir2Symlink);

_client.stop();
_server.stop();
}

@Test
public void test() throws Exception
{
ServletHolder servletHolder;
servletHolder = _context.addServlet(DefaultServlet.class, "/defaultServlet1/*");
servletHolder.setInitParameter("resourceBase", _altDir1Symlink.toString());
servletHolder.setInitParameter("pathInfoOnly", "true");
servletHolder = _context.addServlet(DefaultServlet.class, "/defaultServlet2/*");
servletHolder.setInitParameter("resourceBase", _altDir2Symlink.toString());
servletHolder.setInitParameter("pathInfoOnly", "true");

setAliasCheckers(
new SymlinkAllowedResourceAliasChecker(_context, Resource.newResource(_altDir1Symlink)),
new SymlinkAllowedResourceAliasChecker(_context, Resource.newResource(_altDir2Symlink))
);

_server.start();

// Can access file 1 only through default servlet 1.
URI uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/defaultServlet1/file1");
ContentResponse response = _client.GET(uri);
assertThat(response.getStatus(), is(HttpStatus.OK_200));
assertThat(response.getContentAsString(), is("file 1 contents"));

// File 2 cannot be found with default servlet 1.
uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/defaultServlet1/file2");
response = _client.GET(uri);
assertThat(response.getStatus(), is(HttpStatus.NOT_FOUND_404));

// Can access file 2 only through default servlet 2.
uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/defaultServlet2/file2");
response = _client.GET(uri);
assertThat(response.getStatus(), is(HttpStatus.OK_200));
assertThat(response.getContentAsString(), is("file 2 contents"));

// File 1 cannot be found with default servlet 2.
uri = URI.create("http://localhost:" + _connector.getLocalPort() + "/defaultServlet2/file1");
response = _client.GET(uri);
assertThat(response.getStatus(), is(HttpStatus.NOT_FOUND_404));
}
}

0 comments on commit 998bc8c

Please sign in to comment.