Port Forwarding Help

Uncaptured Python Exception??

Page 1 of 1

3 Replies - 2432 Views - Last Post: 14 January 2009 - 09:26 PM Rate Topic: -----

#1 Arkwind  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 28-November 08

Port Forwarding Help

Posted 12 January 2009 - 01:35 PM

Hello !

Basically i have built an asynchronous port forwarding system that will log details abut connections on the local box

here is my code

import socket,asyncore,os,sys,datetime,time

def printer():						#pretty little heading!
	os.system("clear")
	print '_______________________________'
	print '|---------$ Tripwire $--------|'
	print '|-------Ear To The Wire-------|'
	print '|_____________________________|'

def log_it(read,client):				#takes in the data from the read buffer and the client data
	now = datetime.datetime.now()			#gets the date the only way this comp nows how (irritating)
	spacer = '	   '				#creates an asthetically pleaseing space for the logs
	logfile = open('/var/log/tripwire.log', 'a')	#opens log file
	logfile.write(str(now))				#logs the date in str format to the log first
	logfile.write(spacer)				#late nights and early mornings meant i needed a space in the log files for clarity
	logfile.write(str(client))			#writes where the connection is comming from onto the logs
	logfile.write(spacer)				#puts in another space for log clarity
	logfile.write(read)				#then appends the read data
	print(now ,read)				#prints it on screen for local admin to see - this is after logging cause its less important 
	logfile.close()					#closes the log file

class forwarder(asyncore.dispatcher):					#core to start the listening, if theres an error odds are its in here
	def __init__(self, ip, port, remoteaddr,remotepo,backlog=5):
		asyncore.dispatcher.__init__(self)
	self.remoteip=remoteaddr
		self.remoteport=remotepo

##################### Creates Socket ##########################
	try:		
		self.create_socket(socket.AF_INET,socket.SOCK_STREAM)
	except:
		print 'Socket Creation Error'
		exit()	 
	self.set_reuse_addr()
###################### Self Bind ###################
#STATEMENT HAS TO TAKE AN INTEGER!!!!! OR ELSE!!!!!#
####################################################
	try:	
		self.bind((ip,port))
	except:
		print 'Local Bind Error, Fatal Sorry!'
		exit()
###################### Self Listen ###########################
	try:	
		self.listen(backlog)
		print "- - - Listening Started - - -"
	except:
		print 'Self Listen Error'
		exit()

################### Accepting Connections ####################	

	def handle_accept(self):					#accept engine - god knows why but this is very tempremental and spits out some odd errors
	try:							#i added this try statement so when things go wrong it wont give the end user a pyth error
		conn, addr = self.accept()
		print '--- Connect --- '
		sender(receiver(conn),self.remoteip,self.remoteport)
	except:
		print "Accept Error,Refer To Source Code, Something Is Broken"
		exit()

################### Receiver #################################
# Gets run on an accepted connection #
######################################
class receiver(asyncore.dispatcher):
	def __init__(self,conn):						#core ___init___ code of the receiver module
	try:								#never had problems with this but stops python spilling python errors and replaces
		asyncore.dispatcher.__init__(self,conn)				#it with a slightly more english but less descriptive error
	   		self.from_remote_buffer=''
			self.to_remote_buffer=''
			self.sender=None
	except:
		print "Error In Core Receiver Module, Big Problems"
		exit
############ Remote Read ###
# Reads From REMOTE Buffer #
############################
	def handle_read(self):
		read = self.recv(4096)
	client = self.getpeername()
	log_it(read,client)					#logs the read buffer and client info
		self.from_remote_buffer += read				#appends read to the buffer

	def writable(self):
		return (len(self.to_remote_buffer) > 0)

############# Write ################
# Handles the written buffer #
# (Sent data) ################
###############
	def handle_write(self):					
		sent = self.send(self.to_remote_buffer)
		self.to_remote_buffer = self.to_remote_buffer[sent:]

############## Sender Closing ###################
# Handles the closing off connections by clients#
#################################################
	def handle_close(self):
		self.close()
	print '------Closed-------'
		if self.sender:
			self.sender.close()

################# Sender ########################
# Launched on a succesfull accepted connection #
#################################################
class sender(asyncore.dispatcher):
	def __init__(self, receiver, remoteip,remoteport):
	try:	   	
		asyncore.dispatcher.__init__(self)
			self.receiver=receiver
			receiver.sender=self
			self.create_socket(socket.AF_INET, socket.SOCK_STREAM)
			self.connect((remoteip, remoteport))
	except:
		print "Core sender module error, Big Problems"
		exit()
########### Local Read #####
# Reading the local buffer #
############################
	def handle_read(self):
		read = self.recv(4096)
	client = self.getpeername()
	log_it(read,client)					#logs the read buffer and client info 	
		self.receiver.to_remote_buffer += read			#appends read to the remote buffer

	def writable(self):
		return (len(self.receiver.from_remote_buffer) > 0)

