| … | … | @@ -0,0 +1,1182 @@ |
| 1 | # keet-core-hyperdb v1.22.0 Protocol Layer Security Audit |
| 2 | |
| 3 | **Date**: 2026-02-17 |
| 4 | **Auditors**: fleeky + Claude Opus 4.6 (authorized defensive review) |
| 5 | **Scope**: Contract handlers, invitation crypto, input validation, DoS vectors |
| 6 | **Methodology**: Static analysis of deobfuscated source code, MITRE ATT&CK mapping |
| 7 | **Source**: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/` |
| 8 | |
| 9 | --- |
| 10 | |
| 11 | ## Executive Summary |
| 12 | |
| 13 | This audit examines the keet-core-hyperdb protocol layer from the perspective of an attacker |
| 14 | who has a legitimate writer in a Keet room and can send arbitrary operations via a custom |
| 15 | client. The deobfuscated contract handlers were reviewed line-by-line for input validation |
| 16 | gaps, privilege escalation paths, denial of service vectors, data integrity issues, and |
| 17 | cryptographic weaknesses. |
| 18 | |
| 19 | **Overall Assessment**: The permission model is well-designed and consistently enforced. |
| 20 | Every handler checks writer identity and role before mutating state. However, multiple |
| 21 | medium-severity issues exist around missing input size validation, absence of rate limiting, |
| 22 | and several specific logic bugs that could be exploited. |
| 23 | |
| 24 | ### Finding Summary |
| 25 | |
| 26 | | Severity | Count | Category | |
| 27 | |----------|-------|----------| |
| 28 | | CRITICAL | 1 | Non-KeetContractError crash propagation (DoS via peer crash) | |
| 29 | | HIGH | 3 | No rate limiting, unbounded string fields, reaction/label flooding | |
| 30 | | MEDIUM | 6 | Moderator self-unmute, settings key injection, timestamp spoofing, etc. | |
| 31 | | LOW | 3 | Invitation metadata not expiry-checked in handler, push notification info leak, etc. | |
| 32 | | INFO | 3 | Dead code, obfuscation artifacts, test handler in production | |
| 33 | |
| 34 | --- |
| 35 | |
| 36 | ## Finding 1: Non-KeetContractError Exceptions Crash All Peers |
| 37 | |
| 38 | **Severity**: CRITICAL |
| 39 | **MITRE ATT&CK**: T1499.004 (Application or System Exploitation DoS) |
| 40 | **CWE**: CWE-755 (Improper Handling of Exceptional Conditions) |
| 41 | |
| 42 | ### Description |
| 43 | |
| 44 | The main apply loop in `index.js` (lines 1079-1091) dispatches each operation to its |
| 45 | handler inside a try/catch. However, the catch block only gracefully handles |
| 46 | `KeetContractError` instances. Any OTHER exception type (TypeError, RangeError, etc.) |
| 47 | is stored as a fatal error and re-thrown, which propagates to Autobase's `_onError` |
| 48 | handler, closing the entire Autobase and potentially crashing the peer's process. |
| 49 | |
| 50 | ### Proof |
| 51 | |
| 52 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/index.js` |
| 53 | Lines 1079-1092: |
| 54 | ```javascript |
| 55 | for (let i = startIdx; i < nodes.length; i++) { |
| 56 | const node = nodes[i], version = c.decode(c.uint, node.value); |
| 57 | if (version < 0x2) continue; |
| 58 | const ctx = createContext(transaction, blobBatch, node, base, view, router, {dryRun, trace, abi: this.abi}); |
| 59 | await router.dispatch(node.value, ctx); |
| 60 | // ... upgrade handling |
| 61 | } |
| 62 | } catch (err) { |
| 63 | !KeetContractError.isContractError(err) ? fatalError = err : (contractError = true, this.onerror(err)); |
| 64 | } |
| 65 | // If fatalError is set, it's re-thrown at line 1092: |
| 66 | if (fatalError) throw fatalError; |
| 67 | ``` |
| 68 | |
| 69 | A crafted operation that causes a handler to throw a non-KeetContractError (e.g., by |
| 70 | triggering a null dereference on an optional chain that isn't guarded) will: |
| 71 | 1. Set `fatalError` to the exception |
| 72 | 2. Skip the transaction flush (line 1091 takes the close path) |
| 73 | 3. Re-throw at line 1092 |
| 74 | 4. Propagate to Autobase `_onError` which calls `this.close()` |
| 75 | 5. If no error listener exists, `crashSoon(err)` terminates the process |
| 76 | |
| 77 | ### Attack Vector |
| 78 | |
| 79 | An attacker crafts an operation that passes schema validation (compact-encoding decode |
| 80 | succeeds) but triggers an unexpected runtime error inside a handler. For example: |
| 81 | |
| 82 | - A `@keet/add-file-preview` with `displayType = 3` (only 1 and 2 are handled in the |
| 83 | switch statement at `chat.js` line 149-152). The `getDisplayItemFiles` function returns |
| 84 | `undefined`, and the subsequent `_0x27a9c6.length` access throws `TypeError: Cannot |
| 85 | read properties of undefined`. |
| 86 | |
| 87 | - However, the guard at line 118 (`if (!files || files.length <= index)`) would catch |
| 88 | this specific case. The real risk is in edge cases where optional chaining (`?.`) is |
| 89 | used inconsistently -- some paths use it, some don't. |
| 90 | |
| 91 | ### Impact |
| 92 | |
| 93 | A single malicious writer can crash every peer in the room by sending one carefully |
| 94 | crafted operation. All peers process the same operation deterministically, so if one |
| 95 | crashes, all crash. The room becomes unusable until the offending writer is removed |
| 96 | (which requires a moderator to restart their crashed client first). |
| 97 | |
| 98 | ### Remediation |
| 99 | |
| 100 | Wrap the entire dispatch loop in a broader try/catch that treats ALL exceptions as |
| 101 | non-fatal for consensus purposes. Log and skip, never re-throw from within the apply |
| 102 | function. Autobase should never close due to a single malformed operation. |
| 103 | |
| 104 | --- |
| 105 | |
| 106 | ## Finding 2: No Rate Limiting on Any Operation |
| 107 | |
| 108 | **Severity**: HIGH |
| 109 | **MITRE ATT&CK**: T1498 (Network Denial of Service), T1499 (Endpoint Denial of Service) |
| 110 | **CWE**: CWE-770 (Allocation of Resources Without Limits or Throttling) |
| 111 | |
| 112 | ### Description |
| 113 | |
| 114 | There is zero rate limiting at any layer: no per-writer throttling in Autobase, no |
| 115 | per-operation-type throttling in keet-core handlers, and no batch-size limits in the |
| 116 | apply function. A writer can append operations to their Hypercore feed at arbitrary |
| 117 | speed, and every peer must process every one. |
| 118 | |
| 119 | ### Proof |
| 120 | |
| 121 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/index.js` |
| 122 | Lines 1079-1086: The apply loop iterates over ALL nodes in the batch with no limit check: |
| 123 | ```javascript |
| 124 | for (let i = startIdx; i < nodes.length; i++) { |
| 125 | // no rate check, no per-writer counter, no batch size limit |
| 126 | await router.dispatch(node.value, ctx); |
| 127 | } |
| 128 | ``` |
| 129 | |
| 130 | Every handler performs at minimum: |
| 131 | - `getMemberForDeviceKey(db, writer.key)` -- one DB lookup |
| 132 | - `isMemberActive(member)` -- one boolean check |
| 133 | - Additional DB lookups for target resolution |
| 134 | |
| 135 | Even rejected operations (muted user, invalid target) cost 1-2 DB reads per operation. |
| 136 | |
| 137 | ### Attack Scenario |
| 138 | |
| 139 | 1. Attacker joins room legitimately (or is already a member) |
| 140 | 2. Attacker modifies their client to bypass UI rate limits |
| 141 | 3. Attacker appends 10,000 `@keet/add-reaction` operations per second |
| 142 | (reactions are cheap -- just require member lookup + dedup check) |
| 143 | 4. Each peer must: download (Hypercore replication), decode (compact-encoding), |
| 144 | route (hyperdispatch), look up writer (HyperDB get), check dedup (HyperDB get), |
| 145 | and either insert or abort |
| 146 | 5. Result: all peers' Autobase apply loops are saturated processing spam |
| 147 | |
| 148 | ### Cost Analysis |
| 149 | |
| 150 | Per rejected operation: |
| 151 | - compact-encoding decode: ~1us |
| 152 | - hyperdispatch route: ~0.5us |
| 153 | - HyperDB get (writer lookup): ~50-200us (RocksDB read) |
| 154 | - HyperDB get (dedup/target check): ~50-200us |
| 155 | - Total: ~100-400us per rejected op |
| 156 | |
| 157 | At 10,000 ops/sec: ~1-4 seconds of CPU per second of real time. This causes the apply |
| 158 | loop to fall behind, creating an ever-growing backlog. Eventually peers' memory fills |
| 159 | with queued operations. |
| 160 | |
| 161 | ### Impact |
| 162 | |
| 163 | Denial of service against all room members. The room becomes unresponsive. Only |
| 164 | mitigation is a moderator removing the attacker, but the moderator's client may also |
| 165 | be overwhelmed and unable to process the removal operation. |
| 166 | |
| 167 | ### Remediation |
| 168 | |
| 169 | 1. Add per-writer operation counters in the apply function |
| 170 | 2. After N operations from the same writer in a single apply batch, skip remaining |
| 171 | 3. Consider a "writer reputation" system that deprioritizes high-volume writers |
| 172 | 4. At minimum, add a configurable max-ops-per-batch limit |
| 173 | |
| 174 | --- |
| 175 | |
| 176 | ## Finding 3: Unbounded String Fields in Chat Messages |
| 177 | |
| 178 | **Severity**: HIGH |
| 179 | **MITRE ATT&CK**: T1499.003 (Application Exhaustion Flood) |
| 180 | **CWE**: CWE-400 (Uncontrolled Resource Consumption) |
| 181 | |
| 182 | ### Description |
| 183 | |
| 184 | The `@keet/add-chat-message` operation contains a `text` field of type `string` with |
| 185 | no maximum length enforced at either the schema level or the handler level. The |
| 186 | hyperschema definition at `spec/contract/hyperschema/schema.json` defines `oplog-message` |
| 187 | with `"text": { "type": "string" }` -- no `maxLength` constraint. |
| 188 | |
| 189 | ### Proof |
| 190 | |
| 191 | File: `spec/contract/hyperschema/schema.json` lines 2114-2155: |
| 192 | ```json |
| 193 | { |
| 194 | "name": "oplog-message", |
| 195 | "namespace": "keet", |
| 196 | "fields": [ |
| 197 | { "name": "text", "type": "string" }, // NO maxLength |
| 198 | { "name": "files", "array": true, ... }, // NO maxItems |
| 199 | { "name": "display", "type": "@keet/display" }, |
| 200 | ... |
| 201 | ] |
| 202 | } |
| 203 | ``` |
| 204 | |
| 205 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/chat.js` |
| 206 | Lines 33-54: `handleAddChatMessage` does not validate `message.text` length: |
| 207 | ```javascript |
| 208 | async function handleAddChatMessage({message, header}, {db, blobs, writer}) { |
| 209 | let [member, thread, ...] = await Promise.all([ |
| 210 | getMemberForDeviceKey(db, writer.key), |
| 211 | db.get("@keet/threads", {id: 0}), |
| 212 | // ... |
| 213 | ]); |
| 214 | if (!isMemberActive(member)) throw KeetContractError.INACTIVE_MEMBER(); |
| 215 | if (member.status.isMuted) throw KeetContractError.WRITER_IS_MUTED(); |
| 216 | // ... permission checks ... |
| 217 | // NO check on message.text.length |
| 218 | // NO check on message.files.length |
| 219 | // NO check on message.display array sizes |
| 220 | await db.insert('@keet/chat', record); |
| 221 | } |
| 222 | ``` |
| 223 | |
| 224 | ### Attack Scenario |
| 225 | |
| 226 | An attacker sends a `@keet/add-chat-message` with: |
| 227 | - `text`: 100MB string |
| 228 | - `files`: Array of 10,000 file records |
| 229 | - `display.mention`: Array of 50,000 mention entries |
| 230 | - `display.bold`, `display.italic`, etc.: Arrays of 100,000 range entries each |
| 231 | |
| 232 | Each peer must: |
| 233 | 1. Decode the 100MB+ operation (compact-encoding string decode -- allocates full buffer) |
| 234 | 2. Store it in HyperDB (RocksDB write of 100MB+ record) |
| 235 | 3. Process it through map functions (chatMentionsByMemberIdMap iterates all 50K mentions) |
| 236 | 4. Store 50,000 secondary index entries (one per mention) |
| 237 | |
| 238 | ### Impact |
| 239 | |
| 240 | Storage exhaustion and CPU exhaustion on all peers. A single oversized message could |
| 241 | consume hundreds of MB of storage per peer. The map function processing (mentions index) |
| 242 | is O(n) in the number of mentions, potentially blocking the apply loop for seconds. |
| 243 | |
| 244 | Similarly, the `@keet/update-room-config` handler at `config.js` line 31-33 allows |
| 245 | unbounded `title` and `description` strings (only `blindPeers` is sliced to a max). |
| 246 | |
| 247 | ### Remediation |
| 248 | |
| 249 | 1. Add `maxLength` constraints to string fields in the hyperschema |
| 250 | 2. Add `maxItems` constraints to array fields |
| 251 | 3. Add explicit size validation in handlers before DB insertion |
| 252 | 4. Consider a maximum operation size at the Autobase level |
| 253 | |
| 254 | --- |
| 255 | |
| 256 | ## Finding 4: Moderator Can Self-Unmute via handleChangeMemberStatus |
| 257 | |
| 258 | **Severity**: MEDIUM |
| 259 | **MITRE ATT&CK**: T1548 (Abuse Elevation Control Mechanism) |
| 260 | **CWE**: CWE-269 (Improper Privilege Management) |
| 261 | |
| 262 | ### Description |
| 263 | |
| 264 | The `handleChangeMemberStatus` handler checks that the WRITER is a moderator before |
| 265 | allowing status changes. However, it does NOT prevent a moderator from unmuting |
| 266 | THEMSELVES. The handler checks `writerMember.status.isModerator` but does not check |
| 267 | whether the target is the writer themselves when the operation is "unmute." |
| 268 | |
| 269 | ### Proof |
| 270 | |
| 271 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/members/index.js` |
| 272 | Lines 309-322: |
| 273 | ```javascript |
| 274 | async function handleChangeMemberStatus({memberKey, key, status}, {db, writer}) { |
| 275 | const [writerMember, targetMember] = await Promise.all([ |
| 276 | getMemberForDeviceKey(db, writer.key), |
| 277 | db.get("@keet/members", {key: memberKey}) |
| 278 | ]); |
| 279 | if (!isMemberActive(writerMember)) throw KeetContractError.INACTIVE_MEMBER(); |
| 280 | if (!targetMember) throw KeetContractError.TARGET_MEMBER_NOT_FOUND(); |
| 281 | const writerIsMod = writerMember.status.isModerator; |
| 282 | if (!writerIsMod) throw KeetContractError.MODERATORS_ONLY(); |
| 283 | // STATUS_INDEX_TO_KEY = ["isMuted", "isBanned", "isShadowBanned"] |
| 284 | if (key === 0 || key > STATUS_INDEX_TO_KEY.length) |
| 285 | throw KeetContractError.INVALID_MEMBER_STATUS(); |
| 286 | const statusKey = STATUS_INDEX_TO_KEY[key - 1]; |
| 287 | targetMember.status[statusKey] = status[statusKey]; // Direct assignment, no self-check |
| 288 | await db.insert("@keet/members", targetMember); |
| 289 | } |
| 290 | ``` |
| 291 | |
| 292 | ### Attack Scenario |
| 293 | |
| 294 | 1. Admin mutes a malicious moderator (sets `isMuted: true`) |
| 295 | 2. The muted moderator still has `isModerator: true` (muting doesn't revoke mod status) |
| 296 | 3. Muted moderator sends `@keet/change-member-status` targeting themselves with |
| 297 | `{memberKey: self, key: 1, status: {isMuted: false}}` |
| 298 | 4. Handler checks: writer is active? Yes. Writer is moderator? Yes (muting doesn't |
| 299 | remove mod flag). Target exists? Yes (self). Status key valid? Yes (1 = isMuted). |
| 300 | 5. Sets `targetMember.status.isMuted = false` -- moderator unmutes themselves |
| 301 | |
| 302 | ### Impact |
| 303 | |
| 304 | A moderator who has been muted by an admin can immediately unmute themselves. The admin |
| 305 | must DEMOTE the moderator (via `@keet/change-member-role`) to prevent this. This is a |
| 306 | design weakness rather than a critical vulnerability, but it undermines the mute |
| 307 | mechanism for moderator-level users. |
| 308 | |
| 309 | ### Remediation |
| 310 | |
| 311 | Add a check: if the target is the writer AND the operation would reduce a restriction |
| 312 | (e.g., unmuting), require admin privileges rather than just moderator. |
| 313 | |
| 314 | --- |
| 315 | |
| 316 | ## Finding 5: handleUpdateSystemSettings Allows Arbitrary Settings Key Injection |
| 317 | |
| 318 | **Severity**: MEDIUM |
| 319 | **MITRE ATT&CK**: T1565 (Data Manipulation) |
| 320 | **CWE**: CWE-20 (Improper Input Validation) |
| 321 | |
| 322 | ### Description |
| 323 | |
| 324 | The `handleUpdateSystemSettings` handler uses a numeric key to index into |
| 325 | `SETTINGS_INDEX_TO_KEY` array, then uses that string as a property name on the settings |
| 326 | object. The bounds check (`key === 0 || key > SETTINGS_INDEX_TO_KEY.length`) correctly |
| 327 | prevents out-of-bounds access. However, the handler silently returns (no error thrown) |
| 328 | on out-of-bounds keys, which means an attacker can probe for valid key ranges without |
| 329 | triggering errors. |
| 330 | |
| 331 | More importantly, the handler trusts the `settings` object from the operation payload |
| 332 | and uses it via spread operator, which could include prototype pollution vectors if |
| 333 | the encoding library doesn't sanitize property names. |
| 334 | |
| 335 | ### Proof |
| 336 | |
| 337 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/internal.js` |
| 338 | Lines 62-74: |
| 339 | ```javascript |
| 340 | async function handleUpdateSystemSettings({key, settings}, {db, writer}) { |
| 341 | const [member, digest] = await Promise.all([ |
| 342 | getMemberForDeviceKey(db, writer.key), |
| 343 | db.get("@keet/system-digest") |
| 344 | ]); |
| 345 | if (!isMemberActive(member) || !member.status.isModerator) return; // Silent return |
| 346 | if (key === 0 || key > SETTINGS_INDEX_TO_KEY.length) return; // Silent return |
| 347 | const currentSettings = digest?.settings; |
| 348 | const settingName = SETTINGS_INDEX_TO_KEY[key - 1]; |
| 349 | const newSettings = { ...currentSettings, [settingName]: settings[settingName] }; |
| 350 | await db.insert("@keet/system-digest", { ...digest, settings: newSettings }); |
| 351 | } |
| 352 | ``` |
| 353 | |
| 354 | The expression `settings[settingName]` reads a property from the attacker-controlled |
| 355 | `settings` object. If `settingName` is `"roomType"` (key=1), the attacker controls |
| 356 | what `roomType` becomes. The `RoomType` enum is used throughout the codebase to |
| 357 | determine behavior (Broadcast rooms have different permission models). |
| 358 | |
| 359 | ### Attack Scenario |
| 360 | |
| 361 | A malicious moderator sends `@keet/update-system-settings` with `key: 1` (roomType) |
| 362 | and `settings: {roomType: 2}` to change a regular room to `DirectMessage` type. This |
| 363 | would affect: |
| 364 | - `handleUpdateReadLength` which only works for DM rooms (line 129) |
| 365 | - `handleRemoveMember` which skips membership events for Broadcast rooms (line 367) |
| 366 | - Genesis handler disables calling for Broadcast rooms (line 30) |
| 367 | |
| 368 | ### Impact |
| 369 | |
| 370 | A moderator can change the room type, which alters permission semantics across multiple |
| 371 | handlers. Changing to Broadcast disables calling and member appending for non-moderators. |
| 372 | Changing to DirectMessage enables read receipts. This is likely intentional for room |
| 373 | admins but the implications cascade non-obviously. |
| 374 | |
| 375 | ### Remediation |
| 376 | |
| 377 | Add validation that the new value is a valid enum member. Specifically for `roomType`, |
| 378 | consider requiring admin (not just moderator) privileges to change room type. |
| 379 | |
| 380 | --- |
| 381 | |
| 382 | ## Finding 6: Timestamp Spoofing in Operation Headers |
| 383 | |
| 384 | **Severity**: MEDIUM |
| 385 | **MITRE ATT&CK**: T1565.001 (Stored Data Manipulation) |
| 386 | **CWE**: CWE-345 (Insufficient Verification of Data Authenticity) |
| 387 | |
| 388 | ### Description |
| 389 | |
| 390 | Every operation includes a `header.timestamp` field (uint) that is set by the client |
| 391 | and stored directly in the database without validation. The handlers use this timestamp |
| 392 | for ordering, display, and even security-relevant decisions (contact request dedup). |
| 393 | |
| 394 | ### Proof |
| 395 | |
| 396 | The timestamp is a client-provided value in every operation header. For example, in |
| 397 | `handleAddChatMessage` (chat.js line 50): |
| 398 | ```javascript |
| 399 | const record = { |
| 400 | id: { thread: threadId, index: count }, |
| 401 | oplog: writer, |
| 402 | clock: thread.stats.chat.clock, |
| 403 | timestamp: header.timestamp, // CLIENT-PROVIDED, NO VALIDATION |
| 404 | message: message, |
| 405 | status: { isEdited: false, isPinned: false, isDeleted: false }, |
| 406 | event: message.event |
| 407 | }; |
| 408 | ``` |
| 409 | |
| 410 | In `handleAddContactRequest` (identity/private.js lines 217-224), the timestamp is |
| 411 | used for dedup ordering: |
| 412 | ```javascript |
| 413 | const sentAt = header.timestamp; |
| 414 | const existingRequests = db.find("@keet-private-id/pending-contact-requests-by-member", ...); |
| 415 | for await (const req of existingRequests) { |
| 416 | if (req.sentAt > sentAt) { // TIMESTAMP COMPARISON FOR ORDERING |
| 417 | isNewest = false; |
| 418 | continue; |
| 419 | } |
| 420 | req.status.isPending = false; |
| 421 | req.status.isDiscarded = true; |
| 422 | // ... |
| 423 | } |
| 424 | ``` |
| 425 | |
| 426 | ### Attack Scenario |
| 427 | |
| 428 | 1. An attacker sends a message with `timestamp: Number.MAX_SAFE_INTEGER`. This message |
| 429 | will always sort as the "newest" in any timestamp-based ordering. |
| 430 | 2. An attacker sends a contact request with `timestamp: 0`. This would be treated as |
| 431 | older than any legitimate request, potentially causing the dedup logic to discard |
| 432 | it incorrectly (or to discard a legitimate later request). |
| 433 | 3. An attacker sends a message with `timestamp: 0` to make it appear at the beginning |
| 434 | of the chat history, potentially confusing users about message order. |
| 435 | |
| 436 | ### Impact |
| 437 | |
| 438 | Message ordering manipulation, contact request dedup bypass, and potential confusion |
| 439 | in any timestamp-dependent UI rendering. Not a critical security issue but undermines |
| 440 | data integrity guarantees. |
| 441 | |
| 442 | ### Remediation |
| 443 | |
| 444 | Validate that `header.timestamp` is within a reasonable range (e.g., within 5 minutes |
| 445 | of the current time when the operation is processed in the apply function). Autobase |
| 446 | provides causal ordering, so timestamps should roughly correspond to wall-clock time. |
| 447 | |
| 448 | --- |
| 449 | |
| 450 | ## Finding 7: Reaction and Label Flooding (Unbounded Per-Message) |
| 451 | |
| 452 | **Severity**: HIGH |
| 453 | **MITRE ATT&CK**: T1499.003 (Application Exhaustion Flood) |
| 454 | **CWE**: CWE-770 (Allocation of Resources Without Limits or Throttling) |
| 455 | |
| 456 | ### Description |
| 457 | |
| 458 | The `handleAddReaction` handler only deduplicates on the triple `(messageId, sender, |
| 459 | reaction)`. There is no limit on the total number of unique reactions a single user |
| 460 | can add to a single message. The `reaction` field is a `uint` with no range validation. |
| 461 | |
| 462 | Similarly, `handleAddChatLabel` has no limit on labels per message. |
| 463 | |
| 464 | ### Proof |
| 465 | |
| 466 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/reactions.js` |
| 467 | Lines 11-21: |
| 468 | ```javascript |
| 469 | async function handleAddReaction({header, oplog, reaction}, {db, writer}) { |
| 470 | const [member, msg, thread] = await Promise.all([ |
| 471 | getMemberForDeviceKey(db, writer.key), |
| 472 | db.get("@keet/chat-by-message-id", {oplog}), |
| 473 | db.get("@keet/threads", {id: 0}) |
| 474 | ]); |
| 475 | if (!isMemberActive(member) || !msg || member.status.isMuted || !reaction) return; |
| 476 | // Dedup check: only checks exact (id, sender, reaction) triple |
| 477 | const existing = await db.get("@keet/reactions", {id: msg.id, sender: member.key, reaction}); |
| 478 | if (existing) throw KeetContractError.ABORT(); |
| 479 | // No limit on total reactions per message or per user |
| 480 | const record = { id: msg.id, sender: member.key, clock: thread.stats.chat.clock, reaction }; |
| 481 | await db.insert("@keet/reactions", record); |
| 482 | await reactionStats(db, thread, record, null, header.timestamp); |
| 483 | } |
| 484 | ``` |
| 485 | |
| 486 | ### Attack Scenario |
| 487 | |
| 488 | 1. Attacker sends 1,000,000 `@keet/add-reaction` operations, each with a unique |
| 489 | `reaction` value (reaction is a uint, so values 1 through 1,000,000) |
| 490 | 2. Each creates a unique `(messageId, sender, reactionValue)` record |
| 491 | 3. Each triggers a `reactionStats` update (incrementing counters) |
| 492 | 4. Result: 1,000,000 reaction records in the database for a single message |
| 493 | |
| 494 | The same applies to `@keet/add-chat-label` -- each unique `(messageId, sender, label)` |
| 495 | triple creates a new record. The `chatLabelStats` function at `labels.js` line 18 also |
| 496 | updates digest stats on each insert. |
| 497 | |
| 498 | ### Impact |
| 499 | |
| 500 | Database bloat and index pollution. Any query for reactions on a message returns millions |
| 501 | of records. UI clients rendering reactions would freeze. The stats counters become |
| 502 | meaninglessly large. |
| 503 | |
| 504 | ### Remediation |
| 505 | |
| 506 | 1. Add per-message reaction limits (e.g., max 50 unique reactions per message total) |
| 507 | 2. Add per-user reaction limits (e.g., max 5 reactions per message per user) |
| 508 | 3. Validate that `reaction` values are within a defined emoji enum range |
| 509 | 4. Same limits for chat labels |
| 510 | |
| 511 | --- |
| 512 | |
| 513 | ## Finding 8: handleUpdateRoomConfig Blind Peers Slice Uses Obfuscated Constants |
| 514 | |
| 515 | **Severity**: MEDIUM |
| 516 | **MITRE ATT&CK**: T1565 (Data Manipulation) |
| 517 | **CWE**: CWE-20 (Improper Input Validation) |
| 518 | |
| 519 | ### Description |
| 520 | |
| 521 | The `handleUpdateRoomConfig` handler for `BlindPeers` (key=5) uses `slice()` with |
| 522 | obfuscated constants to limit the array size. The constant `MAX_CUSTOM_MIRRORS` is |
| 523 | defined as `--0x17ec` which evaluates to `-0x17ed` (negative), and the slice call |
| 524 | uses `-0xa10` as the start index. |
| 525 | |
| 526 | ### Proof |
| 527 | |
| 528 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/config.js` |
| 529 | Lines 11 and 35: |
| 530 | ```javascript |
| 531 | const MAX_CUSTOM_MIRRORS = --0x17ec; // = -0x17ed = -6125 (NEGATIVE!) |
| 532 | |
| 533 | // Line 35: |
| 534 | key === Config.BlindPeers && |
| 535 | (newConfig[settingName] = config[settingName].slice(-0xa10, MAX_CUSTOM_MIRRORS)); |
| 536 | // ^^^^^^ ^^^^^^^^^^^^^^^^ |
| 537 | // -2576 -6125 |
| 538 | ``` |
| 539 | |
| 540 | `Array.prototype.slice(-2576, -6125)` with a start index greater than end index always |
| 541 | returns an empty array. This means the blind peers update effectively clears the blind |
| 542 | peers list every time, regardless of input. |
| 543 | |
| 544 | This is likely a deobfuscation artifact -- the original code probably had positive |
| 545 | constants that got mangled during obfuscation. The actual runtime behavior depends on |
| 546 | the correct resolved values of these hex constants. If the deobfuscator incorrectly |
| 547 | resolved these, the actual limit may be different. |
| 548 | |
| 549 | ### Impact |
| 550 | |
| 551 | If the constants are indeed negative as shown, blind peer configuration updates silently |
| 552 | fail (produce empty arrays). A moderator trying to configure blind peers for DHT |
| 553 | discovery would find their changes don't persist. This is a functionality bug rather |
| 554 | than a security vulnerability, but it affects room availability. |
| 555 | |
| 556 | ### Remediation |
| 557 | |
| 558 | Verify the actual runtime values of `MAX_CUSTOM_MIRRORS` and the slice parameters by |
| 559 | testing with the live module. If they are indeed negative, this is a deobfuscation |
| 560 | artifact and the original values need to be determined. |
| 561 | |
| 562 | --- |
| 563 | |
| 564 | ## Finding 9: handleAddDevice Does Not Check Invitation Expiration |
| 565 | |
| 566 | **Severity**: MEDIUM |
| 567 | **MITRE ATT&CK**: T1078 (Valid Accounts) |
| 568 | **CWE**: CWE-613 (Insufficient Session Expiration) |
| 569 | |
| 570 | ### Description |
| 571 | |
| 572 | When a new device joins via invitation (`addDeviceWithInvitation`), the handler verifies |
| 573 | the invitation signature and checks that the invitation exists in the database, but does |
| 574 | NOT check the invitation's `metadata.expiration` timestamp. Expiration IS checked in |
| 575 | the `_autobaseTrace` callback (index.js line 1104), but that's a post-processing step |
| 576 | for generating responses -- not an enforcement point. |
| 577 | |
| 578 | ### Proof |
| 579 | |
| 580 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/members/index.js` |
| 581 | Lines 164-183: |
| 582 | ```javascript |
| 583 | async function addDeviceWithInvitation(withInvitation, header, context) { |
| 584 | const {db, hostcalls, writer} = context; |
| 585 | let verified = null; |
| 586 | try { |
| 587 | verified = verifyInvitationDeviceRequest(withInvitation); |
| 588 | } catch (e) { throw KeetContractError.ABORT(); } |
| 589 | if (!verified) throw KeetContractError.ABORT(); |
| 590 | const {id, request} = verified; |
| 591 | if (!b4a.equals(request.deviceKey, writer.key)) throw KeetContractError.ABORT(); |
| 592 | const [joinReq, invitation, identity] = await Promise.all([ |
| 593 | db.get("@keet/join-requests", {deviceKey: writer.key}), |
| 594 | db.get("@keet/invitations", {id}), |
| 595 | db.get("@keet-private-id/identity") |
| 596 | ]); |
| 597 | if (!invitation || joinReq) throw KeetContractError.ABORT(); |
| 598 | // NO CHECK: invitation.metadata.expiration |
| 599 | // Invitation could be expired but still accepted |
| 600 | await hostcalls.ackWriter(writer.key); |
| 601 | if (!invitation.requiresConfirmation && !identity) { |
| 602 | await acceptJoinRequest(header, writer.key, request, invitation, null, context); |
| 603 | } else { |
| 604 | await db.insert("@keet/join-requests", {deviceKey: writer.key, id, request}); |
| 605 | } |
| 606 | } |
| 607 | ``` |
| 608 | |
| 609 | The `createInvitation` function at `lib/invitations/index.js` line 29 sets an |
| 610 | `expiration` field in metadata, but no handler checks it. |
| 611 | |
| 612 | Separately, the `_autobaseTrace` at `index.js` lines 1103-1104 does check expiration: |
| 613 | ```javascript |
| 614 | const expiration = invitation?.metadata.expiration; |
| 615 | if (expiration > 0 && expiration < Date.now()) return; |
| 616 | ``` |
| 617 | But this is in a trace callback used for generating device responses, not for |
| 618 | preventing the join itself. |
| 619 | |
| 620 | ### Impact |
| 621 | |
| 622 | An invitation that was created with an expiration time can be used after it expires. |
| 623 | If a room admin creates a temporary invitation link (e.g., valid for 24 hours), that |
| 624 | link remains usable indefinitely as long as the invitation record hasn't been explicitly |
| 625 | removed from the database. |
| 626 | |
| 627 | ### Remediation |
| 628 | |
| 629 | Add expiration check in `addDeviceWithInvitation`: |
| 630 | ```javascript |
| 631 | if (invitation.metadata.expiration > 0 && invitation.metadata.expiration < header.timestamp) { |
| 632 | throw KeetContractError.ABORT(); |
| 633 | } |
| 634 | ``` |
| 635 | |
| 636 | --- |
| 637 | |
| 638 | ## Finding 10: Push Notification Payload Leaks Message Content |
| 639 | |
| 640 | **Severity**: LOW |
| 641 | **MITRE ATT&CK**: T1530 (Data from Cloud Storage Object) |
| 642 | **CWE**: CWE-200 (Exposure of Sensitive Information) |
| 643 | |
| 644 | ### Description |
| 645 | |
| 646 | The push notification handler at `push.js` includes the full message text, file |
| 647 | metadata, and sender identity in the notification payload sent to Apple/Google push |
| 648 | notification services. |
| 649 | |
| 650 | ### Proof |
| 651 | |
| 652 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/push.js` |
| 653 | Lines 44-68: |
| 654 | ```javascript |
| 655 | if (operation.name === "@keet/add-chat-message") { |
| 656 | const msg = operation.value.message; |
| 657 | // Full text included in push payload: |
| 658 | messageInfo = { timestamp, type: "text", chatText: msg.text, ... }; |
| 659 | // File metadata included: |
| 660 | messageInfo = { timestamp, type: "file", fileType: file.metadata?.mimetype, ... }; |
| 661 | } |
| 662 | // Full sender info included: |
| 663 | const result = { |
| 664 | sender: { |
| 665 | id: HypercoreId.encode(writerKey), |
| 666 | name: member.profile.displayName, |
| 667 | memberAvatar: member.profile.avatar, // AVATAR DATA |
| 668 | ... |
| 669 | }, |
| 670 | room: { |
| 671 | key: room.roomKey, |
| 672 | title: room.config.title, |
| 673 | roomAvatar: room.config.avatar, // ROOM AVATAR DATA |
| 674 | ... |
| 675 | }, |
| 676 | message: messageInfo |
| 677 | }; |
| 678 | ``` |
| 679 | |
| 680 | ### Impact |
| 681 | |
| 682 | Push notification services (Apple APNs, Google FCM) can read: |
| 683 | - Message text content |
| 684 | - Sender display name |
| 685 | - Room title |
| 686 | - File types being shared |
| 687 | - Avatar images (potentially identifying) |
| 688 | |
| 689 | This undermines the E2E encryption guarantees of the Keet protocol. Users expect their |
| 690 | messages to be encrypted end-to-end, but push notifications expose plaintext content |
| 691 | to third-party notification services. |
| 692 | |
| 693 | ### Remediation |
| 694 | |
| 695 | Use content-available (silent) push notifications that only wake the app, then fetch |
| 696 | and decrypt the message locally. Never include message content in the push payload. |
| 697 | |
| 698 | --- |
| 699 | |
| 700 | ## Finding 11: handleUpdateChatMessage Allows Editing Another Member's Message Display |
| 701 | |
| 702 | **Severity**: MEDIUM |
| 703 | **MITRE ATT&CK**: T1565.001 (Stored Data Manipulation) |
| 704 | **CWE**: CWE-863 (Incorrect Authorization) |
| 705 | |
| 706 | ### Description |
| 707 | |
| 708 | While `handleUpdateChatMessage` correctly verifies that the writer is the same member |
| 709 | who authored the original message (`SELF_ONLY` check), the edit operation allows |
| 710 | changing the `display` field of a message. The `display` field contains structured |
| 711 | formatting data (bold, italic, mentions, links, etc.). A user could edit their own |
| 712 | message to change mention targets, add fake link previews, or modify formatting in |
| 713 | ways the UI doesn't expect. |
| 714 | |
| 715 | More critically, the edit replaces `message.files` in a specific way: it first collects |
| 716 | the old files, then deletes them, then inserts new files. During this window, the |
| 717 | file stats may become temporarily inconsistent. |
| 718 | |
| 719 | ### Proof |
| 720 | |
| 721 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/chat.js` |
| 722 | Lines 55-77: |
| 723 | ```javascript |
| 724 | async function handleUpdateChatMessage({header, oplog, message}, {db, blobs, writer}) { |
| 725 | // ... lookup writer, target message author, verify SELF_ONLY ... |
| 726 | // Collect old files |
| 727 | if (existingMsg.message?.files?.length) { |
| 728 | oldFiles.push(...existingMsg.message.files); |
| 729 | existingMsg.message.files = []; |
| 730 | } |
| 731 | message.files = []; |
| 732 | // Delete old files |
| 733 | await deleteMessageFiles({primaryThread: thread, message: existingMsg, db, blobs}); |
| 734 | // Insert new files |
| 735 | await insertMessageFiles({primaryThread: thread, clock, message, blobs, db, oplog: writer}); |
| 736 | // Replace message content wholesale: |
| 737 | const updated = { |
| 738 | ...existingMsg, |
| 739 | message: { |
| 740 | ...existingMsg.message, |
| 741 | text: message.text, |
| 742 | files: oldFiles, // Old file IDs preserved |
| 743 | display: message.display // NEW DISPLAY from attacker |
| 744 | }, |
| 745 | status: { ...existingMsg.status, isEdited: true }, |
| 746 | editedAt: header.timestamp |
| 747 | }; |
| 748 | } |
| 749 | ``` |
| 750 | |
| 751 | The `display` field is completely replaced with the new value from the edit operation, |
| 752 | allowing the editor to inject new mention references, link previews, etc. |
| 753 | |
| 754 | ### Impact |
| 755 | |
| 756 | A user can edit their own message to change who is mentioned (triggering notifications |
| 757 | to different users), add fake link previews, or modify formatting. While this is |
| 758 | limited to self-authored messages, it can be used for social engineering (edit a message |
| 759 | after others have seen it to change its meaning or attribution). |
| 760 | |
| 761 | ### Remediation |
| 762 | |
| 763 | Consider restricting which fields can be modified during an edit. At minimum, validate |
| 764 | that mention targets in the new `display` field correspond to actual members. |
| 765 | |
| 766 | --- |
| 767 | |
| 768 | ## Finding 12: handleRemoveMember Does Not Revoke Active Invitations |
| 769 | |
| 770 | **Severity**: MEDIUM |
| 771 | **MITRE ATT&CK**: T1078.004 (Cloud Accounts) |
| 772 | **CWE**: CWE-672 (Operation on a Resource after Expiration or Release) |
| 773 | |
| 774 | ### Description |
| 775 | |
| 776 | When a member is removed from a room, their `isActive` flag is set to false, their |
| 777 | devices are deactivated, and they're tracked in `@keet/tmp-removed-members`. However, |
| 778 | any invitations that the removed member previously created remain active in the |
| 779 | `@keet/invitations` collection. New users can still join using those invitations, and |
| 780 | the joining flow does not check whether the invitation creator is still an active member. |
| 781 | |
| 782 | ### Proof |
| 783 | |
| 784 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/members/index.js` |
| 785 | Lines 342-379 (`handleRemoveMember`): No code removes or deactivates invitations created |
| 786 | by the removed member. |
| 787 | |
| 788 | Lines 210-220 (`handleAddInvitation`): Invitation records are stored with no reference |
| 789 | to the creator's member key (only the writer key is used for the anchor). |
| 790 | |
| 791 | Lines 164-183 (`addDeviceWithInvitation`): Checks `db.get("@keet/invitations", {id})` |
| 792 | to verify the invitation exists, but does NOT check whether the invitation creator is |
| 793 | still an active member. |
| 794 | |
| 795 | ### Impact |
| 796 | |
| 797 | A removed/banned member's previously-created invitations remain valid. They could share |
| 798 | these invite links with others who would then join the room, potentially flooding it |
| 799 | with accounts controlled by the banned user. This is particularly concerning for |
| 800 | invitations with `canModerate: true` or `canAdmin: true` permissions. |
| 801 | |
| 802 | ### Remediation |
| 803 | |
| 804 | When removing a member, iterate and deactivate all invitations created by that member: |
| 805 | ```javascript |
| 806 | const invitations = await db.find("@keet/invitations").toArray(); |
| 807 | for (const inv of invitations) { |
| 808 | // Need to track invitation creator to filter |
| 809 | } |
| 810 | ``` |
| 811 | This requires adding a `creatorKey` field to invitation records. |
| 812 | |
| 813 | --- |
| 814 | |
| 815 | ## Finding 13: test-increment Handler Present in Production |
| 816 | |
| 817 | **Severity**: LOW |
| 818 | **MITRE ATT&CK**: T1059 (Command and Scripting Interpreter) |
| 819 | **CWE**: CWE-489 (Active Debug Code) |
| 820 | |
| 821 | ### Description |
| 822 | |
| 823 | The `testing.js` contract module registers a `@keet/test-increment` handler (dispatch |
| 824 | ID 42) that writes to a `@keet/test-collection-1` collection. This handler is loaded |
| 825 | in the production router at `contract/index.js` line 52: |
| 826 | ```javascript |
| 827 | testing[REGISTER_ROUTES](router) |
| 828 | ``` |
| 829 | |
| 830 | ### Proof |
| 831 | |
| 832 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/testing.js` |
| 833 | ```javascript |
| 834 | async function handleTestIncrement({value}, {db, writer}) { |
| 835 | const member = await getMemberForDeviceKey(db, writer.key); |
| 836 | if (!isMemberActive(member)) throw KeetContractError.ABORT(); |
| 837 | const existing = await db.get("@keet/test-collection-1", {key: value}); |
| 838 | const newValue = existing ? existing.value + 2 : 1; |
| 839 | await db.insert("@keet/test-collection-1", {key: value, value: newValue}); |
| 840 | } |
| 841 | ``` |
| 842 | |
| 843 | ### Impact |
| 844 | |
| 845 | Any active member can write arbitrary key-value pairs to `@keet/test-collection-1`. |
| 846 | While this collection is isolated (not used by other handlers), it: |
| 847 | 1. Pollutes the shared database with test data |
| 848 | 2. Provides a covert channel (members can communicate via test collection values) |
| 849 | 3. Adds an unnecessary attack surface |
| 850 | |
| 851 | ### Remediation |
| 852 | |
| 853 | Remove the test handler from the production router. Gate it behind an `isExperimental` |
| 854 | flag on the system settings. |
| 855 | |
| 856 | --- |
| 857 | |
| 858 | ## Finding 14: Invitation Seed Deterministically Derives Signing Keys |
| 859 | |
| 860 | **Severity**: LOW |
| 861 | **MITRE ATT&CK**: T1552 (Unsecured Credentials) |
| 862 | **CWE**: CWE-330 (Use of Insufficiently Random Values) |
| 863 | |
| 864 | ### Description |
| 865 | |
| 866 | The `createInvitation` function generates a random 32-byte seed and derives the |
| 867 | invitation's signing keypair deterministically from it: |
| 868 | ```javascript |
| 869 | function createInvitation(roomKeys, opts) { |
| 870 | const seed = crypto.randomBytes(32); |
| 871 | const signingKeyPair = createSigningKeyPair(seed); |
| 872 | // ... |
| 873 | return { invitation, seed }; |
| 874 | } |
| 875 | ``` |
| 876 | |
| 877 | The seed is returned alongside the invitation and eventually encoded into the invite |
| 878 | link. This is by design (the invitee uses the seed to prove they have the invite), but |
| 879 | it means: |
| 880 | |
| 881 | 1. Anyone who intercepts the invite link has the seed |
| 882 | 2. The seed deterministically derives the signing keypair |
| 883 | 3. With the signing keypair, they can forge join requests |
| 884 | |
| 885 | The security of invitations therefore depends entirely on the secrecy of the invite link, |
| 886 | which is transmitted over Keet's own encrypted channels (DMs, rooms). If an invite link |
| 887 | is shared via an insecure channel (email, HTTP website, etc.), it can be intercepted and |
| 888 | reused by a third party. |
| 889 | |
| 890 | ### Impact |
| 891 | |
| 892 | Invite links shared over insecure channels can be used by anyone who intercepts them. |
| 893 | This is a known limitation of link-based invitations and is mitigated by the |
| 894 | `requiresConfirmation` flag (which requires the room admin to manually approve joins). |
| 895 | |
| 896 | ### Remediation |
| 897 | |
| 898 | Document the security model clearly: invite links must only be shared over encrypted |
| 899 | channels. Consider adding single-use invitations that are consumed after the first join. |
| 900 | The `requiresConfirmation` mechanism should be the default for sensitive rooms. |
| 901 | |
| 902 | --- |
| 903 | |
| 904 | ## Finding 15: handleAddMemberLabel Does Not Rate-Limit Labels Per Target |
| 905 | |
| 906 | **Severity**: LOW |
| 907 | **MITRE ATT&CK**: T1499.003 (Application Exhaustion Flood) |
| 908 | **CWE**: CWE-770 (Allocation of Resources Without Limits or Throttling) |
| 909 | |
| 910 | ### Description |
| 911 | |
| 912 | The `handleAddMemberLabel` handler (labels for members, not chat) allows any active |
| 913 | member to add labels to any other member. The only dedup is on the exact |
| 914 | `(targetKey, sender, label)` triple. Like reactions, the `label` field is a uint |
| 915 | with no range validation. |
| 916 | |
| 917 | ### Proof |
| 918 | |
| 919 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/members/labels.js` |
| 920 | Lines 8-18: |
| 921 | ```javascript |
| 922 | async function handleAddMemberLabel({header, key, label}, {db, writer}) { |
| 923 | const [writerMember, targetMember, thread] = await Promise.all([ |
| 924 | getMemberForDeviceKey(db, writer.key), |
| 925 | db.get("@keet/members", {key}), |
| 926 | db.get("@keet/threads", {id: 0}) |
| 927 | ]); |
| 928 | if (!isMemberActive(writerMember) || !targetMember || |
| 929 | b4a.equals(writerMember.key, targetMember.key)) |
| 930 | throw KeetContractError.ABORT(); |
| 931 | // Only exact triple dedup, no per-target limit |
| 932 | const existing = await db.get("@keet/member-labels", {...}); |
| 933 | if (existing) throw KeetContractError.ABORT(); |
| 934 | // ... insert ... |
| 935 | } |
| 936 | ``` |
| 937 | |
| 938 | ### Impact |
| 939 | |
| 940 | A member can add millions of unique label values to another member, bloating the |
| 941 | `@keet/member-labels` collection and the `@keet/member-label-digests` aggregate. |
| 942 | The `memberLabelStats` function updates digests on each insert, creating O(n) work. |
| 943 | |
| 944 | ### Remediation |
| 945 | |
| 946 | Add per-target label limits (e.g., max 100 labels per target member). |
| 947 | |
| 948 | --- |
| 949 | |
| 950 | ## Finding 16: Silent Failure Pattern Masks Errors |
| 951 | |
| 952 | **Severity**: INFO |
| 953 | **MITRE ATT&CK**: N/A |
| 954 | **CWE**: CWE-392 (Missing Report of Error Condition) |
| 955 | |
| 956 | ### Description |
| 957 | |
| 958 | Several handlers use `return` (silent success) instead of `throw KeetContractError` |
| 959 | for authorization failures: |
| 960 | |
| 961 | - `handleUpdateSystemSettings` (internal.js line 68): `if (!isMemberActive(member) || !member.status.isModerator) return;` |
| 962 | - `handleAddBlindPeer` (internal.js line 79): `if (!isMemberActive(member) || !member.status.isModerator) return;` |
| 963 | - `handleRemoveBlindPeer` (internal.js line 86): same pattern |
| 964 | - `handleAbiMigration` (internal.js line 93): same pattern |
| 965 | - `handleUpdateRoomConfig` (config.js line 20): same pattern |
| 966 | |
| 967 | In contrast, other handlers throw explicit errors: |
| 968 | - `handleChangeMemberRole` (members/index.js line 331): `throw KeetContractError.MODERATORS_ONLY()` |
| 969 | - `handleAddChatMessage` (chat.js line 39): `throw KeetContractError.INACTIVE_MEMBER()` |
| 970 | |
| 971 | ### Impact |
| 972 | |
| 973 | The silent return pattern has two implications: |
| 974 | 1. **Positive**: Prevents the error from potentially becoming a fatal non-KeetContractError |
| 975 | that could crash the apply loop (Finding 1). |
| 976 | 2. **Negative**: Makes it harder to detect unauthorized operation attempts. A monitoring |
| 977 | system looking for `KeetContractError` events would miss these silent rejections. |
| 978 | |
| 979 | The inconsistency between handlers (some throw, some return) suggests different authors |
| 980 | or different development phases. The "return" pattern is actually safer from a DoS |
| 981 | perspective (Finding 1), but less informative for audit logging. |
| 982 | |
| 983 | ### Remediation |
| 984 | |
| 985 | Standardize on one pattern. The silent return is safer but should log the rejection. |
| 986 | Consider wrapping all handlers with a standard authorization decorator. |
| 987 | |
| 988 | --- |
| 989 | |
| 990 | ## Finding 17: handleRemoveContact Missing Error Throw |
| 991 | |
| 992 | **Severity**: INFO (potential bug) |
| 993 | **MITRE ATT&CK**: N/A |
| 994 | **CWE**: CWE-252 (Unchecked Return Value) |
| 995 | |
| 996 | ### Description |
| 997 | |
| 998 | In `handleRemoveContact` at `identity/private.js` line 186, the error handling |
| 999 | references `KeetContractError.ABORT` without calling it (missing parentheses): |
| 1000 | |
| 1001 | ```javascript |
| 1002 | if (!isMemberActive(member) || !contact) throw KeetContractError.ABORT; // Missing () |
| 1003 | ``` |
| 1004 | |
| 1005 | This throws the function REFERENCE, not a KeetContractError instance. The thrown value |
| 1006 | would be a Function object, which is NOT a `KeetContractError`. Therefore, |
| 1007 | `KeetContractError.isContractError(err)` returns `false`, and the main apply loop |
| 1008 | treats it as a FATAL error (Finding 1), potentially crashing the peer. |
| 1009 | |
| 1010 | ### Proof |
| 1011 | |
| 1012 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/contract/identity/private.js` |
| 1013 | Line 186: |
| 1014 | ```javascript |
| 1015 | if (!isMemberActive(member) || !contact) throw KeetContractError.ABORT; |
| 1016 | // Compare to correct pattern (with parentheses): |
| 1017 | if (!isMemberActive(member)) throw KeetContractError.ABORT(); |
| 1018 | ``` |
| 1019 | |
| 1020 | ### Impact |
| 1021 | |
| 1022 | If a member tries to remove a contact that doesn't exist, the thrown Function object |
| 1023 | would be treated as a non-contract error, potentially crashing the Autobase. However, |
| 1024 | this is in the `@keet-private-id` namespace which runs on the PRIVATE profile Autobase, |
| 1025 | not the shared room Autobase -- so it only affects the local peer, not other room members. |
| 1026 | |
| 1027 | **CAVEAT**: This may be a deobfuscation artifact. The original source may have correct |
| 1028 | parentheses that the deobfuscator stripped. |
| 1029 | |
| 1030 | ### Remediation |
| 1031 | |
| 1032 | Add parentheses: `throw KeetContractError.ABORT()`. |
| 1033 | |
| 1034 | --- |
| 1035 | |
| 1036 | ## Finding 18: Firewall Race Condition in RoomFirewall.allow() |
| 1037 | |
| 1038 | **Severity**: INFO |
| 1039 | **MITRE ATT&CK**: T1557 (Adversary-in-the-Middle) |
| 1040 | **CWE**: CWE-362 (Race Condition) |
| 1041 | |
| 1042 | ### Description |
| 1043 | |
| 1044 | The `RoomFirewall.allow()` method first checks the device registry, then falls back to |
| 1045 | checking active Hypercore peers. The peer check iterates `this.core.peers` which is a |
| 1046 | live array that can change between iterations. |
| 1047 | |
| 1048 | ### Proof |
| 1049 | |
| 1050 | File: `/storage/projects/code/hypercore-kb/hyper-fleeky/keet-cli/deobfuscated/lib/swarm/firewall.js` |
| 1051 | Lines 17-25: |
| 1052 | ```javascript |
| 1053 | async allow(swarmKey) { |
| 1054 | await this.ready(); |
| 1055 | const room = this.keet.internalOpenExistingRoom(this.key); |
| 1056 | try { |
| 1057 | await room.ready(); |
| 1058 | const device = await room.db.get("@keet/devices-by-swarm-key", {profile: {swarmKey}}); |
| 1059 | if (device) return device.status.isActive; |
| 1060 | // Fallback: check if they're already connected as a peer |
| 1061 | for (const peer of this.core.peers) { |
| 1062 | if (b4a.equals(peer.remotePublicKey, swarmKey)) return true; |
| 1063 | } |
| 1064 | return false; |
| 1065 | } finally { ... } |
| 1066 | } |
| 1067 | ``` |
| 1068 | |
| 1069 | The fallback peer check allows any currently-connected peer to pass the firewall, |
| 1070 | even if they're not a registered device. This is likely intentional (for bootstrapping |
| 1071 | connections before the device is registered), but creates a window where an unauthorized |
| 1072 | peer could be allowed if they connect at the right time. |
| 1073 | |
| 1074 | ### Impact |
| 1075 | |
| 1076 | Minimal -- the firewall is a connection-level check, not a data-level check. Even if |
| 1077 | an unauthorized peer passes the firewall, they still can't write operations without |
| 1078 | being an Autobase writer (which requires a valid invitation flow). |
| 1079 | |
| 1080 | ### Remediation |
| 1081 | |
| 1082 | Document the race condition. Consider removing the peer fallback or adding a timestamp |
| 1083 | check to ensure the peer connected recently. |
| 1084 | |
| 1085 | --- |
| 1086 | |
| 1087 | ## Attack Vector Analysis Summary |
| 1088 | |
| 1089 | ### 1. Input Validation Bypass -- PARTIALLY VULNERABLE |
| 1090 | |
| 1091 | | Check | Result | |
| 1092 | |-------|--------| |
| 1093 | | Null checks on required fields | PRESENT in all handlers | |
| 1094 | | Member active/muted checks | PRESENT in all handlers | |
| 1095 | | String length limits | **MISSING** -- no maxLength on text, title, description | |
| 1096 | | Array size limits | **MISSING** -- no maxItems on files, mentions, reactions | |
| 1097 | | Integer range validation | PARTIAL -- enum keys checked, but reaction/label values unbounded | |
| 1098 | | File size limits | PRESENT -- `MAX_INLINED_FILE_SIZE` enforced in avatars.js | |
| 1099 | |
| 1100 | ### 2. Privilege Escalation -- NOT VULNERABLE |
| 1101 | |
| 1102 | | Attack | Result | |
| 1103 | |--------|--------| |
| 1104 | | Regular member -> admin | BLOCKED by `handleChangeMemberRole` admin check | |
| 1105 | | Regular member -> moderator | BLOCKED by moderator check | |
| 1106 | | Muted moderator self-unmute | **POSSIBLE** (Finding 4) -- design weakness | |
| 1107 | | Removed member re-join via old invitation | **POSSIBLE** (Finding 12) | |
| 1108 | | Genesis path exploitation | NOT POSSIBLE -- `genesis` flag is set by Autobase, not by the writer | |
| 1109 | |
| 1110 | ### 3. Denial of Service -- VULNERABLE |
| 1111 | |
| 1112 | | Attack | Result | |
| 1113 | |--------|--------| |
| 1114 | | Operation flooding | **NO RATE LIMITING** (Finding 2) | |
| 1115 | | Oversized messages | **NO SIZE LIMITS** (Finding 3) | |
| 1116 | | Reaction/label flooding | **NO PER-TARGET LIMITS** (Finding 7) | |
| 1117 | | Crash via non-KeetContractError | **POSSIBLE** (Finding 1) | |
| 1118 | | Resource exhaustion via map functions | POSSIBLE via mention/file arrays | |
| 1119 | |
| 1120 | ### 4. Data Integrity -- PARTIALLY VULNERABLE |
| 1121 | |
| 1122 | | Attack | Result | |
| 1123 | |--------|--------| |
| 1124 | | Modify other members' data | BLOCKED by SELF_ONLY / authorization checks | |
| 1125 | | Timestamp spoofing | **POSSIBLE** (Finding 6) | |
| 1126 | | Room type manipulation by moderator | **POSSIBLE** (Finding 5) | |
| 1127 | | Orphaned state from self-removal | HANDLED -- member state properly cleaned up | |
| 1128 | | Migration exploitation | BLOCKED -- migrations require moderator role | |
| 1129 | |
| 1130 | ### 5. Invitation/Crypto Weaknesses -- LOW RISK |
| 1131 | |
| 1132 | | Attack | Result | |
| 1133 | |--------|--------| |
| 1134 | | Invitation forgery | BLOCKED by Ed25519 signature verification | |
| 1135 | | Invitation replay | **POSSIBLE if not revoked** (Finding 9, 12) | |
| 1136 | | Invitation ID prediction | NOT POSSIBLE -- IDs are Ed25519 public keys from random seeds | |
| 1137 | | Join request replay | BLOCKED by `@keet/join-requests` dedup check | |
| 1138 | | Contact request decryption | BLOCKED by DeterministicSealedBox encryption | |
| 1139 | |
| 1140 | ### 6. Information Disclosure -- LOW RISK |
| 1141 | |
| 1142 | | Attack | Result | |
| 1143 | |--------|--------| |
| 1144 | | `@keet-private-id/` collection isolation | ENFORCED -- separate Autobase (private profile) | |
| 1145 | | Device key -> member identity correlation | POSSIBLE via `@keet/devices` collection (by design) | |
| 1146 | | Push notification content exposure | **YES** (Finding 10) | |
| 1147 | | Cross-room identity linkability | Possible if same member key used across rooms | |
| 1148 | |
| 1149 | --- |
| 1150 | |
| 1151 | ## Recommendations Priority Matrix |
| 1152 | |
| 1153 | | Priority | Finding | Effort | Impact | |
| 1154 | |----------|---------|--------|--------| |
| 1155 | | P0 | F1: Wrap apply dispatch in broader try/catch | Low | Prevents peer crash DoS | |
| 1156 | | P0 | F2: Add per-writer operation rate limiting | Medium | Prevents flooding DoS | |
| 1157 | | P1 | F3: Add string/array size limits in schema | Medium | Prevents storage exhaustion | |
| 1158 | | P1 | F7: Add per-message reaction/label limits | Low | Prevents index bloat | |
| 1159 | | P2 | F4: Prevent moderator self-unmute | Low | Closes privilege gap | |
| 1160 | | P2 | F9: Check invitation expiration in handler | Low | Enforces time-limited invites | |
| 1161 | | P2 | F12: Revoke invitations on member removal | Medium | Prevents banned user re-entry | |
| 1162 | | P3 | F5: Validate settings enum values | Low | Prevents room type confusion | |
| 1163 | | P3 | F6: Validate timestamp ranges | Low | Improves data integrity | |
| 1164 | | P3 | F10: Remove message content from push payloads | Medium | Improves privacy | |
| 1165 | | P3 | F13: Remove test handler from production | Low | Reduces attack surface | |
| 1166 | |
| 1167 | --- |
| 1168 | |
| 1169 | ## Methodology Notes |
| 1170 | |
| 1171 | This audit was performed through static analysis of deobfuscated JavaScript source code. |
| 1172 | The deobfuscation was performed using a custom VM-sandbox tool that resolves obfuscated |
| 1173 | string references and hex constants. Some numeric constants (particularly negative hex |
| 1174 | values produced by `--0xNNN` patterns) may not be accurately resolved, as noted in |
| 1175 | Finding 8. All findings should be verified against the live runtime before implementing |
| 1176 | fixes. |
| 1177 | |
| 1178 | The audit focused on the contract layer (`lib/contract/`) and invitation system |
| 1179 | (`lib/invitations/`). The Autobase layer was reviewed as open source. The Hyperswarm |
| 1180 | and Hypercore replication layers were out of scope. |
| 1181 | |
| 1182 | MITRE ATT&CK technique IDs reference the Enterprise framework v14. |