CVE-2010-0624: GNU tar(1) & cpio(1) Heap Buffer Overflow

I saw this bug today and even though the initial advisory is very detailed I’ll write a blog post too.
The bug was discovered by Jakob Lell and it affects GNU tar(1) prior to 1.23 release and GNU cpio(1) prior to 2.11. You can find the bug at lib/rtapelib.c of GNU tar(1) or GNU cpio(1)’s source code in the function below..

This is the reading routine when communicating with a remote tape drive. As you can read, it creates a string stored in ‘command_buffer’ that contains the ‘length’ that represents the number of Bytes to read. It sends that value to the remote tape server using do_command() and checks its return value for errors and retrieves the server’s status using get_status() function.
Next, as you can see it enters a ‘for’ loop that will iterate ‘states’ times. Since there is no check, if the ‘status’ iterates more times than the heap allocated buffer ‘buffer’, it will result in heap memory corruption.
To fix this, the initial ‘if’ clause that was calling get_status() was changed to include a check on the length like this: