radareorg / sdb

Simple and fast string based key-value database with support for arrays and json
https://www.radare.org/
MIT License
217 stars 62 forks source link

Fix 'k ***' crash #46

Closed radare closed 10 years ago

radare commented 10 years ago

You can reproduce it this way:

r2 -c'k ***' -

Gdb says:

    frame #8: 0x0000000100cebd91 libr_db.0.9.8.git.dylib`foreach_list_cb + 177
    frame #9: 0x0000000100ceda48 libr_db.0.9.8.git.dylib`sdb_foreach + 232
    frame #10: 0x0000000100cebb79 libr_db.0.9.8.git.dylib`walk_namespace + 137
    frame #11: 0x0000000100cea088 libr_db.0.9.8.git.dylib`sdb_querys + 1864
    frame #12: 0x0000000100082d33 libr_core.0.9.8.git.dylib`cmd_kuery(data=0x0000000100005410, input=0x0000000101027ed1) + 275 at cmd.c:454
    frame #13: 0x00000001000c4a20 libr_core.0.9.8.git.dylib`r_cmd_call(cmd=0x0000000101815200, input=0x0000000101027ed0) + 352 at cmd_api.c:179

By reading the assembly this is this portion of the code:

symbol stub for: malloc
0x100cebd91:  48 b9 ff ff ff ff ff ff ff ff  movabsq $-0x1, %rcx
0x100cebd9b:  48 89 45 d0                    movq   %rax, -0x30(%rbp)
0x100cebd9f:  48 8b 7d d0                    movq   -0x30(%rbp), %rdi
0x100cebda3:  48 8b 75 e8                    movq   -0x18(%rbp), %rsi
0x100cebda7:  48 63 55 cc                    movslq -0x34(%rbp), %rdx
0x100cebdab:  e8 de 37 00 00                 callq  0x100cef58e

This is query.c:88

        line = malloc (klen + vlen + 2);

This reflects the truth that the heap has been corrupted. So, running valgrind tells us the following:

==10534== Invalid write of size 8
==10534==    at 0x11D6B8E: _platform_memmove$VARIANT$Unknown (in /usr/lib/system/libsystem_platform.dylib)
==10534==    by 0x1056D74: __memcpy_chk (in /usr/lib/system/libsystem_c.dylib)
==10534==    by 0xC8EA73: strbuf_append (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0xC8EE11: foreach_list_cb (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0xC90B2E: sdb_foreach (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0xC8EB78: walk_namespace (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0xC8ECB5: walk_namespace (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0xC8D087: sdb_querys (in /Users/pancake/prg/radare2/libr/db/libr_db.dylib)
==10534==    by 0x25D32: cmd_kuery (in /Users/pancake/prg/radare2/libr/core/libr_core.dylib)
==10534==    by 0x67A1F: r_cmd_call (in /Users/pancake/prg/radare2/libr/core/libr_core.dylib)
==10534==    by 0x4836B: r_core_cmd_subst_i (in /Users/pancake/prg/radare2/libr/core/libr_core.dylib)
==10534==    by 0x174CF: r_core_cmd_subst (in /Users/pancake/prg/radare2/libr/core/libr_core.dylib)

There's an overflow in strbuf_append, which is quite obvious by reading the code of the function. So I have fixed it :)