Ejemplo n.º 1
0
def main():

 # assign arugments
 args = ArgumentParser()
 args.add_argument('username', help='email or username')
 args.add_argument('wordlist', help='password list')
 args.add_argument('threads', help='password per seconds. Any number <= 16')
 args = args.parse_args()

 if not exists(args.wordlist):
  exit('[!] Unable to locate `{}`'.format(args.wordlist))

 if not args.threads.isdigit():
  exit('[!] Threads must be a number')

 # assign variables
 engine = Bruter(args.username.title(), int(args.threads), args.wordlist)
 session = Session(args.username.title(), args.wordlist)

 if session.exists():
  if _input('Do you want to resume the attack? [y/n]: ').split()[0][0] == 'y':
   data = session.read()
   if data:
    engine.attempts = int(data['attempts'])
    engine.passlist.queue = eval(data['queue'])
    engine.retrieve = True

 # start attack
 try:
  engine.start()
 finally:
  if not engine.isFound:
   engine.display(engine.pwd)
   print('\n[!] Exiting ...')
  engine.stop()
Ejemplo n.º 2
0
    def initialize(self):
        self.db = mongo
        self.search_cache = Cache(master=False, db=config.Cache.searchdb)
        self.hot_image_cache = Cache(master=False, db=config.Cache.imagedb)
        self.queue = Queue()

        self.session = Session(self,
                               MemcacheStore(),
                               initializer={
                                   'nickname': None,
                                   'uid': None,
                                   'avatar': None,
                                   'email': None,
                                   'super': False,
                                   'channel': None,
                                   'login': False,
                                   'net': None,
                                   'reso': None,
                                   'height': 0,
                                   'width': 0,
                                   'show_msg': None,
                                   'hd': True
                               })
        self.session.processor(self)
        self.context = {
            'se': self.session,
            'static_server': config.Server.static_server,
            'cdn': config.CDN.mhost,
        }
Ejemplo n.º 3
0
def main():

 username = "******"
 wordlist = "password_9.txt"
 threads = "999999" 

 # assign variables
 engine = Bruter(username.title(), int(threads), wordlist)
 session = Session(username.title(), wordlist)

 if session.exists():
  if _input('Do you want to resume the attack? [y/n]: ').split()[0][0] == 'y':
   data = session.read()
   if data:
    engine.attempts = int(data['attempts'])
    engine.passlist.queue = eval(data['queue'])
    engine.retrieve = True

 # start attack
 try:
  engine.start()
 except KeyboardInterrupt:
  engine.user_abort = True 
 finally:
  if all([engine.spyder.proxy_info, not engine.isFound]):
   engine.display(engine.pwd)

  if all([not engine.read, engine.user_abort, not engine.isFound]):
   print('{}[!] Exiting ...'.format('' if not engine.spyder.proxy_info else '\n'))

  if all([engine.read, not engine.isFound]):
   print('\n[*] Password not found')

  sleep(1.5)
  engine.stop()
Ejemplo n.º 4
0
    def get_loris_session_id(self):
        """
        Greps the LORIS session.ID corresponding to the BIDS visit. Note,
        if no BIDS visit are set, will use the default visit label value set
        in the config module

        :return: the session's ID in LORIS
         :rtype: int
        """

        # check if there are any visit label in BIDS structure, if not,
        # will use the default visit label set in the config module
        visit_label = self.bids_ses_id if self.bids_ses_id else self.default_vl

        session = Session(verbose=self.verbose,
                          cand_id=self.cand_id,
                          center_id=self.center_id,
                          visit_label=visit_label)
        loris_vl_info = session.get_session_info_from_loris(self.db)

        if not loris_vl_info:
            message = "ERROR: visit label " + visit_label + "does not exist in " + \
                      "the session table for candidate "  + self.cand_id         + \
                      "\nPlease make sure the visit label is created in the "    + \
                      "database or run bids_import.py with the -s option -s if " + \
                      "you wish that the insertion pipeline creates the visit "  + \
                      "label in the session table."
            print(message)
            exit(lib.exitcode.SELECT_FAILURE)

        return loris_vl_info['ID']
Ejemplo n.º 5
0
 def __init__(self, *args, **kwargs):
     super(BaseHandler, self).__init__(*args, **kwargs)
     self.session = Session(self)
     self.db = self.application.db
     if not isinstance(self, WebSocketHandler):
         # record last view url
         self.set_cookie('last_view', self.request.uri)
         # 一天后过期, 防盗链
         self.set_cookie('uuid', self.uuid, expires_days=1)
Ejemplo n.º 6
0
	def remove(self):
		count = Session.get('count')
		if count > 0:
			count = count - 1
		else:
			count = 0

		Session.set('count', count)
		raise web.seeother('/session/get/')
Ejemplo n.º 7
0
    def initialize(self, method=''):

        #初始化Sesion

        self._session = Session(self, config.setting['session']['time_out'],
                                config.setting['session']['expires_days'])

        self._method = method

        self._cur_entity = None
