About sp2hari

I'm the Co-Founder of Interviewstreet.com.

Friends…

Top ten things that pops out of my mind when I think about Friends.

1. duck and the chick
2. ugly naked guy
3. double pizza
4. paleontologist
5. foozball
6. Days of our Lives
7. Mac and C.H.E.E.S.E
8. How you doin.
9. Turkey in thanksgiving dinner
10. ‘Shall we go get some coffee?’ ‘Sure. Where?’

Friends
Friends

Obfuscate C Code – Part II

Hi all, this is my second post on C code obfuscation. You can check out all my posts on obfuscation here.

In this post, we’ll see two techniques which one can use in C code obfuscation. The more we apply these to our code, the more obfuscated our code will result in. And of course, this is not the complete guide for obfuscation. Just the two important techniques I find interesting. :-)

Recursion
The first one is recursion. Yes recursion. :-) Well, before we start recursion we should know this. “To iterate is human, but to recurse is divine.” ;-). The great point about recursion is that it can make any simple code complicated. Before I explain what I’m going to do, let me post the code final code here.

T
=__LINE__;
#define FF T*T*T*T*T+T*T*T+T*T*T*T-T/T
char *___="He that falls in love with himself will have no rivals.";_$_(int _,int __){(__-_==(T/T)?printf("%c",*(___+_)):(_$_(_,(__-_)/T+_),_$_((__-_)/T+_, __)));}main(){_$_(T-T, FF);}

The code simply prints the quote “He that falls in love with himself will have no rivals.”, quoted by Benjamin Franklin.

So let us start with a simple code which does that.
#include <stdio.h>
int main() {
    printf("He that falls in love with himself will have no rivals.");
    return 0;
}

Now, let us see how to introduce recursion into this. You can say, to print a string, first print the first half of the string and then the second half of the string. Got it? Yes, it is like this

Print the string
    Print the first half of the string
        Print the first half of the first half of the string
        …
        …
        
        Print the second half of the first half of the string
        …
        ….
    Print the second half of the string
        Print the first half of the second half of the string
        …
        …
        
        Print the second half of the second half of the string
        …
        …

After we introduce recursion into this logic, we get a code similar to the following. Again, the code can be made further complicated. Just remember, there is no limit to obfuscation.

#include <stdio.h>
char *str = "He that falls in love with himself will have no rivals.";
void print(int start, int end) {
    if (end-start==1) {
        printf("%c", *(str+start));        
    }
    else {
        print(start, (end-start)/2+start);
        print((end-start)/2+start, end);
    }
}
int main() {
    print(0, 55);
    return 0;
}

Next, we remove the 2 in the else part of the code using #define. I use __LINE__ in this example. :). So now the code looks like this.

#include <stdio.h>
t=__LINE__;
char *str = "He that falls in love with himself will have no rivals.";
void print(int start, int end) {
    if (end-start==1) {
        printf("%c", *(str+start));        
    }
    else {
        print(start, (end-start)/t+start);
        print((end-start)/t+start, end);
    }
}
int main() {
    print(0, 55);
    return 0;
}

Next, we remove the if else in the print statement and have a single conditional statement. That changes the whole picture in the print function, as shown below.

#include <stdio.h>
t=__LINE__;
char *str = "He that falls in love with himself will have no rivals.";
void print(int start, int end) { (end-start==1?printf("%c", *(str+start)):(print(start, (end-start)/t+start),print((end-start)/t+start, end))); }
int main() {
    print(0, 55);
    return 0;
}

Finally we change all the variable names so that they have only _’s and remove unnecessary space. Also you can change the value 55 to as 32+16+8-1 (all of these generated only using the previously used 2). So this is the final code. :)

T
=__LINE__;
#define FF T*T*T*T*T+T*T*T+T*T*T*T-T/T
char *___ = "He that falls in love with himself will have no rivals.";_$_(int _,int __){(__-_==1?printf("%c", *(___+_)):(_$_(_,(__-_)/T+_),_$_((__-_)/T+_, __)));}main(){_$_(T-T, FF);}

Preprocessor Statements
The second technique I find interesting is using #ifdef, #else, #endif and #include. You can make any code obfuscated without much programming.

Again, let us take the same simple code to explain the usage of preprocessor statements. Though it is much more effective when you apply this to an obfuscated code.

So the sample code with which we start will be

#include <stdio.h>
int main() {
    printf("He that falls in love with himself will have no rivals.");
    return 0;
}

The resultant obfuscated code will be


