Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions assemblies/features/standard/src/main/feature/feature.xml
Original file line number Diff line number Diff line change
Expand Up @@ -204,6 +204,13 @@ nano = admin
exec = admin
new = admin
java = admin
source = admin
#
# Files, directories and URLs given as argument to the file built-ins (cat, grep, head, tail, less, ls, sort, wc,
# cd and tac). Reading standard input, for example in "bundle:list | grep foo", isn't affected.
# When no rule matches, only admin has access.
#
.file = admin
</config>
<config name="org.apache.karaf.command.acl.scope_bundle">
################################################################################
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,11 @@
nano = admin
exec = admin
new = admin
java = admin
java = admin
source = admin
#
# Files, directories and URLs given as argument to the file built-ins (cat, grep, head, tail, less, ls, sort, wc,
# cd and tac). Reading standard input, for example in "bundle:list | grep foo", isn't affected.
# When no rule matches, only admin has access.
#
.file = admin
2 changes: 2 additions & 0 deletions itests/test/src/test/filtered-resources/etc/feature.xml
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@
java = admin
.invoke = admin
.redirect = admin
source = admin
.file = admin
</config>
<config name="org.apache.karaf.command.acl.scope_bundle">
#
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,13 +13,17 @@
*/
package org.apache.karaf.itests.ssh;

import java.io.File;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.ops4j.pax.exam.junit.PaxExam;
import org.ops4j.pax.exam.spi.reactors.ExamReactorStrategy;
import org.ops4j.pax.exam.spi.reactors.PerClass;

import static org.jline.keymap.KeyMap.ctrl;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;

