You are on page 1of 60

Labs

Contact: Prof Bill Buchanan


Email:

w.buchanan@napier.ac.uk

Room:

C.63
263

Week
2

Date
14/09/09

Academic
1: Security Fundamentals

21/09/09

2: IDS

28/09/09

3: Encryption

Lab/Tutorial
Lab 1: Packet Capture
Lab 2: Packet Capture (Filter)
Lab 3: Packet Capture (IDS)
Lab 4: Packet Capture (IDS ARP)
Lab 5: IDS Snort 1

05/10/09

4: Authentication (Part 1)

Lab 6: IDS Snort 2

12/10/09

4: Authentication (Part 2)

Lab 7: Private-key Encryption

19/10/09

26/10/09

5: Software Security

Lab 9: Log/Process/Hashing

02/11/09

6: Network Security

10

09/11/09

7: Forensic Computing

Lab 10: TCP Forensics


Lab 11: Binary Analysis/Sig Detetction
Lab 12: Signature Analysis
Lab 13: Role-based Security

11

16/11/09

Professional Certification

12
13
14
15

23/11/09
30/11/09
07/12/09
14/12/09

Professional Certification

Lab 8: Public-key Encryption

264

Week 2
Week
1

Date

Teaching

Attended

Lab 1: Packet Capture


Lab 2: Packet Capture (Filter)
Aim: The aim of the first labs and exercises is to use WinPCap to capture and display data
packets. These can be used to create network monitors and in agent-based intrusion
detection systems.
Time to complete:
4 hours (Two supervised hours in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 1: Packet Capture.
Complete Lab 2: Packet Capture (Filtering).
Complete Exercise 1.16.5 (Unit of Unit 1).
Complete Exercise 1.16.6 (End of Unit 1).
If you have time, complete Exercise 1.16.7 (End of Unit 1).
NetworkSims: CCNA Challenge A1-A10.
Learning activities:
At the end of these activities, you should understand:

How to capture data packets from the network.


How to filter the data packets.

Reflective statements (end-of-exercise):


Do you understand how to determine the network connections on a host, and to select the
one required?
Do you know how to add the WinPCap DLL to a solution?
What filter would be applied to detect all secure FTP traffic (Web research required)?
How would use detect IPSec traffic on the network (Web research required)?
What limitations might WinPCap have when capturing data packets?
Source code used:
http://buchananweb.co.uk/WinPCap1.zip
http://buchananweb.co.uk/WinPCap2.zip

265

Packet Capture (Network Interface)

Lab 1:
Details
Aim:

To provide a foundation in reading data packets

Activities
If Visual Studio is installed on your machine, download the following solution [1]:
http://buchananweb.co.uk/WinPCap1.zip
It has the following code [1]:
using System;
using Tamir.IPLib;
namespace NapierCapture
{
public class ShowDevices
{
public static void Main(string[] args)
{
string verWinPCap =null;
int count=0;
verWinPCap= Tamir.IPLib.Version.GetVersionString();
PcapDeviceList getNetConnections = SharpPcap.GetAllDevices();
Console.WriteLine("WinPCap Version: {0}", verWinPCap);
Console.WriteLine("Connected devices:\r\n");
foreach(PcapDevice net in getNetConnections)
{
Console.WriteLine("{0}) {1}",count,net.PcapDescription);
Console.WriteLine("\tName:\t{0}",net.PcapName);
Console.WriteLine("\tMode:\t\t\t{0}",net.PcapMode);
Console.WriteLine("\tIP Address: \t\t{0}",net.PcapIpAddress);
Console.WriteLine("\tLoopback: \t\t{0}",net.PcapLoopback);
Console.WriteLine();
count++;
}
Console.Write("Press any <RETURN> to exit");
Console.Read();
}
}
}

Run the program, and verify that it produces a list of the available network cards, such
as:
WinPCap Version: 1.0.2.0
Connected devices:
0) Realtek RTL8169/8110 Family Gigabit Ethernet NIC
(Microsoft's Packet Scheduler)
Name:
\Device\NPF_{A22E93C1-A78D-4AFE-AD2B-517889CE42D7}

266

Mode:
IP Address:
Loopback:

Capture
192.168.2.1
False

1) Intel(R) PRO/Wireless 2200BG Network Connection (Microsoft's Packet Scheduler)


Name:
\Device\NPF_{044B069D-B90A-4597-B99E-A68C422D5FE3}
Mode:
Capture
IP Address:
192.168.1.101
Loopback:
False

List the network cards in your machine:

Next update the code so that it displays the information on the network connections [1]:
foreach(PcapDevice net in getNetConnections)
{
Console.WriteLine("{0}) {1}",count,net.PcapDescription);
NetworkDevice netConn = (NetworkDevice)net;
Console.WriteLine("\tIP Address:\t\t{0}",netConn.IpAddress);
Console.WriteLine("\tSubnet Mask:\t\t{0}",netConn.SubnetMask);
Console.WriteLine("\tMAC Address:\t\t{0}",netConn.MacAddress);
Console.WriteLine("\tDefault Gateway:\t{0}",netConn.DefaultGateway);
Console.WriteLine("\tPrimary WINS:\t\t{0}",netConn.WinsServerPrimary);
Console.WriteLine("\tSecondary WINS:\t\t{0}",netConn.WinsServerSecondary);
Console.WriteLine("\tDHCP Enabled:\t\t{0}",netConn.DhcpEnabled);
Console.WriteLine("\tDHCP Server:\t\t{0}",netConn.DhcpServer);
Console.WriteLine("\tDHCP Lease Obtained:\t{0}",netConn.DhcpLeaseObtained);
Console.WriteLine("\tDHCP Lease Expires:\t{0}",netConn.DhcpLeaseExpires);
Console.WriteLine();
count++;
}

A sample run shows the details of the network connections [1]:


1) Intel(R) PRO/Wireless 2200BG
IP Address:
Subnet Mask:
MAC Address:
Default Gateway:
Primary WINS:
Secondary WINS:
DHCP Enabled:
DHCP Server:
DHCP Lease Obtained:
DHCP Lease Expires:

Network Connection (Microsoft's Packet Scheduler)


192.168.1.101
255.255.255.0
0015003402F0
192.168.1.1
0.0.0.0
0.0.0.0
True
192.168.1.1
03/01/2006 10:44:40
04/01/2006 10:44:40

List the details of the connections on your PC:

[1]

This code is based on the code wrapper for WinPCap developed by T.Gal
[http://www.thecodeproject.com/csharp/sharppcap.asp].

267

Lab 2:

Packet Capture (Filtering)

Details
Aim:

To provide an understanding of events in reading data packets

Activities
Using the previous solution from Lab 1, update with the following code [1]. In this case
the 2nd connection is used (getNetConnections[1]) in a promiscuous mode - change, as
required, depending on your network connection). USE THE CONNECTION WHICH
IS THE ETHERNET CONNECTION.
http://buchananweb.co.uk/WinPCap2.zip
using System;
using Tamir.IPLib;
using Tamir.IPLib.Packets;
namespace NapierCapture
{
public class CapturePackets
{
public static void Main(string[] args)
{
PcapDeviceList getNetConnections = SharpPcap.GetAllDevices();
// network connection 1 (change as required)
NetworkDevice netConn = (NetworkDevice)getNetConnections[1];
PcapDevice device = netConn;
// Define packet handler
device.PcapOnPacketArrival +=
new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);
//Open the device for capturing
//true -- means promiscuous mode
//1000 -- means a read wait of 1000ms
device.PcapOpen(true, 1000);
Console.WriteLine("Network connection: {0}", device.PcapDescription);
//Start the capturing process
device.PcapStartCapture();
Console.Write("Press any <RETURN> to exit");
Console.Read();
device.PcapStopCapture();
device.PcapClose();
}
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
Console.WriteLine("{0}:{1}:{2},{3} Len={4}",time.Hour, time.Minute,
time.Second, time.Millisecond, len);
}
}
}

268

