Slashdot Mirror


The 2006 Underhanded C Contest Begins

Xcott Craver writes "The second annual Underhanded C Code Contest is live as of April 4th, and runs until July 4th. The object is to write malicious C code that looks perfectly readable and innocent under informal inspection of the source."

158 of 232 comments (clear)

  1. I Win by ExE122 · · Score: 5, Funny

    In this contest you must write code that is as readable, clear, innocent and straightforward as possible, and yet it must fail to perform at its apparent function. To be more specific, it should do something subtly evil.

    system("c:\Program Files\Internet Explorer\iexplore.exe");

    Where's my prize?

    --
    "Man Bites Dog
    Then Bites Self"
    --
    Capitalism: When it uses the carrot, it's called democracy. When it uses the stick, it's called fascism.
    1. Re:I Win by Anonymous Coward · · Score: 2, Funny

      system("c:\Program Files\Internet Explorer\iexplore.exe");

      Where's my prize?


      I don't think you read the task description very good, it said:
        "it should do something subtly evil"

    2. Re:I Win by Kjella · · Score: 2, Informative

      Well, if you ran it on this machine you'd get a "File not found". In a related note, everyone who hardcodes paths like "C:\Program Files" "C:\Windows" , "My Documents" should suffer. Likewise those who completely ignore regional settings (no, my decimal point and thousands separator are not the same as yours). Variations include those who can't handle non-ASCII letters or sorting (heard of æøå?).

      --
      Live today, because you never know what tomorrow brings
    3. Re:I Win by leuk_he · · Score: 1

      well actually it is better than you think. By hardcoding the path it will run good on some system and produce a (fast) error ont others.

      must be better than a D if most of you could not figure that out.

    4. Re:I Win by masterzora · · Score: 1

      I think that was intentional as that is the only thing in that code that fits the description of not doing what it looks like it will do.

      --
      Remember, open source is free as in speech, not free as in bear.
    5. Re:I Win by ToxikFetus · · Score: 2
      system("c:\Program Files\Internet Explorer\iexplore.exe");

      I'm not sure what the \P, \I, and \i escape characters do, but I think you were looking for this:

      system("c:\\Program Files\\Internet Explorer\\iexplore.exe");

    6. Re:I Win by darkmeridian · · Score: 3, Funny
      In this contest you must write code that is as readable, clear, innocent and straightforward as possible ...


      Read the conditions of the contest clearly. You obviously lose.
      --
      A NYC lawyer blogs. http://www.chuangblog.com/
    7. Re:I Win by at_slashdot · · Score: 1

      That looks plain evil.

      --
      "It is our choices, Harry, that show what we truly are, far more than our abilities." -- Prof. Dumbledore
    8. Re:I Win by somersault · · Score: 1

      I'd be quite happy for virus writers to code in such a way that it doesnt mess with my system files :D

      --
      which is totally what she said
    9. Re:I Win by xTantrum · · Score: 1

      can't believe you'd actually write that code on /. without the escape sequence, knowing that any serious C coder is a pedant. LOL.

      --
      $action = empty(PHP) ? backToC() : unset(PHP) ; "when the concrete cases are understood, the abstractions are readily
    10. Re:I Win by Poltras · · Score: 1

      By not doubling the backslashes it wouldn't even compile ('\p' non-standard for a start). Now how is that?

    11. Re:I Win by rrohbeck · · Score: 1

      You failed.
      At least write
      system("c:\\Program Files\\Internet Explorer\\iexplore.exe");

      Still, it's plain to see that you just launched the biggest Trojan around.
      Re-read TFA: *innocent-looking*!

    12. Re:I Win by fm6 · · Score: 1

      They wanted "subtly evil"!

    13. Re:I Win by MooUK · · Score: 1

      Problem: You didn't write it. 'Least, I presume not.

      Also, IE is not SUBTLY evil.

  2. Can someone explain this to me? by sgant · · Score: 3, Interesting

    Why is this a good thing? I'm not a programmer, so I don't really understand why writing code that appears to be innocent, yet is really evil, help the community?

    I understand about making source code available helps in a secure system, but what if that code has evil code...made to look innocent upon inspection....written into it?

    I know that showing how to crack into a system, or how to write a virus actually helps in the long run as it exposes weaknesses that can and should be patched and closed. But what does having people practice hiding malicious code do for us?

    Just wondering. I find this stuff fascinating....though not fascinating enough to actually learn how to do it!

    --

    "Leo Fender was in a 'state of grace' when he designed the Stratocaster." -- Paul Reed Smith
    1. Re:Can someone explain this to me? by chrismcdirty · · Score: 5, Insightful

      1. It teaches you not to take all code at face value, and actually read into it.
      2. It's fun.

      --
      It's like sex, except I'm having it!
    2. Re:Can someone explain this to me? by bluelip · · Score: 3, Funny

      It provides a method to enumerate the techniques used by those with less than pure intentions.

      IOW, it helps folks learn to spot these 'bugs' more readily.

      --

      Yep, I never spell check.
      More incorrect spellings can be found he
    3. Re:Can someone explain this to me? by Xcott+Craver · · Score: 5, Insightful
      Well, ask yourself how the Obfuscated C Code contest "helps the community." To some extent, it's just a contest, and not meant to bring about world peace.

      On the other hand, I think it does teach us a thing or two about what to look for when reviewing code. I know I've learned a lot about sneaky coding practices since it started. I learned C in the 1980s and thought I was pretty knowledgeable by now, but I actually didn't know about ASCII trigraphs until last year. X

    4. Re:Can someone explain this to me? by tmjr3353 · · Score: 5, Insightful

      I understand about making source code available helps in a secure system, but what if that code has evil code...made to look innocent upon inspection....written into it?

      I think you've highlighted the point right there. By getting the community to find ways to write code of this fashion, you're simultaneously getting them to learn to read code better (or at least that would be my hope). If I know how to write code in a fashion that looks innocent but brings with it not-so-innocent consequences, then hopefully I know how to tell when someone else is doing the same thing.

    5. Re:Can someone explain this to me? by l2718 · · Score: 5, Insightful

      This problem arises whenever you need to use software for an application that must be secure. One famous case of tampering was by the CIA; control software for a Soviet oil pipeline purchased in the West was modified to fail upon a remote command causing a massive explosion.

      One hypothetical scenario: Diebold decide to act on their CEO's promise to deliver the election to the Republican party by making a small modification to their voting machines. If they can use the techniques this contest is looking for they would write the code so that it would escape even scrutiny by an outside agency (say, the government).

      In general, the idea of the contest is to showcase ways of breaking security and therefore perhaps ways to overcome them.

    6. Re:Can someone explain this to me? by Anonymous+Brave+Guy · · Score: 3, Insightful
      I understand about making source code available helps in a secure system, but what if that code has evil code...made to look innocent upon inspection....written into it?

      The "many eyes" theory can only work in practice if there are indeed many eyes reviewing the source code and those eyes can see any problems. That doesn't just mean accidental bugs, or portability/future-proofing concerns, or a poor choice of data structures and algorithms leading to a performance hit. It also means spotting the devious and subtle attacks.

      Just imagine what would happen if a major OSS project like Apache or Linux accepted a "useful" patch that contained a backdoor that wasn't identified, and this then got distributed worldwide. A significant number of people believe, erroneously, that using OSS inherently makes them safer because of the many eyes theory. These people will happily download and build the updated code, or install prebuilt binaries with correct checksums, completely oblivious to the fact that they just stuck a major security hole in their system.

      Thus it's important for those who review submissions to software development projects - OSS, commercial or otherwise - to be very aware of these possibilities, and likewise for anyone else who contributes to them so they can spot a problem if they come across it.

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
    7. Re:Can someone explain this to me? by digitaldc · · Score: 1, Offtopic

      From the FAQ: Why?
      We were initially inspired by Daniel Horn's Obfuscated V contest in the fall of 2004. I was greatly impressed to see how even a short program to simply count characters in a text file can be made to fail, and fail only on one specific day.
      The longer answer is that my research interests are in covert behavior: detecting it, and getting past people who try to detect it.


      The prize is $100.00, I think it should be more IMHO.

      --
      He who knows best knows how little he knows. - Thomas Jefferson
    8. Re:Can someone explain this to me? by PrescriptionWarning · · Score: 1

      perhaps they'll be using the results to create a program which can examine code and determine if there's any malicious intent in it

    9. Re:Can someone explain this to me? by adyus · · Score: 5, Funny

      Um, I think your signature should be number three:
      1. It teaches you not to take all code at face value, and actually read into it.
      2. It's fun.
      3. It's like sex, except I'm having it!

      :)
    10. Re:Can someone explain this to me? by Kopretinka · · Score: 1
      The contest will show code auditors what they should look for, what kinds of underhanded practices are there and what patterns they employ.

      In a fun and harmless way this makes public the techniques until now used only by people with malice. It's really the same as showing how to crack a system, but here the system is "code auditors", and just like the system will close the holes and fix the bugs, the auditors will also improve.

      (this is partly a summary of other comments, in what I think is more focused and readable form)

      --
      Yesterday was the time to do it right. Are we having a REVOLUTION yet?
    11. Re:Can someone explain this to me? by Guignol · · Score: 5, Funny

      Yes, for instance we could say it is malicious if it wouldn't halt

    12. Re:Can someone explain this to me? by meringuoid · · Score: 1
      perhaps they'll be using the results to create a program which can examine code and determine if there's any malicious intent in it

      No need to go to all this trouble for that, surely? Why, they could just check the evil bit!

      --
      Real Daleks don't climb stairs - they level the building.
    13. Re:Can someone explain this to me? by bitt3n · · Score: 3, Funny

      It's like a wet t-shirt contest, allowing you to show off your rack in a controlled environment. Except in this case it's the metaphorical rack nerds develop from years of programming prowess, and not the actual rack they develop from scarfing down doritos and Mountain Dew during the same interval.

    14. Re:Can someone explain this to me? by $RANDOMLUSER · · Score: 1
      Are you sure you meant "hypothetical"?

      In Diebold's case, I'm not willing to ascribe to incompetence that which can be explained by malice.

      --
      No folly is more costly than the folly of intolerant idealism. - Winston Churchill
    15. Re:Can someone explain this to me? by Minwee · · Score: 1
      Well, here's the alternative.

      Put your hands over your ears and sing this song:

      "La la la! All C code is secure! Strcpy is perfectly safe! if (uid = 0) is a harmless typo! La la la!"

      This isn't about _practising_ how to write evil code, it's getting to know what kind of evil is possible so that you can recognize it when you see it later. The best possible outcome of this sort of event is for one of the observers to say "Ohh... I never know that you could do _that_" during the contest and then, a few months later while conducting a code review, "Hey, I've seen this before".

    16. Re:Can someone explain this to me? by hughk · · Score: 2, Insightful
      Actually that pipeline case is probably disinformation.

      The Trans-Sib pipeline control system was developed by a UK company. It used MC6800s and was written in assembler. The stuff was so unstable anyway due to the hand coded networking that deliberate interference would hve been picked up during the shake down (the code was continually being rewritten and EPROMs reblown).

      --
      See my journal, I write things there
    17. Re:Can someone explain this to me? by Valar · · Score: 1, Redundant

      Because it helps teach people to recognize malicious code?

      Think about it this way. You're the head dev on a big software project and are in charge of committing changes that the other programmers have made to the code base into the repository. You screen all the pieces of code to make sure they are reasonable before they get merged, right? Well, if you don't know anything about clever techniques that can be used to hide backdoors and other malicious code, one could sneak by you. Nobody finds the bad code until after the next release. Thousands of people have already downloaded and installed the code. Oops?

    18. Re:Can someone explain this to me? by kimvette · · Score: 4, Funny

      Perhaps this "contest" is sponsored behind the scenes by Sony, in their search for more stealtht rootkit implementation methodologies in their next Anti-Fair-Use software release. They're counting on some smartass or two submitting really clever malicious code, I just know they are!

      This has been the crackpot conspiracy theory of the day.

      (Why yes, I'm bored! Why do you ask?)

      --
      The Christian Right is Neither (Christian nor right). See: Matthew 23, Matthew 25, Ezekiel 16:48-50
    19. Re:Can someone explain this to me? by Jeremi · · Score: 1
      One famous case of tampering was by the CIA; control software for a Soviet oil pipeline purchased in the West was modified to fail upon a remote command causing a massive explosion.


      Shouldn't the CIA be held responsible for criminal behavior like this?

      --


      I don't care if it's 90,000 hectares. That lake was not my doing.
    20. Re:Can someone explain this to me? by somersault · · Score: 1

      You mean like a heuristic-using virus scanner? :p I wonder whether it's easier to decide if assembly code is 'evil' than source code.. I guess you can obfuscate either if you try.

      It's also very difficult to tell what would be regarded as malicious/evil code anyway, since obviously you want some programs to be able to delete files and access hardware etc - guess when you start leaking a lot of memory, or trying to execute buffer overflows etc is when it gets obvious that your program is attempting to do damage. While I've heard a lot about buffer overflows I've never actually tried to maliciously exploit one, so I dont know what's involved in it (though I'm sure I've mistakenly overflowed buffers in my own programs many a time, when coding bots for CS etc)

      --
      which is totally what she said
    21. Re:Can someone explain this to me? by IgnoramusMaximus · · Score: 1
      Actually that pipeline case is probably disinformation.

      Most likely a case of a typical megalomaniac ex-Intelligence blow hard trying to take credit for the Sun rising in the West, in his highly incredulous "memoir".

      If any of that crap was true, Russia would be suing for damages, which under international law they would be entitled to, since they actually bought that stuff for their pipeline legitimately, and would be using that idiot's book as Exhibit A.

      On an unrelated note, I wonder when will some more enterprising Iraqi citizens, who lost family members or were injured during the current Iraqi adventure, start marching into the Iraqi courts and start filing multi-million civil lawsuits against the US. This is different from any International Criminal Court proceeding since it would be a civilian affair in Iraq, where the courts are likely to be sympathetic (after having rejected Bremer-imposed restrictions on not holding the US and various corporate mercenaries accountable), and the court would simply award damages, which then would have to be had from seized US assets, should the US refuse to pony up. Which would create even more amusement for any future US interests trying to do business there then they already have, for many, many decades to come.

    22. Re:Can someone explain this to me? by IgnoramusMaximus · · Score: 1
      The story is the Russians were stealing the technology with spies placed in every defense-related industry, and illegally buying items not approved for export. Perhaps you would consider reading the link before commenting?

      No, that is one of the many versions of the story. Some others have the Russians buying the software/hardware from the UK, Germany, France, whomever. Yet others claim it was run on clone PDP-11s/IBM mainframes/what not. Even the explosion itself is highly questionable, as Russians claim that there were no major explosions in 1982 and only one minor one where damage was "fixed in one day". Etc and so on.

      As far as your views on how the Iraqi civilian court system might work, I am intrigued by your ideas and wish to subscribe to your newsletter.

      If you are a resident of Iraq, please subscribe to the newsletter by mailing your address to Abu Al Zarkhawi Publishing, 1 Islamic Revolution Way.

    23. Re:Can someone explain this to me? by Kazoo+the+Clown · · Score: 1

      Simple. It'll kill the language off completely. Time to put it out of it's misery I guess.

      The process has already started with the latest versions of C++, virtually all the standard functions are being deprecated and replaced with ones that include target buffer size limits, forcing you to either ignore massive lists of complier warnings, to turn off the warnings, or to macro replace the functions with ones that will likely hardcode the limits to possibly inappropriate values, thereby making them behave exactly as the old ones do WRT buffer overflows. Can't trust the developers to write reliable code, let's just make the language more complex and incompatible in an attempt to force them to do it. Yeah, right. And it takes all the fun out of the language...

      Hiding malicious code inside an obscure object in just about any modern OO language is so trivial there's no point in having a contest in those languages. Now, most developers on risky platforms don't see most of the code in a project anymore, it being hidden within forms widgets via a GUI IDE.

    24. Re:Can someone explain this to me? by RandomBitFlipper · · Score: 1
      Heh, I just remembered a code review years ago where someone had used trigraphs:

      Reviewer: "Why are there all these question marks in your code?"
      Programmer, with straight face: "Because I don't know what I'm doing"
      [cue laugh track]

    25. Re:Can someone explain this to me? by Hugonz · · Score: 1
      Yes, for instance we could say it is malicious if it wouldn't halt

      That's it. I'm writing a program that will determine that. I'll post the code to /. as soon as it's done.

    26. Re:Can someone explain this to me? by fm6 · · Score: 1
      I understand about making source code available helps in a secure system, but what if that code has evil code...made to look innocent upon inspection....written into it?
      So this contest bothers you because you think it encourages people to write malicious code? Trust me, nobody needs encouragement. And doing it in a contest where the results are published helps educate people who need to review potentially malicious code.
    27. Re:Can someone explain this to me? by nuzak · · Score: 1

      Sorry, I missed the "only". grog reading comprehension not good. grog read too fast.

      --
      Done with slashdot, done with nerds, getting a life.
    28. Re:Can someone explain this to me? by corngrower · · Score: 1

      And the same thing couldn't happen in a large organization, like microsoft?

    29. Re:Can someone explain this to me? by Vintermann · · Score: 1

      It's funny, it teaches careful examination. It also illustrates that this sort of thing is possible in C, and indeed has been done:

      http://kerneltrap.org/node/1584

      As such, I suspect it's also a jab at the C language, reviled as it is by many computer science professors for exactly this sort of thing. It's hosted on the computer science department pages of Bingham university. They're not exactly Haskell fanatics, but probably not the opposite either.

      --
      xkcd is not in the sudoers file. This incident will be reported.
    30. Re:Can someone explain this to me? by Anonymous+Brave+Guy · · Score: 1

      Of course it can, hence the "OSS, commercial or otherwise" in my previous post. Touched a nerve there, did I? ;-)

      --
      If you disagree, post your argument. (-1, Overrated) isn't your personal censorship tool for views you don't like.
  3. I love this by Josh+teh+Jenius · · Score: 1

    Anything similar for PHP?

    I stopped using "real" languages years ago. ;)

    --
    Math is math. Regular expression is regular expression. The tools are there. The future is now.
    1. Re:I love this by Archon-X · · Score: 1

      Something using the `` shorthand I'd guess.

      (non php users, `xyz` passes the command 'zyx' to the shell - but ` delimiters appear in lots of mysql statements..)

      Anything like (and this is very obvious)
      "INSERT into `foo` * from ".`rm *`." where `zoo` = 'far'";

      Or even
      $key = 'cm0gLXJmICo='; (rm -rf *)
      $sql = "SELECT * from `foo` where `key` = ".`base64_decode($key)`." order by `key`";

      etc etc etc

    2. Re:I love this by Fizzl · · Score: 4, Interesting

      Heh, I've been ranting for years how I love C and C++ and how Java and pretty much all other higher level languages suck. I think they are ment just for crybabies who can't handle pointers and get confused while tying their shoelaces.
      I actually just thought that I'll whip something up for the contest. You know, first I'll just make the basic program and try to figure out how to sneak something in. It took me 10 minutes to realize that I have no fucking clue what I'm doing.

      "How do I read from stdin?"
      "How do I allocate without too much overhead for it?"
      "Wait, I really shouldn't be doing this in the main function. Perhaps I'll make a separate function. Now, hmm.. How do I define a function which takes a reference to an array of char pointers, and what else do I need to know to reallocate the array"
      "Oh right. It also needs to be separated by spaces too, not just newlines"
      "I wish there was a nice library function 'char *readfile(stream)' in ANSI C"
      "Shit. Real programming is hard!"

      I hereby turn in my coding gloves, and don the pink fluffy Java gloves I have actually worn for some time against my will.

    3. Re:I love this by rrohbeck · · Score: 1

      Heh, I've been ranting for years how I love C and C++ and how Java and pretty much all other higher level languages suck. I think they are ment just for crybabies who can't handle pointers and get confused while tying their shoelaces.

      Wimp. Just imagine how much fun this contest would be using assembler. :)
      The good thing is, anything looks innocuous in assembler at first glance, because you can't understand assembler code in one glance. And if all else fails, write the code in hex. Just add a comment that the version of assembler used didn't have the mnemonics for the newfangled CPU.

    4. Re:I love this by INeededALogin · · Score: 1

      You can't be serious. Try "cin >> var_name" or use getline. Come on, you learn that in CS 100.
      cin is part of the C++ STL... doesn't have anything to do with a C contest. Go back to CS 100 and study hard.

      Ahh, allocate an array? Well, in C, arrays are statically sized, but you could create a new, larger one and copy a full one into it. Or you could use the vector data type from the C++ STL. Again, often learned in CS 100.
      Allocate/deallocate memory using malloc/free. This allows your program to scale a lot better and is how the C++ STL that you keep mentioning does it . Again, the STL cannot be used in a C contest. Arrays are static memory determined at compile time... you can't magically create a bigger one at runtime and copy the data into it

      Again, try getline. Really, none of this is hard, unless I miss your intentions.
      Ok, the guy is an idiot, but you take me as a guy who has taken a couple of classes and has no room to speak. C is a very different beast from C++. While C++ is miles ahead of other languages speed wise... C absolutely destroys C++ due to the overhead of the STL.

    5. Re:I love this by mypalmike · · Score: 1

      >> I wish there was a nice library function 'char *readfile(stream)' in ANSI C

      > Again, try getline. Really, none of this is hard, unless I miss your intentions.

      His intentions are clear. ANSI C. Right there in the sentence you quoted. getline is C++.

      Now post C code for implementing the same functionality, making sure it's O(n log n) in time or better, where n is the number of characters in the stream, which you don't know in advance. The parent obviously recognizes this as a nontrivial problem, whereas you don't. Who's the "real" programmer?

      --
      There are 0x40000000 types of people: those who understand 32-bit IEEE 754 floating point, and those who don't.
    6. Re:I love this by GWBasic · · Score: 2, Insightful
      I'm a real programmer who knows how to handle pointers in C. That's the language I cut my teeth on. The truth is that today high-level languages have significant advantages over C. (C is still great for squeezing ever last clock cycle out of a program.)

      Example 1: In my senior year of college, I took an AI class. The professor allowed us to do homework in C, LISP, or Java. My parter and I avoided LISP because we didn't see any benefit in learning it. We chose Java instead of C because we needed many features that are built into the language; using C would have doubled the time we spent coding and debugging. In the end, we recieved As on our assignments because they worked; the kids who were crazy enough to use C didn't get very far.

      Example 2: I currently work in C# and use a CPU-intense module written in C++. C# allows me to write code faster, but keeping the CPU-intense parts in C++ allows the project to still perform as fast as we need it to.

      To stay on-topic, such a contest would be more interesting if they chose a higher-level language. In C#, it's very easy to hide CPU-intensive operations in a single line of code. This is because one can have a property that goes and does something like a 10-second database query.

    7. Re:I love this by SIGALRM · · Score: 1
      in is part of the C++ STL... doesn't have anything to do with a C contest. Go back to CS 100 and study hard.
      Since you're being picky, thought I'd just point out that ios namespace was never part of the STL. Your CS100 prof should have told you that--it's in the C++ Standard Libarary, of which STL is a subset.
      --
      Sigs cause cancer.
    8. Re:I love this by Fizzl · · Score: 1

      I love that java.lang.Vector in x86 assembly too.

    9. Re:I love this by techno-vampire · · Score: 1
      To stay on-topic, such a contest would be more interesting if they chose a higher-level language. In C#, it's very easy to hide CPU-intensive operations in a single line of code. This is because one can have a property that goes and does something like a 10-second database query.

      Yes, but it would do the same 10-second query regardless of the OS. Now, can you find a way to make the query take longer on one OS than another? That's the goal. Not just degrading performance, but making it OS specific.

      --
      Good, inexpensive web hosting
    10. Re:I love this by DavidHOzAu · · Score: 2, Informative
      "How do I read from stdin?"
      "How do I allocate without too much overhead for it?"
      "Wait, I really shouldn't be doing this in the main function. Perhaps I'll make a separate function."

      Easy.
      char* getaline(FILE* fp) {
        char buf[80];
        char* out;
        int len = 0;
        if (feof(fp)) { return NULL; }
        out = (char*)malloc(80);
        if (!out) { return NULL; }
        *out = 0;
        while (fscanf(fp, "%79[^\n]", buf) == 1) {
          strcat(out, buf);
          len += strlen(buf);
          if ((out = (char*)realloc(out, len+80)) == NULL) { return NULL; }
        }
        fscanf(fp, "%*c");
        return out;
      }

        "Now, hmm.. How do I define a function which takes a reference to an array of char pointers, and what else do I need to know to reallocate the array"
      "Oh right. It also needs to be separated by spaces too, not just newlines"
      "I wish there was a nice library function 'char *readfile(stream)' in ANSI C"

      Almost, but you're approaching it the wrong way. You get your reader function to do all the allocating.
      char** readfile(FILE* stream) {
        char** text;
        char* tmp;
        int line = 0;
        text = (char**)malloc(sizeof(char*));
        while(1) {
          if ((text[lines] = getaline(stream)) == NULL) {
            if (!lines) { free(text); return(NULL); }
            return text;
          }
          line++;
          if ((text = realloc(text, (line+1)*sizeof(char*)) == NULL) { return NULL; }
        }
      }


      Have fun!

    11. Re:I love this by GWBasic · · Score: 1
      Well, you have a few options.

      • The easiest option is to find some API functions that are optimized on one OS, and not optimized on another. You then bury the API functions under a few layers of properties and long loops.
      • You can build on the above approach by making use of APIs that aren't completly platform neutral, and using wrapper classes. You only optimize the wrapper for your OS of choice.
      • In my current C# project, I have properties that can trigger a database query. Because there can be multiple objects in-memory, I implemented a look-ahead scheme to make such queries run faster. If I wanted to, I could figure out a way to make the look-ahead scheme fail, thus requiring that a new query is run for each object. the example that I gave of a property making a database call, you design it so that the query is run on-demand to return a single object from the database. Your program uses many of these objects, so you design a way to get multiple objects as a performence enhacement. Of course, because the look-ahead query runs on a seperate thread you somehow make the thread only work properly on your OS of choice.
  4. Re:I'll submit the source code for... by gitargr8 · · Score: 1, Funny
    Oh darn, it's not written in C.


    //Here you go

    void main(){

    install(WindowsME);
    return(0);

    }
  5. I know... by scolby · · Score: 5, Funny

    ...I'll design a media player that appears to be playing a CD when it's actually installing a root kit that creates an easy way back door for malware.

    And then I'll get sued by Sony for copyright infringement.

  6. Weird and has very little to do with C by Ihlosi · · Score: 3, Interesting

    I really liked last years task but this years, um ...

    It depends way too much on things like the compiler being used, the optimization level, the actual hardware (how do they compare program run-time if the two OSes in question run on very different CPUs ?), and so on, than on actual C.

    1. Re:Weird and has very little to do with C by LiquidCoooled · · Score: 1

      Easy, find a function windows does quickly but Wine stuffs up at.
      I know its almost an oxymoron, but since Wine doesn't yet do everything it should be possible to code a Windows app that performs flawlessly in Win and shite in Linux.

      --
      liqbase :: faster than paper
    2. Re:Weird and has very little to do with C by TigerNut · · Score: 1

      But that's the point... you want to create code that either uses a native feature found on certain CPUs (maybe something that PowerPC architecture is optimal for, as compared to the Pentium architecture), or else something that you KNOW causes bad behaviour under certain compilers. As a long-time embedded software designer, I can tell you that with embedded hardware, OS and compiler suites, there is a BIG difference from one system to the next on the level of optimization. About 10 years ago we were doing competitive analysis on various embedded (or embeddable) CPUs, using standard benchmarks as well as a few processing tasks of our own. If you increased the task complexity a critical amount, you'd cause one CPU to start cache thrashing, and the other CPU, with a slightly bigger cache or better reuse strategy, would be fine. Under the rules of the contest, this would be exactly the kind of thing to exploit.

      --

      Less is more.

    3. Re:Weird and has very little to do with C by Penguin+Programmer · · Score: 1

      True, there are more factors than just the C involved in this challenge. However, I think it's a very interesting problem none the less, since degrading performance on competitors' platforms is something that companies actually do. With the recent open-sourcing of Solaris and so many companies getting into open-source, tricks to make certain hardware/software platforms look good or bad will probably become something to watch for in patch submissions and the like.

    4. Re:Weird and has very little to do with C by Carnildo · · Score: 1
      It depends way too much on things like the compiler being used, the optimization level, the actual hardware (how do they compare program run-time if the two OSes in question run on very different CPUs ?), and so on, than on actual C.


      If you do it right, it's entirely dependant on the actual C code (and its interaction with the OS/CPU). There's no compiler flag in the world that can turn an O(n!) program into an O(n) one.
      --
      "They redundantly repeated themselves over and over again incessantly without end ad infinitum" -- ibid.
  7. Re:LAMP by dubloe7 · · Score: 1

    you could learn c so you could code in something people wont hate you for using *cough* php *cough*

    --
    "I worry that some day my child will ask me, 'Dad, where were you when they took freedom of the press from the internet?
  8. This was inspired by ... by l2718 · · Score: 1

    For a (past) contest targeting the specific scenario I described above, see the Obfustcated V contest, which was the inspiration for Xcott's contest. The winning entry manages to only show its bias on the day of the election itself, but not before, so that it can satisfy serious testing.

  9. Re:LAMP by Greyfox · · Score: 1

    Someone's going to have to write the operating system of the future and it ain't going to be in Ruby. Or C# for that matter.

    --

    I'm trying to teach myself to set people on fire with my mind... Is it hot in here?

  10. Any code by Anonymous Coward · · Score: 2, Insightful

    Any code that includes a patented idea could win this contest.

    Looks innocent, is malicious.

  11. Re:LAMP by John_Booty · · Score: 1

    Now that I'm getting PHP under my belt, do I have any reason to learn C? Isn't it Ruby time? Shouldn't everyone go LAMP beginner programmer or otherwise?

    LAMP is certainly a great tool. It's very practical and useful.

    As for a beginner language? Hmm. I always kind of wince when people get their programming feet wet with web-based development. There are so many issues involved with web development (browser issues, the interplay between database/server-side scripting/client-side scripting/etc) and several different languages involved (SQL,PHP,HTML at a minimum) that a beginner's head is often swimming.

    It's certainly not rocket science, and if you can hack it - good for you! But I'm kind of skeptical that the best way to learn good programming practices by starting off with web development.

    On the other hand, web development is fun and you can see some immediate results. Throwing an application up on the web is a lot more satisfying than writing Yet Another Linked List Implementation in C/C++ or something - something that would surely turn a lot of potential programmers off. While I'd rather see new programmers go the traditional CS route and do some learning of "the basics" in non-GUI non-web programming environments*... whatever works. Have fun!

    * These environments could certainly be modern OO languages like Ruby

    --

    OtakuBooty.com: Smart, funny, sexy nerds.
  12. Re:I'll submit the source code for... by Lumpy · · Score: 2, Funny

    Windows!

    Oh darn, it's not written in C.


    Hey Windows XP and Vista are great examples of how powerful and fast VB.NET is!

    You cant write as robust of a Operating system in Python or Ruby!

    --
    Do not look at laser with remaining good eye.
  13. TFA says by LordEd · · Score: 1
    The program is supposed to read a set of words on stdin, and print a frequency count of unique words in lexicographical order. Essentially the output should match the command line

    tr "[:space:]" "\n" | sort | awk 'length($0)>0' | uniq -c
    1. Re:TFA says by zeugma-amp · · Score: 1

      So, to discover the top ten words in the King James Bible:

      $ cat bible11.txt | tr "[:space:]" "\n" | \
      sort | awk 'length($0)>0' | uniq -c |sort -nr | head -10
      62128 the
      38617 and
      34436 of
      13412 to
      12735 And
      12467 that
      12189 in
      9760 shall
      9509 he
      8930 unto

      Fun for the whole family.

      --
      This is an ex-parrot!
  14. Re:LAMP by usidoesit · · Score: 1

    Go Python for now, keep an eye on Rubyforge. Not sure if the way Ruby is implemented (with the syntax trees rather than bytecodes) is going to be an issue or not. Also mod_ruby is implemented still kind of wonky I understand.

  15. Potential for malice? by MT628496 · · Score: 2, Interesting

    Isn't it likely that encouraging people to design programs in this way would lead to companies using these techniques in their own software? Say someone has a contract with Microsoft, the linux version, while being fully functional, could be made to be slower. Then someone would go and demonstrate how poor linux performanace is yadda yadda

    1. Re:Potential for malice? by plover · · Score: 2, Informative
      That's probably part of the point of the contest -- to point out that malicious code such as they're suggesting already exists in the world.

      Saying that this "helps the bad guys" (not that you did) misses the point. We know there are bad guys out there. This becomes an awareness campaign.

      There are several documented cases of stuff like this happening. Both ATI and nVidia (the graphics card companies) added code to their drivers to cheat -- take "shortcuts" when certain benchmark programs were running -- so the reported frame-rate looked great, while the resulting graphics quality silently fell. Detroit Diesel and six other companies were fined millions of dollars for tuning their engine management code to recognize the operating conditions that were specified in the emissions test -- some combination of RPM, time and load -- and adjusted the timing for minimal emissions and fuel consumption under only those conditions. The rest of the time they optimized for maximum power. It was discovered only when they failed to certify their engines in Europe, where the test conditions were different.

      Closer to open source, just a year or two ago an unknown person checked in a subtle change to the kernel source that would have granted root access in the case of a certain error condition. It was caught during a review.

      These are real-world hacks. Denial doesn't solve the problem. Only awareness can help smoke them out.

      --
      John
    2. Re:Potential for malice? by Penguin+Programmer · · Score: 1

      You speak as though this is something that's unheard of. Companies already do this. Challenging the community to come up with ways of doing it can only help with detection of it in the future.

    3. Re:Potential for malice? by corngrower · · Score: 1

      You mean like how Intel constructed their C++ compiler to produce slower code for AMD chips than their own Pentium chips?

  16. Re:That's invalid by LiquidCoooled · · Score: 1

    Of course its valid.
    Running a program in multiple operating systems requires some sort of virtualisation.
    Wine does this job and allows a program to be used in multiple operating systems without recompilation.

    The only other way I know of uses compiler directives to run through different code flows and it would be easy to see why a program ran slowly on X operating system.

    Besides, its UNDERHANDED - nobody said it was a fair competition.

    --
    liqbase :: faster than paper
  17. Re:Fun idea, but... by Penguinoflight · · Score: 2, Interesting

    Yeah, but why pay when you can just get the HACKER to go to jail and be charged as a terrorist?

    --
    "And we have seen and do testify that the Father sent the Son to be the Savior of the World"
    1 John 4:14
  18. Re:That's invalid by Penguinoflight · · Score: 1

    Wine is not an OS, it's a set of libraries which are incomplete. Second, virtualization is not required to run C programs on different operating systems. The idea is you submit the source, specify the compilers/OS's to use and hope for the best(worst). Despite the unexciting design of the page, the write-up is actually quite good.

    --
    "And we have seen and do testify that the Father sent the Son to be the Savior of the World"
    1 John 4:14
  19. can't wait for the results by CaptnMArk · · Score: 1

    void main(int argc, char **argv, char **envp) {
    }

  20. Re:I'll submit the source code for... by mondoterrifico · · Score: 1

    Heh, maybe im missing something, but how is this funny? NT kernel is most definitely written in C. And no you couldn't write a decent operating system with Python or Ruby.
    Maybe I am missing the joke, if so wouldn't be the first time. :)

  21. To quote Fark.com... by clevershark · · Score: 1

    "What could possibly go wrong?"

    --

    My sig is too lon

  22. Re:LAMP by Eli+Gottlieb · · Score: 1

    It's in Pascal :-).

  23. Lucid Programming? by frantzdb · · Score: 2, Interesting

    I see a lot of utility in a contest like this. As much fun as an obfuscated programming contest is, in a day and age when our critical infrastructure, including voting machines, are running on software, it is important that we be aware of just how difficult it to assure that code does what it should.

    A related contest I would like to see is a lucid programming contest. Given some small but insidiously tricky task, write a program in the language of your choice which solves the problem correctly and which is easy for someone else to understand. It would be interesting to discover which languages excel at this task and what sorts of patterns emerge when emphasis is placed on clarity.

    1. Re:Lucid Programming? by Beryllium+Sphere(tm) · · Score: 1

      >Given some small but insidiously tricky task, write a program in the language of your choice which solves the problem correctly and which is easy for someone else to understand.

      (loop (print (eval (read) ) ) )

  24. My entry! by radiumhahn · · Score: 4, Funny
    #include <stdio.h>

    main() {

    /* Rob a bank! */
    /* Steal Stuff! */
    printf("hello, world\n");
    /* Use Drugs! */
    /* Kill, Kill, Kill! */
    }

  25. My entry -- the world's last C bug by PeeAitchPee · · Score: 4, Funny

    An oldie but goodie . . .

    while (1)
    {
    status = GetRadarInfo();
    if (status = 1)
    LaunchMissiles();
    }
    1. Re:My entry -- the world's last C bug by CoughDropAddict · · Score: 3, Funny
      or:
      while(1)
      {
        status = GetRadarInfo();
        if(status == 1);
          LaunchMissles();
      }
    2. Re:My entry -- the world's last C bug by yfarren · · Score: 1

      No. Your Code, is concievably, right. That is ,it depends on what "GetRadarInfo()" returns. His Code, is wrong. Because an assignment operator returns what was assigned.

      so if(status = 1) in his code is always true. In your code, not neccesarily. Hence, his is a bug. And funny.

    3. Re:My entry -- the world's last C bug by joe_bruin · · Score: 4, Insightful

      so if(status = 1) in his code is always true. In your code, not neccesarily. Hence, his is a bug. And funny.

      Look again. This time, look for any extra semi-colons that shouldn't be there. The responder's joke was an improvement on the original, and would not have been flagged by an optional compiler warning (at least in the case of gcc).

      if(status == 1);

    4. Re:My entry -- the world's last C bug by boldtbanan · · Score: 1

      Nah, the function names give it away. You should call them something like OmgPonies() and LOL()*.

      * Of course, that's assuming 12 year old girls will be judging the competition. Function names like that raise huge flags with normal people

    5. Re:My entry -- the world's last C bug by CoughDropAddict · · Score: 1

      Well, thanks for offering a window into the psyche of the moderators, who fail to realize that my joke is at least as funny as the one that kicked off this thread (and a lot more original).

      Sigh... so much is lost on Slashdot moderators these days.

    6. Re:My entry -- the world's last C bug by yfarren · · Score: 1

      Oh Man! I dont even know where to begin. D'OH!

  26. Ho hum... by drrngrvy · · Score: 1

    Is noone talking about which OS will 'lose' (ie. the winning program will run slower on it rather than the competition) because you all assume that Windows will?

    1. Re:Ho hum... by stargazerr · · Score: 1

      I, for one, am assuming that. And you dont even need malicious code for that. Perfectly legitimate code refuses to run on Windows.

    2. Re:Ho hum... by drrngrvy · · Score: 1

      Ahh, you'd be American then...

  27. Re:Any C code is potentially malicious by Paralizer · · Score: 1

    Mod the parent +1 funny.

    This is a hilarious insight into other programmers points of view, but they'll have a hard time writing anything vastly efficient, especially at a lower level (say system drivers).

  28. Re:I'll submit the source code for... by scmason · · Score: 1, Informative

    Uhm, yeah, you missed the joke.

    --
    "I am a patient boy. I wait I wait I wait. My time is water down the drain..." Fugazi
  29. It's marketable! by hGMFliP · · Score: 1

    Imagine you're a company developing applications and you get a resume from someone who won this contest. You want the best infiltrators on your team because they'd know what to look for when writing a "secure application." Just like you'd want the best "(24x02"s on your network security team... theoretically :).

    It's like the story of Frank Abagnale.

    ...and in some circles... it's an extension of one's manhood

    --
    This message was posted using recycled electrons.
  30. Re:Any C code is potentially malicious by BlueScreenOfTOM · · Score: 2, Insightful

    C# has pointers (unsafe blocks anyone?), and generally the OS protects against stupid pointer use in C by throwing the famous Segmentation Fault if you try to mess with something outside your memory boundaries. It gets dangerous when you start making system calls. Try allocating 100kb of Kernel memory in a while(1) loop. That'll fuck up the system real fast.

  31. Beta?? by HaydnH · · Score: 1

    Can I beta test these things? =P

    --
    Time is an illusion. Lunchtime doubly so. - Douglas Adams
  32. Yay you. Way to suck the humour out. by BlargGlarb · · Score: 1

    If you got the joke, it was close enough.

  33. Just another item on my list by Nom+du+Keyboard · · Score: 1
    write malicious C code that looks perfectly readable and innocent under informal inspection of the source.

    Just another item on my list of reasons I hate C-language. And I first started uisng C in 1977.

    --
    "It's the height of ridiculousness to say for those 9 lines you get hundreds of millions."
    1. Re:Just another item on my list by gentlemen_loser · · Score: 1

      Have you not seen most (not everyone's) Visual Basic code? At least C forces some level of competance out of a coder...

  34. Is this the sort of thing they're looking for? by Ashtead · · Score: 2, Interesting

    #include <stdio.h>

    main()
    {
      char stuf[80];

      while(1)
      {
        fputs("Enter something: ", stdout);
        fflush(stdout);
        gets(stuf);
        fputs("You have entered ", stdout);
        printf(stuf);
      }
    }

    silly (and looks innocent enough) but closer inspection will reveal nastyness...

    --
    SIGBUS @ NO-07.308
    1. Re:Is this the sort of thing they're looking for? by Fortun+L'Escrot · · Score: 1

      im not very good at programming. but apart from using fgets which gcc says is dangerous...what is the nastiness in question here?

    2. Re:Is this the sort of thing they're looking for? by Ashtead · · Score: 1

      In addition to the infamous gets() (not fgets(), which is a safe replacement for gets()) there is the call printf(stuf); where interesting things will happen if the string that was typed in contains percent signs directing printf() to try formatting or even writing to the stack in the vicinity of the call itself. This could be the return-address of the printf() call, or some other neighboring variables; and carefully crafted combination of excess bytes here could become interpreted as if it were executable code, and the machine could subsequently be pwnd. The post by whitenaga above gives an example.

      My example was a bit contrived by the way, just a handful of some known bad practices I banged together in five minutes...

      --
      SIGBUS @ NO-07.308
    3. Re:Is this the sort of thing they're looking for? by Otto · · Score: 3, Informative

      im not very good at programming. but apart from using fgets which gcc says is dangerous...what is the nastiness in question here?

      printf(stuf) is dangerous because "stuf" is being used as the format specifier to printf.

      Now, normally you use printf like this: printf("%s", stuf), which says to print the string contained in stuf to stdout. But with the printf(stuf) line, you can carefuly craft what is in stuf to make it execute arbitrary code. The key to doing this lies in the %n specifier.

      If you were to do printf("Ha!%n",&some_int), then not only would the word "Ha!" be printed to the screen, but the contents of some_int would get set to 3, since that's how many characters were printed and that's what %n is telling it to do.

      Now, say I pass in "%X" as stuf. My output will be a number. What number is that? Why, it's the return address of printf, because %X is really telling it to print the contents of the next address on the stack, and that address happens to be a return address (since we didn't pass in real arguments to printf). If I therefore carefully craft my string, I can not only overwrite that return addres using %n, but I can overwrite it with a pointer to a location which will be executed when printf returns by varying the length of my string. And I can easily vary the length of my string by doing some things like %.1234x in there, which will happily stick 1234 characters in my string easily and add 1234 to n.

      Once I know the return address, I can work out where my string buffer is actually being stored, and then I can include my exploit code in that string itself, and execute it right from there.

      Short version is that passing format specifier strings to printf as anything other than literals is dangerous unless you know exactly what the format specifier string really is.

      --
      - Give a man a fire and he's warm for a day, but set him on fire and he's warm for the rest of his life.
  35. Seems ominous by cpt+kangarooski · · Score: 1

    #include

    int main( void )
    {
          printf("Goodbye, world!");

    }

    --
    -- This and all my posts are in the public domain. I am a lawyer. I am not your lawyer, and this is not legal advice.
  36. Re:Any C code is potentially malicious by bckrispi · · Score: 1

    Ever hear the phrase "the right tool for the right job"? Of course, for driver writing you'll need C and Assembler, but for 95% of corporate programming tasks, it's unneeded. Languages with array bound checking, no direct pointer access, etc. may make for larger, slower executables, but they are *much* more condusive to shorter development cycles.

    --
    Xenon, where's my money? -Borno
  37. Not really by Nerdfest · · Score: 1

    I believe the software was stolen, not purchased, so from my point of view, the answer would be a definite 'no', although with the state of legal affairs the way it is (burglar slips and sues), all bets are off.

    Since it's the CIA, and in another country, I would imagine the answer would be 'no' regardless. But happily, IANAL.

    1. Re:Not really by IgnoramusMaximus · · Score: 1
      I believe the software was stolen, not purchased, so from my point of view, the answer would be a definite 'no', although with the state of legal affairs the way it is (burglar slips and sues), all bets are off.

      The story is pretty much proven bullshit, and it keeps changing constantly. In some versions the Russians bought the software from the US, UK, you name it, in some others they stole it, it was written in Assembler running on MC6800, In C on PDP-11s, on IBM mainframes, on Russian clones of PDPs/mainframes/what not, etc and so on. In all likelyhood it was simply an industrial accident but there a lot of idiot "credit" takers who want to paint themselves as characters out of some Chuck Norris flick, while making coin on their "memoirs". The Russians for their part claim that while an explosion occured in 1982, the damage was fixed in "one day", which would render claims of "gigiantic, seen from orbit" rather contradictory. Some of these credit-takers are stupid enough to try to take credit for another accident in June 1989 which destroyed two passenger trains in the Bashkirian Republic of the Soviet Union. Over 400 passengers died immediately and 806 were injured then.

      Since it's the CIA, and in another country, I would imagine the answer would be 'no' regardless.

      Only up to the moment when they proudly announced their handiwork to the world. Cue the lawsuits and seizure of US assets. The only reason it is not happening is that Russians know these crackpot stories to be just that (although the idiots writing these books could open themselves to civil lawsuits in Russia and might open any company in which they have any stake and which operates in Russia to asset seizures).

  38. Re:Any C code is potentially malicious by jchoyt · · Score: 3, Informative

    Er, Java has pointers. They are called references and you HAVE to use them every time you pass an object around - that includes any arrays, including arrays of primitives. It's just that in Java you don't have a choice on how to pass parameters to methods.

    --
    Sometimes the truth is arrived at by adding all the little lies together and deducting them from all that is known.
  39. Re:Any C code is potentially malicious by Jeremi · · Score: 1
    Try allocating 100kb of Kernel memory in a while(1) loop. That'll fuck up the system real fast.


    Maybe not... on many OS's, the memory isn't actually allocated until you read or write it. So e.g. in Linux/Unix, your task would quickly run out of address space and be killed, but the rest of the OS wouldn't notice much difference.


    Now if you were to allocate and clear memory in a loop, that would cause more trouble.

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  40. Voting Fraud - KISS by SeanDuggan · · Score: 1

    In Diebold's case, I'm not willing to ascribe to incompetence that which can be explained by malice.
    Personally, I'd go Occam's Razor on that issue and say that there's been a few hundred more years of mechanical voting fraud to fall back on rather than messing with software. Why do you think the dead rise again every few years to vote?

    --
    This sig has absolutely no significance and serves only to take up screen space and waste the time of the reader.
    1. Re:Voting Fraud - KISS by Richy_T · · Score: 1

      Why do you think the dead rise again every few years to vote?

      Cause the queue to hell is backed up with dead politicians.

      Rich

  41. Re:Fun idea, but... by cno3 · · Score: 1

    I hear the going rate is $10,000 and a trip to Moscow.

  42. So who wants to talk strategy? by patio11 · · Score: 3, Interesting
    Here's what I'm thinking: take a data structure which is well-understood, easy to implement, and boring as mud. Like, say, a hash-table with collisions resolved by linking. Everybody saw that back in sophomore CS right? And everybody knows with even a cursory inspection that a hash table offers constant-time performance on lookups and o(maximum size of table) time on reading out, right? Except when it doesn't. Malicious choice of data for feeding into a hash table can severely degrade performance, and we wouldn't want that, so we're going to be extraordinarily conscientious engineers and salt our hash function so that a malicious user can't cause our program to have worst-case performance.

    I think, with creative use of bad programming, you could corrupt either the salt or the calculation of the hash function in such a way as to guarantee that for a target OS the hash-table performance would degrade into worst-case. So if you took your borked hash table, and used it to implement an associative array, the fairly trivial read in stdin, increment fields in associative array, sort array in order code could be made to perform at average time complexity in non-targetted OSes and worst-case time complexity in your target OS. Assuming you pick an O(n log n) sort algorithm, if you manage to "accidentally" make each of those n's actually polynomial complexity (heck, n^2 even) the computer should essentially blow up on non-trivial data sets. Its late in the evening and I haven't thought through this very much, but one way would be to use utsname's sysname thing as part of your "random data" to make the salt. That sounds a little obvious though. Maybe there's some obscure function somewhere for getting dates or times or something that I can exploit format of the returned data to reveal the difference between OSes, as that would be a lot harder to detect ("oh, seeding a hash function with a date and some magic numbers, nothing wrong with that").

    Anybody got any ideas or corrections to share? Its been a while since I've taken data structures, and I've got essentially no ideas for obscure functions revealing system differences to exploit (C isn't my bag).

    1. Re:So who wants to talk strategy? by Fahrenheit+450 · · Score: 1

      The only problem with this approach is that the difference between O(n log n) and O(n^2), or O(1) and O(n) would likely require a fairly large data set before you see serious practical performance degradation, and I'm not sure you'll get that with their test data. You'd likely need a boneheaded data structure that goes from O(poly) to O(exp) time to see a significant time difference, which I think they're shooting for.

      --
      -30-
    2. Re:So who wants to talk strategy? by psmears · · Score: 1

      Using a hash table with a "biased" hash function is a nice idea. You could exploit subtle differences in the platform, such as whether certain C types are signed/unsigned, or big/little-endianness:

      // Trivial (and fairly useless) hash function
      int calculate_hash(const void *data, size_t length)
      {
      int total = 0;
      const unsigned char *bytes = data;
      for (int i = 0; i < length; i++) { total += bytes[i]; }
      return (total % NUM_BUCKETS);
      }

      // Calculate the hash value for a record. Base it on the
      // employee id since that's unique per employee
      int calculate_employee_hash(const employee *emp)
      {
      return (calculate_hash(&employee->id, 2));
      }
      On a little-endian system, assuming a relatively even distribution of [32 bit] employee IDs, this will perform well; on a big-endian system (high-byte-first) it will store the first 65536 employees in the same hash bucket - which, if you're searching the buckets linearly is going to get pretty slow :-)
    3. Re:So who wants to talk strategy? by Black+Acid · · Score: 1
      Sounds like an Algorithmic Complexity Attack. According to the paper, such vulnerabilities are "extremely widespread", found in software such as:
      Mozilla 1.3.1
      DJBDNS 1.05
      TCL 8.4.3
      GLIB 2.2.1
      Python 2.3b1
      Perl 5.6.1
      Perl 5.8.0
      Linux 2.4.20 directory cache (dcache)
      Squid 2.5STABLE1
      Bro IDS 0.8a20
    4. Re:So who wants to talk strategy? by Ibn+al-Hazardous · · Score: 1

      There's a certain OS that more or less demands that you set hardware time to local time - whereas some other OSes prefer hardware time as GMT. This difference is not exploitable in UK during the winter, and probably not on 'puters with dual boot. It does have something to do with date and time though...

      --
      Yes, I am a biological organism. All rumors to the contrary are just that, rumors.
  43. Dangerous and suspicious looking by whitenaga · · Score: 4, Insightful

    Your code is dangerous, but it has to be exploited by a knowledgable user. I think what they're looking for in the Underhanded C Contest is code that exploits itself. But for the purpose of being pendantic, i'll bite... =)

    • You're using gets(), which is notorious for buffer overrun problems.
    • You mix fputs() and printf(), right next to each other. And you use printf() just like fputs(), and that looks suspicious.
    • printf(stuf); is practically asking for exploitation. If stuf contained the proper combination of "(filler) %junk %junk %n", printf()'s return address would be overwritten.
    --
    Lindsey
    @>-->-----
    1. Re:Dangerous and suspicious looking by Ashtead · · Score: 1

      Yes, I read the featured article afterwards, and they want something a lot more subtle than this, which is admittedly contrived. Anything containing something as obviously evil as gets() is probably disqualified from even entering the race.

      I guess mixing fputs() and printf() like this makes the code look weird and that gives the game away.

      --
      SIGBUS @ NO-07.308
    2. Re:Dangerous and suspicious looking by whitenaga · · Score: 1

      Actually... to me, your fputs() and printf() didn't give it away nearly so much as printf( string_var );. I've taught C and assembly language courses before, and every time there would be one of my students (usually top of the class) who would come up with a clever shortcut of just using "printf( string_var );" instead of "printf( "%s", string_var );". I'd show him/her why it was a bad idea, and at the same time encourage him/her to keep thinking outside the box. =)

      You are right, though: The subtlty described on the site is really clever! I don't think i'll be attempting a contest like this, for lack of mental horsepower...

      --
      Lindsey
      @>-->-----
    3. Re:Dangerous and suspicious looking by tender-matser · · Score: 1

      OT here, but new versions of gcc (with -O2) turn printf("%s\n", str) into puts(str)

      it was fun to discover why some program was dumping core when given a 0 pointer instead of printing "(null)".

      I have no idea what the C standard says about printf("%s", (char*)0), but IMO no optimizer should ever make such changes to the code.

  44. Re:That's invalid by JollyFinn · · Score: 1

    Id say it could be valid if wine ran it MUCH FASTER than windows ;-)

    --
    Emacs is good operating system, but it has one flaw: Its text editor could be better.
  45. Re:C vs. Java, and some observations on the code by Fahrenheit+450 · · Score: 1

    Actually, I think it would be more interesting, as it might require some cleverness instead of the tricks you describe above.

    However, according to the FAQ, you can submit solutions in other languages, so why not try your hand at Java? I've actually got an idea for this contest that uses OCaml, which is just as tight as Java with regard to these tricks. I just have to work a couple of small details first.

    --
    -30-
  46. Compiler says by JollyFinn · · Score: 1

    : undefined reference to `LaunchMissles'
    collect2: ld returned 1 exit status

    --
    Emacs is good operating system, but it has one flaw: Its text editor could be better.
    1. Re:Compiler says by Richy_T · · Score: 2, Funny

      #include "texan.h"

  47. Finally. by JollyFinn · · Score: 1

    There is good way to measure the real difference of different distributions!

    --
    Emacs is good operating system, but it has one flaw: Its text editor could be better.
  48. Fun with endianess by Anonymous Coward · · Score: 1, Interesting

    uint32 foo = 0;
    uint8 *bar =

    *bar = 3;

    while(foo--) {
    do_something();
    }

    You've got the point? With the right endiness, foo will not become '3', but more like 3*124 = ca. 50 Mio.

  49. Re:C vs. Java, and some observations on the code by mad.frog · · Score: 1

    Two of them involved a loop with something like while(a = b) instead of while(a == b)

    That may be *legal* C/C++ code, but IMHO it ain't *moral*.

    I always crank up my compiler warning level to 11 (and then set "treat warnings as errors") to warn about this sort of stuff.

    "But, but, but, that's legal!" you cry. "And it makes for more-efficient code!"

    Well, I submit to you that

    (1) modern optimizing compilers really make this sort of code-squeaking an exercise in obsessiveness, and
    (2) if you REALLY want/need to use this construct, code it like this:

            while ((a = b) != 0) // dodges the "possible unwanted assignment" warning in every compiler I've used

  50. Re:I'll submit the source code for... by Z34107 · · Score: 1

    Actually, the kernel of Windows is written in a smattering of machine language and C. The Windows API (not MFC) is also in C.

    Besides, the contest is to create a program that will perform miserably on a "competitor's" OS without the malicious, anti-competitive part of the code being obvious or anything other than innocent-looking.

    --
    DATABASE WOW WOW
  51. This is more than malicios code. by JollyFinn · · Score: 1

    Its basics of benchmarking. The goal of producing benchark that performs given task and results show one system inferiour to other is REALLY easy. Too bad I don't have one of the old mac mini:s to show my athlon64 the superiority of RISC architecture. We all know very well that RISC is 1000 times faster than CISC dinosaur.

    --
    Emacs is good operating system, but it has one flaw: Its text editor could be better.
  52. switch/case from hell by Merdalors · · Score: 1
    this giant switch statement that decided what function to call at runtime

    Sounds like your typical WndProc() function :o)

    --
    Slashdot entertains. Windows pays the mortgage.
  53. Re:C vs. Java, and some observations on the code by John+Bayko · · Score: 1

    The contest involves opening a file - that's just begging you to take the path (to construct the output file name) and check path separator or initial character while doing so.

    The trick would be to detect different Unix systems (in Java or other) without being obvious.

  54. Re:C vs. Java, and some observations on the code by rrohbeck · · Score: 1

    while ((a = b) != 0)

    But that's 7 (7!!!) keystrokes more than the short version. What's that going to do to my productivity?
    And it's wimpy coding too. No risk, no fun!
    I remember when I first wrote while(a=b) and the compiler complained about an unsafe assignment, I looked up the pragma that turned that warning off :)

  55. Re:Any C code is potentially malicious by Arandir · · Score: 1, Flamebait

    Sorry, but you're an ass. You've been fed a diet of shit so long you think it tastes good. Pointers aren't a problem, improper use of them is. Surprise! Improper use of ANYTHING is a problem!

    Undisciplined use of pointers is going to cause bugs. But since undisciplined coding itself causes bugs, who the fsck cares? The solution isn't to ban pointers, but to start beating undisciplined coders over the head. I'm not saying you have to use pointers, but if you are avoiding them because of fear, it's time to learn how to use them properly.

    --
    A Government Is a Body of People, Usually Notably Ungoverned
  56. real programming ? by coldhg · · Score: 1

    What is real programming?

    First of all it is not programming in C,nor Java, nor LISP, nor Prolog, nor Python.....
    LISP, Prolog, Python, Perl, CafeOBJ, Maude are based on concepts more or far more advanced then those on which C is based.
    And no one cand deny that a 1000+ lines LISP source code is harder to understand than a C code of the same length. (of course it depends on the purpose of the program written).
    And LISP has no pointers.

    In conclusion, try not to judge one programming language only through the prism of one characteristic (e.g.: having or not pointers)

    1. Re:real programming ? by CrankyOldBastard · · Score: 1
      1000 lines of LISP does a hell of a lot more than 1000 lines of C in most cases. Makes sense that it would be harder to understand.

      And yes I know Smalltalk completely shoots this arguement in the foot...

    2. Re:real programming ? by techno-vampire · · Score: 1
      What is real programming?

      It's what Real Programmers write, like Mel. If you've never heard of him, follow the link, read and be humbled by his genius.

      --
      Good, inexpensive web hosting
  57. ways to attack the OS by Creepy · · Score: 1

    since I don't plan to spend any time on this one, I thought I'd start a thread on ways to attack OS specific issues for people that do want to try (the hard version - non hardware dependent - architecture is easy - endian-ness, pipeline, unaligned memory copies, etc).

    since you can't rely on architecture, and can't attack stuff like endian-ness, you need to hit the nuances of the OS. One way I can think of is exploit size differences of stuff like wchar_t, since it's 4 bytes on most newer flavors of BSD (e.g. MacOSX) and 2 bytes on Linux, Windows, AIX, and perhaps others. Forcing a call to get sizeof(size_t) repeatedly if the size is not 2 would be another.

    For Windows to look good, you might be able to do something with line endings, but that may not be enough (since Linux or whatever could add them in their data, too) - try threads. Most OS's use pthreads, but Windows does its own - use that to your advantage. Also use the built-in thread pool functionality of Windows but always destroy and recreate the threads in pthreads. I'd say to use expensive calls like fork() on UNIX boxes, but if I were a judge, I'd call you on that. You could also do mean tricks like forcing locks on critical sections when geared towards the OS you don't like (or force a long delay like 500ms if another thread has the "token" to chose a line then make the code never hit that condition for the preferred thread type).

    how would you do it (if you don't want to bother trying, that is)?

  58. Re:Any C code is potentially malicious by nuzak · · Score: 2, Insightful

    There's no requirement at all in the JVM that references are implemented as pointers.

    Pointers POINT to arbitrary memory locations. References do not. You cannot recast a reference to an arbitrary type, you can't put arbitrary data at a reference location, you cannot reseat a reference with a new instance, you cannot do pointer arithmetic with references.

    It happens that pointers can be like as references, among many other things. This does not make references into pointers.

    --
    Done with slashdot, done with nerds, getting a life.
  59. Re:C vs. Java, and some observations on the code by Xcott+Craver · · Score: 1
    The contest involves opening a file

    No, the program reads from stdin and writes to stdout. Its function is basically the equivalent of that Unix command string on the main page.

    X

  60. Re:C vs. Java, and some observations on the code by Xcott+Craver · · Score: 1
    However, according to the FAQ, you can submit solutions in other languages

    The FAQ does not say this, and I certainly won't feel any obligation to install different compilers and interpreters because somebody submitted code in SML/NJ (or one of the other, inferior functional languages. Smiley.)

    The FAQ says that we'll accept C++, which is about as close as we get to being inclusive.

    X

  61. Re:Any C code is potentially malicious by spaceturtle · · Score: 1

    Actually Linux runs the kernel in ring 0, so the kernel cannot use virtual memory. Thus each 100 Kb would be allocated from physical memory. Also if the kernel "process" were "killed" that would most definitely affect the rest of the OS.

  62. Re:C vs. Java, and some observations on the code by Fahrenheit+450 · · Score: 1

    Well, not to get too nitpickety (especially since it's your FAQ), but it says:

    Can I use C++ instead of C?

    If you actually want to do something like that, then sure.

    No COBOL, please.


    Which to me reads as "Sure. We will accept other languages. Well... not COBOL."
    You may want to rewrite it in a more specific manner if you want to limit the languages involved.

    --
    -30-
  63. Pointers make it much harder to avoid mistakes. by spaceturtle · · Score: 1
    Unlike other constructs, pointer are very hard to verify for correctness. For example, take the following function:

    void readdata(char* s) {fgets(s,100,stdin);}
    Is this function safe? There is no way we can tell just by reading the code of the function. We will have to read the whole program to see if there is any way this function could be called with a NULL, unallocated or undersized buffer.

    Furthermore, if the buffer is undersized the function will likely appear to act correctly, but may cause an apparently unrelated failure somewhere else in the code, which makes pointer related errors much harder to track down.

    We can use a safe C-like language such as Cyclone. But reading the huge number of rules that Cyclone enforces to make pointers safe only reinforces that it is hard it is to be 100% sure that a non-trivial use of a pointer is safe in a C program.

    Further more I understand that ~50% of security holes are caused by misuse of pointers. Programmers *will* make mistakes, but programs written in "safe" languages save you from over half of them.

    Having said that I write a lot of code in C. However most of it is fairly trivial stuff and not security critical.

    1. Re:Pointers make it much harder to avoid mistakes. by Arandir · · Score: 1

      That function isn't safe because it uses fgets(), and not because it uses a pointer. Duh.

      Null terminated arrays (C style strings, in other words) are problematic to begin with, and fgets() and related functions just makes it worse by doing no bounds checking. But that is not a reason to avoid pointers, just a reason to avoid null terminated strings.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
  64. Real programmers by sdfad1 · · Score: 1

    Any Tom, Dick or Harry can write subtly malicious steganographic code, or obfuscated ones. Real programmers leave no traces in their source codes: Bow to the leetest hack of them all.

  65. Re:Any C code is potentially malicious by Jeremi · · Score: 1

    Ah, right you are... I missed the word "kernel" in the original post. I need to read more carefully!

    --


    I don't care if it's 90,000 hectares. That lake was not my doing.
  66. Re:Any C code is potentially malicious by patio11 · · Score: 1

    As a confirmed Java programmer (who is entering this contest anyhow, to broaden my horizons a bit), this argument always sounds like "There is nothing wrong with juggling chainsaws as long as you're man enough to handle it. If an arm gets chopped off, its because you were weak". No, its just that juggling chainsaws is inherently a *bad idea*. So is managing pointers by yourself unless you absolutely, positively have to. Yes, you may be the first programmer EVER who is man enough to handle 100% of his pointers 100% of the time. You might also end up without an arm.

  67. Re:Any C code is potentially malicious by Arandir · · Score: 1

    Using a pointer is NOT like juggling chainsaws. Don't be stupid.

    If you allocate memory, you must free memory. It's as simple as that. If you're allocating so much memory that you can't manage it anymore, then of course, you shouldn't do it. But to suggest that no one should ever use a pointer is silly. Millions of C/C++ programmers do it successfully every day.

    If your argument is that you shouldn't do it because you might do it wrong, then you need to apply the same logic to everything else. You might cause a race condition if you use threads, SO DON'T USE THREADS! In real life in fact, I find more race conditions in C code than I do memory related bugs. Java lets you use threads, so maybe you shouldn't use Java! Or what about the while loop? It's all too easy to create an infinite loop with the while statement. Too many programmers will write a loop without ever stopping to guarantee that the loop with exit. They shouldn't be allowed to do this! While we're at it, let's ban casts as well. And multiple inheritance. And exceptions. And everything else that might cause a bug. And to be safe, everything else as well.

    --
    A Government Is a Body of People, Usually Notably Ungoverned
  68. Are not ye thinking of "gets". by spaceturtle · · Score: 1
    It is "gets" not "fgets" that we are warned against.

    void readdata(char* s) {gets(s);}
    Is a no-no. "fgets" OTOH is about as good as you can get.

    My original objections, that we cannot verify that the psuedo-array "s" is as large as we think it is, or even that "s" is allocated still apply if we do not use fgets or a null-terminated strings e.g. they still apply to the function:

    void readdata(char* s) {for(i=0;i<100;i++){s[i]=getchar();}

    The only additional failure of null-terminated strings is that they are mildly confusing because you need a n+1 sized buffer to store n characters. However a null-terminated string would be perfectly safe if it were stored in a Java-style array.

    In C there is no way for a function to verify that it has been called correctly. Perhaps more seriously, if you call a function in a pointer language you cannot treat it as a blackbox. To be sure that it doesn't corrupt your memory you have to closely check their source code to verify that it uses pointers correctly.

    The ideal case would be e.g. a functional language where you could call Osamas_pretty_icon_function() and be sure that the worst that could possibly happen is that Osama wrote the function to return a ugly icon instead.

    1. Re:Are not ye thinking of "gets". by Arandir · · Score: 1

      Sigh. Your code snippet is passing in a pointer to a character. Yet you are reading in one hundred characters. Do you see the problem? It isn't the pointer!

      I was being a little too specific when I called null terminated arrays problematic. In general, ALL unbounded arrays problematic, and the use of pointers as arrays only compounds the problem. If you're going to use an array you must always know what its size is. In the case of your code snippet, you should have a second parameter for the size of the array.

      But why is it I never hear anyone bitch about arrays in C/C++? Why do they only bitch about pointers? I'll tell you why: because they're too busy bitching about pointers to think through the problem and realize that it's really unbounded arrays that cause the problems. There is no problem with allocating memory for a structure (for use in a linked list, or binary tree, or sparse matrix, or whereever). But the Java zealots have so thoroughly brainwashed people that they now think it's evil to allocate memory for a struct. Truly sad.

      --
      A Government Is a Body of People, Usually Notably Ungoverned
  69. But in C arrays are pointers (more or less). by spaceturtle · · Score: 1
    Since C/C++ more or less treat arrays as pointers, there is little point in treating C style arrays and pointers separately.



    Since we assume that "Data" is 100 bytes it makes little difference whether we add an extra parameter to the function. If the calling function incorrectly believes that it has enough space for 100 bytes, then it makes little difference whether is (incorrectly) states explicitly that it has enough room for 100 bytes or just implicitly assumes it has enough room. Either way readdata cannot check sizeof(s)>100.



    Yes you could disallow use of pointer arithmetic, and use bounded arrays, although C doesn't have primitives for this.



    You could still have code like this:

    AnObject *a;
    a=getAnObject().DoSomething;
    a.DoSmthngEls() ;
    Note that C++ will have automatically freed the temporary object "a" by the third line, and so you will be messing with unallocated memory. This code will work 99% of the time, and thus will only fail at the most embarrassing possible moment.



    Now you could get around this somehow, e.g. by garbage collection, but you will either be left with something like a Java reference or something obscure such as one of several different types of pointer supported by the Cyclone l language.



    So basically, yes you could limit pointers to the extent that they cannot cause strange non-local and non-deterministic problems. But then they wouldn't really be pointers anymore.