Commit 9f8191f1 by Bach Dániel

firewall: rewrite blacklist api

Closes #359
parent 10d51ec8
...@@ -561,3 +561,5 @@ MAX_NODE_RAM = get_env_variable("MAX_NODE_RAM", 1024) ...@@ -561,3 +561,5 @@ MAX_NODE_RAM = get_env_variable("MAX_NODE_RAM", 1024)
CLIENT_DOWNLOAD_URL = get_env_variable('CLIENT_DOWNLOAD_URL', 'http://circlecloud.org/client/download/') CLIENT_DOWNLOAD_URL = get_env_variable('CLIENT_DOWNLOAD_URL', 'http://circlecloud.org/client/download/')
ADMIN_ENABLED = False ADMIN_ENABLED = False
BLACKLIST_PASSWORD = get_env_variable("BLACKLIST_PASSWORD", "")
...@@ -27,6 +27,7 @@ from django.shortcuts import redirect ...@@ -27,6 +27,7 @@ from django.shortcuts import redirect
from circle.settings.base import get_env_variable from circle.settings.base import get_env_variable
from dashboard.views import circle_login, HelpView from dashboard.views import circle_login, HelpView
from dashboard.forms import CirclePasswordResetForm, CircleSetPasswordForm from dashboard.forms import CirclePasswordResetForm, CircleSetPasswordForm
from firewall.views import add_blacklist_item
admin.autodiscover() admin.autodiscover()
...@@ -35,6 +36,7 @@ urlpatterns = patterns( ...@@ -35,6 +36,7 @@ urlpatterns = patterns(
url(r'^$', lambda x: redirect(reverse("dashboard.index"))), url(r'^$', lambda x: redirect(reverse("dashboard.index"))),
url(r'^network/', include('network.urls')), url(r'^network/', include('network.urls')),
url(r'^blacklist-add/', add_blacklist_item),
url(r'^dashboard/', include('dashboard.urls')), url(r'^dashboard/', include('dashboard.urls')),
# django/contrib/auth/urls.py (care when new version) # django/contrib/auth/urls.py (care when new version)
......
...@@ -15,69 +15,66 @@ ...@@ -15,69 +15,66 @@
# You should have received a copy of the GNU General Public License along # You should have received a copy of the GNU General Public License along
# with CIRCLE. If not, see <http://www.gnu.org/licenses/>. # with CIRCLE. If not, see <http://www.gnu.org/licenses/>.
import base64 from __future__ import absolute_import, unicode_literals
import datetime
import json
from django.core.exceptions import ValidationError from datetime import timedelta
from django.db import IntegrityError import logging
from netaddr import AddrFormatError, IPAddress
from django.core.exceptions import PermissionDenied
from django.http import HttpResponse from django.http import HttpResponse
from django.utils.timezone import utc from django.utils import timezone
from django.utils.translation import ugettext_lazy as _ from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST from django.views.decorators.http import require_POST
from .tasks.local_tasks import reloadtask
from .models import BlacklistItem, Host from .models import BlacklistItem, Host
from django.conf import settings
def reload_firewall(request): logger = logging.getLogger(__name__)
if request.user.is_authenticated():
if request.user.is_superuser:
html = (_("Dear %s, you've signed in as administrator!<br />"
"Reloading in 10 seconds...") % request.user.username)
reloadtask.delay()
reloadtask.delay('Vlan')
else:
html = (_("Dear %s, you've signed in!") % request.user.username)
else:
html = _("Dear anonymous, you've not signed in yet!")
return HttpResponse(html)
@csrf_exempt @csrf_exempt
@require_POST @require_POST
def firewall_api(request): def add_blacklist_item(request):
password = request.POST.get('password')
if (not settings.BLACKLIST_PASSWORD or
password != settings.BLACKLIST_PASSWORD):
logger.warning("Tried invalid password. Password: %s IP: %s",
password, request.META["REMOTE_ADDR"])
raise PermissionDenied()
try: try:
data = json.loads(base64.b64decode(request.POST["data"])) address = request.POST.get('address')
command = request.POST["command"] IPAddress(address, version=4)
if data["password"] != "bdmegintelrontottaanetet": except (AddrFormatError, TypeError) as e:
raise Exception(_("Wrong password.")) logger.warning("Invalid IP address: %s (%s)", address, str(e))
return HttpResponse(_("Invalid IP address."))
obj, created = BlacklistItem.objects.get_or_create(ipv4=address)
if created:
try:
obj.host = Host.objects.get(ipv4=address)
except Host.DoesNotExist:
pass
if command == "blacklist": now = timezone.now()
obj, created = BlacklistItem.objects.get_or_create(ipv4=data["ip"]) can_update = ((obj.whitelisted and now > obj.expires_at) or
obj.reason = data["reason"] not obj.whitelisted)
obj.snort_message = data["snort_message"]
if created:
try:
obj.host = Host.objects.get(ipv4=data["ip"])
except (Host.DoesNotExist, ValidationError,
IntegrityError, AttributeError):
pass
modified = obj.modified_at + datetime.timedelta(minutes=1) if created or can_update:
now = datetime.dateime.utcnow().replace(tzinfo=utc) obj.reason = request.POST.get('reason')
if obj.type == 'tempwhite' and modified < now: obj.snort_message = request.POST.get('snort_message')
obj.type = 'tempban' obj.whitelisted = False
if obj.type != 'whitelist': obj.expires_at = now + timedelta(weeks=1)
obj.save() obj.full_clean()
return HttpResponse(unicode(_("OK"))) obj.save()
else:
raise Exception(_("Unknown command."))
except (ValidationError, IntegrityError, AttributeError, Exception) as e: if created:
return HttpResponse(_("Something went wrong!\n%s\n") % e) logger.info("Successfully created blacklist item %s.", address)
except: elif can_update:
return HttpResponse(_("Something went wrong!\n")) logger.info("Successfully modified blacklist item %s.", address)
return HttpResponse(unicode(_("OK"))) return HttpResponse(unicode(_("OK")))
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment