Skip to content
Merged
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
30 changes: 29 additions & 1 deletion keepercommander/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,20 @@
aliases['h'] = 'history'
aliases['q'] = 'quit'

# These commands operate on the interactive Commander session rather than on
# vault data, so they must not be grantable through Service Mode.
SHELL_ONLY_COMMANDS = frozenset({'clear', 'history', 'quit', 'server'})


def get_shell_only_command_names():
"""Return shell/session commands and their registered aliases."""
command_names = {command.lower() for command in SHELL_ONLY_COMMANDS}
for alias, command in aliases.items():
target = command[0] if isinstance(command, (tuple, list)) else command
if isinstance(target, str) and target.lower() in command_names:
command_names.add(alias.lower())
return command_names

logging.getLogger('asyncio').setLevel(logging.WARNING)


Expand Down Expand Up @@ -376,6 +390,15 @@ def do_command(params, command_line):
logging.error('Invalid command: control characters are not allowed in command input.')
return

if getattr(params, 'service_mode', False):
try:
command_tokens = shlex.split(command_line)
except ValueError:
command_tokens = []
if command_tokens and command_tokens[0].lower() in get_shell_only_command_names():
logging.error('Interactive shell/session commands are not available in Service Mode')
return

def is_msp(params_local):
if params_local.enterprise:
if 'licenses' in params_local.enterprise:
Expand Down Expand Up @@ -465,7 +488,12 @@ def is_msp(params_local):
return

# Track commands history
if len(stack) == 0 or stack[0] != command_line:
# Service Mode serves multiple API keys in one process. Never place its raw
# command lines (which may contain credentials) in the interactive shell's
# process-global history buffer.
if (
not getattr(params, 'service_mode', False)
and (len(stack) == 0 or stack[0] != command_line)):
stack.insert(0, command_line)

if command_line.lower() == 'c' or command_line.lower() == 'cls' or command_line.lower() == 'clear':
Expand Down
8 changes: 8 additions & 0 deletions keepercommander/service/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,14 @@ The Service Mode module for Keeper Commander enables REST API integration by pro
- IP deny list management
- Request validation and policy enforcement

### Service Mode command grants: upgrade note

Interactive shell/session controls are not supported Service Mode API commands.
The `clear`/`c`, `history`/`h`, `quit`/`q`, and `server` commands are rejected
by Service Mode provisioning and blocked at runtime, including when they appear
in an existing API key's command list. Remove these entries from command lists
before re-running service provisioning or Docker/Terraform setup.

### Configuration

Create and configure the service with interactive prompts:
Expand Down
9 changes: 8 additions & 1 deletion keepercommander/service/config/service_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -307,6 +307,13 @@ def validate_command_list(self, commands: str, params: KeeperParams = None) -> s
raise ValidationError("Command list cannot be empty")
help_output = self.cli_handler.get_help_output(params)
valid_commands, command_info = self.command_validator.parse_help_output(help_output)
# Keep interactive shell/session controls visible in normal CLI help,
# but never offer them as Service Mode API grants.
from ... import cli
shell_only_commands = cli.get_shell_only_command_names()
valid_commands.difference_update(shell_only_commands)
for shell_command in shell_only_commands:
command_info.pop(shell_command, None)
validated_commands, invalid_commands = self.command_validator.validate_command_list(commands, valid_commands)

if invalid_commands:
Expand Down Expand Up @@ -344,4 +351,4 @@ def update_or_add_record(self, params: KeeperParams) -> None:
else:
logger.debug(f" TLS certificate upload skipped - TLS not enabled.")
except Exception as e:
logger.debug(f"Error checking TLS configuration: {e}")
logger.debug(f"Error checking TLS configuration: {e}")
16 changes: 16 additions & 0 deletions keepercommander/service/util/verified_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ class Verifycommand:
_LEGACY_COMMAND_MSG = (
'Legacy commands are not permitted through Service Mode'
)
_SHELL_ONLY_COMMAND_MSG = (
'Interactive shell/session commands are not permitted through Service Mode'
)

# GroupCommand.execute_args (commands/base.py) strips a leading '-- ' at each
# nested group boundary, desyncing position-based checks below (e.g. pam tunnel).
Expand Down Expand Up @@ -113,6 +116,7 @@ def validate_service_mode_restrictions(command_tokens, request_temp_dir=None):
Verifycommand.validate_service_mode_env_var_expansion_command,
Verifycommand.validate_service_mode_automator_file_access_command,
Verifycommand.validate_service_mode_legacy_command,
Verifycommand.validate_service_mode_shell_only_command,
Verifycommand.validate_nsf_convert_command,
Verifycommand.validate_service_mode_pam_tunnel_command,
Verifycommand.validate_service_mode_download_attachment_command,
Expand Down Expand Up @@ -255,6 +259,18 @@ def validate_service_mode_legacy_command(command_tokens, request_temp_dir=None):
return None
return Verifycommand._LEGACY_COMMAND_MSG

