Ejemplo n.º 1
0
def global_view(request):
    """

    :param request:
    :return:
    """
    cluster = Cluster.objects.get()
    reload_apps = False # Reload the applications when a field is modified

    # Instantiate form
    global_settings = cluster.system_settings.global_settings

    form = GLOBALSettingsForm(request.POST or None, instance=global_settings, error_class=DivErrorList)

    # A quoi ça sert CA ?!
    for repo in MongoDBRepository.objects.all():
        if repo.is_internal:
            break

    # form validation
    if request.method == 'POST':
        old_portal_cookie = global_settings.portal_cookie
        old_app_cookie = global_settings.app_cookie
        old_public_token = global_settings.public_token
        if form.is_valid():
            global_conf = form.save(commit=False)
            global_conf['logs_repository'] = form.cleaned_data.get('logs_repository')
            global_conf['vulture_status_ip_allowed'] = request.POST.get('vulture_status_ip_allowed').split(',')
            reload_apps = (old_portal_cookie != global_conf.portal_cookie) or (
                old_app_cookie != global_conf.app_cookie) or (
                old_public_token != global_conf.public_token)
            cluster.system_settings.global_settings = global_conf
            cluster.save()

    if reload_apps:
        config_modified.send(sender=Cluster, id=None)

    return render_to_response('global.html', {
            'form'         : form,
            'apache_status': ",".join(global_settings.vulture_status_ip_allowed),
            'repo_interne' : str(repo.id),
            'reload_apps'  : reload_apps
        }, context_instance=RequestContext(request))
