ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
feat(connect): open commands sealed to this server's own key
Juan Denisfd64ec09badd
diff --git a/backend/app/services/connect_client.py b/backend/app/services/connect_client.pyindex 099f1a91..233bc494 100644--- a/backend/app/services/connect_client.py+++ b/backend/app/services/connect_client.py@@ -475,7 +475,7 @@ def build_hello(private_key, device_id: str, client_version: str) -> dict:ts = int(time.time())nonce = secrets.token_hex(16)sig = private_key.sign(f'{device_id}|{ts}|{nonce}'.encode()).hex()- return {+ hello = {'t': 'hello','device_id': device_id,'ts': ts,@@ -484,6 +484,14 @@ def build_hello(private_key, device_id: str, client_version: str) -> dict:'proto': PROTO_VERSION,'client_version': client_version,}+ try:+ # Publish this panel's end-to-end key, signed with its identity key.+ # Failing here is not fatal: without it commands+ # arrive under TLS as before, and Cloud says so per server.+ hello.update(connect_keys.e2e_hello_fields(private_key, device_id))+ except Exception:+ logger.debug('Connect: could not publish the end-to-end key', exc_info=True)+ return helloHELLO_HEADERS = {@@ -493,6 +501,10 @@ HELLO_HEADERS = {'sig': 'X-ServerKit-Sig','proto': 'X-ServerKit-Proto','client_version': 'X-ServerKit-Client-Version',+ # The end-to-end key travels on the long-poll fallback too, so a panel in+ # limited mode is not quietly less private than one on a WebSocket.+ 'x25519_pubkey': 'X-ServerKit-X25519',+ 'x25519_sig': 'X-ServerKit-X25519-Sig',}diff --git a/backend/app/services/connect_commands.py b/backend/app/services/connect_commands.pyindex 39b24bbe..2afef238 100644--- a/backend/app/services/connect_commands.py+++ b/backend/app/services/connect_commands.py@@ -14,6 +14,14 @@ checks four things, in this order and with no shortcuts:claim. ServerKit Cloud checks the customer's grant before it signs; this is thesecond check, on the machine that would do the work.+A command's arguments arrive one of two ways. Where this panel has published+an end-to-end key, they are `sealed`: encrypted to that key+by ServerKit Cloud, so the relay carries them without being able to read them — which is+what makes it safe to send a storage credential through it. Otherwise they are+`args`, protected by TLS on both legs. `unseal_args` is where the two meet, and+a sealed payload this panel cannot open is a refused command rather than a+guess.+Only then is the action looked up in HANDLERS. An action this client versiondoes not implement fails with that sentence rather than silently succeeding —the operator sees "this server's ServerKit is too old for that" in Cloud,@@ -148,6 +156,19 @@ def handler(action: str):return register+def unseal_args(claims: dict) -> dict:+ """The command's arguments, whether they arrived sealed or in the clear.++ A sealed payload we cannot open raises: running a command with arguments+ we guessed at is worse than not running it.+ """+ sealed = claims.get('sealed')+ if not sealed:+ return claims.get('args') or {}+ from app.services import connect_keys+ return connect_keys.open_sealed(claims.get('device_id') or '', sealed)++def run(claims: dict, app=None) -> dict:"""Execute one verified command. Returns {ok, summary, code, output}.@@ -161,7 +182,15 @@ def run(claims: dict, app=None) -> dict:'summary': f'This server\'s ServerKit does not know how to run {action}. 'f'Update it and try again.'}try:- out = fn(claims.get('args') or {}, app)+ args = unseal_args(claims)+ except Exception as exc:+ logger.warning('Connect command %s: could not unseal its arguments: %s', action, exc)+ return {'ok': False, 'code': 400,+ 'summary': 'This command arrived encrypted to a key this panel could not use, '+ 'so it was not run. Nothing was changed. Reconnect the panel to '+ 'ServerKit Cloud to publish a fresh key.'}+ try:+ out = fn(args, app)except Exception as exc:logger.warning('Connect command %s failed: %s', action, exc, exc_info=True)return {'ok': False, 'code': 500, 'summary': f'{type(exc).__name__}: {exc}'}diff --git a/backend/app/services/connect_keys.py b/backend/app/services/connect_keys.pyindex 6d979f44..33e3e92f 100644--- a/backend/app/services/connect_keys.py+++ b/backend/app/services/connect_keys.py@@ -21,6 +21,12 @@ from app import pathslogger = logging.getLogger(__name__)KEY_FILENAME = 'connect_device_key.pem'+# The second keypair: X25519, used only to unseal command+# payloads. Separate from the identity key on purpose — an encryption key and+# a signing key have different lifetimes and different blast radii.+E2E_KEY_FILENAME = 'connect_e2e_key.bin'+# What the identity key signs so ServerKit Cloud knows this X25519 key is really ours.+E2E_BINDING = 'x25519'def default_key_path() -> str:@@ -100,3 +106,91 @@ def load_or_create_keypair(path: str = None):pubkey_bytes = _public_bytes(private_key)return private_key, pubkey_bytes.hex(), fingerprint_of(pubkey_bytes)+++# ==================== end-to-end key ====================+++def default_e2e_key_path() -> str:+ return os.path.join(paths.SERVERKIT_CONFIG_DIR, E2E_KEY_FILENAME)+++def load_or_create_e2e_key(path: str = None):+ """The X25519 private key this panel unseals commands with.++ Raw 32 bytes on disk at 0600, not PEM: it is a symmetric-shaped secret+ with no certificate story around it, and a file that is exactly the key is+ a file nobody misreads.++ Returns (private_key, pubkey_hex).+ """+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey++ path = path or default_e2e_key_path()+ if os.path.exists(path):+ with open(path, 'rb') as f:+ raw = f.read()+ if len(raw) != 32:+ raise ValueError(f'{path} is not a 32-byte X25519 private key')+ private_key = X25519PrivateKey.from_private_bytes(raw)+ if os.name != 'nt':+ os.chmod(path, 0o600)+ else:+ private_key = X25519PrivateKey.generate()+ os.makedirs(os.path.dirname(path), exist_ok=True)+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)+ try:+ with os.fdopen(fd, 'wb') as f:+ f.write(private_key.private_bytes_raw())+ except Exception:+ try:+ os.unlink(path)+ except OSError:+ pass+ raise+ if os.name != 'nt':+ os.chmod(path, 0o600)+ logger.info('Generated ServerKit Cloud end-to-end key at %s', path)+ return private_key, private_key.public_key().public_bytes_raw().hex()+++def e2e_binding_message(device_id: str, pubkey_hex: str) -> bytes:+ """The bytes the identity key signs to publish an X25519 key. Must match+ the control plane's binding message exactly, or it will not seal."""+ return f'{device_id}|{E2E_BINDING}|{pubkey_hex}'.encode()+++def e2e_hello_fields(identity_key, device_id: str, path: str = None) -> dict:+ """The two hello fields that publish this panel's end-to-end key.++ Signed with the identity key, so a relay that wanted to read command+ payloads cannot substitute a key of its own — it does not have this+ signature and cannot make one.+ """+ _private, pubkey_hex = load_or_create_e2e_key(path)+ sig = identity_key.sign(e2e_binding_message(device_id, pubkey_hex)).hex()+ return {'x25519_pubkey': pubkey_hex, 'x25519_sig': sig}+++def open_sealed(device_id: str, sealed: dict, path: str = None) -> dict:+ """Unseal a command payload. Raises if the algorithm is not one we know:+ a command we cannot read is refused, never guessed at."""+ import base64+ import json++ from cryptography.hazmat.primitives import hashes+ from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PublicKey+ from cryptography.hazmat.primitives.ciphers.aead import AESGCM+ from cryptography.hazmat.primitives.kdf.hkdf import HKDF++ alg = (sealed or {}).get('alg')+ if alg != 'x25519-hkdf-aesgcm/v1':+ raise ValueError(f'unknown sealing algorithm {alg!r}')+ private_key, _ = load_or_create_e2e_key(path)+ shared = private_key.exchange(+ X25519PublicKey.from_public_bytes(bytes.fromhex(sealed['epk'])))+ key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,+ info=b'serverkit/cmd/v1|' + device_id.encode()).derive(shared)+ plaintext = AESGCM(key).decrypt(base64.b64decode(sealed['nonce']),+ base64.b64decode(sealed['ct']), device_id.encode())+ return json.loads(plaintext.decode())diff --git a/backend/tests/test_connect_sealing.py b/backend/tests/test_connect_sealing.pynew file mode 100644index 00000000..72222598--- /dev/null+++ b/backend/tests/test_connect_sealing.py@@ -0,0 +1,176 @@+"""The panel half of end-to-end sealed commands.++ServerKit Cloud seals a command's arguments to this panel's X25519 key so the relay+carries them without being able to read them. These tests re-implement ServerKit Cloud's+sealing here — the same scheme, written independently from the specification —+and check that this panel opens it. If the two ever drift apart, this fails+rather than a customer's backup silently stopping.+"""+import base64+import json+import os++import pytest+from cryptography.hazmat.primitives import hashes+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey+from cryptography.hazmat.primitives.asymmetric.x25519 import X25519PrivateKey, X25519PublicKey+from cryptography.hazmat.primitives.ciphers.aead import AESGCM+from cryptography.hazmat.primitives.kdf.hkdf import HKDF++from app.services import connect_commands, connect_keys++DEVICE = 'dev_abc123'+++def key_dir(tmp_path, monkeypatch):+ monkeypatch.setattr(connect_keys.paths, 'SERVERKIT_CONFIG_DIR', str(tmp_path))+ return tmp_path+++def seal_like_cloud(device_pubkey_hex: str, device_id: str, payload: dict) -> dict:+ """The control plane's sealing routine, written from the specification rather+ than imported: this is the interop check."""+ peer = X25519PublicKey.from_public_bytes(bytes.fromhex(device_pubkey_hex))+ ephemeral = X25519PrivateKey.generate()+ shared = ephemeral.exchange(peer)+ key = HKDF(algorithm=hashes.SHA256(), length=32, salt=None,+ info=b'serverkit/cmd/v1|' + device_id.encode()).derive(shared)+ nonce = os.urandom(12)+ body = json.dumps(payload, separators=(',', ':'), sort_keys=True).encode()+ return {+ 'alg': 'x25519-hkdf-aesgcm/v1',+ 'epk': ephemeral.public_key().public_bytes_raw().hex(),+ 'nonce': base64.b64encode(nonce).decode(),+ 'ct': base64.b64encode(AESGCM(key).encrypt(nonce, body, device_id.encode())).decode(),+ }+++# ---------- the key ----------+++def test_the_key_is_generated_once_and_reused(key_dir):+ _, first = connect_keys.load_or_create_e2e_key()+ _, second = connect_keys.load_or_create_e2e_key()+ assert first == second+ assert len(bytes.fromhex(first)) == 32+++def test_the_key_file_is_exactly_the_key(key_dir):+ connect_keys.load_or_create_e2e_key()+ path = connect_keys.default_e2e_key_path()+ assert os.path.getsize(path) == 32+++def test_a_truncated_key_file_is_refused_rather_than_used(key_dir):+ connect_keys.load_or_create_e2e_key()+ with open(connect_keys.default_e2e_key_path(), 'wb') as f:+ f.write(b'short')+ with pytest.raises(ValueError):+ connect_keys.load_or_create_e2e_key()+++def test_the_hello_publishes_the_key_signed_with_the_identity_key(key_dir):+ identity = Ed25519PrivateKey.generate()+ fields = connect_keys.e2e_hello_fields(identity, DEVICE)+ assert set(fields) == {'x25519_pubkey', 'x25519_sig'}+ # ServerKit Cloud verifies exactly this, so this test is that check run locally.+ identity.public_key().verify(+ bytes.fromhex(fields['x25519_sig']),+ connect_keys.e2e_binding_message(DEVICE, fields['x25519_pubkey']))+++def test_the_binding_message_is_the_one_cloud_expects(key_dir):+ assert connect_keys.e2e_binding_message('dev_x', 'ab') == b'dev_x|x25519|ab'+++# ---------- opening what ServerKit Cloud sealed ----------+++def test_this_panel_opens_what_cloud_sealed(key_dir):+ _, pubkey_hex = connect_keys.load_or_create_e2e_key()+ payload = {'secret': 's3cr3t-value', 'bucket': 'sk-backups', 'prefix': 'serverkit/x/'}+ sealed = seal_like_cloud(pubkey_hex, DEVICE, payload)+ assert 's3cr3t-value' not in json.dumps(sealed)+ assert connect_keys.open_sealed(DEVICE, sealed) == payload+++def test_a_payload_sealed_for_another_server_will_not_open(key_dir):+ _, pubkey_hex = connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(pubkey_hex, 'dev_someone_else', {'secret': 'x'})+ with pytest.raises(Exception):+ connect_keys.open_sealed(DEVICE, sealed)+++def test_a_payload_sealed_to_a_different_key_will_not_open(key_dir):+ stranger = X25519PrivateKey.generate().public_key().public_bytes_raw().hex()+ connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(stranger, DEVICE, {'secret': 'x'})+ with pytest.raises(Exception):+ connect_keys.open_sealed(DEVICE, sealed)+++def test_an_unknown_algorithm_is_refused(key_dir):+ _, pubkey_hex = connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(pubkey_hex, DEVICE, {'x': 1})+ sealed['alg'] = 'rot13'+ with pytest.raises(ValueError):+ connect_keys.open_sealed(DEVICE, sealed)+++# ---------- the command runner ----------+++def test_a_command_with_plain_arguments_still_runs(key_dir):+ assert connect_commands.unseal_args({'args': {'a': 1}}) == {'a': 1}+ assert connect_commands.unseal_args({}) == {}+++def test_a_sealed_command_is_unsealed_before_the_handler_sees_it(key_dir):+ _, pubkey_hex = connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(pubkey_hex, DEVICE, {'bucket': 'sk-backups'})+ got = connect_commands.unseal_args({'device_id': DEVICE, 'sealed': sealed})+ assert got == {'bucket': 'sk-backups'}+++def test_a_sealed_command_we_cannot_open_is_refused_not_guessed(key_dir):+ """Running a command with arguments we guessed at is worse than not+ running it, so the handler never sees a half-read payload."""+ seen = []++ @connect_commands.handler('test.sealed')+ def _handler(args, app=None):+ seen.append(args)+ return {'ok': True}++ try:+ stranger = X25519PrivateKey.generate().public_key().public_bytes_raw().hex()+ connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(stranger, DEVICE, {'do': 'something'})+ out = connect_commands.run({'action': 'test.sealed', 'device_id': DEVICE,+ 'sealed': sealed})+ assert out['ok'] is False+ assert 'could not use' in out['summary']+ assert 'Nothing was changed' in out['summary']+ assert seen == [], 'the handler must not run on arguments we could not read'+ finally:+ connect_commands.HANDLERS.pop('test.sealed', None)+++def test_a_sealed_command_reaches_its_handler_intact(key_dir):+ seen = []++ @connect_commands.handler('test.sealed_ok')+ def _handler(args, app=None):+ seen.append(args)+ return {'ok': True, 'summary': 'done'}++ try:+ _, pubkey_hex = connect_keys.load_or_create_e2e_key()+ sealed = seal_like_cloud(pubkey_hex, DEVICE, {'secret': 'shh'})+ out = connect_commands.run({'action': 'test.sealed_ok', 'device_id': DEVICE,+ 'sealed': sealed})+ assert out['ok'] is True+ assert seen == [{'secret': 'shh'}]+ finally:+ connect_commands.HANDLERS.pop('test.sealed_ok', None)