Run the program, and produce some network traffic and versify that it is capturing
packets, such as:
13:17:56,990 Len=695
13:17:57,66 Len=288
13:17:57,68 Len=694
13:18:4,363 Len=319
13:18:4,364 Len=373
13:18:4,364 Len=371
13:18:4,365 Len=375
13:18:4,366 Len=367

Did it capture packets?

Yes/No

Update the code with a filter. In the following case an IP and TCP filter is used [1]:
device.PcapOpen(true, 1000);
Console.WriteLine("Network connection: {0}", device.PcapDescription);
string filter = "ip and tcp";
//Associate the filter with this capture
device.PcapSetFilter( filter );
//Start the capturing process
device.PcapStartCapture();

Generate some data traffic, such as loading a Web page, and show that the
program is capturing the data packets.
Did it capture packets?

Yes/No

Next update the filter so that it only captures ICMP packets, such as:
string filter = "icmp";

Generate some data traffic, and prove that it does not capture the packets. Now
ping a node on your network, such as:
Ping 192.168.1.102

And prove that it captures the data packets, such as:


13:40:47,761
13:40:48,756
13:40:48,759
13:40:49,757
13:40:49,760
13:40:50,757

Len=74
Len=74
Len=74
Len=74
Len=74
Len=74

269

Did it capture ICMP packets?

[1]

Yes/No

This code is based on the code wrapper for WinPCap developed by T.Gal
[http://www.thecodeproject.com/csharp/sharppcap.asp].

270

Week 3
Week

Date

Teaching

Attended

Lab 3: Packet Capture (IDS)


Lab 4: Packet Capture (IDS ARP)
Aim: The aim of these labs and exercises are to use WinPCap to create an agent-based IDS,
while building a foundation for the understanding of ARP, IP, TCP, and application layer
protocols.
Time to complete:
4 hours (Two supervised hours in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 3: Packet Capture (IDS)
Complete Lab 4: Packet Capture (ARP detection)
CCNA Challenge A11-A20
Learning activities:
At the end of these activities, you should understand:

How to detect application layer protocols.


How to filter for packet content.

Reflective statements (end-of-exercise):


Do you understand the difference between Ethernet, IP, TCP and the application layer
protocols?
Do you understand the way the TCP ports are used, such as for a server port and a client
port?
Source code used:
http://buchananweb.co.uk/WinPCap3.zip
http://buchananweb.co.uk/WinPCap4.zip

271

Packet Capture (IDS)

Lab 3:
Details
Aim:

To provide define the usage of an intrusion detection system

Activities
1.

The WinPcap library can be used to read the source and destination IP
addresses and TCP ports. For this the TCPPacket class is used. Initially
modify the program in Lab 2 so that it now displays the source and
destination IP and TCP ports [1]:

http://buchananweb.co.uk/WinPCap3.zip
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if(packet is TCPPacket)
{
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
TCPPacket tcp = (TCPPacket)packet;
string srcIp = tcp.SourceAddress;
string dstIp = tcp.DestinationAddress;
int srcPort = tcp.SourcePort;
int dstPort = tcp.DestinationPort;
Console.WriteLine("{0}:{1} -> {2}:{3}", srcIp, srcPort, dstIp, dstPort);
}
}

A sample run, using a Web browser connected to google.com gives:


84.53.143.151:80 -> 192.168.1.101:3582
84.53.143.151:80 -> 192.168.1.101:3582
192.168.1.101:3582 -> 84.53.143.151:80

Where it can be seen that the WWW server TCP port is 80, and the local port
is 3582. Run the program, and generate some network activity, and
determine the output.
Determine the output of the test run:

2.

Modify the program in Part 1, so that it only displays traffic which is destined
for a Web server. Prove its operation.

How was the code modified:

272

3.

Next modify the code so that it detects only ICMP packets (using the
ICMPPacket class), and displays the source and the destination addresses,
along with the TTL (time-to-live) value [1]:
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if(packet is ICMPPacket)
{
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
ICMPPacket icmp = (ICMPPacket)packet;
string srcIp=icmp.DestinationAddress;
string dstIp=icmp.SourceAddress;
string ttl=icmp.TimeToLive.ToString();
Console.WriteLine("{0}->{1} TTL:{2}", srcIp, dstIp, ttl);
}
}

A sample run is shown next for a ping on node 192.168.1.102:


Press any <RETURN> to exit
192.168.1.101->192.168.1.102 TTL:128
192.168.1.102->192.168.1.101 TTL:128
192.168.1.101->192.168.1.102 TTL:128

Run the program, and ping a node on the network. What is the output, and why does
it show three responses for every ping:

4.

Modify the program in Part 3, so that it displays the Ethernet details of the
data frame, such as [4]:
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if( packet is EthernetPacket )
{
EthernetPacket etherFrame = (EthernetPacket)packet;
Console.WriteLine("At: {0}:{1}: MAC:{2} -> MAC:{3}",
etherFrame.PcapHeader.Date.ToString(),
etherFrame.PcapHeader.Date.Millisecond,
etherFrame.SourceHwAddress,
etherFrame.DestinationHwAddress);
}
}

5.

It is possible to read the contents of the data package by converting it to a


byte array (using the Data property), and then convert it to a string, such as:
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if(packet is TCPPacket)
{
DateTime time = packet.PcapHeader.Date;

273

int len = packet.PcapHeader.PacketLength;


TCPPacket tcp = (TCPPacket)packet;
byte [] b = tcp.Data;
System.Text.ASCIIEncoding format = new System.Text.ASCIIEncoding();
string s = format.GetString(b);
s=s.ToLower();
if (s.IndexOf("intel")>0) Console.WriteLine("Intel found...");
}
}

The above code detects the presence of the word Intel in the data packet. Run
the program, and then load a site with the word Intel in it, and prove that it
works, such as for:

Intel found...
Intel found...

Did the code work:

274

6.

It is then possible to filter for source and destination ports, and with source and
destination addresses. For example, the following detects the word Intel on the
destination port of 80:
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if (packet is TCPPacket)
{
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
TCPPacket tcp = (TCPPacket)packet;
int destPort = tcp.SourcePort;
byte [] b = tcp.Data;
System.Text.ASCIIEncoding format = new System.Text.ASCIIEncoding();
string s = format.GetString(b);
s=s.ToLower();
if (destPort==80 && (s.IndexOf("intel")>0))
Console.WriteLine("Intel found in outgoing on port 80...");
}

Did the code work:

7.

A key indication of network traffic is in the TCP flags. The following


determines when the SYN flag is detected, and also the SYN, ACK flags:
if(packet is TCPPacket)
{
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
TCPPacket tcp = (TCPPacket)packet;
int destPort = tcp.SourcePort;
if (tcp.Syn) Console.WriteLine("SYN request");
if (tcp.Syn && tcp.Ack) Console.WriteLine("SYN and ACK");
}

Prove the operation of the code, and modify it so that it detects a SYN request
to a Web server (port: 80), and displays the destination IP address of the Web
server.
Outline the code used:

8.
[1]