Ejemplo n.º 2
0
def topology(request):
    cluster = Cluster.objects.get()
    global_settings = cluster.system_settings.global_settings
    reload_apps = False  # Reload the applications when a field is modified

    if request.method == "POST":
        remote_ip_internal_proxy = request.POST[
            'remote_ip_internal_proxy'].split(',')
        reload_apps = (global_settings.remote_ip_internal_proxy !=
                       remote_ip_internal_proxy)
        global_settings.remote_ip_internal_proxy = remote_ip_internal_proxy
        cluster.system_settings.global_settings = global_settings
        cluster.save()
        if reload_apps:
            config_modified.send(sender=Cluster, id=None)

    return render_to_response('topology.html', {
        'remote_ip_internal_proxy':
        ','.join(global_settings.remote_ip_internal_proxy),
        'reload_apps':
        reload_apps
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 3
0
def edit(request, object_id=None):

    """ View dedicated to templates management

    :param object_id: MongoDB object_id of template
    :param request: Django request object
    """
    template = None
    tpl_list = (
        'html_login',
        'html_logout',
        'html_otp',
        'html_message',
        'html_learning',
        'html_self',
        'html_password',
        'html_registration',
        'email_subject',
        'email_body',
        'html_error',
    )

    if object_id:
        template = portalTemplate.objects.with_id(ObjectId(object_id))
        for tpl in tpl_list:
            html = getattr(template, tpl)
            html = html.replace("{% csrf_token %}","")
            html = html.replace("{% autoescape off %}","")
            html = html.replace("{% endautoescape %}","")
            setattr(template, tpl, html)

    # Fix some default values
    elif request.method != 'POST':
        template = portalTemplate(name="My Template")
        template.error_password_change_ok = "Your password has been changed"
        template.error_password_change_ko = "Error when trying to change your password"
        template.error_email_sent = "An email has been sent to you with instructions to reset your password"

        template.html_login = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container">
            {{form_begin}}
                <img id="vulture_img" src="templates/static/img/vulture-logo-small.png"/>
                {% if error_message != "" %}
                  <div class="alert alert-danger" role="alert">{{error_message}}</div>
                {% endif %}
                <span id="reauth-email" class="reauth-email"></span>
                {{input_login}}
                {{input_password}}
                {% if captcha %}
                    {{captcha}}
                    {{input_captcha}}
                {% endif %}
                {{input_submit}}
                <a href='{{lostPassword}}'>Forgotten password ?</a>
            {{form_end}}
        </div>
    </div>
 </body>
</html>
"""

        template.html_logout = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container" style="text-align:center;">
            <p style="font-size:15px;font-weight:bold;">You have been successfully disconnected</p>
            <a href='{{app_url}}'>Return to the application</a>
        </div>
    </div>
 </body>
</html>"""

        template.html_learning = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body> 
    <div class="container">
        <div class="card card-container" style="text-align:center;">
            <p>Learning form</p>
            {{form_begin}}
                {{input_submit}}
            {{form_end}}
        </div>
    </div>
 </body>
</html>"""

        template.html_self = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container" style="text-align:center;" id="self_service">
            <img id="vulture_img" src="templates/static/img/vulture-logo-small.png"/>
            <br><br>
            {% if error_message != "" %}
                <div class="alert alert-danger">{{error_message}}</div>
            {% endif %}
            <p>Hello <b>{{username}}</b>!</p>
            <p>You currently have access to the following apps:</p>
            <ul class="list-group">
                {% for app in application_list %}
                  <li class="list-group-item"><b>{{app.name}}</b> - <a href='{{app.url}}'>{{app.url}}</a>{% if app.status %}<span class="badge">Logged</span>{% endif %}</li>
                {% endfor %}
            </ul>
            <a href="{{changePassword}}">Change password</a>
            <br><a href="{{logout}}">Logout</a>
        </div>
    </div>
 </body>
</html>"""

        template.html_password = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="../templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container" style="text-align:center;">
            {{form_begin}}
                <img id="vulture_img" src="../templates/static/img/vulture-logo-small.png"/>
                {% if error_message %}
                    <div class="alert alert-danger">{{error_message}}</div>
                {% endif %}
                {% if dialog_change %}
                    <p>Please fill the form to change your current password :</p>
                    {{input_password_old}}
                    {{input_password_1}}
                    {{input_password_2}}
                    {{input_submit}}

                {% elif dialog_lost %}
                    <p>Please enter an email address to reset your password:</p>

                    {{input_email}}
                    {{input_submit}}

                {% endif %}
            {{form_end}}
        </div>
    </div>
 </body>
</html>
"""
        template.html_otp = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body> 
    <div class="container">
        <div class="card card-container" style="text-align:center;">
            {% if error_message != "" %}
                  <div class="alert alert-danger" role="alert">{{error_message}}</div>
            {% endif %}
            <p>OTP Form</p>
            {{form_begin}}
                {{input_key}}
                {{input_submit}}
            {{form_end}}
            {{form_begin}}
                {{resend_button}}
            {{form_end}}
        </div>
    </div>
</body>
 </html>
"""

        template.html_message = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container">
            <img id="vulture_img" src="../templates/static/img/vulture-logo-small.png"/>
            <p>{{message}}</p>
            {% if link_redirect %}<a href='{{link_redirect}}'>Go back</a>{% endif %}
        </div>
    </div>
 </body>
</html>"""

        template.css = """
/*
 * Specific styles of signin component
 */
/*
 * General styles
 */
body, html {
    height: 100%;
    background: #FBFBF0 linear-gradient(135deg, #70848D, #21282E) repeat scroll 0% 0%;
}

.card-container.card {
    max-width: 350px;
    padding: 40px 40px;
}

#self_service {
    max-width: 450px;
    padding: 40px 40px;
}

.list-group-item {
    text-align: left;
}

.btn {
    font-weight: 700;
    height: 36px;
    -moz-user-select: none;
    -webkit-user-select: none;
    user-select: none;
    cursor: default;
}

/*
 * Card component
 */
.card {
    text-align:center;
    background-color: #F7F7F7;
    /* just in case there no content*/
    padding: 20px 25px 30px;
    margin: 0 auto 25px;
    margin-top: 50px;
    /* shadows and rounded borders */
    -moz-border-radius: 2px;
    -webkit-border-radius: 2px;
    border-radius: 2px;
    -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
    box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3);
}

#vulture_img{
    width:150px;
}

.form-signin{
    text-align: center;
}

#captcha{
    border:1px solid #c5c5c5;
    margin-bottom: 10px;
}

.alert{
    margin-bottom: 0px;
    margin-top:15px;
}

.reauth-email {
    display: block;
    color: #404040;
    line-height: 2;
    margin-bottom: 10px;
    font-size: 14px;
    text-align: center;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.form-signin #inputEmail,
.form-signin #inputPassword {
    direction: ltr;
    height: 44px;
    font-size: 16px;
}

input[type=email],
input[type=password],
input[type=text],
button {
    width: 100%;
    display: block;
    margin-bottom: 10px;
    z-index: 1;
    position: relative;
    -moz-box-sizing: border-box;
    -webkit-box-sizing: border-box;
    box-sizing: border-box;
}

.form-signin .form-control:focus {
    border-color: rgb(104, 145, 162);
    outline: 0;
    -webkit-box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgb(104, 145, 162);
    box-shadow: inset 0 1px 1px rgba(0,0,0,.075),0 0 8px rgb(104, 145, 162);
}

.btn.btn-signin {
    background-color: #F1A14C;
    padding: 0px;
    font-weight: 700;
    font-size: 14px;
    height: 36px;
    -moz-border-radius: 3px;
    -webkit-border-radius: 3px;
    border-radius: 3px;
    border: none;
    -o-transition: all 0.218s;
    -moz-transition: all 0.218s;
    -webkit-transition: all 0.218s;
    transition: all 0.218s;
}

.btn.btn-signin:hover{
    cursor: pointer;
}

.forgot-password {
    color: rgb(104, 145, 162);
}

.forgot-password:hover,
.forgot-password:active,
.forgot-password:focus{
    color: rgb(12, 97, 33);
}
"""

        template.email_from = "no-reply@vulture"
        template.email_subject = "Password reset request for {{ app.name }}"
        template.email_body = """<html>
<head>
</head>
<body>
<p>Dear Sir or Madam, <br><br>

We got a request to reset your account on {{ app.url }}.<br><br>

Click here to reset your password: <a href="{{resetLink}}">Reset password</a><br><br>

If you ignore this message, your password won't be changed.<br>
If you didn't request a password reset, <a href='mailto:abuse@vulture'>let us know</a><br>
</body>
</html>
"""
        template.html_error_403 = "403 Forbidden"
        template.html_error_404 = "404 Not found"
        template.html_error_405 = "405 Method Not Allowed"
        template.html_error_406 = "406 Not Acceptable"
        template.html_error_500 = "500 Internal Server Error"
        template.html_error_501 = "501 Not Implemented"
        template.html_error_502 = "502 Bad Gateway"
        template.html_error_503 = "503 Service Unavailable"
        template.html_error_504 = "504 Gateway Time-out"

        template.html_error = """<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    <style>
        {{style}}
    </style>
</head>
<body>
    <div class="container">
        <div class="card card-container">
                <img id="vulture_img" src="https://www.vultureproject.org/assets/images/logo_mini.png"/>
                <p>{{message}}</p>
        </div>
    </div>
</body>
</html>"""
        template.html_registration = """<!DOCTYPE html>
<html>
 <head>
    <meta charset="utf-8" />
    <title>Titre</title>
    <link rel="stylesheet" href="templates/static/html/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">
    {{style}}
 </head>
 <body>
    <div class="container">
        <div class="card card-container" style="text-align:center;">
            {{form_begin}}
                <img id="vulture_img" src="templates/static/img/vulture-logo-small.png"/>
                {% if error_message %}
                    <div class="alert alert-danger">{{error_message}}</div>
                {% endif %}
                {{captcha}}
                {{input_captcha}}
                {% if step2 %}
                    <p>Please fill the form to register your account :</p>
                    {{input_username}}
                    {% if ask_phone %}
                    {{input_phone}}
                    {% endif %}
                    {{input_password_1}}
                    {{input_password_2}}
                    {{input_submit}}
                {% elif step1 %}
                    <p>Please enter your email address to receive the registration mail :</p>
                    {{input_email}}
                    {{input_submit}}
                {% endif %}
            {{form_end}}
        </div>
    </div>
 </body>
