views.py 4.38 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111
import base64
import datetime
import json
import re
import sys

from django.conf import settings
from django.db import IntegrityError
from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.template.loader import render_to_string
from django.utils import translation
from django.utils.timezone import utc
from django.utils.translation import ugettext_lazy as _
from django.views.decorators.csrf import csrf_exempt
from django.views.decorators.http import require_POST

from celery.task.control import inspect
from tasks import *

from firewall.fw import *
from firewall.models import *
from one.tasks import SendMailTask

def reload_firewall(request):
    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()
        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
@require_POST
def firewall_api(request):
    try:
        data=json.loads(base64.b64decode(request.POST["data"]))
        command = request.POST["command"]
        if data["password"] != "bdmegintelrontottaanetet":
            raise Exception(_("Wrong password."))

        if command == "blacklist":
            obj, created = Blacklist.objects.get_or_create(ipv4=data["ip"])
            obj.reason=data["reason"]
            obj.snort_message=data["snort_message"]
            if created:
                try:
                    obj.host = models.Host.objects.get(ipv4=data["ip"])
                    user = obj.host.owner
                    lang = user.person_set.all()[0].language
                    translation.activate(lang)
                    msg = render_to_string('mails/notification-ban-now.txt',
                            { 'user': user,
                              'bl': obj,
                              'instance:': obj.host.instance_set.get(),
                              'url': settings.CLOUD_URL} )
                    SendMailTask.delay(to=obj.host.owner.email, subject='[IK Cloud] %s' % obj.host.instance_set.get().name, msg=msg, sender=u'cloud@ik.bme.hu')
                except (Host.DoesNotExist, ValidationError, IntegrityError, AttributeError):
                    pass
            print obj.modified_at + datetime.timedelta(minutes=5)
            print datetime.datetime.utcnow().replace(tzinfo=utc)
            if obj.type == 'tempwhite' and obj.modified_at + datetime.timedelta(minutes=1) < datetime.datetime.utcnow().replace(tzinfo=utc):
                obj.type = 'tempban'
            obj.save()
            return HttpResponse(unicode(_("OK")))

        if not (data["vlan"] == "vm-net" or data["vlan"] == "war"):
            raise Exception(_("Only vm-net and war can be used."))

        data["hostname"] = re.sub(r' ', '_', data["hostname"])

        if command == "create":
            data["owner"] = "opennebula"
            owner = auth.models.User.objects.get(username=data["owner"])
            host = models.Host(hostname=data["hostname"],
                    vlan=models.Vlan.objects.get(name=data["vlan"]),
                    mac=data["mac"], ipv4=data["ip"], owner=owner,
                    description=data["description"], pub_ipv4=models.
                        Vlan.objects.get(name=data["vlan"]).snat_ip,
                    shared_ip=True)
            host.full_clean()
            host.save()

            host.enable_net()

            for p in data["portforward"]:
                host.add_port(proto=p["proto"],
                        public=int(p["public_port"]),
                        private=int(p["private_port"]))

        elif command == "destroy":
            data["owner"] = "opennebula"
            print data["hostname"]
            owner = auth.models.User.objects.get(username=data["owner"])
            host = models.Host.objects.get(hostname=data["hostname"],
                    owner=owner)

            host.delete()
        else:
            raise Exception(_("Unknown command."))

    except (ValidationError, IntegrityError, AttributeError, Exception) as e:
        return HttpResponse(_("Something went wrong!\n%s\n") % e)
    except:
        return HttpResponse(_("Something went wrong!\n"))

    return HttpResponse(unicode(_("OK")))