[PATCH 2/6] ALSA: compress: fix buffer leak on set_params driver failure

Omer Cohen <[email protected]> Fri, 26 Jun 2026 16:47:05 +0300
Newsgroups org.alsa-project.alsa-devel,org.kernel.vger.stable
Message-ID <[email protected]>
snd_compr_set_params() calls snd_compr_allocate_buffer() which stores
the new buffer pointer in runtime->buffer, then calls
ops->set_params().  If the driver callback fails, the function returns
the error but runtime->buffer already points to the new allocation.
On a subsequent set_params retry, snd_compr_allocate_buffer() overwrites
runtime->buffer with a fresh allocation without freeing the previous
one, leaking kernel memory.

An unprivileged user with access to a compress offload device can
trigger this repeatedly to exhaust kernel memory.

Fix by saving the old buffer state before allocation and restoring it
if the driver callback fails.

Fixes: b21c60a4edd2 ("ALSA: core: add support for compress_offload")
Cc: [email protected]
Reported-by: Omer Cohen <[email protected]>
Signed-off-by: Omer Cohen <[email protected]>
---
 sound/core/compress_offload.c | 14 ++++++++++++++
 1 file changed, 14 insertions(+)

diff --git a/sound/core/compress_offload.c b/sound/core/compress_offload.c
index fd63d219bf86..XXXXXXXXXXXX 100644
--- a/sound/core/compress_offload.c
+++ b/sound/core/compress_offload.c
@@ -665,14 +665,28 @@ snd_compr_set_params(struct snd_compr_stream *stream, unsigned long arg)
 		if (retval)
 			return retval;

+		void *old_buffer = stream->runtime->buffer;
+		size_t old_size = stream->runtime->buffer_size;
+		unsigned int old_frag_size = stream->runtime->fragment_size;
+		unsigned int old_fragments = stream->runtime->fragments;
+
 		retval = snd_compr_allocate_buffer(stream, params);
 		if (retval)
 			return -ENOMEM;

 		retval = stream->ops->set_params(stream, params);
-		if (retval)
+		if (retval) {
+			/* Restore old buffer to avoid leak on retry.
+			 * Free the newly allocated one if it differs.
+			 */
+			if (stream->runtime->buffer != old_buffer &&
+			    !stream->runtime->dma_buffer_p)
+				kfree(stream->runtime->buffer);
+			stream->runtime->buffer = old_buffer;
+			stream->runtime->buffer_size = old_size;
+			stream->runtime->fragment_size = old_frag_size;
+			stream->runtime->fragments = old_fragments;
 			return retval;
+		}

 		if (stream->next_track)
 			return retval;
--
2.43.0