コード例 #1
0
ファイル: rules.py プロジェクト: 0dadj1an/exafs
def ipv4_rule():
    net_ranges = get_user_nets(session['user_id'])
    form = IPv4Form(request.form)

    # add values to form instance
    form.action.choices = get_user_actions(session['user_role_ids'])

    form.net_ranges = net_ranges

    if request.method == 'POST' and form.validate():

        model = get_ipv4_model_if_exists(form.data, 1)

        if model:
            model.expires = round_to_ten_minutes(webpicker_to_datetime(form.expires.data))
            flash_message = u'Existing IPv4 Rule found. Expiration time was updated to new value.'
        else:
            model = Flowspec4(
                source=form.source.data,
                source_mask=form.source_mask.data,
                source_port=form.source_port.data,
                destination=form.dest.data,
                destination_mask=form.dest_mask.data,
                destination_port=form.dest_port.data,
                protocol=form.protocol.data,
                flags=";".join(form.flags.data),
                packet_len=form.packet_len.data,
                expires=round_to_ten_minutes(webpicker_to_datetime(form.expires.data)),
                comment=quote_to_ent(form.comment.data),
                action_id=form.action.data,
                user_id=session['user_id'],
                rstate_id=get_state_by_time(webpicker_to_datetime(form.expires.data))
            )
            flash_message = u'IPv4 Rule saved'
            db.session.add(model)

        db.session.commit()
        flash(flash_message, 'alert-success')

        # announce route if model is in active state
        if model.rstate_id == 1:
            route = messages.create_ipv4(model, constants.ANNOUNCE)
            announce_route(route)

        # log changes
        log_route(session['user_id'], model, RULE_TYPES['IPv4'])

        return redirect(url_for('index'))
    else:
        for field, errors in form.errors.items():
            for error in errors:
                print(u"Error in the %s field - %s" % (
                    getattr(form, field).label.text,
                    error
                ))

    default_expires = datetime.now() + timedelta(days=7)
    form.expires.data = datetime_to_webpicker(default_expires)

    return render_template('forms/ipv4_rule.j2', form=form, action_url=url_for('rules.ipv4_rule'))
コード例 #2
0
def create_rtbh(current_user):
    all_com = db.session.query(Community).all()
    if not all_com:
        insert_initial_communities()

    net_ranges = get_user_nets(current_user["id"])

    json_request_data = request.get_json()
    form = RTBHForm(data=json_request_data, meta={"csrf": False})

    form.community.choices = get_user_communities(current_user["role_ids"])
    form.net_ranges = net_ranges

    if not form.validate():
        form_errors = get_form_errors(form)
        if form_errors:
            return jsonify(form_errors), 400

    model = get_rtbh_model_if_exists(form.data, 1)

    if model:
        model.expires, pref_format = parse_api_time(form.expires.data)
        flash_message = (
            u"Existing RTBH Rule found. Expiration time was updated to new value."
        )
    else:
        expires, pref_format = parse_api_time(form.expires.data)
        model = RTBH(
            ipv4=form.ipv4.data,
            ipv4_mask=form.ipv4_mask.data,
            ipv6=form.ipv6.data,
            ipv6_mask=form.ipv6_mask.data,
            community_id=form.community.data,
            expires=expires,
            comment=quote_to_ent(form.comment.data),
            user_id=current_user["id"],
            rstate_id=get_state_by_time(expires),
        )
        db.session.add(model)
        db.session.commit()
        flash_message = u"RTBH Rule saved"

    # announce routes
    if model.rstate_id == 1:
        route = messages.create_rtbh(model, ANNOUNCE)
        announce_route(route)
    # log changes
    log_route(
        current_user["id"],
        model,
        RULE_TYPES["RTBH"],
        "{} / {}".format(current_user["uuid"], current_user["org"]),
    )

    pref_format = output_date_format(json_request_data, pref_format)
    return jsonify({
        "message": flash_message,
        "rule": model.to_dict(pref_format)
    }), 201