Ejemplo n.º 8
0
    def initialize(self):
        self.db = mongo
        self.message = None

        self.session = Session(self,
                               MemcacheStore(),
                               initializer={
                                   'nickname': None,
                                   'uid': None,
                                   'email': None,
                                   'super': False,
                                   'artist': False,
                               })
        self.session.processor(self)
Ejemplo n.º 9
0
def run(ip, port, new_key, sleep_time):
    # 获取当前使用的rc4加密key
    rc4_key = get_rc4_key(new_key)
    Log.log_message(
        '[*]server cipher key: {}'.format(BOLD(rc4_key)), log_type=Log.SERVER)
    # 启动http监听服务
    session = Session()
    shell = Shell(session)
    httpd = Server(ip, port, JSCatServer, session, shell, rc4_key, sleep_time)
    httpd.start()
    Log.log_message(
        '[*]server running in  {}:{}...'.format(BOLD('0.0.0.0'), BOLD(port)), log_type=Log.SERVER)
    Log.log_message(
        '[*]host connect ip is {}:{}...'.format(BOLD(ip), BOLD(port)), log_type=Log.SERVER)

    print_online_cmd(ip, port)
    # 控制台命令输入
    try:
        while True:
            if not httpd.shell.get_command():
                httpd.shutdown()
                exit()
    except KeyboardInterrupt:
        httpd.shutdown()
        Log.log_message('server shutdown', log_type=Log.SERVER)
    def initialize(self):
        self.db = mongo
        self.search_cache = Cache(master=False, db=config.Cache.searchdb)
        self.hot_image_cache = Cache(master=False, db=config.Cache.imagedb)
        self.queue = Queue()

        self.session = Session(self, MemcacheStore(),
                initializer = {
                    'nickname': None,
                    'uid': None,
                    'avatar': None,
                    'email': None,
                    'super': False,
                    'channel': None,
                    'login': False,
                    'net': None,
                    'reso': None,
                    'height': 0,
                    'width': 0,
                    'show_msg':None,
                    'hd':True
                    }
                )
        self.session.processor(self)
        self.context = {
                'se': self.session,
                'static_server': config.Server.static_server,
                'cdn':config.CDN.mhost,
                }
Ejemplo n.º 11
0
    def __init__(self, ):
        self.session = Session()
        self.PROMPT_MSG = 'JSCat >'
        self.CMD_SESSION = None
        self.input = PromptSession()

        self.alias = {
            'ls': 'dir ',
            'kill': 'taskkill /F /PID ',
            'ipconfig': 'ipconfig ',
            'ifconfig': 'ipconfig ',
            'netstat': 'netstat ',
            'whoami': 'whoami /user',
            'net': 'net ',
            'wimc': 'wimc ',
        }
Ejemplo n.º 12
0
    def run(self, session: Session):
        session.validate(require_token=True)

        # Already cached input
        if path.exists(session.input_file):
            print(
                f"input already exists for {session.challenge}, not fetching")
            return

        # Fetch the input with the session
        cookies = {"session": session.token}
        r = requests.get(session.challenge.input_url, cookies=cookies)

        # Cache to the file
        with open(session.input_file, "w") as f:
            f.write(r.text)
            print(f"Fetched and cached input for ${session.challenge}")
Ejemplo n.º 13
0
def main():

    # assign arugments
    args = ArgumentParser()
    args.add_argument('kullanýcý adý', help='email VEYA kullanýcý adý')
    args.add_argument('wordlist', help='þifre listesi')
    args.add_argument('denenenler',
                      help='saniye baþýna þifre. Herhangi bir numara <= 16')
    args = args.parse_args()

    if not exists(args.wordlist):
        exit('[!] Bulunamadý `{}`'.format(args.wordlist))
    if not args.threads.isdigit():
        exit('[!]Konular bir sayý olmalýdýr ')

    # assign variables
    engine = Bruter(args.username.title(), int(args.threads), args.wordlist)
    session = Session(args.username.title(), args.wordlist)

    if session.exists():
        if _input(
                'attack ý baþlatmak istermisin? [y/n]: ').split()[0][0] == 'y':
            data = session.read()
            if data:
                engine.attempts = int(data['attempts'])
                engine.passlist.queue = eval(data['queue'])
                engine.retrieve = True

    # start attack
    try:
        engine.start()
    except KeyboardInterrupt:
        engine.user_abort = True
    finally:
        if all([engine.spyder.proxy_info, not engine.isFound]):
            engine.display(engine.pwd)

        if all([not engine.read, engine.user_abort, not engine.isFound]):
            print('{}[!] çýkýlýyor ...'.format(
                '' if not engine.spyder.proxy_info else '\n'))

        if all([engine.read, not engine.isFound]):
            print('\n[*] þifre bulunamadý')

        sleep(1.5)
        engine.stop()
