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
fix(pairing): verify Ed25519 proof-of-possession on pairing poll
Juan Denisf295103f293e
diff --git a/agent/internal/pairdriver/driver.go b/agent/internal/pairdriver/driver.goindex b6c23d99..8c616fc2 100644--- a/agent/internal/pairdriver/driver.go+++ b/agent/internal/pairdriver/driver.go@@ -78,6 +78,7 @@ func Run(sysMap := buildSystemInfo(sysInfo, displayName)client := pairing.NewClient(panelURL, log)+ client.SetKeyPair(kp) // enables Ed25519 proof-of-possession on pollenrollCtx, enrollCancel := context.WithTimeout(ctx, 30*time.Second)enrollResp, err := client.Enroll(enrollCtx, pairing.EnrollRequest{Pubkey: kp.PublicKeyHex(),diff --git a/agent/internal/pairing/client.go b/agent/internal/pairing/client.goindex c79c65ae..034026c2 100644--- a/agent/internal/pairing/client.go+++ b/agent/internal/pairing/client.go@@ -4,6 +4,7 @@ import ("bytes""context""crypto/tls"+ "encoding/base64""encoding/json""fmt""io"@@ -66,9 +67,17 @@ type Client struct {UserAgent stringEnrollmentID stringEnrollmentSecret string+ keypair *KeyPairlog *logger.Logger}+// SetKeyPair attaches the agent's Ed25519 keypair so Poll can prove+// possession of the private key matching the enrolled pubkey. Optional: when+// unset, Poll falls back to bearer-secret-only auth (older behavior).+func (c *Client) SetKeyPair(kp *KeyPair) {+ c.keypair = kp+}+// NewClient constructs a pairing client. baseURL must be the panel HTTPS root.func NewClient(baseURL string, log *logger.Logger) *Client {baseURL = strings.TrimSuffix(baseURL, "/")@@ -122,8 +131,16 @@ func (c *Client) SetFreeze(ctx context.Context, frozen bool) (*RefreshResponse,// Returns (claimed, credentials, err). If err is nil and claimed is false the// caller should reconnect immediately for another long-poll.func (c *Client) Poll(ctx context.Context) (bool, *Credentials, error) {+ headers := c.enrollHeaders()+ // Prove possession of the enrolled private key by signing the+ // enrollment_id. The panel verifies this against the pubkey we submitted at+ // enroll() time, so a stolen enrollment_secret alone can't claim our creds.+ if c.keypair != nil && c.EnrollmentID != "" {+ sig := base64.StdEncoding.EncodeToString(c.keypair.Sign([]byte(c.EnrollmentID)))+ headers.Set("X-Enrollment-Signature", sig)+ }var resp PollResponse- if err := c.do(ctx, "GET", "/api/v1/pairing/poll", nil, c.enrollHeaders(), &resp); err != nil {+ if err := c.do(ctx, "GET", "/api/v1/pairing/poll", nil, headers, &resp); err != nil {return false, nil, err}if resp.Status == "claimed" && resp.Credentials != nil {diff --git a/agent/internal/pairing/keypair.go b/agent/internal/pairing/keypair.goindex 9f638bcd..51e1483d 100644--- a/agent/internal/pairing/keypair.go+++ b/agent/internal/pairing/keypair.go@@ -27,6 +27,13 @@ func (k *KeyPair) PublicKeyHex() string {return hex.EncodeToString(k.Public)}+// Sign produces an Ed25519 signature over message using the private key.+// Used for pairing proof-of-possession: the panel verifies the signature+// against the enrolled public key before releasing credentials.+func (k *KeyPair) Sign(message []byte) []byte {+ return ed25519.Sign(k.Private, message)+}+// DefaultKeyPath returns the OS-specific default path for the pairing keyfile.func DefaultKeyPath() string {if runtime.GOOS == "windows" {diff --git a/backend/app/api/pairing.py b/backend/app/api/pairing.pyindex 423e4ef8..f1248b10 100644--- a/backend/app/api/pairing.py+++ b/backend/app/api/pairing.py@@ -114,12 +114,20 @@ def poll():if not enrollment_id or not enrollment_secret:return jsonify({'error': 'Missing enrollment credentials'}), 401+ # Optional Ed25519 proof-of-possession over the enrollment_id. Sent as a+ # header (works for GET long-polls) or in the JSON body. It's constant for a+ # given enrollment, so read it once before the long-poll loop.+ signature = request.headers.get('X-Enrollment-Signature')+ if not signature and request.is_json:+ signature = (request.get_json(silent=True) or {}).get('signature')+deadline = time.time() + 25.0 # leave headroom under typical proxy timeoutspoll_interval = 1.0while True:try:- result = pairing_service.poll(enrollment_id, enrollment_secret)+ result = pairing_service.poll(enrollment_id, enrollment_secret,+ signature=signature)except PairingError as exc:return _error_response(exc)diff --git a/backend/app/services/pairing_service.py b/backend/app/services/pairing_service.pyindex 3f747b16..3f467f2e 100644--- a/backend/app/services/pairing_service.py+++ b/backend/app/services/pairing_service.py@@ -15,6 +15,7 @@ Flow:5. The agent's next /poll returns the credentials. Done."""+import base64import jsonimport loggingimport secrets@@ -214,15 +215,57 @@ def set_freeze(enrollment_id: str, enrollment_secret: str, frozen: bool) -> dictreturn {'pair_code_frozen': pending.pair_code_frozen}-def poll(enrollment_id: str, enrollment_secret: str) -> dict:+def _verify_pop(pubkey_hex: str, enrollment_id: str, signature_b64: str) -> bool:+ """Verify an Ed25519 proof-of-possession signature over the enrollment_id.++ The agent signs the enrollment_id with the private key whose public half it+ submitted at enroll() time. pubkey is stored as lowercase hex of the raw+ 32-byte Ed25519 key; the signature is base64 of the raw 64-byte signature.+ Any decode/verify failure returns False (never raises) so a malformed or+ wrong-key signature is treated as a failed proof, not a 500.+ """+ if not pubkey_hex or not signature_b64:+ return False+ try:+ from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey+ pub = Ed25519PublicKey.from_public_bytes(bytes.fromhex(pubkey_hex))+ pub.verify(base64.b64decode(signature_b64), enrollment_id.encode())+ return True+ except Exception:+ return False+++def poll(enrollment_id: str, enrollment_secret: str,+ signature: Optional[str] = None) -> dict:"""Called by the agent to check whether an operator has claimed it yet.+ signature (optional): base64 Ed25519 signature over the enrollment_id,+ proving possession of the private key matching the enrolled pubkey. When+ supplied it MUST verify before anything is returned — so a stolen+ enrollment_secret alone can't claim the credentials of a device whose+ private key the attacker lacks. Verification is best-effort for backward+ compatibility: agents that predate signing omit it and fall back to+ bearer-secret-only auth (this becomes mandatory once signing agents have+ rolled out — see SECURITY.md).+Returns:{'status': 'pending', ...} if still waiting.{'status': 'claimed', 'credentials': {...}} once claimed (delivered ONCE)."""pending = _load_pending_for_agent(enrollment_id, enrollment_secret)++ # Proof-of-possession: a present signature must verify against the enrolled+ # pubkey. A present-but-invalid signature is an attack (or key mismatch) and+ # is rejected outright, before last_seen_at or any state is touched.+ if signature is not None:+ if not _verify_pop(pending.pubkey, enrollment_id, signature):+ logger.warning(+ "Pairing poll signature verification FAILED for enrollment %s",+ enrollment_id,+ )+ raise InvalidEnrollmentError("Invalid proof-of-possession signature")+pending.last_seen_at = datetime.utcnow()if pending.is_claimed() and pending.claim_payload_encrypted:diff --git a/backend/tests/test_pairing_pop.py b/backend/tests/test_pairing_pop.pynew file mode 100644index 00000000..65e70139--- /dev/null+++ b/backend/tests/test_pairing_pop.py@@ -0,0 +1,67 @@+"""+Tests for Ed25519 proof-of-possession in the short-code pairing poll (bug D).++The agent enrolls a hex-encoded Ed25519 pubkey, then signs the enrollment_id+with the matching private key on each poll. The panel verifies that signature+when present, so a stolen enrollment_secret alone can't claim a device whose+private key the attacker lacks. Verification is best-effort for backward+compatibility: a poll with no signature still works (older agents), but a+present-but-invalid signature is rejected.+"""+import base64++import pytest+from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey+from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat++from app.services import pairing_service+from app.services.pairing_service import InvalidEnrollmentError+++def _enroll():+ """Enroll a fresh keypair; return (private_key, enrollment dict)."""+ priv = Ed25519PrivateKey.generate()+ raw_pub = priv.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw)+ pubkey_hex = raw_pub.hex()+ enr = pairing_service.enroll(pubkey_hex, "pass1234", "machine-pop", {})+ return priv, enr+++def _sig(priv, enrollment_id):+ return base64.b64encode(priv.sign(enrollment_id.encode())).decode()+++def test_poll_accepts_valid_signature(app):+ priv, enr = _enroll()+ eid, esec = enr['enrollment_id'], enr['enrollment_secret']++ res = pairing_service.poll(eid, esec, signature=_sig(priv, eid))+ # Not claimed yet, but the signature was accepted (no exception raised).+ assert res['status'] == 'pending'+++def test_poll_rejects_invalid_signature(app):+ priv, enr = _enroll()+ eid, esec = enr['enrollment_id'], enr['enrollment_secret']+ bad_sig = base64.b64encode(b'\x00' * 64).decode()++ with pytest.raises(InvalidEnrollmentError):+ pairing_service.poll(eid, esec, signature=bad_sig)+++def test_poll_rejects_signature_from_wrong_key(app):+ _priv, enr = _enroll()+ eid, esec = enr['enrollment_id'], enr['enrollment_secret']+ attacker = Ed25519PrivateKey.generate()+ wrong_sig = base64.b64encode(attacker.sign(eid.encode())).decode()++ with pytest.raises(InvalidEnrollmentError):+ pairing_service.poll(eid, esec, signature=wrong_sig)+++def test_poll_without_signature_is_backward_compatible(app):+ _priv, enr = _enroll()+ eid, esec = enr['enrollment_id'], enr['enrollment_secret']++ res = pairing_service.poll(eid, esec)+ assert res['status'] == 'pending'