コード例 #3
0
ファイル: apiv1.py プロジェクト: 0dadj1an/exafs
def create_ipv4(current_user):
    """
    Api method for new IPv4 rule
    :param data: parsed json request
    :param current_user: data from jwt token
    :return: json response
    """
    net_ranges = get_user_nets(current_user['id'])
    json_request_data = request.get_json()
    form = IPv4Form(data=json_request_data, meta={'csrf': False})
    # add values to form instance
    form.action.choices = get_user_actions(current_user['role_ids'])
    form.net_ranges = net_ranges

    # if the form is not valid, we should return 404 with errors
    if not form.validate():
        form_errors = get_form_errors(form)
        if form_errors:
            return jsonify(form_errors), 400

    model = get_ipv4_model_if_exists(form.data, 1)

    if model:
        model.expires, pref_format = parse_api_time(form.expires.data)
        flash_message = u'Existing IPv4 Rule found. Expiration time was updated to new value.'
    else:
        expires, pref_format = parse_api_time(form.expires.data)
        model = Flowspec4(source=form.source.data,
                          source_mask=form.source_mask.data,
                          source_port=form.source_port.data,
                          destination=form.dest.data,
                          destination_mask=form.dest_mask.data,
                          destination_port=form.dest_port.data,
                          protocol=form.protocol.data,
                          flags=";".join(form.flags.data),
                          packet_len=form.packet_len.data,
                          expires=expires,
                          comment=quote_to_ent(form.comment.data),
                          action_id=form.action.data,
                          user_id=current_user['id'],
                          rstate_id=get_state_by_time(expires))
        flash_message = u'IPv4 Rule saved'
        db.session.add(model)

    db.session.commit()

    # announce route if model is in active state
    if model.rstate_id == 1:
        route = messages.create_ipv4(model, ANNOUNCE)
        announce_route(route)

    # log changes
    log_route(current_user['id'], model, RULE_TYPES['IPv4'])

    pref_format = output_date_format(json_request_data, pref_format)
    return jsonify({
        'message': flash_message,
        'rule': model.to_dict(pref_format)
    }), 201
コード例 #4
0
ファイル: rules.py プロジェクト: CESNET/exafs
def group_update_save(rule_type):
    # redirect bad request
    try:
        to_update = session['group-update']
    except KeyError:
        return redirect(
            url_for('dashboard.index',
                    rtype=session[constants.TYPE_ARG],
                    rstate=session[constants.RULE_ARG],
                    sort=session[constants.SORT_ARG],
                    squery=session[constants.SEARCH_ARG],
                    order=session[constants.ORDER_ARG]))

    model_name = DATA_MODELS[rule_type]
    form_name = DATA_FORMS[rule_type]

    form = form_name(request.form)

    # set new expiration date
    expires = round_to_ten_minutes(webpicker_to_datetime(form.expires.data))
    # set state by time
    rstate_id = get_state_by_time(webpicker_to_datetime(form.expires.data))
    comment = form.comment.data
    route_model = ROUTE_MODELS[rule_type]

    for rule_id in to_update:
        # update record
        model = db.session.query(model_name).get(rule_id)
        model.expires = expires
        model.rstate_id = rstate_id
        model.comment = "{} {}".format(model.comment, comment)
        db.session.commit()

        if model.rstate_id == 1:
            # announce route
            route = route_model(model, constants.ANNOUNCE)
            announce_route(route)
            # log changes
            log_route(
                session['user_id'], model, rule_type,
                "{} / {}".format(session['user_email'], session['user_orgs']))
        else:
            # withdraw route
            route = route_model(model, constants.WITHDRAW)
            announce_route(route)
            # log changes
            log_withdraw(
                session['user_id'], route, rule_type, model.id,
                "{} / {}".format(session['user_email'], session['user_orgs']))

    flash(u'Rules {} successfully updated'.format(to_update), 'alert-success')

    return redirect(
        url_for('dashboard.index',
                rtype=session[constants.TYPE_ARG],
                rstate=session[constants.RULE_ARG],
                sort=session[constants.SORT_ARG],
                squery=session[constants.SEARCH_ARG],
                order=session[constants.ORDER_ARG]))
コード例 #5
0
ファイル: rules.py プロジェクト: 0dadj1an/exafs
def rtbh_rule():
    all_com = db.session.query(Community).all()
    if not all_com:
        insert_initial_communities()

    net_ranges = get_user_nets(session['user_id'])
    form = RTBHForm(request.form)

    form.community.choices = get_user_communities(session['user_role_ids'])
    form.net_ranges = net_ranges

    if request.method == 'POST' and form.validate():

        model = get_rtbh_model_if_exists(form.data, 1)

        if model:
            model.expires = round_to_ten_minutes(webpicker_to_datetime(form.expires.data))
            flash_message = u'Existing RTBH Rule found. Expiration time was updated to new value.'
        else:

            model = RTBH(
                ipv4=form.ipv4.data,
                ipv4_mask=form.ipv4_mask.data,
                ipv6=form.ipv6.data,
                ipv6_mask=form.ipv6_mask.data,
                community_id=form.community.data,
                expires=round_to_ten_minutes(webpicker_to_datetime(form.expires.data)),
                comment=quote_to_ent(form.comment.data),
                user_id=session['user_id'],
                rstate_id=get_state_by_time(webpicker_to_datetime(form.expires.data))
            )
            db.session.add(model)
            db.session.commit()
            flash_message = u'RTBH Rule saved'

        flash(flash_message, 'alert-success')
        # announce routes
        if model.rstate_id == 1:
            route = messages.create_rtbh(model, constants.ANNOUNCE)
            announce_route(route)
        # log changes
        log_route(session['user_id'], model, RULE_TYPES['RTBH'])

        return redirect(url_for('index'))
    else:
        for field, errors in form.errors.items():
            for error in errors:
                print(u"Error in the %s field - %s" % (
                    getattr(form, field).label.text,
                    error
                ))

    default_expires = datetime.now() + timedelta(days=7)
    form.expires.data = datetime_to_webpicker(default_expires)

    return render_template('forms/rtbh_rule.j2', form=form, action_url=url_for('rules.rtbh_rule'))
