0% found this document useful (0 votes)
13 views

Cnsl Lab Manual

The document outlines assignments for a Network Security course, focusing on implementing client-server communication using Python and various cryptographic algorithms. It covers RSA for secure communication, digital signatures for authentication, and DES for message encryption, along with key exchange methods like Diffie-Hellman. Each assignment aims to enhance understanding of client/server environments and public key cryptography.

Uploaded by

jakhuranusrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
13 views

Cnsl Lab Manual

The document outlines assignments for a Network Security course, focusing on implementing client-server communication using Python and various cryptographic algorithms. It covers RSA for secure communication, digital signatures for authentication, and DES for message encryption, along with key exchange methods like Diffie-Hellman. Each assignment aims to enhance understanding of client/server environments and public key cryptography.

Uploaded by

jakhuranusrat
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 110

Assignment No 1

Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the
communication between these two entities by using RSA cryptosystem.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

Client-Server Architecture

Client-server architecture is a network model where every process or computer on a network


is a server or a client. The client-servers are the robust computers that are dedicated to managing the
printers, disk drives, and network traffic. Clients are workstations or PCs on which the users run their
applications. Clients mainly rely on the servers for resources, like devices, files, and processing power.

A client-server relationship corresponds to the request–response pattern and should adhere


to the common communications procedure that defines the language, rules, or dialog patterns used.
The client-server communication adheres to TCP or IP protocol suite.

The TCP protocol maintains the connection until a client/server has completed their message
exchange. And TCP protocol decides the best method to distribute the application data in packets that
networks will deliver, transfers the packets to and get packets from a network, and manages the flow
control or retransmission of the dropped and garbled packets. Internet Protocol is the connectionless
protocol where every packet traveling on the Internet is the independent data unrelated to other data
units.

How Does Client-Server Architecture Works?

Now let us go ahead and look at how the Internet works through web browsers.
Client: The word Client means an organization or an individual using a service. Even in the digital world
Client is a Host (computer) that can receive information or using service from the Servers.

Server: Server means a person that serves something. The server, in the digital world, is the remote
computer that offers information or access to services.

So, it is basically a Client requesting something & a Server serving it providing its presence in a
database.

Types of Client-Server Architecture

1-Tier Architecture

All client or server configuration settings, UI environment, data logic, as well as marketing logic are
there on the same system. The 1-tier architecture services are quite reliable but tough tasks to handle
as they have all data in various variance that will be allotted the complete replication of the whole
work. 1-Tier architecture also has different layers.

For example –Business, Presentation, Data Access layer using a single software package. Data will be
saved on a local machine. Some applications manage 3 tiers like an MP3 player and MS Office;
however, these applications are presented in a 1-tier architecture system.

2-Tier Architecture

In 2-Tier Architecture, the UI is stored at the client machine, and the database gets stored on a server.
The business logic and database logic are filed at server or client but have to be well-maintained.
Suppose Data Logic and Business Logic are collected at the client-side, it’s called fat client-server
architecture. Suppose Data Logic and Business Logic are handled on a server, its thin client-server
architecture. It is considered affordable.

In 2-Tier architecture, server and client need to come in the direct incorporation. Suppose a client
provides any input to a server there must not be any intermediate. It is generally done for rapid results
and to avoid confusion between various clients. For example, an online ticket reservations application
uses this 2-Tier architecture.

3-Tier Architecture

It consists of the presentation tier that is the User Interface layer, an application tier that is a service
layer, which performs the detailed processing, and a data tier that consists of the database server,
which stores information. Three-tier architecture can be split into 3 parts, the presentation layer (or
Client Tier), the Application layer (or Business Tier), and the Database layer (or Data Tier). It works in
the following ways: The Client system handles the Presentation layer; the Application server looks
after the Application layer, and the Server system supervises the Database layer.

What is the RSA algorithm?

The RSA algorithm is an asymmetric cryptography algorithm; this means that it uses a public key and
a private key (i.e two different, mathematically linked keys). As their names suggest, a public key is
shared publicly, while a private key is secret and must not be shared with anyone.

The RSA algorithm is named after those who invented it in 1978: Ron Rivest, Adi Shamir, and Leonard
Adleman.

The following illustration highlights how asymmetric cryptography works:

How it works

The RSA algorithm ensures that the keys, in the above illustration, are as secure as possible. The
following steps highlight how it works:
1. Generating the keys

1. Select two large prime numbers, x and y. The prime numbers need to
be large so that they will be difficult for someone to figure out.
2. Calculate n =x * y.
3. Calculate the totient function; ϕ(n)=(x−1)(y−1).
4. Select an integer e, such that e is co-prime to ϕ(n) and

1 < e < ϕ(n). The pair of numbers (n,e) makes up the public key.
5. Calculate d such that e.d = 1 mod ϕ(n).

d can be found using the extended euclidean algorithm. The pair (n,d) makes up the private key.

2. Encryption

Given a plaintext P, represented as a number, the ciphertext C is calculated


as:

C = Pe mod n.

3. Decryption

Using the private key (n,d)(n,d), the plaintext can be found using:

P = Cd mod n.
Pseudocode

Consider an example of the RSA algorithm through the following pseudocode:

int x = 61, int y = 53;

int n = x * y;

// n = 3233.

// compute the totient, phi

int phi = (x-1)*(y-1);

// phi = 3120.
int e = findCoprime(phi);

// find an 'e' which is > 1 and is a co-prime of phi.

// e = 17 satisfies the current values.

//two integers a and b are coprime, relatively prime or mutually prime if the only positive integer that
//is a divisor of both of them is 1.

// Using the extended euclidean algorithm, find 'd' which satisfies

// this equation:

d = (1 mod (phi))/e; OR (d * e) % φ(n) = 1


// d = 2753 for the example values.

public_key = (e=17, n=3233);

private_key = (d=2753, n=3233);

// Given the plaintext P=123, the ciphertext C is :

C = (123^17) % 3233 = 855;

// To decrypt the cypher text C:

P = (855^2753) % 3233 = 123;

Simple Example

 Choose p = 3 and q = 11
 Compute n = p * q = 3 * 11 = 33
 Compute φ(n) = (p - 1) * (q - 1) = 2 * 10 = 20
 Choose e such that 1 < e < φ(n) and e and φ (n) are coprime. Let e = 7
 Compute a value for d such that (d * e) % φ(n) = 1. One solution is d = 3

[(3 * 7) % 20 = 1]

 Public key is (e, n) => (7, 33)


 Private key is (d, n) => (3, 33)
 The encryption of m = 2 is c = 27 % 33 = 29
 The decryption of c = 29 is m = 293 % 33 = 2
Assignment No 2
Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the authentication
of sender between these two entities by using RSA digital signature cryptosystem.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

RSA Digital Signature Scheme

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on
two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given
to everyone and the Private key is kept private.

An example of asymmetric cryptography :

 A client (for example browser) sends its public key to the server and requests for some data.
 The server encrypts the data using the client’s public key and sends the encrypted data.
 Client receives this data and decrypts it.

Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party
has the public key of browser.

Digital signatures are used to verify the authenticity of the message sent electronically. A digital
signature algorithm uses a public key system. The intended transmitter signs his/her message with
his/her private key and the intended receiver verifies it with the transmitter’s public key. A digital
signature can provide message authentication, message integrity and non-repudiation services.

Algorithm

RSA Key Generation:

 Choose two large prime numbers p and q


 Calculate n=p*q
 Select public key e such that it is not a factor of (p-1)*(q-1)
 Select private key d such that the following equation is true (d*e)mod(p-1)(q-1)=1 or d is
inverse of E in modulo (p-1)*(q-1)
RSA Digital Signature Scheme:

In RSA, d is private; e and n are public.

 Alice creates her digital signature using S=M^d mod n where M is the message
 Alice sends Message M and Signature S to Bob
 Bob computes M1=S^e mod n
 If M1=M then Bob accepts the data sent by Alice.

Basic Implementation:

# Function to find gcd

# of two numbers

def euclid(m, n):

if n == 0:

return m

else:

r=m%n

return euclid(n, r)

# Program to find

# Multiplicative inverse

def exteuclid(a, b):

r1 = a

r2 = b

s1 = int(1)

s2 = int(0)

t1 = int(0)

t2 = int(1)

while r2 > 0:
q = r1//r2

r = r1-q * r2

r1 = r2

r2 = r

s = s1-q * s2

s1 = s2

s2 = s

t = t1-q * t2

t1 = t2

t2 = t

if t1 < 0:

t1 = t1 % a

return (r1, t1)

# Enter two large prime

# numbers p and q

p = 823

q = 953

n=p*q

Pn = (p-1)*(q-1)

# Generate encryption key

# in range 1<e<Pn

key = []

for i in range(2, Pn):

gcd = euclid(Pn, i)
if gcd == 1:

key.append(i)

# Select an encryption key

# from the above list

e = int(313)

# Obtain inverse of

# encryption key in Z_Pn

r, d = exteuclid(Pn, e)

if r == 1:

d = int(d)

print("decryption key is: ", d)

else:

