April 14, 2009

C tutorial [Chapter 1]

Introduction

The purpose of this tutorial is to learn how to use C with some of its best features like pointers, process and thread creation, semaphores and signal handling. Of course to learn how to do all this we need to start from the beginning.
This is not a basic programming tutorial. If you don't know how the art of programming works this is not a tutorial for you. C is a very complex language if you are a beginner. Try Python or even Java if you want to start with something easy then you will be prepared to learn this awesome language.
I love Linux. Linux loves C. I don't know if any of the techniques exposed here work in a Windows machine... I really don't care if they work... Linux is a very efficient OS. I won't explain why, but in the references below, you will find the book that explains why any Unix based system is better than any flavor of Windows.

In the beginning there was darkness

Lets learn some syntax first:

Variable types


int: Integer
char: Character
float: Float
char* or char[]: Strings


Among others...

Assignment


int intName = 10;
char charName = 48; // "0"
char* str1Name = "Hello World";



IF-ELSE IF-ELSE statements


if(condition1){
Instructions
}else if(condition2){
Instructions
...
}else if(conditionN){
Instructions
}else{
Instructions
}


Switch statements


Faster than If statements


switch(condition){
case 1:
Instructions
break;
...
case N:
Instructions
break;
default:
Instructions
}


Loops

While loop

while(condition){
Instructions
}


For Loop

int i;
for(i=0; condition; i++){
Instructions
}


Do-While Loop

do{
Instructions
}while(condition);



Useful functions

Search in the man pages of your Linux distribution how to use them. In Debian you have to install them from the repositories.

apt-get install manpages-dev



The functions you should man for now are:
printf
scanf
strlen
strcpy
strcat
malloc
free

Pointers
The beautiful pointers... Thanks to them we have Orient Object Programming.
Let's say this is our memory (All numbers in Hex with a Little-Endian 32 bits hardware):

Endianness Explanation




Also lets say our program is:

int a = 10; //Address 0x00
int* b = &a; //Address 0x04
char* c = "HELLO"; //Address 0x08


b is a pointer. If I print b I will get 0x00000000
which is the address of a. If I print *b I will print
the value of the thing b is pointing, in this case a.
So printing *b will result in 0x0000000A or 10
If I print &a I will get the address of a which is 0x00000000

Now if I print c[2] I will get 4C which is L in the ascii table.
If I print all the string, it will print till it gets to the null byte
In this case the null byte is in the sixth byte of the string.


Now you know how to get the information of a pointer :)
To reserve memory use the function malloc like this:


char* str;
int* i;
/*
* To reserve 10 bytes for str. The (char *)
* is for the program to know what kind of
* pointer will be.
*/
str = (char *)malloc(10);
/*
* To reserve enough space for a int I use the
* sizeof function.
*/
i = (int *)malloc(sizeof(int));


Precompiler Instructions

This are special instructions. All the calculations are made by the compiler, but make us the life easier.
Include precompiler instruction
It's to import the libraries you want to use in your program.
For system libraries:

#include //This will include the stdio.h file.


For user defined libraries:

#include "list.h"//This will include the lis.h file.


Define precompiler instruction
To define a constant:

#define TRUE 1//This will define the word TRUE as 1



The .h files are the headers files. There you'll have the firm of every function in the .c with the same name.

sum.h


#include

void printSum(int, int);


sum.c


#include "sum.h"

int sum( int a, int b ){
return ( a + b );
}

void printSum(int a, int b ){
printf("The result is %d", sum( a , b ));//Prints result on screen
}


As you can see, the the sum.h only have the printSum function. This is because printSum is a public function while sum is just a private function. If someone use this useless library will not be able to use sum, but will be able to use printSum. So to define a class you should to use a header file. But how do you define a new data type? With Structures :)

Structures
Let's say we want to define the data type Person (Name, Age, Gender)

person.h


#include
#include
#include

struct PERSON{
char* pName;
int pAge;
int pGender;//0 for man, 1 for woman
}

typedef struct PERSON Person;

Person* newPerson(char*, int, int);


person.c


#include "person.h"