#ifdef T1
    #ifdef T2
        #ifdef T3
            #ifdef T4
                }    //Line 5
            #else
                #define T4
                return 0;    //Line 4
                #include __FILE__
            #endif        
        #else
            #define T3
            printf("He that falls in love with himself will have no rivals.");    //Line 3
            #include __FILE__
        #endif
    #else
        #define T2
            int main() { //Line 2
        #include __FILE__
                
    #endif
#else
    #define T1
        #include <stdio.h> //Line 1
    #include __FILE__
#endif

I guess I can’t explain much on this. This is one simple concept in which preprocessor complies selected lines and then the same file is included again. :) If the above code is confusing, read this article on preprocessing and then try some simple code using this idea. Then this code will be a cakewalk.

You can download all the C files as a single zip file here.

Obfuscate C Code – Part I

Hello, this is the first post I’m writing on C code obfuscation. Let me warn you before I start. I am a beginner in code obfuscation and still learning from different code snippets I get from my friends.

Since this is the first post in this series, we will start with hello world. But instead of printing the same old hello world, we will print the quote “He that falls in love with himself will have no rivals.”, quoted by Benjamin Franklin.

We need a simple base program to start with right? The following code prints the quote.

#include
int main() {
char s[123] = "He that falls in love with himself will have no rivals.";
printf("%s", s);
return 0;
}

Surely, that is not the obfuscated code. First, let us convert the string into character array and instead of printing the string, we print the character array. Simple right? So the code now looks like this.

#include
int main() {
int i;
char s[] = {'H','e',' ','t','h','a', 't', ' ', 'f', 'a', 'l', 'l', 's', ' ', 'i', 'n', ' ', 'l', 'o', 'v', 'e', ' ', 'w', 'i', 't', 'h', ' ', 'h', 'i', 'm', 's', 'e', 'l', 'f', ' ', 'w', 'i', 'l', 'l', ' ', 'h', 'a', 'v', 'e', ' ', 'n', 'o', ' ', 'r', 'i', 'v', 'a', 'l', 's', '.'};
for (i=0; i<55; i++) {
printf("%c", s[i]);
}
return 0;
}

Next step, we take the two variables “i” and “s” outside the main. Since now the two variables are in global scope, if we don’t define the data type, it is an integer by default. Since we can define a character array as an integer array, we need not provide the datatype for both the variables. So now the code looks like this. Also we can change “int main” to “main” and remove the “return 0;” statement.

Note:: This idea of not defining the data type shouldn’t be used if you are practising for IOCCC. In there, the guidelines clearly states the following.
When declaring local or global variables, you should declare the type:

int this_is_ok;
this_is_not; <-- don't use such implicit type declarations

i, s[] = {'H','e',' ','t','h','a', 't', ' ', 'f', 'a', 'l', 'l', 's', ' ', 'i', 'n', ' ', 'l', 'o', 'v', 'e', ' ', 'w', 'i', 't', 'h', ' ', 'h', 'i', 'm', 's', 'e', 'l', 'f', ' ', 'w', 'i', 'l', 'l', ' ', 'h', 'a', 'v', 'e', ' ', 'n', 'o', ' ', 'r', 'i', 'v', 'a', 'l', 's', '.'};
main() {
for (i=0; i<55; i++) {
printf("%c", s[i]);
}
}

Next, we remove the 55 to the size of the array. We need to replace 55 by “sizeof(s)/sizeof(int)”. Let us do that in a better way as shown below. The two preprocessor statements added below to replaces ck by sizeof(s)/sizeof(int). The point to note here is that we have added the preprocessor statements in between the for statement.


i, s[] = {'H','e',' ','t','h','a', 't', ' ', 'f', 'a', 'l', 'l', 's', ' ', 'i', 'n', ' ', 'l', 'o', 'v', 'e', ' ', 'w', 'i', 't', 'h', ' ', 'h', 'i', 'm', 's', 'e', 'l', 'f', ' ', 'w', 'i', 'l', 'l', ' ', 'h', 'a', 'v', 'e', ' ', 'n', 'o', ' ', 'r', 'i', 'v', 'a', 'l', 's', '.'};
main() {
for (i=0;
#define f(z) sizeof(z)
#define ck f(s)/f(int)
i<ck; i++) {
printf("%c", i[s]);
}
}

Since i is a global variable, we need not initialize the value to 0. Again, we can remove the i++ statement by changing s[i] to s[i++]. And also note that a[i] and i[a] are both the same. So we can use i++[s]. So the code now becomes

i, s[] = {'H','e',' ','t','h','a', 't', ' ', 'f', 'a', 'l', 'l', 's', ' ', 'i', 'n', ' ', 'l', 'o', 'v', 'e', ' ', 'w', 'i', 't', 'h', ' ', 'h', 'i', 'm', 's', 'e', 'l', 'f', ' ', 'w', 'i', 'l', 'l', ' ', 'h', 'a', 'v', 'e', ' ', 'n', 'o', ' ', 'r', 'i', 'v', 'a', 'l', 's', '.'};
main() {
for (;
#define f(z) sizeof(z)
#define ck f(s)/f(int)
i<ck;
)
printf("%c", i++[s]);
}

