Showing posts with label networking. Show all posts
Showing posts with label networking. Show all posts

Wednesday, 23 September 2015

client server program in c !

In previous tutorial "Introduction to Network Programming using TCP/IP ! " : http://programmingethicalhackerway.blogspot.in/2015/07/introduction-to-network-programming.html, We had learned about socket functions. In this tutorial, we will look at how these functions are used by server-client application. Before we proceeding, let's first we understand what exactly is the server-client ? If i say in simple words, a server is one who serve services and client is one who receive services from server. Consider a case, you are writing a program which hack the victim's computer. The idea of the program may be you are a server and your victim is client. You wrote a malicious client program which spawn shell and send it to the attacker's IP address. Now you send this client program to your victim and whenever your victim run this program, game will over. So, Your victim send shell (cmd.exe or bin/bash) to you and you receive the shell  on your server.

I hope now you get some basic idea of client-server concept. Let us first write server code , then client code. Don't get panic after looking code. I will describe each and every line in detail later.

server.c
  1. #include <sys/types.h>
  2. #include <sys/socket.h>
  3. #include <netinet/in.h>
  4. #include <stdio.h>
  5. #include <unistd.h>
  6. #include <stdlib.h>
  7. #include <arpa/inet.h>
  8. #define port 8080
  9. int main()
  10. {
  11.      int fd, newfd, serlength, clienlength, num;
  12.      int yes =1;
  13.     
  14.      struct sockaddr_in server;            
  15.      struct sockaddr_in clienlen;       
  16.  
  17.      char buffer[1024];
  18.      char *msg = "Recived your message. Good Bye\n";
  19.     
  20.     
  21.      fd=socket(AF_INET, SOCK_STREAM, 0);    
  22.      if (fd < 0)
  23.         perror("Error in Opening socket");
  24.      if (setsockopt(fd,SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int)) == -1)       
  25.         perror("Error in reusing address\n");
  26.      server.sin_family=AF_INET;                   
  27.      server.sin_addr.s_addr=INADDR_ANY;           
  28.      server.sin_port=htons(port);                 
  29.      serlength=sizeof(server);
  30.      if (bind(fd, (struct sockaddr *)&server, serlength) < 0)
  31.           perror("Error in binding socket");
  32.      clienlength=sizeof(clienlen);                       
  33.      if (listen(fd,10) < 0)                                
  34.           perror("Error in listening");
  35.      while (1) {
  36.          newfd =accept(fd, (struct sockaddr *)&clienlen, &clienlength);      
  37.          if (newfd < 0)
  38.             perror("Error in Accepting");
  39.         printf("A connection has been accepted from %s\n", inet_ntoa((struct in_addr)clienlen.sin_addr));
  40.          num = recv(newfd,buffer,1023,0);                   
  41.          printf("Recieve %d bytes from client\n",num);
  42.          if (num == -1) {
  43.             perror("Error in Reading");
  44.          }
  45.          else {
  46.            buffer[num]='\0';
  47.            printf("Message from client : %s\n",buffer);   
  48.            serlength = strlen(msg);
  49.            num = send(newfd,msg,serlength,0);               
  50.            if (num < serlength)
  51.                 perror("Error in writing");
  52.            if (close(newfd) == -1)
  53.                 perror("Error in closing");
  54.                 
  55.      }
  56.      }
  57.     
  58. }

Now i will explain step by step.
The header file #include <sys/types.h> contains definitions of a number of data types used in system calls.
The header file #include <netinet/in.h> contains constants and structures needed for internet domain addresses.
The header file #include <sys/socket.h> includes a number of definitions of structures needed for sockets.
The Two variables fd and newfd are file descriptors and store the values returned by the socket system call and the accept system call. clienlen stores the size of the address of the client. num is the return value for the read() and write() calls.

A sockaddr_in is a structure containing an internet address.We have already discussed about this  structure in our previous tutorial.

The socket() system call creates a new socket. It takes three arguments as we already discussed previously. If the socket call fails, it returns -1.

The setsockopt() function allow us to reuse a given address for binding. Without this option set, when the program tries to bind to a given port, it will fail if that port is already in use.

The variable server is a structure of type struct sockaddr_in. This structure has four fields and set accordingly our requirement.

Now The bind() call passes the socket file descriptor, the address structure,  and the length of the address structure.

The listen() call tells the socket to listen for incoming connections. It takes two arguments. The first argument is the socket file descriptor, and the second is the the number of connections that can be waiting.

The accept() call actually accepts an incoming connection.The accept() system call causes the process to block until a client connects to the server.It takes three arguments. The accept() function returns a new socket file descriptor for the accepted connection. This way, the original socket file descriptor can continue to be used for accepting new connections, while the new socket file descriptor
is used for communicating with the connected client.

Once a connection has been established, everything written by the client will be read by the server, and everything written by the server will be read by the client. So when our connection has been established, we will receive a message from our client and then our server send a message "Received your message. Good Bye!" to the client.


                                                  
    

if  this code is still not clear to you, then i would recommend you:
1 . C  programming for hackers.
2. Introduction to Network Programming using TCP/IP !
In the next post, we will discuss about client program.

If you like this post or have any question, please feel free to comment!

Tuesday, 21 July 2015

Introduction to Network Programming using TCP/IP !

The client server programming is the most common type(other is P2P network) of network applications. A server is a program(like Google,Yahoo) that provides services to client(like You). A client is a program that access these services by connecting to a server program.
A socket is the mechanism that most popular operating systems provide to give programs access to the network. It allows messages to be sent and received between applications on different networked machines. There are several different types of sockets that determine the structure of the transport layer .The most common types are stream sockets(TCP) and datagram sockets(UDP). Sockets are created using a system call, and each socket created by the operating system is identified by a small integer called a socket descriptor.The system calls for establishing a connection are somewhat different for the client and the server, but both involve the basic construct of a socket. When an application calls a socket, the operating system allocates a new data structure to hold the information needed for client server communication. Once a socket has been created, it either waits for an incoming connection, called a passive socket,or initiates a connection, called an active socket. A server creates passive socket and a client creates an active socket.
Server Examples : web server(port 80) , FTP server(port 21), Mail server(port 25)
Client Examples : Web-browsers.

Socket Functions :
These functions have their prototypes defined in /usr/include/sys/sockets.h.
1. socket() : create an endpoint for communication
SYNOPSIS : socket(int domain, int type, int protocol);

2. connect() : initiate a connection on a socket.
SYNOPSIS : connect(int fd, struct sockaddr *remote_host, int addr_length);

3.bind() : bind a name to a socket
SYNOPSIS :bind(int fd, struct sockaddr *local_addr, socklen_t addr_length);

4. listen() : listen for connections on a socket.
SYNOPSIS : listen(int fd, int backlog_queue_size);

5.accept(): accept a connection on a socket.
SYNOPSIS : accept(int fd, sockaddr *remote_host, socklen_t *addr_length);

6. send() : Sends n bytes from *buffer to socket fd.
SYNOPSIS :send(int fd, void *buffer, size_t n, int flags)

7. recv() : Receives n bytes from socket fd into *buffer.
SYNOPSIS :recv(int fd, void *buffer, size_t n, int flags)

The steps involved in establishing a socket on the client side are as follows:
1.Create a socket with the socket() system call
2.Connect the socket to the address of the server using the connect() system call
3.Send and receive data. There are a number of ways to do this, but the simplest is to use the read() and write() system calls.

The steps involved in establishing a socket on the server side are as follows:
1.Create a socket with the socket() system call
2.Bind the socket to an address using the bind() system call. For a server socket on the Internet, an address consists of a port number on the host machine.
3.Listen for connections with the listen() system call
4.Accept a connection with the accept() system call. This call typically blocks until a client connects with the server.
5. Send and receive data

This can be understood by a simple diagram :

                                                      



Socket Addresses :
Many of the socket functions reference a sockaddr structure to pass address information that defines a host.
Generic socket addresses :
struct sockaddr {
    uint8_t sa_len;                /* total length of address  */
    sa_family_t sa_family;         /*  family of address */
    char sa_data[14];              /*   the address itself*/
};

sa_data contain a destination address and port number for socket.

To deal with struct sockaddr, programmer created a parallel structure i.e. struct  sockaddr_in(IPv4)

struct sockaddr_in {
    uint8_t sin_len;               /*  total length of adress */
    sa_family_t sin_family;         /*   family of address */
    in_port_t sin_port;             /*  port to connect to */
    struct in_addr sin_addr;         /*  host's IP address */
    char sin_zero[8];                 /* padding, ignored  */
};


Here we deal with Internet Protocol version 4, which is the protocol family PF_INET,  using the address family AF_INET.

                                           


.
Network Byte Order:
The internet protocols specify a format in which binary numbers are passed around between hosts.This format is called network byte order.The port number and IP address used in the AF_INET socket address structure are expected to follow the network byte ordering, which is big-endian. This is the opposite of x86’s little-endian byte ordering, so these values must be converted.
There are several functions specifically for these conversions.

