Chủ Nhật, 17 tháng 6, 2018

Security Testing - Cryptography

What is Cryptography?

Cryptography is the science to encrypt and decrypt data that enables the users to store sensitive information or transmit it across insecure networks so that it can be read only by the intended recipient.

Data which can be read and understood without any special measures is called plaintext, while the method of disguising plaintext in order to hide its substance is called encryption.

Encrypted plaintext is known as cipher text and process of reverting the encrypted data back to plain text is known as decryption.

The science of analyzing and breaking secure communication is known as cryptanalysis. The people who perform the same also known as attackers.

Cryptography can be either strong or weak and the strength is measured by the time and resources it would require to recover the actual plaintext.

Hence an appropriate decoding tool is required to decipher the strong encrypted messages.

There are some cryptographic techniques available with which even a billion computers doing a billion checks a second, it is not possible to decipher the text.

As the computing power is increasing day by day, one has to make the encryption algorithms very strong in order to protect data and critical information from the attackers.


How Encryption Works?


A cryptographic algorithm works in combination with a key (can be a word, number, or phrase) to encrypt the plaintext and the same plaintext encrypts to different cipher text with different keys.

Hence, the encrypted data is completely dependent couple of parameters such as the strength of the cryptographic algorithm and the secrecy of the key.


Cryptography Techniques


Symmetric Encryption − Conventional cryptography, also known as conventional encryption, is the technique in which only one key is used for both encryption and decryption. For example, DES, Triple DES algorithms, MARS by IBM, RC2, RC4, RC5, RC6.

Asymmetric Encryption − It is Public key cryptography that uses a pair of keys for encryption: a public key to encrypt data and a private key for decryption. Public key is published to the people while keeping the private key secret. For example, RSA, Digital Signature Algorithm (DSA), Elgamal.

Hashing − Hashing is ONE-WAY encryption, which creates a scrambled output that cannot be reversed or at least cannot be reversed easily. For example, MD5 algorithm. It is used to create Digital Certificates, Digital signatures, Storage of passwords, Verification of communications, etc.

Security Testing - Encoding and Decoding

What is Encoding and Decoding?

Encoding is the process of putting a sequence of characters such as letters, numbers and other special characters into a specialized format for efficient transmission.

Decoding is the process of converting an encoded format back into the original sequence of characters. It is completely different from Encryption which we usually misinterpret.

Encoding and decoding are used in data communications and storage. Encoding should NOT be used for transporting sensitive information.

URL Encoding

URLs can only be sent over the Internet using the ASCII character-set and there are instances when URL contains special characters apart from ASCII characters, it needs to be encoded. URLs do not contain spaces and are replaced with a plus (+) sign or with %20.

ASCII Encoding


The Browser (client side) will encode the input according to the character-set used in the web-page and the default character-set in HTML5 is UTF-8.

Following table shows ASCII symbol of the character and its equal Symbol and finally its replacement which can be used in URL before passing it to the server

Security Testing - HTTPS Protocol Basics

HTTPS (Hypertext Transfer Protocol over Secure Socket Layer) or HTTP over SSL is a web protocol developed by Netscape. It is not a protocol but it is just the result of layering the HTTP on top of SSL/TLS (Secure Socket Layer/Transport Layer Security).

In short, HTTPS = HTTP + SSL


When is HTTPS Required?

When we browse, we normally send and receive information using HTTP protocol. So this leads anyone to eavesdrop on the conversation between our computer and the web server. Many a times we need to exchange sensitive information which needs to be secured and to prevent unauthorized access.

Https protocol used in the following scenarios −
- Banking Websites
- Payment Gateway
- Shopping Websites
- All Login Pages
- Email Apps
- Basic Working of HTTPS

Public key and signed certificates are required for the server in HTTPS Protocol.

Client requests for the https:// page

When using an https connection, the server responds to the initial connection by offering a list of encryption methods the webserver supports.

In response, the client selects a connection method, and the client and server exchange certificates to authenticate their identities.

After this is done, both webserver and client exchange the encrypted information after ensuring that both are using the same key, and the connection is closed.

For hosting https connections, a server must have a public key certificate, which embeds key information with a verification of the key owner's identity.

Almost all certificates are verified by a third party so that clients are assured that the key is always secure.


Security Testing - HTTP Protocol Basics

Understanding the protocol is very important to get a good grasp on security testing. You will be able to appreciate the importance of the protocol when we intercept the packet data between the webserver and the client.

