CCS354 Network Security
CCS354 Network Security
AIM:
To use Data Encryption Standard (DES) Algorithm for a practical application like User Message
Encryption.
ALGORITHM:
1. Create a DES Key.
2. Create a Cipher instance from Cipher class, specify the following information and separated by a
slash (/).
a. Algorithm name
b. Mode (optional)
c. Padding scheme (optional)
3. Convert String into Byte[] array format.
4. Make Cipher in encrypt mode, and encrypt it with Cipher.doFinal() method.
5. Make Cipher in decrypt mode, and decrypt it with Cipher.doFinal() method.
PROGRAM:
DES.java
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
try{
System.out.println("Message Encryption Using DES Algorithm\n ------ ");
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher;
desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
byte[] text = "Secret Information ".getBytes();
System.out.println("Message [Byte Format] : " + text);
System.out.println("Message : " + new String(text));
byte[] textEncrypted = desCipher.doFinal(text);
System.out.println("Encrypted Message: " + textEncrypted);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[] textDecrypted = desCipher.doFinal(textEncrypted);
}catch(InvalidKeyException e){e.printStackTrace();
}catch(IllegalBlockSizeException e){e.printStackTrace();
}catch(BadPaddingException e){e.printStackTrace();
}
}
}
OUTPUT:
Message Encryption Using DES Algorithm
Result:
Thus the java program for DES Algorithm has been executed and output verifies successfully.
lOMoAR cPSD| 27765217
lOMoAR cPSD| 27765217
lOMoAR cPSD| 27765217
AIM:
To implement symmetric key Algorithms-Advanced Encryption Standard (AES) Algorithm for a
practical application.
ALGORITHM:
STEP 1: Import necessary libraries.
STEP 2: Define a class SymmetricKeyGenerator.
STEP 3: Create a method createAESKey() to generate an AES key.
STEP 4: Use SecureRandom to provide a secure random number.
STEP 5: Initialize a KeyGenerator with the AES algorithm and a key length of 256 bits.
STEP 6: Generate the secret key using keyGenerator.generateKey().
STEP 7: Print the generated key in hexadecimal format in the main method.
lOMoAR cPSD| 27765217
PROGRAM:
// Java program to generate
// a symmetric key
import java.security.SecureRandom;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.xml.bind.DatatypeConverter;
// Class to create a
// symmetric key
public class symmetric {public static final String AES = "AES";
// Function to create a secret key
public static SecretKey createAESKey()
throws Exception
{
// Creating a new instance of
// SecureRandom class.
SecureRandom securerandom = new SecureRandom();
// Passing the string to
// KeyGenerator
KeyGenerator keygenerator = KeyGenerator.getInstance(AES);
// Initializing the KeyGenerator
// with 256 bits.
keygenerator.init(256, securerandom);
SecretKey key = keygenerator.generateKey();
return key;
}
// Driver code
public static void main(String args[])
throws Exception
{
SecretKey Symmetrickey
= createAESKey();
System.out.println("Output");
System.out.print("The Symmetric Key is :"
+ DatatypeConverter.printHexBinary(
Symmetrickey.getEncoded()));
}
}
lOMoAR cPSD| 27765217
Output:
Result:
Thus the java program for DES Algorithm has been executed and output verifies successfully.
lOMoAR cPSD| 27765217
AIM:
To implement asymmetric key Algorithms-RSA Algorithm for a practical application.
ALGORITHM:
1. Import necessary libraries.
2. Define a class named Asymmetric in the package java_cryptography.
3. Declare a constant string RSA with the value "RSA."
4. Define a method named generateRSAKeyPair() that returns a KeyPair.
5. Inside the method:
6. Create a SecureRandom object for secure random number generation.
7. Create a KeyPairGenerator instance using the RSA algorithm.
8. Initialize the key pair generator with a key size of 2048 bits and the secure random object.
9. Generate and return the key pair using keyPairGenerator.generateKeyPair()
10. Define the main method.
11. Inside the main method:
12. Call the generateRSAKeyPair method to obtain an RSA key pair.
13. Print the public key in hexadecimal format using DatatypeConverter.printHexBinary.
14. Print the private key in hexadecimal format using DatatypeConverter.printHexBinary.
lOMoAR cPSD| 27765217
PROGRAM:
Output:
Result:
Thus the java program for RSA Algorithm has been executed and output verifies successfully.
lOMoAR cPSD| 27765217
AIM:
To implement the Diffie-Hellman Key Exchange algorithm for a given problem .
ALGORITHM:
PROGRAM:
DiffieHellman.java
class DiffieHellman {
public static void main(String args[]) {
int p = 23; /* publicly known (prime number) */
int g = 5; /* publicly known (primitive root) */
int x = 4; /* only Alice knows this secret */
int y = 3; /* only Bob knows this secret */
double aliceSends = (Math.pow(g, x)) % p;
double bobComputes = (Math.pow(aliceSends, y)) % p;
double bobSends = (Math.pow(g, y)) % p;
double aliceComputes = (Math.pow(bobSends, x)) % p;
double sharedSecret = (Math.pow(g, (x * y))) % p;
System.out.println("simulation of Diffie-Hellman key exchange algorithm\n-------------------------
");
System.out.println("Alice Sends : " + aliceSends);
System.out.println("Bob Computes : " + bobComputes);
System.out.println("Bob Sends : " + bobSends);
System.out.println("Alice Computes : " + aliceComputes);
System.out.println("Shared Secret : " + sharedSecret);
OUTPUT:
simulation of Diffie-Hellman key exchange algorithm
RESULT:
Thus the Diffie-Hellman key exchange algorithm has been implemented using Java Program and
theoutput has been verified successfully.
lOMoAR cPSD| 27765217
AIM:
To implement digital signature schemes.
ALGORITHM :
1. Import necessary libraries
2. Define main method with throws Exception
3. Create a Scanner object
4. Prompt user to enter some text and read it
5. Create a KeyPairGenerator instance using DSA
6. Initialize key pair generator with key size 2048 bits
7. Generate a KeyPair
8. Retrieve the private key from the KeyPair
9. Create a Signature object using "SHA256withDSA"
10. Initialize the signature with the private key
11. Convert the input message to bytes
12. Update the signature with the message bytes
13. Calculate the digital signature
14. Print the digital signature as a string
15. Handle exceptions appropriately in real-world application
lOMoAR cPSD| 27765217
PROGRAM:
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.PrivateKey;
import java.security.Signature;
import java.util.Scanner;
public class CreatingDigitalSignature {
public static void main(String args[]) throws Exception {
//Accepting text from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter some text");
String msg = sc.nextLine();
//Creating KeyPair generator object
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
//Initializing the key pair generator
keyPairGen.initialize(2048);
//Generate the pair of keys
KeyPair pair = keyPairGen.generateKeyPair();
//Getting the private key from the key pair
PrivateKey privKey = pair.getPrivate();
//Creating a Signature object
Signature sign = Signature.getInstance("SHA256withDSA");
//Initialize the signature
sign.initSign(privKey);
byte[] bytes = "msg".getBytes();
//Adding data to the signature
sign.update(bytes);
//Calculating the signature
byte[] signature = sign.sign();
lOMoAR cPSD| 27765217
Result:
Thus the java program for digital signature scheme algorithm has been executed and output
verified successfully.
lOMoAR cPSD| 27765217
Select a long packet anywhere in the middle of your trace whose protocol is listed as TCP. Expand
the TCP protocol section in the middle panel (by using the “+” expander or icon). All packets
except the initial HTTP GET and last packet of the HTTP response should be listed as TCP. Picking
a long packet ensures that we are looking at a download packet from the server to your computer.
Looking at the protocol lay- ers, you should see an IP block before the TCP block. This is because
the TCP segment is carried in an IP. We have shown the TCP block expanded in our figure.
As well as the above fields, there may be other informational lines that Wireshark provides to help
you interpret the packet. We have covered only the fields that are carried across the network.
Step 3: TCP Segment Structure
This drawing differs from the text drawing in the book in only minor respects:
The Header length and Flags fields are combined into a 2-byte quantity. It is not easy to
deter- mine their bit lengths with Wireshark.
The Urgent Pointer field is shown as dotted. This field is typically not used, and so does
not show up in Wireshark and we do not expect you to have it in your drawing. You can
notice its exist- ence in Wireshark, however, by observing the zero bytes in the segment
that are skipped over as you select the different fields.
The Options field is shown dotted, as it may or may not be present for the segments in your
trace. Most often it will be present, and when it is then its length will be a multiple of four
bytes.
The Payload is optional. It is present for the segment you viewed, but not present on an
Ack- only segment, for example.
Note, you can work out sizes yourself by clicking on a protocol block in the middle panel (the
block itself, not the “+” expander). Wireshark will highlight the corresponding bytes in the
packet in the lower panel, and display the length at the bottom of the window. You may
lOMoAR cPSD| 27765217
also use the overall packet size shown in the Length column or Frame detail block. See
below where a TCP packet of length 66 is highlighted.
Three-Way Handshake
To see the “three way handshake” in action, look for a TCP segment with the SYN flag on. These
are up at the beginning of your trace, and the packets that follow it (see below).
The SYN flag is noted in the Info column. You can also search for packets with the SYN flag on
using the
filter expression “tcp.flags.syn==1”. (See below)
lOMoAR cPSD| 27765217
Next, we wish to clear the display filter tcp.flags.syn==1 so that we can once again see all the
packets in our original trace. Do this by clearing the display filter as shown below.
Figure 11: Clearing the display filter TCP segment with SYN flag on
If you do this correctly, you should see the full trace. We are most interested in the first three packets.
established. As usual, time runs down the page, and lines across the page indicate segments.
Common Options include Maximum Segment Size (MSS) to tell the other side the largest segment
that can be received, and Timestamps to include information on segments for estimating the round
trip time. There are also Options such as NOP (No-operation) and End of Option list that serve to
format the Op- tions but do not advertise capabilities. You do not need to include these formatting
options in your an- swer above. Options can also be carried on regular segments after the
connection is set up when they play a role in data transfer. This depends on the Option. For
example: the MSS option is not carried on each packet because it does not convey new
information; timestamps may be included on each packet to keep a fresh estimate of the RTT; and
options such as SACK (Selective Acknowledgments) are used only when data is received out of
order.
Our TCP Options are Maximum Segment Size, Window Scale, SACK permitted, and Timestamps.
Each of these Options is used in both directions. There are also the NOP & End of Option List
formatting options.
Wireshark) but clearly depend on the resource that is fetched. You can tell that it is
around 1 MB long.
The RTT in the FIN exchange is like that in the SYN exchange, as it should be. Your
RTT will vary depending on the distance between the computer and server as before.
Step 6: FIN/RST Teardown
Finally, the TCP connection is taken down after the download is complete. This is typically done
with FIN (Finalize) segments. Each side sends a FIN to the other and acknowledges the FIN they
receive; it is simi- lar to the three-way handshake. Alternatively, the connection may be torn down
abruptly when one end sends a RST (Reset). This packet does not need to be acknowledged by the
other side.
Below is a picture of the teardown in your trace, starting from when the first FIN or RST is issued
until the connection is complete. It shows the sequence and ACK numbers on each segment.
Points to note:
The teardown is initiated by the computer; it might also be initiated by the server.
The teardown is abrupt – a single RST in this case, and then it is closed, which the
other end must accommodate.
The sequence and Ack numbers do not really matter here. They are simply the
(relative Wireshark) values at the end of the connection.
For this part, we are going to launch an older version of Wireshark called Wireshark legacy. You
do this by selecting the Wireshark legacy application as follows.
When it launches, you should open the trace-tcp file which is in your downloads folder from earlier.
lOMoAR cPSD| 27765217
You should then be presented with the same trace-tcp as used previously in this exercise.
The middle portion of the TCP connection is the data transfer, or download, in our trace. This is the
main event. To get an overall sense of it, we will first look at the download rate over time.
Under the Statistics menu select an “IO Graph” (as shown below).
You should end up with a graph like below. By default, this graph shows the rate of packets over
time. You might be tempted to use the “TCP Stream Graph” tools under the Statistics menu instead.
However, these tools are not useful for our case because they assume the trace is taken near the
computer send- ing the data; our trace is taken near the computer receiving the data.
Now we will tweak it to show the download rate with the changes given below
On the x-axis, adjust the tick interval and pixels per tick. The tick interval should be small
enough to see into the behavior over the trace, and not so small that there is no averaging.
0.1 seconds is a good choice for a several second trace. The pixels per tick can be adjusted
to make the graph wider or narrower to fill the window. Make this 10. See below.
On the y-axis, change the unit to be Bits/Tick. The default is Packet/Tick. By changing it,
we can easily work out the bits/sec throughput by taking the y-axis value and scaling as
appropriate, e.g., 10X for ticks of 0.1 seconds.
Add a filter expression to see only the download packets. So far we are looking at all of the
pack- ets. Assuming the download is from the usual web server port of 80, you can filter
for it with a filter of “tcp.srcport==80”. Don’t forget to press Enter, and you may need to
click the
“Graph” button to cause it to redisplay.
To see the corresponding graph for the upload traffic, enter a second filter in the next box.
Again assuming the usual web server port, the filter is “tcp.dstport==80”. After you press
Enter and click the Graph button, you should have two lines on the graph.
Our graph for this procedure is shown in the figure on next page. From it we can see the sample
down- load rate quickly increase from zero to a steady rate, with a bit of an exponential curve.
This is slow- start. The download rate when the connection is running is approximately 2.5 Mbps.
The upload rate is a steady, small trickle of ACK traffic. Our download also proceeds fairly steadily
until it is done. This is the ideal, but many downloads may display more variable behavior if, for
example, the available bandwidth varies due to competing downloads, the download rate is set by
the server rather than the network, or enough packets are lost to disrupt the transfer.
Note, you can click on the graph to be taken to the nearest point in the trace if there is a feature you
would like to investigate.
Try clicking on parts of the graph and watch where you are taken in the Wireshark trace window.
lOMoAR cPSD| 27765217
Inspect the packets in the download in the middle of your trace for these features:
You should see a pattern of TCP segments received carrying data and ACKs sent back to the server.
Typically, there will be one ACK every couple of packets. These ACKs are called Delayed ACKs. By
delaying for a short while, the number of ACKs is halved.
Since this is a download, the sequence number of received segments will increase; the ACK number
of subsequently transmitted segments will increase correspondingly.
Since this is a download, the sequence number of transmitted segments will not increase (after the initial
get). Thus the ACK number on received segments will not increase either.
Each segment carries Window information to tell the other end how much space remains in the buffer.
The Window must be greater than zero, or the connection will be stalled by flow control.
Note the data rate in the download direction in packets/second and bits/second once the TCP connec- tion is
running well is 250 packet/sec and 2.5 Mbps.
Our download packets are 1434 bytes long, of which 1368 bytes are the TCP payload carrying contents. Thus 95%
of the download is content.
The data rate in the upload direction in packets/second and bits/second due to the ACK packets is 120 packets/sec
and 60,000 bits/sec. We expect the ACK packet rate to be around half of the data packet rate for the typical pattern
of one delayed ACK per two data packets received. The ACK bit rate will be at least an order of magnitude
below the data bit rate as the packets are much smaller, around 60 bytes.
The Ack number tells the next expected sequence number therefore it will be X plus the number of TCP payload
bytes in the data segment.
lOMoAR cPSD| 27765217
PROGRAM:
import javax.net.ssl.*;
import java.io.*;
import java.security.KeyStore;
public class SecureServer {
public static void main(String[] args) {
try {
// Load the keystore
char[] keystorePassword = "password".toCharArray();
KeyStore keystore = KeyStore.getInstance("JKS");
keystore.load(new FileInputStream("server.keystore"), keystorePassword);
// Set up key manager factory
KeyManagerFactory kmf =
KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
kmf.init(keystore, keystorePassword);
// Set up trust manager factory
TrustManagerFactory tmf =
TrustManagerFactory.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(keystore);
// Set up SSL context
SSLContext context = SSLContext.getInstance("TLS");
context.init(kmf.getKeyManagers(), tmf.getTrustManagers(), null);
// Create SSLServerSocket
SSLServerSocketFactory sslServerSocketFactory = context.getServerSocketFactory();
SSLServerSocket serverSocket = (SSLServerSocket) sslServerSocketFactory.createServerSocket(9999);
// Wait for client connection
System.out.println("Waiting for client connection...");
SSLSocket clientSocket = (SSLSocket) serverSocket.accept();
System.out.println("Client connected.");
// Input and output streams for secure communication
BufferedReader reader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
PrintWriter writer = new PrintWriter(clientSocket.getOutputStream(), true);
// Read a message from the client
lOMoAR cPSD| 27765217
Result:
Thus the java program to check message integrity and confidentiality has been executed and output
is verified successfully.
lOMoAR cPSD| 27765217
MITM attacks
Step 1: Clone the official Xerosploit repository from Github using the git clone command.
git clone https://github.com/LionSec/xerosploit
Step 2: Change the directory to xerosploit using the cd command. and then install the xerosploit.
sudo cd xerosploit
sudo python install.py
lOMoAR cPSD| 27765217
Step
3: Install it’s all dependencies using the following command:
sudo apt install nmap hping3 build-essential ruby-dev libpcap-dev libgmp3-dev
Step 6: Use the commands for various purposes like scanning the network use the below command.
scan
Step 7: Select the target and run the module you want to execute.
lOMoAR cPSD| 27765217
lOMoAR cPSD| 27765217
Step 4 − Open up the terminal and type “Ettercap –G” to start the graphical version of Ettercap.
Step 5 − Now click the tab “sniff” in the menu bar and select “unified sniffing” and click OK to select the interface.
We are going to use “eth0” which means Ethernet connection.
lOMoAR cPSD| 27765217
Step 6 − Now click the “hosts” tab in the menu bar and click “scan for hosts”. It will start scanning the whole
network for the alive hosts.
Step 7 − Next, click the “hosts” tab and select “hosts list” to see the number of hosts available in the network. This
list also includes the default gateway address. We have to be careful when we select the targets.
Step 8 − Now we have to choose the targets. In MITM, our target is the host machine, and the route will be the
router address to forward the traffic. In an MITM attack, the attacker intercepts the network and sniffs the packets.
So, we will add the victim as “target 1” and the router address as “target 2.”
In VMware environment, the default gateway will always end with “2” because “1” is assigned to the physical
machine.
Step 9 − In this scenario, our target is “192.168.121.129” and the router is “192.168.121.2”. So we will add target 1
as victim IP and target 2 as router IP.
lOMoAR cPSD| 27765217
Step 10 − Now click on “MITM” and click “ARP poisoning”. Thereafter, check the option “Sniff remote
connections” and click OK.
Step 11 − Click “start” and select “start sniffing”. This will start ARP poisoning in the network which means we
have enabled our network card in “promiscuous mode” and now the local traffic can be sniffed.
Note − We have allowed only HTTP sniffing with Ettercap, so don’t expect HTTPS packets to be sniffed with this
process.
Step 12 − Now it’s time to see the results; if our victim logged into some websites. You can see the results in the
toolbar of Ettercap.
lOMoAR cPSD| 27765217
ManageEngine is a leading producer of IT network infrastructure monitoring and management solutions. EventLog
Analyzer is part of the company’s security products. This is a HIDS that focuses on managing and analyzing log
files generated by standard applications and operating systems. The tool installs on Windows Server or Linux. It
gathers data from those operating systems and also from Mac OS, IBM AIX, HP UX, and Solaris systems. The
logs from Windows systems include sources from Windows Server Windows Vista and above and the Windows
DHCP Server.
Key Features:
FIREWALL
Configuring Firewall Defender on Windows:
Step 1: Launch Start from the taskbar.
Step 2: Search “Settings” in the search bar if you do not find the Settings icon in Start menu.
lOMoAR cPSD| 27765217
Step 6: Now Window’s Security window will pop up window’s. Here you can verify whether your Defender
firewall is active or not.
Step 7: Now to configure the firewall according to your requirement, click Advanced settings. You will be
prompted by User Account Control to give Administrative access to Windows Defender to make changes.
Click Yes to proceed.
Step 8: Windows Defender Firewall with Advanced Security window will launch after giving administrative
permission.
lOMoAR cPSD| 27765217
Step 11: Now we will configure an inbound rule for a network port. A New Inbound Rule Wizard window
pops-up, select Port option and click next.
lOMoAR cPSD| 27765217
Step 12: Now select TCP and specify port number 65000.
lOMoAR cPSD| 27765217
Step 13: Now we can select the action we need to take on this port. We will block the inbound connection by
selecting Block the connection option then click Next.
lOMoAR cPSD| 27765217
Step 14: Here we can specify when should this rule come into action. We will keep only Public option selected
and move Next.
lOMoAR cPSD| 27765217
Step 15: This is the last step. Here we provide a name to this rule so that we can keep track of it later in the
Inbound rules list. Write the name “65000 Port Block (Public)”. Click Finish.
lOMoAR cPSD| 27765217
Step 16: The inbound rule is successfully created. We can find “65000 Port Block (Public)” in the Inbound
rules list.
Step 17: Right-click the rule we just created and there are multiple options with which it can
be Disabled or Deleted.
lOMoAR cPSD| 27765217
VPN:
1. On the client computer, confirm that the connection to the Internet is correctly configured.
2. Click Start > Control Panel > Network Connections. Click Create a new connection under Network
Tasks, and then click Next.
3. Click Connect to the network at my workplace to create the dial-up connection. Click Next to continue.
4. Click Virtual Private Network connection, and then click Next.
5. Type a descriptive name for this connection in the Company name dialog box, and then click Next.
6. Click Do not dial the initial connection if the computer is permanently connected to the Internet. If the
computer connects to the Internet through an Internet Service Provider (ISP), click Automatically dial this
initial connection, and then click the name of the connection to the ISP. Click Next.
7. Type the IP address or the host name of the VPN server computer (for example,
VPNServer.SampleDomain.com).
8. Click Anyone's use if you want to permit any user who logs on to the workstation to have access to this dial-
up connection. Click My use only if you want this connection to be available only to the currently logged-on
user. Click Next.
9. Click Finish to save the connection.
10. Click Start > Control Panel > Network Connections.
11. Double-click the new connection.
12. Click Properties to continue to configure options for the connection. To continue to configure options for the
connection, follow these steps:
If you're connecting to a domain, click the Options tab, and then click to select the Include Windows
logon domain check box to specify whether to request Windows Server 2003 logon domain information
before trying to connect.
If you want the connection to be redialed if the line is dropped, click the Options tab, and then click to
select the Redial if line is dropped check box.
lOMoAR cPSD| 27765217