def edit_user(request, user_id): user = get_object_or_404(User, pk=user_id) context = {'user': user, 'username': json.dumps(user.username)} if request.method == 'POST': form = UserSettingsForm(request.POST, instance=user) if form.is_valid(): user = form.save() UserAction.create(action_type='edit_user', comment=form.cleaned_data['comment'], user=request.user, other_user=user) return redirect('list_accounts') context['error'] = 'Edition form is not valid' context['form'] = form context['current_action'] = 'Edit user %s' % user.username return scirius_render(request, 'accounts/user.html', context) form = UserSettingsForm(instance=user) context['form'] = form context['current_action'] = 'Edit user %s' % user.username context['is_from_ldap'] = user.sciriususer.is_from_ldap() return scirius_render(request, 'accounts/user.html', context)
def add_group(request): if request.method == 'POST': form = GroupEditForm(request.POST) if form.is_valid(): group = form.save() UserAction.create(action_type='create_group', comment=form.cleaned_data['comment'], user=request.user, new_group=group) return redirect('list_accounts') context = { 'form': form, 'current_action': 'Add role', 'can_edit': True } return scirius_render(request, 'accounts/group.html', context) form = GroupEditForm() context = { 'form': form, 'current_action': 'Add role', 'mapping': json.dumps(form.mapping), 'can_edit': True } return scirius_render(request, 'accounts/group.html', context)
def add_user(request): if request.method == 'POST': form = UserSettingsForm(request.POST) password_form = PasswordCreationForm(request.POST) if form.is_valid() and password_form.is_valid(): ruser = form.save() ruser.set_password(password_form.cleaned_data['password1']) ruser.save() UserAction.create(action_type='create_user', comment=form.cleaned_data['comment'], user=request.user, new_user=ruser) return redirect('list_accounts') context = { 'error': 'Username and/or password are not valid', 'form': form, 'password_form': password_form, 'current_action': 'Add user' } return scirius_render(request, 'accounts/user.html', context) form = UserSettingsForm() password_form = PasswordCreationForm() context = { 'form': form, 'current_action': 'Add user', 'password_form': password_form } return scirius_render(request, 'accounts/user.html', context)
def edit_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: return scirius_render(request, 'rules/edit_ruleset.html', {'ruleset': ruleset, 'error': 'Unsufficient permissions'}) if request.method == 'POST': # If the form has been submitted... # check if this is a categories edit # ID is unique so we can just look by indice and add if request.POST.has_key('category'): # clean ruleset ruleset.categories.clear() # add updated entries for cat in request.POST.getlist('category_selection'): category = get_object_or_404(Category, pk=cat) ruleset.categories.add(category) ruleset.save() elif request.POST.has_key('rules'): for rule in request.POST.getlist('rule_selection'): rule_object = get_object_or_404(Rule, pk=rule) ruleset.suppressed_rules.remove(rule_object) ruleset.save() elif request.POST.has_key('sources'): # clean ruleset ruleset.sources.clear() # add updated entries for src in request.POST.getlist('source_selection'): source = get_object_or_404(SourceAtVersion, pk=src) ruleset.sources.add(source) ruleset.save() return redirect(ruleset) else: cats_selection = [] categories_list = {} sources = ruleset.sources.all() ruleset_cats = ruleset.categories.all() for sourceatversion in sources: src_cats = Category.objects.filter(source = sourceatversion.source) for pcats in src_cats: if pcats in ruleset_cats: cats_selection.append(str(pcats.id)) cats = EditCategoryTable(src_cats) tables.RequestConfig(request,paginate = False).configure(cats) categories_list[sourceatversion.source.name] = cats rules = EditRuleTable(ruleset.suppressed_rules.all()) tables.RequestConfig(request, paginate = False).configure(rules) context = {'ruleset': ruleset, 'categories_list': categories_list, 'sources': sources, 'rules': rules, 'cats_selection': ", ".join(cats_selection) } if request.GET.has_key('mode'): context['mode'] = request.GET['mode'] if context['mode'] == 'sources': all_sources = SourceAtVersion.objects.all() sources_selection = [] for source in sources: sources_selection.append(source.pk) sources_list = EditSourceAtVersionTable(all_sources) tables.RequestConfig(request, paginate = False).configure(sources_list) context['sources_list'] = sources_list context['sources_selection'] = sources_selection return scirius_render(request, 'rules/edit_ruleset.html', context)
def elasticsearch(request): data = None if request.GET.__contains__('query'): query = request.GET.get('query', 'dashboards') if query == 'dashboards': data = es_get_dashboard(count=settings.KIBANA_DASHBOARDS_COUNT) elif query == 'rules': host = request.GET.get('host', None) from_date = request.GET.get('from_date', None) if host != None and from_date != None: rules = es_get_rules_stats(request, host, from_date = from_date) context = {'table': rules} return scirius_render(request, 'rules/table.html', context) elif query == 'rule': sid = request.GET.get('sid', None) from_date = request.GET.get('from_date', None) if from_date != None and sid != None: hosts = es_get_sid_by_hosts(request, sid, from_date = from_date) context = {'table': hosts} return scirius_render(request, 'rules/table.html', context) elif query == 'timeline': from_date = request.GET.get('from_date', None) cshosts = request.GET.get('hosts', None) hosts = cshosts.split(',') qfilter = request.GET.get('filter', None) data = es_get_timeline(from_date = from_date, hosts = hosts, qfilter = qfilter) else: data = None else: data = es_get_dashboard(count=settings.KIBANA_DASHBOARDS_COUNT) return HttpResponse(json.dumps(data), content_type="application/json")
def edit_group(request, group_id): django_group = get_object_or_404(DjangoGroup, pk=group_id) context = { 'group': django_group, 'action': 'edit', 'group_name': json.dumps(django_group.name) } if request.method == 'POST': form = GroupEditForm(request.POST, instance=django_group) if form.is_valid(): form.save() UserAction.create(action_type='edit_group', comment=form.cleaned_data['comment'], user=request.user, group=django_group) return redirect('list_accounts') context['error'] = 'Edition form is not valid' context['form'] = form context['current_action'] = 'Edit group %s' % django_group.name return scirius_render(request, 'accounts/group.html', context) form = GroupEditForm(instance=django_group) context['can_edit'] = django_group.name not in GroupEditForm.DEFAULT_GROUPS context['form'] = form context['mapping'] = json.dumps(form.mapping) context['current_action'] = 'Edit role %s' % django_group.name return scirius_render(request, 'accounts/group.html', context)
def update(request): suri = get_suri() if suri == None: form = SuricataForm() context = { 'creation': True , 'form': form} return scirius_render(request, 'suricata/edit.html', context) if request.method == 'POST': form = SuricataUpdateForm(request.POST) if not form.is_valid(): return scirius_render(request, 'suricata/update.html', { 'suricata': suri, 'error': "Invalid form"}) message = [] if form.cleaned_data['reload']: suri.ruleset.update() message.append("Rule downloaded at %s. " % (suri.ruleset.updated_date)) if form.cleaned_data['build']: suri.generate() suri.updated_date = datetime.now() suri.save() message.append("Successful ruleset build at " + str(suri.updated_date)) if form.cleaned_data['push']: ret = suri.push() suri.updated_date = datetime.now() suri.save() if ret: message.append("Successful asked ruleset reload at " + str(suri.updated_date)) else: message.append("Suricata restart already asked.") context = { 'message': message, 'suricata': suri } return scirius_render(request, 'suricata/update.html', context) else: return scirius_render(request, 'suricata/update.html', { 'suricata': suri })
def loginview(request, target): if request.method == 'POST': form = LoginForm(request.POST) if not form.is_valid(): # All validation rules pass form = LoginForm() context = { 'form': form, 'error': 'Invalid form' } return scirius_render(request, 'accounts/login.html', context) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if not form.cleaned_data['persistent']: request.session.set_expiry(0) return redirect("/" + target) else: form = LoginForm() context = { 'form': form, 'error': 'Disabled account' } return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = { 'form': form, 'error': 'Invalid login' } return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = { 'form': form } return scirius_render(request, 'accounts/login.html', context)
def edit_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: return scirius_render(request, 'rules/edit_ruleset.html', {'ruleset': ruleset, 'error': 'Unsufficient permissions'}) if request.method == 'POST': # If the form has been submitted... # check if this is a categories edit # ID is unique so we can just look by indice and add if request.POST.has_key('category'): # clean ruleset ruleset.categories.clear() # add updated entries for cat in request.POST.getlist('category_selection'): category = get_object_or_404(Category, pk=cat) ruleset.categories.add(category) ruleset.needs_test() elif request.POST.has_key('rules'): for rule in request.POST.getlist('rule_selection'): rule_object = get_object_or_404(Rule, pk=rule) rule_object.enable(ruleset) ruleset.needs_test() elif request.POST.has_key('sources'): # clean ruleset ruleset.sources.clear() # add updated entries for src in request.POST.getlist('source_selection'): source = get_object_or_404(SourceAtVersion, pk=src) ruleset.sources.add(source) ruleset.needs_test() return redirect(ruleset) else: cats_selection = [] categories_list = {} sources = ruleset.sources.all() ruleset_cats = ruleset.categories.all() for sourceatversion in sources: src_cats = Category.objects.filter(source = sourceatversion.source) for pcats in src_cats: if pcats in ruleset_cats: cats_selection.append(str(pcats.id)) cats = EditCategoryTable(src_cats) tables.RequestConfig(request,paginate = False).configure(cats) categories_list[sourceatversion.source.name] = cats rules = EditRuleTable(ruleset.suppressed_rules.all()) tables.RequestConfig(request, paginate = False).configure(rules) context = {'ruleset': ruleset, 'categories_list': categories_list, 'sources': sources, 'rules': rules, 'cats_selection': ", ".join(cats_selection) } if request.GET.has_key('mode'): context['mode'] = request.GET['mode'] if context['mode'] == 'sources': all_sources = SourceAtVersion.objects.all() sources_selection = [] for source in sources: sources_selection.append(source.pk) sources_list = EditSourceAtVersionTable(all_sources) tables.RequestConfig(request, paginate = False).configure(sources_list) context['sources_list'] = sources_list context['sources_selection'] = sources_selection return scirius_render(request, 'rules/edit_ruleset.html', context)
def edit_threshold(request, threshold_id): threshold = get_object_or_404(Threshold, pk=threshold_id) rule = threshold.rule if not request.user.is_staff: return redirect(threshold) if request.method == 'POST': # If the form has been submitted... form = EditThresholdForm( request.POST, instance=threshold) # A form bound to the POST data if form.is_valid(): # All validation rules pass form.save() return redirect(threshold) else: context = { 'threshold': threshold, 'form': form, 'error': 'Invalid form' } return scirius_render(request, 'rules/edit_threshold.html', context) else: form = EditThresholdForm(instance=threshold) context = {'threshold': threshold, 'form': form} return scirius_render(request, 'rules/edit_threshold.html', context)
def suppress_category(request, cat_id, operation='suppress'): cat_object = get_object_or_404(Category, id=cat_id) if not request.user.is_staff: context = { 'category': cat_object, 'error': 'Unsufficient permissions', 'operation': operation } return scirius_render(request, 'rules/suppress_category.html', context) if request.method == 'POST': # If the form has been submitted... form = RulesetSuppressForm(request.POST) if form.is_valid(): # All validation rules pass rulesets = form.cleaned_data['rulesets'] for ruleset_pk in rulesets: ruleset = get_object_or_404(Ruleset, pk=ruleset_pk) if operation == 'suppress': ruleset.categories.remove(cat_object) elif operation == 'enable': ruleset.categories.add(cat_object) ruleset.needs_test() ruleset.save() return redirect(cat_object) form = RulesetSuppressForm() context = {'category': cat_object, 'form': form, 'operation': operation} return scirius_render(request, 'rules/suppress_category.html', context)
def add_source(request): if not request.user.is_staff: return scirius_render(request, 'rules/add_source.html', {'error': 'Unsufficient permissions'}) if request.method == 'POST': # If the form has been submitted... form = SourceForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass try: source = Source.objects.create( name=form.cleaned_data['name'], uri=form.cleaned_data['uri'], method=form.cleaned_data['method'], created_date=datetime.now(), datatype=form.cleaned_data['datatype'], ) if source.method == 'local' and request.FILES.has_key('file'): source.handle_uploaded_file(request.FILES['file']) except IntegrityError, error: return scirius_render(request, 'rules/add_source.html', { 'form': form, 'error': error }) return redirect(source)
def switch_rule(request, rule_id, operation = 'suppress'): rule_object = get_object_or_404(Rule, sid=rule_id) if not request.user.is_staff: context = { 'rule': rule_object, 'operation': operation, 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/suppress_rule.html', context) if request.method == 'POST': # If the form has been submitted... form = RulesetSuppressForm(request.POST) if form.is_valid(): # All validation rules pass ruleset = form.cleaned_data['ruleset'] if operation == 'suppress': rule_object.disable(ruleset) elif operation == 'enable': rule_object.enable(ruleset) ruleset.save() return redirect(rule_object) form = RulesetSuppressForm() rules = rule_object.get_flowbits_group() context = { 'rule': rule_object, 'form': form } if len(rules): rules = RuleTable(rules) tables.RequestConfig(request).configure(rules) context['rules'] = rules context['operation'] = operation return scirius_render(request, 'rules/suppress_rule.html', context)
def switch_rule(request, rule_id, operation = 'suppress'): rule_object = get_object_or_404(Rule, sid=rule_id) if not request.user.is_staff: context = { 'rule': rule_object, 'operation': operation, 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/suppress_rule.html', context) if request.method == 'POST': # If the form has been submitted... form = RulesetSuppressForm(request.POST) if form.is_valid(): # All validation rules pass ruleset = form.cleaned_data['ruleset'] disable_rules = rule_object.get_flowbits_group() if operation == 'suppress': if disable_rules: ruleset.suppressed_rules.add(*list(disable_rules)) else: ruleset.suppressed_rules.add(rule_object) elif operation == 'enable': if disable_rules: ruleset.suppressed_rules.remove(*list(disable_rules)) else: ruleset.suppressed_rules.remove(rule_object) ruleset.save() return redirect(rule_object) form = RulesetSuppressForm() rules = rule_object.get_flowbits_group() context = { 'rule': rule_object, 'form': form } if len(rules): rules = RuleTable(rules) tables.RequestConfig(request).configure(rules) context['rules'] = rules context['operation'] = operation return scirius_render(request, 'rules/suppress_rule.html', context)
def index(request, error=None): # try to get suricata from db suri = get_suri() if settings.SURICATA_NAME_IS_HOSTNAME: suri.name = socket.gethostname() if suri: context = {'suricata': suri} if error: context['error'] = error if suri.ruleset: supp_rules = list( Rule.objects.filter( ruletransformation__ruleset=suri.ruleset, ruletransformation__key=Transformation.SUPPRESSED.value, ruletransformation__value=Transformation.S_SUPPRESSED.value )) if len(supp_rules): suppressed = ",".join([unicode(x.sid) for x in supp_rules]) context['suppressed'] = suppressed if settings.USE_ELASTICSEARCH: context['rules'] = True return scirius_render(request, 'suricata/index.html', context) else: form = SuricataForm() context = {'creation': True, 'form': form} missing = dependencies_check(Suricata) if missing: context['missing'] = missing return scirius_render(request, 'suricata/edit.html', context)
def loginview(request, target): if request.method == 'POST': form = LoginForm(request.POST) if not form.is_valid(): # All validation rules pass form = LoginForm() context = {'form': form, 'error': 'Invalid form'} return scirius_render(request, 'accounts/login.html', context) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) if not form.cleaned_data['persistent']: request.session.set_expiry(0) return redirect("/" + target) else: form = LoginForm() context = {'form': form, 'error': 'Disabled account'} return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form, 'error': 'Invalid login'} return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form} return scirius_render(request, 'accounts/login.html', context)
def switch_rule(request, rule_id, operation="suppress"): rule_object = get_object_or_404(Rule, sid=rule_id) if not request.user.is_staff: context = {"rule": rule_object, "operation": operation, "error": "Unsufficient permissions"} return scirius_render(request, "rules/suppress_rule.html", context) if request.method == "POST": # If the form has been submitted... form = RulesetSuppressForm(request.POST) if form.is_valid(): # All validation rules pass ruleset = form.cleaned_data["ruleset"] disable_rules = rule_object.get_flowbits_group() if operation == "suppress": if disable_rules: ruleset.suppressed_rules.add(*list(disable_rules)) else: ruleset.suppressed_rules.add(rule_object) elif operation == "enable": if disable_rules: ruleset.suppressed_rules.remove(*list(disable_rules)) else: ruleset.suppressed_rules.remove(rule_object) ruleset.save() return redirect(rule_object) form = RulesetSuppressForm() rules = rule_object.get_flowbits_group() context = {"rule": rule_object, "form": form} if len(rules): rules = RuleTable(rules) tables.RequestConfig(request).configure(rules) context["rules"] = rules context["operation"] = operation return scirius_render(request, "rules/suppress_rule.html", context)
def manageview(request, action): context = { 'action': 'User management' } if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): if request.user.is_superuser: ruser = form.save() sciriususer = SciriusUser.objects.create(user=ruser, timezone='UTC') sciriususer.save() else: context['error'] = 'Not enough permission to create users' else: if action != 'add': context['error'] = 'Invalid form' else: context['error'] = 'Username and/or password are not valid' context['form'] = form return scirius_render(request, 'accounts/user.html', context) else: if request.user.is_superuser is False: if len(action) == 0: action = 'list' context['error'] = 'Not enough permission to %s users' % action return scirius_render(request, 'accounts/user.html', context) if (action == 'add'): form = UserCreationForm() context = { 'form': form, 'current_action': 'Add user'} return scirius_render(request, 'accounts/user.html', context) return scirius_listing(request, User, 'Users', adduri="/accounts/manage/add")
def edit(request): suri = get_suri() if not request.user.is_staff: return redirect('/') if request.method == 'POST': if suri: suri.updated_date = timezone.now() form = SuricataForm(request.POST, instance = suri) else: form = SuricataForm(request.POST) if form.is_valid(): if suri: form.save() return redirect(index) try: suricata = Suricata.objects.create(name = form.cleaned_data['name'], descr = form.cleaned_data['descr'], output_directory = form.cleaned_data['output_directory'], created_date = timezone.now(), updated_date = timezone.now(), ruleset = form.cleaned_data['ruleset'], yaml_file = form.cleaned_data['yaml_file'], ) except IntegrityError, error: return scirius_render(request, 'suricata/edit.html', { 'form': form, 'error': error }) return redirect(index) else: return scirius_render(request, 'suricata/edit.html', { 'form': form, 'error': 'Invalid form' })
def add_source(request): if not request.user.is_staff: return scirius_render(request, 'rules/add_source.html', { 'error': 'Unsufficient permissions' }) if request.method == 'POST': # If the form has been submitted... form = AddSourceForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass try: src = Source.objects.create(name = form.cleaned_data['name'], uri = form.cleaned_data['uri'], authkey = form.cleaned_data['authkey'], method = form.cleaned_data['method'], created_date = timezone.now(), datatype = form.cleaned_data['datatype'], ) if src.method == 'local' and request.FILES.has_key('file'): try: src.handle_uploaded_file(request.FILES['file']) except OSError, error: src.delete() return scirius_render(request, 'rules/add_source.html', { 'form': form, 'error': error }) except IntegrityError, error: return scirius_render(request, 'rules/add_source.html', { 'form': form, 'error': error }) try: ruleset_list = form.cleaned_data['rulesets'] except: ruleset_list = [] rulesets = [ ruleset.pk for ruleset in ruleset_list ] ruleset_list = [ '"' + ruleset.name + '"' for ruleset in ruleset_list ] return scirius_render(request, 'rules/add_source.html', { 'source': src, 'update': True, 'rulesets': rulesets, 'ruleset_list': ruleset_list})
def edit_source(request, source_id): source = get_object_or_404(Source, pk=source_id) if not request.user.is_staff: return scirius_render(request, 'rules/add_source.html', { 'error': 'Unsufficient permissions' }) if request.method == 'POST': # If the form has been submitted... form = SourceForm(request.POST, request.FILES, instance=source) try: if source.method == 'local' and request.FILES.has_key('file'): categories = Category.objects.filter(source = source) firstimport = False if not categories: firstimport = True source.handle_uploaded_file(request.FILES['file']) if not source.datatype == 'other' and not firstimport: source.create_update() form.save() return redirect(source) except ValueError: pass else: form = SourceForm(instance = source) return scirius_render(request, 'rules/add_source.html', { 'form': form, 'source': source})
def edit_password(request, user_id): user = get_object_or_404(User, pk=user_id) context = {'user': user, 'username': json.dumps(user.username)} if request.method == 'POST': form = PasswordForm(request.POST) if form.is_valid(): user.set_password(form.cleaned_data['password']) user.save() if user == request.user: # If the user change his own password prevent the session to be invalidated update_session_auth_hash(request, user) UserAction.create(action_type='edit_user_password', comment=form.cleaned_data['comment'], user=request.user, other_user=user) return redirect('list_accounts') else: context['error'] = 'Password form is not valid' context['form'] = form return scirius_render(request, 'accounts/user.html', context) form = PasswordForm() context['form'] = form context['current_action'] = 'Edit password for user %s' % user.username return scirius_render(request, 'accounts/user.html', context)
def edit_source(request, source_id): source = get_object_or_404(Source, pk=source_id) if not request.user.is_staff: return scirius_render(request, "rules/add_source.html", {"error": "Unsufficient permissions"}) if request.method == "POST": # If the form has been submitted... form = SourceForm(request.POST, request.FILES, instance=source) try: if source.method == "local" and request.FILES.has_key("file"): categories = Category.objects.filter(source=source) firstimport = False if not categories: firstimport = True source.handle_uploaded_file(request.FILES["file"]) if not source.datatype == "other" and not firstimport: source.create_update() form.save() return redirect(source) except ValueError: pass else: form = SourceForm(instance=source) return scirius_render(request, "rules/add_source.html", {"form": form, "source": source})
def index(request, error = None): # try to get suricata from db suri = get_suri() if suri: context = {'suricata': suri} if error: context['error'] = error if suri.ruleset: supp_rules = list(suri.ruleset.suppressed_rules.all()) if len(supp_rules): suppressed = ",".join([ str(x.sid) for x in supp_rules]) context['suppressed'] = suppressed if settings.USE_ELASTICSEARCH: context['rules'] = True complete_context(request, context) return scirius_render(request, 'suricata/index.html', context) else: form = SuricataForm() context = { 'creation': True , 'form': form} missing = dependencies_check(Suricata) if missing: context['missing'] = missing return scirius_render(request, 'suricata/edit.html', context)
def editview(request, action): if request.user.is_authenticated(): if request.method == 'POST': context = { 'action': 'User settings' } orig_superuser = request.user.is_superuser orig_staff = request.user.is_staff if (action == 'password'): form = PasswordChangeForm(data=request.POST, user = request.user) elif (action == 'settings'): form = UserSettingsForm(request.POST, instance = request.user) if form.is_valid(): ruser = form.save(commit = False) if not orig_superuser: ruser.is_superuser = False ruser.is_staff = orig_staff ruser.save() form.save_m2m() else: context['error'] = 'Invalid form' return scirius_render(request, 'accounts/edit.html', context) else: if (action == 'password'): form = PasswordChangeForm(request.user) context = { 'form': form, 'action': 'Change password' } elif (action == 'settings'): if request.user.is_superuser: form = UserSettingsForm(instance = request.user) else: form = NormalUserSettingsForm(instance = request.user) context = { 'form': form, 'action': 'Edit settings for ' + request.user.username } else: context = { 'action': 'User settings' } return scirius_render(request, 'accounts/edit.html', context)
def update(request): suri = get_suri() if not request.user.is_staff: return redirect('/') if suri is None: form = SuricataForm() context = {'creation': True, 'form': form} return scirius_render(request, 'suricata/edit.html', context) if request.method == 'POST': form = SuricataUpdateForm(request.POST) if not form.is_valid(): return scirius_render(request, 'suricata/update.html', { 'suricata': suri, 'error': "Invalid form" }) message = [] if form.cleaned_data['reload']: try: suri.ruleset.update() except IOError as errors: return index(request, error="Can not fetch data: %s" % (errors)) message.append("Rule downloaded at %s." % str(suri.ruleset.updated_date)) if form.cleaned_data['build']: suri.generate() suri.updated_date = timezone.now() suri.save() message.append("Successful ruleset build at %s." % str(suri.updated_date)) if form.cleaned_data['push']: ret = suri.push() suri.updated_date = timezone.now() suri.save() if ret: message.append("Successful asked ruleset reload at %s." % str(suri.updated_date)) else: message.append("Suricata restart already asked.") UserAction.create(action_type='edit_suricata', comment=form.cleaned_data['comment'], user=request.user, suricata=suri) context = {'message': message, 'suricata': suri} return scirius_render(request, 'suricata/update.html', context) else: return scirius_render(request, 'suricata/update.html', { 'suricata': suri, 'form': CommentForm() })
def edit(request): suri = get_suri() if request.method == 'POST': if suri: suri.updated_date = timezone.now() form = SuricataForm(request.POST, instance=suri) else: form = SuricataForm(request.POST) if form.is_valid(): if suri: form.save() UserAction.create( action_type='edit_suricata', comment=form.cleaned_data['comment'], user=request.user, suricata=suri ) return redirect(index) try: suricata = Suricata.objects.create( name=form.cleaned_data['name'], descr=form.cleaned_data['descr'], output_directory=form.cleaned_data['output_directory'], created_date=timezone.now(), updated_date=timezone.now(), ruleset=form.cleaned_data['ruleset'], yaml_file=form.cleaned_data['yaml_file'], ) except IntegrityError as error: return scirius_render( request, 'suricata/edit.html', {'form': form, 'error': error} ) UserAction.create( action_type='create_suricata', comment=form.cleaned_data['comment'], user=request.user, suricata=suricata ) return redirect(index) else: return scirius_render( request, 'suricata/edit.html', {'form': form, 'error': 'Invalid form'} ) else: if suri: form = SuricataForm(instance=suri) else: form = SuricataForm() missing = dependencies_check(Suricata) return scirius_render(request, 'suricata/edit.html', {'form': form, 'missing': missing})
def elasticsearch(request): data = None if request.GET.__contains__("query"): query = request.GET.get("query", "dashboards") if query == "dashboards": data = es_get_dashboard(count=settings.KIBANA_DASHBOARDS_COUNT) elif query == "rules": host = request.GET.get("host", None) from_date = request.GET.get("from_date", None) qfilter = request.GET.get("filter", None) if host != None and from_date != None: rules = es_get_rules_stats(request, host, from_date=from_date, qfilter=qfilter) if rules == None: return HttpResponse(json.dumps(rules), content_type="application/json") context = {"table": rules} return scirius_render(request, "rules/table.html", context) elif query == "rule": sid = request.GET.get("sid", None) from_date = request.GET.get("from_date", None) if from_date != None and sid != None: hosts = es_get_sid_by_hosts(request, sid, from_date=from_date) context = {"table": hosts} return scirius_render(request, "rules/table.html", context) elif query == "timeline": from_date = request.GET.get("from_date", None) cshosts = request.GET.get("hosts", None) hosts = cshosts.split(",") qfilter = request.GET.get("filter", None) data = es_get_timeline(from_date=from_date, hosts=hosts, qfilter=qfilter) elif query == "health": data = es_get_health() elif query == "stats": data = es_get_stats() elif query == "indices": data = es_get_indices_stats() elif query == "rules_per_category": from_date = request.GET.get("from_date", None) cshosts = request.GET.get("hosts", None) if cshosts: hosts = cshosts.split(",") else: hosts = None qfilter = request.GET.get("filter", None) data = es_get_rules_per_category(from_date=from_date, hosts=hosts, qfilter=qfilter) else: data = None return HttpResponse(json.dumps(data), content_type="application/json") else: if request.is_ajax(): data = es_get_dashboard(count=settings.KIBANA_DASHBOARDS_COUNT) return HttpResponse(json.dumps(data), content_type="application/json") else: context = {} complete_context(request, context) return scirius_render(request, "rules/elasticsearch.html", context)
def changelog_source(request, source_id): source = get_object_or_404(Source, pk=source_id) supdate = SourceUpdate.objects.filter(source = source).order_by('-created_date') # get last for now if len(supdate) == 0: return scirius_render(request, 'rules/source.html', { 'source': source, 'error': "No changelog" }) changelogs = SourceUpdateTable(supdate) tables.RequestConfig(request).configure(changelogs) diff = supdate[0].diff() build_source_diff(request, diff) return scirius_render(request, 'rules/source.html', { 'source': source, 'diff': diff, 'changelogs': changelogs , 'src_update': supdate[0]})
def editview(request, action): if request.user.is_authenticated(): if request.method == 'POST': context = {'action': 'User settings'} orig_superuser = request.user.is_superuser orig_staff = request.user.is_staff if (action == 'password'): form = PasswordChangeForm(data=request.POST, user=request.user) elif (action == 'settings'): if request.user.is_superuser: form = UserSettingsForm(request.POST, instance=request.user) else: form = NormalUserSettingsForm(request.POST, instance=request.user) if form.is_valid(): ruser = form.save(commit=False) if not orig_superuser: ruser.is_superuser = False ruser.is_staff = orig_staff ruser.save() if action == 'settings': try: sciriususer = ruser.sciriususer sciriususer.timezone = form.cleaned_data['timezone'] except: sciriususer = SciriusUser.objects.create( user=ruser, timezone=form.cleaned_data['timezone']) sciriususer.save() else: context['error'] = 'Invalid form' return scirius_render(request, 'accounts/edit.html', context) else: if (action == 'password'): form = PasswordChangeForm(request.user) context = {'form': form, 'action': 'Change password'} elif (action == 'settings'): if request.user.is_superuser: form = UserSettingsForm(instance=request.user, ) else: form = NormalUserSettingsForm(instance=request.user) try: form.initial[ 'timezone'] = request.user.sciriususer.timezone except: pass context = { 'form': form, 'action': 'Edit settings for ' + request.user.username } else: context = {'action': 'User settings'} return scirius_render(request, 'accounts/edit.html', context)
def delete_source(request, source_id): source = get_object_or_404(Source, pk=source_id) if not request.user.is_staff: return scirius_render(request, 'rules/delete.html', { 'error': 'Unsufficient permissions' }) if request.method == 'POST': # If the form has been submitted... source.delete() return redirect("/rules/source/") else: context = {'object': source, 'delfn': 'delete_source' } return scirius_render(request, 'rules/delete.html', context)
def delete_source(request, source_id): source = get_object_or_404(Source, pk=source_id) if not request.user.is_staff: return scirius_render(request, "rules/delete.html", {"error": "Unsufficient permissions"}) if request.method == "POST": # If the form has been submitted... source.delete() return redirect("/rules/source/") else: context = {"object": source, "delfn": "delete_source"} return scirius_render(request, "rules/delete.html", context)
def loginview(request, target): if request.method == 'POST': form = LoginForm(request.POST) if not form.is_valid(): # All validation rules pass form = LoginForm() context = {'form': form, 'error': 'Invalid form'} return scirius_render(request, 'accounts/login.html', context) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) try: sciriususer = SciriusUser.objects.get(user=user) sciriususer.sciriususerapp except (SciriusUser.DoesNotExist, AttributeError): SciriusUser.objects.get_or_create( user=user, defaults={'timezone': 'UTC'}) get_middleware_module('common').update_scirius_user_class( user, form.cleaned_data) if not form.cleaned_data['persistent']: request.session.set_expiry(0) logger = logging.getLogger('authentication') logger.info("Successful login for '%s' from '%s'", username, get_client_ip(request)) UserAction.create(action_type='login', user=user, force_insert=True) return redirect("/" + target) else: form = LoginForm() context = {'form': form, 'error': 'Disabled account'} logger = logging.getLogger('authentication') logger.error( "Invalid login attempt for disabled account '%s' from '%s'", username, get_client_ip(request)) return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form, 'error': 'Invalid login'} logger = logging.getLogger('authentication') logger.error("Invalid login attempt for '%s' from '%s'", username, get_client_ip(request)) return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form} return scirius_render(request, 'accounts/login.html', context)
def delete_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: context = { 'object': ruleset, 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/delete.html', context) if request.method == 'POST': # If the form has been submitted... ruleset.delete() return redirect("/rules/ruleset/") else: context = {'object': ruleset, 'delfn': 'delete_ruleset' } return scirius_render(request, 'rules/delete.html', context)
def delete_threshold(request, threshold_id): threshold = get_object_or_404(Threshold, pk=threshold_id) ruleset = threshold.ruleset if not request.user.is_staff: context = { 'object': threshold, 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/delete.html', context) if request.method == 'POST': # If the form has been submitted... threshold.delete() return redirect(ruleset) else: context = {'object': threshold, 'delfn': 'delete_threshold' } return scirius_render(request, 'rules/delete.html', context)
def delete_threshold(request, threshold_id): threshold = get_object_or_404(Threshold, pk=threshold_id) ruleset = threshold.ruleset if not request.user.is_staff: context = {'object': threshold, 'error': 'Unsufficient permissions'} return scirius_render(request, 'rules/delete.html', context) if request.method == 'POST': # If the form has been submitted... threshold.delete() return redirect(ruleset) else: context = {'object': threshold, 'delfn': 'delete_threshold'} return scirius_render(request, 'rules/delete.html', context)
def delete_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: context = {"object": ruleset, "error": "Unsufficient permissions"} return scirius_render(request, "rules/delete.html", context) if request.method == "POST": # If the form has been submitted... ruleset.delete() return redirect("/rules/ruleset/") else: context = {"object": ruleset, "delfn": "delete_ruleset"} return scirius_render(request, "rules/delete.html", context)
def add_source(request): if not request.user.is_staff: return scirius_render(request, 'rules/add_source.html', {'error': 'Unsufficient permissions'}) if request.method == 'POST': # If the form has been submitted... form = AddSourceForm(request.POST, request.FILES) # A form bound to the POST data if form.is_valid(): # All validation rules pass try: src = Source.objects.create( name=form.cleaned_data['name'], uri=form.cleaned_data['uri'], authkey=form.cleaned_data['authkey'], method=form.cleaned_data['method'], created_date=timezone.now(), datatype=form.cleaned_data['datatype'], cert_verif=form.cleaned_data['cert_verif'], ) if src.method == 'local' and request.FILES.has_key('file'): try: src.handle_uploaded_file(request.FILES['file']) except Exception, error: src.delete() return scirius_render(request, 'rules/add_source.html', { 'form': form, 'error': error }) except IntegrityError, error: return scirius_render(request, 'rules/add_source.html', { 'form': form, 'error': error }) try: ruleset_list = form.cleaned_data['rulesets'] except: ruleset_list = [] rulesets = [ruleset.pk for ruleset in ruleset_list] ruleset_list = [ '"' + ruleset.name + '"' for ruleset in ruleset_list ] return scirius_render( request, 'rules/add_source.html', { 'source': src, 'update': True, 'rulesets': rulesets, 'ruleset_list': ruleset_list })
def changelog_source(request, source_id): source = get_object_or_404(Source, pk=source_id) supdate = SourceUpdate.objects.filter(source=source).order_by("-created_date") # get last for now if len(supdate) == 0: return scirius_render(request, "rules/source.html", {"source": source, "error": "No changelog"}) changelogs = SourceUpdateTable(supdate) tables.RequestConfig(request).configure(changelogs) diff = supdate[0].diff() build_source_diff(request, diff) return scirius_render( request, "rules/source.html", {"source": source, "diff": diff, "changelogs": changelogs, "src_update": supdate[0]}, )
def add_ruleset(request): if not request.user.is_staff: return scirius_render(request, 'rules/add_ruleset.html', { 'error': 'Unsufficient permissions' }) context = {} if request.method == 'POST': # If the form has been submitted... form = RulesetForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass # Process the data in form.cleaned_data # ... try: ruleset = form.create_ruleset() except IntegrityError, error: return scirius_render(request, 'rules/add_ruleset.html', { 'form': form, 'error': error }) return redirect(ruleset)
def loginview(request, target): if request.method == 'POST': form = LoginForm(request.POST) if not form.is_valid(): # All validation rules pass form = LoginForm() context = {'form': form, 'error': 'Invalid form'} return scirius_render(request, 'accounts/login.html', context) username = form.cleaned_data['username'] password = form.cleaned_data['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) try: sciriususer = SciriusUser.objects.get(user=user) except SciriusUser.DoesNotExist: sciriususer = SciriusUser.objects.create(user=user, timezone='UTC') if not form.cleaned_data['persistent']: request.session.set_expiry(0) logger = logging.getLogger('authentication') logger.info("Successful login for '%s' from '%s'", username, get_real_ip(request)) from rules.models import UserAction UserAction.create(action_type='login', user=user, force_insert=True) return redirect("/" + target) else: form = LoginForm() context = {'form': form, 'error': 'Disabled account'} logger = logging.getLogger('authentication') logger.error( "Invalid login attempt for disabled account '%s' from '%s'", username, get_real_ip(request)) return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form, 'error': 'Invalid login'} logger = logging.getLogger('authentication') logger.error("Invalid login attempt for '%s' from '%s'", username, get_real_ip(request)) return scirius_render(request, 'accounts/login.html', context) else: form = LoginForm() context = {'form': form} return scirius_render(request, 'accounts/login.html', context)
def copy_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: context = { 'object': ruleset, 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/copy_ruleset.html', context) if request.method == 'POST': # If the form has been submitted... form = RulesetCopyForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass copy = ruleset.copy(form.cleaned_data['name']) return redirect(copy) else: form = RulesetCopyForm() context = {'object': ruleset , 'form': form} return scirius_render(request, 'rules/copy_ruleset.html', context)
def ruleset(request, ruleset_id, mode = 'struct', error = None): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if mode == 'struct': categories_list = {} sources = ruleset.sources.all() for sourceatversion in sources: cats = CategoryTable(ruleset.categories.filter(source = sourceatversion.source)) tables.RequestConfig(request, paginate={"per_page": 15}).configure(cats) categories_list[sourceatversion.source.name] = cats rules = RuleTable(ruleset.suppressed_rules.all()) tables.RequestConfig(request).configure(rules) context = {'ruleset': ruleset, 'categories_list': categories_list, 'sources': sources, 'rules': rules, 'mode': mode} if error: context['error'] = error elif mode == 'display': rules = RuleTable(ruleset.generate()) tables.RequestConfig(request).configure(rules) context = {'ruleset': ruleset, 'rules': rules, 'mode': mode} if error: context['error'] = error elif mode == 'export': rules = ruleset.generate() file_content = "# Rules file for " + ruleset.name + " generated by Scirius at " + str(datetime.now()) + "\n" for rule in rules: file_content += rule.content response = HttpResponse(file_content, content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=scirius.rules' return response return scirius_render(request, 'rules/ruleset.html', context)
def ruleset(request, ruleset_id, mode = 'struct', error = None): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if mode == 'struct': categories_list = {} sources = ruleset.sources.all() for sourceatversion in sources: cats = CategoryTable(ruleset.categories.filter(source = sourceatversion.source)) tables.RequestConfig(request, paginate={"per_page": 15}).configure(cats) categories_list[sourceatversion.source.name] = cats rules = RuleTable(ruleset.suppressed_rules.all()) tables.RequestConfig(request).configure(rules) context = {'ruleset': ruleset, 'categories_list': categories_list, 'sources': sources, 'rules': rules, 'mode': mode} if error: context['error'] = error elif mode == 'display': rules = RuleTable(ruleset.generate()) tables.RequestConfig(request).configure(rules) context = {'ruleset': ruleset, 'rules': rules, 'mode': mode} if error: context['error'] = error elif mode == 'export': file_content = ruleset.to_buffer() response = HttpResponse(file_content, content_type="text/plain") response['Content-Disposition'] = 'attachment; filename=scirius.rules' return response return scirius_render(request, 'rules/ruleset.html', context)
def system_settings(request): if not request.user.is_staff: context = { 'error': 'Unsufficient permissions' } return scirius_render(request, 'rules/system_settings.html', context) if request.method == 'POST': form = SystemSettingsForm(request.POST, instance = get_system_settings()) context = { 'form': form } if not form.is_valid(): context['error'] = "Invalid form." return scirius_render(request, 'rules/system_settings.html', context) form.save() context['success'] = "All changes saved." return scirius_render(request, 'rules/system_settings.html', context) form = SystemSettingsForm(instance = get_system_settings()) context = { 'form': form } return scirius_render(request, 'rules/system_settings.html', context)
def probe_index(request, probe_id, error=None, error_heading=None): context = get_context(request) context['current_id'] = int(probe_id) try: probe = context['probes'].get(id=probe_id) except Probes.DoesNotExist: messages.error(request, 'The selected probe could not be loaded.') return redirect(index) context['probe'] = probe context['editProbeForm'] = ProbeForm(instance=probe) context['error'] = error context['error_heading'] = error_heading if probe.ruleset: supp_rules = list(probe.ruleset.suppressed_rules.all()) if len(supp_rules): suppressed = ",".join([str(x.sid) for x in supp_rules]) context['suppressed'] = suppressed if settings.USE_ELASTICSEARCH: context['rules'] = True complete_context(request, context) return scirius_render(request, 'probes/probe.html', context)
def ruleset(request, ruleset_id, mode="struct", error=None): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if mode == "struct": categories_list = {} sources = ruleset.sources.all() for sourceatversion in sources: cats = CategoryTable(ruleset.categories.filter(source=sourceatversion.source)) tables.RequestConfig(request, paginate={"per_page": 15}).configure(cats) categories_list[sourceatversion.source.name] = cats rules = RuleTable(ruleset.suppressed_rules.all()) tables.RequestConfig(request).configure(rules) context = { "ruleset": ruleset, "categories_list": categories_list, "sources": sources, "rules": rules, "mode": mode, } if error: context["error"] = error elif mode == "display": rules = RuleTable(ruleset.generate()) tables.RequestConfig(request).configure(rules) context = {"ruleset": ruleset, "rules": rules, "mode": mode} if error: context["error"] = error elif mode == "export": rules = ruleset.generate() file_content = "# Rules file for " + ruleset.name + " generated by Scirius at " + str(datetime.now()) + "\n" for rule in rules: file_content += rule.content response = HttpResponse(file_content, content_type="text/plain") response["Content-Disposition"] = "attachment; filename=scirius.rules" return response return scirius_render(request, "rules/ruleset.html", context)
def manageuser(request, user_id): user = get_object_or_404(User, pk=user_id) context = {'action': 'User actions', 'user': user} if not request.user.is_superuser: context['error'] = 'Unsufficient permissions' context['user'] = get_object_or_404(User, pk=request.user.pk) return scirius_render(request, 'accounts/user.html', context)
def copy_ruleset(request, ruleset_id): ruleset = get_object_or_404(Ruleset, pk=ruleset_id) if not request.user.is_staff: context = {"object": ruleset, "error": "Unsufficient permissions"} return scirius_render(request, "rules/copy_ruleset.html", context) if request.method == "POST": # If the form has been submitted... form = RulesetCopyForm(request.POST) # A form bound to the POST data if form.is_valid(): # All validation rules pass copy = ruleset.copy(form.cleaned_data["name"]) return redirect(copy) else: form = RulesetCopyForm() context = {"object": ruleset, "form": form} return scirius_render(request, "rules/copy_ruleset.html", context)
def system_settings(request): if not request.user.is_staff: context = {"error": "Unsufficient permissions"} return scirius_render(request, "rules/system_settings.html", context) if request.method == "POST": form = SystemSettingsForm(request.POST, instance=get_system_settings()) context = {"form": form} if not form.is_valid(): context["error"] = "Invalid form." return scirius_render(request, "rules/system_settings.html", context) form.save() context["success"] = "All changes saved." return scirius_render(request, "rules/system_settings.html", context) form = SystemSettingsForm(instance=get_system_settings()) context = {"form": form} return scirius_render(request, "rules/system_settings.html", context)