python socket setsockopt with raw socket - python

Just send tcp_syn with python socket raw. I follow the code here, but when I run the code I got below error:
Traceback (most recent call last):
File "findPort.py", line 122, in <module>
s.sendto(packet, (dest_ip , 27015 )) # put this in a loop if you want to flood the target
socket.error: [Errno 22] Invalid argument
However, when I delete setsockopt:
#s.setsockopt(socket.IPPROTO_IP, socket.IP_HDRINCL, 1)
the code run smoothly. Unfortunately, as you can image, the wireshark sniff two tcp header data. one is the kernel add the other is myself add.
So the question is :
what does the error mean as I show above?
why I delete setsockopt the error disappear?
how can I send tcp_syn with python 2.7?
thanks so much in advance~~~~~~

Let me answer my own question. The main reason why python can not send raw socket because Mac/Windows not support customize TCP/UDP header. If you want to write your own TCP/UDP header and send it to net, you need to use LINUX operation system.

Related

Pyshark - tshark can't use user plugin in 'decode_as'

I use Pyshark that uses tshark to decode a pcap file, and I have a problem using 'decode_as' option.
I'm trying to decode a specific UDP port as SOMEIP protocol. This is a dissector I added that is taken from here.
It is important to say that both the dissector and the "decode_as" option work perfectly in Wireshark.
This is the code I use:
import pyshark
packets=pyshark.FileCapture(pcap_path, display_filter="udp")
packets.next() # Works fine
packets=pyshark.FileCapture(pcap_path, display_filter="udp", decode_as={"udp.port==50000":"someip"})
packets.next() # doesn't return a packet
There is also an ignored exception:
Exception ignored in: <function Capture.__del__ at 0x000001D9CE035268>
Traceback (most recent call last):
File "C:\Users\SHIRM\AppData\Local\Continuum\anaconda3\lib\site-packages\pyshark\capture\capture.py", line 412, in __del__
self.close()
File "C:\Users\SHIRM\AppData\Local\Continuum\anaconda3\lib\site-packages\pyshark\capture\capture.py", line 403, in close
self.eventloop.run_until_complete(self._close_async())
File "C:\Users\SHIRM\AppData\Local\Continuum\anaconda3\lib\asyncio\base_events.py", line 573, in run_until_complete
return future.result()
File "C:\Users\SHIRM\AppData\Local\Continuum\anaconda3\lib\site-packages\pyshark\capture\capture.py", line 407, in _close_async
await self._cleanup_subprocess(process)
File "C:\Users\SHIRM\AppData\Local\Continuum\anaconda3\lib\site-packages\pyshark\capture\capture.py", line 400, in _cleanup_subprocess
% process.returncode)
pyshark.capture.capture.TSharkCrashException: TShark seems to have crashed (retcode: 1). Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.
As it recommends I use debug mode(packets.set_debug()), and after running it I get:
tshark: Protocol "someip" isn't valid for layer type "udp.port"
tshark: Valid protocols for layer type "udp.port" are:
....
and then a long list of protocols, which "someip" is not in... (but another dissector that I added, and is dll, is)
Any idea what is wrong here?
Does the dissector causes the problems, or did I do something wrong?
Again- the "decode as" works fine when done manually in Wireshark.
Thanks!
EDIT
I found the part in Wireshark code that causes this error:
So I read about dissector tables, and it seems that there shouldn't be a problem, since the dissector lua code does add "someip" to the dissector table of "udp.port":
local udp_dissector_table = DissectorTable.get("udp.port")
-- Register dissector to multiple ports
for i,port in ipairs{30490,30491,30501,30502,30503,30504} do
udp_dissector_table:add(port,p_someip)
tcp_dissector_table:add(port,p_someip)
end
I also tried to use the dissectortable:add_for_decode_as(proto) function (described in 11.6.2.11 here):
udp_dissector_table:add_for_decode_as(p_someip)
But it didn't work :(
Any idea will be appreciated, thanks
Even though it is an old question:
I tried with a pcap of mine at it worked. So 3 suggestions:
There has been a bug, which is fixed now - then it should work for you now as well
The udp port is wrong. I do have a different one (30490) and if this one is wrong, the package will be empty. Please try with 50001, as this port shows on your screenshot
The pcap has some problems, in this case, try with another one.
Hope that helps!