//Constructor of Person. Returns NULL on error
Person* newPerson(char* name, int age, int gender){
/*
* To reserve some memory use malloc with the size you need
* In this case I need the space enough to hold a Person type
* so I use sizeof(Person);
*/
Person* nPerson = (Person *) malloc(sizeof(Person));
//To access the members of this class we should use the "->" operator.
if(gender != 0 && gender != 1){
free(nPerson);//To free the space used by nPerson
return NULL;
}
//To access the pGender, member of Person
nPerson->pGender = gender;
if(age<0){
free(nPerson);//To free the space used by nPerson
return NULL;
}
//To access the pAge, member of Person
nPerson->pAge = age;
/*
* With the function malloc I reserve as many bytes the char* name has and then
* and I assign the new address to the pName, member of Person. If the malloc
* return NULL the system call to ask some more memory failed, and the creation
* of the new type also should failed. It's efficient to free the space used for
* any reference data type if it won't be used anymore. That's why I use free(void*)
* everytime a inconsistent data or a failed system call appears.
*/
if((nPerson->pName = (char *) malloc(strlen(name)))==NULL){
free(nPerson);//To free the space used by nPerson
return NULL;
}
/*
* This function copies name to pName
* This nPerson->pName = name would only copie the
* address of name to nPerson->pName
*/
strcpy(nPerson->pName,name);
return nPerson;
}


You can also use "." intead of "->", but you need to change some things... I think is easier to work this way...

Explanation of the code:

Here I declare the members of the "class". In this case you have pName, pAge, pGender.


struct PERSON{
char* pName;
int pAge;
int pGender;
}


Here I rename the "class" from "struct PERSON" to "Person". It's just to write less code :)


typedef struct PERSON Person;

Then I declare the "constructor" of the "class"

Person* newPerson(char*, int, int);


End Chapter 1
Chapter 2: fork() system call, signals, semaphores (ERROR 501: NOT IMPLEMENTED)
Chapter 3: File Descriptors, Pipes (ERROR 501: NOT IMPLEMENTED)
Chapter 4: Thread creation (ERROR 501: NOT IMPLEMENTED)
Chapter 5: Security risks (ERROR 501: NOT IMPLEMENTED)
Chapter 6: Networking (ERROR 501: NOT IMPLEMENTED)

Thanks for reading :)

References


This book is awesome. Everybody should read it :)
Operating Systems: Internals and Design Principles by William Stallings

The best search engine:
Google

The best reference for C language:
Debian man pages for development.

Endianness

Avoiding Public Ridicule (Securely Erasing your Hard-Disk)

Let's say you bought a brand new hard-disk and you want to sell your old hard-disk to John Doe, a really good friend. Also let's say you have in your old hard-disk tons compromising photos, enough to fill the Internet with twice, of yourself wearing a pink thong while you are posing for the camera. You decide to erase your disk to prevent the public ridicule. After a few seconds you have erased your entire disk and it's ready to be sold.
After a week, you enter in Google, but instead of the Google logo is one of those compromising photos, the worst of all of them. Suddenly, your cellphone starts to ring and you noticed your e-mail box is full... and almost all the subjects of all those e-mails start with "Hahaha". You answer your phone and you hear the voice of your good friend John Doe: "Hahaha, you sick bastard!! Next time really erase your data, you idiot!!".

And all this could be avoided... How? Well, with a simple and nice tool called wipe.

Lets say your old hard-disk is an IDE hard-disk and also is your primary disk with three partitions.


hda1 / Ext3
hda2 /home Ext3
hda3 swap


Let's say you have a Linux LiveCD. You boot from it and install wipe (if it's not installed yet). Then erase every partition with it:

Syntax:

wipe /dev/

For more information:
man wipe


In our case:

wipe /dev/hda1
wipe /dev/hda2
wipe /dev/hda3


Wipe's developers suggest only wiping one partition at a time
Then if you want you can erase every partition.

Now it's pretty hard to recover the information of the disk and you are a bit safer.

The moral of this little story: Never take compromising photos of yourself again

Annexe
If you want a LiveCD for free and without effort:
Ubuntu LiveCD/
Also you can donwload the iso image and burn it on a CD.

Don't be afraid of needles (JS Injection)

Prologue and Disclaimer

If you don't know HTML, go and learn it before you read this.
If you don't know javascript, I recommend you learn to read it at least.
This text is for educational purpose, I am not responsible of what you do with this information. I just hope you stay in the Light Side of the Force.

A Beautiful World

When I was young and reckless (two years ago) and I was starting in the world of hacking I was amazed by a thing called javascript injections. I would never thought I could inject code into a page without any sophisticated tool, just my knowledge of javascript and my favorite browser firefox.

Know your World


In your URL bar write:

javascript:alert("Hello World")

