python script in relation to the spike fuzzer connecting to vulnserver.exe - python

ok so i have vulnserver.exe running on my win7 box waiting for input on port 9999. It takes in certain commands with parameters one of which is TRUN and is designed to trigger a buffer overflow if the TRUN parameters are the right length:
this is the python im running on kali linux to try to connect to vulnserver and see if can cause a crash:
import socket
numAs = 10
try:
while True:
# open a connection to vulnserver
s = socket.socket (socket.AF_INET, socket.SOCK_STREAM)
s.connect (("194.168.1.154", 9999))
# receive the banner for vulnserver
s.recv (1024)
print "[*] Sending " + str(numAs) + " As"
# send the number of As to fuzz the HTER command
s.send ("HTER " + "A" * numAs + " \r\n")
# receive the response from vulnserver
s.recv (1024)
# close the connection
s.close ()
# increase the number of As we send next time
numAs += 10
except:
# if we get to here then something happened to vulnserver because the
connection is closed
print "Socket closed after sending " + str(numAs - 10) + " As"
however here is the command line output im getting
./hterfuzz.py: line 2: numAs: command not found
./hterfuzz.py: line 3: try:: command not found
./hterfuzz.py: line 6: syntax error near unexpected token `('
./hterfuzz.py: line 6: `s = socket.socket (socket.AF_INET,socket.SOCK_STREAM)'
Im very new to python and dont understand some basic errors so any help would be greatly appreciated. Thanks so much !
also the vulnserver.exe program is available here :
http://sites.google.com/site/lupingreycorner/vulnserver.zip
and the tutorial on fuzzing using vulnserver is here:
https://samsclass.info/127/proj/vuln-server.htm
if there is any other info I can provide just ask, Im simply trying to fix the errors in the py script so I can play around with it to try and find out whats needed to cause the overflow and eventually modify it to create a useful input string to execute processes on the win7 box by sending the string to vulnserver.
Thanks for any help people :)

Quite a simple one this - your script is being interpreted by bash, not python.
Just add this as the first line of your code: #!/usr/bin/python

Related

Python script crashes when I run opc.write () using OpenOpc

I am making a python program to write variables to an opc DA server.
I have the connection and others, but when trying to write values ​​for a variable, the program does not respond and a windows error message appears saying:
My code:
import OpenOPC
import sys
opc = OpenOPC.client()
servers = opc.servers()
idServer = int(2)
print('connecting to opc server:', servers[idServer])
opc.connect(servers[idServer])
print('connection okey:', servers[idServer])
write = opc.write(('variableName', 1))
print('write:', write)
input('> ')
Does anyone know why the program crashes when it reaches that part? Thanks a lot

Checking FTP connection is valid using NOOP command

I'm having trouble with one of my scripts seemingly disconnecting from my FTP during long batches of jobs. To counter this, I've attempted to make a module as shown below:
def connect_ftp(ftp):
print "ftp1"
starttime = time.time()
retry = False
try:
ftp.voidcmd("NOOP")
print "ftp2"
except:
retry = True
print "ftp3"
print "ftp4"
while (retry):
try:
print "ftp5"
ftp.connect()
ftp.login('LOGIN', 'CENSORED')
print "ftp6"
retry = False
print "ftp7"
except IOError as e:
print "ftp8"
retry = True
sys.stdout.write("\rTime disconnected - "+str(time.time()-starttime))
sys.stdout.flush()
print "ftp9"
I call the function using only:
ftp = ftplib.FTP('CENSORED')
connect_ftp(ftp)
However, I've traced how the code runs using print lines, and on the first use of the module (before the FTP is even connected to) my script runs ftp.voidcmd("NOOP") and does not except it, so no attempt is made to connect to the FTP initially.
The output is:
ftp1
ftp2
ftp4
ftp success #this is ran after the module is called
I admit my code isn't the best or prettiest, and I haven't implemented anything yet to make sure I'm not reconnecting constantly if I keep failing to reconnect, but I can't work out why this isn't working for the life of me so I don't see a point in expanding the module yet. Is this even the best approach for connecting/reconnecting to an FTP?
Thank you in advance
This connects to the server:
ftp = ftplib.FTP('CENSORED')
So, naturally the NOOP command succeeds, as it does not need an authenticated connection.
Your connect_ftp is correct, except that you need to specify a hostname in your connect call.

Telnet connection to TS3 ServerQuery keeps getting slower and slower