Next, we remove the extra spaces so that the code is “poorly” aligned, as shown below. Also, now, we can replace the variable names by _ and __ etc. I haven’t done much to the character array here. That is not the aim of this post. Will write a separate post on manipulating strings. But for now, we can convert the character array to hexadecimal or octal numbers. ;-) (This is not the best way to obfuscate it though).

So the final code looks something like this.

#define ____(z) sizeof(z)
_, __[] = {0x48, 0x65, 0x20, 0x74, 0x68, 0x61, 0x74, 0x20, 0x66, 0x61, 0x6c, 0x6c, 0x73, 0x20, 0x69, 0x6e, 0x20, 0x6c, 0x6f, 0x76, 0x65, 0x20, 0x77, 0x69, 0x74, 0x68, 0x20, 0x68, 0x69, 0x6d,0x73, 0x65, 0x6c, 0x66, 0x20, 0x77, 0x69, 0x6c, 0x6c, 0x20,0x68, 0x61, 0x76, 0x65, 0x20, 0x6e, 0x6f, 0x20, 0x72, 0x69, 0x76, 0x61, 0x6c, 0x73, 0x2e}; main() { for (;
#define ___ ____(__)/____(int)
_<___;) printf("%c", _++[__]);}

All suggestions on still screwing up this code are welcome. ;-)

Update: You can download all the C files as a single zip file here.

Swirl images with ImageMagick

This simple snippet can be used for creating animated gif images with swirl effects. I was bored at home and saw that ImageMagick was installed in my machine. :) So started playing with that. :-)

The shell script will create the second image from the first image shown below.

Don\'t Panic —–> Don\'t Panic Swirl :)

#!/bin/bash
FILENAME="hari.png"
FRAMES=30
ROTATEANGLE=30
OPTION="swirl"
declare -i I
COMMANDOPTION="";
I=0;
while [ $I -lt $FRAMES ]
do
    NAME=`echo "$I*$ROTATEANGLE" | bc`;
    convert -$OPTION "$NAME" "$FILENAME" "$OPTION"_"$NAME".png
    COMMANDOPTION=$COMMANDOPTION" "$OPTION"_"$NAME".png"
    echo $NAME
    I=$I+1
done
convert -coalesce -dither -colors 32 -layers optimize $COMMANDOPTION hari-opt-32.gif

The code is pretty simple once you know the options for convert command of ImageMagick.

ImageMagick doc says the following for convert command. “convert between image formats as well as resize an image, blur, crop, despeckle, dither, draw on, flip, join, re-sample, and much more.” Well, seriously, there is MUCH MORE. :-)

The option to swirl an image is swirl. It takes angle by which the images has to be swirled as the parameter.
So the following command swirls the image by 90 degrees.
convert -swirl 90 src.png dest.png

To create an animated GIF using a set of png images, we use the coalesce option. The following command creates output.gif using three PNG files (input1.png, input2.png and input3.png). To reduce the file size, use the options like dither, colors and layers. The more colors you have in your image, the more will be the file size. For example, in the following snippet, the second commands generates a GIF file which is small in size compared to the first GIF file.

convert -coalesce input1.png input2.png input3.png output.gif
convert -coalesce -dither -colors 32 -layers optimize input1.png input2.png input3.png output-compressed.gif

Fetching the internet…

This is a simple tutorial to fetch web pages using php code. This starts with a example to fetch pages, and then sending get and post request :).

First, a few stuff from the php manual. This is just a summary. You can read the whole stuff at http://in.php.net/manual/en/book.curl.php

“”"PHP supports libcurl, a library created by Daniel Stenberg, that allows you to connect and communicate to many different types of servers with many different types of protocols. libcurl currently supports the http, https, ftp, gopher, telnet, dict, file, and ldap protocols. libcurl also supports HTTPS certificates, HTTP POST, HTTP PUT, FTP uploading (this can also be done with PHP’s ftp extension), HTTP form based upload, proxies, cookies, and user+password authentication.

These functions have been added in PHP 4.0.2.”"”

First, check whether you have curl installed with php. If not, instructions to install libcurl is given in the above link.
The following code checks whether curl is installed with php or not

<?php
//Check if the extension is loaded
if( !extension_loaded('curl') ){
echo "Oops... Curl extension is not loaded. :-(";
}
else {
echo "Wow... Curl extension is loaded. :-)";
}
?>

Check this code both under cli and under apache. Because sometimes, php doesn’t have curl loaded under cli, but has curl loaded when it runs under apache.

So, now that we have curl, we will proceed fetching a page. :-). How about fetching our Google page. ;-).

<?php
// create a new cURL resource
$ch = curl_init();
// set URL and other appropriate options
curl_setopt($ch, CURLOPT_URL, "http://www.google.co.in/"); //www.google.com gives a 301 moved response.
// grab URL and pass it to the browser
curl_exec($ch);
// close cURL resource, and free up system resources
curl_close($ch);
?>

The curl_setopt is THE function for all the different cases of fetching we might need to do. You better see the options which curl gives us at http://in.php.net/manual/en/function.curl-setopt.php.

Also we need to consider GET and POST methods of the form differently. Sending a GET request is quite easy. All you need to do is to change the URL so that it has the GET request parameters. For POST request, you need to add one more curl_setopt call to specify the POST data. Another important issue here is that, even though this will fetch the javascript code, this can’t run the javascript code. So it’ll be a little difficult to fetch pages loaded through Ajax. Again, remember, I’m not saying impossible. Just difficult. That’s all.

First, we’ll send a GET request to google server.

<?php
$ch = curl_init();
//First, we set the request to GET.
curl_setopt ($ch, CURLOPT_HTTPGET, true);
//Then we add the data to the reuqest URL
curl_setopt($ch, CURLOPT_URL, "http://www.google.co.in/search?q=sp2hari&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a");
//Change the browser agent so that it corresponds to Firefox from a Windows box. You better use a fetcher name instead of firefox here.
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 (CK) Firefox/3.0.1");
//You might want to set the referer, so that in case google checks it, you get proper results. Though google doesn't.
curl_setopt ($ch, CURLOPT_REFERER, "http://www.google.com");
//We don't the header in the output. We need only the HTML content
curl_setopt ($ch, CURLOPT_HEADER, false);
curl_exec($ch);
curl_close($ch);
?>

One more thing I want to mention here is that this can’t be used to fetch image, css or js files. This just gets the HTML content. Maybe you can send a request to the image or js or css file directly and then save the image locally.

Now how about sending a POST request. POST is a little complicated since we should what exactly we need to POST. This can be understood by seeing the form, but the best way is to use a Firefox plugin called “Tamper Data”.

In the example mentioned below, I’m posting the data to indianrailways site and fetching the list of trains from Bangalore to Trichy. ;-)

Simple steps to use Tamper Data to get the exact data to be sent to Indian Railways site
1. Install Tamper Data plugin to firefox
2. Browse to http://www.indianrail.gov.in/cgi_bin/inet_srcdestnm_cgi_date.cgi
3. Enter Source Station code as SBC
4. Enter the Destination Station code as TPJ
5. Enter the class as Sleeper Class
6. Enter the date as you want.
7. Don’t click the submit button for now.
8. Open Tamper Data plugin from Options -> Tamper Data
9. Click the Submit Button in the form
10. Analyze the first request.

From the Tamper Data, you see that the data to be posted as “CurrentMonth=4&CurrentDate=1&CurrentYear=2006&lccp_src_stncode=SBC&lccp_dstn_stncode=TPJ&lccp_classopt=SL&lccp_day=01&lccp_month=10″

Tamper Data
The following code fetches the data

<?php
$ch = curl_init();
//First, we set the request to POST.
curl_setopt ($ch, CURLOPT_POST, true);
//Set the url to the action file of the form
curl_setopt($ch, CURLOPT_URL, "http://www.indianrail.gov.in/cgi_bin/inet_srcdest_cgi_date.cgi");
//Set the post data from the value we got from Tamper Data
curl_setopt($ch, CURLOPT_POSTFIELDS, "CurrentMonth=4&CurrentDate=1&CurrentYear=2006&lccp_src_stncode=SBC&lccp_dstn_stncode=TPJ&lccp_classopt=SL&lccp_day=01&lccp_month=10");
//Change the browser agent so that it corresponds to Firefox from a Windows box. You better use a fetcher name instead of firefox here.
curl_setopt ($ch, CURLOPT_USERAGENT, "Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.1) Gecko/2008070208 (CK) Firefox/3.0.1");
//You might want to set the referer, so that in case indianrailways checks it, you get proper results.
curl_setopt ($ch, CURLOPT_REFERER, "http://www.indianrail.gov.in/src_dest_trns.html");
//We don't the header in the output. We need only the HTML content
curl_setopt ($ch, CURLOPT_HEADER, false);
curl_exec($ch);
curl_close($ch);
?>

This gives the HTML page of the result page. Parse it, tamper it and screw it as much as you want and get the list of trains. You can even fetch and use this HTML content to fetch Availability, Fare or Timings. One thing you should remember is that you are trying to do the job of a browser. So all you need to do is to send a proper request. That’s the only thing you should worry about. You need not bother whether the server’s code is in asp, php or jsp.

Happy Fetching :)