mirror of
https://github.com/kovidgoyal/kitty.git
synced 2026-11-17 05:32:41 +00:00
Remote control: Harden authorization of stream continuations
Requests on a registered stream skip authentication, so restrict that to genuine continuations of the authorized request that opened the stream: - A continuation may differ from the opening request only in its data, so it can no longer, for example, supply a different cmdline to run. - Streams are bound to the socket peer or window that opened them, and only requests from that origin can continue or cancel them. - Streams are aborted, discarding any buffered data, when the peer disconnects, the window is closed or the request is cancelled, so abandoned streams no longer stay authorized.
This commit is contained in:
parent
96ea662bc7
commit
67d337794f
5 changed files with 166 additions and 14 deletions
|
|
@ -839,7 +839,7 @@ class Boss:
|
|||
return {'ok': False, 'error': 'Remote control disallowed by window specific password'}
|
||||
if allowed_unconditionally:
|
||||
return self._execute_remote_command(pcmd, window, peer_id, self_window)
|
||||
q = is_cmd_allowed(pcmd, window, from_socket, extra_data)
|
||||
q = is_cmd_allowed(pcmd, window, from_socket, extra_data, peer_id)
|
||||
if q is True:
|
||||
return self._execute_remote_command(pcmd, window, peer_id, self_window)
|
||||
if q is None:
|
||||
|
|
@ -1006,6 +1006,9 @@ class Boss:
|
|||
def peer_message_received(self, msg_bytes: bytes, peer_id: int, is_remote_control: bool) -> bytes | bool | None:
|
||||
if peer_id > 0 and msg_bytes == b'peer_death':
|
||||
self.peer_data_map.pop(peer_id, None)
|
||||
from .remote_control import abort_active_streams_from
|
||||
|
||||
abort_active_streams_from(peer_id=peer_id)
|
||||
return False
|
||||
if is_remote_control:
|
||||
cmd_prefix = b'\x1bP@kitty-cmd'
|
||||
|
|
|
|||
|
|
@ -297,15 +297,20 @@ class StreamInFlight:
|
|||
self.stream_id = ''
|
||||
self.tempfile: BytesIO | None = None
|
||||
|
||||
def discard(self, stream_id: str) -> None:
|
||||
# Drop any data received for the specified stream, if it is in flight
|
||||
if stream_id and stream_id == self.stream_id:
|
||||
self.stream_id = ''
|
||||
if self.tempfile is not None:
|
||||
self.tempfile.close()
|
||||
self.tempfile = None
|
||||
|
||||
def handle_data(self, stream_id: str, data: bytes) -> AsyncResponse | BytesIO:
|
||||
from ..remote_control import close_active_stream
|
||||
|
||||
def abort_stream() -> None:
|
||||
close_active_stream(self.stream_id)
|
||||
self.stream_id = ''
|
||||
if self.tempfile is not None:
|
||||
self.tempfile.close()
|
||||
self.tempfile = None
|
||||
self.discard(self.stream_id)
|
||||
|
||||
if stream_id != self.stream_id:
|
||||
abort_stream()
|
||||
|
|
|
|||
|
|
@ -12,7 +12,7 @@ from contextlib import suppress
|
|||
from functools import lru_cache, partial
|
||||
from time import time_ns
|
||||
from types import GeneratorType
|
||||
from typing import TYPE_CHECKING, Any, Optional, TypeVar, cast
|
||||
from typing import TYPE_CHECKING, Any, NamedTuple, Optional, TypeVar, cast
|
||||
|
||||
from .cli import parse_args
|
||||
from .cli_stub import RCOptions
|
||||
|
|
@ -33,7 +33,19 @@ from .typing_compat import BossType, WindowType
|
|||
from .utils import TTYIO, log_error, parse_address_spec, resolve_custom_file
|
||||
|
||||
active_async_requests: dict[str, float] = {}
|
||||
active_streams: dict[str, str] = {}
|
||||
|
||||
|
||||
class ActiveStream(NamedTuple):
|
||||
cmd: str
|
||||
# The origin of the request that opened the stream: the socket peer or the
|
||||
# window the request was received from
|
||||
peer_id: int
|
||||
window_id: int
|
||||
# The parts of the request that must be the same for every chunk of the stream
|
||||
fingerprint: str
|
||||
|
||||
|
||||
active_streams: dict[str, ActiveStream] = {}
|
||||
T = TypeVar('T')
|
||||
if TYPE_CHECKING:
|
||||
from .window import Window
|
||||
|
|
@ -176,9 +188,9 @@ def password_authorizer(auth_items: frozenset[str]) -> PasswordAuthorizer:
|
|||
user_password_allowed: dict[str, bool] = {}
|
||||
|
||||
|
||||
def is_cmd_allowed(pcmd: dict[str, Any], window: Optional['Window'], from_socket: bool, extra_data: dict[str, Any]) -> bool | None:
|
||||
sid = pcmd.get('stream_id', '')
|
||||
if sid and active_streams.get(sid, '') == pcmd['cmd']:
|
||||
def is_cmd_allowed(pcmd: dict[str, Any], window: Optional['Window'], from_socket: bool, extra_data: dict[str, Any], peer_id: int = 0) -> bool | None:
|
||||
if is_stream_continuation(pcmd, window, peer_id):
|
||||
# The request that opened the stream was authorized
|
||||
return True
|
||||
if 'cancel_async' in pcmd and str(pcmd.get('async', '')):
|
||||
# we allow these without authentication as they are sent on error
|
||||
|
|
@ -210,10 +222,56 @@ def set_user_password_allowed(pwd: str, allowed: bool = True) -> None:
|
|||
user_password_allowed[pwd] = allowed
|
||||
|
||||
|
||||
def stream_fingerprint(pcmd: dict[str, Any]) -> str:
|
||||
# Every chunk of a stream repeats the request with only the data changed,
|
||||
# so everything else must match the authorized request that opened the stream
|
||||
payload = pcmd.get('payload') or {}
|
||||
if isinstance(payload, dict):
|
||||
# peer_id, stream_id and async_id are added to the payload by handle_cmd()
|
||||
payload = {k: v for k, v in payload.items() if k not in ('data', 'peer_id', 'stream_id', 'async_id')}
|
||||
return json.dumps({'cmd': pcmd.get('cmd'), 'async': str(pcmd.get('async', '')), 'payload': payload}, sort_keys=True)
|
||||
|
||||
|
||||
def window_id_of(window: WindowType | None) -> int:
|
||||
return 0 if window is None else window.id
|
||||
|
||||
|
||||
def is_stream_continuation(pcmd: dict[str, Any], window: WindowType | None, peer_id: int) -> bool:
|
||||
sid = str(pcmd.get('stream_id', ''))
|
||||
s = active_streams.get(sid) if sid else None
|
||||
return (
|
||||
s is not None
|
||||
and s.cmd == pcmd.get('cmd')
|
||||
and s.peer_id == peer_id
|
||||
and s.window_id == window_id_of(window)
|
||||
and s.fingerprint == stream_fingerprint(pcmd)
|
||||
)
|
||||
|
||||
|
||||
def register_active_stream(stream_id: str, pcmd: dict[str, Any], window: WindowType | None, peer_id: int) -> None:
|
||||
active_streams[stream_id] = ActiveStream(pcmd['cmd'], peer_id, window_id_of(window), stream_fingerprint(pcmd))
|
||||
while len(active_streams) > 32:
|
||||
abort_active_stream(next(iter(active_streams)))
|
||||
|
||||
|
||||
def close_active_stream(stream_id: str) -> None:
|
||||
active_streams.pop(stream_id, None)
|
||||
|
||||
|
||||
def abort_active_stream(stream_id: str) -> None:
|
||||
# Close the stream and discard any data already received on it
|
||||
s = active_streams.pop(stream_id, None)
|
||||
if s is not None:
|
||||
command_for_name(s.cmd).stream_in_flight.discard(stream_id)
|
||||
|
||||
|
||||
def abort_active_streams_from(peer_id: int = 0, window_id: int = 0) -> None:
|
||||
# Called when the socket peer or window that opened streams goes away, as
|
||||
# the streams can no longer be completed
|
||||
for sid in [sid for sid, s in active_streams.items() if s.peer_id == peer_id and s.window_id == window_id]:
|
||||
abort_active_stream(sid)
|
||||
|
||||
|
||||
def handle_cmd(
|
||||
boss: BossType, window: WindowType | None, cmd: dict[str, Any], peer_id: int, self_window: WindowType | None
|
||||
) -> dict[str, Any] | None | AsyncResponse:
|
||||
|
|
@ -237,6 +295,11 @@ def handle_cmd(
|
|||
payload['async_id'] = async_id
|
||||
if 'cancel_async' in cmd:
|
||||
active_async_requests.pop(async_id, None)
|
||||
# Cancellations are allowed without authentication, so only let
|
||||
# them abort a stream opened from the same origin
|
||||
s = active_streams.get(stream_id) if stream_id else None
|
||||
if s is not None and s.peer_id == peer_id and s.window_id == window_id_of(window):
|
||||
abort_active_stream(stream_id)
|
||||
c.cancel_async_request(boss, self_window or window, PayloadGetter(c, payload))
|
||||
return None
|
||||
active_async_requests[async_id] = monotonic()
|
||||
|
|
@ -247,10 +310,7 @@ def handle_cmd(
|
|||
# Register the stream only after cancellations have returned, as they
|
||||
# are allowed without authentication and requests on a registered
|
||||
# stream are allowed without authentication as well
|
||||
active_streams[stream_id] = cmd['cmd']
|
||||
if len(active_streams) > 32:
|
||||
oldest = next(iter(active_streams))
|
||||
del active_streams[oldest]
|
||||
register_active_stream(stream_id, cmd, window, peer_id)
|
||||
try:
|
||||
ans = c.response_from_kitty(boss, self_window or window, PayloadGetter(c, payload))
|
||||
except Exception:
|
||||
|
|
|
|||
|
|
@ -2225,8 +2225,11 @@ class Window:
|
|||
traceback.print_exc()
|
||||
|
||||
def destroy(self) -> None:
|
||||
from .remote_control import abort_active_streams_from
|
||||
|
||||
self.call_watchers(self.watchers.on_close, {})
|
||||
self.destroyed = True
|
||||
abort_active_streams_from(window_id=self.id)
|
||||
if self.clear_progress_timer:
|
||||
remove_timer(self.clear_progress_timer)
|
||||
self.clear_progress_timer = 0
|
||||
|
|
|
|||
|
|
@ -5,6 +5,7 @@ import os
|
|||
import subprocess
|
||||
import tempfile
|
||||
from types import MethodType
|
||||
from typing import Any, cast
|
||||
from unittest.mock import Mock, patch
|
||||
|
||||
from kitty.constants import kitty_exe
|
||||
|
|
@ -129,6 +130,86 @@ class TestRemoteControl(BaseTest):
|
|||
pcmd = {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': sid, 'payload': {'cmdline': ['true'], 'data': ''}}
|
||||
self.assertIsNot(is_cmd_allowed(pcmd, None, False, {}), True)
|
||||
|
||||
def test_stream_continuation_auth(self):
|
||||
from base64 import standard_b64encode
|
||||
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
from kitty.remote_control import abort_active_stream, abort_active_streams_from, active_streams, handle_cmd, is_cmd_allowed, register_active_stream
|
||||
|
||||
self.set_options({'remote_control_password': {'secret': frozenset(('ls',))}})
|
||||
command = command_for_name('run')
|
||||
|
||||
def cleanup() -> None:
|
||||
for sid in tuple(active_streams):
|
||||
abort_active_stream(sid)
|
||||
|
||||
self.addCleanup(cleanup)
|
||||
|
||||
def chunk(sid: str, data: bytes = b'x', payload: dict[str, Any] | None = None, **kw: Any) -> dict[str, Any]:
|
||||
p: dict[str, Any] = {'cmdline': ['true'], 'data': standard_b64encode(data).decode('ascii'), **(payload or {})}
|
||||
return {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': sid, 'async': 'a-' + sid, 'payload': p, **kw}
|
||||
|
||||
def open_stream(sid: str, peer_id: int = 0, window: Window | None = None) -> None:
|
||||
# handle_cmd() is only called for authorized requests
|
||||
r = handle_cmd(Mock(spec=KittyBoss), window, chunk(sid, stream=True), peer_id, None)
|
||||
self.ae(r, {'ok': True, 'stream': True})
|
||||
self.assertIn(sid, active_streams)
|
||||
|
||||
def allowed(pcmd: dict[str, Any], peer_id: int = 0, window: Window | None = None) -> bool:
|
||||
return is_cmd_allowed(pcmd, cast(Any, window), peer_id > 0, {}, peer_id) is True
|
||||
|
||||
# continuations from the same origin with only the data changed are allowed
|
||||
open_stream('s1', peer_id=7)
|
||||
self.assertTrue(allowed(chunk('s1', b'y'), 7))
|
||||
self.assertTrue(allowed(chunk('s1', b''), 7))
|
||||
# continuations must not change anything other than the data
|
||||
self.assertFalse(allowed(chunk('s1', payload={'cmdline': ['evil']}), 7))
|
||||
self.assertFalse(allowed(chunk('s1', payload={'env': ['A=b']}), 7))
|
||||
self.assertFalse(allowed({**chunk('s1'), 'async': 'other'}, 7))
|
||||
self.assertFalse(allowed({**chunk('s1'), 'cmd': 'set-window-logo'}, 7))
|
||||
# continuations must come from the origin that opened the stream
|
||||
self.assertFalse(allowed(chunk('s1'), 8))
|
||||
self.assertFalse(allowed(chunk('s1'), 0, Window(7, 1)))
|
||||
self.assertFalse(allowed(chunk('unknown'), 7))
|
||||
|
||||
# cancellations only abort streams opened from the same origin
|
||||
cancel = {'cmd': 'run', 'version': [0, 26, 0], 'stream_id': 's1', 'async': 'a-s1', 'cancel_async': True}
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, dict(cancel), 8, None))
|
||||
self.assertIn('s1', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, 's1')
|
||||
self.assertIsNone(handle_cmd(Mock(spec=KittyBoss), None, dict(cancel), 7, None))
|
||||
self.assertNotIn('s1', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, '')
|
||||
self.assertIsNone(command.stream_in_flight.tempfile)
|
||||
self.assertFalse(allowed(chunk('s1'), 7))
|
||||
|
||||
# streams are aborted when the peer or window that opened them goes away
|
||||
w = Window(5, 1)
|
||||
open_stream('s2', peer_id=7)
|
||||
open_stream('s3', window=w)
|
||||
self.assertTrue(allowed(chunk('s3'), 0, w))
|
||||
abort_active_streams_from(peer_id=7)
|
||||
self.assertNotIn('s2', active_streams)
|
||||
self.assertIn('s3', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, 's3')
|
||||
abort_active_streams_from(window_id=w.id)
|
||||
self.assertNotIn('s3', active_streams)
|
||||
self.ae(command.stream_in_flight.stream_id, '')
|
||||
|
||||
# a command has only one stream in flight, opening another aborts the first
|
||||
open_stream('s4', peer_id=7)
|
||||
open_stream('s5', peer_id=8)
|
||||
self.assertNotIn('s4', active_streams)
|
||||
self.assertFalse(allowed(chunk('s4'), 7))
|
||||
self.assertTrue(allowed(chunk('s5'), 8))
|
||||
|
||||
# the number of registered streams is bounded
|
||||
for i in range(40):
|
||||
register_active_stream(f'many-{i}', chunk(f'many-{i}'), None, 9)
|
||||
self.ae(len(active_streams), 32)
|
||||
self.assertNotIn('many-0', active_streams)
|
||||
self.assertIn('many-39', active_streams)
|
||||
|
||||
def test_combine_parse_error_reporting(self):
|
||||
from kitty.boss import Boss as KittyBoss
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue