예제 #1
0
def statistics():
    legend = 'Flag delivery statistics'
    config = reloader.get_config()
    f = open('statistics.json', 'r')
    json_string = ''
    for line in f.readlines():
        json_string = json_string + line
    f.close()
    statistics = json.loads(json_string)
    flags = [
        statistics['one_flags'], statistics['two_flags'],
        statistics['three_flags'], statistics['four_flags'],
        statistics['five_flags'], statistics['six_flags']
    ]
    times = [
        statistics['one_time'], statistics['two_time'],
        statistics['three_time'], statistics['four_time'],
        statistics['five_time'], statistics['six_time']
    ]
    refresh_interval = config['GRAPHICS_REFRESH_INTERVAL'] * 1000
    return render_template('chart.html',
                           values=flags,
                           labels=times,
                           legend=legend,
                           refresh_interval=refresh_interval)
예제 #2
0
def run_loop():
    app.logger.info('Starting submit loop')
    with app.app_context():
        db = database.get(context_bound=False)

    while True:
        submit_start_time = time.time()

        config = reloader.get_config()

        skip_time = round(submit_start_time - config['FLAG_LIFETIME'])
        db.execute("UPDATE flags SET status = ? WHERE status = ? AND time < ?",
                   (FlagStatus.SKIPPED.name, FlagStatus.QUEUED.name, skip_time))
        db.commit()

        cursor = db.execute("SELECT * FROM flags WHERE status = ?", (FlagStatus.QUEUED.name,))
        queued_flags = [Flag(**item) for item in cursor.fetchall()]

        if queued_flags:
            grouped_flags = defaultdict(list)
            for item in queued_flags:
                grouped_flags[item.sploit, item.team].append(item)
            flags = get_fair_share(grouped_flags.values(), config['SUBMIT_FLAG_LIMIT'])

            app.logger.debug('Submitting %s flags (out of %s in queue)', len(flags), len(queued_flags))
            results = submit_flags(flags, config)

            rows = [(item.status.name, item.checksystem_response, item.flag) for item in results]
            db.executemany("UPDATE flags SET status = ?, checksystem_response = ? "
                           "WHERE flag = ?", rows)
            db.commit()

        submit_spent = time.time() - submit_start_time
        if config['SUBMIT_PERIOD'] > submit_spent:
            time.sleep(config['SUBMIT_PERIOD'] - submit_spent)
예제 #3
0
def get_config():
    config = reloader.get_config()

    return jsonify({
        key: value
        for key, value in config.items()
        if 'PASSWORD' not in key and 'TOKEN' not in key
    })
예제 #4
0
    def decorated(*args, **kwargs):
        config = reloader.get_config()

        if config['ENABLE_API_AUTH']:
            if request.headers.get('X-Token', '') != config['API_TOKEN']:
                return Response('Provided token is invalid.', 403)

        return f(*args, **kwargs)
예제 #5
0
def index():
    distinct_values = {}
    for column in ['sploit', 'status', 'team']:
        rows = database.query(
            'SELECT DISTINCT {} FROM flags ORDER BY {}'.format(column, column))
        distinct_values[column] = [item[column] for item in rows]

    statuses = [name for name, _ in FlagStatus.__members__.items()]

    # Setup counts and it's 'Total' dictionary
    counts = {'Total': {'TOTAL': 0}}
    for status in statuses:
        counts['Total'][status] = {'count': 0, 'percent': 0}

    # Get the number of statuses for each service and calculate running totals
    max_sploit_total = 0
    for sploit in distinct_values['sploit']:
        counts[sploit] = {'TOTAL': 0}
        for status in statuses:
            count = database.query(
                "SELECT COUNT(*) FROM flags WHERE sploit = '%s' AND status = '%s'"
                % (sploit, status))[0][0]
            counts[sploit][status] = {'count': count}
            counts[sploit]['TOTAL'] += count
            counts['Total'][status]['count'] += count
            counts['Total']['TOTAL'] += count
        max_sploit_total = max(max_sploit_total, counts[sploit]['TOTAL'])

    # Calculate sploit status percentages based off max_sploit_total
    for sploit in distinct_values['sploit']:
        for sploit_status in [counts[sploit][status] for status in statuses]:
            sploit_status[
                'percent'] = 100 * sploit_status['count'] / max_sploit_total

    # Calculate overall status percentages based off total flag count
    for status_total in [counts['Total'][status] for status in statuses]:
        status_total[
            'percent'] = 100 * status_total['count'] / counts['Total']['TOTAL']

    # Sort by sploit flag total
    counts = {
        key: value
        for key, value in sorted(counts.items(),
                                 key=lambda item: -item[1]['TOTAL'])
    }
    config = reloader.get_config()

    server_tz_name = time.strftime('%Z')
    if server_tz_name.startswith('+'):
        server_tz_name = 'UTC' + server_tz_name

    return render_template('index.html',
                           flag_format=config['FLAG_FORMAT'],
                           distinct_values=distinct_values,
                           counts=counts,
                           server_tz_name=server_tz_name)
예제 #6
0
def post_flags_manual():
    config = reloader.get_config()
    flags = re.findall(config['FLAG_FORMAT'], request.form['text'])

    cur_time = round(time.time())
    rows = [(item, 'Manual', '*', cur_time, FlagStatus.QUEUED.name)
            for item in flags]

    db = database.get()
    db.executemany(
        "INSERT OR IGNORE INTO flags (flag, sploit, team, time, status) "
        "VALUES (?, ?, ?, ?, ?)", rows)
    db.commit()

    return ''
예제 #7
0
def index():
    distinct_values = {}
    for column in ['sploit', 'status', 'team']:
        rows = database.query(
            'SELECT DISTINCT {} FROM flags ORDER BY {}'.format(column, column))
        distinct_values[column] = [item[column] for item in rows]

    config = reloader.get_config()

    server_tz_name = time.strftime('%Z')
    if server_tz_name.startswith('+'):
        server_tz_name = 'UTC' + server_tz_name

    return render_template('index.html',
                           flag_format=config['FLAG_FORMAT'],
                           distinct_values=distinct_values,
                           server_tz_name=server_tz_name)
예제 #8
0
def index():
    distinct_values = {}
    for column in ['sploit', 'status', 'team']:
        rows = database.query(
            'SELECT DISTINCT {} FROM flags ORDER BY {}'.format(column, column))
        distinct_values[column] = [item[column] for item in rows]

    config = reloader.get_config()

    legend = 'Flag delivery statistics'

    f = open('statistics.json', 'r')
    json_string = ''
    for line in f.readlines():
        json_string = json_string + line
    f.close()
    statistics = json.loads(json_string)
    flags = [
        statistics['one_flags'], statistics['two_flags'],
        statistics['three_flags'], statistics['four_flags'],
        statistics['five_flags'], statistics['six_flags']
    ]
    times = [
        statistics['one_time'], statistics['two_time'],
        statistics['three_time'], statistics['four_time'],
        statistics['five_time'], statistics['six_time']
    ]
    refresh_interval = config['GRAPHICS_REFRESH_INTERVAL'] * 1000

    server_tz_name = time.strftime('%Z')
    if server_tz_name.startswith('+'):
        server_tz_name = 'UTC' + server_tz_name

    return render_template('index.html',
                           flag_format=config['FLAG_FORMAT'],
                           distinct_values=distinct_values,
                           server_tz_name=server_tz_name,
                           values=flags,
                           labels=times,
                           legend=legend,
                           refresh_interval=refresh_interval)
예제 #9
0
 def decorated(*args, **kwargs):
     auth = request.authorization
     config = reloader.get_config()
     if auth is None or auth.password != config['SERVER_PASSWORD']:
         return unauthorized_response()
     return f(*args, **kwargs)