print("Multiplicative inverse for\

the given encryption key does not \

exist. Choose a different encryption key ")

# Enter the message to be sent

M = 19070

# Signature is created by Alice

S = (M**d) % n

# Alice sends M and S both to Bob

# Bob generates message M1 using the

# signature S, Alice's public key e


# and product n.

M1 = (S**e) % n

# If M = M1 only then Bob accepts

# the message sent by Alice.

if M == M1:

print("As M = M1, Accept the\

message sent by Alice")

else:

print("As M not equal to M1,\

Do not accept the message\

sent by Alice ")


Assignment No 3
Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the encryption of
message of sender between these two entities by using DES Algorithm and use Diffie Hellman method
for exchange of keys.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

DES algorithm

Data Encryption Standard (DES) is a block cipher algorithm that takes plain text in blocks of 64 bits and
converts them to ciphertext using keys of 48 bits. It is a symmetric key algorithm, which means that
the same key is used for encrypting and decrypting data.

Encryption and decryption using the DES algorithm.

Steps for generating keys

There are 16 rounds of encryption in the algorithm, and a different key is used for each round. How
keys are generated is listed below.
Bits are labeled from 1 to 64 starting from the most significant bit and going to the least significant
bit.

1. Compress and transpose the given 64-bit key into a 48-bit key using
the following table:
// The array elements denote the bit numbers
int pc1[56] = {
57,49,41,33,25,17,9,
1,58,50,42,34,26,18,
10,2,59,51,43,35,27,
19,11,3,60,52,44,36,
63,55,47,39,31,23,15,
7,62,54,46,38,30,22,
14,6,61,53,45,37,29,
21,13,5,28,20,12,4
};

2. Divide the result into two equal parts: C and D.

3. C and D are left-shifted circularly. For encryption rounds 1, 2, 9, and


16 they are left shifted circularly by 1 bit; for all of the other rounds,
they are left-circularly shifted by 2.

4. The result is compressed to 48 bits in accordance with the following


rule:
int pc2[48] = {
14,17,11,24,1,5,
3,28,15,6,21,10,
23,19,12,4,26,8,
16,7,27,20,13,2,
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32
};

5. The result of step 3 is the input for the next round of key generation.

Steps for encryption

1. Transpose the bits in the 64-block according to the following:


// 58 means that the 58th bit should be considered
// the first bit, 50th bit the second bit and so on.
int initial_permutation_table[64] = {
58,50,42,34,26,18,10,2,
60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,
64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,
59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,
63,55,47,39,31,23,15,7
};

2. Divide the result into equal parts: left plain text (1-32 bits) and right
plain text (33-64 bits)

3. The resulting parts undergo 16 rounds of encryption in each round.

The right plain text is expanded using the following expansion table:
// The array elements denote the bit numbers
int expansion_table[48] = {
32,1,2,3,4,5,4,5,
6,7,8,9,8,9,10,11,
12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,
22,23,24,25,24,25,26,27,
28,29,28,29,30,31,32,1
};

4. The expanded right plain text now consists of 48 bits and is XORed
with the 48-bit key.

5. The result of the previous step is divided into 8 boxes. Each box
contains 6 bits. After going through the eight substitution boxes, each
box is reduced from 6 bits to 4 bits. The first and last bit of each box
provides the row index, and the remaining bits provide the column
index. These indices are used to look-up values in a substitution box.
A substitution box has 4 rows, 16 columns, and contains numbers
from 0 to 15.

6. The result is transposed in accordance with the following rule:


// The array elements denote the bit numbers
int permutation_table[32] = {
16,7,20,21,29,12,28,17,
1,15,23,26,5,18,31,10,
2,8,24,14,32,27,3,9,
19,13,30,6,22,11,4,25
};
7. XOR the left half with the result from the above step. Store this in the
right plain text.

8. Store the initial right plain text in the left plain text.

9. These halves are inputs for the next round. Remember that there are
different keys for each round.

10.After the 16 rounds of encryption, swap the left plain text and the
right plain text.

11. Finally, apply the inverse permutation (inverse of the initial


permutation), and the ciphertext will be generated.
Steps for decryption:

The order of the 16 48-bit keys is reversed such that key 16 becomes key 1, and so on. Then, the steps
for encryption are applied to the ciphertext.

Diffie Hellman Key Exchange Algorithm

Whitefield Diffie and Martin Hellman develop Diffie Hellman key exchange Algorithms in 1976 to
overcome the problem of key agreement and exchange. It enables the two parties who want to
communicate with each other to agree on a symmetric key, a key that can be used for encrypting and
decryption; note that Diffie Hellman key exchange algorithm can be used for only key exchange, not
for encryption and decryption process. The algorithm is based on mathematical principles.

The algorithm is based on Elliptic Curve Cryptography, a method of doing public-key


cryptography based on the algebra structure of elliptic curves over finite fields. The DH also uses the
trapdoor function, just like many other ways to do public-key cryptography. The simple idea of
understanding to the DH Algorithm is the following.

1. The first party picks two prime numbers, g and p and tells them to the second party.

2. The second party then picks a secret number (let’s call it a), and then it computes ga mod p
and sends the result back to the first party; let’s call the result A. Keep in mind that the secret
number is not sent to anyone, only the result is.

3. Then the first party does the same; it selects a secret number b and calculates the result B
similor to the

4. step 2. Then, this result is sent to the second party.

5. The second party takes the received number B and calculates Ba mod p

6. The first party takes the received number A and calculates Ab mod p

This is where it gets interesting; the answer in step 5 is the same as the answer in step 4. This means
both parties will get the same answer no matter the order of exponentiation.
(ga mod p)b mod p = gab mod p

(gb mod p)a mod p = gba mod p

The number we came within steps 4 and 5 will be taken as the shared secret key. This key can be used
to do any encryption of data that will be transmitted, such as blowfish, AES, etc

Diffie Hellman Algorithm

1. key =(YA)XBmod q -> this is the same as calculated by B

2. Global Public Elements

 q: q is a prime number

 a: a < q and α is the primitive root of q

3. Key generation for user A

 Select a Private key XA Here, XA <q

Now, Calculation of Public key YA YA = aXA mod q

4. Key generation for user B

 Select a Private key XB Here, XB <q

 Now, Calculation of Public key YB YB = aXb mod q

5. Calculation of Secret Key by A

 key =(YB)XA mod q

6. Calculation of Secret Key by B

 key =(YA)XB mod q


Example

1. Alice and Bob both use public numbers P = 23, G = 5

2. Alice selected private key a = 4, and Bob selected b = 3 as the private key

3. Both Alice and bob now calculate the value of x and y as follows:

 Alice: x = (54 mod 23) = 4

 Bob: y = (53 mod 23) = 10

4. Now, both Alice and Bob exchange public numbers with each other.

5. Alice and Bob now calculate the symmetric keys

 Alice: ka = ya mod p = 104 mod 23 = 18

 Bob: kb = xb mod p = 43 mod 23 = 18

6. 18 is the shared secret key.

Uses of Diffie Hellman Algorithm

Aside from using the algorithm for generating public keys, there are some other places where DH
Algorithm can be used:

Encryption: The Diffie Hellman key exchange algorithm can be used to encrypt; one of the first
schemes to do is ElGamal encryption. One modern example of it is called Integrated Encryption
Scheme, which provides security against chosen plain text and chosen clipboard attacks.

Password Authenticated Agreement: When two parties share a password, a password-authenticated


key agreement can be used to prevent the Man in the middle attack. This key Agreement can be in
the form of Diffie-Hellman. Secure Remote Password Protocol is a good example that is based on this
technique.
Forward Secrecy: Forward secrecy-based protocols can generate new key pairs for each new session,
and they can automatically discard them when the session is finished. In these forward Secrecy
protocols, more often than not, the Diffie Hellman key exchange is used.

Advantages of the Diffie Hellman Algorithm

 The sender and receiver don’t need any prior knowledge of each other.
 Once the keys are exchanged, the communication of data can be done through an insecure
channel.
 The sharing of the secret key is safe.

Disadvantages of the Diffie Hellman Algorithm

 The algorithm can not be sued for any asymmetric key exchange.
 Similarly, it can not be used for signing digital signatures.
 Since it doesn’t authenticate any party in the transmission, the Diffie Hellman key exchange is
susceptible to a man-in-the-middle attack.
Assignment No 4
Group B (Network Security)

Aim: Use the snort intrusion detection package to analyze traffic and create a signature to identify
problem traffic.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

Intrusion Detection System (IDS)

An Intrusion Detection System (IDS) is a system that monitors network traffic for suspicious activity
and issues alerts when such activity is discovered. It is a software application that scans a network or
a system for the harmful activity or policy breaching. Any malicious venture or violation is normally
reported either to an administrator or collected centrally using a security information and event
management (SIEM) system. A SIEM system integrates outputs from multiple sources and uses alarm
filtering techniques to differentiate malicious activity from false alarms.

Although intrusion detection systems monitor networks for potentially malicious activity, they are also
disposed to false alarms. Hence, organizations need to fine-tune their IDS products when they first
install them. It means properly setting up the intrusion detection systems to recognize what normal
traffic on the network looks like as compared to malicious activity.

Intrusion prevention systems also monitor network packets inbound the system to check the malicious
activities involved in it and at once send the warning notifications.

Classification of Intrusion Detection System:

IDS are classified into 5 types:

1 Network Intrusion Detection System (NIDS):

Network intrusion detection systems (NIDS) are set up at a planned point within the network to
examine traffic from all devices on the network. It performs an observation of passing traffic on the
entire subnet and matches the traffic that is passed on the subnets to the collection of known attacks.
Once an attack is identified or abnormal behavior is observed, the alert can be sent to the
administrator. An example of a NIDS is installing it on the subnet where firewalls are located in order
to see if someone is trying to crack the firewall.

2 Host Intrusion Detection System (HIDS):

Host intrusion detection systems (HIDS) run on independent hosts or devices on the network. A HIDS
monitors the incoming and outgoing packets from the device only and will alert the administrator if
suspicious or malicious activity is detected. It takes a snapshot of existing system files and compares
it with the previous snapshot. If the analytical system files were edited or deleted, an alert is sent to
the administrator to investigate. An example of HIDS usage can be seen on mission-critical machines,
which are not expected to change their layout.

3 Protocol-based Intrusion Detection System (PIDS):

Protocol-based intrusion detection system (PIDS) comprises a system or agent that would consistently
resides at the front end of a server, controlling and interpreting the protocol between a user/device
and the server. It is trying to secure the web server by regularly monitoring the HTTPS protocol stream
and accept the related HTTP protocol. As HTTPS is un-encrypted and before instantly entering its web
presentation layer then this system would need to reside in this interface, between to use the HTTPS.

4 Application Protocol-based Intrusion Detection System (APIDS):

Application Protocol-based Intrusion Detection System (APIDS) is a system or agent that generally
resides within a group of servers. It identifies the intrusions by monitoring and interpreting the
communication on application-specific protocols. For example, this would monitor the SQL protocol
explicit to the middleware as it transacts with the database in the web server.

5 Hybrid Intrusion Detection System:

Hybrid intrusion detection system is made by the combination of two or more approaches of the
intrusion detection system. In the hybrid intrusion detection system, host agent or system data is
combined with network information to develop a complete view of the network system. Hybrid
intrusion detection system is more effective in comparison to the other intrusion detection system.
Prelude is an example of Hybrid IDS.

Detection Method of IDS:

1 Signature-based Method:

Signature-based IDS detects the attacks on the basis of the specific patterns such as number of bytes
or number of 1’s or number of 0’s in the network traffic. It also detects on the basis of the already
known malicious instruction sequence that is used by the malware. The detected patterns in the IDS
are known as signatures.

Signature-based IDS can easily detect the attacks whose pattern (signature) already exists in system
but it is quite difficult to detect the new malware attacks as their pattern (signature) is not known.

2 Anomaly-based Method:

Anomaly-based IDS was introduced to detect unknown malware attacks as new malware are
developed rapidly. In anomaly-based IDS there is use of machine learning to create a trustful activity
model and anything coming is compared with that model and it is declared suspicious if it is not found
in model. Machine learning-based method has a better-generalized property in comparison to
signature-based IDS as these models can be trained according to the applications and hardware
configurations.

Comparison of IDS with Firewalls:

IDS and firewall both are related to network security but an IDS differs from a firewall as a firewall
looks outwardly for intrusions in order to stop them from happening. Firewalls restrict access between
networks to prevent intrusion and if an attack is from inside the network it doesn’t signal. An IDS
describes a suspected intrusion once it has happened and then signals an alarm.
What is Snort?

Snort is the foremost Open Source Intrusion Prevention System (IPS) in the world. Snort IPS uses a
series of rules that help define malicious network activity and uses those rules to find packets that
match against them and generates alerts for users.

Snort can be deployed inline to stop these packets, as well. Snort has three primary uses: As a packet
sniffer like tcpdump, as a packet logger — which is useful for network traffic debugging, or it can be
used as a full-blown network intrusion prevention system. Snort can be downloaded and configured
for personal and business use alike.

SNORT is a powerful open-source intrusion detection system (IDS) and intrusion prevention system
(IPS) that provides real-time network traffic analysis and data packet logging. SNORT uses a rule-based
language that combines anomaly, protocol, and signature inspection methods to detect potentially
malicious activity.

Using SNORT, network admins can spot denial-of-service (DoS) attacks and distributed DoS (DDoS)
attacks, Common Gateway Interface (CGI) attacks, buffer overflows, and stealth port scans. SNORT
creates a series of rules that define malicious network activity, identify malicious packets, and send
alerts to users.

SNORT is a free-to-use open-source piece of software that can be deployed by individuals and
organizations. The SNORT rule language determines which network traffic should be collected and
what should happen when it detects malicious packets. This snorting meaning can be used in the same
way as sniffers and network intrusion detection systems to discover malicious packets or as a full
network IPS solution that monitors network activity and detects and blocks potential attack vectors.

What Are the Features of SNORT?

There are various features that make SNORT useful for network admins to monitor their systems and
detect malicious activity. These include:

1 Real-time Traffic Monitor

SNORT can be used to monitor the traffic that goes in and out of a network. It will monitor traffic in
real time and issue alerts to users when it discovers potentially malicious packets or threats on
Internet Protocol (IP) networks.

2 Packet Logging

SNORT enables packet logging through its packet logger mode, which means it logs packets to the disk.
In this mode, SNORT collects every packet and logs it in a hierarchical directory based on the host
network’s IP address.

3 Analysis of Protocol

SNORT can perform protocol analysis, which is a network sniffing process that captures data in
protocol layers for additional analysis. This enables the network admin to further examine potentially
malicious data packets, which is crucial in, for example, Transmission Control Protocol/IP (TCP/IP)
stack protocol specification.
4 Content Matching

SNORT collates rules by the protocol, such as IP and TCP, then by ports, and then by those with content
and those without. Rules that do have content use a multi-pattern matcher that increases
performance, especially when it comes to protocols like the Hypertext Transfer Protocol (HTTP). Rules
that do not have content are always evaluated, which negatively affects performance.

5 OS Fingerprinting

Operating system (OS) fingerprinting uses the concept that all platforms have a unique TCP/IP stack.
Through this process, SNORT can be used to determine the OS platform being used by a system that
accesses a network.

6 Can Be Installed in Any Network Environment

SNORT can be deployed on all operating systems, including Linux and Windows, and as part of all
network environments.

7 Open Source

As a piece of open-source software, SNORT is free and available for anyone who wants to use an IDS
or IPS to monitor and protect their network.

8 Rules Are Easy to Implement

SNORT rules are easy to implement and get network monitoring and protection up and running. Its
rule language is also very flexible, and creating new rules is pretty simple, enabling network admins to
differentiate regular internet activity from anomalous or malicious activity.

What Are the Different SNORT Modes?

There are three different modes that SNORT can be run in, which will be dependent on the flags used
in the SNORT command.

1 Packet Sniffer

SNORT’s packet sniffer mode means the software will read IP packets then display them to the user
on its console.

2 Packet Logger

In packet logger mode, SNORT will log all IP packets that visit the network. The network admin can
then see who has visited their network and gain insight into the OS and protocols they were using.

3 NIPDS (Network Intrusion and Prevention Detection System)

In NIPDS mode, SNORT will only log packets that are considered malicious. It does this using the preset
characteristics of malicious packets, which are defined in its rules. The action that SNORT takes is also
defined in the rules the network admin sets out.

Installation Steps:

1. wget https://www.snort.org/downloads/snort/daq-2.0.7.tar.gz
2. wget https://www.snort.org/downloads/snort/snort-2.9.19.tar.gz
3. tar xvzf daq-2.0.7.tar.gz
4. cd daq-2.0.7
5. ./configure && make && sudo make install
6. cd ..
7. tar xvzf snort-2.9.19.tar.gz
8. cd snort-2.9.19
9. ./configure --enable-sourcefire && make && sudo make install
Assignment No 1
Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the
communication between these two entities by using RSA cryptosystem.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

Client-Server Architecture

Client-server architecture is a network model where every process or computer on a network


is a server or a client. The client-servers are the robust computers that are dedicated to managing the
printers, disk drives, and network traffic. Clients are workstations or PCs on which the users run their
applications. Clients mainly rely on the servers for resources, like devices, files, and processing power.

A client-server relationship corresponds to the request–response pattern and should adhere


to the common communications procedure that defines the language, rules, or dialog patterns used.
The client-server communication adheres to TCP or IP protocol suite.

The TCP protocol maintains the connection until a client/server has completed their message
exchange. And TCP protocol decides the best method to distribute the application data in packets that
networks will deliver, transfers the packets to and get packets from a network, and manages the flow
control or retransmission of the dropped and garbled packets. Internet Protocol is the connectionless
protocol where every packet traveling on the Internet is the independent data unrelated to other data
units.

How Does Client-Server Architecture Works?

Now let us go ahead and look at how the Internet works through web browsers.
Client: The word Client means an organization or an individual using a service. Even in the digital world
Client is a Host (computer) that can receive information or using service from the Servers.

Server: Server means a person that serves something. The server, in the digital world, is the remote
computer that offers information or access to services.

So, it is basically a Client requesting something & a Server serving it providing its presence in a
database.

Types of Client-Server Architecture

1-Tier Architecture

All client or server configuration settings, UI environment, data logic, as well as marketing logic are
there on the same system. The 1-tier architecture services are quite reliable but tough tasks to handle
as they have all data in various variance that will be allotted the complete replication of the whole
work. 1-Tier architecture also has different layers.

For example –Business, Presentation, Data Access layer using a single software package. Data will be
saved on a local machine. Some applications manage 3 tiers like an MP3 player and MS Office;
however, these applications are presented in a 1-tier architecture system.

2-Tier Architecture

In 2-Tier Architecture, the UI is stored at the client machine, and the database gets stored on a server.
The business logic and database logic are filed at server or client but have to be well-maintained.
Suppose Data Logic and Business Logic are collected at the client-side, it’s called fat client-server
architecture. Suppose Data Logic and Business Logic are handled on a server, its thin client-server
architecture. It is considered affordable.

In 2-Tier architecture, server and client need to come in the direct incorporation. Suppose a client
provides any input to a server there must not be any intermediate. It is generally done for rapid results
and to avoid confusion between various clients. For example, an online ticket reservations application
uses this 2-Tier architecture.

3-Tier Architecture

It consists of the presentation tier that is the User Interface layer, an application tier that is a service
layer, which performs the detailed processing, and a data tier that consists of the database server,
which stores information. Three-tier architecture can be split into 3 parts, the presentation layer (or
Client Tier), the Application layer (or Business Tier), and the Database layer (or Data Tier). It works in
the following ways: The Client system handles the Presentation layer; the Application server looks
after the Application layer, and the Server system supervises the Database layer.

What is the RSA algorithm?

The RSA algorithm is an asymmetric cryptography algorithm; this means that it uses a public key and
a private key (i.e two different, mathematically linked keys). As their names suggest, a public key is
shared publicly, while a private key is secret and must not be shared with anyone.

The RSA algorithm is named after those who invented it in 1978: Ron Rivest, Adi Shamir, and Leonard
Adleman.

The following illustration highlights how asymmetric cryptography works:

How it works

The RSA algorithm ensures that the keys, in the above illustration, are as secure as possible. The
following steps highlight how it works:
1. Generating the keys

1. Select two large prime numbers, x and y. The prime numbers need to
be large so that they will be difficult for someone to figure out.
2. Calculate n =x * y.
3. Calculate the totient function; ϕ(n)=(x−1)(y−1).
4. Select an integer e, such that e is co-prime to ϕ(n) and

1 < e < ϕ(n). The pair of numbers (n,e) makes up the public key.
5. Calculate d such that e.d = 1 mod ϕ(n).

d can be found using the extended euclidean algorithm. The pair (n,d) makes up the private key.

2. Encryption

Given a plaintext P, represented as a number, the ciphertext C is calculated


as:

C = Pe mod n.

3. Decryption

Using the private key (n,d)(n,d), the plaintext can be found using:

P = Cd mod n.
Pseudocode

Consider an example of the RSA algorithm through the following pseudocode:

int x = 61, int y = 53;

int n = x * y;

// n = 3233.

// compute the totient, phi

int phi = (x-1)*(y-1);

// phi = 3120.
int e = findCoprime(phi);

// find an 'e' which is > 1 and is a co-prime of phi.

// e = 17 satisfies the current values.

//two integers a and b are coprime, relatively prime or mutually prime if the only positive integer that
//is a divisor of both of them is 1.

// Using the extended euclidean algorithm, find 'd' which satisfies

// this equation:

d = (1 mod (phi))/e; OR (d * e) % φ(n) = 1


// d = 2753 for the example values.

public_key = (e=17, n=3233);

private_key = (d=2753, n=3233);

// Given the plaintext P=123, the ciphertext C is :

C = (123^17) % 3233 = 855;

// To decrypt the cypher text C:

P = (855^2753) % 3233 = 123;

Simple Example

 Choose p = 3 and q = 11
 Compute n = p * q = 3 * 11 = 33
 Compute φ(n) = (p - 1) * (q - 1) = 2 * 10 = 20
 Choose e such that 1 < e < φ(n) and e and φ (n) are coprime. Let e = 7
 Compute a value for d such that (d * e) % φ(n) = 1. One solution is d = 3

[(3 * 7) % 20 = 1]

 Public key is (e, n) => (7, 33)


 Private key is (d, n) => (3, 33)
 The encryption of m = 2 is c = 27 % 33 = 29
 The decryption of c = 29 is m = 293 % 33 = 2
Assignment No 2
Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the authentication
of sender between these two entities by using RSA digital signature cryptosystem.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

RSA Digital Signature Scheme

RSA algorithm is an asymmetric cryptography algorithm. Asymmetric actually means that it works on
two different keys i.e. Public Key and Private Key. As the name describes that the Public Key is given
to everyone and the Private key is kept private.

An example of asymmetric cryptography :

 A client (for example browser) sends its public key to the server and requests for some data.
 The server encrypts the data using the client’s public key and sends the encrypted data.
 Client receives this data and decrypts it.

Since this is asymmetric, nobody else except the browser can decrypt the data even if a third party
has the public key of browser.

Digital signatures are used to verify the authenticity of the message sent electronically. A digital
signature algorithm uses a public key system. The intended transmitter signs his/her message with
his/her private key and the intended receiver verifies it with the transmitter’s public key. A digital
signature can provide message authentication, message integrity and non-repudiation services.

Algorithm

RSA Key Generation:

 Choose two large prime numbers p and q


 Calculate n=p*q
 Select public key e such that it is not a factor of (p-1)*(q-1)
 Select private key d such that the following equation is true (d*e)mod(p-1)(q-1)=1 or d is
inverse of E in modulo (p-1)*(q-1)
RSA Digital Signature Scheme:

In RSA, d is private; e and n are public.

 Alice creates her digital signature using S=M^d mod n where M is the message
 Alice sends Message M and Signature S to Bob
 Bob computes M1=S^e mod n
 If M1=M then Bob accepts the data sent by Alice.

Basic Implementation:

# Function to find gcd

# of two numbers

def euclid(m, n):

if n == 0:

return m

else:

r=m%n

return euclid(n, r)

# Program to find

# Multiplicative inverse

def exteuclid(a, b):

r1 = a

r2 = b

s1 = int(1)

s2 = int(0)

t1 = int(0)

t2 = int(1)

while r2 > 0:
q = r1//r2

r = r1-q * r2

r1 = r2

r2 = r

s = s1-q * s2

s1 = s2

s2 = s

t = t1-q * t2

t1 = t2

t2 = t

if t1 < 0:

t1 = t1 % a

return (r1, t1)

# Enter two large prime

# numbers p and q

p = 823

q = 953

n=p*q

Pn = (p-1)*(q-1)

# Generate encryption key

# in range 1<e<Pn

key = []

for i in range(2, Pn):

gcd = euclid(Pn, i)
if gcd == 1:

key.append(i)

# Select an encryption key

# from the above list

e = int(313)

# Obtain inverse of

# encryption key in Z_Pn

r, d = exteuclid(Pn, e)

if r == 1:

d = int(d)

print("decryption key is: ", d)

else:

print("Multiplicative inverse for\

the given encryption key does not \

exist. Choose a different encryption key ")

# Enter the message to be sent

M = 19070

# Signature is created by Alice

S = (M**d) % n

# Alice sends M and S both to Bob

# Bob generates message M1 using the

# signature S, Alice's public key e


# and product n.

M1 = (S**e) % n

# If M = M1 only then Bob accepts

# the message sent by Alice.

if M == M1:

print("As M = M1, Accept the\

message sent by Alice")

else:

print("As M not equal to M1,\

Do not accept the message\

sent by Alice ")


Assignment No 3
Group B (Network Security)

Aim: Implement a client and a server on different computers using python. Perform the encryption of
message of sender between these two entities by using DES Algorithm and use Diffie Hellman method
for exchange of keys.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

DES algorithm

Data Encryption Standard (DES) is a block cipher algorithm that takes plain text in blocks of 64 bits and
converts them to ciphertext using keys of 48 bits. It is a symmetric key algorithm, which means that
the same key is used for encrypting and decrypting data.

Encryption and decryption using the DES algorithm.

Steps for generating keys

There are 16 rounds of encryption in the algorithm, and a different key is used for each round. How
keys are generated is listed below.
Bits are labeled from 1 to 64 starting from the most significant bit and going to the least significant
bit.

1. Compress and transpose the given 64-bit key into a 48-bit key using
the following table:
// The array elements denote the bit numbers
int pc1[56] = {
57,49,41,33,25,17,9,
1,58,50,42,34,26,18,
10,2,59,51,43,35,27,
19,11,3,60,52,44,36,
63,55,47,39,31,23,15,
7,62,54,46,38,30,22,
14,6,61,53,45,37,29,
21,13,5,28,20,12,4
};

2. Divide the result into two equal parts: C and D.

3. C and D are left-shifted circularly. For encryption rounds 1, 2, 9, and


16 they are left shifted circularly by 1 bit; for all of the other rounds,
they are left-circularly shifted by 2.

4. The result is compressed to 48 bits in accordance with the following


rule:
int pc2[48] = {
14,17,11,24,1,5,
3,28,15,6,21,10,
23,19,12,4,26,8,
16,7,27,20,13,2,
41,52,31,37,47,55,
30,40,51,45,33,48,
44,49,39,56,34,53,
46,42,50,36,29,32
};

5. The result of step 3 is the input for the next round of key generation.

Steps for encryption

1. Transpose the bits in the 64-block according to the following:


// 58 means that the 58th bit should be considered
// the first bit, 50th bit the second bit and so on.
int initial_permutation_table[64] = {
58,50,42,34,26,18,10,2,
60,52,44,36,28,20,12,4,
62,54,46,38,30,22,14,6,
64,56,48,40,32,24,16,8,
57,49,41,33,25,17,9,1,
59,51,43,35,27,19,11,3,
61,53,45,37,29,21,13,5,
63,55,47,39,31,23,15,7
};

2. Divide the result into equal parts: left plain text (1-32 bits) and right
plain text (33-64 bits)

3. The resulting parts undergo 16 rounds of encryption in each round.

The right plain text is expanded using the following expansion table:
// The array elements denote the bit numbers
int expansion_table[48] = {
32,1,2,3,4,5,4,5,
6,7,8,9,8,9,10,11,
12,13,12,13,14,15,16,17,
16,17,18,19,20,21,20,21,
22,23,24,25,24,25,26,27,
28,29,28,29,30,31,32,1
};

4. The expanded right plain text now consists of 48 bits and is XORed
with the 48-bit key.

5. The result of the previous step is divided into 8 boxes. Each box
contains 6 bits. After going through the eight substitution boxes, each
box is reduced from 6 bits to 4 bits. The first and last bit of each box
provides the row index, and the remaining bits provide the column
index. These indices are used to look-up values in a substitution box.
A substitution box has 4 rows, 16 columns, and contains numbers
from 0 to 15.

6. The result is transposed in accordance with the following rule:


// The array elements denote the bit numbers
int permutation_table[32] = {
16,7,20,21,29,12,28,17,
1,15,23,26,5,18,31,10,
2,8,24,14,32,27,3,9,
19,13,30,6,22,11,4,25
};
7. XOR the left half with the result from the above step. Store this in the
right plain text.

8. Store the initial right plain text in the left plain text.

9. These halves are inputs for the next round. Remember that there are
different keys for each round.

10.After the 16 rounds of encryption, swap the left plain text and the
right plain text.

11. Finally, apply the inverse permutation (inverse of the initial


permutation), and the ciphertext will be generated.
Steps for decryption:

The order of the 16 48-bit keys is reversed such that key 16 becomes key 1, and so on. Then, the steps
for encryption are applied to the ciphertext.

Diffie Hellman Key Exchange Algorithm

Whitefield Diffie and Martin Hellman develop Diffie Hellman key exchange Algorithms in 1976 to
overcome the problem of key agreement and exchange. It enables the two parties who want to
communicate with each other to agree on a symmetric key, a key that can be used for encrypting and
decryption; note that Diffie Hellman key exchange algorithm can be used for only key exchange, not
for encryption and decryption process. The algorithm is based on mathematical principles.

The algorithm is based on Elliptic Curve Cryptography, a method of doing public-key


cryptography based on the algebra structure of elliptic curves over finite fields. The DH also uses the
trapdoor function, just like many other ways to do public-key cryptography. The simple idea of
understanding to the DH Algorithm is the following.

1. The first party picks two prime numbers, g and p and tells them to the second party.

2. The second party then picks a secret number (let’s call it a), and then it computes ga mod p
and sends the result back to the first party; let’s call the result A. Keep in mind that the secret
number is not sent to anyone, only the result is.

3. Then the first party does the same; it selects a secret number b and calculates the result B
similor to the

4. step 2. Then, this result is sent to the second party.

5. The second party takes the received number B and calculates Ba mod p

6. The first party takes the received number A and calculates Ab mod p

This is where it gets interesting; the answer in step 5 is the same as the answer in step 4. This means
both parties will get the same answer no matter the order of exponentiation.
(ga mod p)b mod p = gab mod p

(gb mod p)a mod p = gba mod p

The number we came within steps 4 and 5 will be taken as the shared secret key. This key can be used
to do any encryption of data that will be transmitted, such as blowfish, AES, etc

Diffie Hellman Algorithm

1. key =(YA)XBmod q -> this is the same as calculated by B

2. Global Public Elements

 q: q is a prime number

 a: a < q and α is the primitive root of q

3. Key generation for user A

 Select a Private key XA Here, XA <q

Now, Calculation of Public key YA YA = aXA mod q

4. Key generation for user B

 Select a Private key XB Here, XB <q

 Now, Calculation of Public key YB YB = aXb mod q

5. Calculation of Secret Key by A

 key =(YB)XA mod q

6. Calculation of Secret Key by B

 key =(YA)XB mod q


Example

1. Alice and Bob both use public numbers P = 23, G = 5

2. Alice selected private key a = 4, and Bob selected b = 3 as the private key

3. Both Alice and bob now calculate the value of x and y as follows:

 Alice: x = (54 mod 23) = 4

 Bob: y = (53 mod 23) = 10

4. Now, both Alice and Bob exchange public numbers with each other.

5. Alice and Bob now calculate the symmetric keys

 Alice: ka = ya mod p = 104 mod 23 = 18

 Bob: kb = xb mod p = 43 mod 23 = 18

6. 18 is the shared secret key.

Uses of Diffie Hellman Algorithm

Aside from using the algorithm for generating public keys, there are some other places where DH
Algorithm can be used:

Encryption: The Diffie Hellman key exchange algorithm can be used to encrypt; one of the first
schemes to do is ElGamal encryption. One modern example of it is called Integrated Encryption
Scheme, which provides security against chosen plain text and chosen clipboard attacks.

Password Authenticated Agreement: When two parties share a password, a password-authenticated


key agreement can be used to prevent the Man in the middle attack. This key Agreement can be in
the form of Diffie-Hellman. Secure Remote Password Protocol is a good example that is based on this
technique.
Forward Secrecy: Forward secrecy-based protocols can generate new key pairs for each new session,
and they can automatically discard them when the session is finished. In these forward Secrecy
protocols, more often than not, the Diffie Hellman key exchange is used.

Advantages of the Diffie Hellman Algorithm

 The sender and receiver don’t need any prior knowledge of each other.
 Once the keys are exchanged, the communication of data can be done through an insecure
channel.
 The sharing of the secret key is safe.

Disadvantages of the Diffie Hellman Algorithm

 The algorithm can not be sued for any asymmetric key exchange.
 Similarly, it can not be used for signing digital signatures.
 Since it doesn’t authenticate any party in the transmission, the Diffie Hellman key exchange is
susceptible to a man-in-the-middle attack.
Assignment No 4
Group B (Network Security)

Aim: Use the snort intrusion detection package to analyze traffic and create a signature to identify
problem traffic.

Objectives:

1. To learn various client/server environments to use application layer protocols.


2. To understand the network security by using public key cryptography algorithms.

Theory:

Intrusion Detection System (IDS)

An Intrusion Detection System (IDS) is a system that monitors network traffic for suspicious activity
and issues alerts when such activity is discovered. It is a software application that scans a network or
a system for the harmful activity or policy breaching. Any malicious venture or violation is normally
reported either to an administrator or collected centrally using a security information and event
management (SIEM) system. A SIEM system integrates outputs from multiple sources and uses alarm
filtering techniques to differentiate malicious activity from false alarms.

Although intrusion detection systems monitor networks for potentially malicious activity, they are also
disposed to false alarms. Hence, organizations need to fine-tune their IDS products when they first
install them. It means properly setting up the intrusion detection systems to recognize what normal
traffic on the network looks like as compared to malicious activity.

Intrusion prevention systems also monitor network packets inbound the system to check the malicious
activities involved in it and at once send the warning notifications.

Classification of Intrusion Detection System:

IDS are classified into 5 types:

1 Network Intrusion Detection System (NIDS):

Network intrusion detection systems (NIDS) are set up at a planned point within the network to
examine traffic from all devices on the network. It performs an observation of passing traffic on the
entire subnet and matches the traffic that is passed on the subnets to the collection of known attacks.
Once an attack is identified or abnormal behavior is observed, the alert can be sent to the
administrator. An example of a NIDS is installing it on the subnet where firewalls are located in order
to see if someone is trying to crack the firewall.

2 Host Intrusion Detection System (HIDS):

Host intrusion detection systems (HIDS) run on independent hosts or devices on the network. A HIDS
monitors the incoming and outgoing packets from the device only and will alert the administrator if
suspicious or malicious activity is detected. It takes a snapshot of existing system files and compares
it with the previous snapshot. If the analytical system files were edited or deleted, an alert is sent to
the administrator to investigate. An example of HIDS usage can be seen on mission-critical machines,
which are not expected to change their layout.

3 Protocol-based Intrusion Detection System (PIDS):

Protocol-based intrusion detection system (PIDS) comprises a system or agent that would consistently
resides at the front end of a server, controlling and interpreting the protocol between a user/device
and the server. It is trying to secure the web server by regularly monitoring the HTTPS protocol stream
and accept the related HTTP protocol. As HTTPS is un-encrypted and before instantly entering its web
presentation layer then this system would need to reside in this interface, between to use the HTTPS.

4 Application Protocol-based Intrusion Detection System (APIDS):

Application Protocol-based Intrusion Detection System (APIDS) is a system or agent that generally
resides within a group of servers. It identifies the intrusions by monitoring and interpreting the
communication on application-specific protocols. For example, this would monitor the SQL protocol
explicit to the middleware as it transacts with the database in the web server.

5 Hybrid Intrusion Detection System:

Hybrid intrusion detection system is made by the combination of two or more approaches of the
intrusion detection system. In the hybrid intrusion detection system, host agent or system data is
combined with network information to develop a complete view of the network system. Hybrid
intrusion detection system is more effective in comparison to the other intrusion detection system.
Prelude is an example of Hybrid IDS.

Detection Method of IDS:

1 Signature-based Method:

Signature-based IDS detects the attacks on the basis of the specific patterns such as number of bytes
or number of 1’s or number of 0’s in the network traffic. It also detects on the basis of the already
known malicious instruction sequence that is used by the malware. The detected patterns in the IDS
are known as signatures.

Signature-based IDS can easily detect the attacks whose pattern (signature) already exists in system
but it is quite difficult to detect the new malware attacks as their pattern (signature) is not known.

2 Anomaly-based Method:

Anomaly-based IDS was introduced to detect unknown malware attacks as new malware are
developed rapidly. In anomaly-based IDS there is use of machine learning to create a trustful activity
model and anything coming is compared with that model and it is declared suspicious if it is not found
in model. Machine learning-based method has a better-generalized property in comparison to
signature-based IDS as these models can be trained according to the applications and hardware
configurations.

Comparison of IDS with Firewalls:

IDS and firewall both are related to network security but an IDS differs from a firewall as a firewall
looks outwardly for intrusions in order to stop them from happening. Firewalls restrict access between
networks to prevent intrusion and if an attack is from inside the network it doesn’t signal. An IDS
describes a suspected intrusion once it has happened and then signals an alarm.
What is Snort?

Snort is the foremost Open Source Intrusion Prevention System (IPS) in the world. Snort IPS uses a
series of rules that help define malicious network activity and uses those rules to find packets that
match against them and generates alerts for users.

Snort can be deployed inline to stop these packets, as well. Snort has three primary uses: As a packet
sniffer like tcpdump, as a packet logger — which is useful for network traffic debugging, or it can be
used as a full-blown network intrusion prevention system. Snort can be downloaded and configured
for personal and business use alike.

SNORT is a powerful open-source intrusion detection system (IDS) and intrusion prevention system
(IPS) that provides real-time network traffic analysis and data packet logging. SNORT uses a rule-based
language that combines anomaly, protocol, and signature inspection methods to detect potentially
malicious activity.

Using SNORT, network admins can spot denial-of-service (DoS) attacks and distributed DoS (DDoS)
attacks, Common Gateway Interface (CGI) attacks, buffer overflows, and stealth port scans. SNORT
creates a series of rules that define malicious network activity, identify malicious packets, and send
alerts to users.

SNORT is a free-to-use open-source piece of software that can be deployed by individuals and
organizations. The SNORT rule language determines which network traffic should be collected and
what should happen when it detects malicious packets. This snorting meaning can be used in the same
way as sniffers and network intrusion detection systems to discover malicious packets or as a full
network IPS solution that monitors network activity and detects and blocks potential attack vectors.

What Are the Features of SNORT?

There are various features that make SNORT useful for network admins to monitor their systems and
detect malicious activity. These include:

1 Real-time Traffic Monitor

SNORT can be used to monitor the traffic that goes in and out of a network. It will monitor traffic in
real time and issue alerts to users when it discovers potentially malicious packets or threats on
Internet Protocol (IP) networks.

2 Packet Logging

SNORT enables packet logging through its packet logger mode, which means it logs packets to the disk.
In this mode, SNORT collects every packet and logs it in a hierarchical directory based on the host
network’s IP address.

3 Analysis of Protocol

SNORT can perform protocol analysis, which is a network sniffing process that captures data in
protocol layers for additional analysis. This enables the network admin to further examine potentially
malicious data packets, which is crucial in, for example, Transmission Control Protocol/IP (TCP/IP)
stack protocol specification.
4 Content Matching

SNORT collates rules by the protocol, such as IP and TCP, then by ports, and then by those with content
and those without. Rules that do have content use a multi-pattern matcher that increases
performance, especially when it comes to protocols like the Hypertext Transfer Protocol (HTTP). Rules
that do not have content are always evaluated, which negatively affects performance.

5 OS Fingerprinting

Operating system (OS) fingerprinting uses the concept that all platforms have a unique TCP/IP stack.
Through this process, SNORT can be used to determine the OS platform being used by a system that
accesses a network.

6 Can Be Installed in Any Network Environment

SNORT can be deployed on all operating systems, including Linux and Windows, and as part of all
network environments.

7 Open Source

As a piece of open-source software, SNORT is free and available for anyone who wants to use an IDS
or IPS to monitor and protect their network.

8 Rules Are Easy to Implement

SNORT rules are easy to implement and get network monitoring and protection up and running. Its
rule language is also very flexible, and creating new rules is pretty simple, enabling network admins to
differentiate regular internet activity from anomalous or malicious activity.

What Are the Different SNORT Modes?

There are three different modes that SNORT can be run in, which will be dependent on the flags used
in the SNORT command.

1 Packet Sniffer

SNORT’s packet sniffer mode means the software will read IP packets then display them to the user
on its console.

2 Packet Logger

In packet logger mode, SNORT will log all IP packets that visit the network. The network admin can
then see who has visited their network and gain insight into the OS and protocols they were using.

3 NIPDS (Network Intrusion and Prevention Detection System)

In NIPDS mode, SNORT will only log packets that are considered malicious. It does this using the preset
characteristics of malicious packets, which are defined in its rules. The action that SNORT takes is also
defined in the rules the network admin sets out.

Installation Steps:

1. wget https://www.snort.org/downloads/snort/daq-2.0.7.tar.gz
2. wget https://www.snort.org/downloads/snort/snort-2.9.19.tar.gz
3. tar xvzf daq-2.0.7.tar.gz
4. cd daq-2.0.7
5. ./configure && make && sudo make install
6. cd ..
7. tar xvzf snort-2.9.19.tar.gz
8. cd snort-2.9.19
9. ./configure --enable-sourcefire && make && sudo make install
Assignment 1(b)

Access control list


ACLs are basically a set of commands, grouped together by a number or name that is used to
filter traffic entering or leaving an interface.

When activating an ACL on an interface, you must specify in which direction the traffic
should be filtered:

 Inbound (as the traffic comes into an interface)


 Outbound (before the traffic exits an interface)

Inbound ACLs: Incoming packets are processed before they are routed to an outbound
interface. An inbound ACL is efficient because it saves the overhead of routing lookups if the
packet will be discarded after it is denied by the filtering tests. If the packet is permitted by
the tests, it is processed for routing.

Outbound ACLs: Incoming packets are routed to the outbound interface and then processed
through the outbound ACL.

Universal fact about Access control list

1. ACLs come in two varieties : Numbered and named


2. Each of these references to ACLs supports two types of filtering: standard and
extended.
3. Standard IP ACLs can filter only on the source IP address inside a packet.
4. Whereas an extended IP ACLs can filter on the source and destination IP addresses
in the packet.
5. There are two actions an ACL can take: permit or deny.
6. Statements are processed top-down.
7. Once a match is found, no further statements are processed—therefore, order is
important.
8. If no match is found, the imaginary implicit deny statement at the end of the ACL
drops the packet.
1
9. An ACL should have at least one permit statement; otherwise, all traffic will be
dropped because of the hidden implicit deny statement at the end of every ACL.

No matter what type of ACL you use, though, you can have only one ACL per protocol, per
interface, per direction. For example, you can have one IP ACL inbound on an interface and
another IP ACL outbound on an interface, but you cannot have two inbound IP ACLs on the
same interface.

Access List Ranges


Type Range
IP Standard 1–99
IP Extended 100–199
IP Standard Expanded Range 1300–1999
IP Extended Expanded Range 2000–2699

Standard ACLs
A standard IP ACL is simple; it filters based on source address only. You can filter a
source network or a source host, but you cannot filter based on the destination of a
packet, the particular protocol being used such as the Transmission Control Protocol
(TCP) or the User Datagram Protocol (UDP), or on the port number. You can permit or
deny only source traffic.

Extended ACLs:
An extended ACL gives you much more power than just a standard ACL. Extended IP
ACLs check both the source and destination packet addresses. They can also check for
specific protocols, port numbers, and other parameters, which allow administrators
more flexibility and control.

Named ACLs
One of the disadvantages of using IP standard and IP extended ACLs is that you
reference them by number, which is not too descriptive of its use. With a named ACL,
this is not the case because you can name your ACL with a descriptive name. The ACL
named Deny Mike is a lot more meaningful than an ACL simply numbered 1. There are
both IP standard and IP extended named ACLs.

2
Another advantage to named ACLs is that they allow you to remove individual lines
out of an ACL. With numbered ACLs, you cannot delete individual statements. Instead,
you will need to delete your existing access list and re-create the entire list.

Configuration Guidelines
 Order of statements is important: put the most restrictive statements at the top of the
list and the least restrictive at the bottom.
 ACL statements are processed top-down until a match is found, and then no more
statements in the list are processed.
 If no match is found in the ACL, the packet is dropped (implicit deny).
 Each ACL needs either a unique number or a unique name.
 The router cannot filter traffic that it, itself, originates.
 You can have only one IP ACL applied to an interface in each direction (inbound and
outbound)—you can't have two or more inbound or outbound ACLs applied to the
same interface. (Actually, you can have one ACL for each protocol, like IP and IPX,
applied to an interface in each direction.)
 Applying an empty ACL to an interface permits all traffic by default: in order for an
ACL to have an implicit deny statement, you need at least one actual permit or deny
statement.
 Remember the numbers you can use for IP ACLs.Standard ACLs can use numbers
ranging 1–99 and 1300–1999, and extended ACLs can use 100–199 and 2000–
2699.
 Wildcard mask is not a subnet mask. Like an IP address or a subnet mask, a wildcard
mask is composed of 32 bits when doing the conversion; subtract each byte in the
subnet mask from 255.

There are two special types of wildcard masks:

0.0.0.0 and 255.255.255.255

A 0.0.0.0 wildcard mask is called a host mask

255.255.255.255. If you enter this, the router will cover the address and mask to the
keyword any.

Placement of ACLs
3
Standard ACLs should be placed as close to the destination devices as possible.

Extended ACLs should be placed as close to the source devices as possible.

4
Standard access lists
Because a standard access list filters only traffic based on source traffic, all you need is the IP
address of the host or subnet you want to permit or deny. ACLs are created in global
configuration mode and then applied on an interface. The syntax for creating a standard ACL is

access-list {1-99 | 1300-1999} {permit | deny} source-address


[wildcard mask]

In this article we will configure standard access list. If you want read the feature and
characteristic of access list reads this previous article.

Access control list

In this article we will use a RIP running topology. Which we created in RIP routing practical.

Three basic steps to configure Standard Access List

 Use the access-list global configuration command to create an entry in a standard ACL.
 Use the interface configuration command to select an interface to which to apply the
ACL.
 Use the ip access-group interface configuration command to activate the existing ACL on
an interface.

With Access Lists you will have a variety of uses for the wild card masks, but typically For CCNA
exam prospective you should be able to do following:

1. Match a specific host,


2. Match an entire subnet,
3. Match an IP range, or
4. Match Everyone and anyone
Match specific hosts

Task

You have given a task to block 10.0.0.3 from gaining access on 40.0.0.0. While 10.0.0.3 must be
able to communicate with networks. Other computer from the network of 10.0.0.0 must be able
to connect with the network of 40.0.0.0.

Decide where to apply ACL and in which directions.

Our host must be able to communicate with other host except 40.0.0.0 so we will place this
access list on FastEthernet 0/1 of R2 (2811) connected to the network of 40.0.0.0. Direction will
be outside as packet will be filter while its leaving the interface. If you place this list on R1(1841)
then host 10.0.0.3 will not be able to communicate with any other hosts including 40.0.0.0.

To configure R2 double click on it and select CLI (Choose only one method result will be same)

R2>enable
R2#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 1 deny host 10.0.0.3
R2(config)#access-list 1 permit any
R2(config)#interface fastEthernet 0/1
R2(config-if)#ip access-group 1 out

OR

R2>enable
R2#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 1 deny 10.0.0.3 0.0.0.0
R2(config)#access-list 1 permit any
R2(config)#interface fastEthernet 0/1
R2(config-if)#ip access-group 1 out

To test first do ping from 10.0.0.3 to 40.0.0.3 it should be request time out as this packet will
filter by ACL. Then ping 30.0.0.3 it should be successfully replay.

PC>ping 40.0.0.3

Pinging 40.0.0.3 with 32 bytes of data:


Request timed out.
Request timed out.
Request timed out.
Request timed out.

Ping statistics for 40.0.0.3:


Packets: Sent = 4, Received = 0, Lost = 4 (100% loss),

PC>ping 30.0.0.3
Pinging 30.0.0.3 with 32 bytes of data:

Request timed out.


Reply from 30.0.0.3: bytes=32 time=140ms TTL=126
Reply from 30.0.0.3: bytes=32 time=156ms TTL=126
Reply from 30.0.0.3: bytes=32 time=112ms TTL=126

Ping statistics for 30.0.0.3:


Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),
Approximate round trip times in milli-seconds:
Minimum = 112ms, Maximum = 156ms, Average = 136ms

As we applied access list only on specific host so other computer from the network of 10.0.0.0
must be able to connect with the network of 40.0.0.0. To test do ping from 10.0.0.2 to 40.0.0.3

PC>ipconfig

IP Address......................: 10.0.0.2
Subnet Mask.....................: 255.0.0.0
Default Gateway.................: 10.0.0.1

PC>ping 40.0.0.3

Pinging 40.0.0.3 with 32 bytes of data:

Request timed out.


Reply from 40.0.0.3: bytes=32 time=141ms TTL=126
Reply from 40.0.0.3: bytes=32 time=140ms TTL=126
Reply from 40.0.0.3: bytes=32 time=125ms TTL=126

Ping statistics for 40.0.0.3:


Packets: Sent = 4, Received = 3, Lost = 1 (25% loss),
Approximate round trip times in milli-seconds:
Minimum = 125ms, Maximum = 141ms, Average = 135ms

Match an entire subnet

Task

You have given a task to the network of 10.0.0.0 from gaining access on 40.0.0.0. While 10.0.0.0
must be able to communicate with networks .

Wildcards

Wildcards are used with access lists to specify an individual host, a network, or a certain range
of a network or networks.

Formula to calculate wild card mask for access list


The key to matching an entire subnet is to use the following formula for the wildcard mask. It
goes as follows:
Wildcard mask = 255.255.255.255 – subnet
So for example if my current subnet was 255.0.0.0, the mask would be 0.255.255.255.

255.255.255.255
255 .0 .0 .0 -
----------------
0. 255 .255.255
----------------

Once you have calculated the wild card mask rest is same as we did in pervious example

R2>enable
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 2 deny 10.0.0.0 0.255.255.255
R2(config)#access-list 2 permit any
R2(config)#interface fastethernet 0/1
R2(config-if)#ip access-group 2 out
R2(config-if)#

To test first do ping from 10.0.0.3 to 40.0.0.3 it should be request time out as this packet will
filter by ACL. Then ping 30.0.0.3 it should be successfully replay.

Now do ping from 10.0.0.2 to 40.0.0.3 and further 30.0.0.2 result should be same as the packet
is filtering on network based

Match an IP range

You are a network administrator at ComputerNetworkingNotes.com. You task is to block an ip


range of 10.3.16.0 – 10.3.31.255 from gaining access to the network of 40.0.0.0

Solutions

Our range is 10.3.16.0 – 10.3.31.255. In order to find the mask, take the higher IP and subtract
from it the lower IP.

10.3.31.255
10.3.16.0 -
--------------
0.0.15.255
--------------

In this case the wildcard mask for this range is 0.0.15.255.


To permit access to this range, you would use the following:

R2>enable
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 2 deny 10.3.16.0 0.0.15.255
R2(config)#access-list 2 permit any
R2(config)#interface fastethernet 0/1
R2(config-if)#ip access-group 2 out
R2(config-if)#

One thing to note is that each non-zero value in the mask must be one less than a power of 2,
i.e. 0, 1, 3, 7, 15, 31, 63, 127, 255.

Match Everyone and Anyone

This is the easiest of Access-Lists to create, just use the following:


access-list 1 permit any
or
access-list 1 permit 0.0.0.0 255.255.255.255

Secure telnet session via standard ACL

This is among the highly tested topic in CCNA exam. We could use extended ACL to secure
telnet session but if you did that, you’d have to apply it inbound on every interface, and that
really wouldn’t scale well to a large router with dozens, even hundreds, of interfaces.Here's a
much better solution:

Use a standard IP access list to control access to the VTY lines themselves.

To perform this function, follow these steps:

1. Create a standard IP access list that permits only the host or hosts you want to be able
to telnet into the routers.
2. Apply the access list to the VTY line with the access-class command

Secure R2 in a way that only 20.0.0.2 can telnet it beside it all other telnet session should be
denied

R2>enable
R2#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 3 permit host 20.0.0.2
R2(config)#line vty 0 4
R2(config-line)#password vinita
R2(config-line)#login
R2(config-line)#access-class 3 in

To test do telnet from 20.0.0.2 first is should be successful.

PC>ipconfig

IP Address......................: 20.0.0.2
Subnet Mask.....................: 255.0.0.0
Default Gateway.................: 20.0.0.1

PC>telnet 50.0.0.2
Trying 50.0.0.2 ...

User Access Verification

Password:
R2>

Now telnet it from any other pc apart from 20.0.0.2. it must be filter and denied

PC>ipconfig

IP Address......................: 20.0.0.3
Subnet Mask.....................: 255.0.0.0
Default Gateway.................: 20.0.0.1

PC>telnet 50.0.0.2
Trying 50.0.0.2 ...

% Connection refused by remote host


PC>
Configure Extended Access Lists

An extended ACL gives you much more power than just a standard ACL. Extended IP ACLs check
both the source and destination packet addresses. They can also check for specific protocols,
port numbers, and other parameters, which allow administrators more flexibility and control.

access-list access-list-number {permit | deny}


protocol source source-wildcard [operator port]
destination destination-wildcard [operator port]
[established] [log]

Command Parameters Descriptions


access-list Main command
Identifies the list using a number in the ranges of 100–199 or 2000–
access-list-number
2699.
permit | deny Indicates whether this entry allows or blocks the specified address.
protocol IP, TCP, UDP, ICMP, GRE, or IGRP.
source and destination Identifies source and destination IP addresses.
The operator can be lt (less than), gt (greater than), eq (equal to),
or neq (not equal to). The port number referenced can be either
source-wildcard and the source port or the destination port, depending on where in the
destination-wildcard ACL the port number is configured. As an alternative to the port
number, well-known application names can be used, such as
Telnet, FTP, and SMTP.
For inbound TCP only. Allows TCP traffic to pass if the packet is a
response to an outbound-initiated session. This type of traffic has
established
the acknowledgement (ACK) bits set. (See the Extended ACL with
the Established Parameter example.)
log Sends a logging message to the console.

Before we configure Extended Access list you should cram up some important port number

Well-Known Port Numbers and IP Protocols

Port Number IP Protocol


20 (TCP) FTP data
21 (TCP) FTP control
23 (TCP) Telnet
25 (TCP) Simple Mail Transfer Protocol (SMTP)
53 (TCP/UDP) Domain Name System (DNS)
69 (UDP) TFTP
80 (TCP) HTTP
In this article we will configure Extended access list. If you want to read the feature and
characteristic of access list reads this previous article.

Access control list

In this article we will use a RIP running topology. Which we created in RIP routing practical.

Three basic steps to configure Extended Access List

 Use the access-list global configuration command to create an entry in a Extended ACL.
 Use the interface configuration command to select an interface to which to apply the
ACL.
 Use the ip access-group interface configuration command to activate the existing ACL on
an interface.

With Access Lists you will have a variety of uses for the wild card masks, but typically For CCNA
exam prospective you should be able to do following:

1. Block host to host


2. Block host to network
3. Block Network to network
4. Block telnet access for critical resources of company
5. Limited ftp access for user
6. Stop exploring of private network from ping
7. Limited web access
8. Configure established keyword
Block host to host

Task

You are the network administrator at ComputerNetworkingNotes.com. Your company hire a


new employee and give him a pc 10.0.0.3. your company's critical record remain in 40.0.0.3. so
you are asked to block the access of 40.0.0.3 from 10.0.0.3. while 10.0.0.3 must be able connect
with other computers of network to perfom his task.

Decide where to apply ACL and in which directions.

As we are configuring Extended access list. With extended access list we can filter the packed as
soon as it genrate. So we will place our access list on F0/0 of Router1841 the nearest port of
10.0.0.3

To configure Router1841 (Hostname R1) double click on it and select CLI

R1>enable
R1#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
R1(config)#access-list 101 deny ip host 10.0.0.3 40.0.0.3 0.0.0.0
R1(config)#access-list 101 permit ip any any
R1(config)#interface fastEthernet 0/0
R1(config-if)#ip access-group 101 out
R1(config-if)#exit
R1(config)#

Verify by doing ping from 10.0.0.3 to 40.0.0.3. It should be reqest time out. Also ping other
computers of network including 40.0.0.2. ping shuld be sucessfully.

Block host to network

Task

Now we will block the 10.0.0.3 from gaining access on the network 40.0.0.0. ( if you are doing
this practical after configuring pervious example don't forget to remove the last access list 101.
With no access-list command. Or just close the packet tracer without saving and reopen it to be
continue with this example.)

R1(config)#access-list 102 deny ip host 10.0.0.3 40.0.0.0 0.255.255.255


R1(config)#access-list 102 permit ip any any
R1(config)#interface fastEthernet 0/0
R1(config-if)#ip access-group 102 out
R1(config-if)#exit
R1(config)#

Verify by doing ping from 10.0.0.3 to 40.0.0.3. and 40.0.0.2.It should be reqest time out. Also
ping computers of other network. ping shuld be sucessfully.

Once you have calculated the wild card mask rest is same as we did in pervious example
R2>enable
Enter configuration commands, one per line. End with CNTL/Z.
R2(config)#access-list 2 deny 10.0.0.0 0.255.255.255
R2(config)#access-list 2 permit any
R2(config)#interface fastethernet 0/1
R2(config-if)#ip access-group 2 out
R2(config-if)#

To test first do ping from 10.0.0.3 to 40.0.0.3 it should be request time out as this packet will
filter by ACL. Then ping 30.0.0.3 it should be successfully replay.

Network to Network Access List

Task

Student’s lab is configured on the network of 10.0.0.0. While management's system remain in
the network of 40.0.0.0. You are asked to stop the lab system from gaining access in
management systems

Now we will block the network of 10.0.0.0 from gaining access on the network 40.0.0.0. ( if you
are doing this practical after configuring pervious example don't forget to remove the last
access list 101. With no access-list command. Or just close the packet tracer without saving and
reopen it to be continue with this example.)

R1(config)#access-list 103 deny ip 10.0.0.0 0.255.255.255 40.0.0.0 0.255.255.255


R1(config)#access-list 103 permit ip any any
R1(config)#interface fastethernet 0/0
R1(config-if)#ip access-group 103 in
R1(config-if)#exit
R1(config)#

Verify by doing ping from 10.0.0.3 and 10.0.0.2 to 40.0.0.3. and 40.0.0.2.It should be reqest
time out. Also ping computers of other network. ping shuld be sucessfully.

Network to host

Task

For the final scenario you will block all traffic to 40.0.0.3 from the Network of 10.0.0.0 To
accomplish this write an extended access list. The access list should look something like the
following.

R1(config)#interface fastethernet 0/0


R1(config-if)#no ip access-group 103 in
R1(config-if)#exit
R1(config)#no access-list 103 deny ip 10.0.0.0 0.255.255.255 40.0.0.0 0.255.255.255
R1(config)#access-list 104 deny ip 10.0.0.0 0.255.255.255 40.0.0.3 0.0.0.0
R1(config)#access-list 104 permit ip any any
R1(config)#interface fastethernet 0/0
R1(config-if)#ip access-group 104 in
R1(config-if)#exit
R1(config)#

Verify by doing ping from 10.0.0.3 and 10.0.0.2 to 40.0.0.3.It should be reqest time out. Also
ping computers of other network. ping shuld be sucessfully.

Application based Extended Access list

In pervoius example we filter ip base traffic. Now we will filter applicaion base traffic. To do this
practical either create a topology as shown in figure and enable telnet and http and ftp service
on server or download this pre configured topology and load it in packet tracer.

Extended Access list

The established keyword

The established keyword is a advanced feature that will allow traffic through only if it sees that
a TCP session is already established. A TCP session is considered established if the three-way
handshake is initiated first. This keyword is added only to the end of extended ACLs that are
filtering TCP traffic.
You can use TCP established to deny all traffic into your network except for incoming traffic that
was first initiated from inside your network. This is commonly used to block all originating
traffic from the Internet into a company's network except for Internet traffic that was first
initiated from users inside the company. The following configuration would accomplish this for
all TCP-based traffic coming in to interface serial 0/0/0 on the router:

R1(config)#access-list 101 permit tcp any any established


R1(config)#interface serial 0/0/0
R1(config-if)#ip access-group 101 in
R1(config-if)#exit

Although the access list is using a permit statement, all traffic is denied unless it is first
established from the inside network. If the router sees that the three-way TCP handshake is
successful, it will then begin to allow traffic through.
To test this access list double click on any pc from the network 10.0.0.0 and select web brower.
Now give the ip of 30.0.0.2 web server. It should get sucessfully access the web page. Now go
30.0.0.2 and open command prompt. And do ping to 10.0.0.2 or any pc from the network the
10.0.0.0. it will request time out.

Stop ping but can access web server

We host our web server on 30.0.0.2. But we do not want to allow external user to ping our
server as it could be used as denial of services. Create an access list that will filter all ping
requests inbound on the serial 0/0/0 interface of router2.

R2(config)#access-list 102 deny icmp any any echo


R2(config)#access-list 102 permit ip any any
R2(config)#interface serial 0/0/0
R2(config-if)#ip access-group 102 in

To test this access list ping from 10.0.0.2 to 30.0.0.2 it should be request time out. Now open
the web browser and access 30.0.0.2 it should be successfully retrieve

Grant FTP access to limited user

You want to grant ftp access only to 10.0.0.2. no other user need to provide ftp access on
server. So you want to create a list to prevent FTP traffic that originates from the subnet
10.0.0.0/8, going to the 30.0.0.2 server, from traveling in on Ethernet interface E0/1 on R1.

R1(config)#access-list 103 permit tcp host 10.0.0.2 30.0.0.2 0.0.0.0 eq 20


R1(config)#access-list 103 permit tcp host 10.0.0.2 30.0.0.2 0.0.0.0 eq 21
R1(config)#access-list 103 deny tcp any any eq 20
R1(config)#access-list 103 deny tcp any any eq 21
R1(config)#access-list 103 permit ip any any
R1(config)#interface fastethernet 0/1
R1(config-if)#ip access-group 103 in
R1(config-if)#exit

Grant Telnet access to limited user

For security purpose you don’t want to provide telnet access on server despite your own
system. Your system is 10.0.0.4. create a extended access list to prevent telnet traffic that
originates from the subnet of 10.0.0.0 to server.

R1(config)#access-list 104 permit tcp host 10.0.0.4 30.0.0.2 0.0.0.0 eq 23


R1(config)#access-list 104 deny tcp 10.0.0.0 0.255.255.255 30.0.0.2 0.0.0.0 eq 23
R1(config)#access-list 104 permit ip any any
R1(config)#interface fast 0/1
R1(config-if)#ip access-group 104 in
R1(config-if)#exit
Assignment 2(a)

Features and characteristics of EIGRP


 It is a Cisco Proprietary routing protocol.
 It is based on IGRP Routing protocol.
 It is an enhanced version of IGRP (Interior Gateway Routing Protocol) protocol.
 In comparison of IGRP it provides faster convergence times, superior handling of routing
loops and improved scalability.
 It was released in 1994.
 It is a hybrid routing protocol.
 It has characteristics of both distance vector and link state protocols.
 It uses DUAL (Diffusing Update Algorithm) algorithm to select the best path.
 It uses RTP (Reliable Transport Protocol) to communicate with neighbors.
 It uses multicast for routing updates.
 It supports IP [Both IPv4 and IPV6], Apple Talk and IPX routed protocols.
 It includes subnet mask information in routing updates.
 It supports route summarization and discontiguous networks.
 It supports VLSM/CIDR.
 It supports load balancing across the six routes for a single destination.
 It supports trigger updates.

From introduction to till the preparation of this tutorial, EIGRP is ruling the world of routing
protocols. The only negative about EIGRP was Cisco kept this protocol as proprietary protocol.
In order to run this protocol, we had to buy all routers from Cisco. This thing was changed a
little in 2013 when partial functionality of EIGRP was converted in open standard. Now we can
also buy routers from other vendors along with Cisco, still running EIGRP on all routers.

Since EIGRP is hybrid protocol, it has advantages of both link state and distance vector protocol.
It uses composite metric calculation formula to select the best route for destination. It sends
partial or full update only when something is change in network. It maintains three tables for
ultra-fast convergence.

1. Neighbor Table
2. Topology Table
3. Routing Table

Neighbor Table

EIGRP shares routing information only with neighbors. To know who the neighbors are, it uses
neighbor table. When a new neighbor is discovered, EIGRP would add its address and interface
on which neighbor is connected in neighbor table. EIGRP uses separate neighbor table for each
routed protocol.

Topology Table
EIGRP uses this table to store all routes which it learned from neighbors. It contains a list of all
destinations and routes advertised by neighboring routers. EIGRP selects single best route for
each destination from this list. That route goes in routing table. Remaining routes are marked
as backup routes. EIGRP refers selected route as Successor and backup route as Feasible
Successor. EIGRP uses separate topology table for each routed protocol.

Routing Table

EIGRP stores single best (Successor) route for each destination in this table. Router uses this
table to forward the packet. There is a separate routing table for each routed protocol.

Protocol Dependent Modules

PDMs are the special feature of EIGPR. Through these modules EIGRP supports multiple
network layer protocols. It maintains separate tables for separate routed (Network Layer)
protocols. For example if you are using both (IPv4 and IPv6) versions of IP protocol, it will
maintain separate IPv4/EIGRP and IPv6/EIGRP tables.

Metric

EIGRP uses metric to select the best route from all available routes for destination. Metric has
five components.

 Bandwidth
 Load
 Delay
 Reliability
 MTU

From these only bandwidth and delay are by default enabled.

RTP

EIGRP uses RTP to communicate with other EIGRP speaking routers. RTP (Reliable Transport
Protocol) uses multicast and unicast to exchange the data with neighbors. It uses class D
address 224.0.0.10 for multicast. It keeps track of each multicast it sends out. EIGRP maintains a
list of the neighbors who have replied. If it doesn’t receive a reply from any neighbor, RTP will
resend the same data using unicast. It will make 16 unicast attempts before declaring neighbor
is dead.

DUAL

EIGRP uses DUAL (Diffusing Update Algorithm) to provide the fastest route convergence among
all protocols. Route convergence includes:-

 Selecting best route from all available routes


 Supporting VLSMs
 Dynamically recovering from route failure
 Finding an alternative route if primary route goes down

DUAL uses topology table along with RTP to accomplish above tasks in minimal time. As we
know EIGRP maintain a copy of all routes including neighbors in topology table, so it would be
the first place to look for an alternative route in a route failure situation. If EIGRP does not find
an alternative here, it will ask neighbors for help. If neighbors have any updates about asked
route, they will reply back with that information. This strong mechanism allows DUAL to find
and maintain the best routes for destination speedily.

Autonomous System

EIGRP shares routing information only with neighbors. In order to become a neighbor AS
number must be matched. AS create a logical boundary for route information. By default router
will not propagate route information outside the AS. For example a router which belongs to AS
number 10 will not share routing information with the router that belongs to AS number 20 or
any other AS numbers except AS number 10. For easy administration a large network may have
multiple ASes.

Not all routing protocols understand the concept of AS. Luckily EIGRP not only understand the
concept of AS but also supports multiple ASes. We can easily configure multiple AS instance
with EIGRP to divide a large network in smaller segments. By default EIGRP routers will not
share routing information between different AS.

Redistribution is used to exchange the route information between different ASes. When a route
is learned through the redistribution, it has higher AD value than its original source. For
example EIGRP has two AD values 90 for interior EIGRP and 170 for exterior EIGRP. Exterior
EIGRP means EIGRP instance which has different AS number.

Administrative Distance
In a complex network, we may have multiple routing protocols running simultaneously.
Different routing protocols use different metrics to calculate the best path for destination. In
this situation router may receive different routes information for a single destination network.
Routers use AD value to select the best path among these routes. Lower ad value has more
trustworthiness.

AD value Protocol / Source


0 Directly connected interface
0 or 1 Static route
90 EIGRP (Interior)
110 OSPF
120 RIP
170 EIGRP (Exterior)
255 Unknown source

Let’s understand it with a simple example; a router learned two different paths for 20.0.0.0/8
network from EIGRP Interior and EIGRP Exterior. Which one should it select?

Answer of this question is hidden in above table. Check the AD value of both protocols.
Administrative distance is the believability of routing protocols. Routers measure each route
source on a scale of 0 to 255. 0 is the best route. 255 is the worst, router will never use the
route learned by this source. In our question we have two protocols EIGRP Interior and EIGRP
Exterior. EIGRP Interior has lower AD value than EIGRP Exterior. So its route will be selected for
routing table.

That’s all for this part. In this part we covered basic terminology used in EIGRP routing protocol.
Essential configuration values
EIGRP Router doesn’t trust anyone blindly. It checks following configuration values to insure that
requesting router is eligible to become his neighbor or not.

1. Active Hello packets


2. AS Number
3. K-Values

Active Hello packets

EIGRP uses hello packets to maintain the neighborship between routers. It uses them for neighbor
discovery and recovery process. Hello packets are periodically sent from all active interfaces.

By default when we enable EIGRP routing, all interfaces (that meet network command criteria)
become participate of it. EIGRP allows us to exclude any interface from it.

Passive interface

passive-interface command is used to exclude an interface from EIGRP. Passive interface


command is a double edged sword. If used carelessly, it could bring entire network down. Once
you marked an interface as passive, EIGRP will never send a hello packet from it. And we know
that hello packet is first condition of EIGRP neighborship. In this situation EIGRP neighborship will
not take place on this interface. This could be critical if this interface is the only way to connect
with other routers. Making this interface as passive will close all possible doors to communicate
with those networks.

So our first condition that needs to be fulfilled in order to become an EIGRP neighbor is an active
interface generating hello packets. Two routers will become neighbors only when they see each
other's hello packets on a common network.

EIGRP sends hello packets from all active interfaces in hello interval. Hello interval is a time
duration that EIGRP takes between two hello packets. Default hello interval for high bandwidth
link is 5 seconds. For low bandwidth links, hello interval is 60 seconds.

 Ethernet, Token Ring, Point to Point serial links, HDLC leased lines are the examples of high
bandwidth link.
 Multipoint circuits, Multipoint ATM, Multipoint Frame Relay, ISDN and BRIs are the
example of low bandwidth links.

An EIGRP router must receive hello packets continuously from its neighbors. If it does not receive
hello packets from any neighbor in hold down time, it will mark that neighbor as dead.

Hold time is the time duration that an EIGRP router waits before marking a router dead without
receiving a hello packet from it. Typically hold down time is three times of hello interval. So for
high bandwidth link it would be 15 seconds and 180 seconds for slow bandwidth link. We can
adjust hold down time with ip hold-time eigrp command.
EIGRP uses multicast and unicast for hello packets delivery. It uses 224.0.0.10 IP address for
multicast. Since hello packets do not have any important routing information, they need not be
acknowledged.

Basically Hello packets perform two essential functions of EIGRP.

 Find another EIGRP router in network and help in building neighborship.


 Once neighborship is built, check continuously whether neighbor is alive or not.

Adjacency

Neighborship is referred as adjacency in EIGRP. So when you see New Adjacency in log, take it for
new neighborship. It indicates that a new neighbor is found and neighborship with it has been
established.

AS Number

An AS is a group of networks running under a single administrative control. This could be our
company or a branch of company. Just like Subnetting AS is also used to break a large network in
smaller networks.

AS creates a boundary for routing protocol which allow us to control how far routing information
should be propagated. Beside this we can also filter the routing information before sharing it with
other AS systems. These features enhance security and scalability of overall network.

Basically AS concept was developed for large networks. Routing protocols which were developed
for small networks such as RIP do not understand the concept of AS systems.

There are two types of routing protocols IGP and EGP.

 IGP (Interior Gateway Protocol) is a routing protocol that runs in a single AS such as RIP,
IGRP, EIGRP, OSPF and IS-IS.
 EGP (Exterior Gateway Protocol) is a routing protocol that performs routing between
different AS systems. Nowadays only BGP (Border Gateway Protocol) is an active EGP
protocol.

To keep distinguish between different autonomous systems, AS numbers are used. An AS number
start from 1 and goes up to 65535. Same as IP addresses, AS numbers are divided in two types;
Private and public.

 Public AS Numbers: - We only need to use public numbers if we connect our AS with
Internet backbone through the BGP routes. IANA (Numbers Authority) controls the public
AS numbers.
 Private AS Numbers: - Private AS numbers are used to break our internal network into the
smaller networks.
EIGRP routers that belong to different ASs don’t become neighbors therefore they don’t share any
routing information.

So our second condition that needs to be fulfilled in order to become EIGRP neighbor is the same
AS number. Two routers will become neighbors only when they see same AS number in each
other's hello packets.

K Values

EIGRP may use five metric components to select the best route for routing table. These are
Bandwidth, Load, Delay, Reliability and MTU. By default EIGRP uses only two components;
Bandwidth and delay. With K-Values we can control which components should be used in route
metric calculation. For five metric components we have five K values.

K Values Metric components


K1 Bandwidth
K2 Load
K3 Delay
K4 Reliability
K5 MTU

Two routers must use same K Values in order to become the EIGPR neighbor. For example if one
router is using three K- Values (K1, K2 and K3) while second router is using default K values (K1 and
K3) then these two routers will never become neighbor.

In order to become EIGRP neighbor two routers must use same K values.

EIGRP Neighbor Discovery process

Step 1:- First router R1 sends a hello packet from all active interfaces. This packet contains
essential configuration values which are required to be a neighbor.
Step 2:- Receiving router R2 will compare these values with its own configuration values. If both
necessary values match (AS number and K-values), it will reply with a routing update. This update
includes all routes information from its routing table excluding one route. The route which it
learned from the same interface that bring hello packet to it. This mechanism is known as split
horizon. It states that if a router receives an update for route on any interface, it will not
propagate same route information back to the sender router on same port. Split horizon is used to
avoid routing loops.

Step 3:- First router will receive R2’s routing update and sends an acknowledgement message back
to R2.

Step 4:- R1 will sync its EIGRP topology table with routing information that it received in routing
update. It will also send a routing update containing all route information from its routing
topology to R2.
Step 5:- R2 will respond with an acknowledgement message. It will also sync its EIGRP topology
table with routing information that it received in routing update.

At this point, the two routers have becomes neighbor. Now they will maintain this neighborship
with ongoing hello packets. If they see any change in network, they will update each other with
partial updates.

Partial update contains information only about the recent change.

That’s all for this part. In this part we explained how two routers become EIGRP neighbors.
K-Values and EIGRP Metrics
K-Values are the most confusing part of EIGRP. Usually newbies take K Values as EIGRP metric
components. K Values are not the metric components in them self. They are only the place holder
or influencer for actual metric components in metric calculation formula. So when we enable or
disable a K value, actually we enable or disable its associate metric component.

EIGRP uses four components out of five to calculate the routing metric.

K Value Component Description


K1 Bandwidth Lowest bandwidth of route
K2 Load Worst load on route based on packet rate
K3 Delay Cumulative interface delay of route
K4 Reliability Worst reliability of route based on keep alive
Smallest MTU in path [Not used in route
K5 MTU
calculation]

Bandwidth (K1)

Bandwidth is a static value. It will change only when we make some physical (layer1) changes in
route such as changing cable or upgrading link types. EIGPR picks lowest bandwidth from all outing
going interfaces of route to the destination network.

For example have a look on following figure.

We have two serial links. One has 56Kbps bandwidth and other has 128Kbps. So which one will be
selected?

Among these bandwidths EIGRP will pick 56Kbps for composite metric calculation formula.
You may surprise why it picks the lowest instead of the highest? Well picking the highest
bandwidth doesn’t give us a surety of equivalent bandwidth throughout the route. It’s a maximum
cap which means we will get its equivalent or lower bandwidth in this route.

While picking the lowest bandwidth gives us a guarantee of equivalent of higher bandwidth
throughout the route. Since this is the bottleneck of route.

For example have a look on following network

With highest bandwidth comparison

Highest bandwidth of Route1 (72Kbps)

Highest bandwidth of Route2 (64Kbps)

Which route provides better bandwidth?

72Kbps (Route1) > 64Kbps (Route2)

With this comparison Route1 will be selected.

With lowest bandwidth comparison

Lowest bandwidth of Route1 (28Kbps)

Lowest bandwidth of Route2 (56Kbps)

Which route provides better bandwidth?

56Kbps (Route2) > 28Kbps (Route1)

With this comparison Route2 will be selected.


Looking at lowest bandwidth gives us the actual idea of route.

Next logical question is how EIGRP determine the bandwidth?

EIGRP first looks at bandwidth command. If bandwidth is set through this command, EIGRP will use
it. If bandwidth is not set, it will use interface’s default bandwidth.

When we enable an interface, router automatically assign a bandwidth value to it based on its type.
For example serial interface has a default bandwidth value of 1544Kbps. Until we change this value
with bandwidth command, it will be used where it is required.

Let me clear one more thing about bandwidth. Changing default bandwidth with bandwidth
command does not change the actual bandwidth of interface. Neither default bandwidth nor
bandwidth set by bandwidth command has anything to do with actual layer one link bandwidth.

Then what purpose does this command solve?

This command is only used to influence the routing protocol which uses bandwidth in route
selection process such as EIGRP and OSPF.

Suppose we have two routes for single destination; Route1 and Route2. For some reason we want
to take Route1 instead of Route2. How will we influence default metric calculation to select the
Route1?

In starting of this article we talked about K-Values. K-Values allow us to influence the metric
calculation. K1 is associated with bandwidth. K1 gets its weight from interface’s default bandwidth
or bandwidth set through the bandwidth command. Changing default bandwidth with bandwidth
command will change the K1’s value in metric calculation formula.

So to take Route1, we will have to make its lowest bandwidth higher than Route2. This can be done
in two ways; either raise the lowest bandwidth of Route1 higher than Route2 or reduce the lowest
bandwidth of Route2 lower than Route1. Both can be done easily with bandwidth command.

Let’s understand this with a simple example. Following figure illustrate a simple EIGRP network.
In this network R0 has two routes to reach at 50.0.0.0/8 network.

1. Route1 (Via R0 – R1 – R2)


2. Route2 (Via R0 – R3 – R2)

EIGRP is configured on all routers and all links have default bandwidth.

Serial link has default bandwidth of 1544Kbps. Until we change bandwidth of any route, both
routes have equal lowest bandwidth.

Route1’s lowest bandwidth (1544Kbps) = Route2’s lowest bandwidth (1544Kbps)

Both routes are load balanced with equal cost value 2684416.
Ok, let’s change default bandwidth to see how bandwidth component influence the route metric.

Set bandwidth to 64Kbps (lower than default 1544Kbps) on R3’s serial 0/0/0 interface.

Route1’s lowest bandwidth (1544Kbps) > Route2’s lowest bandwidth (64Kbps)

Now Route1 has the higher lowest bandwidth so it would be selected.

Ok let’s change bandwidth at R3 again this time increase default bandwidth to 2800Kbps.

Route1’s lowest bandwidth (1544Kbps) = Route2’s lowest bandwidth (1544Kbps)


Both routes have equal lowest bandwidth. They will be load balanced.

Here I have question for you.

Why EIGRP load balanced between Route1 and Route2 while now Route2 has better bandwidth?

Because EIGRP uses the lowest bandwidth of route to calculate the path cost and that is still
1544Kbps.
Load (K2)

Load is a dynamic value that changes frequently. It is based on packet rate and bandwidth of
interface. It calculates the volume of traffic passing through the interface in comparison of
maximum capacity. It is expressed on a scale of 255 where 1 represent that an interface is empty
and 255 represent that an interface is fully utilized.

Since data flows from both directions, router maintains two separate metric counters;

 Txload for outgoing traffic


 Rxload for incoming traffic

If K2 is enabled, maximum Txload value will be used in composite metric calculation formula.

Delay (k3)

Delay reflects the time taken by a packet in crossing the interface. It is measured in fractions of
seconds. Like as bandwidth Cisco has implicit delay values for all interfaces based on the type of
interface hardware. For example a FastEthernet has default delay of 100 microseconds. Since it is a
static value, we can override it with delay command.

Delay can be set anywhere from 10 to 167,772,140 microseconds.

Default delay value or value set by delay command has nothing to do with the actual delay caused
by interface. Just like bandwidth, this value is also an influencer.

It is expressed in terms of tens of microseconds. To define a delay of 1000 microseconds, we need


to configure 100(1000/10) on interface. Output of show interface command will automatically
multiply it with ten before displaying.

Total delay is used in metric calculation formula.

Total delay = delay received from neighboring router + its own interface delay

EIGRP is an enhanced distance vector routing protocol. It also uses route poisoning, withdrawing
route, split horizon and poisoned reverse for loop free optimized network. For all these mentioned
techniques EIGRP use the maximum delay as the indication of the unreachable route. To denote
the unreachable route EIGRP uses the delay of 16,777,215 tens of the microseconds.

Reliability (K4)

Just like load, reliability is also a dynamic value. It compares all successfully received frames against
all received frames. 100% reliability indicates that all the frames which we received were good. We
don’t have any issue with physical link. If we have any issue with physical link, this value will be
decrease.
Reliability is expressed as the fraction of 255. 255 expresses 100% reliability while 0 represents 0%
reliability. If K4 is enabled in metric calculation formula, it will use minimal reliability.

MTU (K5)

MTU stands for maximum transmission unit. It is advertised with routing update but it does not
actively participate in metric calculation. EIGRP allows us to load balance between equal cost paths
(6 maximum, default set to 4). It is used when equal cost paths for same destination exceed the
number of allowed paths set from maximum-paths command. For example we set maximum
allowed paths for load balancing to 5 and metric calculates 6 equal cost paths for a single
destination. In this situation path with lowest MTU will be ignored.

EIGRP Metric Calculation Formula

EIGRP uses following formula to produce a single 32 bit metric:-

At first glance this formula looks like a complicated equation. But it is not as difficult as it sound.
Let’s make it easier.

As we know MTU (K5) is not actively participate in formula. So set its value to Zero. When K5 is
equal to 0 then [K5/ (K4 + reliability)] is defined to be 1.

By default EIGRP does not use dynamic values in metric. This will disable two more components;
load (K2) and reliability (K4).

Now only two static values remain in formula.

Use of default constants [K1 (Enabled), K2 (Disabled), K3 (Enabled), K4 (Disabled), K5 (Disabled not
used)] reduce our formula to:-

Metric = (BandwidthE + DelayE)*256.

Cisco uses following configuration values for Bandwidth and delay

BandwidthE = 107/ least bandwidth of route [Lowest bandwidth from all interfaces between source
and destination. Use interface default bandwidth wherever bandwidth is not set through the
bandwidth command]

ValueE = cumulative delay of route [Sum of all outgoing interface’s delay. Use interface default
delay, if not set through the delay command]

Putting these configuration values will make formula to look like this
Before we move further, let me explain why EIGRP keeps dynamic values disable by default.

Dynamic values change over the time. Enabling dynamic values will force EIGRP routers to calculate
metric all the time and send updates each other just because the load or reliability of an interface
has changed. This will create serious performance issue. To avoid such a situation EIGRP only
enables static values for metric calculation.

If we only enable static values for metric calculation, EIGRP will not recalculate the metric unless it
changed. Static values change only when a physical change occurred in network such as an
interface is down or router is dead. This will keep EIGRP nice and clean.

Let’s see this formula in action. Earlier in this tutorial we used an example topology to explain the
bandwidth component. Load that topology in packet tracer and run show ip route eigrp command
from privilege mode. We have four routes for three destination networks. One destination network
has two routes.

30.0.0.0/8

For this destination network metric cost is 2681856. Before we learn how this cost was calculated,
we need to understand some key points associated with formula.

 EIGRP picks the lowest bandwidth from all interfaces in route.


 EIGRP picks delay from all outgoing interfaces in route.
 show interface [interface] command of privilege mode will display the configured value of
metric components.
 While calculating the cost term least-bandwidth uses the unit of Kbps (Kilobits per second).
 show interface [interface] command list bandwidth in Kbps. So we can use listed bandwidth
in formula as it is.
 While calculating the cost term cumulative-delay uses the unit of tens of microseconds.
 show interface [interface] command list delay in microseconds. So we need to divide it with
10 before using it in formula.
 Any decimal value will be rounded back to the nearest integer before performing the rest of
the formula.

We have three serial interfaces between source and destination. So our first step is to find out the
value of bandwidth and delay.

We can use show interface command to know the values.

All interfaces have equal bandwidth so our least bandwidth would be 1544Kbps.

We have two outgoing interfaces between source and destination. Both have a default delay of
20000 microseconds so total delay would be 40000 microseconds. As we know this delay is in
microseconds and formula uses the unit of “tens of microseconds”. We need to divide 40000 with
10. So our cumulative delay would be 40000/10 = 4000.

Okay now we have least bandwidth (1544Kbps) and cumulative delay (4000) let’s put them in
formula
Metric = ((10000000/1544) +4000)*256

Metric = ((6476.6839) +4000)*256

As I said “Any decimal value will be rounded back to the nearest integer before performing the rest
of the formula.”

Before solving rest of the formula, convert decimal value back in positive integer.

Metric = ((6476) +4000)*256

Metric = (10476)*256

Metric = 10476*256

Metric = 2681856

Great! We have revealed the cost calculation method. Let’s do this calculation again for next route.

40.0.0.0/8

For this route we have lowest bandwidth 1544Kbps and cumulative delay of 4000(ten of
microseconds).

Let’s put these values in our formula

Metric = ((10000000/1544)+4000)*256

Metric = (6476 + 4000) * 256

Metric = 10476 * 256

Metric = 2681856
Fine, now we have only route left. Let’s figure out its cost also.

50.0.0.0/8

For this destination we have two routes. Both routes have equal least bandwidth and cumulative
delay. So naturally their cost will also be same. As we know EIGRP automatically load balance equal
cost routes and these routes have equal cost. So they both make their way to routing table.

Metric = ((10000000/1544) + 4010) * 256

Metric = (6476 + 4010) * 256

Metric = 10486 * 256

Metric = 2684416

This is how EIGRP calculates the route cost. In job life you will rarely need to calculate the route
cost manually
Configuration for EIGRP Routing Protocol
In this assignment we will see basic concepts of EIGRP such as Features and characteristics of
EIGRP, Neighbor Table, Topology Table, Routing Table, Protocol Dependent Modules, Metric,
RTP, DUAL, Autonomous System and Administrative Distance.

Also we we will see how two routers become EIGRP neighbor and maintain this neighborship. In
order to become an EIGRP neighbor, three essential configuration values must be matched.

EIGRP uses composite metric calculation formula to calculate the best path. Bandwidth,
reliability, delay, load and MTU are the components of formula. In this we explained these
components with formula in easy language with examples.

Create a topology as illustrate in following figure or download this pre-created topology.

Device Interface IP Configuration Connected with


PC0 Fa0/0 10.0.0.2/8 Router0’s Fa0/0
Router0 Fa0/0 10.0.0.1/8 PC0’s Fa0/0
Router0 Fa0/1 192.168.1.1/30 Router4’s Fa0/1
Router4 Fa0/1 192.168.1.2/30 Router0’s Fa0/1
Router4 Fa0/0 192.168.1.5/30 Router3’s F0/0
Router3 Fa0/0 192.168.1.6/30 Router4’s Fa0/0
Router3 Fa0/1 192.168.1.9/30 Router5’s Fa0/1
Router5 Fa0/1 192.168.1.10/30 Router3’s Fa0/1
Router5 Fa0/0 20.0.0.1/8 Serve0’s Fa0/0
Server Fa0/0 20.0.0.2/8 Router5’s Fa0/0
Router5 Se0/0/0 192.168.1.254/30 Router2’s Se0/0/0
Router2 Se0/0/0 192.168.1.253/30 Router5’s Se0/0/0
Router2 Se0/0/1 192.168.1.250/30 Router1’s Se0/0/1
Router1 Se0/0/1 192.168.1.249/30 Router2’s Se0/0/1
Router1 Se0/0/0 192.168.1.246/30 Router0’s Se0/0/0
Router0 Se0/0/0 192.168.1.245/30 Router1’s Se0/0/0

Assign IP address to PCs

Double click PC0 and click Desktop menu item and click IP Configuration. Assign IP address
10.0.0.2/8 to PC0.

Repeat same process for Server0 and assign IP address 20.0.0.2/8.

Assign IP address to interfaces of routers

Double click Router0 and click CLI and press Enter key to access the command prompt of
Router0.
Three interfaces FastEthernet0/0, FastEthernet0/1 and Serial0/0/0 of Router0 are used in this
topology. By default interfaces on router are remain administratively down during the start up.

We need to configure IP address and other parameters on interfaces before we could actually
use them for routing. Interface mode is used to assign the IP address and other parameters.
Interface mode can be accessed from global configuration mode. Following commands are used
to access the global configuration mode.

Router>enable
Router# configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#

From global configuration mode we can enter in interface mode. From there we can configure
the interface. Following commands will assign IP address on FastEthernet0/0 and
FastEthernet0/1.

Router(config)#interface fastEthernet 0/0


Router(config-if)#ip address 10.0.0.1 255.0.0.0
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface fastEthernet 0/1
Router(config-if)#ip address 192.168.1.1 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#

interface fastEthernet 0/0 command is used to enter in interface mode.

ip address 10.0.0.1 255.0.0.0 command will assign IP address to interface.

no shutdown command will bring the interface up.

exit command is used to return in global configuration mode.

Serial interface needs two additional parameters clock rate and bandwidth. Every serial cable
has two ends DTE and DCE. These parameters are always configured at DCE end.
We can use show controllers interface command from privilege mode to check the cable’s end.

Router#show controllers serial 0/0/0


Interface Serial0/0/0
Hardware is PowerQUICC MPC860
DCE V.35, clock rate 2000000
[Output omitted]

Fourth line of output confirms that DCE end of serial cable is attached. If you see DTE here
instead of DCE skip these parameters.

Now we have necessary information let’s assign IP address to serial interface.

Router# configure terminal


Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface serial 0/0/0
Router(config-if)#ip address 192.168.1.245 255.255.255.252
Router(config-if)#clock rate 64000
Router(config-if)#bandwidth 64
Router(config-if)#no shutdown
Router(config-if)#exit

Router#configure terminal Command is used to enter in global configuration mode.

Router(config)#interface serial 0/0/0 Command is used to enter in interface mode.

Router(config-if)#ip address 192.168.1.245 255.255.255.252 Command assigns IP address to


interface. For serial link we usually use IP address from /30 subnet.

Router(config-if)#clock rate 64000

In real life environment this parameter controls the data flow between serial links and need to
be set at service provider’s end. In lab environment we need not to worry about this value. We
can use any valid rate here.

Router(config-if)#bandwidth 64

Bandwidth works as an influencer. It is used to influence the metric calculation of EIGRP or any
other routing protocol which uses bandwidth parameter in route selection process.

Router(config-if)#no shutdown Command brings interface up.

Router(config-if)#exit Command is used to return in global configuration mode.

We will use same commands to assign IP addresses on interfaces of remaining routers. We


need to provided clock rate and bandwidth only on DCE side of serial interface. Following
command will assign IP addresses on interface of Router1.
Router1

Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface serial 0/0/0
Router(config-if)#ip address 192.168.1.246 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface serial 0/0/1
Router(config-if)#ip address 192.168.1.249 255.255.255.252
Router(config-if)#clock rate 64000
Router(config-if)#bandwidth 64
Router(config-if)#no shutdown
Router(config-if)#exit

We will use same commands to assign IP addresses on interfaces of remaining routers.

Router2

Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface serial 0/0/1
Router(config-if)#ip address 192.168.1.250 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface serial 0/0/0
Router(config-if)#ip address 192.168.1.253 255.255.255.252
Router(config-if)#clock rate 64000
Router(config-if)#bandwidth 64
Router(config-if)#no shutdown
Router(config-if)#exit

Router5

Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface fastEthernet 0/0
Router(config-if)#ip address 20.0.0.1 255.0.0.0
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface fastEthernet 0/1
Router(config-if)#ip address 192.168.1.10 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#
Router(config)#interface serial 0/0/0
Router(config-if)#ip address 192.168.1.254 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit

Router3

Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface fastEthernet 0/0
Router(config-if)#ip address 192.168.1.6 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface fastEthernet 0/1
Router(config-if)# ip address 192.168.1.9 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#

Router4

Router>enable
Router#configure terminal
Enter configuration commands, one per line. End with CNTL/Z.
Router(config)#interface fastEthernet 0/0
Router(config-if)#ip address 192.168.1.5 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#interface fastEthernet 0/1
Router(config-if)# ip address 192.168.1.2 255.255.255.252
Router(config-if)#no shutdown
Router(config-if)#exit
Router(config)#

Great job we have finished our half journey. Now routers have information about the networks
that they have on their own interfaces. Routers will not exchange this information between
them on their own. We need to implement EIGRP routing protocol that will insist them to share
this information.

To be on same track I have uploaded my practice topology on our server. Use this if you want to
skip the IP configuration part.

Configure EIGRP routing protocol

Enabling EIGRP is a two steps process:-

1. Enable EIGRP routing protocol from global configuration mode.


2. Tell EIGRP which interfaces we want to include.

For these steps following commands are used respectively.

Router(config)# router eigrp autonomous_system_#


Router(config-router)# network IP_network_# [subnet_mask]

Router(config)# router eigrp autonomous_system_#

This command will enable EIGRP routing protocol in router. We can use any ASN (Autonomous
System Number) from 1 to 65,535. In order to become EIGRP neighbors this number must be
same on all participates.

Router(config-router)# network IP_network_# [subnet_mask]

This command allows us to specify the local interfaces which we want to include in EIGRP.
Basically we define a range of addresses and router search for these addresses in local
interfaces. If match found EIGRP will be enabled on that interface. Once enabled, EIGRP will
starts advertising about the connected subnets with that interface.

We have two options while defining the range of addresses with network command

1. Without wildcard mask


2. With wildcard

Without wildcard

Choosing this option allows us to configure the classful network. This option is very
straightforward. All we need to do is, type the network ID with network command. For example
network 172.168.0.0 command will enable EIGRP on all interfaces which belong to network
172.168.0.0.

What if I type network number instead of network ID?

Well in this situation EIGRP will automatically convert it back to network ID in which this
network number is resides. For example 172.168.1.1 will be converted back in 172.168.0.0.
This creates another query. Why it will be converted in 172.168.0.0 instead of 172.168.1.0?

Answer of this question is hidden in classful configuration. In classful configuration EIGRP will
match network addresses with in default boundary. Consider following figure

We have four networks 172.168.1.0/24, 172.168.2.0/24, 172.168.3.0/24 and 172.168.4.0/24


Subnetted from single class B network 172.168.0.0/16. Classful configuration does not
understand the concept of Subnetting. In classful configuration all these networks belong to a
single network. Classful configuration works only with in default boundary of mask. Default
boundary of this address is 16 bits. So it will match only first 16 bits (172.168.x.y) of network
address.

If we want excludes serial interfaces from EIGRP, we need to configure network command with
more specific information.

With wildcard

In this option we provide wildcard mask along with network ID. Wildcard mask allows us to
match exact networks. With wildcard we are no longer limited with default boundaries. We can
match Subnetted networks as well as default networks.

For example we were tasked to exclude serial interfaces in above configuration. We can use a
wildcard mask of 0.0.0.255 to match the subnet mask of /24.

Router(config-router)# network 172.168.1.0 0.0.0.255


Router(config-router)# network 172.168.2.0 0.0.0.255

Above commands will ask router to match /24 bits of address instead of default /16 bits. Now
router will look for 172.168.1.x and 172.168.2.x network. Our serial interfaces have
172.168.3.0/24 and 172.168.4.0/24 networks which do not fall in these search criteria.
If you are unfamiliar with wildcard mask, I suggest you to read our tutorials on ACL where we
explained wildcard mask in detail with examples.

Until you learn wildcard mask, use subnet mask in the place of wildcard mask. Following
commands are also valid and do the same job by matching /24 bits of address.

Router(config-router)# network 172.168.1.0 255.255.255.0


Router(config-router)# network 172.168.2.0 255.255.255.0

Subnet mask is a substitute, not a replacement of wildcard mask. When we use Subnet mask,
router converts them in wildcard mask before searching for associated interfaces. We can look
in running configuration to know what exactly being used by router.

EIGRP configuration

Now we know the essential commands for configuration. Let’s implement them in our network.

Router0

Router(config)#router eigrp 20
Router(config-router)#network 10.0.0.0 0.0.0.255
Router(config-router)#network 192.168.1.244 0.0.0.3
Router(config-router)#network 192.168.1.0 0.0.0.3
Router(config-router)#

Router1

Router(config)#router eigrp 20
Router(config-router)#network 192.168.1.244 0.0.0.3
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.245 (Serial0/0/0) is up: new adjacency
Router(config-router)#network 192.168.1.248 0.0.0.3
Router(config-router)#

Router2

Router(config)#router eigrp 20
Router(config-router)#network 192.168.1.248 0.0.0.3
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.249 (Serial0/0/1) is up: new adjacency
Router(config-router)#network 192.168.1.252 0.0.0.3
Router(config-router)#

As I mentioned earlier, we can use both wildcard mask and subnet mask with network
command. We have used wildcard mask for above routers. In remaining routers we will use
subnet mask.

Router5

Router(config)#router eigrp 20
Router(config-router)#network 20.0.0.0 255.0.0.0
Router(config-router)#network 192.168.1.252 255.255.255.252
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.253 (Serial0/0/0) is up: new adjacency
Router(config-router)#network 192.168.1.8 255.255.255.252
Router(config-router)#

Router3

Router(config)#router eigrp 20
Router(config-router)#network 192.168.1.8 255.255.255.252
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.10 (FastEthernet0/1) is up: new
adjacency
Router(config-router)#network 192.168.1.4 255.255.255.252
Router(config-router)#
Router4

Router(config)#router eigrp 20
Router(config-router)#network 192.168.1.4 255.255.255.252
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.6 (FastEthernet0/0) is up: new
adjacency
Router(config-router)#network 192.168.1.0 255.255.255.252
Router(config-router)#
%DUAL-5-NBRCHANGE: IP-EIGRP 20: Neighbor 192.168.1.1 (FastEthernet0/1) is up: new
adjacency
Router(config-router)#

That’s it. Our network is ready to take the advantage of EIGRP routing. To verify the setup we
will use ping command. ping command is used to test the connectivity between two devices.
We have two routes between source and destination. tracert command is used to know the
route which is used to get the destination.

Access the command prompt of PC1 and use ping command to test the connectivity from
Server0. After that use tracert command to print the taken path.
Good going we have successfully implemented EIGRP routing protocol in our network. For cross
check we have uploaded a configured topology on our server. You can use this if not getting
same output.

EIGRP protocol automatically manages all routes for us. If one route goes down, it will
automatically switch to another available route. To explain this process more clearly we have
added one additional route in our network.

Currently there are two routes between PC0 and Server.

Route 1

PC0 <==> Router0 <==> Router4 <==> Router3 <==> Router5 <==> Server0

Route 2

PC0 <==> Router0 <==> Router1 <==> Router2 <==> Router5 <==> Server0

By default EIGRP uses the route that has low metric value. Our path separates from Router0, so
let’s see which route it takes to deliver the packet of 20.0.0.0 network. show ip route eigrp
command will list all available routes.
Output of show ip route eigrp Explained

D: - It indicates that route is learned by EIGRP. Cisco chose letter D for EIGRP, because letter E
was already taken by Exterior Gateway Protocol (EGP).

20.0.0.0/8: - It is our destination network.

90: - Administrative distance of EIGRP.

35840: - Is the metric value of this route calculated by EIGRP

Via 192.168.1.2: - IP address of the next hop.

00:01:01: - How long this route was learned (Age of route)

FastEthernet1: - Exit interface of this router to get the next hop.

You may wonder where Route2 is in this output. Well EIGRP puts only the best route in routing
table. Route2’s metric value is higher than Route1. Till route1 is available, it will not insert
route2 in routing table. When route1 is down, it will look for next possible route. If other routes
are available, it will replace current route with new route which has the lowest metric value.
We can watch this process live with debug eigrp fsm command. On debug process on Router0.

Router# debug eigrp fsm

Now suppose route1 is down. We can simulate this situation by removing the cable attached
between Router3 [Fa0/1] and Router5 [Fa0/1].

Okay our primary route went down. What will be happen now?
EIGRP will look in topology table for next available routes. If single alternative is available, it will
be selected. If multiple routes are available, it will select the route with the lowest metric value.

We can use show ip route eigrp command again to see the selected route.

Run tracert command again from PC0 to verify the change.


That’s all for this article. Before closing just do a quick recap of important commands.

EIGRP configuration commands cheat sheet

Command Description
Enable EIGRP with AS number 20. AS number must be
Router(config)#router eigrp 20
same on all routers to become EIGRP neighbor.
Router(config-router)#network Enable EIGRP on interfaces which belongs to network
10.10.0.0 10.0.0.0/8. [Classful implementation].
Enable EIGRP on interfaces which belongs to network
Router(config-router)#network
10.10.0.0/16. [Classless implementation – Wildcard mask
10.10.0.0 0.0.255.255
method].
Enable EIGRP on interfaces which belongs to network
Router(config-router)#network
10.10.0.0/16. [Classless implementation – Subnet mask
10.10.0.0 255.255.0.0
method].
Router(config-router)#no network Disable EIGRP on interfaces which belongs to network
10.10.0.0 10.0.0.0/8.
Router(config-router)#no network Disable EIGRP on interfaces which belongs to network
10.10.0.0 0.0.255.255 10.10.0.0/16.
Router(config-router)#no network Disable EIGRP on interfaces which belongs to network
10.10.0.0 255.255.0.0 10.10.0.0/16.
Enable/Disable K values used in metric calculation
formula.
Router(config-router) #metric Default values are tos=0, k1=1, k2=0, k3=1, k4=0, k5=0
weights tos k1 k2 k3 k4 k5 Tos(type of service), K1(bandwidth), K2(load), K3(delay),
K4(reliability), K5(MTU).
By default only K1 and K3 are enabled.
Router(config-router)#auto- Enable auto summarization feature of EIGRP. ( Default –
summary disable )
Router(config-router)#no auto-
Disable auto summarization feature of EIGRP.
summary
Router(config)#no router eigrp 20 Disable EIGRP routing process 20.
Set bandwidth to 64Kbps. Used to influence the metric
Router(config-if)#bandwidth 64
calculation.
Router#show ip eigrp neighbors Display the neighbor table in brief.
Router#show ip eigrp neighbors Display the neighbor table in detail. Used to verify
detail whether a neighbor is configured as stub router or not.
Router#show ip eigrp interfaces Display information about all EIGRP interfaces.
Router#show ip eigrp interfaces
Display information about a particular EIGRP interface.
serial 0/0
Display information about EIGRP interfaces running AS
Router#show ip eigrp interfaces 20
process 20.
Router#show ip eigrp topology Displays the topology table.
Displays the number and type of packets sent and
Router#show ip eigrp traffic
received.
Router#show ip route eigrp Display EIGRP route from routing table.
Displays the events or actions related to feasible
Router#debug eigrp fsm
successor metrics (FSM).
Router#debug eigrp packet Displays the events or actions related to EIGRP packets.
Turn off debug message related to feasible successor
Router#no debug eigrp fsm
metrics (FSM).
Router#no debug eigrp packet Turn off debug message related to EIGRP packets.
Assignment 3

UNIX Sockets

Problem Statement:.
UNIX Sockets: WAP program in C/C++ sockets API
a. TCP sockets
b. UDP sockets

Theory:
● Sockets are used for interprocess communication.
● Most of the interprocess communication follow a Client-Server
● Model, where client and server are two separate processes in itself.
● Server and Client exchange messages over the network through a common Socket API

Server Examples
• Web server (port 80)
• FTP server (20, 21)
• Telnet server (23)
• Mail server (25)

Client Examples
• Examples of client programs
– Web browsers, ftp, telnet, ssh

How does a client find the server?


● The IP address in the server socket address identifies the host
● The (well-known) port in the server socket address identifies the service, and thus
implicitly identifies the server process that performs that service.

Examples of well know ports


• Port 7: Echo server
• Port 23: Telnet server
• Port 25: Mail server
• Port 80: Web server

What is an API ?
API expands as Application Programming Interface.
A set of routines that an application uses to request and carry out lower-level services
performed by a computer's operating system.

What is a socket?
● An interface between application and network which is used for communication
between processes
● Once configured the application can
o pass data to the socket for network transmission
o receive data from the socket (transmitted through the network by some
other host)
● To the kernel, a socket is an endpoint of communication.
● To an application, a socket is a file descriptor that lets the application read/write
from/to the network.
● Clients and servers communicate with each by reading from and writing to socket
descriptors.
● Remember: All Unix I/O devices, including networks, are modeled as files.

Two essential types of sockets


SOCK_STREAM
● TCP
● connection-oriented
● reliable delivery
● in-order guaranteed
● bidirectional

SOCK_DGRAM
● UDP
● no notion of “connection” – app indicates dest. for each packet
● unreliable delivery
● no order guarantees
● can send or receive

Socket Primitives
socket()

The function socket() creates an endpoint for communication and returns a file descriptor for the
socket. socket() takes three arguments:

● domain, which specifies the protocol family of the created socket. For example:
o AF_INET for network protocol IPv4 or
o AF_INET6 for IPv6.
o AF_UNIX for local socket (using a file).
● type, one of:
o SOCK_STREAM (reliable stream-oriented service or Stream Sockets)
o SOCK_DGRAM (datagram service or Datagram Sockets)
o SOCK_SEQPACKET (reliable sequenced packet service), or
o SOCK_RAW (raw protocols atop the network layer).
● protocol specifying the actual transport protocol to use. The most common are
IPPROTO_TCP, IPPROTO_SCTP, IPPROTO_UDP, IPPROTO_DCCP. These protocols
are specified in file netinet/in.h. The value 0 may be used to select a default protocol from
the selected domain and type.

The function returns -1 if an error occurred. Otherwise, it returns an integer representing the
newly assigned descriptor.

Prototype:

● int socket(int domain, int type, int protocol)

bind()

bind() assigns a socket to an address. When a socket is created using socket(), it is only given a
protocol family, but not assigned an address. This association with an address must be performed
with the bind() system call before the socket can accept connections to other hosts. bind() takes
three arguments:

● sockfd, a descriptor representing the socket to perform the bind on.


● my_addr, a pointer to a sockaddr structure representing the address to bind to.
● addrlen, a socklen_t field specifying the size of the sockaddr structure.

Bind() returns 0 on success and -1 if an error occurs.

Prototype:

● int bind(int sockfd, const struct sockaddr *my_addr, socklen_t addrlen);

listen()

After a socket has been associated with an address, listen() prepares it for incoming connections.
However, this is only necessary for the stream-oriented (connection-oriented) data modes, i.e.,
for socket types (SOCK_STREAM, SOCK_SEQPACKET). listen() requires two arguments:

● sockfd, a valid socket descriptor.


● backlog, an integer representing the number of pending connections that can be queued
up at any one time. The operating system usually places a cap on this value.

Once a connection is accepted, it is dequeued. On success, 0 is returned. If an error occurs, -1 is


returned.

Prototype:

● int listen(int sockfd, int backlog);

accept()

When an application is listening for stream-oriented connections from other hosts, it is notified
of such events (cf. select() function) and must initialize the connection using the accept()
function. The accept() function creates a new socket for each connection and removes the
connection from the listen queue. It takes the following arguments:

● sockfd, the descriptor of the listening socket that has the connection queued.
● cliaddr, a pointer to a sockaddr structure to receive the client's address information.
● addrlen, a pointer to a socklen_t location that specifies the size of the client address
structure passed to accept(). When accept() returns, this location indicates how many
bytes of the structure were actually used.
The accept() function returns the new socket descriptor for the accepted connection, or -1 if an
error occurs. All further communication with the remote host now occurs via this new socket.

Datagram sockets do not require processing by accept() since the receiver may immediately
respond to the request using the listening socket.

Prototype:

● int accept(int sockfd, struct sockaddr *cliaddr, socklen_t *addrlen)

connect()

The connect() system call connects a socket, identified by its file descriptor, to a remote host
specified by that host's address in the argument list.

Certain types of sockets are connectionless, most commonly user datagram protocol sockets. For
these sockets, connect takes on a special meaning: the default target for sending and receiving
data gets set to the given address, allowing the use of functions such as send() and recv() on
connectionless sockets.

connect() returns an integer representing the error code: 0 represents success, while -1 represents
an error. Historically, in the BSD-derived systems, the state of a socket descriptor is undefined if
the call to connect() fails (as it is specified in the Single Unix Specification), thus, portable
applications should close the socket descriptor immediately and obtain a new descriptor with
socket(), in the case the call to connect() fails. [3]

Prototype:

● int connect(int sockfd, const struct sockaddr *serv_addr, socklen_t addrlen)

gethostbyname() and gethostbyaddr()

The gethostbyname() and gethostbyaddr() functions are used to resolve host names and addresses
in the domain name system or the local host's other resolver mechanisms (e.g., /etc/hosts
lookup). They return a pointer to an object of type struct hostent, which describes an Internet
Protocol host. The functions take the following arguments:

● name specifies the name of the host. For example: www.wikipedia.org


● addr specifies a pointer to a struct in_addr containing the address of the host.
● len specifies the length, in bytes, of addr.
● type specifies the address family type (e.g., AF_INET) of the host address.
The functions return a NULL pointer in case of error, in which case the external integer h_errno
may be checked to see whether this is a temporary failure or an invalid or unknown host.
Otherwise a valid struct hostent * is returned.

These functions are not strictly a component of the BSD socket API, but are often used in
conjunction with the API functions. Furthermore, these functions are now considered legacy
interfaces for querying the domain name system. New functions that are completely protocol-
agnostic (supporting IPv6) have been defined. These new function are getaddrinfo() and
getnameinfo(), and are based on a new addrinfo data structure.

Prototypes:

● struct hostent *gethostbyname(const char *name)


● struct hostent *gethostbyaddr(const void *addr, int len, int type)

Socket programming with TCP

Socket programming with UDP


Conclusion: TCP & UDP socket programs are studied and executed.

/**Mclient.c**/

#include"stdio.h"
#include"stdlib.h"
#include"sys/types.h"
#include"sys/socket.h"
#include"string.h"
#include"netinet/in.h"
#include"netdb.h"

#define PORT 5561


#define BUF_SIZE 2000

int main(int argc, char**argv) {


struct sockaddr_in addr, cl_addr;
int sockfd, ret;
char buffer[BUF_SIZE];
struct hostent * server;
char * serverAddr;

if (argc < 2) {
printf("usage: client < ip address >\n");
exit(1);
}

serverAddr = argv[1];
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) {
printf("Error creating socket!\n");
exit(1);
}
printf("Socket created...\n");

memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = inet_addr(serverAddr);
addr.sin_port = PORT;

ret = connect(sockfd, (struct sockaddr *) &addr, sizeof(addr));


if (ret < 0) {
printf("Error connecting to the server! : : %d\n",ret);
exit(1);
}
printf("Connected to the server @ %s\n",serverAddr);

memset(buffer, 0, BUF_SIZE);
printf("Enter your message(s): ");

while (fgets(buffer, BUF_SIZE, stdin) != NULL) {


ret = sendto(sockfd, buffer, BUF_SIZE, 0, (struct sockaddr *) &addr,
sizeof(addr));
if (ret < 0) {
printf("Error sending data!\n\t-%s", buffer);
}
ret = recvfrom(sockfd, buffer, BUF_SIZE, 0, NULL, NULL);
if (ret < 0) {
printf("Error receiving data!\n");
} else {
printf("Received: ");
fputs(buffer, stdout);
printf("\n");
}
}

return 0;
}

/**Mserver.c**/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <errno.h>

#define PORT 5561


#define BUF_SIZE 2000
#define CLADDR_LEN 100

char *itoaa(int val, int base);

int main()
{
struct sockaddr_in addr, cl_addr;
int sockfd, len, ret, newsockfd;
char buffer[BUF_SIZE];
pid_t childpid;
char clientAddr[CLADDR_LEN];
int num, rem, sum;
char *str;

sockfd = socket(AF_INET, SOCK_STREAM, 0);

if (sockfd < 0)
{
printf("Error creating socket!\n");
exit(1);
}

printf("Socket created...\n");

memset(&addr, 0, sizeof(addr));
addr.sin_family = AF_INET;
addr.sin_addr.s_addr = INADDR_ANY;
addr.sin_port = PORT;

ret = bind(sockfd, (struct sockaddr *) &addr, sizeof(addr));


if (ret < 0)
{
printf("Error binding!\n");
exit(1);
}
else
printf("Binding done...\n");

printf("Waiting for a connection...@ port no : %d\n",PORT );

listen(sockfd, 5);
for (;;) //infinite loop
{
len = sizeof(struct sockaddr_in);
newsockfd = accept(sockfd, (struct sockaddr
*)&cl_addr,(socklen_t *)&len);
if (newsockfd < 0)
{
printf("Error accepting connection!\n");
exit(1);
}
else
printf("Connection accepted from ");

inet_ntop(AF_INET, &(cl_addr.sin_addr), clientAddr,


CLADDR_LEN);

printf("Port %d of %s
Client\n",ntohs(cl_addr.sin_port),inet_ntoa(cl_addr.sin_addr));

if ((childpid = fork()) == 0) //creating a child process


{
close(sockfd);
//stop listening for new connections by the main process.
//the child will continue to listen.
//the main process now handles the connected client.

for (;;)
{
memset(buffer, 0, BUF_SIZE);

ret = recvfrom(newsockfd, buffer, BUF_SIZE, 0,


(struct sockaddr *) &cl_addr, (socklen_t *)&len);

if(ret < 0)
{
printf("Error receiving data!\n");
exit(1);
}
else
printf("Received data from Port No %d of
Client %s : %s\n ", ntohs(cl_addr.sin_port),clientAddr, buffer);

num=atoi(buffer);
sum=0;
while(num>0)
{
sum = sum + (num % 10);
num = num / 10;
}

strcat(buffer," = sum of digits = ");


str=itoaa(sum,10);
strcat(buffer,str);

ret = sendto(newsockfd, buffer, BUF_SIZE, 0,


(struct sockaddr *) &cl_addr, len);

if (ret < 0)
{
printf("Error sending data!\n");
exit(1);
}
else
printf("\tSent data to %s on Port No %d :
%s\n", clientAddr,ntohs(cl_addr.sin_port), buffer);

printf("-------------------------------------------
-----------------------------------------------------------------\n");
}
}
close(newsockfd);
}
return(0);
}

char *itoaa(int val, int base)


{
static char buf[32] = {0};

int i = 30;

for( ; val && i ; --i, val /= base)


buf[i]="0123456789abcdef"[val % base];

return &buf[i+1];
}

You might also like