Python Nmap - Argument Parsing

I'm trying to improve my python and working with the Violent Python book to help me do that.
One of the tasks is to create a Python nmap scanner, which I've done and can successfully scan a host, checking against a list of ports. However, the scanner is using the default -sV switch for version scanning, however I want to try and implement a way to change the type of scan that the user wants to run, i.e. -sU for UDP etc...
My code is available at: https://absentia.mycorneroftheinter.net/james/violentPythonScripts/src/master/chapter2/pyPortScanNmap.py
(It is a self-signed cert, so you will get a warning...)
Back to my question... when I try and code the option for a specify a different scanning option, such as -sU for UDP, the program crashes out saying that another argument is required - which is the IP address of the host to scan, however I would have already specified that using the -H 172.16.133.136 switch.
I think that I have missed something when I try and put different scan functionality in, because I thought specifying a different switch would just replace the default scan type that nmap.py uses(?)
Can someone shed any light on where I have gone wrong? You can see in the code I have comments where I have tried to implement the additional option, but alas, not successfully.
EDIT:
As per the comments below, when I supply the --ping switch for example, and then supply a random value to this, I get the following stack trace error returned:
Traceback (most recent call last):
File "pyPortScanNmap.py", line 88, in <module>
main()
File "pyPortScanNmap.py", line 62, in main
parser.add_option("", dest = 'tcpScan', type = 'string', help = 'Run TCP Scan') # Run a TCP scan against the specified host(s)
File "/usr/lib/python2.7/optparse.py", line 1013, in add_option
option = self.option_class(*args, **kwargs)
File "/usr/lib/python2.7/optparse.py", line 566, in __init__
opts = self._check_opt_strings(opts)
File "/usr/lib/python2.7/optparse.py", line 586, in _check_opt_strings
raise TypeError("at least one option string must be supplied")
TypeError: at least one option string must be supplied

using python to open a device for raw writing

