Subject: Bugs in TAC and TAIL for closed stdin
From: Marcel Böhme <[email-masked]>
To: [email-masked]
Date: Sun, 27 Nov 2016 17:15:24 +0800
List-Id: <debbugs-submit.debbugs.gnu.org>

Dear all,

During fuzzing, we found one use-after-free in tac and one invalid-loading-of-value in tail.
Interestingly, these errors can be observed only when stdin is externally closed but internally expected to be open.

The bugs were found by AFLFast, a fork of AFL. 
The bug in tac was also found by Klee.
Thanks again also to Van-Thuan Pham.

The following execution crashes TAC in trunk. For the same execution of preinstalled version 8.21 on Ubuntu x86_64, valgrind flags a few invalid reads of size 8. There is no problem in version 6.10:

$ ./tac - - <&-
./tac: 'standard input': read error: Bad file descriptor
=================================================================
==53813==ERROR: AddressSanitizer: heap-use-after-free on address 0x61600000f990 at pc 0x00000040e127 bp 0x7ffefd0f76e0 sp 0x7ffefd0f76d8
READ of size 8 at 0x61600000f990 thread T0
    #0 0x40e126 in rpl_fseeko ../lib/fseeko.c:51
    #1 0x4032ac in temp_stream ../src/tac.c:480
    #2 0x4032ac in copy_to_temp ../src/tac.c:504
    #3 0x4032ac in tac_nonseekable ../src/tac.c:553
    #4 0x4032ac in tac_file ../src/tac.c:595
    #5 0x4032ac in main ../src/tac.c:701
    #6 0x7f135e464f44 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x21f44)
    #7 0x404779  (/home/ubuntu/subjects/coreutils/obj-gcov/src/tac+0x404779)

0x61600000f990 is located 16 bytes inside of 568-byte region [0x61600000f980,0x61600000fbb8)
freed by thread T0 here:
    #0 0x7f135f5e1090 in __interceptor_free (/usr/lib/x86_64-linux-gnu/libasan.so.3+0xc2090)
    #1 0x7f135e4b0a24 in _IO_fclose (/lib/x86_64-linux-gnu/libc.so.6+0x6da24)

previously allocated by thread T0 here:
    #0 0x7f135f5e13a8 in __interceptor_malloc (/usr/lib/x86_64-linux-gnu/libasan.so.3+0xc23a8)
    #1 0x7f135e4b0c81 in fdopen (/lib/x86_64-linux-gnu/libc.so.6+0x6dc81)

SUMMARY: AddressSanitizer: heap-use-after-free ../lib/fseeko.c:51 in rpl_fseeko
=================================================================

The following execution of TAIL in trunk is flagged by UBSAN.
$ tail -f <&-
tail.c:2220:18: runtime error: load of value 190, which is not a valid value for type ‘_Bool'

For trunk version, version 8.21, and version 6.10 on Ubuntu x86_64, valgrind reports:
==28236== Conditional jump or move depends on uninitialised value(s)
==28236==    at 0x405941: ignore_fifo_and_pipe (tail.c:2220)
==28236==    by 0x405941: main (tail.c:2334)

Best regards,
- Marcel