Ejemplo n.º 14
0
def main():

    # assign arugments
    args = ArgumentParser()
    args.add_argument('Username', help='email or username')
    args.add_argument('wordlist', help='password list')
    args.add_argument('threads', help='password per seconds. Any number <= 16')
    args = args.parse_args()

    if not exists(args.wordlist):
        exit('[!] Unable to locate WordList `{}`'.format(args.wordlist))

    if not args.threads.isdigit():
        exit('[!] Threads must be a number')

    # assign variables
    engine = Bruter(args.username.title(), int(args.threads), args.wordlist)
    session = Session(args.username.title(), args.wordlist)

    if session.exists():
        if _input('Do you want to resume the attack? [y/n]: ').split(
        )[0][0] == 'y':
            data = session.read()
            if data:
                engine.attempts = int(data['attempts'])
                engine.passlist.queue = eval(data['queue'])
                engine.retrieve = True

    # start attack
    try:
        engine.start()
    except KeyboardInterrupt:
        engine.user_abort = True
    finally:
        if all([engine.spyder.proxy_info, not engine.isFound]):
            engine.display(engine.pwd)

        if all([not engine.read, engine.user_abort, not engine.isFound]):
            print('{}[!] Exiting ...'.format(
                '' if not engine.spyder.proxy_info else '\n'))

        if all([engine.read, not engine.isFound]):
            print('\n[*] Password not found')

        sleep(1.5)
        engine.stop()
Ejemplo n.º 15
0
    def hook_get_session(self):
        # TODO: session_id 应该基于 ip, uuid.uuid3(uuid.NAMESPACE_DNS, ip)

        session_bucket = self.application.server_sess

        session = None
        session_id = self.get_cookie(".session")

        if session_id:
            session = session_bucket.get(session_id)

        if not session:
            session = Session()
            session.callback = session_bucket.save
            session.destroy = session_bucket.remove

        return session
Ejemplo n.º 16
0
def main():
    arugments = args()
    mode = arugments.mode
    username = arugments.username
    wordlist = arugments.wordlist
    modes = {0: 128, 1: 64, 2: 32, 3: 16}

    if not exists(wordlist):
        exit('[!] Invalid path to wordlist')

    session = Session(username.title(), wordlist)
    engine = Bruter(username.title(), modes[mode], wordlist)

    if session.exists:
        if _input('Do you want to resume the attack? [y/n]: ').split(
        )[0][0] == 'y':
            data = session.read()
            if data:
                engine.attempts = int(data['attempts'])
                engine.passlist.queue = eval(data['queue'])
                engine.retrieve = True

    # start attack
    try:
        engine.start()
    except KeyboardInterrupt:
        engine.user_abort = True
        engine.stop()
    finally:
        if all([engine.spyder.proxy_info, not engine.isFound]):
            engine.display(engine.pwd)

        if all([not engine.read, engine.user_abort, not engine.isFound]):
            print('{}[!] Exiting ...'.format(
                '' if not engine.spyder.proxy_info else '\n'))

        if all([engine.read, not engine.isFound]):
            print('\n[*] Password not found')

        try:
            sleep(1.5)
        except:
            pass

        engine.stop()
 def __init__(self, username, threads, passlist_path, is_color):  
     self.bruter = None 
     self.resume = False 
     self.is_alive = True 
     self.threads = threads
     self.username = username
     self.passlist_path = passlist_path
     self.display = Display(is_color=is_color)
     self.session = Session(username, passlist_path)
Ejemplo n.º 18
0
    def finish_saved_job(self, jobname):
        """Restore client with pickle. Transfer dump."""
        restored_client = pickle.load(open(jobname, 'rb'))
        cprint("Client restored!", 'green')
        cprint("Retrieving RAM dump {}".format(restored_client.output), 'blue')

        if not os.path.isdir(restored_client.output_dir):
            os.mkdir(restored_client.output_dir)

        saved_session = Session(restored_client)
        delayed_profiler = Profiler()
        LimeDeploy(saved_session, delayed_profiler).transfer_dump()
        VolDeploy(saved_session).main(self.volatility_profile_dir)
        cprint(
            "Job {} pickup has been completed!".format(restored_client.output),
            'green')
        saved_session.disconnect()
        os.remove(jobname)
Ejemplo n.º 19
0
	def session(self):
		if hasattr(self, '_session'):
			return self._session
		else:
			sessionid = self.get_secure_cookie('sid')
			self._session = Session(self.application.session_store, sessionid, expires_days=1)
			if not sessionid:
				self.set_secure_cookie('sid', self._session.id, expires_days=1)
			return self._session
    def count_lines(self):
        lines = 0
        fingerprint = sha256(
            self.username.lower().strip().encode() + self.service.lower().strip().encode()
        ).hexdigest().encode()

        self.display.info('Reading wordlist ...')

        with open(self.passlist_path, 'rb') as f:
            for data in f:
                lines += 1
                chunk = sha256(data).hexdigest().encode()
                fingerprint = sha256(fingerprint + chunk).hexdigest().encode()

        self.fingerprint = fingerprint
        self.session = Session(self.fingerprint)

        return lines + 1