I'm writing some code to read and interpret the MBR and then the FAT of a pen drive formatted with fat32, everything is going fine, I now want to write to the device at a specific position, so after closing the device I'd opened to read, I try again like this:
dr = file("/dev/disk5","r+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 16] Resource busy: '/dev/disk5'
So i close everything up, and restart the interpreter with sudo (sudo python), and retry all with the same results.
what can I do in order to be able to open the device for write access?
thanks
EDIT with some more code.
import sys,os
disk = file("/dev/disk5",'rb')
disk.seek(0)
sector_size=512
first_sector = disk.read(1*sector_size)
fat_part_list = (first_sector[-66:])[:64]
part1=fat_part_list[:16]
#more code here in order to analyse the first partition information in the MBR and get the required offset to actually read the partition itself.
#now for instance lets say I want to write here in sector 1 byte 0 ( so basically at seek(0).
disk.close()#close the device
disk = file("/dev/disk5","r+")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IOError: [Errno 16] Resource busy: '/dev/disk5'
in fact you could simply see the problem as this:
http://pastie.org/2521541
never got the formating to work properly...
it all seems like an privileges error, but running the interpreter with sudo yields no changes.
You should unmount the block device before opening it in Python.

Connecting to SQLServer 2005 with adodbapi

I'm very new to Python and I have Python 3.2 installed on a Win 7-32 workstation. Trying to connect to MSSQLServer 2005 Server using adodbapi-2.4.2.2, the latest update to that package.
The code/connection string looks like this:
conn = adodbapi.connect('Provider=SQLNCLI.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=XXX;Data Source=123.456.789');
From adodbapi I continually get the error (this is entire error message from Wing IDE shell):
Traceback (most recent call last):
File "D:\Program Files\Wing IDE 4.0\src\debug\tserver_sandbox.py", line 2, in
if name == 'main':
File "D:\Python32\Lib\site-packages\adodbapi\adodbapi.py", line 298, in connect
raise InterfaceError #Probably COM Error
adodbapi.adodbapi.InterfaceError:
I can trace through the code and see the exception as it happens.
I also tried using conn strings with OLEDB provider and integrated Windows security, with same results.
All of these connection strings work fine from a UDL file on my workstation, and from SSMS, but fail with the same error in adodbapi.
How do I fix this?
Try this connection string:
Initial Catalog=XXX; Data Source=<servername>\\<SQL Instance name>; Provider=SQLOLEDB.1; Integrated Security=SSPI
Update
Umm ok. Looking at the source for adodbapi I would have to say that you are suffering a COM error. (yeah I know the traceback says that). But specifically with initialising the relevant COM objects.
This means that your connection string has nothing to do with the traceback. I think a good place to start would be to make sure that your copy of pythoncom is up-to-date.
It could be that win32com/pythoncom does not support Python 3K (3.0 onwards) yet, but after a minute of googleing I have not found anything useful on that, I'll leave it to you.
This code should run successfully when you have fixed your problem (and should fail at the moment).
import win32com.client
import pythoncom
pythoncom.CoInitialize()
win32com.client.Dispatch('ADODB.Connection')
Also any exception that code throws would be useful to help debug your problem.
In case anyone else finds this thread looking for the resolution to a similar error that I saw with Python 2.7:
Traceback (most recent call last):
File "get_data.py", line 10, in <module>
connection = get_connection(r"XXX\YYY", "DB")
File "get_data.py", line 7, in get_connection
conn = adodbapi.connect(connstring)
File "C:\Python27\lib\site-packages\adodbapi\adodbapi.py", line 116, in connect
raise api.OperationalError(e, message)
adodbapi.apibase.OperationalError: (InterfaceError("Windows COM Error: Dispatch('ADODB.Connection') failed.",), 'Error opening connection to "Data Source=XXX\\YYY; Initial Catalog=DB; Provider=SQLOLEDB.1; Integrated Security=SSPI"')
In my case the simple solution was to install Python for Windows Extensions (pywin32) from here:
http://sourceforge.net/projects/pywin32/files/pywin32/Build%20219/
I had the same problem, and I tracked it down to a failure to load win32com.pyd, because of some system DLLs that was not in the "dll load path", such as msvcp100.dll
I solved the problem by copying a lot of these dll's (probably too many) into C:\WinPython-64bit-3.3.3.2\python-3.3.3.amd64\Lib\site-packages\win32

socket.getaddrinfo fails on one machine; works on another apparently-identical one. Why?

I've got a laptop and a desktop, both running Ubuntu 10.04, both running the stock Python 2.6.5 that comes with Ubuntu.
On the laptop, the following program
#!/usr/bin/env python
import socket
print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM))
works -- i.e., it prints out some stuff without getting an error.
The stuff, in fact, is:
[(10, 1, 6, '', ('::1', 8025, 0, 0)), (2, 1, 6, '', ('127.0.0.1', 8025))]
(That's one bunch of IPv6 data, and one bunch of IPv4 data.)
However, on the other box, the same program does this:
Traceback (most recent call last):
File "socktest.py", line 5, in <module>
print(socket.getaddrinfo("localhost", 8025, 0, socket.SOCK_STREAM))
socket.gaierror: [Errno -2] Name or service not known
Why?
The laptop is x86 (i.e., 32-bit) whereas the desktop is x86_64, but I'd be surprised if that mattered. The laptop also has two network interfaces (wireless and wired), whereas the desktop just has wired; again I doubt that's relevant. All three interfaces were bound to IPv6 addresses, according to "ifconfig". I diffed /etc/network on the two boxes, and saw no difference, except that the laptop has this clause
# The primary network interface
auto eth0
iface eth0 inet dhcp
... which, again, strikes me as irrelevant.
::
If you want some context: my Python program is trying to send email, and it's the email software that is ultimately calling getaddrinfo.
Check /etc/hosts on the box where it does not work. Is there an entry for localhost?
Also compare /etc/nsswitch.conf and see if there is anything suspicious, like missing 'hosts' line

Categories

Resources