コード例 #6
0
ファイル: rules.py プロジェクト: 0dadj1an/exafs
def reactivate_rule(rule_type, rule_id):
    """
    Set new time for the rule of given type identified by id
    :param rule_type: string - type of rule
    :param rule_id: integer - id of the rule
    """
    model_name = DATA_MODELS[rule_type]
    form_name = DATA_FORMS[rule_type]

    model = db.session.query(model_name).get(rule_id)
    form = form_name(request.form, obj=model)
    form.net_ranges = get_user_nets(session['user_id'])

    if rule_type > 2:
        form.action.choices = [(g.id, g.name)
                               for g in db.session.query(Action).order_by('name')]
        form.action.data = model.action_id

    if rule_type == 1:
        form.community.choices = get_user_communities(session['user_role_ids'])
        form.community.data = model.community_id

    if rule_type == 4:
        form.protocol.data = model.protocol

    if rule_type == 6:
        form.next_header.data = model.next_header

    # do not need to validate - all is readonly
    if request.method == 'POST':
        # set new expiration date
        model.expires = round_to_ten_minutes(webpicker_to_datetime(form.expires.data))
        # set again the active state
        model.rstate_id = get_state_by_time(webpicker_to_datetime(form.expires.data))
        model.comment = form.comment.data
        db.session.commit()
        flash(u'Rule successfully updated', 'alert-success')

        route_model = ROUTE_MODELS[rule_type]

        if model.rstate_id == 1:
            # announce route
            route = route_model(model, constants.ANNOUNCE)
            announce_route(route)
            # log changes
            log_route(session['user_id'], model, rule_type)
        else:
            # withdraw route
            route = route_model(model, constants.WITHDRAW)
            announce_route(route)
            # log changes
            log_withdraw(session['user_id'], route, rule_type, model.id)

        return redirect(url_for('dashboard.index',
                                rtype=session[constants.TYPE_ARG],
                                rstate=session[constants.RULE_ARG],
                                sort=session[constants.SORT_ARG],
                                squery=session[constants.SEARCH_ARG],
                                order=session[constants.ORDER_ARG]))
    else:
        flash_errors(form)

    form.expires.data = datetime_to_webpicker(model.expires)
    for field in form:
        if field.name not in ['expires', 'csrf_token', 'comment']:
            field.render_kw = {'disabled': 'disabled'}

    action_url = url_for('rules.reactivate_rule', rule_type=rule_type, rule_id=rule_id)

    return render_template(DATA_TEMPLATES[rule_type], form=form, action_url=action_url, editing=True, title="Update")
コード例 #7
0
def create_ipv6(current_user):
    """
    Create new IPv6 rule
    :param data: parsed json request
    :param current_user: data from jwt token
    :return:
    """
    net_ranges = get_user_nets(current_user["id"])
    json_request_data = request.get_json()
    form = IPv6Form(data=json_request_data, meta={"csrf": False})
    form.action.choices = get_user_actions(current_user["role_ids"])
    form.net_ranges = net_ranges

    if not form.validate():
        form_errors = get_form_errors(form)
        if form_errors:
            return jsonify(form_errors), 400

    model = get_ipv6_model_if_exists(form.data, 1)

    if model:
        model.expires, pref_format = parse_api_time(form.expires.data)
        flash_message = (
            u"Existing IPv6 Rule found. Expiration time was updated to new value."
        )
    else:
        expires, pref_format = parse_api_time(form.expires.data)
        model = Flowspec6(
            source=form.source.data,
            source_mask=form.source_mask.data,
            source_port=form.source_port.data,
            destination=form.dest.data,
            destination_mask=form.dest_mask.data,
            destination_port=form.dest_port.data,
            next_header=form.next_header.data,
            flags=";".join(form.flags.data),
            packet_len=form.packet_len.data,
            expires=expires,
            comment=quote_to_ent(form.comment.data),
            action_id=form.action.data,
            user_id=current_user["id"],
            rstate_id=get_state_by_time(expires),
        )
        flash_message = u"IPv6 Rule saved"
        db.session.add(model)

    db.session.commit()

    # announce routes
    if model.rstate_id == 1:
        route = messages.create_ipv6(model, ANNOUNCE)
        announce_route(route)

    # log changes
    log_route(
        current_user["id"],
        model,
        RULE_TYPES["IPv6"],
        "{} / {}".format(current_user["uuid"], current_user["org"]),
    )

    pref_format = output_date_format(json_request_data, pref_format)
    return jsonify({
        "message": flash_message,
        "rule": model.to_dict(pref_format)
    }), 201