HTTP Protocol

The Hypertext Transfer Protocol (HTTP) is an application-level protocol for distributed, collaborative, hypermedia information systems. This is the foundation for data communication for the World Wide Web since 1990. HTTP is a generic and stateless protocol which can be used for other purposes as well using extension of its request methods, error codes, and headers.

Basically, HTTP is a TCP/IP based communication protocol, which is used to deliver data such as HTML files, image files, query results etc. over the web. It provides a standardized way for computers to communicate with each other. HTTP specification specifies how clients’ requested data are sent to the server, and how servers respond to these requests.


Basic Features

There are following three basic features which make HTTP a simple yet powerful protocol −

HTTP is connectionless − The HTTP client, i.e., the browser initiates an HTTP request. After making a request, the client disconnects from the server and waits for a response. The server processes the request and re-establishes the connection with the client to send the response back.

HTTP is media independent − Any type of data can be sent by HTTP as long as both the client and server know how to handle the data content. This is required for client as well as server to specify the content type using appropriate MIME-type.

HTTP is stateless − HTTP is a connectionless and this is a direct result that HTTP is a stateless protocol. The server and client are aware of each other only during a current request. Afterwards, both of them forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain information between different requests across the web pages.

HTTP/1.0 uses a new connection for each request/response exchange whereas HTTP/1.1 connection may be used for one or more request/response exchanges.
Architecture

The following diagram shows a very basic architecture of a web application and depicts where HTTP resides −



The HTTP protocol is a request/response protocol based on the client/server architecture where web browser, robots, and search engines etc. act as HTTP clients and the web server acts as a server.

Client − The HTTP client sends a request to the server in the form of a request method, URI, and protocol version, followed by a MIME-like message containing request modifiers, client information, and possible body content over a TCP/IP connection.

Server − The HTTP server responds with a status line, including the protocol version of the message and a success or error code, followed by a MIME-like message containing server information, entity meta information, and possible entity-body content.

HTTP – Disadvantages

- HTTP is not a completely secured protocol.
- HTTP uses port 80 as default port for communication.
- HTTP operates at the application Layer. It needs to create multiple connections for data transfer, which increases administration overheads.
- No encryption/digital certificates are required for using HTTP.

[Guide fo C] Types of Function calls in C

Functions are called by their names, we all know that, then what is this tutorial for? Well if the function does not have any arguments, then to call a function you can directly use its name. But for functions with arguments, we can call a function in two different ways, based on how we specify the arguments, and these two ways are:
- Call by Value
- Call by Reference
- Call by Value

Calling a function by value means, we pass the values of the arguments which are stored or copied into the formal parameters of the function. Hence, the original values are unchanged only the parameters inside the function changes.


#include<stdio.h>

void calc(int x);

int main()
{
    int x = 10;
    calc(x);
    // this will print the value of 'x'
    printf("\nvalue of x in main is %d", x);
    return 0;
}

void calc(int x)
{
    // changing the value of 'x'
    x = x + 10 ;
    printf("value of x in calc function is %d ", x);
}
value of x in calc function is 20 
value of x in main is 10

In this case, the actual variable x is not changed. This is because we are passing the argument by value, hence a copy of x is passed to the function, which is updated during function execution, and that copied value in the function is destroyed when the function ends(goes out of scope). So the variable x inside the main() function is never changed and hence, still holds a value of 10.

But we can change this program to let the function modify the original x variable, by making the function calc() return a value, and storing that value in x.

#include<stdio.h>

int calc(int x);

int main()
{
    int x = 10;
    x = calc(x);
    printf("value of x is %d", x);
    return 0;
}

int calc(int x)
{
    x = x + 10 ;
    return x;
}
value of x is 20

Call by Reference

In call by reference we pass the address(reference) of a variable as argument to any function. When we pass the address of any variable as argument, then the function will have access to our variable, as it now knows where it is stored and hence can easily update its value.

