TE-SEM5_PL-02
(Programming Laboratory II)
------------------------------
Practicals List:
-----------------------------
Assignments Group A (Mandatory)
1 Implementation of following spoofing assignments using C++ multicore Programming
a) IP Spoofing
b) Web spoofing.
2 A fire is to be detected using relevant wireless sensor network installed in a remote location
to communicate the data to the central server for the monitoring purpose and detection of
the fire. Write a program to implement the system using WSN and Different data
communication strategies/ algorithms (at least two) to compare the reliability of the data
received and efficient timing. Use of Fort Forwarding/Tunneling Protocol is expected.
3.Write a computer forensic application program in Java/Python/C++ for Recovering Deleted
Files and Deleted Partitions
4
A person on a nearby road is trying to enter into a WiFi network by trying to crack the
Password to use the IP Printer resource; write a program in Java/Python/C++ to detect such
attempt and prohibit the access. Develop the necessary scenario by Using an IEEE 802.11,
configure a Wi-Fi adapter and Access Point.
5 Write a program to implement Pulse Code Modulation Technique to transfer the data to
other computer.
6 Write a program in C++ /Python to analyze email header.
Assignments Group B (Any Six Assignments, All assignments to be covered in the Batch)
1
Develop a GUI and write a Java/Pythn/C++ program to monitor Network Forensics,
Investigating Logs and Investigating Network Traffic.
2 Write a program in Python for Investigating Wireless Attacks using Multi-core
programming.
3 Write a program in Python for Investigating Web Attacks. Finding originator's IP, Subnet
Mask and Default gateway where a Web Server is connected using Optical Router.
4 Create a Scenario and write a program for overcoming a Website hacking problems and
identifying hacker machine using Java/Python/C++. Develop a prototype website using
Ruby on rails.
5 Write a program in C++ for Tracking Emails and Investigating Email Crimes
6 Install and use Android Mobile Forensics Open Source Tools.
7 Write a program to Implement a packet sniffing tool in C++/Java/Python.
8 Write a program in C++ to implement to identify DOS attack on a wireless cluster of
servers.
9 Install and use open source tools to Identifying various types of WiFi attacks. Write a C++/
Java/Python program to identify atleast one such attack.
10 Install and use a open source tool to Identifying MMS attacks, create necessary Scenario.
11 Design and implementation of Honeypot
12 Write a program to identifying private data acquisition of digital evidence using Java in a
WiFi system, use SAN storage(BIGDATA)
13 Write a program to Implement a packet sniffing tool in C++
14 Write a program to Implement a fingerprint recognition using Java Programming
15 Write a program for identifying the image tampering, voice data
(recorded/Blogged/twitted/Social Web Sites) tampering Python Programming. use SAN
storage(BIGDATA)
16 Write a program for identifying the voice data (recorded/ blogged Video/twitted/ Social Web
Sites ) tampering, where a Mic is attached through WSN. use SAN storage(BIGDATA)
17 Write a program for Identifying the tampering of digital signature using Python
18 Write a C++/Java program for Log Capturing and Event Correlation.
19 Write a tool to detect and prevent Capturing mobile messages in Python/Java.
Assignment Group C: Advance Technology Assignments (Any One)
1 Implementation of Steganography program.
2 Implement a program to generate and verify CAPTCHA image.
3 Intrusion detection system
4 Write a program to detect and prevent windows 8 registry Hacks and Twicks
Simulate the performance of DSDV, AODV and DSR routing protocols over the WSN.
5 Installation and configuration of WSN using ZigBee protocol
6 Set up a small wireless sensor network of few nodes and show communication between two
nodes using NS3 or equivalent
PL2Manual_1
GroupA
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH :T1
// ASSIGNMENT NO.: 01
/* TITLE : Implementation of following spoofing assignments using C++ multicore Programming
a) IP Spoofing
b) Web spoofing.
//============================================================================*/
//C++ multicore Programming
#include <iostream>
#include <cstdlib>
#include <cstring> // For memcpy()
#include <sys/socket.h>
#include <netinet/in.h> // IPPROTO_ICMP
#include <netinet/ip.h> // struct ip
#include <netinet/ip_icmp.h> // stuct icmp
#include <arpa/inet.h> // inet_ntoa, inet_addr
using namespace std;
class IP
{
struct ip ip;
public:
IP()
{
ip.ip_v = 0x4;
ip.ip_tos = 0x0;
ip.ip_sum = 0x0;
}
IP(char * src_addr, char * dst_addr)
{
ip.ip_v = 0x4;
ip.ip_tos = 0x0;
ip.ip_sum = 0x0;
ip.ip_src.s_addr = inet_addr(src_addr); //inbuilt in inet.h
ip.ip_dst.s_addr = inet_addr(dst_addr);
}
void set_header_len(int hl) { ip.ip_hl = hl; }
void set_len(int len) { ip.ip_len = htons(len); }
unsigned short get_len() { return ntohs(ip.ip_len); }
struct ip * get_addr() { return &ip; }
void set_id(int id) { ip.ip_id = htons(id); }
void set_offset(int offset) { ip.ip_off = offset; }
void set_ttl(int ttl) { ip.ip_ttl = ttl; }
void set_proto(int p) { ip.ip_p = p; }
void set_sum(unsigned short sum){ ip.ip_sum = sum; }
};
class ICMP
{
struct icmp icmp;
public:
ICMP()
{
icmp.icmp_id = 1234; // Any arbitrary unsigned int
icmp.icmp_seq = 0;
icmp.icmp_cksum = 0x0;
}
struct icmp * get_addr() { return &icmp; }
void set_type(unsigned int type) { icmp.icmp_type = type; }
unsigned int get_type() { return icmp.icmp_type; }
void set_code(unsigned int code) { icmp.icmp_code = code; }
void set_cksum(unsigned short sum) { icmp.icmp_cksum = sum; }
};
unsigned short checksum(unsigned short *addr, int len)
{
int nleft = len;
int sum = 0;
unsigned short *w = addr;
unsigned short answer = 0;
while (nleft > 1)
{
sum += *w++;
nleft -= 2;
}
if (nleft == 1)
{
*(unsigned char *) (&answer) = *(unsigned char *) w;
sum += answer;
}
sum = (sum >> 16) + (sum & 0xFFFF);
sum += (sum >> 16);
answer = ~sum;
return (answer);
}
int main(int argc, char * argv[])
{
unsigned char * packet;
int sd;
const int on = 1;
struct sockaddr_in sockaddr;
char * src;
char * dst;
if(argc == 3)
{
src = argv[1];
dst = argv[2];
}
else
{
cout<<"Usage :"<<endl;
cout<<argv[0]<<" source destination"<<endl;
exit(1);
}
// IP header
IP ip_pkt(src, dst);
ip_pkt.set_header_len(0x5);
ip_pkt.set_id(12830);
ip_pkt.set_offset(0x0);
ip_pkt.set_ttl(64);
ip_pkt.set_len(60);
ip_pkt.set_proto(IPPROTO_ICMP);
ip_pkt.set_sum(checksum((u_short *)ip_pkt.get_addr(), sizeof(struct ip)));
// ICMP header
ICMP icmp_pkt;
icmp_pkt.set_type(ICMP_ECHO);
icmp_pkt.set_code(0);
icmp_pkt.set_cksum(checksum((u_short *)icmp_pkt.get_addr(), 8));
/*
Allocate memory for the packet and copy
the IP header first, then the ICMP header
after an offset of 20 bytes.
*/
packet = (unsigned char *) malloc(ip_pkt.get_len());
memcpy(packet, ip_pkt.get_addr(), sizeof(struct ip));
memcpy(packet + 20, icmp_pkt.get_addr(), 8);
/*
Create a raw socket so that kernel doesn’t interfere
with the headers of the custom packet.
*/
if ((sd = socket(AF_INET, SOCK_RAW, IPPROTO_RAW)) < 0)
{
cout<<"Couldn’t create raw socket"<<endl;
exit(1);
}
if (setsockopt(sd, IPPROTO_IP, IP_HDRINCL, &on, sizeof(on)) < 0)
{
cout<<"setsockopt() failed"<<endl;
exit(1);
}
memset(&sockaddr, 0, sizeof(sockaddr));
sockaddr.sin_family = AF_INET;
sockaddr.sin_addr.s_addr = inet_addr(dst);
// Send the packet
if(sendto(sd, packet, ip_pkt.get_len(), 0, (struct sockaddr *)&sockaddr,
sizeof(struct sockaddr)) < 0)
{
cout<<"Packet couldn’t be sent"<<endl;
exit(1);
}
cout<<"Packet sent!"<<endl;
return 0;
}
/* OUTPUT
aman@Aman-pc:~$ cd Desktop
aman@Aman-pc:~/Desktop$ g++ pl2_a1.cpp
aman@Aman-pc:~/Desktop$ sudo ./a.out 123.238.65.100 123.238.65.102
[sudo] password for aman:
Packet sent!
aman@Aman-pc:~/Desktop$
*/
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 03
/* TITLE : 3.Write a computer forensic application program in Java/Python/C++ for Recovering Deleted
Files and Deleted Partitions
//============================================================================*/
//C++
#include<iostream>
#include<sys/stat.h>
#include<stdlib.h>
using namespace std;
int main()
{
cout<<"\n\n\t\tPAGE DELETED RECOVERY FILES";
cout<<"\n\t\t****************************************";
system("foremost -v -T -c etc/foremost.conf -i/dev/sta -o output");
cout<<"\n\n\t*****************************************";
cout<<"\n\n\t DELETED FILE IS RECOVERED";
return(0);
}
/* OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ g++ pl2_a03.cpp
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ ./a.out
PAGE DELETED RECOVERY FILES
Foremost version 1.5.7 by Jesse Kornblum, Kris Kendall, and Nick Mikus
Audit File
Foremost started at Fri Aug 21 16:24:26 2015
Invocation: foremost -v -T -c etc/foremost.conf -i/dev/sta -o output
Output directory: /home/ccpvg/Desktop/output_Fri_Aug_21_16_24_26_2015
Configuration file: /etc/foremost.conf
Processing: stdin
|------------------------------------------------------------------
File: stdin
Start: Fri Aug 21 16:24:26 2015
Length: Unknown
Num Name (bs=512) Size File Offset Comment
*/
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 05
/* TITLE : 5 Write a program to implement Pulse Code Modulation Technique to transfer the data to
other computer.
//============================================================================*/
//C++
#include<math.h>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int x[512],z[512],A;
cout<<"Enter Amplitude:";cin>>A;
float f;
int t=0,T;
cout<<"Enter time:";cin>>T;
f=1.0/T;
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);
size=A/m;
int p,n,k;
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++)
{
if(x[t]<=p&&x[t]>=n)
{
z[t]=m-k-1;
break;
}
p=n;
n=n-size;
}
}
cout<<" "<<z[t];
}
cout<<"\n\n";
long i,rem,j=0,sum=0;
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<<" "<<sum;
}
cin.get();
cout<<"\n";
return 0;
}
/*OUTPUT
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ g++ pl2_a05.cpp
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ ./a.out
Enter Amplitude:10
Enter time:12
0 5 8 9 8 4 0 -5 -8 -9 -8 -4 0
Enter No of bits for Quantisation code:3
4 6 7 0 7 5 4 1 0 0 0 2 4
100 110 111 0 111 101 100 1 0 0 0 10 100
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
*/
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 06
/* TITLE : Write a program in C++ /Python to analyze email header.
//============================================================================*/
//C++ program
#include <iostream>
#include"fstream"
using namespace std;
int main()
{
ifstream in("mail.txt",ios::in);
string sender,receiver,mesId,sub,recip,recdate,mime_ver,from,to;
string temp1[2];
int i=0;
while(in>>temp1[i])
{
if(temp1[i].compare("Delivered-To:")==0)
getline(in,receiver);
else if(temp1[i].compare("Return-Path:")==0)
getline(in,sender);
else if(temp1[i].compare("Date:")==0)
getline(in,recdate);
else if(temp1[i].compare("Message-ID:")==0)
getline(in,mesId);
else if(temp1[i].compare("Subject:")==0)
getline(in,sub);
else if(temp1[i].compare("MIME-Version:")==0)
getline(in,mime_ver);
else if(temp1[i].compare("From:")==0)
getline(in,from);
else if(temp1[i].compare("To:")==0)
getline(in,to);
}
cout<<"Message Id:-"<<mesId<<endl;
cout<<"From:"<<from<<endl;
cout<<"To:"<<to<<endl;
cout<<"Delivered To:-"<<receiver<<endl;
cout<<"Return Path:-"<<sender<<endl;
cout<<"Subject:-"<<sub<<endl;
cout<<"Date:-"<<recdate<<endl;
cout<<"MIME-Version:"<<mime_ver<<endl;
cout<<"From:"<<from<<endl;
cout<<"To:"<<to<<endl;
return 0;
}
/*
output
pvg@pvg-Veriton-M200-H61:~$ cd Desktop
pvg@pvg-Veriton-M200-H61:~/Desktop$ g++ main.cpp
pvg@pvg-Veriton-M200-H61:~/Desktop$ ./a.out
Message Id:- <CAJBcm1z+JzQ=n0AqBj3GvCqqgy3-sK53zGWoEnijgKzw76U6pg@mail.gmail.com>
From: SWAPNIL M SONKAMBLE <swapnil.sms15@gmail.com>
To: Aman Bohra <bohraaman@gmail.com>
Delivered To:- bohraaman@gmail.com
Return Path:- <swapnil.sms15@gmail.com>
Subject:- Need Feebaback for the Training Program
Date:- Fri, 5 Jun 2015 22:00:08 +0530
MIME-Version: 1.0
From: SWAPNIL M SONKAMBLE <swapnil.sms15@gmail.com>
To: Aman Bohra <bohraaman@gmail.com>
pvg@pvg-Veriton-M200-H61:~/Desktop$
*/
#python program
#!/usr/bin/env python
import re
emails = open("input.txt","r") #opens the file to analyze
results = open("op.txt","w") #creates new file for search results
resultsList = []
for line in emails:
if "From - " in line: #recgonizes the beginning of a email message and adds a linebreak
newMessage = re.findall(r'\w\w\w\s\w\w\w.*', line)
if newMessage:
resultsList.append("\n\t*** EMAIL HEADER DETAILS ***\n")
if "From: " in line:
address = re.findall(r'[\w.-]+@[\w.-]+', line)
if address:
resultsList.append("\n\nFrom : ")
resultsList.append(address)
resultsList.append(";")
if "To: " in line:
if "Delivered-To:" not in line: #avoids confusion with 'Delivered-To:' tag
address = re.findall(r'[\w.-]+@[\w.-]+', line)
if address:
resultsList.append("\n\nTo : ")
for person in address:
resultsList.append(person)
resultsList.append("; ")
if "Bcc: " in line:
address = re.findall(r'[\w.-]+@[\w.-]+', line)
if address:
resultsList.append("\n\nBcc : ")
resultsList.append(address)
resultsList.append(";")
if "Date: " in line:
address = re.findall(r'\w\w\w\,.*', line)
if address:
resultsList.append("\n\nDate : ")
resultsList.append(address)
resultsList.append(";")
if "Subject: " in line:
address = re.findall(r'[\w\s.-]+[\w.-]+', line)
if address:
resultsList.append("\n\nSub : ")
resultsList.append(address)
for result in resultsList:
results.writelines(result)
emails.close()
results.close()
/*
output:
Date : Fri, 5 Jun 2015 22:00:08 +0530;
Sub : Subject Need Feebaback for the Training Program
From : swapnil.sms15@gmail.com;
To : bohraaman@gmail.com; */
Assignment Group B:
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.:06
/* TITLE :6 Install and use Android Mobile Forensics Open Source Tools.
//============================================================================*/
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 07
/* TITLE :Write a program to Implement a packet sniffing tool in C++/Java/Python.
//============================================================================*/
//C++
#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() { 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); 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"); 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"); 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###########################################################"); } 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###########################################################"); } 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" ); } } } ***********OUTPUT************************* ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ gcc packet.c ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ sudo ./a.out [sudo] password for ccpvg: Starting... TCP : 0 UDP : 620 ICMP : 16 IGMP : 70 Others : 656 Total : 1362 **********************UDP Packet************************* Ethernet Header |-Destination Address : FF-FF-FF-FF-FF-FF |-Source Address : 6C-F0-49-14-07-7E |-Protocol : 8 IP Header |-IP Version : 4 |-IP Header Length : 5 DWORDS or 20 Bytes |-Type Of Service : 0 |-IP Total Length : 78 Bytes(Size of Packet) |-Identification : 19309 |-TTL : 128 |-Protocol : 17 |-Checksum : 50640 |-Source IP : 20.0.0.99 |-Destination IP : 20.255.255.255 UDP Header |-Source Port : 137 |-Destination Port : 137 |-UDP Length : 58 |-UDP Checksum : 1871 IP Header FF FF FF FF FF FF 6C F0 49 14 07 7E 08 00 45 00 ......l.I..~..E. 00 4E 4B 6D .NKm UDP Header 00 00 80 11 C5 D0 14 00 ....... Data Payload 8C 49 01 10 00 01 00 00 00 00 00 00 20 46 48 46 .I.......... FHF 41 45 42 45 45 43 41 43 41 43 41 43 41 43 41 43 AEBEECACACACACAC 41 43 41 43 41 43 41 43 41 43 41 41 41 00 00 20 ACACACACACAAA.. 00 01 .. ########################################################### ***********************UDP Packet************************* Ethernet Header |-Destination Address : FF-FF-FF-FF-FF-FF |-Source Address : D4-BE-D9-BA-DE-0B |-Protocol : 8 IP Header |-IP Version : 4 |-IP Header Length : 5 DWORDS or 20 Bytes |-Type Of Service : 0 |-IP Total Length : 78 Bytes(Size of Packet) |-Identification : 17816 |-TTL : 128 |-Protocol : 17 |-Checksum : 52091 |-Source IP : 20.0.0.141 |-Destination IP : 20.255.255.255 UDP Header |-Source Port : 137 |-Destination Port : 137 |-UDP Length : 58 |-UDP Checksum : 912 IP Header FF FF FF FF FF FF D4 BE D9 BA DE 0B 08 00 45 00 ..............E. 00 4E 45 98 .NE. UDP Header 00 00 80 11 CB 7B 14 00 ....{.. Data Payload 81 DE 01 10 00 01 00 00 00 00 00 00 20 46 48 46 ............ FHF 41 45 42 45 45 43 4F 43 41 43 41 43 41 43 41 43 AEBEECOCACACACAC 41 43 41 43 41 43 41 43 41 43 41 41 41 00 00 20 ACACACACACAAA.. 00 01 ..
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.:14
/* TITLE :Write a program to Implement a fingerprint recognition using Java Programming
//============================================================================*/
//Fingerprint Recognition
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.PixelGrabber;
public class cc {
static void processImage() {
String file1 = "p4.jpg";
String file2 = "p5.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();
}
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("Fingerprint matches : " + java.util.Arrays.equals(data1, data2));
} catch (InterruptedException e1) {
e1.printStackTrace();
}
}
public static void main(String args[]) {
processImage();
}
}
/*==========OUTPUT===============
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac cc.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java cc
Fingerprint matches : false
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac cc.java
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java cc
Fingerprint matches : true */
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.:15
/* TITLE :Write a program for identifying the image tampering, voice data
(recorded/Blogged/twitted/Social Web Sites) tampering Python Programming. use SAN
storage(BIGDATA)
//============================================================================*/
Detecting copy-move forgery in images
This time I`ll talk about
digital image forensic and how to detect copy-move forgery in images.
I`ve implemented some ad-hoc algorithm for detection of this kind of
forgeries. Algorithm is robust, so it can detect forgeries in lossy
image formats- such as JPEG. Please keep in mind - this algorithm is
experimental toy, if you want more general solutions - you should read
this paper or maybe this to get some ideas in the field. BTW, this
algorithm is only tested with Python 2.6, so you better install Python
2.6.
Robust detection algorithm steps
1. Blur image for eliminating image details
2. Convert image to degraded palette
3. Decompose image into small NxN pixel blocks
4. Alphabetically order these blocks by their pixel values
5. Extract only these adjacent blocks which have small absolute color difference
6. Cluster these blocks into clusters by intersection area among blocks
7. Extract only these clusters which are bigger than block size
8.
Extract only these clusters which have similar cluster, by using some
sort of similarity function (in this case Hausdorff distance between
clusters)
9. Draw discovered similar clusters on image
Copy-move detection script usage instructions
Run script from the command line - cmd in Windows or terminal in Linux.
1. At first try to execute script with default parameters-
python detect_copymove.py image_file.jpg
2. Then try to lower block color deviation threshold-
python detect_copymove.py image_file.jpg --blcoldev=0.05
3. Finally - run script in manual mode and try to spot similar regions by eyes-
python detect_copymove.py image_file.jpg --blcoldev=0.05 --imauto=0
If
by trying all 3 steps - no copy-move tamperings revealed - there is a
good chance that really there are no such tamperings in image. BTW,
script has more parameters, full list of them -
python detect_copymove.py --help
link:http://coding-experiments.blogspot.in/2009/03/detecting-copy-move-forgery-in-images.html
//Aman@Aman-Lenovo-G580:~/Desktop/pl2_image$ python detect_image.py 1.jpgAnalyzing image, please wait... (can take some minutes)
Done. Found 0 identical regions
Output is saved in file - 1_analyzed.jpg
Aman@Aman-Lenovo-G580:~/Desktop/pl2_image$ python detect_image.py 2.jpgAnalyzing image, please wait... (can take some minutes)
Done. Found 2 identical regions
Output is saved in file - 2_analyzed.jpg
#python 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.
"""
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.
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 >= float(opt.blcoldev):
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
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))
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
"""Output
Aman@Aman-Lenovo-G580:~/Desktop/pl2_image$ python detect_image.py 1.jpgAnalyzing image, please wait... (can take some minutes)
Done. Found 0 identical regions
Output is saved in file - 1_analyzed.jpg
"""
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.:17
/* TITLE :17 Write a program for Identifying the tampering of digital signature using Python
//============================================================================*/
import fractions #gcd
def generateRSAKeys(p, q):
"Generate RSA Public and Private Keys from prime numbers p & q"
n = p * q #is used as the modulus for both the public and private keys
etf = (p - 1) * (q - 1) #Euler's totient function. etf
# Generate a number e so that gcd(n, e) = 1, start with e = 7
e = 7
while 1:
if fractions.gcd(e, etf) == 1 and 1<e and e<etf:
break
else:
e = e + 1
#e is released as the public key exponent.
# start with a number d = etf/e will be atleast 1
#e*d == 1%etf #multiplicative inverse of etf
d = (e**(etf-2)) % etf
# Return a tuple of public and private keys
return ((n,e), (n,d))
if __name__ == "__main__":
p =int(input("Enter the value of p (prime number):"))
q =int(input("Enter the value of q (prime number):"))
print ("Generating public and private keys....")
(publickey, privatekey) = generateRSAKeys(p, q)
print ("Public Key (n, e) =", publickey)
print ("Private Key (n, d) =", privatekey)
n, e = publickey
n, d = privatekey
m = r= int(input("Enter number to be encrypted:"))
print ("0<m<n m=", m)
print ("0<m<n n=", n)
#then computes ciphertext c
#c = pow(m,e,n)
c = (m**e)%n
print ("Encrypted number using public key =", c)
#recovering
m = (c**d)%n
print ("Decrypted (Original) number using private key =", r)
"""output
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~$ cd Desktop
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ python c2.py
Enter the value of p (prime number):3
Enter the value of q (prime number):7
Generating public and private keys....
('Public Key (n, e) =', (21, 7))
('Private Key (n, d) =', (21, 1))
Enter number to be encrypted:7
('0<m<n m=', 7)
('0<m<n n=', 21)
('Encrypted number using public key =', 7)
('Decrypted (Original) number using private key =', 7)
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ """
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.:18
/* TITLE :18 Write a C++/Java program for Log Capturing and Event Correlation.
//============================================================================*/
//Log Capturing
import java.io.*; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Scanner; import java.util.*; import java.lang.*; //import java.sql.Date; import java.text.DateFormat; public class logtest { public static void main(String[] args) throws IOException { String userName; String passWord; FileWriter fw=null; Date dNow = new Date( ); SimpleDateFormat ft = new SimpleDateFormat("yyyy/MM/dd'T'HH:mm:ss'Z'"); 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"); System.out.println("\nlogin with username "+ userName +" on "+ ft.format(dNow)); System.out.println("\n"); } else { System.out.println("Unsuccessfully login"); fw.write("\nUnsuccessful login with username "+userName +" on "+ ft.format(dNow)); fw.append("\n"); System.out.println("\nUnsuccessful login with username "+userName +" on "+ ft.format(dNow)); System.out.println("\n"); } fw.close(); } } /*output ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac logtest.java ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java logtest Enter UserName: admin Enter PassWord admin Successfully login login with username admin on 2015/09/22T12:39:10Z ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ javac logtest.java ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ java logtest Enter UserName: rks Enter PassWord admin Unsuccessfully login Unsuccessful login with username rks on 2015/09/22T12:39:25Z */
//Event Correlation.
import java.awt.EventQueue;
import java.awt.BorderLayout;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import java.awt.Color;
import javax.swing.BorderFactory;
import javax.swing.border.Border;
import java.awt.event.MouseListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseWheelListener;
import java.awt.event.MouseWheelEvent;
import java.awt.event.MouseMotionListener;
public class b_18 {
JLabel mouseLabel;
JLabel mouseMoveLabel;
JTextArea mouseEvents;
//Note: Typically the main method will be in a
//separate class. As this is a simple one class
//example it's all in the one class.
public static void main(String[] args) {
//Use the event dispatch thread for Swing components
EventQueue.invokeLater(new Runnable()
{
@Override
public void run()
{
new MouseLabel();
}
});
}
public MouseLabel()
{
JFrame guiFrame = new JFrame();
//make sure the program exits when the frame closes
guiFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
guiFrame.setTitle("Mouse Event Example");
guiFrame.setSize(700,300);
//This will center the JFrame in the middle of the screen
guiFrame.setLocationRelativeTo(null);
//creating a border to highlight the label areas
Border outline = BorderFactory.createLineBorder(Color.black);
//mouseLabel will trigger the Mouse click evetns
mouseLabel = new JLabel("Interactive Label", JLabel.CENTER);
mouseLabel.setBorder(outline);
//Attach the MouseListener to mouseLabel
//as an anonymous inner class.
//Each method changes the test of mouseLabel and
//logs the mouse event in the JTextArea
mouseLabel.addMouseListener(new MouseListener()
{
@Override
public void mouseClicked(MouseEvent e)
{
mouseLabel.setText("I've been clicked!");
mouseEvents.append("MouseClicked Event");
mouseEvents.append(e.getClickCount() + " click(s)\n");
mouseEvents.append("Xpos: " + e.getX() + " Ypos: " + e.getY() + "\n");
}
@Override
public void mousePressed(MouseEvent e)
{
mouseLabel.setText("You're holding the mouse button aren't you?");
mouseEvents.append("MousePressed Event\n");
}
Assignment Group C: Advance Technology Assignments (Any One)
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 02
/* TITLE : 2 Implement a program to generate and verify CAPTCHA image.
//============================================================================*/
//c++ program
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
static const char arr[] =
"0123456789"
"!@#$%^&*"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
int strlength = sizeof(arr) - 1;
char randomno()
{
return arr[rand() % strlength];
}
int main()
{
int ch,roll,flag=0;
char str[5],name[5],code[5];
do
{
//clrscr();
cout<<"\t\t\tName: ";
cin>>name;
cout<<"\t\t\tRoll no: ";
cin>>roll;
cout<<"\t\t\tCaptcha: ";
srand(time(0));
for( int i = 0; i <5; ++i)
{
str[i] = randomno();
}
for(int i=0;i<5;i++)
cout << str[i];
cout<<"\n\t\t\tEnter Captcha: ";
cin>>code;
for(int i=0;i<5;i++)
{
if(str[i]==code[i])
{
flag=0;
}
else
{
flag=1;
break;
}
}
if(flag==0)
{
cout<<"\t\t\tCode Match..!!";
}
else
{
cout<<"\t\t\tInvalid Code please try again...!!!";
}
cout<<"\n\t\t\t-------------------";
cout<<"\n\t\t\t1.Refresh\t2.Exit ";
cin>>ch;
}while(ch==1);
}
/*********************OUTPUT****************
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ g++ captcha.CPP
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$ ./a.out
Name: avi
Roll no: 12
Captcha: GsjNv
Enter Captcha: GsjNv
Code Match..!!
-------------------
1.Refresh 2.Exit 1
Name: avi
Roll no: 12
Captcha: tgVm5
Enter Captcha: sdas5
Invalid Code please try again...!!!
-------------------
1.Refresh 2.Exit 2
ccpvg@ccpvg-HP-Compaq-4000-Pro-SFF-PC:~/Desktop$
*/
<!--HTML Program-->
<html>
<head>
<script type="text/javascript">
function Captcha(){
var alpha = new Array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',0,1,2,3,4,5,6,7,8,9,'@','$','#','*');
var i;
for (i=0;i<6;i++){
var a = alpha[Math.floor(Math.random() * alpha.length)];
var b = alpha[Math.floor(Math.random() * alpha.length)];
var c = alpha[Math.floor(Math.random() * alpha.length)];
var d = alpha[Math.floor(Math.random() * alpha.length)];
var e = alpha[Math.floor(Math.random() * alpha.length)];
var f = alpha[Math.floor(Math.random() * alpha.length)];
var g = alpha[Math.floor(Math.random() * alpha.length)];
}
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("mainCaptcha").value = code
}
function ValidCaptcha(){
var string1 = removeSpaces(document.getElementById('mainCaptcha').value);
var string2 = removeSpaces(document.getElementById('txtInput').value);
if (string1 == string2){
return true;
}
else{
return false;
}
}
function removeSpaces(string){
return string.split(' ').join('');
}
</script>
</head>
<body onload="Captcha();">
<table>
<tr>
<td>
Text Captcha<br />
</td>
</tr>
<tr>
<td>
Username: <input type="text" name="username"><br>
Password : <input type="password" name="password"><br>
<input type="text" id="mainCaptcha"/>
<input type="button" id="refresh" value="Refresh" onclick="Captcha();" />
</td>
</tr>
<tr>
<td>
<input type="text" id="txtInput"/>
</td>
</tr>
<tr>
<td>
<input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
</td>
# Python code
#!/usr/bin/env python
#---------------------------------------------------------------------
# Import the necessary module.
#---------------------------------------------------------------------
import CaptchasDotNet
#---------------------------------------------------------------------
# Construct the captchas object. Replace the required parameters
# 'demo' and 'secret' with the values you receive upon
# registration at http://captchas.net.
#
# Optional Parameters and Defaults:
#
# alphabet: 'abcdefghkmnopqrstuvwxyz' (Used characters in captcha)
# We recommend alphabet without mistakable ijl.
#
# letters: '6' (Number of characters in captcha)
#
# width: '240' (image width)
# height: '80' (image height)
#
# Don't forget the same settings in check.cgi
#---------------------------------------------------------------------
captchas = CaptchasDotNet.CaptchasDotNet (
client = 'demo',
secret = 'secret'#,
#alphabet = 'abcdefghkmnopqrstuvwxyz',
#letters = 6,
#width = 240,
#height = 80
)
#---------------------------------------------------------------------
# Print html page
#---------------------------------------------------------------------
print 'Content-Type: text/html'
print '''
<html>
<head><title>Sample Python CAPTCHA Query</title></head>
<h1>Sample Python CAPTCHA Query</h1>
<form method="get" action="check.cgi">
<table>
<tr>
<td>
<input type="hidden" name="random" value="%s" />
Your message:</td><td><input name="message" size="60" />
</td>
</tr>
<tr>
<td>
The CAPTCHA password:
</td>
<td>
<input name="password" size="16" />
</td>
</tr>
<tr>
<td>
</td>
<td>
%s <br>
<a href="%s">Phonetic spelling (mp3)</a>
</td>
</tr>
<tr>
<td>
</td>
<td>
<input type="submit" value="Submit" />
</td>
</tr>
</table>
</form>
</html>
''' % (captchas.random (), captchas.image (), captchas.audio_url ())
#---------------------------------------------------------------------
# End
#---------------------------------------------------------------------
//java Program
import java.util.*;
import java.io.*;
public class Captcha
{
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
{
Captcha captcha = new Captcha();
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))
{
System.out.println("Both strings are same....");
}
else
{
System.out.println("Both strings are not same....");
}
}
}
/*---------------------------------------------------
OUTPUT
-----------------------------------------------------
administrator@administrator-Vostro-230:~/Desktop/TE_07/PL_02/Assgnmnt02$ javac Captcha.java
Note: Captcha.java uses or overrides a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
administrator@administrator-Vostro-230:~/Desktop/TE_07/PL_02/Assgnmnt02$ java Captcha
Randomly Selected Captcha string is : bKM5L
Enter Captcha String name :
bKM5L
Both strings are same....
administrator@administrator-Vostro-230:~/Desktop/TE_07/PL_02/Assgnmnt02$ java Captcha
Randomly Selected Captcha string is : qe6Ji
Enter Captcha String name :
Qe6ji
Both strings are not same....
administrator@administrator-Vostro-230:~/Desktop/TE_07/PL_02/Assgnmnt02$
*/
//============================================================================
// Author: Aman Bohra
// ( bohraaman.blogspot.in)
// ROLL NO : 007
// CLASS : TE(COMPUTER)
// BATCH : T1
// ASSIGNMENT NO.: 06
/*
TITLE :6 Set up a small wireless sensor network of few nodes and show communication between two
nodes using NS3 or equivalent
//============================================================================*/
INSTALLING NS3 IN UBUNTU 12.10
once ubuntu is installed run following command opening your terminal(ctrl+alt+T).
To install prerequisites-
sudo apt-get install gcc g++ python python-dev mercurial bzr gdb valgrind gsl-bin libgsl0-dev libgsl0ldbl flex bison tcpdump sqlite sqlite3 libsqlite3-dev libxml2 libxml2-dev libgtk2.0-0 libgtk2.0-dev uncrustify doxygen graphviz imagemagick texlive texlive-latex-extra texlive-generic-extra texlive-generic-recommended texinfo dia texlive texlive-latex-extra texlive-extra-utils texlive-generic-recommended texi2html python-pygraphviz python-kiwi python-pygoocanvas libgoocanvas-dev python-pygccxml
(now make sure you have not run sudo su to be superuser)
Downloading NS-3(ns-3 version 3.19 not 3.13)
cd
mkdir ns3
cd ns3
wget http://www.nsnam.org/release/ns-allinone-3.19.tar.bz2
tar xjf ns-allinone-3.19.tar.bz2
cd ns-allinone-3.19/
ls
Then you can find build.py along with other files.
Then to build the examples in ns-3 run
./build.py --enable-examples --enable-tests
If the build is successful then it will give output
"Build finished successfully".(clap for yourself)
Now run the following command to configure with waf(build tool)
./waf -d debug --enable-examples --enable-tests configure
To build with waf(optional)
./waf
To test everything allright
./test.py
If the tests are ok the installation is done. :)
After installing ns3 what to do??
make sure you are in directory where waf script is available then run
./waf --run first
and you will probably get
At time 2s client sent 1024 bytes to 10.1.1.2 port 9
At time 2.00369s server received 1024 bytes from 10.1.1.1 port 49153
At time 2.00369s server sent 1024 bytes to 10.1.1.1 port 49153
At time 2.00737s client received 1024 bytes from 10.1.1.2 port 9
then you can replace first by second,third till seven to get different outputs.note that you are running files of directory ../examples/tutorials which are of .cc extension but you have not used .cc in your command.
Next thing you need to know is put your programs in scratch directory so that you have not to make entry in wscript file.for eg copy availabe prigrams in scratch directory using different filename and try to run them.
ok the above information can also be found in ns3 tutorial but more important points for you can be:
1)ns3 can be used to generate .xml, .pcap, .csv, .dat files.
2)Netanim will be used to visualize your output that will use .xml file.
3).pcap is packet capture file you can open it using wireshark or tcpdump.
4)you can open .csv by just double clicking it(by Libre office).
5).dat is just your file to store data that can be used by .gnuplot script written by you to generate different graphs.
if you are new to netanim, gnuplot or wireshark don't panic i will probably write some intro that will help you to get started with them.
No comments :
Post a Comment