mirror of
https://github.com/Droid-Deck/DroidDeck.git
synced 2026-11-19 04:46:08 +00:00
Restrict Xbox credential IPC and address launch review findings (#1164)
* Restrict Xbox credentials to host backends and lease game launches * Verify mapped PRoot backend images and retry lease heartbeat timeouts * Bound Xbox backend shutdown and isolate service socket lifetimes * Keep unique Xbox service sockets within Unix address limits * Own licensed launch directories and recover abandoned views safely * Serialize Xbox account revocation with sign-in commits and launch authorization
This commit is contained in:
1 parent
f5bba17f53
commit
6bbcf3ad8b
27 files changed
+834
-85
No files matched your search
@@ -316,7 +316,11 @@ def main():
|
||||
if mic_enabled == "0":
|
||||
env["BANNER_AUDIO_DIRECT_MIC"] = "0"
|
||||
env = force_ssbs(command, env)
|
||||
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
|
||||
try:
|
||||
xbox = runpy.run_path(str(Path(__file__).with_name("droiddeck-xbox")))
|
||||
except Exception as error:
|
||||
print("droiddeck-game-env: Xbox support unavailable (%s); stock launch" % error, file=sys.stderr)
|
||||
xbox = {"launch": lambda command, env: None}
|
||||
try:
|
||||
xbox_result = xbox["launch"](command, env)
|
||||
except (OSError, ValueError, KeyError, RuntimeError) as error:
|
||||
|
||||
@@ -102,15 +102,16 @@ def bridge(upstream):
|
||||
return server.getsockname()[1], key.decode('ascii'), close
|
||||
|
||||
|
||||
def wine(argv):
|
||||
with open(os.environ['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file:
|
||||
def wine(argv, source_env=None):
|
||||
source_env = os.environ if source_env is None else source_env
|
||||
with open(source_env['DROIDDECK_XBOX_COMMAND_FILE'], encoding='utf-8') as file:
|
||||
command = json.load(file)
|
||||
if len(command) < 3 or command[1] != 'waitforexitandrun' or len(argv) != 1:
|
||||
raise ValueError('Invalid Xbox Proton invocation')
|
||||
env = dict(os.environ)
|
||||
env = dict(source_env)
|
||||
env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
|
||||
env.pop('DROIDDECK_XBOX_COMMAND_FILE', None)
|
||||
prefix = Path(os.environ['STEAM_COMPAT_DATA_PATH']) / 'pfx'
|
||||
prefix = Path(source_env['STEAM_COMPAT_DATA_PATH']) / 'pfx'
|
||||
prefix.parent.mkdir(parents=True, exist_ok=True)
|
||||
if not (prefix / 'system.reg').is_file():
|
||||
result = subprocess.run([command[0], 'run', 'cmd', '/c', 'exit', '0'], stdout=sys.stderr, env=env)
|
||||
@@ -128,10 +129,21 @@ def wine(argv):
|
||||
return subprocess.call([*command[:2], argv[0], *command[3:]], env=env)
|
||||
|
||||
|
||||
def renew_lease(ask, channel, product, lease, stopped):
|
||||
while not stopped.wait(15):
|
||||
response = ask(channel, {'op': 'xbox-renew', 'id': product, 'lease': lease}, timeout=10)
|
||||
if response is not None and response.get('ok') is False:
|
||||
return
|
||||
|
||||
|
||||
def launch(command, env):
|
||||
if len(command) < 3 or command[1] != 'waitforexitandrun' or env.get('DROIDDECK_XBOX_ACTIVE') == '1':
|
||||
return None
|
||||
store = runpy.run_path(str(BIN / 'droiddeck-store-launch'))
|
||||
try:
|
||||
store = runpy.run_path(str(BIN / 'droiddeck-store-launch'))
|
||||
except Exception as error:
|
||||
print('droiddeck-xbox: store detection unavailable (%s); stock launch' % error, file=sys.stderr)
|
||||
return None
|
||||
found = store['find_store_game'](command[2:])
|
||||
if found is None or found[1].get('store') != 'xbox':
|
||||
return None
|
||||
@@ -142,19 +154,26 @@ def launch(command, env):
|
||||
launch_dir = env.get('BL_LAUNCH_DIR')
|
||||
if not launch_dir:
|
||||
raise RuntimeError('No Xbox account channel; start the game from DroidDeck')
|
||||
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=95)
|
||||
reply = store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-prepare', 'id': sidecar['id']}, timeout=190)
|
||||
if not reply or not reply.get('ok'):
|
||||
raise RuntimeError('Xbox account service is unavailable; sign in again and retry')
|
||||
port, key, close = bridge(reply['socket'])
|
||||
stopped = threading.Event()
|
||||
close = lambda: None
|
||||
try:
|
||||
port, key, close = bridge(reply['socket'])
|
||||
|
||||
threading.Thread(target=renew_lease, args=(store['ask'], Path(launch_dir) / 'stores',
|
||||
sidecar['id'], reply['lease'], stopped), daemon=True).start()
|
||||
with tempfile.TemporaryDirectory(prefix='droiddeck-xbox-') as temporary:
|
||||
context = Path(temporary) / 'command.json'
|
||||
context.write_text(json.dumps(command), encoding='utf-8')
|
||||
context.chmod(0o600)
|
||||
owned_env = dict(env, DROIDDECK_XBOX_ACTIVE='1', DROIDDECK_XBOX_COMMAND_FILE=str(context),
|
||||
DROIDDECK_XBOX_CREDENTIAL_SOCKET=reply['credentials'],
|
||||
XODUS_SOCKET=reply['socket'], XODUS_BRIDGE_PORT=str(port), XODUS_BRIDGE_KEY=key,
|
||||
XODUS_LOG='off', RUST_LOG='off', XODUS_SAVE_SYNC='auto' if sidecar.get('cloud', True) else 'off')
|
||||
owned_env.pop('DROIDDECK_XBOX_CREDENTIAL_SOCKET', None)
|
||||
if reply.get('playfab'):
|
||||
owned_env['XODUS_XSTS_PLAYFAB'] = reply['playfab']
|
||||
content = folder / '.xbox-content'
|
||||
roots = []
|
||||
if content.is_dir():
|
||||
@@ -167,12 +186,11 @@ def launch(command, env):
|
||||
pass
|
||||
if roots:
|
||||
owned_env['XODUS_CONTENT_ROOTS'] = ';'.join(roots)
|
||||
market = sidecar.get('extra', {}).get('market', 'US')
|
||||
return subprocess.call([str(RUNTIME / 'xodus-cli'), 'run', str(folder), str(BIN / 'droiddeck-xbox'),
|
||||
'--exe', sidecar['exe'], '--materialize-chain', '--market', market], env=owned_env)
|
||||
return wine([reply['exe']], owned_env)
|
||||
finally:
|
||||
stopped.set()
|
||||
close()
|
||||
store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-released', 'id': sidecar['id']})
|
||||
store['ask'](Path(launch_dir) / 'stores', {'op': 'xbox-released', 'lease': reply['lease']})
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
|
||||
@@ -43,6 +43,17 @@ class ReadConfigMappingTest(unittest.TestCase):
|
||||
|
||||
|
||||
class GameEnvironmentTest(unittest.TestCase):
|
||||
def test_optional_xbox_loader_failure_keeps_stock_launch(self):
|
||||
from unittest.mock import patch
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
calls = []
|
||||
with patch.dict(os.environ, {}, clear=True), patch('sys.argv', ['droiddeck-game-env', '/stock', 'run']), \
|
||||
patch('runpy.run_path', side_effect=error), patch('os.execvpe', side_effect=lambda *args: calls.append(args)), \
|
||||
patch.dict(MODULE['main'].__globals__, load_sync=lambda: None, select_sync=lambda command, env, sync: (command, env)):
|
||||
MODULE['main']()
|
||||
self.assertEqual(calls[0][0:2], ('/stock', ['/stock', 'run']))
|
||||
|
||||
|
||||
def test_directaudio_capture_follows_the_session_microphone_setting(self):
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
home = Path(tmp)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
|
||||
class XboxBuildSourceTest(unittest.TestCase):
|
||||
def test_main_advancing_between_jobs_does_not_change_packaged_source(self):
|
||||
try:
|
||||
import yaml
|
||||
except ImportError:
|
||||
self.fail('PyYAML is required to execute workflow steps')
|
||||
workflow = yaml.safe_load((Path(__file__).resolve().parents[2] / '.github/workflows/build.yml').read_text())
|
||||
jobs = workflow['jobs']
|
||||
step = lambda job, name: next(s['run'] for s in jobs[job]['steps'] if s.get('name') == name)
|
||||
with tempfile.TemporaryDirectory() as directory:
|
||||
root = Path(directory)
|
||||
env = dict(os.environ, GIT_AUTHOR_NAME='test', GIT_COMMITTER_NAME='test',
|
||||
GIT_AUTHOR_EMAIL='test@example.test', GIT_COMMITTER_EMAIL='test@example.test',
|
||||
GITHUB_STEP_SUMMARY=str(root / 'summary'))
|
||||
def git(*args, cwd=root):
|
||||
return subprocess.check_output(['git', *args], cwd=cwd, env=env, stderr=subprocess.DEVNULL, text=True).strip()
|
||||
git('init', '-q', '-b', 'main')
|
||||
(root / 'backend').write_text('base')
|
||||
git('add', '.'); git('commit', '-qm', 'base')
|
||||
git('switch', '-qc', 'feature')
|
||||
(root / 'app').write_text('feature')
|
||||
git('add', '.'); git('commit', '-qm', 'feature')
|
||||
head = git('rev-parse', 'HEAD')
|
||||
git('switch', '-q', 'main')
|
||||
(root / 'backend').write_text('merged backend')
|
||||
git('commit', '-qam', 'backend changed after branch')
|
||||
for name in ('xbox', 'apk'):
|
||||
git('clone', '-q', str(root), str(root / name))
|
||||
git('checkout', '-q', head, cwd=root / name)
|
||||
output = root / 'output'
|
||||
env['GITHUB_OUTPUT'] = str(output)
|
||||
subprocess.run(['bash', '-c', step('xbox', 'Pin and merge the APK source')], cwd=root / 'xbox', env=env, check=True, capture_output=True)
|
||||
base = output.read_text().strip().split('=', 1)[1]
|
||||
tree = git('rev-parse', 'HEAD^{tree}', cwd=root / 'xbox')
|
||||
(root / 'backend').write_text('newer main, after backend build')
|
||||
git('commit', '-qam', 'main advanced again')
|
||||
env.update(BUILD_BASE_SHA=base, XBOX_SOURCE_TREE=tree)
|
||||
subprocess.run(['bash', '-c', step('build', 'Merge onto main, or say what conflicts')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
subprocess.run(['bash', '-c', step('build', 'Verify backend and APK source match')], cwd=root / 'apk', env=env, check=True, capture_output=True)
|
||||
self.assertEqual((root / 'apk/backend').read_text(), 'merged backend')
|
||||
self.assertEqual(git('rev-parse', 'HEAD^{tree}', cwd=root / 'apk'), tree)
|
||||
@@ -19,6 +19,64 @@ class XboxLaunchTest(unittest.TestCase):
|
||||
(folder / '.droiddeck-store.json').write_text(json.dumps({'store': 'gog', 'id': '1'}))
|
||||
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', str(folder / 'Game.exe')], {}))
|
||||
|
||||
def test_renewal_retries_a_timeout_and_stops_after_rejection(self):
|
||||
stopped = unittest.mock.Mock()
|
||||
stopped.wait.side_effect = [False, False, False, AssertionError('renewed a rejected lease')]
|
||||
ask = unittest.mock.Mock(side_effect=[None, {'ok': True}, {'ok': False}])
|
||||
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
|
||||
self.assertEqual(ask.call_count, 3)
|
||||
|
||||
def test_stopping_a_launch_stops_renewal_without_another_request(self):
|
||||
stopped = threading.Event()
|
||||
stopped.set()
|
||||
ask = unittest.mock.Mock()
|
||||
xbox['renew_lease'](ask, Path('/channel'), 'GAME', 'lease-1', stopped)
|
||||
ask.assert_not_called()
|
||||
|
||||
def test_missing_store_detector_keeps_stock_launch(self):
|
||||
for error in (FileNotFoundError('missing'), RuntimeError('module initialization failed')):
|
||||
with self.subTest(error=error), patch('runpy.run_path', side_effect=error):
|
||||
self.assertIsNone(xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {}))
|
||||
|
||||
def test_launch_uses_prepared_image_and_never_receives_account_credentials(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
runtime = root / 'runtime/windows'
|
||||
runtime.mkdir(parents=True)
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).write_bytes(b'MZ')
|
||||
store = {'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}),
|
||||
'ask': unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1',
|
||||
'exe': '/private/Game.exe', 'playfab': 'game-token'})}
|
||||
close = unittest.mock.Mock()
|
||||
with patch('runpy.run_path', return_value=store), patch.dict(xbox['launch'].__globals__, RUNTIME=runtime.parent), \
|
||||
patch.dict(xbox['launch'].__globals__, bridge=lambda path: (1234, 'key', close)), \
|
||||
patch.dict(xbox['launch'].__globals__, wine=unittest.mock.Mock(return_value=7)):
|
||||
launch = xbox['launch']
|
||||
self.assertEqual(launch(['/proton', 'waitforexitandrun', '/encrypted/Game.exe'],
|
||||
{'BL_LAUNCH_DIR': '/launch', 'DROIDDECK_XBOX_CREDENTIAL_SOCKET': 'stale'}), 7)
|
||||
wine = launch.__globals__['wine']
|
||||
self.assertEqual(wine.call_args.args[0], ['/private/Game.exe'])
|
||||
env = wine.call_args.args[1]
|
||||
self.assertNotIn('DROIDDECK_XBOX_CREDENTIAL_SOCKET', env)
|
||||
self.assertEqual(env['XODUS_XSTS_PLAYFAB'], 'game-token')
|
||||
close.assert_called_once()
|
||||
self.assertEqual(store['ask'].call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
|
||||
def test_bridge_start_failure_still_releases_the_lease(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
root = Path(root)
|
||||
runtime = root / 'windows'
|
||||
runtime.mkdir()
|
||||
for name in xbox['DLLS']:
|
||||
(runtime / name).touch()
|
||||
ask = unittest.mock.Mock(return_value={'ok': True, 'socket': '/service', 'lease': 'lease-1'})
|
||||
with patch('runpy.run_path', return_value={'find_store_game': lambda argv: (root, {'store': 'xbox', 'id': 'GAME'}), 'ask': ask}), \
|
||||
patch.dict(xbox['launch'].__globals__, RUNTIME=root, bridge=unittest.mock.Mock(side_effect=OSError('bind failed'))):
|
||||
with self.assertRaises(OSError):
|
||||
xbox['launch'](['/proton', 'waitforexitandrun', '/Game.exe'], {'BL_LAUNCH_DIR': '/launch'})
|
||||
self.assertEqual(ask.call_args.args[1], {'op': 'xbox-released', 'lease': 'lease-1'})
|
||||
|
||||
def test_bridge_authenticates_before_forwarding(self):
|
||||
with tempfile.TemporaryDirectory() as root:
|
||||
path = str(Path(root) / 'service.sock')
|
||||
|
||||
+20
-3
@@ -24,16 +24,33 @@ in the build cache and publishes both in CI's `xbox-corresponding-source`
|
||||
artifact; distribute corresponding sources with published binaries.
|
||||
|
||||
`droiddeck-credentials.patch` replaces Linux Secret Service with a bounded,
|
||||
UID-checked Android abstract socket. The Android host encrypts every persistent
|
||||
Android abstract socket restricted to the backend process started by the host. The Android host encrypts every persistent
|
||||
write using its existing Keystore cipher, verifies backend read-backs, and
|
||||
rejects writes when Keystore is unavailable. No token values enter process
|
||||
arguments, external storage, application logs or a plaintext credential file.
|
||||
Account-generation invalidation prevents a signed-out child's later writes from
|
||||
restoring credentials. Each process gets its own unguessable socket name.
|
||||
restoring credentials. Each backend gets its own socket. The host checks the peer UID, the PRoot tracer
|
||||
owned by its live child, and an executable mapping of the backend file with a matching inode and
|
||||
SHA-256 against the APK asset. PRoot's loader can occupy `/proc/<pid>/exe`, so
|
||||
authentication checks the mapped backend image instead. A socket name alone grants no credential operations, including to another
|
||||
copy of Xodus started by the guest.
|
||||
|
||||
Licensed launch-view preparation runs in an Android-owned Xodus child, which
|
||||
never starts Wine or a game. An in-memory, single-use Play authorization is
|
||||
required before the guest can request preparation. The reply contains a random
|
||||
launch lease, a materialized executable path, a game-service socket and the
|
||||
existing PlayFab game token; it contains no account credential endpoint.
|
||||
Leases bind product, account and session, expire without heartbeats, and release
|
||||
idempotently. Cancellation, session stop and account changes revoke leases;
|
||||
closing the child's stdin lets it remove its private view. Suspension preserves
|
||||
live leases. Launch Xbox games through DroidDeck's Play action; an unsolicited
|
||||
launch from inside Steam has no Play authorization.
|
||||
The Proton initialization and game processes do not inherit the raw credential
|
||||
channel or command-file environment variables. The authenticated GDK bridge
|
||||
remains available to the game. Like the other stores, games share DroidDeck's
|
||||
Linux environment and Android UID; this is not a sandbox against malicious games.
|
||||
Linux environment and Android UID. The process checks close the direct
|
||||
credential-socket route; they do not isolate writable runtime files, prevent
|
||||
same-UID process tampering, or provide a sandbox against malicious games.
|
||||
|
||||
Microsoft sign-in uses Nexus's private stdio protocol in an isolated Android
|
||||
WebView process. Its page bridge is restricted to the allowed Microsoft/Xbox
|
||||
|
||||
@@ -84,3 +84,23 @@
|
||||
}
|
||||
|
||||
#[test]
|
||||
--- a/crates/xodus-cli/src/commands/run.rs
|
||||
+++ b/crates/xodus-cli/src/commands/run.rs
|
||||
@@ -618 +618,17 @@
|
||||
+ if wine == "droiddeck:prepare" {
|
||||
+ use std::io::Write;
|
||||
+ if !materialize_chain { return ExitCode::FAILURE; }
|
||||
+ let ready = serde_json::json!({
|
||||
+ "exe": stub_path,
|
||||
+ "playfab": playfab_auth_header(client, tokens).await,
|
||||
+ });
|
||||
+ println!("DROIDDECK_LAUNCH_V1 {}", ready);
|
||||
+ let _ = std::io::stdout().flush();
|
||||
+ let mut release = String::new();
|
||||
+ let _ = std::io::stdin().read_line(&mut release);
|
||||
+ drop(launch_mirror);
|
||||
+ cleanup().await;
|
||||
+ return ExitCode::SUCCESS;
|
||||
+ }
|
||||
+
|
||||
let mut command = Command::new(wine);
|
||||
Reference in new issue
Block a user