</html>"""
        template.email_register_from = "no-reply@vulture"
        template.email_register_subject = "Registration request for {{ app.name }}"
        template.email_register_body = """<html>
    <head>
    </head>
    <body>
        <p>Dear Sir or Madam, <br><br>
    
        We got a request to register your account on {{ app.url }}.<br><br>
    
        Click here to validate the registration : <a href="{{registerLink}}">Register account</a><br><br>
    
        If you ignore this message, your account won't be confirmed.<br>
        If you didn't request a registration, <a href='mailto:abuse@vulture'>let us know</a><br>
    </body>
</html>
        """

    form = portalTemplateForm(request.POST or None, instance=template)
    # Saving information into database and redirect to template list
    if request.method == 'POST' and form.is_valid():
        template = form.save(commit=False)

        for tpl in tpl_list:
            html = getattr(template, tpl)
            if tpl not in ["email_subject", "email_body", "email_register_subject", "email_register_body"]:
                html = html.replace("{{form_begin}}", "{{form_begin}}{% csrf_token %}")
                html = "{% autoescape off %}\n" + html + "\n" + "{% endautoescape %}"
            if tpl == "html_logout":
                # Load cluster global configuration
                cluster = Cluster.objects.get()
                system_settings = cluster.system_settings
                global_conf = system_settings.global_settings
                html = html.replace('src=\"portal_statics/', 'src=\"../'+global_conf.public_token+"/portal_statics/")
            setattr(template, tpl, html)

        template.save()
        config_modified.send(sender=portalTemplate, id=template.id)
        return HttpResponseRedirect('/template/')

    images = TemplateImage.objects()

    return render_to_response('template_edit.html',
                              {'form': form, 'object_id': object_id, 'template': template, 'images': images},
                              context_instance=RequestContext(request))
Ejemplo n.º 4
0
def edit(request, object_id=None):
    """ View dedicated to access management

    :param object_id: MongoDB object_id of access list
    :param request: Django request object
    """

    modaccess = None
    #Retrieving access configuration
    if object_id:
        modaccess = ModAccess.objects.with_id(ObjectId(object_id))
        access_list = modaccess.access_list
    else:
        access_list = ""

    form = ModAccessForm(request.POST or None, instance=modaccess)

    #Check if request are valid - and populate arrays with form values
    if request.method == 'POST':
        dataPosted = request.POST
        dataPostedRaw = str(request.body).split("&")
        access_list = ""
        for data in dataPostedRaw:
            #Access rule management
            m = re.match('element_(\d+)', data)
            if m != None:
                id_ = m.group(1)

                #Force harmless default values to prevent any injection or jQuery problem
                element = 'all-denied'
                isnot = ''
                expected = ''

                try:
                    element = dataPosted['element_' + id_]
                except:
                    continue

                try:
                    isnot = dataPosted['element_not_' + id_]
                    expected = dataPosted['expected_' + id_]
                except:
                    pass

                access_list = access_list + str(element) + '|||' + str(
                    isnot) + '|||' + str(expected) + '\n'

    #We need to transform the access_list text to a list of access rules
    access_rules = list()
    for r in access_list.split('\n'):
        elt = r.split('|||')
        try:
            rule = AccessRule()
            rule.element = elt[0]
            rule.isnot = elt[1]
            rule.expected = elt[2]
            access_rules.append(rule)
        except:
            pass

    # Saving information into database and redirect to application list
    if request.method == 'POST' and form.is_valid():
        modaccess = form.save(commit=False)
        modaccess.access_list = access_list
        modaccess.save()
        config_modified.send(sender=ModAccess, id=modaccess.id)
        return HttpResponseRedirect('/firewall/access/')

    return render_to_response('access_edit.html', {
        'form': form,
        'object_id': object_id,
        'modaccess': modaccess,
        'access_rules': access_rules
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 5
0
def edit(request, object_id=None):
    """ View dedicated to proxy balancer management

    :param object_id: MongoDB object_id of a proxybalancer
    :param request: Django request object
    """
    # Retrieving rewriting configuration
    balancer = ProxyBalancer.objects.with_id(ObjectId(object_id))

    # ProxyBalancer doesn't exist ==> create it
    if not balancer:
        balancer = ProxyBalancer(name="My Proxy Balancer")

    form = ProxyBalancerForm(request.POST or None,
                             instance=balancer,
                             error_class=DivErrorList)

    members = []
    if request.method == 'POST':
        dataPosted = request.POST
        dataPostedRaw = str(request.body).split("&")
        for data in dataPostedRaw:

            # Members management
            m = re.match('uri_type_(\d+)', data)
            if m is not None:
                id_ = m.group(1)

                # Force harmless default values to prevent any injection or jQuery problem
                uri_type = dataPosted.get('uri_type_' + id_, "http")
                uri = dataPosted.get('uri_' + id_, '192.168.1.1')
                # Boolean fields
                disablereuse = True if dataPosted.get('disablereuse_' +
                                                      id_) else False
                keepalive = True if dataPosted.get('keepalive_' +
                                                   id_) else False
                lbset = dataPosted.get('lbset_' + id_, 0)
                retry = dataPosted.get('retry_' + id_, 60)
                route = dataPosted.get('route_' + id_, "")
                timeout = dataPosted.get('timeout_' + id_, 60)
                ttl = dataPosted.get('ttl_' + id_, "")
                config = dataPosted.get('config_' + id_, "")

                #FIXME: Coherence control
                member = ProxyBalancerMember(uri_type, uri, disablereuse,
                                             keepalive, lbset, retry, route,
                                             timeout, ttl, config)
                members.append(member)
    else:
        members = balancer.members

    # Saving information into database and redirect to balancer list
    if request.method == 'POST' and form.is_valid():

        # Verify coherence of backends type
        member_type = ""
        for member in members:
            if member_type and member.uri_type != member_type:
                form.add_error('members',
                               "You cannot set different types of backend.")
                break
            else:
                member_type = member.uri_type

        if form.errors:
            return render_to_response('proxybalancer_edit.html', {
                'form': form,
                'object_id': object_id,
                'balancername': balancer.name,
                'members': members
            },
                                      context_instance=RequestContext(request))

        #1) Remove old members
        old_balancer = ProxyBalancer.objects.with_id(ObjectId(object_id))
        if old_balancer and old_balancer.members:
            for member in old_balancer.members:
                member.delete()

        #2) Create new members
        for member in members:
            member.save()

        #3) Assign members
        balancer = form.save(commit=False)
        balancer.members = members

        #4) Save balancer
        balancer.save()
        config_modified.send(sender=ProxyBalancer, id=balancer.id)

        return HttpResponseRedirect('/network/proxybalancer/#reload')

    return render_to_response('proxybalancer_edit.html', {
        'form': form,
        'object_id': object_id,
        'balancername': balancer.name,
        'members': members
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 6
0
def edit_rules(request, object_id=None):
    """ View dedicated to mod_security rules set management

    :param object_id: MongoDB object_id of mod_security rules set
    :param request: Django request object
    """

    modsec_rulesset = None
    #Retrieving access configuration
    if object_id:
        modsec_rulesset = ModSecRulesSet.objects.with_id(ObjectId(object_id))

    form = ModSecRulesSetForm(request.POST or None, instance=modsec_rulesset)

    # Saving information into database and redirect to policy list
    if request.method == 'POST' and form.is_valid():

        modsec_rs = form.save(commit=False)
        modsec_rs.save()
        config_modified.send(sender=ModSecRulesSet, id=modsec_rs.id)

        dataPosted = request.POST
        # Handle OWASP / TRSUWAVE or Custom selection
        if modsec_rs.type_rule in ('crs', 'trustwave', 'vulture', 'wlbl'):
            rules = ModSecRules.objects.filter(rs=modsec_rs).order_by('name')
            for rule in rules:
                rule.is_enabled = False
                rule_enabled = None

                try:
                    rule_enabled = dataPosted['rule_' + str(rule.id)]
                except Exception as e:
                    rule.save()
                    continue

                if rule_enabled:
                    rule.is_enabled = True
                rule.save()

        # Else, create or update the custom rules
        else:
            try:
                custom_rules = dataPosted['custom_rules']
            except Exception as e:
                custom_rules = ""
                pass

            create = False
            try:
                rule = ModSecRules.objects.get(rs=modsec_rulesset)
            except Exception as e:
                create = True
                rule = ModSecRules()
                pass

            rule.rs = ModSecRulesSet.objects.with_id(ObjectId(modsec_rs.id))
            rule.name = "custom.conf"
            rule.rule_content = custom_rules
            rule.save()

        conf = modsec_rs.get_conf()
        modsec_rs.conf = conf
        modsec_rs.save()

        if modsec_rs.type_rule == 'virtualpatching':
            return HttpResponseRedirect('/firewall/virtualpatching/')
        else:
            return HttpResponseRedirect('/firewall/modsec_rules/')

    # Build the list of available / activated rules
    rules_list = []
    custom_file = None
    custom_rules = None
    is_crs = False
    is_trustwave = False
    is_crs_or_trustwave = False
    whitelist_or_blacklist = False

    if modsec_rulesset:
        if modsec_rulesset.type_rule in ('crs', 'trustwave', 'vulture'):
            is_crs_or_trustwave = True
            rules = ModSecRules.objects.filter(
                rs=modsec_rulesset).order_by('name')
            for rule in rules:
                rules_list.append(rule)

        elif modsec_rulesset.type_rule == 'wlbl':
            whitelist_or_blacklist = True
            try:
                rules = ModSecRules.objects.filter(
                    rs=modsec_rulesset).order_by('name')
            except ModSecRules.DoesNotExist:
                rules = []

            for rule in rules:
                rule.rule_content = rule.rule_content.split('\n')
                rules_list.append(rule)

        # Load rule content for custom Rule, except if dataPosted exists
        else:
            # There can be only one rule
            try:
                rules = ModSecRules.objects.get(rs=modsec_rulesset)
                custom_rules = rules.rule_content
            except ModSecRules.DoesNotExist:
                custom_rules = ""

    # Override custom_rules with posted content, if any
    try:
        dataPosted = request.POST
        custom_rules = dataPosted['custom_rules']
    except Exception as e:
        pass

    if is_crs_or_trustwave:
        return render_to_response('modsec_rulesset_edit_crs.html', {
            'form': form,
            'object_id': object_id,
            'modsec_rulesset': modsec_rulesset,
            'rules_list': rules_list,
            'custom_rules': custom_rules
        },
                                  context_instance=RequestContext(request))
    elif whitelist_or_blacklist:
        return render_to_response('modsec_rulesset_edit_wlbl.html', {
            'form': form,
            'object_id': object_id,
            'modsec_rulesset': modsec_rulesset,
            'rules_list': rules_list,
            'custom_rules': custom_rules
        },
                                  context_instance=RequestContext(request))
    else:
        return render_to_response('modsec_rulesset_edit.html', {
            'form': form,
            'object_id': object_id,
            'modsec_rulesset': modsec_rulesset,
            'rules_list': rules_list,
            'custom_rules': custom_rules
        },
                                  context_instance=RequestContext(request))
Ejemplo n.º 7
0
def edit(request, object_id=None):
    """ View dedicated to mod_security policy management

    :param object_id: MongoDB object_id of mod_security profile
    :param request: Django request object
    """

    modsec = None
    dos_rules = []
    # Retrieving access configuration
    if object_id:
        modsec = ModSec.objects.with_id(ObjectId(object_id))

    if request.method == 'POST':
        form = ModSecForm(request.POST, instance=modsec)
        dataPosted = request.POST
        dataPostedRaw = str(request.body).split("&")
        for data in dataPosted:
            m = re.match('DOSRule_url_(\d+)', data)
            if m is not None:
                id_ = m.group(1)

                # Force harmless default values to prevent any injection or jQuery problem
                dos_rule_enabled = True
                dos_rule_url = "/index.php"
                dos_rule_burst = 100
                dos_rule_thresold = 100
                dos_rule_timeout = 600

                try:
                    dos_rule_enabled = True if dataPosted.get(
                        'DOSRule_enable_' + id_) == 'on' else False
                    dos_rule_url = dataPosted['DOSRule_url_' + id_]
                    dos_rule_burst = dataPosted['DOSRule_burst_' + id_]
                    dos_rule_thresold = dataPosted['DOSRule_thresold_' + id_]
                    dos_rule_timeout = dataPosted['DOSRule_timeout_' + id_]
                except Exception as e:
                    pass

                dos_rule = ModSecDOSRules(dos_rule_enabled, dos_rule_url,
                                          dos_rule_burst, dos_rule_thresold,
                                          dos_rule_timeout)
                dos_rules.append(dos_rule)
    else:
        form = ModSecForm(None, instance=modsec)
        try:
            dos_rules = modsec.dos_rules
        except:
            dos_rules = []

    if request.method == 'POST' and form.is_valid():
        old_modsec = ModSec.objects.with_id(ObjectId(object_id))

        # 1) Remove old DOSRules
        if old_modsec and old_modsec.dos_rules:
            for dos_rule in old_modsec.dos_rules:
                dos_rule.delete()

        # 2) Create new DOSRules
        for dos_rule in dos_rules:
            dos_rule.save()

        modsec = form.save(commit=False)
        modsec.dos_rules = dos_rules

        if request.POST.get('block_desktops_ua', "off") == "on":
            modsec.ua_browser_anomaly_score = "999"
        else:
            modsec.ua_browser_anomaly_score = "0"

        if request.POST.get('block_crawler_ua', "off") == "on":
            modsec.ua_crawler_anomaly_score = "999"
        else:
            modsec.ua_crawler_anomaly_score = "2"

        if request.POST.get('block_suspicious_ua', "off") == "on":
            modsec.ua_unknown_anomaly_score = "999"
            modsec.ua_anonymous_anomaly_score = "999"
            modsec.ua_bot_anomaly_score = "999"
            modsec.ua_console_anomaly_score = "999"
            modsec.ua_emailclient_anomaly_score = "999"
            modsec.ua_emailharvester_anomaly_score = "999"
            modsec.ua_script_anomaly_score = "999"
        else:
            modsec.ua_unknown_anomaly_score = "2"
            modsec.ua_anonymous_anomaly_score = "2"
            modsec.ua_bot_anomaly_score = "2"
            modsec.ua_console_anomaly_score = "2"
            modsec.ua_emailclient_anomaly_score = "2"
            modsec.ua_emailharvester_anomaly_score = "2"
            modsec.ua_script_anomaly_score = "2"

        modsec.outbound_anomaly_score_threshold = modsec.inbound_anomaly_score_threshold

        modsec.save()
        config_modified.send(sender=ModSec, id=modsec.id)
        return HttpResponseRedirect('/firewall/modsec/#reload')

    return render_to_response('modsec_edit.html', {
        'form': form,
        'object_id': object_id,
        'modsec': modsec,
        'dos_rules': dos_rules
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 8
0
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Vulture 3.  If not, see http://www.gnu.org/licenses/.
"""
__author__ = "Kevin Guillemot"
__credits__ = []
__license__ = "GPLv3"
__version__ = "3.0.0"
__maintainer__ = "Vulture Project"
__email__ = "*****@*****.**"
__doc__ = """This migration script reload Applications configuration"""