예제 #10
0
def start_loop():

    print('Statistics')
    config = reloader.get_config()

    while (True):
        times_dict = {}

        for column in ['time']:
            rows = query('SELECT * FROM flags')
            times_dict[column] = [item[column] for item in rows]

        total_flags = 0
        normal_times = []

        for time in times_dict['time']:
            total_flags = total_flags + 1
            normal_times.append(datetime.fromtimestamp(time))

        flags = []
        times = []

        for item in set(normal_times):
            times.append(item)
            flags.append(normal_times.count(item))

        time_points = []

        #Сюда загружаться должен параметр конфига START_TIME
        point = datetime.strptime(config['START_TIME'], "%Y-%m-%d %H:%M:%S")
        flags_sum = 0
        flags_sums = []

        for loop in range(0, 400):
            time_points.append(point)
            try:
                for index in range(0, flags.__len__()):
                    if times[index] < point + timedelta(
                            seconds=config['ROUND_PERIOD']
                    ) and times[index] > point:
                        flags_sum = flags_sum + flags[index]
            except:
                pass
            flags_sums.append(flags_sum)
            flags_sum = 0
            point = point + timedelta(seconds=config['ROUND_PERIOD'])

        now_point = datetime.now()

        if flags.__len__() == 0:
            pass

        next_point = now_point

        for this_point in time_points:
            if now_point < this_point:
                next_point = this_point
                break

        six_point = next_point

        for this_point in reversed(time_points):
            if this_point < next_point:
                six_point = this_point
                change_flags('six_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('six_time', str(this_point.strftime("%H:%M:%S")))
                break

        five_point = six_point

        for this_point in reversed(time_points):
            if this_point < six_point:
                five_point = this_point
                change_flags('five_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('five_time', str(this_point.strftime("%H:%M:%S")))
                break

        four_point = five_point

        for this_point in reversed(time_points):
            if this_point < five_point:
                four_point = this_point
                change_flags('four_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('four_time', str(this_point.strftime("%H:%M:%S")))
                break

        three_point = four_point

        for this_point in reversed(time_points):
            if this_point < four_point:
                three_point = this_point
                change_flags('three_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('three_time',
                             str(this_point.strftime("%H:%M:%S")))
                break

        two_point = three_point

        for this_point in reversed(time_points):
            if this_point < three_point:
                two_point = this_point
                change_flags('two_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('two_time', str(this_point.strftime("%H:%M:%S")))
                break

        one_point = two_point

        for this_point in reversed(time_points):
            if this_point < two_point:
                one_point = this_point
                change_flags('one_flags',
                             str(flags_sums[time_points.index(this_point)]))
                change_times('one_time', str(this_point.strftime("%H:%M:%S")))
                break

        sleep(config['GRAPHICS_REFRESH_INTERVAL'])
예제 #11
0
import re
import time
import json
import requests

from datetime import datetime, timedelta
from flask import jsonify, render_template, request

from server import app, auth, database, reloader
from server.models import FlagStatus
from server import statistics

start_config = reloader.get_config()


@app.template_filter('timestamp_to_datetime')
def timestamp_to_datetime(s):
    return datetime.fromtimestamp(s)


@app.route('/<sploit_name>')
@auth.auth_required
def sploit(sploit_name):
    teams = start_config['TEAMS'].keys()  #команды
    flags_per_time = [
    ]  #стыренные флаги по 6-ти временным промежуткам и по каждой тиме
    for i in range(0, len(teams)):
        flags_per_time.append(['0', '0', '0', '0', '0',
                               '0'])  #инициализация стыренных флагов

    teams_info = []
예제 #12
0
def run_loop():
    app.logger.info('Starting submit loop')
    with app.app_context():
        db = database.get(context_bound=False)

    cycle = db.execute("SELECT MAX(sent_cycle) AS last_cycle "
                       "FROM flags").fetchone()['last_cycle']
    if not cycle:
        cycle = 0

    while True:
        cycle += 1

        submit_start_time = time.time()

        config = reloader.get_config()

        # If flag time > FLAG_LIFETIME set as SKIPPED
        skip_time = round(submit_start_time - config['FLAG_LIFETIME'])
        db.execute(
            "UPDATE flags SET status = ? WHERE status = ? AND time < ?",
            (FlagStatus.SKIPPED.name, FlagStatus.QUEUED.name, skip_time))
        db.commit()

        cursor = db.execute("SELECT * FROM flags WHERE status = ?",
                            (FlagStatus.QUEUED.name, ))
        queued_flags = [Flag(**item) for item in cursor.fetchall()]

        if queued_flags:
            grouped_flags = defaultdict(list)
            for item in queued_flags:
                grouped_flags[item.sploit, item.team].append(item)

            flags = get_fair_share(grouped_flags.values(),
                                   config['SUBMIT_FLAG_LIMIT'])

            app.logger.debug(
                f'Submitting {len(flags)} flags (out of {len(queued_flags)} in queue)'
            )
            # Send flags to gameserver
            results = submit_flags(flags, config)

            rows = [(item.status.name, item.checksystem_response, cycle,
                     item.flag) for item in results]
            db.executemany(
                "UPDATE flags "
                "SET status = ?, checksystem_response = ?, sent_cycle = ? "
                "WHERE flag = ?", rows)
            db.commit()

            flags_status = {result.flag: result.status for result in results}

            def add_status(item: Flag):
                return Flag(item.flag, item.sploit, item.team, item.time,
                            flags_status[item.flag], item.checksystem_response,
                            item.sent_cycle)

            flags = list(map(add_status, flags))
            flag_ann.announce((cycle, flags))

        submit_spent = time.time() - submit_start_time
        if config['SUBMIT_PERIOD'] > submit_spent:
            time.sleep(config['SUBMIT_PERIOD'] - submit_spent)