and then hit enter.You should see a nice little pop up that says Hello World.
I will explain the code:
1. javascript: - Introduces javascript code.
2. alert() - This function makes that little pop up you saw before. The argument of the function is the message in the pop up.

This function is very useful to see the information hidden from you, like cookies:

javascript:alert(document.cookie)


1. document - represents the current page.
2. document.cookie - represents the cookies for that page.
This code would show your current cookies.

Let's say we have this form:

1. <form action="/Neo.php" method="post">
2. <select name="message">
3. <option value="Take the blue pill">Take the blue pill</option>
4. </select>
5. <br>
7. <input type="submit" value="Send Message to Neo!">
8. </form>

In this case we do not want Neo to take the blue pill because we need him as the Chosen One. We need him to save us. So we have to send him a message that says "Take the red pill". There are several ways to do this(Two of them metioned below). I will explain the JS way.
In your URL bar write this:

javascript:alert(document.forms[0])


1. document.forms[x] - represents a form in the current page being x the number of the form. If we have three forms, first one would be document.forms[0] and the last one document.forms[2].

Now write:

javascript:alert(document.forms[0].elements[0])


1. document.forms[0].elements[0] - represents an element in the form. In our form we have two elements: select tag (document.forms[0].elements[0]) and input tag (document.forms[0].elements[1]).

And now:

javascript:alert(document.forms[0].elements[0].options[0])


1. document.forms[0].elements[0].options[0] - represents an option in the select tag.

In our form we have just one option and to see its value we do:

javascript:alert(document.forms[0].elements[0].options[0].value)


This code will alert "Take the blue pill".
So we finally have access to the thing we want to change.

Change your World


You can skip this only if you fully understand it.

Differences between = and == in common
programming languages

I will explain this with a little example:


1. var yoda = 1000;
2. yoda = 200;
3. if(yoda == 200){
4. alert("yoda rocks!");
5. }else{
6. alert("Chimichanga!");
7. }

In the first line = is used to asign 1000 to the variable yoda. With that I mean yoda's value is 1000. The same thing happens in the second line where 200 is asigned to yoda. Now the expresion (yoda == 200) works in this case like an equal sign. So if yoda equals 200 then that condition in the if statement is true and will alert that yoda rocks, else will alert Chimichanga. This code will always alert that yoda rocks because that's the last value asigned to the variable yoda.


To change the value of a variable we use the void() function. Example:

1. <html>
2. <head>
3. <script type="text/javascript">
4. c = 1000000;
5. function counter(){
6. document.getElementById('counter').innerHTML="Seconds left: "+c;
7. if(c==0){
8. window.location="http://google.com";
9. }else{
10. c=c-1;
11. var time = setTimeout('counter()',1000);
12. }
13. }
14. </script>
15. </head>
16. <body onload="counter()">
17. <div id="counter"></div>
18. </body>
19. <html>


If we want to visit google a bit faster we could do:

javascript:void(c=0)



You can skip this if you fully understanded the code above.

function counter() explained

This function is a backwards counter that goes from 1000000s to 0s (about 11 days), so this means you can only access to google after 11 days you load the page. We see in the line 4 a global variable (variable c). That global variable is the responsible for the long wait to finally go to google. Our advantage here is the fact that the variable is global, so we can change it with a injection using the function void(). If we change the value of variable c to 0, we inmediately will be redirected to google.com. So that's why we use the injection javascript:void(c=0).

If you don't understand the code and you want to fully understand it (it would be advisable) go to this page http://www.w3schools.com and learn some javascript.


In our form we need to change the message and it is almost the same code above:

javascript:void(document.forms[0].elements[0].options[0].value="Take the red pill")


It seems we did not do much, but our form is now injected. If you hit "Send Message to Neo!", the form will send now the right message to our savior. :)
And that Code Highlighting :: Select Code
is the way to make the world a better place with JS Injections. :)

Summary
- alert(something)
something == String or something == variable
- void(something = something_else)
something == variable and something_else == new value for something
- Enjoy :D

If you want to know more about injections I recommend to learn javascript. This injections will make your life a bit easier.

Annex

You can make the same modifications to a form with firebug(Firefox extension) or copying the source code of the page in a text editor(notepad, gedit, vim, emacs, etc.), modify the code, save it in your computer(as html file if you are in Windows) and then submit the form(Remember to change the form's action from action="/Neo.php" to action="http://ChosenOne.org/Neo.php")

Well, that's all folks! May the force be with you and accept Jesus Christ as your Savior!