Ejemplo n.º 21
0
def grep_or_create_visit_label_db_info(bids_id, cand_id, visit_label, db,
                                       createvisit, verbose, loris_bids_dir,
                                       center_id):
    """
    Greps (or creates if candidate does not exist and createcand is true) the
    BIDS candidate in the LORIS candidate's table and return a list of
    candidates with their related fields from the database.

    :parma bids_id       : BIDS ID of the candidate
     :type bids_id       : str
    :param cand_id       : CandID to use to create the session
     :type cand_id       : int
    :param visit_label   : Visit label to use to create the session
     :type visit_label   : str
    :param db            : database handler object
     :type db            : object
    :param createvisit   : if true, creates the candidate in LORIS
     :type createvisit   : bool
    :param verbose       : if true, prints out information while executing
     :type verbose       : bool
    :param loris_bids_dir: LORIS BIDS import root directory to copy data
     :type loris_bids_dir: str

    :return: session information grepped from LORIS for cand_id and visit_label
     :rtype: dict
    """

    session = Session(verbose,
                      cand_id=cand_id,
                      visit_label=visit_label,
                      center_id=center_id)
    loris_vl_info = session.get_session_info_from_loris(db)

    if not loris_vl_info and createvisit:
        loris_vl_info = session.create_session(db)

    # create the visit directory for in the candidate folder of the LORIS
    # BIDS import directory
    lib.utilities.create_dir(
        loris_bids_dir + "sub-" + bids_id + "/ses-" + visit_label, verbose)

    return loris_vl_info
Ejemplo n.º 22
0
    def run(self, session: Session):
        session.validate(require_token=True)
        print(f"=====\nRunning {session.challenge}:")

        start_time = time.perf_counter()
        helper = language_helper(session)
        return_code, output = helper.run()
        end_time = time.perf_counter()

        if return_code != 0:
            print(f"error: {output}")
            return

        print(f"runtime: {(end_time - start_time)}")

        # If saving, overwrite the current solution
        if session.command == Command.RUN or session.command == Command.TEST:
            if output and session.command_args.save:
                print(f"saving output {output}")
                with open(session.output_file, "w") as f:
                    f.write(output)
            else:
                # When not saving, compare the solution to the current solution and report
                if path.exists(session.output_file):
                    with open(session.output_file) as f:
                        solution = f.read()
                        if solution == output:
                            print("✅ your solution appears correct!")
                        else:
                            print(
                                f"❌ solution does not match one found in {session.output_file}"
                            )
                            print(f"\texpected: {solution}")
                            print(f"\treceived: {output}")
                else:
                    print(
                        "⚠️ solution does not exist for validation. skipping..."
                    )

        # When running the submit command, return the output
        if session.command == Command.SUBMIT:
            return output
Ejemplo n.º 23
0
    def count_lines(self):
        lines = 0
        buffer = 256 << 23  # 4 bytes
        fingerprint = sha256(
            self.username.lower().strip().encode()
        ).hexdigest().encode()

        with open(self.passlist_path, 'rb') as f:

            data = f.read(buffer)

            while data:
                lines += data.count(b'\n')
                data = f.read(buffer)
                chunk = sha256(data).hexdigest().encode()
                fingerprint = sha256(fingerprint + chunk).hexdigest().encode()

        self.fingerprint = fingerprint
        self.session = Session(self.fingerprint)

        return lines + 1
 def create(self, user_id, user_secret):
     """
     param: user_id - Chat user unique identifier.
     param: user_secret - A pseudo-secret word provided by
     the user and used as part of the UUID hashing process.
     """
     # Don't create a new session if one already exists.
     if self.exists(user_id):
         raise SessionExistsError
     session = Session(user_id, user_secret)
     # Store the session.
     self.store.put(session)
     return session
    def initialize(self):
        self.db = mongo
        self.message = None

        self.session = Session(self,MemcacheStore(),
                    initializer = {
                        'nickname': None,
                        'uid': None,
                        'email': None,
                        'super': False,
                        'artist': False,
                        }
                    )
        self.session.processor(self)
Ejemplo n.º 26
0
    def run(self, session: Session):
        args = session.command_args

        if args.token:
            session.token = args.token
            print("updated token")
        if args.l:
            session.language = args.l
            print(f"updated language to {session.language}")
        if args.d or args.y or args.today or args.next:
            now = datetime.now(timezone(timedelta(hours=-5)))
            if args.today:
                if now.month != 12:
                    raise ValueError(
                        "advent of code is not currently running. try -n?")
                if now.day not in _valid_days:
                    raise ValueError("advent of code is not currently running")
                session.challenge.year = now.year
                session.challenge.day = now.day
            elif args.next:
                if now.month == 11 and now.day == 30:
                    session.challenge.year = now.year
                    session.challenge.day = 1
                else:
                    if now.month != 12:
                        raise ValueError(
                            "advent of code is not running tomorrow")
                    if now.day + 1 not in _valid_days:
                        raise ValueError(
                            "advent of code is not running tomorrow")
                    session.challenge.year = now.year
                    session.challenge.day = now.day + 1
            else:
                if args.y:
                    session.challenge.year = args.y
                    session.challenge = Challenge(args.y,
                                                  session.challenge.day)
                if args.d:
                    session.challenge.day = args.d
                    session.challenge = Challenge(session.challenge.year,
                                                  args.d)
            print(f"updated challenge to {session.challenge}")

        session.validate()
        session.cache()
        print(session)
