I’m trying to make a TCP port scanner, but I’m sticking to a very simple example that I lined together from a more advanced example I found online.
I don’t get any errors.
I’m expecting the code to show me that port 80 is open since I started my Apache server on my Linux box.
Here is the code:
#!/usr/bin/python
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
from scapy.all import *
ip = "127.0.0.1"
port = 80
response = sr1(IP(dst=ip)/TCP(dport=port, flags="S"),verbose=False, timeout=0.2)
if response :
if response[TCP].flags == 18 :
print "Port open"
Warning I had (but that does not show up any more):
WARNING: No route found for IPv6 destination :: (no default route?)
I read that including these two lines below would help on the error:
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)
Nmap scan:
STATE SERVICE
80/tcp open http
The output is… Nothing at all.
I tried several things like changing the port to different other ports, some which I had open and some which I did not.
Any ideas as to what I did wrong?
The scapy docs mention that the loopback address is a special case
The loopback interface is a very special interface. Packets going
through it are not really assembled and dissassembled. The kernel
routes the packet to its destination while it is still stored an
internal structure. What you see with tcpdump -i lo is only a fake to
make you think everything is normal. The kernel is not aware of what
Scapy is doing behind his back, so what you see on the loopback
interface is also a fake. Except this one did not come from a local
structure. Thus the kernel will never receive it.
In order to speak to local applications, you need to build your
packets one layer upper, using a PF_INET/SOCK_RAW socket instead of a
PF_PACKET/SOCK_RAW (or its equivalent on other systems that Linux):
>>> conf.L3socket
<class __main__.L3PacketSocket at 0xb7bdf5fc>
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
<IP version=4L ihl=5L tos=0x0 len=28 id=40953 flags= frag=0L ttl=64 proto=ICMP chksum=0xdce5 src=127.0.0.1 dst=127.0.0.1 options=''
|\>
However testing this on my OS-X machine results in the following error:
>>> conf.L3socket=L3RawSocket
>>> sr1(IP(dst="127.0.0.1")/ICMP())
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/sendrecv.py", line 334, in sr1
s=conf.L3socket(filter=filter, nofilter=nofilter, iface=iface)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/scapy/supersocket.py", line 64, in __init__
self.ins = socket.socket(socket.AF_PACKET, socket.SOCK_RAW, socket.htons(type))
AttributeError: 'module' object has no attribute 'AF_PACKET'
So your mileage may vary
EDIT
Apparently this is a known bug in scapy on BSD like systems (including OS-X): http://bb.secdev.org/scapy/issue/174/sniffing-loopback-in-mac-os-x-darwin
Related
I'm on a 2020.4 Kali Linux VM on VMWare Workstation 16 Player and I'm working with the Black Hat Python book by Justin Seitz. Right in the beginning of Chapter 2 he introduces a basic UDP client but for some reason, I get thrown a ConnectionResetError every time because either the port I'm sending to or the port I'm receiving from is occupied. I then added a line to make it bind to the address I'm sending to and it worked. Is it not automatically binding when I sendto()? If I'm pentesting, I shouldn't need the password/admin to bind when I make a UDP client.
Here is my code:
import socket
address = ('127.0.0.1', 80)
# Create a socket object.
client = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
# I commented this out just for testing reasons.
# client.bind(address)
# Send some data.
client.sendto(b'AAABBBCCC', address)
# Receive some data.
data, addr = client.recvfrom(4096)
print(data)
Here's the error:
Traceback (most recent call last):
File ".\udp_client.py", line 15, in <module>
data, addr = client.recvfrom(4096)
ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host
I apologize in advance if this is some dumb mistake on my part.
EDIT:
I changed the code to use a different port (65536) yet now it just doesn't print anything or end the script, it just keeps running.
I'd suggest you try using a port other than port 80 (default for all HTTP traffic) which is likely being used constantly and isn't a good port to try and hold onto, try port numbers > 1023
I use mcpi: https://github.com/AdventuresInMinecraft/AdventuresInMinecraft-Linux
Starting the local server.
After, run program:
import mcpi.minecraft as minecraft
mc = minecraft.Minecraft.create()
mc.postToChat("Hello Minecraft World")
I am facing the below error:
Traceback (most recent call last):
File "/home/home/AdventuresInMinecraft/MyAdventures/HelloMinecraftWorld.py", line 2, in mc = minecraft.Minecraft.create()
File "/home/home/.local/lib/python3.6/site-packages/mcpi/minecraft.py", line 376, in create return Minecraft(Connection(address, port))
File "/home/home/.local/lib/python3.6/site-packages/mcpi/connection.py", line 17, in init self.socket.connect((address, port))
ConnectionRefusedError: [Errno 111] Connection refused
A ConnectionRefusedError means that the address + port combination was unable to be secured for this particular Minecraft server and thus raised an exception. This could be because some other application is already using the port of interest, the port is unavailable because of the OS, or a handful of other networking configuration mishaps.
But perhaps a better series of questions to ask yourself is:
What is the default address and port that minecraft.Minecraft.create() will attempt to launch / listen at?
Do I have access to that server (address + port)?
If I do have access, are there any security issues (AKA Firewall)?
This post has already addressed the root issue of your question, and I hope it gives you a good start at understanding the foundation of your problem.
Notice how their question mentions s.connect((host,port)) and your stack trace has self.socket.connect((address, port)) Looks like the same thing to me!
Some more reading:
- localhost
- check if port is in use
I encountered the same issue. I looked into the code of mcpi and found that the default port is 4711. However, a Minecraft Server's default port is 25565. All you need to do is add 2 parameters on the create() function. Code(Python):
mc = minecraft.Minecraft.create(address="127.0.0.1", port=25565)
btw change "address" in the code to the host of the server (only if you modified the "server.properties" file).
Also, ConnectionRefusedError doesn't mean that it's not secured, I believe it means that either the server is not online, it doesn't exist, or the server refused it for some reason.
EDIT:
Oops sorry I just found out that mcpi actually connects to the RaspberryJam plugin which is hosted on another IP and port. The plugin runs on port 4711. So mcpi has the right port.
So check if you have the RaspberryJam plugin installed. If not, download it from
https://www.spigotmc.org/resources/raspberryjuice.22724/
And put the .jar file inside the plugins folder in your server directory.
I am trying to communicate Python with the CPU1212C PLC (using PLCSIM), but an error always occurs.
Code:
IP = '192.168.100.100'
RACK = 0
SLOT = 1
plc = snap7.client.Client()
plc.connect(IP, RACK, SLOT)
print(plc.get_cpu_state())
No handlers could be found for logger "snap7.common"
Traceback (most recent call last):
File "C:/Python27/Teste_Snap7.py", line 8, in plc.connect(IP, RACK, SLOT)
File "C:\Python27\lib\site-packages\snap7\client.py", line 25, in f check_error(code, context="client")
File "C:\Python27\lib\site-packages\snap7\common.py", line 65, in check_error raise Snap7Exception(error)
Snap7Exception: TCP : Connection timed out
Is this a problem with Windows10?
I am using Windows10 64 bit, Python 2.7.17, Snap7 1.1.0, Python-Snap7 0.10.
I copied and pasted the snap7.dll and snap7.lib file into the System32, Python27, Python27 / site-packages / snap7 folders. And I created for each folder a path in the environment variables in an attempt to work.
I followed this tutorial: https://www.youtube.com/watch?v=BKnK4AT_WKs
It's not a problem related with Windows, in the error message you can see the problem:
Snap7Exception: TCP : Connection timed out.
Verify your physical connection to the machine and then verify the client IP.
Verify:
if PLC actually ping
if Snap7 server is enabled on your PC
if rack and slot are correct, according to your PLC.
The handbook provided with snap7 is very exhaustive, please refer to it
Verify in tia portal:
properties > Protection and security > connection mechanism > and check the "permit acess with PUT/GET.."
I have been trying to get the ipaddress of the person who logged into the machine using the below code but I get a error.
>>> import socket
>>> socket.gethostbyname_ex(socket.gethostname())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
socket.gaierror: [Errno -2] Name or service not known
The same code works in other linux box.
Not sure I fix it.
Error has occurred just because of not setting up hostname properly. Set the hostname at three different places, which are in -
/etc/hostname
/etc/hosts
run command $ hostname
then logout and login again. You are done.
Check what is being returned by socket.gethostname() and see if you can ping it. Basically this is a lookup failure. Check your /etc/hosts to see if it is listed. I know it seems strange, but I think if the hostname being returned does not have an entry, you'll get a name service failure which is what that is.
If you are working with IPv6 or with servers with multiple network interfaces, this command will not work correctly.
Instead, you can use this command that tries to connect to the Google DNS server at 8.8.8.8 at port 53, and return your ip:
import socket
print([(s.connect(('8.8.8.8', 53)), s.getsockname()[0], s.close()) for s in [socket.socket(socket.AF_INET, socket.SOCK_DGRAM)]][0][1])
I have a problem with a python server I am creating. It works on my home machine, but when I've tried to run it on a different machine it does not work. When compiled using pyinstaller, the window immideatly closes, and when ran as a raw python file (python 2.7.10 is installed on both my home machine and the machine it is not working on) it throws the error:
Traceback (most recent call last):
File "fileModifyServer.py", line 136, in <module>
startServer()
File "fileModifyServer.py", line 11, in startServer
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
File "N:\Python27\lib\socket.py", line 191, in __init__
_sock = _realsocket(family, type, proto)
socket.error: [Errno 10022] An invalid argument was supplied
My code it is referencing to is as follows:
import socket
def startServer():
global serversocket
serversocket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
serversocket.bind((socket.gethostname(), 8010))
serversocket.listen(5)
print "Server started"
The traceback you have is strange. It indicates a line when attempting to instantiate the socket, which would indicate a problem with your python installation or network stack. It also indicates that error occurred on line 11, but in your code the line in question appears on line 6. I'm not sure how it happened here, but I know this can happen if you edit files while your program is running and then it crashes. The traceback simply prints out the line number from the file in question that caused the error, and the file source doesn't appear to be read until the error occurs; Therefore the traceback will reflect the line in the modified file, which isn't the line that was present when the program was compiled, and thus is not the line that actually caused the problem.
Without looking at the traceback, I do see an error with your code. You are attempting to bind your server to an invalid interface. The hostname returned by socket.gethostname is not an interface. From the documentation:
If you want to know the current machine’s IP address, you may want to use gethostbyname(gethostname()).
This operation assumes that there is a valid address-to-host mapping for the host, and the assumption does not always hold.
# for example
local_ip_address = socket.gethostbyname(socket.gethostname())
Which will return a string representation of your local ip address. Unfortunately, that would still throw an error, as it is not an interface that you can bind to.
Some interfaces that you can bind to include "0.0.0.0", which means all available interfaces, and "localhost", which means "local" connections only, so no external network traffic allowed.