Professional Documents
Culture Documents
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)
12/10/09
4: Authentication (Part 2)
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
11
16/11/09
Professional Certification
12
13
14
15
23/11/09
30/11/09
07/12/09
14/12/09
Professional Certification
264
Week 2
Week
1
Date
Teaching
Attended
265
Lab 1:
Details
Aim:
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
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++;
}
[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:
Details
Aim:
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
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
Len=74
Len=74
Len=74
Len=74
Len=74
Len=74
269
[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
271
Lab 3:
Details
Aim:
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);
}
}
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.
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);
}
}
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.
273
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...
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...");
}
7.
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
Lab 4:
Details
Aim:
Activities
1.
http://buchananweb.co.uk/WinPCap4.zip
2.
16 bits
16 bits
Hardware Type
H/W Len
Prot Len
Protocol Type
Op Code
276
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:
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
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:
278
Lab 5:
Invoking Snort
Details
Aim:
Activities
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;
processCaller.Start();
}
This defines
private void btnInterface_Click(object sender, System.EventArgs
e) the Snort
{
arguments that are used
this.runSnort("-W");
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:
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
280
6.
Select one of the TCP data packets, and determine the following:
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.
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";
}
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...";
}
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).
12.
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.
284
Figure 5:
Figure 6:
Note: If you want the complete solution at any time, use:
http://buchananweb.co.uk/SnortCallerComplete.zip
[1]
285
Week 5
Week
Date
Teaching
Attended
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:
286
Lab 6:
IDS 2 (Snort)
Details
Aim:
Note:
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
Activities
1.
Write rules which will detect the word Intel in the payload, so that the
alerts are:
A.
B.
2.
288
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:
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:
5.
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
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.
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 payload
IP Address
292
Week 6
Week
Date
Teaching
Attended
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:
293
Lab 7:
Details
Aim:
Activities
If Visual Studio is installed on your machine, download the following solution [1]:
http://buchananweb.co.uk/encryption.zip
1.
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();
}
294
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)
Add the following method, and thus convert MD5 and SHA-1 Base-64 hash
signatures to hex format:
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
}
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();
}
}
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
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]
libraries
provided
at
http://
297
Week 7
Week
Date
Teaching
Attended
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:
298
Lab 8:
Public-Key Encryption
Details
Aim:
Activities
1.
http://buchananweb.co.uk/eventLogNew.zip
It has a Windows interface, such as:
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.
4. From the form, add the following code to the Read Keys button:
300
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.
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.
301
Week 8
Week
Date
Teaching
Attended
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.
302
Lab 9:
Log/Process/Hashing
Details
Aim:
Activities
1.
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.
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.
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.
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):
305
Last four
event logs
will appear
at the end
of the
listing.
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.
306
14.
EventLogEntryType.Warning
15.
type.
Update the program so that it shows an Error type, and also for Information
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
17.
Using Notepad, create a file named YourMatric.txt, and add the following text to
it:
19.
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:
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).
309
Week 9
Week
Date
Teaching
Attended
11
Author: W.Buchanan
310
Lab 10:
TCP Forensics
Details
Aim:
Activities
1.
http://buchananweb.co.uk/tcpForensics.zip
It has a Windows interface, such as:
Figure 1: Inteface
2.
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("
}
}
3.
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
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:
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.
http://ceres.napier.ac.uk/staff/bill/seg2.zip
Using Wireshark or Ethereal, answer the following questions:
1.
2.
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.
6.
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.
http://ceres.napier.ac.uk/staff/bill/seg7.zip
11.
Author: W.Buchanan
314
Week 10
Week
Date
12
15 Dec
Teaching
Attended
Author: W.Buchanan
315
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
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);
}
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
File2
DOC/PPT/XLS/JPEG/GIF/WMF/ZIP
File3
DOC/PPT/XLS/JPEG/GIF/WMF/ZIP
Author: W.Buchanan
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.
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
7.
For other binary file formats, determine their signature (if possible).
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
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
d0 cf 11 e0 a1 b1 1a
00
d0 cf 11 e0 a1 b1 1a
01
Author: W.Buchanan
d0 cf 11 e0 a1 b1 1a
01
320
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");
}
}
}
Author: W.Buchanan
322