392 points · by robinhouston · 12y ago · 214 comments
This is not, however, the actual goal or purpose of this tool. The fact that many people use Perl as nothing more than a slightly better version of sed doesn't mean that Perl's ability to write complex object-oriented software is "over-engineering". You just don't know what this tool is actually for, which is OK, but means you can't judge whether or not it is "over-engineered".
BSD, apparently going back to at least BSD 4.3, also had a strings tool, and it did the exact same thing: it parsed binary files to dump their strings table. Apple's strings tool has no code heritage from the GNU version, instead being a vague descendent of the one from BSD 4.3. This is how this tool has always worked: stop being part of the noise trying to turn this into a GNU-bash fest :/.
Not sure I agree with you on Perl in particular, but other than that I agree with what you're saying ;-) (That is, I don't think GNU being over-engineered is the (or perhaps even "a") problem here.
>> Am I the only person who thinks there's something fundamentally wrong with computing if running "strings" could let someone take over your computer?
No, the underlying library (libbfd) is an example of something that should've been fixed a long time ago. Maybe not quite the horror that was/is openssl -- but clearly an example of "old c code that sort of works" -- perhaps in some ways like bash was/is. It's old, it works, but it could use some clean-up (as evidenced by a number of related buffer under/over-flows and whatnot).
Note that parsing arbitrary binary (or otherwise) input safely, is a pretty hard problem. There was recently a (resource DOS) bug in libxml2, which have been under quite a lot of scrutiny lately (by virtue of being a brilliant injection vector for malicious code, if a bug can be found).
I read this as a two-part bug: one, a lot of people didn't know that strings did more complex parsing than a hexdump and a filter for printable strings (me included) -- and it turns out that the "smart" library isn't terribly robust (in other words: it's typical C code).
While it is possible (at least in theory) to write small C utilities that are safe, if you want them to be (wildly) portable, and have sane handling of various kinds of encoded strings, and encoded data, along with handling different endianess -- apparently most people screw up.
I think there are two basic camps wrt what should be done: those that think we need something like rust, so that we can have safety without much of a slowdown, and those that say screw it, we're no longer running on 5Mhz (or 50Mhz) cpus, we can take anything up to a 100x (10x) slow down without it really being an issue -- Security/stability/predictability is more important.
Those that can't decide between the two, continue writing C like it was still 1989, and we get lots of stuff like this.
I'm not sure if it's usually the mix of a "smart" C programmer writing a program that is patched by a "hobby" C programmer, or the fact that getting C right is just too hard -- or that people don't -Wall and don't run fuzzers and static checkers -- but whatever the reason, we keep seeing serious bugs in C programs.
I'd like to think some of it could be avoided if people wrote more "bloated" C with copious use of functions, more call-by-value, smaller loops, perhaps more computer generated code -- and other "slow" things (while still being C). But I'm probably hopelessly naive.
While I'm definitely not sold on C++ (at least not as viable "better" C for systems programming), I think the old 1998 article[1] by Strostrup on "simple" C and C++ programs illustrate quite well how hard C can be to get reasonably right, for even simple problems. Perhaps rather than waiting for Rust, a reimplementation on large parts of the backbone of our OSs/GNU in Guile, Lua, or some other higher-than-C level language could be worthwhile.
As a side note -- does anyone know of any follow up on Stroustrup's article?
An alternative is to implement a subset of full parsing specifically tailored to each utility. In the case of strings(1) that's very simple; in the case of some other utilities it's of intermediate complexity; all the way up to some that need to parse every corner of ELF. Whether that produces a bigger or smaller attack surface depends on a lot of factors: each parser might be simpler, but there are many more of them. FreeBSD was contemplating centralizing more of that into a common libelf, so I don't think it's only GNU who think that's a good idea in principle: https://wiki.freebsd.org/LibElf
Some friends of mine are tackling this problem. You should help them. http://langsec.org
BSD tools are simpler. They're also generally less useful.
C should have been buried decades ago, it's a toy language for small pieces of code on isolated systems (and yes, I've written larger programs in C myself, 20 years ago).
Nowdays, C should not even be considered safe for implementing interpreters and runtime systems for other languages. There are plenty of reasonably portable choices available (and no, don't use Java / anything JVM based).
It can't be terribly hard to reimplement "strings" and similar software in a modern language without such deficiencies (i.e. plenty of ways to shoot oneself in the foot and overwrite the stack etc.).
So, there is a perfectly good reason C is still prevalent to this day, even if there are many security implications in doing so.
We've only had Pascal and Modula-2 for what, 40-45 years?
>perfectly good reason C is still prevalent to this day
... it's not that and it's not good. It's just that security implications were largely ignored, people were lazy and innovation and making sound decisions (rather than popular ones) has never been strong in the OSS/Linux community (apart from the kernel itself).
Here's a start: https://news.ycombinator.com/item?id=7882211 https://github.com/uutils/coreutils/tree/master/src
No, the problem comes from the other end. Strings should not be able to compromise a system. It only needs to read a user supplied file, and write to stdout. There's no reason for it to be allowed to exec a piece of code.
It is common to blame C for being unsafe but the real issue seems to be trusting user input, without sanitising it first. You could use a typed language to enforce sanitising by having a special type for user input (whether read from a file or received from the system) and have the converters sanitise it.
I've done most of my OS-level hacking in C and a limited subset of C++. I think it works well down there, where resources can't be "magic" and it's really important to know what's going on (and you often have to tell the optimizer "hands off").
At higher levels, it's lunacy to be using C. I sure wouldn't write a compiler in one, for instance.
You sure about that? If it was a re-implementation in non-cleanroom conditions, Microsoft likely don't have that right.
Even if that's not the case, I'm curious what commercial gain Microsoft believe they would have be keeping it private.
One wonders how much other code of public interest is hidden behind closed doors (and not just Microsoft's).
It's certainly not the right solution for everything, but there are plenty of cases where I'd think it could be an excellent choice. Most of Android (except the kernel) is written in Java, as an example.
Is it really so bloody hard to ensure that e.g. the fields of the executable header, if they're offsets, are actually valid values? I've written tools that work with PEs, many of them reading the entire file into a buffer first, and "make sure you're inside the file" was one of the points I always kept in mind.
I say we need to fix how programmers think, not the language, because the same mindset that leads to bugs like these in "unsafe" languages will also lead to (maybe less severe, maybe more severe but also more subtle) bugs in "safe" languages too.
Citation needed. The plethora of over overcomplicated C code is a strong argument against this claim.
I agree, but unfortunately, changing the language or replacing it, is a lot easier than changing the way programmers think.
Why not? There are meta-circular implementations of Java, with native code generation on their toolchains.
Even OpenJDK is going to get a AOT compiler as discussed on JVM Language Summit 2014.
If you are disregarding Java when you are looking for portable options, then you are IMHO limiting yourself quite a bit and could be missing out on a good solution to your problem.
It's also a basic problem that so much complicated systems software is written in C, but that's better known.
Knowing which programmer signed the code is nice, writing stuff in a "more secure" language is nice, but sandboxing beats it all.
It does attempt to parse a.out format, but any weird values in the header won't cause reading/writing beyond the end of a buffer.
http://marc.info/?l=bugtraq&m=104612710031920 http://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2008-2383
I wrote a buffer overflow exploit at that time.
I thought "strings" was just a dumb scan over the file. Does this mean that with a properly crafted binary it is also possible to hide strings from a quick check with "strings"?
But if you manage to trick libbfd into thinking it's looking at a particular format, you can hide plain text from a simple "strings" invocation even in files that are not executable. I've been using "strings" on all kinds of files, not only executables, and assumed that it will always display all sequences of printable characters present in the file.
-a
--all
- Do not scan only the initialized and loaded sections of object files; scan the whole files.
Both the name and description imply that by default it won't scan the whole thing.So in that sense, it's somewhat counterproductive to just say "somebody oughta rewrite this stuff", unless (like RMS) you're willing to dedicate a good chunk of your life to that mission - or think that your post will inspire somebody else to do the same.
http://www.drdobbs.com/architecture-and-design/cs-biggest-mi...
it is easy to add bounds checking arrays to the C language. The trouble is, nobody is interested in doing it.
It'd be a heckuva lot easier than changing languages.
I agree completely about C. I've been saying this for years. There are three big problems that cause crashes in C programs: "How big is it?", "Who owns it?", and "Who locks it?". The result is over three decades of segfaults and buffer overflows.
There have been three or four variants on C which address some of those issues. I've proposed one myself. None got any traction. The only thing that might work is if someone developed a safe variant of C which could be machine-generated from existing C code, and didn't add significant overhead. GCC already has a fat-pointer subscript checking option, but nobody uses it. That approach is usually slow, with a subscript check on every reference. If you do it right, most subscript checks get hoisted out of loops. Go does that for many FOR statements.
Rust is one of the very few languages which addresses all three of those issues without resorting to garbage collection. I really hope the Rust crowd doesn't screw it up.
My experience with adding extensions to C++ is that nobody will use them, not even the people who proposed the extension, unless it is adopted by the Standard. The same goes for C.
The feature I proposed for C has been in D since the beginning, and has a very strong track record of success - both in user acceptance and in eliminating bugs. Whether the runtime bounds checking is actually done or not is controlled by a compiler switch - but most users choose to leave it on.
It isn't a magic bullet, but as buffer overflows are (I presume) the most common cause of C security exploits, this would help a lot.
Or, more generally, memory safety.
Of the three you described, Rust makes the strongest memory safety guarantees. Neither D nor Rust require a complicated runtime. I'd say this isn't really Go's intended area of usage.
Also, Go is missing things like ASLR and DEP (last time I checked), which means that if you link to any vulnerable non-Go code using cgo (which is almost inevitable when writing core utils), or if you find a good bug in the Go runtime, it's trivial to get code execution.
Which of these are you describing as a buffer overflow?
http://www.cvedetails.com/vulnerability-list/vendor_id-9069/...
Unfortunately, it's a dead project, and as far as I recall, never compiled on 64-bit architectures.
(This evening, I'm struggling with a broken "gedit" on Ubuntu. It turns out that editing a sufficiently large file will break "gedit". Not just crash it once, mess its configuration up so badly that future uses of "gedit" hang the entire GUI.
Known bug since 2012. https://bugs.launchpad.net/ubuntu/+source/gedit/+bug/1021720 Status: unassigned.
If the program terminated with "subscript out of range at line 1354 of 'editmain.c'", this would have been fixed by now.)
Lately I've even been playing with a Ruby gem that's a C extension that calls into a Rust .a that exposes itself via extern C.
Once Rust settles down, the next step is academic work to automatically translate existing C into Rust.
Ugh, wouldn't that fall in "just because you can do something doesn't mean you actually should" category? :) Suppose I wrote the library in Go and exported some type of C wrapper and then I loaded that in Rust using Rust->C mechanism - that will load the Golang runtime in Rust! And you still got non-trivial C code to deal with anyways!
https://metacpan.org/pod/PerlPowerTools
I'd rather see that than a language such as Rust, D, or Go.
¹ http://www.catonmat.net/blog/ldd-arbitrary-code-execution/
$ readelf -d /bin/ls
[...] Tag Type Name/Value 0x0000000000000001 (NEEDED) Shared library: [libselinux.so.1] 0x0000000000000001 (NEEDED) Shared library: [libcap.so.2] 0x0000000000000001 (NEEDED) Shared library: [libacl.so.1] 0x0000000000000001 (NEEDED) Shared library: [libc.so.6] [...]
I don't know how careful readelf is with its input validation.
From my /usr/bin/ldd:
try_trace() (
output=$(eval $add_env '"$@"' 2>&1; rc=$?; printf 'x'; exit $rc)
rc=$?
printf '%s' "${output%x}"
return $rc
)
…
# If the program exits with exit code 5, it means the process has been
# invoked with __libc_enable_secure. Fall back to running it through
# the dynamic linker.
try_trace "$file"It's insecure, but it's actually a bit more nuanced. What I'm describing applies to up-to-date glibc, it might have been even more insecure in the past.
ldd first calls the dynamic linker with --verify, i.e.:
/lib/ld-linux.so.2 --verify $file
This is the system's dynamic linker, which should be considered safe. The --verify parameter tells the dynamic linker to check if the file is a valid dynamically linked file. Assuming that the file exists and it is an ELF file, the dynamic linker exits with status 1 if the file doesn't have a DYNAMIC segment, with 2 if the file doesn't have a INTERP segment or with 0 if it has both (the typical case). Execution is never passed to the file with this flag.Depending on the exit status of the loader, ldd does different things:
* If it was 0, it calls try_trace "$file", meaning that the file is invoked directly. However, remember that for the status to be 0, the file must have an INTERP segment, meaning that the kernel will call the interpreter, typically the dynamic linker, i.e. /lib/ld-linux.so.2. A well behaved linker doesn't pass control to the file if LD_TRACE_LOADED_OBJECTS is set.
This is the insecure case. The interpreter can be set to any other application (it must be statically linked or it must dynamically link itself). However, if the attacker doesn't control the file system, there typically aren't any files which match this condition and either pass control to the application or do anything harmful when invoked with no arguments. The alternative is to set the interpreter field to be the file itself. The problem with that is the full path to the ELF file must be known by the attacker (or it must be known that the victim will call ldd from the directory in which the file resides). /proc/self/exe will not work because at the time the kernel reads the entry, it will still point to the executable of the calling process, usually bash in this case.
* If the exit status was 1, ldd quits (because it's an invalid file).
* If the exit status was 2 (no INTERP segment), the dynamic loader is invoked directly, i.e.
try_trace "$RTLD" "$file"
These two latter cases are safe.A bug which can significantly simplify the attack would be a mismatch between the dynamic loader and the kernel, where the dynamic linker thinks that the ELF file has an INTERP filed and returns 0 for --verify and then the kernel doesn't find the INTERP field and passes control directly to the application. I've poked a bit around and as far as I can tell, there's no such bug in the latest kernel and glibc releases. In addition, the kernel aborts the loading process for any errors related to loading the interpreter.
This 30C3 talk[0] discusses potential security issues arising because of mismatches between the various ELF parsers.
This is an insightful bug report: https://bugzilla.redhat.com/show_bug.cgi?id=531160
I think almost everyone ships that version of strings and objdump, fwiw. FreeBSD and NetBSD ship an almost verbatim GNU binutils; OpenBSD's seems to have more local changes (partly b/c it's based on an older binutils they've diverged from), but its 'strings' still uses libbfd.
The only exception I ran across in some quick digging is that Illumos ships the Solaris version of 'strings', and doesn't ship an 'objdump'. This 'strings' seems to have come via Sun via Microsoft via AT&T via UC Berkeley: https://github.com/illumos/illumos-gate/blob/master/usr/src/.... Whether it's safer I haven't investigated; it also parses ELF files, but via its own libelf rather than GNU libbfd.
In this case, he was just fuzzing with "AAAAAAAAAAA" and the program ended up at 0x41414141 ("AAAA"), which is alarming. The next step would to be to figure out where the input file is in memory, replace AAAA with that address, and replace the data there with code. Now "strings" is executing CPU instructions that were in the input file. That's bad.
Some compilers do workarounds, like putting a canary value between the user data and the compiler data, and checking the canary before returning. Some compilers also randomize the location where things go in memory, so it's harder for an attack to predict that address. Some OSes set certain pages to "not executable", so even if an attacker can jump to that memory address, the CPU won't run code from there. None of these are fixes; just barriers for the determined attacker. (W^X is easy to get around, just call code that's already in the binary legitimately, like execve()!)
The fix is to only write to memory you've actually allocated; something the C compiler will not help you with.
To emphasize to the casual reader: 'bad' is a bit of an understatement: it's 'game over'.
Because the buffer is local to the function, and because the function return address happens to reside at a higher address than the buffer itself, you probably get to overwrite the return address. Thus, after the function is executed, the execution doesn't return to the call-site but to the address you specified. Place your payload code in the buffer you provided, and overwrite the function return address to be the address of your buffer and you might do all sorts of fun things. Spawn a root shell (if suid binary), spawn a reverse shell, execute a kernel exploit to get root etc.
But what about objcopy? Much more important utility than strings(1), in my opinion. I admit I rely on it and do not a have a substitute at the ready.
At some stage we need a BSD alternative to the GNU binutils (aside from gcc alternatives). I have seen it discussed several times over the years, but as far as I know it does not exist?
The code in 'file' tries to parse the given file with every built-in format loader, so there are likely many more vulnerabilities like this one.