@staticmethod
def validate_service_mode_shell_only_command(command_tokens, request_temp_dir=None):
"""Block interactive shell/session commands in Service Mode."""
if not command_tokens:
return None
# Source the command names and aliases from the CLI definition so
# provisioning and runtime enforcement cannot drift apart.
from ... import cli
if command_tokens[0].lower() not in cli.get_shell_only_command_names():
return None
return Verifycommand._SHELL_ONLY_COMMAND_MSG

@staticmethod
def validate_service_mode_pam_tunnel_command(command_tokens, request_temp_dir=None):
"""Allow only pam tunnel edit in Service Mode; error string or None."""
Expand Down
12 changes: 12 additions & 0 deletions unit-tests/service/test_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,18 @@ def test_validate_session(self):
result = CommandExecutor.validate_session()
self.assertIsNone(result)

def test_execute_rejects_shell_only_commands_with_forbidden_status(self):
"""The real Service Mode executor must reject shell/session controls."""
params = params_module.KeeperParams()
with mock.patch(
'keepercommander.service.core.globals.ensure_params_loaded',
return_value=params):
for command in ('history', 'h', 'server host --insecure'):
with self.subTest(command=command):
response, status_code = CommandExecutor.execute(command)
self.assertEqual(status_code, 403)
self.assertIn('Interactive shell/session commands', response['error'])

@unittest.skip
def test_command_execution_success(self):
"""Test successful command execution"""
Expand Down
8 changes: 8 additions & 0 deletions unit-tests/service/test_service_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -152,6 +152,14 @@ def test_validate_command_list_invalid(self, mock_cli_handler):
with self.assertRaises(ValidationError):
self.service_config.validate_command_list("invalid_command", params)

def test_validate_command_list_rejects_shell_and_session_commands(self):
"""Interactive shell/session controls must not be grantable to Service Mode keys."""
params = KeeperParams()
for command in ('clear', 'c', 'history', 'h', 'quit', 'q', 'server'):
with self.subTest(command=command):
with self.assertRaises(ValidationError):
self.service_config.validate_command_list(command, params)

@unittest.skip
@patch.object(ServiceConfig, 'record_handler')
def test_update_or_add_record(self, mock_record_handler):
Expand Down
8 changes: 8 additions & 0 deletions unit-tests/service/test_verified_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,14 @@ def _tokens(command: str):
class TestServiceModeCommandPolicy(TestCase):
"""Service Mode bans must use the same tokenize path as CommandExecutor."""

def test_interactive_shell_and_session_commands_are_blocked(self):
check = Verifycommand.validate_service_mode_restrictions
for command in ('clear', 'c', 'history', 'h', 'quit', 'q', 'server'):
with self.subTest(command=command):
error = check(_tokens(command))
self.assertIsNotNone(error)
self.assertIn('Interactive shell/session commands', error)

def test_pam_tunnel_blocked_except_edit(self):
for cmd in (
'pam tunnel start uid --run id',
Expand Down
34 changes: 34 additions & 0 deletions unit-tests/test_cli.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from collections import OrderedDict
import io
import sys
from types import SimpleNamespace
from unittest import TestCase, mock

from keepercommander import cli
from keepercommander.commands import base
from keepercommander.cli import do_command, read_command_with_continuation
from data_vault import get_connected_params
Expand Down Expand Up @@ -50,6 +53,37 @@ def test_do_command_no_opts(self):
do_command(params, 'this-device')
mock_print_dev.assert_called()

def test_service_mode_does_not_read_or_write_global_history(self):
original_stack = cli.stack[:]
sentinel = 'record-add password=DO-NOT-DISCLOSE'
try:
cli.stack[:] = [sentinel]
params = SimpleNamespace(service_mode=True)

with mock.patch('keepercommander.cli.display.formatted_history') as mock_history, \
mock.patch('keepercommander.cli.server_command') as mock_server_command, \
mock.patch('builtins.print'):
for command in ('history', 'h', 'clear', 'c', 'quit', 'q', 'server'):
with self.subTest(command=command):
do_command(params, command)
mock_history.assert_not_called()
mock_server_command.assert_not_called()

self.assertEqual(cli.stack, [sentinel])
finally:
cli.stack[:] = original_stack

def test_in_shell_help_still_lists_shell_commands(self):
# In-shell help uses show_shell=False; this flag controls help hints,
# not whether working shell commands are displayed.
with mock.patch('sys.stdout', new_callable=io.StringIO) as output:
cli.display_command_help(show_shell=False)

help_text = output.getvalue()
for command in ('clear (c)', 'history (h)', 'quit (q)', 'server'):
with self.subTest(command=command):
self.assertIn(command, help_text)

def test_line_continuation(self):
"""Test that line continuation with backslash works correctly."""
params = get_connected_params()
Expand Down