Modify the code in 7 so that it displays all the flags for data packets.
This code is based on the code wrapper for WinPCap developed by T.Gal
[http://www.thecodeproject.com/csharp/sharppcap.asp].

275

Packet Capture (IDS) ARP Detection

Lab 4:
Details
Aim:

To provide define the capture of ARP information

Activities
1.

The ARP protocol is important on networks, as it allows a node to determine


the MAC address of a destination node on the same network. For security it
is important, as it gives information on the activity on the local network. In
this lab ARP packets will be captured, and then displayed for their basic
information. The solution can be found at:

http://buchananweb.co.uk/WinPCap4.zip
2.

The basic format of the ARP header is:

16 bits

16 bits

Hardware Type
H/W Len
Prot Len

Protocol Type
Op Code

Figure 1: ARP header


Thus a program to capture the ARP packets is given next. Notice that the
byte array is read for the first two bytes for the hardware type, and the next
two for the protocol type [1]:
using System;
using Tamir.IPLib;
using Tamir.IPLib.Packets;
namespace NapierCapture
{
public class CapturePackets
{
public static void Main(string[] args)
{
PcapDeviceList getNetConnections = SharpPcap.GetAllDevices();
// network connection 1 (change as required)
NetworkDevice netConn = (NetworkDevice)getNetConnections[1];
PcapDevice device = netConn;
// Define packet handler
device.PcapOnPacketArrival +=
new SharpPcap.PacketArrivalEvent(device_PcapOnPacketArrival);
device.PcapOpen(true, 1000);
Console.WriteLine("Network connection: {0}", device.PcapDescription);
//Start the capturing process
device.PcapStartCapture();

276

Console.WriteLine("Press any <RETURN> to exit");


Console.Read();
device.PcapStopCapture();
device.PcapClose();
}
private static void device_PcapOnPacketArrival(object sender, Packet packet)
{
if(packet is ARPPacket)
{
byte [] b = packet.Header;
int type = b[1] + (b[0]<<8);
int protocol = b[3] + (b[2]<<8);
int opcode = b[7] + (b[6]<<8);
Console.WriteLine("ARP: Hardware type {0}, protocol {1}, op-code: {2}",
type,protocol,opcode);
}
}

Run the code, and ping a node on your network (one which you have not
previously accessed for a while, or not at all), and examine the output:
Output of the program:
Did it detect the ARP packets:
What where the ARP types (from the op-code [2]1):

3.

Modify the code so that it displays the other fields in the ARP header.

4.

Modify the code so that it displays the actual ARP type, rather than the code,
Such as with:

Console.Write("ARP: Hardware type {0}, protocol {1}, ",type,protocol);


if (opcode==1) Console.Write("ARP Request");
else if (opcode==2) Console.Write("ARP Reply");
..

References
[1]

This code is based on the code wrapper for WinPCap developed by T.Gal
[http://www.thecodeproject.com/csharp/sharppcap.asp].
http://www.networksorcery.com/enp/protocol/arp.htm

[2]

Note: For Ethernet, the type is normal set to 1 [2]. The protocol type for IP is 0x8000
(2048), and the table for the op-code is:
1

1
2
3
4

Request
Reply
Request Reverse
Rely Request

277

Week 4
Week

Date

Teaching

Attended

Lab 5: IDS Snort 1

Aim: The aim of these labs and exercises are to integrate with Snort, and to capture
network and host events.
Time to complete:
4 hours (Two supervised hours in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 5: Invoking Snort
Complete Exercise 3.16.1: Running Snort (stand-alone)
Complete Exercise 3.16.2: Running Snort (stand-alone)
PIX_SNPA Challenge I1-10
Learning activities:
At the end of these activities, you should understand:

How to invoke Snort from an application program.


How to write a file of commands for Snort.
How to create Snort scripts.
The packet formats for IP and TCP.

Reflective statements (end-of-exercise):


Do you understand the main objectives of an IDS?
Do you understand how an application program can interface to Snort?
Source code used:
http://buchananweb.co.uk/SnortCaller.zip
http://buchananweb.co.uk/dotNetClientServer.zip
References:
Unit 2

278

Lab 5:

Invoking Snort

Details
Aim:

To provide a foundation in invoking and controlling Snort

Activities
1.

If Visual Studio is installed on your machine, download the following solution


[1]:

http://buchananweb.co.uk/SnortCaller.zip
An outline of the code is:
public void runSnort(string arguments)
{
processCaller = new ProcessCaller(this);
processCaller.FileName = @"c:\snort\bin\snort.exe";
processCaller.Arguments = arguments;
processCaller.StdErrReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.StdOutReceived += new DataReceivedHandler(writeStreamInfo);
processCaller.Completed += new EventHandler(processCompletedOrCanceled);
processCaller.Cancelled += new EventHandler(processCompletedOrCanceled);
this.richTextBox1.Text = "Started function.
+ Environment.NewLine;

Please stand by.."

processCaller.Start();
}
This defines
private void btnInterface_Click(object sender, System.EventArgs
e) the Snort
{
arguments that are used
this.runSnort("-W");

to run the program.

2.

In the Project listing, double click on the SnortCaller.cs file, then double click on
the Show interf button, and add the following highlighted code:
private void btnInterface_Click(object sender, System.EventArgs e)
{
this.runSnort("-W");
}

3.

Run the program, and show that the output is similar to the output in Figure 1:

What is/are your interface(s)?

279

Figure 1:

4.

Double click on the Capture Inter button, and add the following highlighted
code. Replace the c:\\bill with c:\\yourMatricNo, and replace the value after the
i option with the interface number. This should log to the folder defined.
private void btnStart_Click(object sender, System.EventArgs e)
{
if (!Directory.Exists("c:\\bill")) Directory.CreateDirectory("c:\\bill");
this.runSnort("-dev -i 1 -p -l c:\\bill -K ascii");
}

5.

Run the program and get Snort to capture the packets, and then stop it with the
Stop button (Figure 2). Generate some Web traffic, and view the output, and
verify that it is capturing data packets, such as:

Src MAC
Dest MAC
=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+

Src IP

Src TCP

01/12-11:11:07.410133 0:15:0:34:2:F0 -> 0:C:41:F5:23:D5 type:0x800 len:0x19A


192.168.1.101:2735 -> 146.176.1.188:80 TCP TTL:128 TOS:0x0 ID:13141 IpLen:20 D
Len:396 DF
***AP*** Seq: 0xCEDC79A8 Ack: 0xE2431ED3 Win: 0x4037 TcpLen: 20
47 45 54 20 2F 68 6F 6D 65 5F 6E 65 77 2F 69 6D GET /home_new/im
61 67 65 73 2F 70 72 6F 67 5F 66 32 2E 67 69 66 ages/prog_f2.gif
20 48 54 54 50 2F 31 2E 31 0D 0A 41 63 63 65 70
HTTP/1.1..Accep
74 3A 20 2A 2F 2A 0D 0A 52 65 66 65 72 65 72 3A t: */*..Referer:
20 68 74 74 70 3A 2F 2F 77 77 77 2E 6E 61 70 69
http://www.napi
Dest TCP
65 72 2E 61 63 2E 75 6B 2F 0D 0A 41 63 63 65 70 er.ac.uk/..Accep
74 2D 4C 61 6E 67 75 61 67 65 3A 20 65 6E 2D 67 t-Language: en-g
62 0D 0A 41 63 63 65 70 74 2D 45 6E 63 6F 64 69 b..Accept-Encodi
Dest IP
6E 67 3A 20 67 7A 69 70 2C 20 64 65 66 6C 61 74 ng: gzip, deflat
65 0D 0A 55 73 65 72 2D 41 67 65 6E 74 3A 20 4D e..User-Agent: M
6F 7A 69 6C 6C 61 2F 34 2E 30 20 28 63 6F 6D 70 ozilla/4.0 (comp

280

6.

Select one of the TCP data packets, and determine the following:

The source IP address:


The source TCP port:
The destination IP address:
The destination TCP port:
The source MAC address:
The destination MAC address:
The TCP flags:

Figure 2:

7.

Double click on the View Output button, and add the following highlighted
code. Replace the c:\\bill with c:\\yourMatricNo.
private void btnView_Click(object sender, System.EventArgs e)

281

{
openFileDialog1.InitialDirectory="c:\\bill";
openFileDialog1.ShowDialog();
Process.Start("wordpad.exe", openFileDialog1.FileName);
}

8.

Run the program, and select the View Output button, and verify that you get the
output seen in Figure 3, and open one of the IDS files in the subfolders, and
verify the output, as shown in Figure 4.

What are the contents of the folder:

Go into one of the folders and view the contents of the IDS file. What does it contain:

Figure 3:

282

Figure 4:

9.

Double click on the Create IDS rule button, and add the following code:
private void btnIDSRule_Click(object sender, System.EventArgs e)
{
string rule;
rule = "alert tcp any any -> any 80 (content:\"napier\"; msg:\"Napier detected\";)";
StreamWriter SW;
SW=File.CreateText("c:\\snort\\bin\\napier.txt");
SW.WriteLine(rule);
SW.Close();
statusIDS.Text+="IDS updated... please restart Snort";
}

which writes a Snort rule to the napier.txt file.


10.

Double click on the View alert.ids button, and add the following code
(remember to replace the c:\\bill with c:\\yourMatricNo):
private void btnViewAlert_Click(object sender, System.EventArgs e)
{
if (File.Exists("c:\\bill\\alert.ids"))
{
Process.Start("wordpad.exe", "c:\\bill\\alert.ids");
}
else statusIDS.Text+="File does not exist...";
}

also update the line:


this.runSnort("-dev -i 1 -p -l c:\\bill -K ascii");

with (to allow Snort to read-in the newly created rules file):
this.runSnort("-dev -i 1 -p -l c:\\bill -K ascii c c:\\snort\\bin\\napier.txt");

283

11.

Run the program, and capture some Web traffic with the name napier in it. Then
Stop the capture, and select the View alert.ids button (Figure 5).

What are the contents of the alert.ids file:

Did it detect napier:

12.

Next download the client and server programs from:

http://buchananweb.co.uk/dotNetClientServer.zip
13.

In groups of two, one person should run the server on their computer, and the
other person runs the client, and connects to the server on port 1001. Make sure
that you can chat, before going onto the next part of the tutorial (Figure 6).

14.

Write a Snort rule which detects the word napier in the communications
between the client and server.

What is the Snort rule for this:

284

Figure 5:

Figure 6:
Note: If you want the complete solution at any time, use:

http://buchananweb.co.uk/SnortCallerComplete.zip
[1]

Code is based on http://www.codeproject.com/csharp/LaunchProcess.asp.

285

Week 5
Week

Date

Teaching

Attended

Lab 6: IDS Snort 2

Aim: The aim of these labs and exercises are to understand deep packet inspection for an
IDS (Snort).
Time to complete:
4 hours (One supervised hour in B.56, and three additional hours, unsupervised).
Activitities:
Complete Lab 6: IDS 2 (Snort)
Complete Exercise 3.16.1: Running Snort (stand-alone) - if you have not already completed.
Complete Exercise 3.16.2: Running Snort (stand-alone) - if you have not already completed.
PIX_SNPA Challenge I11-30
Learning activities:
At the end of these activities, you should understand:

How to perform deep inspect of data packets.


How NMAP is used to determine vunerabilities.

Reflective statements (end-of-exercise):


How is it possible to ignore the case of a word within a data packet?
What is the main advantages of using NMAP?
Source code used:
http://buchananweb.co.uk/SnortAnalyser.zip
References:
Unit 2

286

Lab 6:

IDS 2 (Snort)

Details
Aim:
Note:

To use Snort to detect attacks


To enhance the development, you can use the following program:

http://buchananweb.co.uk/SnortAnalyser.zip
Before you start... double click on the form, and reveal the code. Now select Edit, then
Find and Replace, and then Replace. After this, change all the occurrences of c:\\bill to
c:\\mymatric (where mymatric is your matriculation number), such as:

To update the rules, double click on the Create IDS rule button, and add the necessary
rules. For example to add two rules:
string rule1,rule2;
rule1 = "alert tcp any any -> any 80 (content:\"napier\"; msg:\"Napier detected\";)";
rule2 = "alert tcp any any -> any 80 (content:\"fred\"; msg:\"Napier detected\";)";
StreamWriter SW;
SW=File.CreateText("c:\\snort\\bin\\napier.txt");
SW.WriteLine(rule1);
SW.WriteLine(rule2);
SW.Close();

Run the program, and verify that it detects the presence of the word Napier in the
outgoing network traffic, such as:

287

Click here to enable the log

Activities
1.

Write rules which will detect the word Intel in the payload, so that the
alerts are:
A.

Intel found on outgoing WWW traffic (port 80). Change it so that it


detects Intel either in upper or lower case.

B.

Intel found on incoming WWW traffic (port 80).

Verify your rules by running tests.


What are the rules:

2.

Write a rule which detects the following:


A.

An incoming Web page with the words John and Napier.

What is the rule:

288

Show that it works with the site: http://www.johnnapier.com/


and not with: http://www.napier.ac.uk
3.

Run the program, and click on the Log checkbox, and start Snort (with Capture
Inter). Run Snort, and ping one or more hosts. From the Log window, scroll until
you find your ping activity. From this locate the ARP and ping activity (see
Appendix A for an example of the packets):

What information does the sending ARP and also the receiving ARP packet have:

What are the contents of the ping packet:

4.

Run the program, and click on the Log checkbox, and start Snort (with Capture
Inter). Run Snort, and access the main Web site of the University of Edinburgh
(www.ed.ac.uk). From the Log window, scroll until you find your DNS activity
(see Appendix A for an example of the packets):

What information does the sending DNS and also the receiving DNS packet have:

Which TCP port does the DNS server use:


From the contents of the DNS return, and using nslookup on www.ed.ac.uk, is it
possible to determent the IP address that is returned from the DNS server (see
Appendix A)? Yes/No

5.

A typical signature of a network attack is a port scan, where an intruder scans


the open ports on a host. Using Netstat, determine your connected ports, and
using netstat a, determine the all your listening port.

Some of the connected ports:


Some of the listening ports:

289

6.

A factor in security is to determine the TCP ports which are listening on hosts, as
these can be one way that an intruder can gain access to a host. Also it is possible
to detect an intruder if they are scanning a network. Thus, download the NMAP
portscanner. Note: DO NOT PORT SCAN ANY OTHER MACHINE THAN
YOUR NEIGHBOURS COMPUTER. An example is at:

http://download.insecure.org/nmap/dist/nmap-3.95-win32.zip
A sample run is:
> nmap 192.168.1.1
Starting Nmap 3.95 ( http://www.insecure.org/nmap ) at 2006-01-12 13:26 GMT Standard Time
Interesting ports on 192.168.1.1:
(The 1668 ports scanned but not shown below are in state: closed)
PORT
STATE SERVICE
80/tcp
open http
8080/tcp open http-proxy
MAC Address: 00:0C:41:F5:23:D5 (The Linksys Group)
Nmap finished: 1 IP address (1 host up) scanned in 2.969 seconds

For your host, and using NMAP, complete the following:


Which ports are open:
Using the command netstat a verify that these ports are open:

7.

Download the client and server program, and run the server on one machine and
set its listening port to 1001. Rerun the port scanner from your neighbours
machine.

http://buchananweb.co.uk/dotNetClientServer.zip
Does the port scanner detect the new server port: Yes/No

8.

Next with the server listing on port 1001. Now write a Snort rule which detects the
incoming SYN flag for a connection from a client to the server.

What is the Snort rule:

9.

Write a rule for Snort which allows a port scan to be detected, and verify that it
works:

290

Snort rule:
Did it detect the port scan: Yes/no

Note
If you ever want to run the program as a
stand-alone file, you will find the EXE in
the solution folder, such as:

291

Appendix A
ARP. An ARP packet has the format:
03/05-19:59:56.376568 ARP who-has 192.168.1.101 tell 192.168.1.102
03/05-19:59:56.378315 ARP reply 192.168.1.101 (0:C:41:38:9B:A4) is-at
0:60:B3:9F:CA:E1

Ping (echo). A ping packet has the following format:


03/05-19:59:56.378331 0:15:0:34:2:F0 -> 0:60:B3:9F:CA:E1 type:0x800 len:0x4A
192.168.1.102 -> 192.168.1.101 ICMP TTL:128 TOS:0x0 ID:2861 IpLen:20 DgmLen:60
Type:8 Code:0 ID:512
Seq:4096 ECHO
61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 abcdefghijklmnop
71 72 73 74 75 76 77 61 62 63 64 65 66 67 68 69 qrstuvwabcdefghi

Ping (echo-reply). A ping packet has the following format:


03/05-19:59:56.379672 0:C:41:38:9B:A4 -> 0:15:0:34:2:F0 type:0x800 len:0x4A
192.168.1.101 -> 192.168.1.102 ICMP TTL:128 TOS:0x0 ID:21803 IpLen:20 DgmLen:60
Type:0 Code:0 ID:512 Seq:4096 ECHO REPLY
61 62 63 64 65 66 67 68 69 6A 6B 6C 6D 6E 6F 70 abcdefghijklmnop
71 72 73 74 75 76 77 61 62 63 64 65 66 67 68 69 qrstuvwabcdefghi

DNS (request). A DNS request packet has the following format:

ping payload

03/05-20:21:33.008948 0:15:0:34:2:F0 -> 0:C:41:F5:23:D5 type:0x800 len:0x48


192.168.1.102:1082 -> 195.92.195.94:53 UDP TTL:128 TOS:0x0 ID:3318 IpLen:20
DgmLen:58
Len: 30
80 07 01 00 00 01 00 00 00 00 00 00 03 77 77 77 .............www
02 68 77 02 61 63 02 75 6B 00 00 01 00 01
.hw.ac.uk.....

DNS (reply). A DNS rely packet has the following format:

DNS Server port

03/05-20:21:33.037234 0:C:41:F5:23:D5 -> 0:15:0:34:2:F0 type:0x800 len:0xF6


195.92.195.94:53 -> 192.168.1.102:1082 UDP TTL:62 TOS:0x0 ID:0 IpLen:20
DgmLen:232 DF
Len: 204
80 07 81 80 00 01 00 01 00 04 00 04 03 77 77 77 .............www
02 68 77 02 61 63 02 75 6B 00 00 01 00 01 C0 0C .hw.ac.uk.......
00 01 00 01 00 00 B4 36 00 04 89 C3 96 32 C0 10 .......6.....2..
00 02 00 01 00 00 B4 36 00 0C 03 6E 73 32 02 6A .......6...ns2.j
61 03 6E 65 74 00 C0 10 00 02 00 01 00 00 B4 36 a.net..........6
00 0A 07 6E 65 6D 65 73 69 73 C0 10 C0 10 00 02 ...nemesis......
00 01 00 00 B4 36 00 0C 09 6E 61 6D 65 73 65 72 .....6...nameser
76 65 C0 10 C0 10 00 02 00 01 00 00 B4 36 00 0C ve...........6..
09 6E 65 74 73 65 72 76 65 31 C0 10 C0 3A 00 01 .netserve1...:..
00 01 00 00 D3 24 00 04 C1 3F 69 11 C0 52 00 01 .....$...?i..R..
00 01 00 00 B4 36 00 04 89 C3 97 6E C0 68 00 01 .....6.....n.h..
00 01 00 01 16 D9 00 04 89 C3 97 69 C0 80 00 01 ...........i....
00 01 00 00 B4 36 00 04 89 C3 96 3D
.....6.....=

IP Address
292

Week 6
Week

Date

Teaching

Attended

Lab 7: Private-key Encryption

Aim: The aim of these labs and exercises are to understand the usage of private-key
encryption, key exchange, and hash signatures.
Time to complete:
4 hours (One supervised hour in B.56, and three additional hours, unsupervised).
Activitities:
Complete Lab 7: Private-key encryption
Goto: http://buchananweb.co.uk/security19.aspx and take the test
Complete Exercise 3.15.5 Diffie-Hellman key exchange.
Complete Exercise 3.17.1: Security Policy, for hash, Diffie-Hellman, and so on.
PIX_SNPA Challenge I31-I50
Learning activities:
At the end of these activities, you should understand:

Understand some of the basic methods of private-key encryption.


Understand the basic methods used in hash signatures.
Understand the conversion of binary to hexadecimal formats.

Reflective statements (end-of-exercise):


What is the usage of hash signatures?
What are the main methods used in private-key encryption?
What methods could be used to pass the private-key?
What is the main fundamental difference between DES and RC4?
What is the main weakness of the Diffie-Hellman method?
Source code used:
http://buchananweb.co.uk/encryption.zip
References:
Unit 3

293

Lab 7:

Private Key Encryption

Details
Aim:

To provide a foundation in data encryption.

Activities
If Visual Studio is installed on your machine, download the following solution [1]:
http://buchananweb.co.uk/encryption.zip
1.

The .NET environment provides a number of cryptography classes. An excellent


method is to use a code wrapper, which provides a simple method of accessing
these classes [1]. It provides encryption algorithms such as DES, 3DES and
BlowFish, and also to hash algorithms such as MD5 and SHA. The following is a
simple example using the 3DES algorithm:

using System;
using XCrypt;
// Program uses XCrypt library from http://www.codeproject.com/csharp/xcrypt.asp
namespace encryption
{
class MyEncryption
{
static void Main(string[] args)
{
XCryptEngine xe = new XCryptEngine();
xe.InitializeEngine(XCryptEngine.AlgorithmType.TripleDES);
// Other algorithms are:
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.BlowFish);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.Twofish);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.DES);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.MD5);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.RC2);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.Rijndael);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.SHA);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.SHA256);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.SHA384);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.SHA512);
xe.Key = "MyKey";
Console.WriteLine("Enter string to encrypt:");
string inText = Console.ReadLine();
string encText = xe.Encrypt(inText);
string decText = xe.Decrypt(encText);
Console.WriteLine("Input: {0}\r\nEncr: {1}\r\nDecr: {2}",
inText,encText,decText);
Console.ReadLine();
}

A sample run shows:


Enter string to encrypt:
test
Input: test
Encr: uVZLHJ3Wr8s=
Decr: test

294

By changing the method to SHA gives:


Enter string to hash:
test
Input: test
Hash: qUqP5cyxm6YcTAhz05Hph5gvu9M=

2.

Implement a program for the MD5, SHA, SHA (256-bit), SHA (384-bit), SHA
(512-bit) and complete the following table (for the first few characters of the
signature):

Text
apple
Apple
apples
This is it.
This is it

MD5

SHA

SHA (256)

SHA (384)

SHA (512)

How many characters does each of the types have?


3.

Add the following method, and thus convert MD5 and SHA-1 Base-64 hash
signatures to hex format:

public static string Base64ToHex(string input)


{
StringBuilder sb = new StringBuilder();
byte [] inputBytes = Convert.FromBase64String(input);
foreach(byte b in inputBytes)
{
sb.Append(string.Format("{0:x2}", b));
}
return sb.ToString();
}

And change the main program so that it uses the method, such as:
xe.InitializeEngine(XCryptEngine.AlgorithmType.MD5);
Console.WriteLine("Enter string to encrypt:");
string inText = Console.ReadLine();
string encText = Base64ToHex(xe.Encrypt(inText));

Determine the hash signature for hello, and check it again a standard MD5 program,
such as from: http://pajhome.org.uk/crypt/md5/
4.

Prove that the following program can decrypt an encrypted message with the
correct encryption key, while an incorrect one does not. Change the program so
that the user enters the encryption key, and also the decryption key:
xe.Key = "MyKey";
Console.WriteLine("Enter string to encrypt:");

295

string inText = Console.ReadLine();


string encText = xe.Encrypt(inText);
xe.Key = "test"; // should not be able to decrypt as the key differs
try
{
string decText = xe.Decrypt(encText);
Console.WriteLine("Input: {0}\r\nEncr: {1}\r\nDecr: {2}",
inText,encText,decText);

}
catch { Console.WriteLine("Cannot decrypt");}
Console.ReadLine();

5.

The following program uses a single character as an encryption key, and then
searches for the encryption key, and displays it. Modify it so that it implements
a 2-character encryption key, and then a 3-character one:

using System;
using XCrypt;
// Program uses XCrypt library from http://www.codeproject.com/csharp/xcrypt.asp
namespace encryption
{
class MyEncryption
{
static void Main(string[] args)
{
XCryptEngine xe = new XCryptEngine();
xe.InitializeEngine(XCryptEngine.AlgorithmType.TripleDES);
// Other algorithms are:
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.BlowFish);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.Twofish);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.DES);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.RC2);
//
xe.InitializeEngine(XCryptEngine.AlgorithmType.Rijndael);
xe.Key = "f";
Console.WriteLine("Enter string to encrypt:");
string inText = Console.ReadLine();
string encText = xe.Encrypt(inText);
for (char ch ='a'; ch<='z'; ch++)
{
try
{
xe.Key=ch.ToString();
string decText = xe.Decrypt(encText);
if (inText==decText) Console.WriteLine("Encryption key found {0}",xe.Key);
}
catch {} ;
}
Console.ReadLine();
}
}

An example test run is:


Enter string to encrypt:
test

Encryption key found f

Note
C# programs can be created without the need for Visual Studio. To compile them, either
go to the .NET framework directory, such as:
c:\> cd \WINDOWS\Microsoft.NET\Framework\v1.1.4322

296

C:\WINDOWS\Microsoft.NET\Framework\v1.1.4322> csc myprog.cs

which produces an executable file named myprog.exe or create a batch file, with the
contents:
c:\windows\microsoft.net\framework\v1.1.4322\csc %1
and call it compile.bat, and then run compile myprog.cs, and it produces the exe.
[1]

This code is based around the Xcrypt


www.codeproject.com/csharp/xcrypt.asp.

libraries

provided

at

http://

297

Week 7
Week

Date

Teaching

Attended

Lab 8: Public-key Encryption

Aim: The aim of these labs and exercises are to understand the usage of public-key
methods, and the usage of message authentication.
Time to complete:
4 hours (Two supervised hour in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 8: Public-key encryption
Complete Exercise 4.11.4: HMAC.
Complete Exercise 4.11.6: HMAC.
Complete Exercise 4.11.7: HMAC.
PIX_SNPA Challenge I51-70
Learning activities:
At the end of these activities, you should understand:

Understand some of the basic methods of public-key encryption.


Understand the basic methods used in HMAC and the formats used.

Reflective statements (end-of-exercise):


What is the main advantage of public-key encryption over private-key?
Why is private-key methods still the most common encryption method?
How does HMAC authenticate the message and the sender?
Source code used:
http://buchananweb.co.uk/encryption.zip
References:
Unit 3/4

298

Lab 8:

Public-Key Encryption

Details
Aim:

To provide a foundation in asymmetric encryption, using the RSA


method.

Activities
1.

.NET provides us with an excellent foundation in creating applications in


which we can view and log events, as well as monitoring for processes.
Another key feature is that it supports many encryption and authentication
standards. If Visual Studio is installed on your machine, download the
following solution:

http://buchananweb.co.uk/eventLogNew.zip
It has a Windows interface, such as:

Figure 1: Public-key encryption

2. For the Create Keys button add the following code:

299

System.Security.Cryptography.RSACryptoServiceProvider RSAProvider;
RSAProvider = new System.Security.Cryptography.RSACryptoServiceProvider(1024);
publicAndPrivateKeys = RSAProvider.ToXmlString(true );
justPublicKey = RSAProvider.ToXmlString( false);
StreamWriter fs = new StreamWriter("c:\\public.xml");
fs.Write(justPublicKey);
fs.Close();
fs = new StreamWriter("c:\\private.xml");
fs.Write(publicAndPrivateKeys);
fs.Close();
checkBox2.Checked=true;

3.

This creates two files on your disk. One contains your public key (public.xml)
and the other contains both the private key and the public key (private.xml). Run
the program, and using the View Keys button, view the keys.

What is the format of the keys:


View the files using Internet Explorer to see the XML format.
What are the XML tags in each of the files:

4. From the form, add the following code to the Read Keys button:

300

XmlTextReader xtr = new XmlTextReader("c:\\private.xml");


publicAndPrivateKeys=""; // reset keys
justPublicKey="";
while (xtr.Read())
{
publicAndPrivateKeys += xtr.ReadOuterXml();
}
xtr.Close();
xtr = new XmlTextReader("c:\\public.xml");
while (xtr.Read())
{
justPublicKey += xtr.ReadOuterXml();
}
xtr.Close();
checkBox2.Checked=true;

5. Now add the following code to the Encrypt text button:


RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string txt=tbTxtEncrypt.Text;
rsa.FromXmlString(justPublicKey);
byte[] plainbytes = System.Text.Encoding.UTF8.GetBytes(txt);
byte[] cipherbytes = rsa.Encrypt(plainbytes,false);
this.tbTxtEncrypted.Text=Convert.ToBase64String(cipherbytes);

6. Now add the following code to the Decrypt text button:


RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
string txt=tbTxtEncrypted.Text;
rsa.FromXmlString(publicAndPrivateKeys);
byte[] cipherbytes = Convert.FromBase64String(txt);
byte[] plainbytes = rsa.Decrypt(cipherbytes,false);
System.Text.ASCIIEncoding enc = new System.Text.ASCIIEncoding();
this.tbTxtDecrypt.Text = enc.GetString(plainbytes);

7.
the

Now run the program and add some text to the Text to encrypt box, and see if
program encrypts the text, and correctly decrypts it.

Did the program encrypt and decrypt correctly:

8.

Now get your give your neighhour your public key file (public.key), and get
them to encrypt a message. Now take the encrypted message (pass it through
copy and paste, and then email the cipertext, or put it on a shared folder), and
see if can decrypt it.

Did the program decrypt correctly:

301

Week 8
Week

Date

Teaching

Attended

Lab 9: Logging/Processes and


Hashing

Aim: To provide a foundation on how event logs are generated and to determine running
processes, and to view and update logs. It also includes methods on using the hashing
function
Time to complete:
4 hours (Two supervised hour in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 9
PIX_SNPA Challenge I71-96
Learning activities:
At the end of these activities, you should understand:

How event logs are used, and how applications can add information to them.
How to control and view processes.

Reflective statements (end-of-exercise):


How might a system be created which monitors the system for malious programs?
How important is the hash method in defining if there are any changes in a file?

302

Lab 9:

Log/Process/Hashing

Details
Aim:

To provide a foundation on how event logs are generated and to


determine running processes, and to view and update logs. It also
includes methods on using the hashing function.

Activities
1.

.NET provides us with an excellent foundation in creating applications in


which we can view and log events, as well as monitoring for processes.
Another key feature is that it supports many encryption and authentication
standards. If Visual Studio is installed on your machine, download the
following solution:

http://buchananweb.co.uk/eventLog.zip
It has a Windows interface, such as:

Click on
the tab
buttons for
the
different
programs
in this
tutorial.

Figure 1: Processes

Processes

The processes which run on a system are important, especially in monitoring for
malicious processes, such as for spyware and trap-door programs, and also in creating
303

systems which provide audit facilities for event tracking. This part of the lab shows how
a program can be written which monitors the programs which are running, and,
possibly, kill them.
2.

Run the program, and view the processes that are running on your machine.

A few of the processes running are:


ID:
ID:
ID:
ID:
ID:

Process Name:
Process Name:
Process Name:
Process Name:
Process Name:

3.

Responding:
Responding:
Responding:
Responding:
Responding:

From the form, double click on the Kill Process (name) button, and add the
highlighted code:
private void button7_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process[] p =System.Diagnostics.Process.GetProcesses();
for(int i=0 ;i<p.Length;i++)
{
if (p[i].ProcessName==tbKillProcess1.Text) p[i].Kill();
}
}

4.

From the form, double click on the Kill Process (ID) button, and add the
highlighted code:
private void button9_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process[] p =System.Diagnostics.Process.GetProcesses();
for(int i=0 ;i<p.Length;i++)
{
if (p[i].Id==Convert.ToInt32(tbKillProcess2.Text)) p[i].Kill();
}
}

6.
the

Now startup up Notepad, and view that it is one of the processes. Now, using
Kill Process (Name) button, kill the process running Notepad.

Did you see the process, and was it killed properly?

304

7.
the

Now startup up Notepad, and view that it is one of the processes. Now, using
Kill Process (ID) button, kill the process running Notepad.

Did you see the process, and was it killed properly?

Log files

A key feature in tracing the history of a computer is event log files. This part of the lab
shows show to access the event logs on the system.
8.

Select the EventLogs tab, and add the following code to the List Application
Log button:
for (int i=0;i<listBox1.Items.Count;i++) listBox1.Items.RemoveAt(0);
foreach (System.Diagnostics.EventLogEntry ev in this.eventLogApplication.Entries)
{
listBox1.Items.Add("Date: " + ev.TimeGenerated+"\tEvent ID: "+
ev.EventID+"\tMessage: "+ev.Message);
}

9.

Add the code for the other buttons (such as List Security Log and List System
Log with their logs). Run the program, and identify the last four logs for each of
the event logs (Figure 2):

Last four events for Application log:

Last four events for Security log:

Last four events for System log:

305

Last four
event logs
will appear
at the end
of the
listing.

Figure 2: Event logs

10.

Next add the following code to the Update Application Log button:

this.eventLogApplication.Source="My Application";
this.eventLogApplication.WriteEntry(textBox1.Text,EventLogEntryType.Warning);

11.

Next add the following code to the Update Security Log button:

this.eventLogSecurity.Source="My Security";
this.eventLogSecurity.WriteEntry(textBox2.Text,EventLogEntryType.Warning);

12.

Next add the following code to the Update System Log button:

this.eventLogSystem.Source="My System";
this.eventLogSystem.WriteEntry(textBox2.Text,EventLogEntryType.Warning);

13.

Run the program, and add a message to each of the logs.

Did each of the logs update?


Verify that the message has been added to the Event Viewer logs [Control Panel>Admin Tools->Event Viewer (Figure 3) right-click on My Computer and select
Manage].

306

Figure 3: Event log

14.

Determine the range of messages possible by modify the EventLogEntryType


parameter:

EventLogEntryType.Warning

15.
type.

Update the program so that it shows an Error type, and also for Information

What is the icon used for an Error type:


What is the icon used for an Information type:
What is the icon used for a Warning type:

Hash signatures

The hash signature is a key feature of creating dependable authentication for systems,
especially for file signatures. In this part of the lab you will open a file, and generate a
hash signature for it.
16.

Select the Hashing tab, and add the following code to the Open File button:
byte [] buff = new byte[9999999]; // up to 9,999,999 bytes
string hashString="";
openFileDialog1.ShowDialog();
string fname = openFileDialog1.FileName;
tbFile.Text= fname;
FileStream fs = File.OpenRead(fname);
BinaryReader br = new BinaryReader(fs);
int count = br.Read(buff,0,9999999);

307

MD5 md5 = new MD5CryptoServiceProvider();


byte[] result = md5.ComputeHash(buff,0,count);
for (int i=0;i<result.Length;i++)
{
hashString+=result[i].ToString("X2"); // hexadecimal to string conversion
}
this.tbHash.Text = hashString;

17.

Using Notepad, create a file named YourMatric.txt, and add the following text to
it:

This is an example of generating a hash signature for a file.


18.

Now run your program, and determine the hash signature.

Is the signature: 3e7baacc988a9077ddd1cd82bc6f0a04?


Now
download
an
MD5
program
(such
as
from
http://ourworld.
compuserve.com/homepages/pagrosse/hash.htm) and verify that the signature is
correct.

19.

Using Notepad, now modify the file to give the following:

This is an example of generating a Hash signature for a file.

Is the signature: 00B1A69FC8ED0D7D9195A423851E5427?

20.

.NET also has an in-built SHA1 hash signature generator. Modify the program so
that it now gives a SHA1 hash signature, such as with:

SHA1 sha1 = new SHA1CryptoServiceProvider();

How many characters does the SHA1 signature have:

21.

Now generate a signature for SHA256, then SHA384, and finally SHA512, and
note the number of characters in the signature:

308

SHA256 characters:
SHA384 characters:
SHA512 characters:
Which gives the more verifiable signature, and why?

Note
The event logs are easily added to the form by dragging the log from the Server Explorer
window onto the form (see Figure 4).

Figure 4: Adding an event log onto a form

309

Week 9
Week

Date

Teaching

Attended

11

Lab 10: TCP Forensics


Lab 11: Binary Analysis/Sig
Detetction
Aim: To provide a foundation provide a foundation in analysing TCP packets for network
forensics, and in analysing digital signatures.
Time to complete:
4 hours (Two supervised hour in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 10
Complete Lab 11
Learning activities:
At the end of these activities, you should understand:

How to analyse TCP traces for network forensics.


How to detect file contents based on a signature.

Reflective statements (end-of-exercise):


What are the main traces of a conversation that you would look for in network forensics?
What type of files would you look for in a disk analysis, and how would you search for
them?

Author: W.Buchanan

310

Lab 10:

TCP Forensics

Details
Aim:

To provide a foundation in analysing TCP packets

Activities
1.

.NET provides an excellent interface to capturing and reading back data


packets. For this lab download the solution from:

http://buchananweb.co.uk/tcpForensics.zip
It has a Windows interface, such as:

Figure 1: Inteface

2.

For the Open button add the following code:


PcapDevice device=null;
Packet packet=null;
openFileDialog1.ShowDialog();
try
{
device = SharpPcap.GetPcapOfflineDevice(openFileDialog1.FileName);
device.PcapOpen();
}
catch (Exception e1)
{
MessageBox.Show("Error: " + e1.Message);

Author: W.Buchanan

311

return;
}
while( (packet=device.PcapGetNextPacket()) != null )
{
if (packet is TCPPacket)
{
TCPPacket tcp = (TCPPacket)packet;
string srcIp = tcp.SourceAddress;
string dstIp = tcp.DestinationAddress;
int srcPort = tcp.SourcePort;
int dstPort = tcp.DestinationPort;
DateTime time = packet.PcapHeader.Date;
int len = packet.PcapHeader.PacketLength;
this.lbOutput.Items.Add(showFlags(tcp)+" Time: " +time.Hour+":"
+ time.Minute+ ":"+time.Second+
" IP Src: " + srcIp+ " TCP Src " + srcPort+
" IP Dest: " + dstIp+ " TCP Dest " + dstPort);
ASCIIEncoding utf = new System.Text.ASCIIEncoding();
string s = utf.GetString(tcp.Data);
this.lbOutput.Items.Add("

Content: " + s);

}
}

3.

Now download the file:

http://buchananweb.co.uk/capture1.zip
Read the file in, and determine the start of each conversation with the server, and
complete Table 1 (note that the first entry has already been added).
Note: Identify a connection with the SYN, SYN/ACK and ACK flag sequence.
What is the domain name of the remote server?
What is the application protocol used?
For the first connection what is the HTTP request send (note look for commands such
as GET, Accept: and so on)?

For the first connection what is the format of the HTTP reply (note look for a request
such as HTTP/1.1 200)?

Author: W.Buchanan

312

Table 1:
Connection
1
2
3
4
5
6
7
8
4.

Src IP
192.168.1.102

Src Port
1386

Dst IP
66.102.9.147

Dst Port
80

Now download the file:

http://buchananweb.co.uk/capture2.zip
Read the file in, and determine the start of each conversation with the server, and
complete Table 1 (note that the first entry has already been added).
Note: Identify a connection with the SYN, SYN/ACK and ACK flag sequence.
What is the domain name of the remote server?

What is the trace of the traffic to and from the client to the server:

Which TCP ports are used on the server:

Table 1:
Connection
1
2
3
4
5
6
7
8

Src IP
192.168.1.102

Author: W.Buchanan

Src Port
1433

Dst IP
198.175.98.64

Dst Port
21

313

5.

Now download the file:

http://ceres.napier.ac.uk/staff/bill/seg2.zip
Using Wireshark or Ethereal, answer the following questions:
1.

List four of the most used application protocols:

2.

Which type of service is used for UDP packets:

3.

What was the username and password used to access the FTP server, and which
is the IP address of the requestor, and the IP address of the server?

4.

Which subfolders did the user go into when then accessed the FTP server?

5.

Which files were uploaded or downloaded from the FTP server?

6.

Which is/are the IP address(es) of the SSH server(s)?

7.

By examing ARP activity, which is the IP address of the local gateway, and what
is its MAC address? Why does the gateway send ARP requests?

8.

Determine the list of local IP addresses (10.0.1.x) which are part of the conversion
within the network segment.

9.

Which are the top three machines in terms of the packets generated?

10.

Now download the file:

http://ceres.napier.ac.uk/staff/bill/seg7.zip
11.

Determine the locations involved in a Hydra attack?

Author: W.Buchanan

314

Week 10
Week

Date

12

15 Dec

Teaching

Attended

Lab 12: Signature Analysis


Lab 13: Role-based Security
Aim: To provide a foundation provide a foundation in determining the signature of files
for digital forensics.
Time to complete:
4 hours (Two supervised hour in C.27, and two additional hours, unsupervised).
Activitities:
Complete Lab 12
Complete Lab 13
Learning activities:
At the end of these activities, you should understand:

How to analyse file types.

Reflective statements (end-of-exercise):


How might you search the whole of a disk for file activities?
How might it be possible to find files on a disk without them being in the Table of Contents
for the disk?

Author: W.Buchanan

315

Lab 12: Binary Reader/File Signature Analysis


Details
Aim:

To provide a foundation in analysing file formats

Activities
1.

.NET provides an excellent interface in reading from files, and viewing them as
ASCII characters or in a hexadecimal format. For this lab download the
solution from:

http://buchananweb.co.uk/sigAnalysis.zip
It has a Windows interface, such as:

Char format
Hex format

Figure 1: Interface

2.

Open the solution, and for the Open button add the following code:
textBox1.Text="";
textBox2.Text="";
DialogResult result = this.openFileDialog1.ShowDialog();
textBox3.Text=openFileDialog1.FileName;
byte [] buff= getBytes(openFileDialog1.FileName);
for (int i=0;i<buff.Length;i++)
{

Author: W.Buchanan

316

char c = (char) buff[i];


if (c>=' ' && c<='z')
textBox1.Text+=(char)buff[i];
else textBox1.Text+=".";
textBox2.Text+=buff[i].ToString("X2")+" "; // hex format
if ((i+1)%16==0) // add a new line very 16 characters
{
textBox1.Text+="\r\n";
textBox2.Text+="\r\n";
}
}

and also add the following (which reads the file into a byte array):
public byte [] getBytes(string f)
{
FileStream fsIn = new FileStream(f,FileMode.Open, FileAccess.Read);
byte [] b = new byte[2048];
int bytesRead = fsIn.Read(b,0,2048);
fsIn.Close();
return(b);
}

The following tutorial uses files which are in a ZIP file:


http://buchananweb.co.uk/files.zip
3.

Download this file, and extract them to a folder.

4.

Now run the file and open the first file (file1). The output should be something
like in Figure 1.

Refer to the Appendix given, and determine the format of the file.
What is the format of the file (such as GIF, JPEG, ZIP, etc):

Now repeat for files 2 to 10, and complete the following table:
Name

File format (circle correct one)

File2

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File3

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

Author: W.Buchanan

Is there any copyright information in the


file (or associated information that is
readable)?

317

File4

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File5

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File6

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File7

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File8

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File9

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

File10

DOC/PPT/XLS/JPEG/GIF/WMF/ZIP

5.

For the ZIP file:

Identify the file name contained within the ZIP file:


What is the termination character used to terminate the file name:
Can you tell the date and time that it was last modified?

6.

0x identifies a
hex format

Now add a new button and give it the text of Identify File, and use it to read in
a file, and to try and determine the file type from the basic header signature. For
example, the following shows some of the code required to identify a ZIP file and
a JPEG file:
textBox1.Text="";
textBox2.Text="";
DialogResult result = this.openFileDialog1.ShowDialog();
textBox3.Text=openFileDialog1.FileName;
byte [] buff= getBytes(openFileDialog1.FileName);
if (buff[0]==0x50 && buff[1]==0x4B) textBox1.Text="ZIP file";

Author: W.Buchanan

318

else if (buff[0]==0xff && buff[1]==0xD8) textBox1.Text="JPEG file";


else textBox1.Text="Not known";

7.

For other binary file formats, determine their signature (if possible).

PDF file signature:


SWF (Flash) file signature:
DLL file signature:
RTF file signature (open up a Word document, and save it in an RTF file format):
XML file signature (open up a Word document, and save it in an XML file format):
[or use: http://buchananweb.co.uk/1.xml]
8.

Modify the program in 6 to identify these files.

Appendix
JPEG file format:
FFD8 start of image
length -- two bytes
identifier -- five bytes: 4A, 46, 49, 46, 00 (the ASCII code equivalent of a zero terminated
"JFIF" string)
version -- two bytes: often 01, 02
ZIP file format:
00
04
06
08
0A
0C
0E
12
16
1A
1C
1E

ZIPLOCSIG
ZIPVER
ZIPGENFLG
ZIPMTHD
ZIPTIME
ZIPDATE
ZIPCRC
ZIPSIZE
ZIPUNCMP
ZIPFNLN
ZIPXTRALN
ZIPNAME

HEX 504B0304
DW 0000
DW 0000
DW 0000
DW 0000
DW 0000
HEX 00000000
HEX 00000000
HEX 00000000
DW 0000
DW 0000
DS ZIPFNLN

;Local File Header Signature


;Version needed to extract
;General purpose bit flag
;Compression method
;Last mod file time (MS-DOS)
;Last mod file date (MS-DOS)
;CRC-32
;Compressed size
;Uncompressed size
;Filename length
;Extra field length
;filename

GIF file format:


The header is 6 bytes long and identifies the GIF signature and the version number of
the chosen GIF specification. Its format is:
3 bytes with the characters G, I and F.
3 bytes with the version number (such as 87a or 89a). Version numbers are ordered
Author: W.Buchanan

319

with two digits for the year, followed by a letter (a, b, and so on).
WMF file format:
Standard header of:

d7 cd c6

Excel file format:


Standard header of:
Byte position 40(hex):

d0 cf 11 e0 a1 b1 1a
00

Word file format:


Standard header of:
Byte position 40(hex):

d0 cf 11 e0 a1 b1 1a
01

PPT file format:


Standard header of:
Byte position 40(hex):

Author: W.Buchanan

d0 cf 11 e0 a1 b1 1a
01

320

Lab 13: Role-based security


The Microsoft .NET environment now offers an excellent alternative to Java in
producing portable and secure code. It uses a role-based approach for user
authentication, with the WindowsIndentity class, where the GetCurrent() method can
be used to get the current user. The WindowsPrincipal class can then be used to apply
the role. For example to test if the user is an administrator:
using System;
using System.Security;
using System.Security.Principal;
namespace ConsoleApplication3
{
class Class1
{
static void Main(string[] args)
{
WindowsIdentity myID = WindowsIdentity.GetCurrent();
System.Console.WriteLine("Your ID: " + myID.Name);
System.Console.WriteLine("Authentication: " +
myID.AuthenticationType);
WindowsPrincipal myPrin = new WindowsPrincipal(myID);
if (myPrin.IsInRole(WindowsBuiltInRole.Administrator))
System.Console.WriteLine("You're an Administrator ");
else
System.Console.WriteLine("You're not an Administrator");
Console.ReadLine();
}
}
}

A sample run gives:


Your ID: BILLS\William Buchanan
Authentication: NTLM
You're an Administrator

Other roles are also defined, such as:


WindowsBuiltInRole.Guest
WindowsBuiltInRole.PowerUser
WindowsBuiltInRole.User

Next we could apply this security to only allow an administrator to view the IP address
of the computer, with:
using
using
using
using

System;
System.Security;
System.Security.Principal;
System.Net;

Author: W.Buchanan

321

namespace ConsoleApplication3
{
class Class1
{
static void Main(string[] args)
{
WindowsIdentity myID = WindowsIdentity.GetCurrent();
System.Console.WriteLine("Your ID: " + myID.Name);
System.Console.WriteLine("Authentication: " +
myID.AuthenticationType);
WindowsPrincipal myPrin = new WindowsPrincipal(myID);
if (myPrin.IsInRole(WindowsBuiltInRole.Administrator))
{
string strHostName = Dns.GetHostName();
IPHostEntry ipEntry = Dns.GetHostByName(strHostName);
IPAddress [] addr = ipEntry.AddressList;
System.Console.WriteLine("IP: " + addr[0]);
}
else
System.Console.WriteLine(
"Sorry ... you have no permissions for this");
}
}
}

Run this program, and view the output.

Author: W.Buchanan

322

You might also like