In this case the formal parameter can be taken as a reference or a pointer(don't worry about pointers, we will soon learn about them), in both the cases they will change the values of the original variable.

#include<stdio.h>

void calc(int *p);      // functin taking pointer as argument

int main()
{
    int x = 10;
    calc(&x);       // passing address of 'x' as argument
    printf("value of x is %d", x);
    return(0);
}

void calc(int *p)       //receiving the address in a reference pointer variable
{
    /*
        changing the value directly that is 
        stored at the address passed
    */
    *p = *p + 10; 
}
value of x is 20

NOTE
: If you do not have any prior knowledge of pointers, do study Pointers first. Or just go over this topic and come back again to revise this, once you have learned about pointers.

[Guide for C] Error Handling in C

C language does not provide any direct support for error handling. However a few methods and variables defined in error.h header file can be used to point out error using the return statement in a function. In C language, a function returns -1 or NULL value in case of any error and a global variable errno is set with the error code. So the return value can be used to check error while programming.

What is errno?

Whenever a function call is made in C language, a variable named errno is associated with it. It is a global variable, which can be used to identify which type of error was encountered while function execution, based on its value. Below we have the list of Error numbers and what does they mean.

errno valueError
1Operation not permitted
2No such file or directory
3No such process
4Interrupted system call
5I/O error
6No such device or address
7Argument list too long
8Exec format error
9Bad file number
10No child processes
11Try again
12Out of memory
13Permission denied

C language uses the following functions to represent error messages associated with errno:
perror(): returns the string passed to it along with the textual represention of the current errno value.
strerror() is defined in string.h library. This method returns a pointer to the string representation of the current errno value.

Time for an Example

#include <stdio.h>       
#include <errno.h>       
#include <string.h> 
 
int main ()
{
    FILE *fp;
 
    /* 
        If a file, which does not exists, is opened,
        we will get an error
    */ 
    fp = fopen("IWillReturnError.txt", "r");
 
    printf("Value of errno: %d\n ", errno);
    printf("The error message is : %s\n", strerror(errno));
    perror("Message from perror");
 
    return 0;
}
Value of errno: 2 
The error message is: No such file or directory 
Message from perror: No such file or directory
Other ways of Error Handling

We can also use Exit Status constants in the exit() function to inform the calling function about the error. The two constant values available for use are EXIT_SUCCESS and EXIT_FAILURE. These are nothing but macros defined stdlib.h header file.

#include <stdio.h>       
#include <errno.h>       
#include <stdlib.h>       
#include <string.h>       
 
extern int errno;
 
void main()
{
    char *ptr = malloc( 1000000000UL);  //requesting to allocate 1gb memory space
    if (ptr == NULL)    //if memory not available, it will return null 
    {  
        puts("malloc failed");
        puts(strerror(errno));
        exit(EXIT_FAILURE);     //exit status failure
    }
    else
    {
        free( ptr);
        exit(EXIT_SUCCESS);     //exit status Success      
    }
}

Here exit function is used to indicate exit status. Its always a good practice to exit a program with a exit status. EXIT_SUCCESS and EXIT_FAILURE are two macro used to show exit status. In case of program coming out after a successful operation EXIT_SUCCESS is used to show successful exit. It is defined as 0. EXIT_Failure is used in case of any failure in the program. It is defined as -1.
Division by Zero

There are some situation where nothing can be done to handle the error. In C language one such situation is division by zero. All you can do is avoid doing this, becasue if you do so, C language is not able to understand what happened, and gives a runtime error.

Best way to avoid this is, to check the value of the divisor before using it in the division operations. You can use if condition, and if it is found to be zero, just display a message and return from the function.

[Guide for C] Type of User-defined Functions in C

There can be 4 different types of user-defined functions, they are:
- Function with no arguments and no return value
- Function with no arguments and a return value
- Function with arguments and no return value
- Function with arguments and a return value

Below, we will discuss about all these types, along with program examples.
Function with no arguments and no return value

Such functions can either be used to display information or they are completely dependent on user inputs.

Below is an example of a function, which takes 2 numbers as input from user, and display which is the greater number.

#include<stdio.h>

void greatNum();       // function declaration

int main()
{
    greatNum();        // function call
    return 0;
}

void greatNum()        // function definition
{
    int i, j;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    if(i > j) {
        printf("The greater number is: %d", i);
    }
    else {
        printf("The greater number is: %d", j);
    }
}

Function with no arguments and a return value

We have modified the above example to make the function greatNum() return the number which is greater amongst the 2 input numbers.

#include<stdio.h>

int greatNum();       // function declaration

int main()
{
    int result;
    result = greatNum();        // function call
    printf("The greater number is: %d", result);
    return 0;
}

int greatNum()        // function definition
{
    int i, j, greaterNum;
    printf("Enter 2 numbers that you want to compare...");
    scanf("%d%d", &i, &j);
    if(i > j) {
        greaterNum = i;
    }
    else {
        greaterNum = j;
    }
    // returning the result
    return greaterNum;
}

[Guide for C] Introduction to Structure

Structure is a user-defined datatype in C language which allows us to combine data of different types together. Structure helps to construct a complex data type which is more meaningful. It is somewhat similar to an Array, but an array holds data of similar type only. But structure on the other hand, can store data of any type, which is practical more useful.

For example: If I have to write a program to store Student information, which will have Student's name, age, branch, permanent address, father's name etc, which included string values, integer values etc, how can I use arrays for this problem, I will require something which can hold data of different types together.

In structure, data is stored in form of records.
Defining a structure

struct keyword is used to define a structure. struct defines a new data type which is a collection of primary and derived datatypes.

Syntax:
struct [structure_tag]
{
    //member variable 1
    //member variable 2
    //member variable 3
    ...
}[structure_variables];

As you can see in the syntax above, we start with the struct keyword, then it's optional to provide your structure a name, we suggest you to give it a name, then inside the curly braces, we have to mention all the member variables, which are nothing but normal C language variables of different types like int, float, array etc.

After the closing curly brace, we can specify one or more structure variables, again this is optional.

Note: The closing curly brace in the structure type declaration must be followed by a semicolon(;).
Example of Structure
struct Student
{
    char name[25];
    int age;
    char branch[10];
    // F for female and M for male
    char gender;
};
Here struct Student declares a structure to hold the details of a student which consists of 4 data fields, namely name, age, branch and gender. These fields are called structure elements or members.

Each member can have different datatype, like in this case, name is an array of char type and age is of int type etc. Student is the name of the structure and is called as the structure tag.
Declaring Structure Variables

It is possible to declare variables of a structure, either along with structure definition or after the structure is defined. Structure variable declaration is similar to the declaration of any normal variable of any other datatype. Structure variables can be declared in following two ways:1) Declaring Structure variables separately