import os
import sys

sys.path.append('/home/vlt-gui/vulture')
os.environ.setdefault("DJANGO_SETTINGS_MODULE", 'vulture.settings')

import django
django.setup()

from gui.models.system_settings import Cluster
from gui.signals.gui_signals import config_modified

if __name__ == '__main__':

    config_modified.send(sender=Cluster, id=None)

    print("Applications configuration reloaded.")
Ejemplo n.º 9
0
def edit(request, object_id=None):
    """ View dedicated to rewriting rules management

    :param object_id: MongoDB object_id of a rule
    :param request: Django request object
    """
    # Retrieving rewriting configuration
    rewrite = Rewrite.objects.with_id(ObjectId(object_id))

    # Rewrite doesn't exist ==> create it
    if not rewrite:
        rewrite = Rewrite(name="My rule", is_template=False)

    # Check if rules are valid - and populate an array
    ruleset = []

    form = RewriteForm(request.POST or None, instance=rewrite)

    if request.method == 'POST':

        dataPosted = request.POST
        dataPostedRaw = str(request.body).split("&")
        for data in dataPostedRaw:

            m = re.match('pattern_(\d+)', data)
            if m is not None:
                id_ = m.group(1)

                # Force harmless default values to prevent any injection or jQuery problem
                pattern = '^/(.*)$'
                replacement = '/test/$1'
                flags = 'R'

                try:
                    pattern = dataPosted['pattern_' + id_]
                    replacement = dataPosted['replacement_' + id_]
                    flags = dataPosted['flags_' + id_]
                except Exception as e:
                    pass

                # FIXME: Coherence control
                rule = RewriteRule(pattern, replacement, flags)
                ruleset.append(rule)
    else:
        ruleset = rewrite.rules

    reload_needed = False
    # Saving information into database and redirect to rewrite list
    if request.method == 'POST' and form.is_valid():

        old_rewrite = Rewrite.objects.with_id(ObjectId(object_id))

        rewrite = form.save(commit=False)

        # If there is no old RewriteRule
        if not old_rewrite:
            reload_needed = True
        else:
            if len(ruleset) != len(old_rewrite.rules):
                reload_needed = True
            elif rewrite.pk != old_rewrite.pk \
                    or rewrite.name != old_rewrite.name \
                    or rewrite.is_template != old_rewrite.is_template \
                    or rewrite.application != old_rewrite.application:
                reload_needed = True
            else:
                i = 0
                for rule in ruleset:
                    if old_rewrite.rules[i].pattern != rule.pattern or \
                                    old_rewrite.rules[i].replacement != rule.replacement or \
                                    old_rewrite.rules[i].flags != rule.flags:
                        reload_needed = True
                        break
                    i += 1

        if reload_needed:
            # 1) Remove old rules
            if old_rewrite and old_rewrite.rules:
                for rule in old_rewrite.rules:
                    rule.delete()

            # 2) Create new rules
            for rule in ruleset:
                rule.save()

            # 3) Assign rules
            rewrite.rules = ruleset

            # 4) Save rewriting
            rewrite.save()
            config_modified.send(sender=Rewrite, id=rewrite.id)

        if reload_needed:
            return HttpResponseRedirect('/network/rewrite/#reload')
        else:
            return HttpResponseRedirect('/network/rewrite/')

    return render_to_response('rewrite_edit.html', {
        'form': form,
        'object_id': object_id,
        'rulename': rewrite.name,
        'ruleset': ruleset
    },
                              context_instance=RequestContext(request))
