Skip to content

Fix use-after-free and memory leak in mqtt_pit.c#20

Open
juandiego-bmu wants to merge 2 commits intohoneynet:mainfrom
juandiego-bmu:fix-uaf-and-memleak
Open

Fix use-after-free and memory leak in mqtt_pit.c#20
juandiego-bmu wants to merge 2 commits intohoneynet:mainfrom
juandiego-bmu:fix-uaf-and-memleak

Conversation

@juandiego-bmu
Copy link
Copy Markdown

Fixes the use-after-free and the sendPubrel() memory leak reported in #19.

Use-after-free in packet processing loop

When disconnectClient() is called inside the switch (DISCONNECT, CONNECT failure, PUBCOMP, PING), it frees the client struct. But break only exits the switch, not the for loop — so after the loop, lines like:

uint32_t leftover = client->bytesWrittenToBuffer - processedPackets;
memmove(client->buffer, client->buffer + processedPackets, leftover);

are accessing freed memory. Also, if there are multiple MQTT packets in one TCP segment, the loop keeps iterating and reads client->buffer again.

Fix: added a clientDisconnected flag that breaks out of both the switch and the for loop, and wraps the post-loop buffer cleanup in if (!clientDisconnected).

Memory leak in sendPubrel()

sendPubrel() calls malloc but never frees the buffer. Added free(arr) before both return paths, matching the pattern used by sendConnack.

Fixes #19

When disconnectClient() is called inside the packet processing switch,
it frees the client struct. But break only exits the switch, not the
for loop — so the code after the loop still accesses the freed client
(reading bytesWrittenToBuffer, calling memmove on client->buffer).

Added a clientDisconnected flag that breaks out of both the switch and
the for loop, and guards the post-loop buffer cleanup so it only runs
when the client is still alive.

Also added free(arr) to sendPubrel() which was leaking a small
allocation on every call.

Fixes honeynet#19
lookupClient() can return NULL if the fd is not found in the hash table.
The code on line 873 used the return value immediately without checking,
which would cause a NULL pointer dereference. Now we safely remove the
fd from epoll and close it if the client is not found.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] use-after-free and memory leak in mqtt_pit.c

1 participant