示例#1
0
def upload():
    form = UploadForm()
    if form.validate_on_submit():
        if not user_has_roles(current_user, RoleEnum.USER):
            return flask.abort(HTTPStatus.FORBIDDEN, description="You do not have the permission to start jobs.")
        # flask-uploads already uses werkzeug.secure_filename()
        filename = cap_uploads.save(request.files['capture'], folder=current_user.username)
        cap_path = Path(app.config['CAPTURES_DIR']) / filename
        cap_path = Path(shlex.quote(str(cap_path)))
        try:
            file_22000 = convert_to_22000(cap_path)
        except (FileNotFoundError, InvalidFileError) as error:
            logger.exception(error)
            return flask.abort(HTTPStatus.BAD_REQUEST, description="Bad input capture file.")
        Thread(target=download_wordlist, args=(form.get_wordlist_path(),)).start()
        folder_split_by_essid = split_by_essid(file_22000)
        tasks = {}
        hashcat_args = ' '.join(form.hashcat_args())
        for file_essid in folder_split_by_essid.iterdir():
            bssid_essid = next(bssid_essid_from_22000(file_essid))
            bssid, essid = bssid_essid.split(':')
            essid = bytes.fromhex(essid).decode('utf-8')
            new_task = UploadedTask(user_id=current_user.id, filename=cap_path.name, wordlist=form.get_wordlist_name(),
                                    rule=form.rule.data, bssid=bssid, essid=essid, hashcat_args=hashcat_args)
            tasks[file_essid] = new_task
        db.session.add_all(tasks.values())
        db.session.commit()
        for file_essid, task in tasks.items():
            hashcat_worker.submit_capture(file_essid, uploaded_form=form, task=task)
        flask.flash(f"Uploaded {filename}")
        return redirect(url_for('user_profile'))
    return render_template('upload.html', title='Upload', form=form)
示例#2
0
 def callback_attack(self, future: concurrent.futures.Future):
     # called when the future is done or cancelled
     try:
         exception = future.exception()
     except concurrent.futures.CancelledError as cancelled_error:
         exception = None
     if exception is not None:
         logger.exception(repr(exception), exc_info=False)
     job_id = id(future)
     lock = self.locks.pop(job_id, None)
     if lock is None:
         logger.error("Could not find lock for job {}".format(job_id))
         return
     with lock:
         if future.cancelled():
             lock.set_status(TaskInfoStatus.CANCELLED)
         else:
             lock.set_status(TaskInfoStatus.COMPLETED)
         if exception is not None:
             if isinstance(exception, CancelledError):
                 lock.set_status(TaskInfoStatus.CANCELLED)
             else:
                 lock.set_status(repr(exception))
         lock.finish()
         update_dict = lock.update_dict()
         task_id = lock.task_id
     UploadedTask.query.filter_by(id=task_id).update(update_dict)
     db.session.commit()
     self.locks_onetime.append(lock)
示例#3
0
async def error_middleware(request: Request, handler: Handler) -> Response:
    """Обработка ошибок по типу 404, 500 и т.д."""
    try:
        response = await handler(request)
    except web.HTTPClientError as e:
        response = await render_error_template(request, e.status_code)
    except Exception:
        logger.exception("Произошла непредвиденная ошибка!")
        response = await render_error_template(request, 500)
    finally:
        return response  # noqa: B012
示例#4
0
def start_get_password(message):
    if Guards.is_cancel(message) or Guards.is_command(message):
        return bot.reply_to(message, 'Action was canceled. Type /start to repeat')

    chat_id, ctx = get_or_create_context(message)

    password = message.text

    try:
        rf_user = execute(login_to_rf(ctx.username, password))

        # fixme
        #  Yes, this is extremely bad to store unhashed password, but I have no choice for now.
        #  If you really concern - self host this bot.
        #  Meanwhile I am trying to create better solution.
        ctx.password = password
        ctx.is_authorized = True
        ctx.save()

        msg = bot.send_message(
            chat_id,
            f'Hi, {rf_user.surname} {rf_user.name}!\n'
            f'Your login and password is correct!\n'
            f'\n'
            f'Now, paste URL to the destination node:\n'
        )
        bot.register_next_step_handler(msg, setup_complete)

    except Exception as e:
        logger.exception(e)

        msg = bot.send_message(
            chat_id,
            'Something went wrong. Please try again or type /cancel\n'
            'Type your username (email):'
        )
        bot.register_next_step_handler(msg, start_get_username)

    finally:
        bot.delete_message(chat_id, message.message_id)
示例#5
0
def catch_all(message):
    chat_id, ctx = get_or_create_context(message)

    if Guards.is_cancel(message):
        return bot.reply_to(message, 'Nothing to cancel')

    if Guards.is_command(message):
        return bot.reply_to(
            message,
            'Unsupported command\n'
            f'{COMMANDS}'
        )

    if not Guards.is_authorized(ctx):
        return bot.reply_to(message, 'You have to /start first')

    if not Guards.is_setup_completed(ctx):
        return bot.reply_to(message, 'You have to /setup first')

    try:
        rf_node = execute(create_new_node(ctx, text_to_html(message.text)))
        url = link_to_node(rf_node.map_id, rf_node.id)

        bot.reply_to(message, f'<a href="{url}">Saved</a>', parse_mode='HTML')

    except Exception as e:
        logger.exception(e)

        target_url = link_to_node(ctx.target.map_id, ctx.target.node_id)

        bot.reply_to(
            message,
            'Something went wrong. Please check if you have access to the destination node and try again\n'
            f'<a href="{target_url}">Destination node</a>',
            parse_mode='HTML'
        )
示例#6
0
def fill_missing_review_data(review_id):
    logger.info(f'filling missing for {review_id}')

    reviews_without_name = list(
        maybe_filter(Review.objects.select_related('reviewable').filter(
            Q(name__isnull=True) | Q(name='')),
                     id=review_id))

    logger.info(f'reviews_without_name: {reviews_without_name}')

    context = PageCache()
    for review in tqdm(reviews_without_name):
        try:
            good_title = get_good_title_for_page(review.url, context)
        except Exception:
            logger.exception('could not fetch {}'.format(review.url))
        else:
            if good_title:
                review.name = good_title
                review.save(update_fields=['name'])

    reviewables_without_image = list(
        maybe_filter(Reviewable.objects.filter(
            Q(image_url__isnull=True) | Q(image_url='')),
                     review__id=review_id))

    logger.info(f'reviewables_without_image: {reviewables_without_image}')
    for reviewable in tqdm(reviewables_without_image):
        try:
            good_image = get_good_image_for_page(reviewable.url, context)
        except Exception:
            logger.exception('could not fetch {}'.format(reviewable.url))
        else:
            if good_image:
                reviewable.image_url = good_image
                reviewable.save(update_fields=['image_url'])
示例#7
0
 async def http_exception_handler(request: Request, exc: HTTPException):
     if exc.status_code == 500:
         logger.exception(exc)
     else:
         logger.info(exc)
     return UJSONResponse({'message': exc.detail}, exc.status_code)