Ejemplo n.º 10
0
def edit(request, object_id=None):
    """ method dedicated to certificate modification
    :param request: Django request object
    Obviously, only properties not related to the certificate can be modified
    It is possible to change:
        - The friendly name of the certificate
        - The chain list
    """

    # Retrieving access configuration
    if object_id:
        cert = SSLCertificate.objects.with_id(ObjectId(object_id))
    else:
        return HttpResponseRedirect('/system/cert/')

    if request.method == 'POST':
        dataPosted = request.POST

        error = dict()
        err = None
        name = None
        chain = None
        crl = None

        try:
            chain = str(dataPosted['chain'])
        except:
            err = 1
            error['chain'] = 'Chain is missing'
            pass

        try:
            name = str(dataPosted['name'])
        except:
            err = 1
            error['cert'] = 'Name is missing'
            pass

        if chain:
            cert.chain = chain

        try:
            crl = str(dataPosted['crl'])
        except:
            pass

        cert.crl = crl

        if name:
            cert.name = name
        else:
            err = 1
            error['cert'] = 'Name is required'

        if err:
            return render_to_response('cert_edit.html', {
                'cert': cert,
                'object_id': object_id,
                'error': error
            },
                                      context_instance=RequestContext(request))

        # Update certificate details
        cert.save()
        config_modified.send(sender=SSLCertificate, id=cert.id)

        return HttpResponseRedirect('/system/cert/')

    return render_to_response('cert_edit.html', {
        'cert': cert,
        'object_id': object_id,
    },
                              context_instance=RequestContext(request))