Ejemplo n.º 27
0
def run(ip, port, new_key, sleep_time):
    # 获取当前使用的rc4加密key
    rc4_key = get_rc4_key(new_key)
    print('[*]server encrypt key is {}'.format(BOLD(rc4_key)))
    # 启动http监听服务
    session = Session()
    shell = Shell(session)
    httpd = Server(ip, port, JSCatServer, session, shell, rc4_key, sleep_time)
    httpd.start()
    print('[*]server running in {}:{}...'.format(BOLD(ip), BOLD(port)))
    print_online_cmd(ip, port)
    # 控制台命令输入
    try:
        while True:
            if not httpd.shell.get_command():
                httpd.shutdown()
                exit()
    except KeyboardInterrupt:
        httpd.shutdown()
        print('server shutdown')
Ejemplo n.º 28
0
class PublicHandler(RequestHandler):
    def initialize(self):
        self.session = Session(self.application.session_manager, self)
        self.init_data()

    def init_data(self):
        pass

    @authenticated  # tornado会在prepare()后检查一下_finished值,而redirect后会把_finished设置成True
    def prepare(self):
        self.method_before()

    def method_before(self):
        """在执行任何method前都会执行的"""
        pass

    @property
    def UA(self):
        return self.request.headers.get('User-Agent', '')

    def is_authenticated(self):
        return self.current_user

    @property
    def current_user(self):
        return self.session.get('user', None)

    @property
    def client_ip(self):
        return self.request.remote_ip

    @property
    def full_host(self):
        return self.request.protocol + '://' + self.request.host

    @property
    def redis_db(self):
        return self.application.redis_db
Ejemplo n.º 29
0
class PublicHandler(RequestHandler):
    def initialize(self):
        self.session = Session(self.application.session_manager, self)
        self.init_data()

    def init_data(self):
        pass

    @authenticated # tornado会在prepare()后检查一下_finished值,而redirect后会把_finished设置成True
    def prepare(self):
        self.method_before()
        
    def method_before(self):
        """在执行任何method前都会执行的"""
        pass

    @property
    def UA(self):
        return self.request.headers.get('User-Agent', '')

    def is_authenticated(self):
        return self.current_user

    @property
    def current_user(self):
        return self.session.get('user', None)

    @property
    def client_ip(self):
        return self.request.remote_ip

    @property
    def full_host(self):
        return self.request.protocol + '://' + self.request.host

    @property
    def redis_db(self):
        return self.application.redis_db
Ejemplo n.º 30
0
    def count_lines(self, wordlist) -> int:
        '''Count the number of lines in the wordlist.
        '''

        self.display.clear()
        self.check_password_path()

        lines = 0
        fingerprint = sha256(
            self.username.lower().strip().encode()).hexdigest().encode()

        self.display.info('Loading password list', '', '...')
        time.sleep(3)

        with open(wordlist, 'rb') as f:

            for data in f:
                lines += 1
                chunk = sha256(data).hexdigest().encode()
                fingerprint = sha256(fingerprint + chunk).hexdigest().encode()

        self.session = Session(fingerprint)
        return lines
Ejemplo n.º 31
0
def main():
    logger.info("Starting robot")

    session = Session()
    update_delay = 1.0 / general_config.update_rate_hz
    try:
        session.start()
        while True:
            session.update()
            time.sleep(update_delay)
    except (LowBatteryException, ShutdownException) as e:
        logger.error(str(e), exc_info=True)
        shutdown(session)
    except RebootException as e:
        logger.error(str(e), exc_info=True)
        reboot(session)
    except (RelaunchException, DeviceRestartException) as e:
        logger.error(str(e), exc_info=True)
        relaunch(session)

    except BaseException as e:
        logger.error(str(e), exc_info=True)
        close(session)
	def __init__ (self, config, app):
		self.app = app
		self.config = config
		self.session = Session.create()
		self.session_created = False
Ejemplo n.º 33
0
def test_session():
    """
    Session class tests
    """
    user_id = "test_id"
    secret = "test_secret"
    session = Session(user_id, secret)

    # Session not expired
    assert False is session.is_expired()

    # Unseal a session
    assert True is session.is_sealed()
    session.unseal()
    assert False is session.is_sealed()

    # Time-to-live
    assert 3600 == session.ttl()
    session.ttl(300)
    assert 300 == session.ttl()

    # Secret
    assert True is session.match_secret(secret)

    # Expired session
    session.ttl(1)
    time.sleep(2)
    with pytest.raises(SessionExpiredError):
        session.is_expired()