I wrote a bot for TeamSpeak 3 that runs over ServerQuery (a telnet interface).
But the bot keeps responding later and later, in the beginning it takes like 0.1 sec, after like 1 minute the bot takes about 10 seconds to respond, and using commands makes it even faster.
Any idea why?
So basically the telnet interface sends data from the TS3 Server to my python script, the ts3 module recieves and processes the data, then the script will make a decision of what the action will be.
As modules I am using MySQLdb and ts3(https://github.com/benediktschmitt/py-ts3)
My sourcecode is here: https://pastebin.com/cJuyB9ZH
Another script, which just takes all clients and pushes them into a database every 5 min, runs multiple days without any issues.
I checked the code multiple times now and even deleted variables right after they have been used, but it still has the same issue.
My guess would be that is sortof clogges the RAM, so I looked through the code multiple times, but couldn't find out why or where.
Sidenote: I know I sometimes call a commit() when its totally not necessary, but I don't know if that might cause problems, but I dont see how.
Short(er) version of my code:
import ts3
import MySQLdb
# Some other imports like time and threading and such
## Connect to TS3
tsConn = ts3.query.TS3Connection(tsAddr, tsPort)
try:
tsConn.login(client_login_name=tsUser, client_login_password=tsPass)
tsConn.use(sid=tsSID, virtual=True)
print(" ==>> CONNECTED TO TS3 SERVER: " + tsAddr)
except ts3.query.TS3QueryError as e:
print("Login to TS Server failed! Aborting...")
exit(1)
## Connect to mySQL
try:
qConn = MySQLdb.connect(host=qHost, user=qUser, passwd=qPass, db=qDB)
qServer = qConn.cursor()
print(" ==>> CONNECTED TO mySQL SERVER: " + qHost)
except OperationalError:
print("Cannot connect to mySQL Database! Aborting...")
exit(1)
running = True
while running:
tsConn.send_keepalive()
qServer.execute("SELECT 1") # keepalive
try:
e = tsConn.wait_for_event(timeout=1)
except TS3TimeoutError:
pass
else:
try:
# <some command processing here>
except KeyError:
try:
if event[0]["reasonid"] == "0":
tsConn.sendtextmessage(targetmode=1, target=event[0]["clid"], msg=greetingmsg.format(event[0]["client_nickname"]))
except:
pass

How to check if there is a SSH hostname resolution error

I'm using Python to automate copying binaries off a network sensor using scp. I want to add in some error checking and I can't figure out how to reliably check if SSH throws errors, such as a hostname resolution error. I'm currently using .communicate() to collect stdout, and then matching on "ssh" in the error message. The reason I'm checking if err starts with "ssh" is because if no error is thrown, that err variable contains the banner of the sensor it's logging in to, so I don't really have a way to reliably check if err actually has a value or not (If that makes sense). I'm also checking error codes in case a file is not found or some other error is tossed. Is there a better method?
This is the currently working code:
sp = Popen(['scp', '#'.join([self.user, self.sensor]) + ':{0}{1}'.format(self.binPath, self.binName), self.storePath], stdout = PIPE, stderr = PIPE)
data, error = sp.communicate()
if error.startswith("ssh"):
print("ERROR: {}".format(error))
else:
if sp.returncode == 1:
print("ERROR: {} - No such file or directory".format(self.binPath + self.binName))
elif sp.returncode == 0:
self.hashCMP(self.storePath, self.binName, md5Sum)
else:
pass
Would one way around this be to create a test for the domain? For example using something like:
from socket import getaddrinfo
result = getaddrinfo("www.google.com", None)
print result[0][4]
I notice you are using popen - if your OS has nc (netcat) could you maybe run the command:
nc -v <host> <port> #I believe this uses the getaddrinfo under the hood as well ;-)
Thanks,
//P

paramiko ssh client does not work with HP switches

I've been using my script for a unix server and it's working perfectly. However when i use the same script( with some minor command changes) to connect to HP Procurve switches , script crashes with error. Part of the script is below:
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(address, username=userna, password=passwd)
stdin,stdout,stderr= ssh.exec_command("show ver")
for line in stdout:
print '... ' + line.strip('\n')
ssh.close()
This gives error
Traceback (most recent call last):
File "C:/Users/kucar/Desktop/my_python/switchmodel", line 34, in <module>
stdin,stdout,stderr= ssh.exec_command("show ver")
File "C:\Python27\lib\site-packages\paramiko\client.py", line 379, in exec_command
chan.exec_command(command)
File "C:\Python27\lib\site-packages\paramiko\channel.py", line 218, in exec_command
self._wait_for_event()
File "C:\Python27\lib\site-packages\paramiko\channel.py", line 1122, in _wait_for_event
raise e
SSHException: Channel closed.
I've found similar complaints in the web however seems like solution is not provided at all. Switch is open to ssh and works fine with putty. Appreciate if you give any ideas that could help me. I cannot do "show ver" command manually for 100 switches.
As #dobbo mentioned above you have to do invoke_shell() on the channel so that you can execute multiple commands. Also HP ProCurve has ANSI Escape Codes in the output so you have to strip those out. Finally, HP ProCurve throws up a "Press any key to continue" message which you have to get past at least on some devices.
I have an HP ProCurve handler in this library https://github.com/ktbyers/netmiko
Set device_type to "hp_procurve".
Exscript also has some sort of a ProCurve handler though I haven't dug into it enough to get it to work.
I had the same experience connecting to my Samsung s4 phone with an ssh server.
I had no problem connecting to a SUSE VM or a Rasperry Pi and also tried MobaXterm (putty is SO last week).
I have not found the answer but will share my research.
I had a look at the source and found line 1122 in channel.py (copied below).
With my phone (and possibly your HP switch) I have noticed that there is no login message or MOTD at all and when exiting (with putty/mobaXterm) the session doesn't end properly.
In some other reading, I have found that the parameko is not getting much support from the author any more but others are working to port it to python 3x.
Here is the source code I found.
def _wait_for_send_window(self, size):
"""
(You are already holding the lock.)
Wait for the send window to open up, and allocate up to C{size} bytes
for transmission. If no space opens up before the timeout, a timeout
exception is raised. Returns the number of bytes available to send
(may be less than requested).
"""
# you are already holding the lock
if self.closed or self.eof_sent:
return 0
if self.out_window_size == 0:
# should we block?
if self.timeout == 0.0:
raise socket.timeout()
# loop here in case we get woken up but a different thread has filled the buffer
timeout = self.timeout
while self.out_window_size == 0:
if self.closed or self.eof_sent:
return 0
then = time.time()
self.out_buffer_cv.wait(timeout)
if timeout != None:
timeout -= time.time() - then
if timeout <= 0.0:
raise socket.timeout()
# we have some window to squeeze into
It seems that if you don't clean up the connection buffer Paramiko goes nuts when working with HP Procurves. First off you need to invoke a shell or Paramiko will simply drop the connection after the first command (normal behavior, but confusing).
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(switch_ip, username=switch_user, password=switch_pass,look_for_keys=False)
conn = ssh.invoke_shell()
recieveData() # <-- see below
It's important to actually handle the data, and as I've learned you need to make sure Paramiko has actually received all the data before you ask it to do stuff with it. I do this by using the following function. You can adjust the sleep as needed, in some cases 0.050 will work fine.
def recieveData():
tCheck = 0
while not conn.recv_ready():
time.sleep(1)
tCheck+=1
if tCheck >=10:
print "time out"
cleanThatStuffUp(conn.recv(1024)) # <-- see below
This is an example of the garbage that is returning to your ssh client.
[1;24r[24;1H[24;1H[2K[24;1H[?25h[24;1H[24;1HProCurve Switch 2650# [24;1H[24;23H[24;1H[?5h[24;23H[24;23Hconfigure[24;23H[?25h[24;32H[24;0HE[24;1H[24;32H[24;1H[2K[24;1H[?5h[24;1H[1;24r[24;1H[1;24r[24;1H[24;1H[2K[24;1H[?25h[24;1H[24;1H
There's also exit codes to deal with before each "[". So to deal with that I figured out some regex to clean all of that "stuff" up.
procurve_re1 = re.compile(r'(\[\d+[HKJ])|(\[\?\d+[hl])|(\[\d+)|(\;\d+\w?)')
procurve_re2 = re.compile(r'([E]\b)')
procurve_re3 = re.compile(ur'[\u001B]+') #remove stupid escapes
def cleanThatStuffUp(message):
message = procurve_re1.sub("", message)
message = procurve_re2.sub("", message)
message = procurve_re3.sub("", message)
print message
Now you can go about entering commands, just make sure you clear out the buffer each time using recieveData().
conn.send("\n") # Get past "Press any key"
recieveData()

Categories

Resources