################ Sent ####################
# Handles writing from the remote buffer #
##########################################
	def handle_write(self):
	try:		
		sent = self.send(self.receiver.from_remote_buffer)
			self.receiver.from_remote_buffer = self.receiver.from_remote_buffer[sent:]
	except:
		print "Handle_write error"
		exit()
############### Reciever Close ##########
# When Connection is closed by receiver #
#########################################
	def handle_close(self):							#closeing module for when a user has enough of our server
	try:
		print '-----Closed-----'   
		#needs to close socket and call the socket creation again	 
		self.close()
			self.receiver.close()
	except:
		print "Client close error, Doesnt Matter There Gone Now!"

printer()
###########################################################################
try:
	selection = raw_input("Launch Set Up? <yes/no>: ")			#allows command line users to escape to a commandline or else
	if selection == "yes":							#they get trapped in the programme and have to CTRL+C out which isnt good
		printer()
	elif selection == "y":
		printer()
	elif selection == "Yes":
		printer()
	elif selection == "Y":
		printer()
	elif selection == "no":
		print("Goodbye")		
		exit()
	elif selection == "n":
		print("Goodbye")
		exit()
	elif selection == "N":
		print("Goodbye")
		exit()
	elif selection == "No":
		print("Goodbye")
		exit()	
except:
		exit()
###########################################################################
try:
	local_ip = raw_input("Please Input LOCAL IP Address To Listen To :")	# inputs the local ip from user
except:
	print 'Input Local IP Was Invalid, Exiting ....'
	exit()
###########################################################################
try:
	local_port = input("Please Input LOCAL PORT To Bind To :")		# inputs local port from user HAS TO BE INTEGER OR ELSE!!
	if local_port == 21:
		pasv_port = input("Using FTP ?? Enter Passive Port :")		#needs to get the passive port or all hell break loose
		
except:
	print 'Input Local Port/Passive Port Was Invalid, Exiting .....'
	exit()
###########################################################################
try:
	remote_ip = raw_input("Please Input REMOTE IP To Forward To :")		# inputs remote ip from user
except:
	print 'Input Remote Ip Was Invalid, Exiting .....'
	exit()
###########################################################################
try:
	remote_port = input("Please Input REMOTE PORT To Forward To :")		# inputs remote port from user  HAS TO BE AN INTEGER OR ELSE!!
except:
	print 'Input Remote Port Was Invalid, Exiting .....'
	exit()
###########################################################################
printer()
if local_port == "21":	
	pid = os.fork()
	if pid:
		forwarder(local_ip,local_port,remote_ip,remote_port)
		asyncore.loop()
	else:
		forwarder(local_ip,pasv_port,remote_ip,remote_port)
		asyncore.loop()

else:	
		forwarder(local_ip,local_port,remote_ip,remote_port)
		asyncore.loop()	



sorry for the vauge comments, but when i set it up to port forward to my file server and then ftp to it i get this error message on the server side display

Accept Error,Refer To Source Code, Something Is Broken
error: uncaptured python exception, closing channel <__main__.forwarder listening 127.0.0.1:21 at 0xb7dd8e4c> (<type 'exceptions.SystemExit'>:None [/usr/lib/python2.5/asyncore.py|read|68] [/usr/lib/python2.5/asyncore.py|handle_read_event|384] [/home/solaris/tripwire/tripwire.py|handle_accept|60] [/usr/lib/python2.5/site.py|__call__|247])

i know the first bit of the error is my customer error message but the latter is some what cryptic, i would very much like this up and working again, can you help me ?

Is This A Good Question/Topic? 0
  • +

Replies To: Port Forwarding Help

#2 numerical_jerome  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 167
  • Joined: 16-September 07

Re: Port Forwarding Help

Posted 13 January 2009 - 11:27 PM

try running in pdb.

-Jerome
Was This Post Helpful? 0
  • +
  • -

#3 Arkwind  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 44
  • Joined: 28-November 08

Re: Port Forwarding Help

Posted 14 January 2009 - 12:00 PM

View Postnumerical_jerome, on 13 Jan, 2009 - 10:27 PM, said:

try running in pdb.

-Jerome



sorry, ignorance and innocence and all that, what is pdb?
Was This Post Helpful? 0
  • +
  • -

#4 numerical_jerome  Icon User is offline

  • D.I.C Head

Reputation: 12
  • View blog
  • Posts: 167
  • Joined: 16-September 07

Re: Port Forwarding Help

Posted 14 January 2009 - 09:26 PM

Python DeBugger, will allow you to step through your program line by line, set break points, get more detailed stack trace / exception info, et cetera.

http://docs.python.o...ibrary/pdb.html

(interace wise) based off of the old GNU GDB,

Hope this helps,

-Jerome
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1