Ejemplo n.º 34
0
	def destroy(self):
		Session.destroy()
		raise web.seeother('/session/get/')
Ejemplo n.º 35
0
	def add(self):
		count = Session.get('count')
		count = count + 1
		Session.set('count', count)
		raise web.seeother('/session/get/')
Ejemplo n.º 36
0
	def get(self):
		params = {}
		params['key'] = 'count'
		params['value'] = Session.get('count')

		return View.load('/session/get.tpl', params)
Ejemplo n.º 37
0
	def set(self):
		Session.set('count', 1)
		return View.load('/session/set.tpl')
Ejemplo n.º 38
0
 def initialize(self):
     self.session = Session(self.application.session_manager, self)
     self.init_data()
Ejemplo n.º 39
0
class BaseHandler(tornado.web.RequestHandler):

    debug = True

    def debug(self, message=''):
        if self.debug:
            import sys

            call_func_name = sys._getframe(1).f_code.co_name
            class_name = self.__class__.__name__

            print '[ %s:%s ] %s' % (class_name, call_func_name, message)
        else:
            pass

    def initialize(self):
        self.db = mongo
        self.message = None

        self.session = Session(self,
                               MemcacheStore(),
                               initializer={
                                   'nickname': None,
                                   'uid': None,
                                   'email': None,
                                   'super': False,
                                   'artist': False,
                               })
        self.session.processor(self)

    def prepare(self):
        if self.session.uid and not self.session.super:
            raise tornado.web.HTTPError(404)

    def get_current_user(self):
        try:
            return self.session.uid
        except:
            return None

    def get_error_html(self, status_code, **kwargs):
        return self.render_string("error.html", error_code=status_code)

    def split_page(self, length, offset, limit):
        if offset > 0:
            if offset <= limit:
                front = 0
            else:
                front = offset - limit
        else:
            front = None

        if offset + limit < length:
            end = offset + limit
        else:
            end = None

        tail = (length / limit) * limit
        if tail < 0: tail = 0

        page = (offset + limit) / limit
        i = length / limit
        j = length % limit
        total = i if j == 0 else i + 1

        return front, end, tail, "%d/%d" % (page, total)
class BaseHandler(tornado.web.RequestHandler):

    def initialize(self):
        self.db = mongo
        self.search_cache = Cache(master=False, db=config.Cache.searchdb)
        self.hot_image_cache = Cache(master=False, db=config.Cache.imagedb)
        self.queue = Queue()

        self.session = Session(self, MemcacheStore(),
                initializer = {
                    'nickname': None,
                    'uid': None,
                    'avatar': None,
                    'email': None,
                    'super': False,
                    'channel': None,
                    'login': False,
                    'net': None,
                    'reso': None,
                    'height': 0,
                    'width': 0,
                    'show_msg':None,
                    'hd':True
                    }
                )
        self.session.processor(self)
        self.context = {
                'se': self.session,
                'static_server': config.Server.static_server,
                'cdn':config.CDN.mhost,
                }

    def get_current_user(self):
        try:
            return self.session.uid
        except:
            return None

    def split_page(self, length, offset, limit):
        if offset > 0:
            if offset <= limit:
                front = 0
            else:
                front = (offset - limit) /limit
        else:
            front = None

        if offset+limit < length:
            end = (offset+limit)/limit
        else:
            end = None

        page = (offset+limit)/limit
        i = length / limit
        j = length % limit
        total = i if j == 0 else i+1

        return front, end, page, total

    def get_error_html(self,status_code, **kwargs):
        return self.render_string("error.html", error_code=status_code)

    def notfound(self):
        self.render("notfound.html")

    def flash(self,msg):
        self.session.show_msg = None
        self.session.msg = msg
