forked from kenzuya/unshackle
fix(api): refuse peer cache files that name types other than datetime
The server and the client both check a forwarded cache file before they write it, because Cacher decodes it with jsonpickle. The session-create cache write now runs off the event loop.
This commit is contained in:
@@ -23,7 +23,7 @@ from aiohttp import web
|
||||
from unshackle.core.api.compression import safe_inflate
|
||||
from unshackle.core.api.errors import APIError, APIErrorCode, categorize_exception, handle_api_exception
|
||||
from unshackle.core.api.input_bridge import AuthStatus, InputBridge, NoUserBridge
|
||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, sanitize_log
|
||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload, sanitize_log
|
||||
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
|
||||
from unshackle.core.api.session_store import SessionStore
|
||||
from unshackle.core.cacher import Cacher
|
||||
@@ -316,9 +316,9 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
|
||||
"""Write a client-sent ``cache`` map into the cache directory ``cache_tag``.
|
||||
|
||||
Each cache key is a file path relative to that directory, and each value is the file as
|
||||
base64 of zlib-compressed bytes. The function skips an unsafe key or a file it cannot write,
|
||||
and raises INVALID_INPUT for a map that is not an object, has too many entries, or holds a
|
||||
value that is not a string.
|
||||
base64 of zlib-compressed bytes. The function skips an unsafe key, a file that names a type
|
||||
other than a datetime, or a file it cannot write, and raises INVALID_INPUT for a map that is
|
||||
not an object, has too many entries, or holds a value that is not a string.
|
||||
"""
|
||||
if not isinstance(cache_data, dict) or len(cache_data) > MAX_SESSION_CACHE_KEYS:
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, f"cache must hold at most {MAX_SESSION_CACHE_KEYS} entries")
|
||||
@@ -332,6 +332,9 @@ def write_client_cache(cache_data: Any, cache_tag: str) -> None:
|
||||
if not isinstance(content, str):
|
||||
raise APIError(APIErrorCode.INVALID_INPUT, "cache values must be base64 strings")
|
||||
decompressed = safe_inflate(base64.b64decode(content)).decode("utf-8")
|
||||
if not safe_cache_payload(decompressed):
|
||||
log.warning(f"Rejecting session cache file {sanitize_log(key)}: it holds a type a peer may not send")
|
||||
continue
|
||||
target = cache_dir / f"{safe_name}.json"
|
||||
try:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
@@ -3895,7 +3898,7 @@ async def session_create_handler(data: Dict[str, Any], request: Optional[web.Req
|
||||
|
||||
cache_data = data.get("cache", {})
|
||||
if cache_data and session_cache_tag:
|
||||
write_client_cache(cache_data, session_cache_tag)
|
||||
await asyncio.to_thread(write_client_cache, cache_data, session_cache_tag)
|
||||
|
||||
service_instance._input_bridge = bridge
|
||||
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
from pathlib import PureWindowsPath
|
||||
from typing import Optional
|
||||
@@ -41,3 +42,38 @@ def safe_cache_key(key: object) -> Optional[str]:
|
||||
if any(not part or part in {".", ".."} or part.endswith((" ", ".")) or ":" in part for part in parts):
|
||||
return None
|
||||
return "/".join(parts)
|
||||
|
||||
|
||||
SAFE_PICKLE_TAGS = frozenset({"py/object", "py/type", "py/reduce", "py/tuple", "py/set", "py/b64", "py/id"})
|
||||
SAFE_PICKLE_TYPES = frozenset(
|
||||
{"datetime.datetime", "datetime.date", "datetime.time", "datetime.timedelta", "datetime.timezone"}
|
||||
)
|
||||
|
||||
|
||||
def safe_cache_payload(text: str) -> bool:
|
||||
"""True when a peer-supplied cache file is JSON that jsonpickle decodes to plain data and datetimes only.
|
||||
|
||||
``Cacher`` decodes cache files with jsonpickle, which imports and calls any type a file names,
|
||||
so a file from another machine may name the datetime types and nothing else.
|
||||
"""
|
||||
try:
|
||||
root = json.loads(text)
|
||||
except (ValueError, RecursionError):
|
||||
return False
|
||||
stack = [root]
|
||||
while stack:
|
||||
node = stack.pop()
|
||||
if isinstance(node, list):
|
||||
stack.extend(node)
|
||||
elif isinstance(node, dict):
|
||||
for key, value in node.items():
|
||||
if key.startswith("py/") and key not in SAFE_PICKLE_TAGS:
|
||||
return False
|
||||
if key in ("py/object", "py/type") and not (isinstance(value, str) and value in SAFE_PICKLE_TYPES):
|
||||
return False
|
||||
if key in ("py/reduce", "__reduce__") and not (
|
||||
isinstance(value, list) and value and isinstance(value[0], dict) and value[0].keys() == {"py/type"}
|
||||
):
|
||||
return False
|
||||
stack.append(value)
|
||||
return True
|
||||
|
||||
@@ -1977,12 +1977,13 @@ class RemoteService:
|
||||
can forward them back, skipping interactive auth. The same filter that
|
||||
:meth:`load_cache_files` applies drops a file that belongs to another
|
||||
credential or profile, so it cannot overwrite that profile's local file.
|
||||
The client also refuses a file that names a type other than a datetime.
|
||||
"""
|
||||
if not cache_data:
|
||||
return
|
||||
|
||||
from unshackle.core.api.compression import safe_inflate
|
||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key
|
||||
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, safe_cache_payload
|
||||
|
||||
if len(cache_data) > MAX_SESSION_CACHE_KEYS:
|
||||
self.log.warning(f"Ignoring {len(cache_data)} cache files from server: more than {MAX_SESSION_CACHE_KEYS}")
|
||||
@@ -2003,6 +2004,11 @@ class RemoteService:
|
||||
continue
|
||||
try:
|
||||
decompressed = safe_inflate(base64.b64decode(content))
|
||||
if not safe_cache_payload(decompressed.decode("utf-8")):
|
||||
self.log.warning(
|
||||
f"Rejecting cache file '{safe_name}' from the server: it holds a type a peer may not send"
|
||||
)
|
||||
continue
|
||||
# Not with_suffix: that would turn the key "keys.v2" into "keys.json".
|
||||
target = cache_dir / f"{safe_name}.json"
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
Reference in New Issue
Block a user