Software, technology, sysadmin war stories, and more. Feed
Wednesday, September 29, 2021

Fun with glibc and the ctype.h functions

I got really bored tonight and went down some rabbit holes and turned up something from about a year ago. If you follow the latest Linux type stuff, you probably remember this, but if not, this might seem new to you. It's just something dumb and amusing.

To say it again: I did not discover this. I just don't think this got nearly enough attention when it went around the first time.

Go grab a Linux box with glibc on it. Then compile and run this C code:

#include <ctype.h>
#include <stdio.h>
int main() {
  int i;
  for (i = 0; ; ++i) {
    printf("[%d] : %d\n", i, isalnum(i));
  return 0;

Then run it and watch what happens. If you have multiple machines, try it on some of them and compare the results. If the results are different, why do you suppose that is?

If you run this in a debugger, note the line number of the crash. Can you figure out what's going on there? (My guess is massive amounts of inlining leading to nothing else going on the stack.)

Neat, right? It makes me want to go looking for places where people are calling these functions with ints that I can control to see if I can blow it up.

Now, remember how I said this is not even close to something that I found? Go check out the source to see how the sausage is made by someone who did the work already.



After writing the initial cut of this and just before posting it, that little evil part of my head that goes "what about..." woke up, and I tried it with a different function. This time, it was isdigit(). It blew up just the same! Cool! So I went for isalpha(), and yep, same thing. I'm not going to exhaustively test all of them right now, but my guess is that it's pretty consistent across the whole set of them.

This is awesome because it's that many more possibilities. I had been grepping source for "isalnum" to try to find inputs I can control, but now I realize that FAR more functions give a way into this. Have fun!