struct Student
{
    char name[25];
    int age;
    char branch[10];
    //F for female and M for male
    char gender;
};

struct Student S1, S2;      //declaring variables of struct Student

2) Declaring Structure variables with structure definition

struct Student
{
    char name[25];
    int age;
    char branch[10];
    //F for female and M for male
    char gender;
}S1, S2;
Here S1 and S2 are variables of structure Student. However this approach is not much recommended.
Accessing Structure Members

Structure members can be accessed and assigned values in a number of ways. Structure members have no meaning individually without the structure. In order to assign a value to any structure member, the member name must be linked with the structure variable using a dot . operator also called period or member access operator.

For example:
#include<stdio.h>
#include<string.h>

struct Student
{
    char name[25];
    int age;
    char branch[10];
    //F for female and M for male
    char gender;
};

int main()
{
    struct Student s1;
    
    /*
        s1 is a variable of Student type and 
        age is a member of Student
    */
    s1.age = 18;
    /*
        using string function to add name
    */
    strcpy(s1.name, "Viraaj");
    /*
        displaying the stored values
    */
    printf("Name of Student 1: %s\n", s1.name);
    printf("Age of Student 1: %d\n", s1.age);
    
    return 0;
}

Name of Student 1: Viraaj Age of Student 1: 18

We can also use scanf() to give values to structure members through terminal.
scanf(" %s ", s1.name);
scanf(" %d ", &s1.age);

Structure Initialization

Like a variable of any other datatype, structure variable can also be initialized at compile time.

struct Patient
{
    float height;
    int weight;  
    int age; 
};

struct Patient p1 = { 180.75 , 73, 23 };    //initialization
or,
struct Patient p1;
p1.height = 180.75;     //initialization of each member separately
p1.weight = 73;
p1.age = 23;

Array of Structure

We can also declare an array of structure variables. in which each element of the array will represent a structure variable. Example : struct employee emp[5];

The below program defines an array emp of size 5. Each element of the array emp is of type Employee.

#include<stdio.h>

struct Employee
{
    char ename[10];
    int sal;
};

struct Employee emp[5];
int i, j;
void ask()
{
    for(i = 0; i < 3; i++)
    {
        printf("\nEnter %dst Employee record:\n", i+1);
        printf("\nEmployee name:\t");
        scanf("%s", emp[i].ename);
        printf("\nEnter Salary:\t");
        scanf("%d", &emp[i].sal);
    }
    printf("\nDisplaying Employee record:\n");
    for(i = 0; i < 3; i++)
    {
        printf("\nEmployee name is %s", emp[i].ename);
        printf("\nSlary is %d", emp[i].sal);
    }
}
void main()
{
    ask();
}