htonl(long value) : Host-to-Network Long
Converts a 32-bit integer from the host’s byte order to network byte order.

htons(short value):  Host-to-Network Short
Converts a 16-bit integer from the host’s byte order to network byte order

ntohl(long value) :Network-to-Host Long
Converts a 32-bit integer from network byte order to the host’s byte order

ntohs(long value)
: Network-to-Host Short
Converts a 16-bit integer from network byte order to the host’s byte order

Internet Address Conversion :

ASCII to Network : inet_aton(char *ascii_addr, struct in_addr *network_addr)

This function converts an ASCII string containing an IP address in dottednumber

format into an in_addr structure.

Network to ASCII : inet_ntoa(struct in_addr *network_addr)

This function converts the other way. It is passed a pointer to an in_addr structure containing an IP address.

Reference : "Hacking: The art of exploitation"
                   "Google"

In the next tutorials we will learn how to write server-client programs.
Note : All the codes given in this blog have been tested under Kali-linux using gcc C compiler.
If you're stuck somewhere, Please feel free to comment !

Why do hackers need to network programming ?

Machines can also talk to each other by means of networking. Similarly, programs can become much more powerful when they have the ability to communicate with other programs via a network. In this world, you will find most systems connected in networks rather than individual. Therefore, to be a complete hacker, you must need some networking knowledge.

So now question is why hacker needs network programming ?
Network programming is an essential part of becoming a hacker.It helps in  create your own hacking tools which can communicate over the internet. Let's discuss some practicle uses of network programming in real world :
* Designing malware : Suppose you are writing your own keylogger which capture keystroke(Each keyboard key press is a keystroke) and send to you. But how  keylogger can send you keystorke When you physically can not access the victim's computer? It makes use of the network programming.By network programming you can send/receive data from the victim's computer.

* Developing remote exploits : If you find a vulnerability in software, say Internet explorer. As you know internet explorer is installed by default on winodws. Now you want exploit this vulnerability in your victim's system remotely. You can't exploit your victim without the network programming. With networking, you  write remote exploit which exploit the vulnerability in software.
 
* Attacking network application like SMTP, FTP :  There are many networking applications like Apache http server, FTP(File transfer protocol), ssh. Now suppose you attacking ssh(Secure shell, port no.22 ) for username and password through brute force attack. To communicate with ssh for username and password you need to network programming in your brute-force program.


Learn networking  :
Knowing as much as you can about how a network operates, including basics such as what an IP address, port, protocol, and the thousands of other networking definitions, can be yet another vital thing to learn about.

OSI Network Layer Model :
Before we start learn about network, let's first we discuss about network architecture. ISO designed the standardized architecture of networks known as OSI (Open Systems Interconnection). The OSI architecture is a layered model of an ideal network. The OSI model provides standards that allow hardware, such as  routers and firewalls, to focus on one particular aspect of communication that applies to them and ignore others. The OSI model is broken down into conceptual layers of communication.

                                    
       



Physical Layer: This is the 1st layer of OSI model. This layer is composed of hardware. The network cables and other network hardware devices lie in this layer.

Data Link Layer: This is the 2nd layer of OSI model. The Ethernet protocol works in this layer. The devices in this layer are addressed using their hardware address also known as MAC (Media Access Control) address.

Network Layer: This is the 3rd layer of OSI model. The networks are broken into logical segments into this layer. The networked systems are identified with IP (internet protocol) addresses into this layer.

Transport Layer: This is the most important layer. The transport layer is the 4th layer of OSI model. The TCP (Transmission Control Protocol) and UDP (User Datagram Protocol) work in this layer.

Session Layer: Te session layer as name suggests keeps track of all connections (sessions). This layer keeps track of the data provided by the upper layers and sends them to their respective lower layer circuits.

Presentation Layer: This layer is most important from security point of view. The encryption if applied can be applied here on the data.

Application Layer: This layer is the main application, i.e. the program, which may or may not be interacting with the user.

When data is communicated through these protocol layers, it’s sent in small pieces called packets. Each packet contains implementations of these protocol layers. Starting from the application layer, the packet wraps the presentation layer around that data, which wraps the session layer, which wraps the transport layer, and so forth. This process is called encapsulation. Each wrapped layer contains a header and a body. The header contains the protocol information needed for that layer, while the body contains the data for that layer. The body of one layer contains the entire package of previously encapsulated layers, like the skin of an onion or the functional contexts found on a program’s stack.
Blogger Widget