/**
* This test exercises the Shell Command ACL for the shell scope commands as defined in
Expand Down Expand Up @@ -48,4 +52,32 @@ public void testShellCommandSecurityViaSsh() throws Exception {
assertCommand("karaf", "shell:new", Result.OK);
assertCommand("karaf", "shell:java", Result.OK);
}

@Test
public void testFileBuiltinsViaSsh() throws Exception {
String vieweruser = "view" + System.nanoTime() + "_" + counter++;

addViewer(vieweruser);

// A viewer can't read, list or write files and URLs with the built-ins, or run a script from a file
assertCommand(vieweruser, "cat etc/users.properties", Result.NO_CREDENTIALS);
assertCommand(vieweruser, "grep karaf etc/users.properties", Result.NO_CREDENTIALS);
assertCommand(vieweruser, "head etc/host.key", Result.NO_CREDENTIALS);
assertCommand(vieweruser, "shell:ls etc", Result.NO_CREDENTIALS);
assertCommand(vieweruser, "cat http://127.0.0.1:1/", Result.NO_CREDENTIALS);
File written = new File(System.getProperty("karaf.data"), vieweruser + ".txt");
assertCommand(vieweruser, "echo foo | tac " + written.getAbsolutePath(), Result.NO_CREDENTIALS);
assertFalse(written.exists());
assertCommand(vieweruser, "shell:source etc/users.properties", Result.NOT_FOUND);

// Standard input is open to every user
// -n prefixes the line number, so that the match can't be confused with the echoed command line
String output = assertCommand(vieweruser, "echo hello-from-viewer | grep -n --color=never viewer", Result.OK);
assertTrue(output, output.contains("1:hello-from-viewer"));
assertCommand(vieweruser, "feature:list | grep -i shell | wc -l", Result.OK);

output = assertCommand("karaf", "cat etc/users.properties", Result.OK);
assertTrue(output, output.contains("admingroup"));
assertCommand("karaf", "shell:ls etc", Result.OK);
}
}
4 changes: 3 additions & 1 deletion manual/src/main/asciidoc/user-guide/security.adoc
Original file line number Diff line number Diff line change
Expand Up @@ -509,7 +509,9 @@ By default, Apache Karaf defines the following commands ACLs:
* `etc/org.apache.karaf.command.acl.maven.cfg` configuration file (provided by the `maven` feature) defines the ACL for `maven:*` commands.
Modifying Maven configuration (`maven:http-proxy`, `maven:password`, `maven:repository-add`, `maven:repository-change`, `maven:repository-remove`) or viewing passwords with `-x` requires the `admin` role, whereas read-only commands (`maven:summary`, `maven:http-proxy-list`, `maven:repository-list`) require the `viewer` role.
* `etc/org.apache.karaf.command.acl.shell.cfg` configuration file defines the ACL for `shell:*` and "direct" commands.
Only the users with `admin` role can execute `shell:nano` (`shell:edit`), `shell:exec`, `shell:new`, and `shell:java` commands.
Only the users with `admin` role can execute `shell:nano` (`shell:edit`), `shell:exec`, `shell:new`, `shell:java` and `shell:source` commands.
The `.file` rule controls the files, directories and URLs given as argument to the file built-ins (`cat`, `grep`, `head`, `tail`, `less`, `ls`, `sort`, `wc`, `cd` and `tac`):
only the users with `admin` role can access them, and this is also the default when no rule matches `.file`. Reading standard input, for example in `bundle:list | grep foo`, is open to any user.
The other `shell:*` commands can be executed by any user.
* `etc/org.apache.karaf.command.acl.system.cfg` configuration file defines the ACL for `system:*` commands.
Only the users with `admin` role can execute `system:property` and `system:shutdown` commands. Users with `manager` role can call `system:start-level` above 100, otherwise `admin` role is required. Also users with `viewer` role can obtain the current start-level.
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
/*
* 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
*
* http://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.karaf.shell.impl.console;

import java.io.IOException;
import java.net.URI;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.felix.gogo.jline.Builtin;
import org.apache.felix.gogo.jline.Posix;
import org.apache.felix.service.command.CommandProcessor;
import org.apache.felix.service.command.CommandSession;
import org.jline.builtins.Options;

/**
* Gogo's file built-ins ({@code cat}, {@code grep}, {@code ls}, {@code tac}...) open any file, directory or URL given
* as argument, with the permissions of the Karaf process. These subclasses pass each of them to a {@link Check} before
* the built-in opens it. Standard input isn't checked, so piping the output of a command into {@code grep},
* {@code less} or {@code wc} keeps working for every user.
*/
final class FileAccessGuard {

/**
* Checks that the current user can access a file, directory or URL.
*/
@FunctionalInterface
interface Check {
/**
* @param command the built-in, for example {@code cat}
* @param location the absolute URI of the file, directory or URL
* @throws SecurityException to refuse access
*/
void check(CommandSession session, String command, String location);
}

// Posix built-ins that take no file argument. Every other built-in has all its arguments checked.
private static final Set<String> NO_FILE_ARGS = set("echo", "sleep", "pwd", "clear", "date", "tmux", "ttop", "watch");
// Posix built-ins that read standard input for a "-" argument
private static final Set<String> STDIN_DASH = set("cat", "head", "tail", "wc", "less", "grep");
// Posix built-ins that open their arguments as URLs resolved against the current directory, not as paths
private static final Set<String> URL_ARGS = set("cat", "sort");

private FileAccessGuard() {
}

static class GuardedPosix extends Posix {

private final Check check;

GuardedPosix(CommandProcessor processor, Check check) {
super(processor);
this.check = check;
}

// Each built-in parses its arguments here, before it opens anything
@Override
protected Options parseOptions(CommandSession session, String[] usage, Object[] argv) throws Exception {
Options opt = super.parseOptions(session, usage, argv);
String command = String.valueOf(argv[0]);
if (NO_FILE_ARGS.contains(command)) {
return opt;
}
List<String> args = opt.args();
if ("grep".equals(command) && !args.isEmpty()) {
// grep PATTERN [FILES]
args = args.subList(1, args.size());
} else if ("ls".equals(command) && args.isEmpty()) {
// ls lists the current directory
args = Collections.singletonList(".");
}
for (String arg : args) {
if (!("-".equals(arg) && STDIN_DASH.contains(command))) {
check.check(session, command, location(session, command, arg));
}
}
return opt;
}
}

static class GuardedBuiltin extends Builtin {

// Same as Builtin.tac(), so that the arguments are parsed the same way
private static final String[] TAC_USAGE = {
"tac - capture stdin as String or List and optionally write to file.",
"Usage: tac [-al] [FILE]",
" -a --append append to FILE",
" -l --list return List<String>",
" -? --help show help"};

private final Check check;

GuardedBuiltin(Check check) {
this.check = check;
}

// tac FILE writes its standard input to FILE
@Override
public Object tac(CommandSession session, String[] argv) throws IOException {
for (String arg : Options.compile(TAC_USAGE).parse(argv).args()) {
check.check(session, "tac", location(session, "tac", arg));
}
return super.tac(session, argv);
}
}

// The location the built-in opens, made absolute and normalized so that ACL rules can match it.
// A local file gets the same location whichever built-in opens it.
static String location(CommandSession session, String command, String arg) {
try {
Path cwd = session.currentDir();
Path path;
if (URL_ARGS.contains(command)) {
URI uri = cwd.toUri().resolve(arg).normalize();
if (!"file".equalsIgnoreCase(uri.getScheme())) {
return uri.toString();
}
path = Paths.get(uri);
} else {
path = cwd.resolve(arg);
}
return path.toAbsolutePath().normalize().toUri().toString();
} catch (RuntimeException e) {
// The built-in fails on it too, but check what was asked for anyway
return arg;
}
}

private static Set<String> set(String... values) {
return Collections.unmodifiableSet(new HashSet<>(Arrays.asList(values)));
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -78,7 +78,7 @@ public Path redirect(CommandSessionImpl session, Path path, int mode) {
register(new ShellCommand("removeCommand", "Remove a command", commandProcessor, "removeCommand"));
register(new ShellCommand("eval", "Evaluate", commandProcessor, "eval"));

Builtin builtin = new Builtin();
Builtin builtin = new FileAccessGuard.GuardedBuiltin(this::checkFileAccess);
for (String name : new String[]{"format", "getopt", "new", "set", "tac", "type", "jobs", "fg", "bg", "keymap", "setopt", "unsetopt", "complete", "history", "widget", "__files", "__directories", "__usage_completion"}) {
register(new ShellCommand(name, null, builtin, name));
}
Expand All @@ -88,7 +88,7 @@ public Path redirect(CommandSessionImpl session, Path path, int mode) {
register(new ShellCommand(name, null, procedural, name));
}

Posix posix = new Posix(commandProcessor);
Posix posix = new FileAccessGuard.GuardedPosix(commandProcessor, this::checkFileAccess);
for (String name : new String[]{"cat", "echo", "grep", "sort", "sleep", "cd", "pwd", "ls", "less", "nano", "head", "tail", "clear", "wc", "date", "tmux", "ttop"}) {
register(new ShellCommand(name, null, posix, name));
}
Expand Down Expand Up @@ -127,6 +127,17 @@ protected Path redirect(CommandSessionImpl session, Path path, int mode) {
return session.currentDir().resolve(path);
}

/**
* Called by the file built-ins ({@code cat}, {@code grep}, {@code ls}, {@code tac}...) for each file, directory
* or URL given as argument, before they open it.
*
* @param command the built-in, for example {@code cat}
* @param location the absolute URI of the file, directory or URL
* @throws SecurityException to refuse access
*/
protected void checkFileAccess(CommandSession session, String command, String location) {
}

public CommandProcessorImpl getCommandProcessor() {
return commandProcessor;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -25,18 +25,21 @@
import java.security.Principal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Dictionary;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.function.Predicate;

import javax.security.auth.Subject;

import org.apache.felix.gogo.runtime.CommandNotFoundException;
import org.apache.felix.gogo.runtime.CommandSessionImpl;
import org.apache.felix.service.command.CommandSession;
import org.apache.felix.service.command.Function;
import org.apache.felix.service.threadio.ThreadIO;
import org.apache.karaf.jaas.boot.principal.RolePrincipal;
Expand Down Expand Up @@ -64,6 +67,9 @@ public class SecuredSessionFactoryImpl extends SessionFactoryImpl implements Con
private static final String SHELL_SCOPE = "shell";
private static final String SHELL_INVOKE = ".invoke";
private static final String SHELL_REDIRECT = ".redirect";
private static final String SHELL_FILE = ".file";
// Role needed for SHELL_FILE when the shell ACL has no rule for it, for example in an etc/ kept from an older version
private static final String SHELL_FILE_DEFAULT_ROLE = "admin";

private static final Logger LOGGER = LoggerFactory.getLogger(SecuredSessionFactoryImpl.class);

Expand Down Expand Up @@ -108,8 +114,33 @@ protected Path redirect(CommandSessionImpl session, Path path, int mode) {
});
}

@Override
protected void checkFileAccess(CommandSession session, String command, String location) {
Dictionary<String, Object> config = getScopeConfig(SHELL_SCOPE);
boolean allowed = JaasHelper.doAs(sessionSubject(session), (PrivilegedAction<Boolean>) () ->
isFileAccessAllowed(config, command, location, SecuredSessionFactoryImpl::currentUserHasRole));
if (!allowed) {
throw new SecurityException("Insufficient credentials to access " + location);
}
}

/**
* Unlike commands, which anyone can run when no ACL rule matches them, file access fails closed: when no rule
* matches {@code .file}, only {@code admin} has it. The rules see the arguments as {@code [command, location]}.
*/
static boolean isFileAccessAllowed(Dictionary<String, Object> config, String command, String location,
Predicate<String> hasRole) {
List<String> roles = new ArrayList<>();
if (config == null || ACLConfigurationParser.getRolesForInvocation(SHELL_FILE,
new Object[] { Arrays.asList(command, location).toString() }, null, config, roles)
== ACLConfigurationParser.Specificity.NO_MATCH) {
roles = Collections.singletonList(SHELL_FILE_DEFAULT_ROLE);
}
return roles.stream().anyMatch(hasRole);
}

// Same as SecuredCommand.execute(): this runs on Gogo's pipeline threads, so the session's subject is authoritative
private Subject sessionSubject(CommandSessionImpl commandSession) {
private Subject sessionSubject(CommandSession commandSession) {
Subject subject = getSubject(getSession(commandSession));
return subject != null ? subject : Subject.current();
}
Expand Down
Loading
Loading