Nested Structures

Nesting of structures, is also permitted in C language. Nested structures means, that one structure has another stucture as member variable.

Example:
struct Student
{
    char[30] name;
    int age;
    /* here Address is a structure */
    struct Address
    {
        char[50] locality;
        char[50] city;
        int pincode;  
    }addr;
};

Structure as Function Arguments

We can pass a structure as a function argument just like we pass any other variable or an array as a function argument.

Example:
#include<stdio.h>

struct Student
{
    char name[10];
    int roll;
};

void show(struct Student st);

void main()
{
    struct Student std;
    printf("\nEnter Student record:\n");
    printf("\nStudent name:\t");
    scanf("%s", std.name);
    printf("\nEnter Student rollno.:\t");
    scanf("%d", &std.roll);
    show(std);
}

void show(struct Student st)
{
    printf("\nstudent name is %s", st.name);
    printf("\nroll is %d", st.roll);
}

[Guide for C] C Input and Output

C Input and Output

Input means to provide the program with some data to be used in the program and Output means to display data on screen or write the data to a printer or a file.

C programming language provides many built-in functions to read any given input and to display data on screen when there is a need to output the result.

In this tutorial, we will learn about such functions, which can be used in our program to take input from user and to output the result on screen.

All these built-in functions are present in C header files, we will also specify the name of header files in which a particular function is defined while discussing about it.
scanf() and printf() functions

The standard input-output header file, named stdio.h contains the definition of the functions printf() and scanf(), which are used to display output on screen and to take input from user respectively.

#include<stdio.h>

void main()
{
    // defining a variable
    int i;
    /* 
        displaying message on the screen
        asking the user to input a value
    */
    printf("Please enter a value...");
    /*
        reading the value entered by the user
    */
    scanf("%d", &i);
    /*
        displaying the number as output
    */
    printf( "\nYou entered: %d", i);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered on screen.

You must be wondering what is the purpose of %d inside the scanf() or printf() functions. It is known as format string and this informs the scanf() function, what type of input to expect and in printf() it is used to give a heads up to the compiler, what type of output to expect.

Format StringMeaning
%dScan or print an integer as signed decimal number
%fScan or print a floating point number
%cTo scan or print a character
%sTo scan or print a character string. The scanning ends at whitespace.
We can also limit the number of digits or characters that can be input or output, by adding a number with the format string specifier, like "%1d" or "%3s", the first one means a single numeric digit and the second one means 3 characters, hence if you try to input 42, while scanf() has "%1d", it will take only 4 as input. Same is the case for output.

In C Language, computer monitor, printer etc output devices are treated as files and the same process is followed to write output to these devices as would have been followed to write the output to a file.

NOTE : printf() function returns the number of characters printed by it, and scanf() returns the number of characters read by it.

int i = printf("studytonight");

In this program printf("studytonight"); will return 12 as result, which will be stored in the variable i, because studytonight has 12 characters.

getchar() & putchar() functions

The getchar() function reads a character from the terminal and returns it as an integer. This function reads only single character at a time. You can use this method in a loop in case you want to read more than one character. The putchar() function displays the character passed to it on the screen and returns the same character. This function too displays only a single character at a time. In case you want to display more than one characters, use putchar() method in a loop.

#include <stdio.h>

void main( )
{
    int c;
    printf("Enter a character");
    /*
        Take a character as input and 
        store it in variable c
    */
    c = getchar();
    /*
        display the character stored 
        in variable c 
    */
    putchar(c);
}

When you will compile the above code, it will ask you to enter a value. When you will enter the value, it will display the value you have entered.

gets() & puts() functions

The gets() function reads a line from stdin(standard input) into the buffer pointed to by str pointer, until either a terminating newline or EOF (end of file) occurs. The puts() function writes the string str and a trailing newline to stdout.

str → This is the pointer to an array of chars where the C string is stored. (Ignore if you are not able to understand this now.)
#include<stdio.h>

void main()
{
    /* character array of length 100 */
    char str[100];
    printf("Enter a string");
    gets( str );
    puts( str );
    getch();
}

When you will compile the above code, it will ask you to enter a string. When you will enter the string, it will display the value you have entered.

Difference between scanf() and gets()

The main difference between these two functions is that scanf() stops reading characters when it encounters a space, but gets() reads space as character too.

If you enter name as Study Tonight using scanf() it will only read and store Study and will leave the part after space. But gets() function will read it completely.