Ejemplo n.º 41
0
    def wsgi(self, environ, start_response):
        """
        レスポンスのボディを返す。
        environ
            HTTP リクエストが格納された辞書。
        start_response
            呼び出し可能オブジェクト。
            start_response を使って、ステータスコードとレスポンスヘッダを出力する。
        """
        self.error_info = []
        # 設定
        setting = self.setting()
        # ルーティング情報取得
        route = environ.get('PATH_INFO', '').strip('/').split('/')
        # POSTデータ取出し
        """
        post = MyStrage()
        if environ.get('REQUEST_METHOD') == 'POST':
            content_length = environ.get('CONTENT_LENGTH', '')
            if not content_length.isalnum():
                content_length = 0
            else:
                wsgi_input = environ['wsgi.input']
                input_parse = cgi.parse_qsl(wsgi_input.read(int(content_length)))
                for value in input_parse:
                    post.setvalue(value[0], value[1])
        """
        if environ['REQUEST_METHOD'].upper() == 'POST':
            post = cgi.FieldStorage(fp=environ['wsgi.input'], environ=environ, keep_blank_values=1)
        else:
            post = cgi.FieldStorage()
        # データベース
        dba = DBAccess.create(setting['database'])
        if setting['database']['create'].upper() == 'ON':
            self.create_table(dba)
        # クッキー
        cookie=SimpleCookie(environ.get('HTTP_COOKIE',''))
        # セッション
        session_id = None
        if setting['session']['id'] in cookie:
            session_id = cookie[setting['session']['id']].value
        session = Session.create(setting['session'], session_id)

        # リクエスト情報を設定
        request = MyStrage()
        request.setvalue('Setting', setting)
        request.setvalue('Session', session)
        request.setvalue('DBA', dba)
        request.setvalue('Route', route)
        request.setvalue('Post', post)
        request.setvalue('Cookie', cookie)
        request.setvalue('Environ', environ)

        self.request = request

        # レスポンスを作成
        response = self.routing(request)

        #デバッグ出力
        debug_output = ''
        if setting['debug']['enable'].upper() == 'ON':
            debug_output = self.debug()

        session.close()

        response_header =[('Content-type', 'text/html;charset=utf-8')]
        if session.get_session_id():
            # クッキーにセッションIDをセット
            response_header.append(('Set-Cookie', '%s=%s'%(setting['session']['id'],session.get_session_id())))

        # レスポンス
        print(response_header)
        print(u'%s'%debug_output)
        print(u'%s\n'%response)
        if response is not None:
            start_response("200 OK", response_header)
            return (u'%s%s'%(debug_output,response)).encode('utf-8')
        else:
            start_response("404 Not Found", response_header)
            return (u'%sページが見つかりません'%(debug_output)).encode('utf-8')
class BaseHandler(tornado.web.RequestHandler):

    debug = True

    def debug(self, message=''):
        if self.debug:
            import sys

            call_func_name = sys._getframe(1).f_code.co_name
            class_name = self.__class__.__name__

            print '[ %s:%s ] %s' % (class_name, call_func_name, message)
        else:
            pass

    def initialize(self):
        self.db = mongo
        self.message = None

        self.session = Session(self,MemcacheStore(),
                    initializer = {
                        'nickname': None,
                        'uid': None,
                        'email': None,
                        'super': False,
                        'artist': False,
                        }
                    )
        self.session.processor(self)

    def prepare(self):
        if self.session.uid and not self.session.super:
            raise tornado.web.HTTPError(404)


    def get_current_user(self):
        try:
            return self.session.uid
        except:
            return None


    def get_error_html(self,status_code, **kwargs):
        return self.render_string(
                "error.html",
                error_code=status_code
                )

    def split_page(self, length, offset, limit):
        if offset > 0:
            if offset <= limit:
                front = 0
            else:
                front = offset - limit
        else:
            front = None

        if offset + limit < length:
            end = offset + limit
        else:
            end = None

        tail = (length / limit) * limit
        if tail < 0: tail = 0

        page = (offset + limit) / limit
        i = length / limit
        j = length % limit
        total = i if j == 0 else i+1

        return front, end, tail, "%d/%d" % (page, total)
Ejemplo n.º 43
0
def game_init(host=None, port=None, nickname=None):
    clock = pygame.time.Clock()

    background = pygame.image.load(os.path.join('assets', 'montreal.jpg'))
    screen = pygame.display.set_mode(RES)

    bgManager = scroll_bgmanager.BackgroundManager(screen, background)

    session = Session()

    # serverClient = ServerClient()
    port = reactor.listenUDP(0, ServerClient(host, PORT))

    get_players = {'command': 'get_players'}
    # serverClient.sendMessage(json.dumps(get_players))

    port.write(json.dumps(get_players), (host, PORT))
    print session.players
    print "checking in session about player %s" % nickname
    print "player exists: %s" % session.player_exists(nickname)

    if session.player_exists(nickname):
        sys.exit(0)

    local_group = scroll_group.ScrollSpriteGroup(bgManager)
    session.set_scroll_group(local_group)

    player = session.create_player(nickname)
    session.set_local_player(player)

    local_group.add(player)

    bgManager.BlitSelf(screen)
    pygame.display.flip()

    def _loop():

        # serverClient.sendMessage(player.get_status())
        port.write(player.get_status())
        clock.tick(FPS)
        for p in session.get_players():
            if p != player:
                if pygame.sprite.collide_rect(player, p):
                    player.speed = 0

        for event in pygame.event.get():
            if not hasattr(event, 'key'):
                continue
            down = event.type == KEYDOWN
            if event.key == K_RIGHT:
                player.k_right = down * -5
                player.k_down = down * -0.2
            elif event.key == K_LEFT:
                player.k_left = down * 5
                player.k_down = down * -0.2
            elif event.key == K_UP:
                player.k_up = down * 0.2
            elif event.key == K_DOWN:
                player.k_down = down * -0.4
            elif event.key == K_ESCAPE:
                status = {'status': 'disconnected', 'name': player.name}
                # serverClient.sendMessage(json.dumps(status))
                port.write(json.dumps(status))
                # reactor.stop()
                pygame.quit()
                sys.exit(0)

        bgManager.NotifyPlayerSpritePos(player.rect)

        local_group.clear(screen)
        local_group.update()
        changedRects = local_group.draw(screen)
        pygame.display.update(changedRects)
        reactor.callLater(1. / FPS, _loop)

    status = {'status': 'connected', 'name': nickname}
    # serverClient.sendMessage(json.dumps(status))
    port.write(json.dumps(status))
    _loop()
Ejemplo n.º 44
0
    def main(self):
        """Start the interactive session for LiMEaide."""
        cprint("""\
  .---.                                                     _______
  |   |.--. __  __   ___         __.....__              .--.\  ___ `'.         __.....__
  |   ||__||  |/  `.'   `.   .-''         '.            |__| ' |--.\  \    .-''         '.
  |   |.--.|   .-.  .-.   ' /     .-''"'-.  `.          .--. | |    \  '  /     .-''"'-.  `.
  |   ||  ||  |  |  |  |  |/     /________\   \    __   |  | | |     |  '/     /________\   |
  |   ||  ||  |  |  |  |  ||                  | .:--.'. |  | | |     |  ||                  |
  |   ||  ||  |  |  |  |  |\    .-------------'/ |   \ ||  | | |     ' .'\    .-------------'
  |   ||  ||  |  |  |  |  | \    '-.____...---.`" __ | ||  | | |___.' /'  \    '-.____...---.
  |   ||__||__|  |__|  |__|  `.             .'  .'.''| ||__|/_______.'/    `.             .'
  '---'                        `''-...... -'   / /   | |_   \_______|/       `''-...... -'
                                               \ \._,\ '/
                                                `--'  `"
             by kd8bny {0}\n""".format(self.__version__),
               'green',
               attrs=['bold'])
        print("LiMEaide is licensed under GPL-3.0\n"
              "LiME is licensed under GPL-2.0\n")

        date = datetime.strftime(datetime.today(), "%Y_%m_%dT%H_%M_%S_%f")
        self.check_directories()
        self.check_tools()

        logging.basicConfig(level=logging.INFO,
                            filename='{0}{1}.log'.format(self.log_dir, date))
        self.logger = logging.getLogger()

        args = self.get_args()
        config = configparser.ConfigParser()
        config.read('.limeaide')
        profiler = Profiler()
        profiler.load_profiles()
        client = self.get_client(args, config)

        if args.pickup:
            self.finish_saved_job(args.pickup)
            sys.exit()

        if args.case is not None:
            self.args_case = 'case_%s' % (args.case)

        # Start session
        session = Session(client, args.verbose)
        session.connect()
        client.output_dir = "{0}{1}{2}/".format(self.output_dir,
                                                self.args_case, date)
        os.mkdir(client.output_dir)

        if args.force_clean:
            session.disconnect()
            sys.exit("Clean attempt complete")

        if args.profile is not None:
            profile = profiler.select_profile(args.profile[0], args.profile[1],
                                              args.profile[2])
            if profile is None:
                new_profile = input(
                    colored(
                        "No profiles found... Would you like to build a new" +
                        "profile for the remote client [Y/n] ", 'red'))
                if new_profile.lower() == 'n':
                    sys.exit()
            else:
                client.profile = profile
                cprint("Profile found!", 'green')

        elif not args.no_profiler:
            use_profile = input(
                colored(
                    "Would you like to select a pre-generated profile " +
                    "[y/N] ", 'green'))
            if use_profile.lower() == 'y':
                profile = profiler.interactive_chooser()
                if profile is None:
                    cprint(
                        "No profiles found... Will build new profile " +
                        "for remote client", 'red')
                else:
                    client.profile = profile

        LimeDeploy(session, profiler).main()

        if args.delay_pickup:
            self.save_job(client, client.jobname)
            cprint("> RAM dump retrieval is postponed", 'green')
            cprint(
                "> To retrieve, run LiMEaide with" +
                '"-P scheduled_jobs/{}.dat"'.format(client.jobname), 'yellow')
        else:
            # Now that's taken care of, lets do work on Volatility
            VolDeploy(session).main(self.volatility_profile_dir)
            session.disconnect()

        logging.shutdown()
Ejemplo n.º 45
0
 if not exists(args.wordlist):

  exit('[!] Unable to locate `{}`'.format(args.wordlist))


 if not args.threads.isdigit():

  exit('[!] Threads must be a number')


 # assign variables

 engine = Bruter(args.username.title(), int(args.threads), args.wordlist)

 session = Session(args.username.title(), args.wordlist)


 if session.exists():

  if _input('Do you want to resume the attack? [y/n]: ').split()[0][0] == 'y':

   data = session.read()

   if data:

    engine.attempts = int(data['attempts'])

    engine.passlist.queue = eval(data['queue'])

    engine.retrieve = True