Statistics
| Branch: | Tag: | Revision:

root / flowspec / views.py @ 370ce61c

History | View | Annotate | Download (21.7 kB)

1
# Create your views here.
2
import urllib2
3
import socket
4
import json
5
from django import forms
6
from django.views.decorators.csrf import csrf_exempt
7
from django.core import urlresolvers
8
from django.core import serializers
9
from django.contrib.auth.decorators import login_required
10
from django.contrib.auth import logout
11
from django.contrib.sites.models import Site
12
from django.contrib.auth.models import User
13
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
14
from django.shortcuts import get_object_or_404, render_to_response
15
from django.core.context_processors import request
16
from django.template.context import RequestContext
17
from django.template.loader import get_template, render_to_string
18
from django.core.urlresolvers import reverse
19
from django.contrib import messages
20
from flowspy.accounts.models import *
21
from ipaddr import *
22

    
23
from django.contrib.auth import authenticate, login
24

    
25
from django.forms.models import model_to_dict
26

    
27
from flowspy.flowspec.forms import * 
28
from flowspy.flowspec.models import *
29
from flowspy.peers.models import *
30

    
31
from registration.models import RegistrationProfile
32

    
33
from copy import deepcopy
34
from flowspy.utils.decorators import shib_required
35

    
36
from django.views.decorators.cache import never_cache
37
from django.conf import settings
38
from django.core.mail.message import EmailMessage
39
import datetime
40
import os
41

    
42
LOG_FILENAME = os.path.join(settings.LOG_FILE_LOCATION, 'celery_jobs.log')
43
#FORMAT = '%(asctime)s %(levelname)s: %(message)s'
44
#logging.basicConfig(format=FORMAT)
45
formatter = logging.Formatter('%(asctime)s %(levelname)s %(clientip)s %(user)s: %(message)s')
46

    
47
logger = logging.getLogger(__name__)
48
logger.setLevel(logging.DEBUG)
49
handler = logging.FileHandler(LOG_FILENAME)
50
handler.setFormatter(formatter)
51
logger.addHandler(handler)
52

    
53
@login_required
54
def user_routes(request):
55
    user_routes = Route.objects.filter(applier=request.user)
56
    return render_to_response('user_routes.html', {'routes': user_routes},
57
                              context_instance=RequestContext(request))
58

    
59
def welcome(request):
60
    return render_to_response('welcome.html', context_instance=RequestContext(request))
61

    
62
@login_required
63
@never_cache
64
def group_routes(request):
65
    group_routes = []
66
    try:
67
        peer = request.user.get_profile().peer
68
    except UserProfile.DoesNotExist:
69
        error = "User <strong>%s</strong> does not belong to any peer or organization. It is not possible to create new firewall rules.<br>Please contact Helpdesk to resolve this issue" % request.user.username
70
        return render_to_response('error.html', {'error': error})
71
    if peer:
72
       peer_members = UserProfile.objects.filter(peer=peer)
73
       users = [prof.user for prof in peer_members]
74
       group_routes = Route.objects.filter(applier__in=users)
75
       if request.user.is_superuser:
76
           group_routes = Route.objects.all()
77
       return render_to_response('user_routes.html', {'routes': group_routes},
78
                              context_instance=RequestContext(request))
79

    
80

    
81
@login_required
82
@never_cache
83
def add_route(request):
84
    applier = request.user.pk
85
    applier_peer_networks = request.user.get_profile().peer.networks.all()
86
    if not applier_peer_networks:
87
         messages.add_message(request, messages.WARNING,
88
                             "Insufficient rights on administrative networks. Cannot add rule. Contact your administrator")
89
         return HttpResponseRedirect(reverse("group-routes"))
90
    if request.method == "GET":
91
        form = RouteForm(initial={'applier': applier})
92
        if not request.user.is_superuser:
93
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
94
            form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
95
        return render_to_response('apply.html', {'form': form, 'applier': applier},
96
                                  context_instance=RequestContext(request))
97

    
98
    else:
99
        request_data = request.POST.copy()
100
        if request.user.is_superuser:
101
            request_data['issuperuser'] = request.user.username
102
        else:
103
            request_data['applier'] = applier
104
            try:
105
                del requset_data['issuperuser']
106
            except:
107
                pass
108
        form = RouteForm(request_data)
109
        if form.is_valid():
110
            route=form.save(commit=False)
111
            if not request.user.is_superuser:
112
                route.applier = request.user
113
            route.status = "PENDING"
114
            route.response = "Applying"
115
            route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
116
            route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
117
            route.save()
118
            form.save_m2m()
119
            route.commit_add()
120
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
121
            fqdn = Site.objects.get_current().domain
122
            admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
123
            mail_body = render_to_string("rule_action.txt",
124
                                             {"route": route, "address": requesters_address, "action": "creation", "url": admin_url})
125
            user_mail = "%s" %route.applier.email
126
            user_mail = user_mail.split(';')
127
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s creation request submitted by %s" %(route.name, route.applier.username),
128
                              mail_body, settings.SERVER_EMAIL, user_mail,
129
                              get_peer_techc_mails(route.applier))
130
            d = { 'clientip' : "%s"%requesters_address, 'user' : route.applier.username }
131
            logger.info(mail_body, extra=d)
132
            return HttpResponseRedirect(reverse("group-routes"))
133
        else:
134
            if not request.user.is_superuser:
135
                form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
136
                form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
137
            return render_to_response('apply.html', {'form': form, 'applier':applier},
138
                                      context_instance=RequestContext(request))
139

    
140
@login_required
141
@never_cache
142
def edit_route(request, route_slug):
143
    applier = request.user.pk
144
    applier_peer = request.user.get_profile().peer
145
    route_edit = get_object_or_404(Route, name=route_slug)
146
    route_edit_applier_peer = route_edit.applier.get_profile().peer
147
    if applier_peer != route_edit_applier_peer and (not request.user.is_superuser):
148
        messages.add_message(request, messages.WARNING,
149
                             "Insufficient rights to edit rule %s" %(route_slug))
150
        return HttpResponseRedirect(reverse("group-routes"))
151
#    if route_edit.status == "ADMININACTIVE" :
152
#        messages.add_message(request, messages.WARNING,
153
#                             "Administrator has disabled editing of rule %s" %(route_slug))
154
#        return HttpResponseRedirect(reverse("group-routes"))
155
#    if route_edit.status == "EXPIRED" :
156
#        messages.add_message(request, messages.WARNING,
157
#                             "Cannot edit the expired rule %s. Contact helpdesk to enable it" %(route_slug))
158
#        return HttpResponseRedirect(reverse("group-routes"))
159
    if route_edit.status == "PENDING" :
160
        messages.add_message(request, messages.WARNING,
161
                             "Cannot edit a pending rule: %s." %(route_slug))
162
        return HttpResponseRedirect(reverse("group-routes"))
163
    route_original = deepcopy(route_edit)
164
    if request.POST:
165
        request_data = request.POST.copy()
166
        if request.user.is_superuser:
167
            request_data['issuperuser'] = request.user.username
168
        else:
169
            request_data['applier'] = applier
170
            try:
171
                del request_data['issuperuser']
172
            except:
173
                pass
174
        form = RouteForm(request_data, instance = route_edit)
175
        critical_changed_values = ['source', 'destination', 'sourceport', 'destinationport', 'port', 'protocol', 'then']
176
        if form.is_valid():
177
            changed_data = form.changed_data
178
            route=form.save(commit=False)
179
            route.name = route_original.name
180
            route.status = route_original.status
181
            route.response = route_original.response
182
            if not request.user.is_superuser:
183
                route.applier = request.user
184
            if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
185
                route.status = "PENDING"
186
                route.response = "Applying"
187
                route.source = IPNetwork("%s/%s" %(IPNetwork(route.source).network.compressed, IPNetwork(route.source).prefixlen)).compressed
188
                route.destination = IPNetwork("%s/%s" %(IPNetwork(route.destination).network.compressed, IPNetwork(route.destination).prefixlen)).compressed
189
            route.save()
190
            if bool(set(changed_data) & set(critical_changed_values)) or (not route_original.status == 'ACTIVE'):
191
                form.save_m2m()
192
                route.commit_edit()
193
                requesters_address = request.META['HTTP_X_FORWARDED_FOR']
194
                fqdn = Site.objects.get_current().domain
195
                admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
196
                mail_body = render_to_string("rule_action.txt",
197
                                             {"route": route, "address": requesters_address, "action": "edit", "url": admin_url})
198
                user_mail = "%s" %route.applier.email
199
                user_mail = user_mail.split(';')
200
                send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s edit request submitted by %s" %(route.name, route.applier.username),
201
                              mail_body, settings.SERVER_EMAIL, user_mail,
202
                              get_peer_techc_mails(route.applier))
203
                d = { 'clientip' : requesters_address, 'user' : route.applier.username }
204
                logger.info(mail_body, extra=d)
205
            return HttpResponseRedirect(reverse("group-routes"))
206
        else:
207
            if not request.user.is_superuser:
208
                form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
209
                form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
210
            return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
211
                                      context_instance=RequestContext(request))
212
    else:
213
        if (not route_original.status == 'ACTIVE'):
214
            route_edit.expires = datetime.date.today() + datetime.timedelta(days = settings.EXPIRATION_DAYS_OFFSET)
215
        dictionary = model_to_dict(route_edit, fields=[], exclude=[])
216
        if request.user.is_superuser:
217
            dictionary['issuperuser'] = request.user.username
218
        else:
219
            try:
220
                del dictionary['issuperuser']
221
            except:
222
                pass
223
        form = RouteForm(dictionary)
224
        if not request.user.is_superuser:
225
            form.fields['then'] = forms.ModelMultipleChoiceField(queryset=ThenAction.objects.filter(action__in=settings.UI_USER_THEN_ACTIONS).order_by('action'), required=True)
226
            form.fields['protocol'] = forms.ModelMultipleChoiceField(queryset=MatchProtocol.objects.filter(protocol__in=settings.UI_USER_PROTOCOLS).order_by('protocol'), required=False)
227
        return render_to_response('apply.html', {'form': form, 'edit':True, 'applier': applier},
228
                                  context_instance=RequestContext(request))
229

    
230
@login_required
231
@never_cache
232
def delete_route(request, route_slug):
233
    if request.is_ajax():
234
        route = get_object_or_404(Route, name=route_slug)
235
        applier_peer = route.applier.get_profile().peer
236
        requester_peer = request.user.get_profile().peer
237
        if applier_peer == requester_peer or request.user.is_superuser:
238
            route.status = "PENDING"
239
            route.expires = datetime.date.today()
240
            if not request.user.is_superuser:
241
                route.applier = request.user
242
            route.response = "Suspending"
243
            route.save()
244
            route.commit_delete()
245
            requesters_address = request.META['HTTP_X_FORWARDED_FOR']
246
            fqdn = Site.objects.get_current().domain
247
            admin_url = "https://%s%s" % (fqdn, "/fod/edit/%s"%route.name)
248
            mail_body = render_to_string("rule_action.txt",
249
                                             {"route": route, "address": requesters_address, "action": "removal", "url": admin_url})
250
            user_mail = "%s" %route.applier.email
251
            user_mail = user_mail.split(';')
252
            send_new_mail(settings.EMAIL_SUBJECT_PREFIX + "Rule %s removal request submitted by %s" %(route.name, route.applier.username), 
253
                              mail_body, settings.SERVER_EMAIL, user_mail,
254
                             get_peer_techc_mails(route.applier))
255
            d = { 'clientip' : requesters_address, 'user' : route.applier.username }
256
            logger.info(mail_body, extra=d)
257
        html = "<html><body>Done</body></html>"
258
        return HttpResponse(html)
259
    else:
260
        return HttpResponseRedirect(reverse("group-routes"))
261

    
262
@login_required
263
@never_cache
264
def user_profile(request):
265
    user = request.user
266
    try:
267
        peer = request.user.get_profile().peer
268
        peers = Peer.objects.filter(pk=peer.pk)
269
        if user.is_superuser:
270
            peers = Peer.objects.all()
271
    except UserProfile.DoesNotExist:
272
        error = "User <strong>%s</strong> does not belong to any peer or organization. It is not possible to create new firewall rules.<br>Please contact Helpdesk to resolve this issue" % user.username
273
        return render_to_response('error.html', {'error': error})
274
    return render_to_response('profile.html', {'user': user, 'peers':peers},
275
                                  context_instance=RequestContext(request))
276

    
277
@never_cache
278
def user_login(request):
279
    try:
280
        error_username = False
281
        error_orgname = False
282
        error_entitlement = False
283
        error_mail = False
284
        has_entitlement = False
285
        error = ''
286
        username = request.META['HTTP_EPPN']
287
        if not username:
288
            error_username = True
289
        firstname = request.META['HTTP_SHIB_INETORGPERSON_GIVENNAME']
290
        lastname = request.META['HTTP_SHIB_PERSON_SURNAME']
291
        mail = request.META['HTTP_SHIB_INETORGPERSON_MAIL']
292
        organization = request.META['HTTP_SHIB_HOMEORGANIZATION']
293
        entitlement = request.META['HTTP_SHIB_EP_ENTITLEMENT']
294
        if settings.SHIB_AUTH_ENTITLEMENT in entitlement.split(";"):
295
            has_entitlement = True
296
        if not has_entitlement:
297
            error_entitlement = True
298
        if not organization:
299
            error_orgname = True
300
        if not mail:
301
            error_mail = True
302
        if error_username:
303
            error = "Your idP should release the HTTP_EPPN attribute towards this service<br>"
304
        if error_orgname:
305
            error = error + "Your idP should release the HTTP_SHIB_HOMEORGANIZATION attribute towards this service<br>"
306
        if error_entitlement:
307
            error = error + "Your idP should release an appropriate HTTP_SHIB_EP_ENTITLEMENT attribute towards this service<br>"
308
        if error_mail:
309
            error = error + "Your idP should release the HTTP_SHIB_INETORGPERSON_MAIL attribute towards this service"
310
        if error_username or error_orgname or error_entitlement or error_mail:
311
            return render_to_response('error.html', {'error': error, "missing_attributes": True},
312
                                  context_instance=RequestContext(request))
313
        try:
314
            user = User.objects.get(username__exact=username)
315
            user.email = mail
316
            user.first_name = firstname
317
            user.last_name = lastname
318
            user.save()
319
            user_exists = True
320
        except:
321
            user_exists = False
322
        user = authenticate(username=username, firstname=firstname, lastname=lastname, mail=mail, authsource='shibboleth')
323
        if user is not None:
324
            try:
325
                peer = Peer.objects.get(domain_name=organization)
326
                up = UserProfile.objects.get_or_create(user=user,peer=peer)
327
            except:
328
                error = "Your organization's domain name does not match our peers' domain names<br>Please contact Helpdesk to resolve this issue"
329
                return render_to_response('error.html', {'error': error})
330
            if not user_exists:
331
                user_activation_notify(user)
332
            if user.is_active:
333
               login(request, user)
334
               return HttpResponseRedirect(reverse("group-routes"))
335
            else:
336
                error = "User account <strong>%s</strong> is pending activation. Administrators have been notified and will activate this account within the next days. <br>If this account has remained inactive for a long time contact your technical coordinator or GRNET Helpdesk" %user.username
337
                return render_to_response('error.html', {'error': error, 'inactive': True},
338
                                  context_instance=RequestContext(request))
339
        else:
340
            error = "Something went wrong during user authentication. Contact your administrator"
341
            return render_to_response('error.html', {'error': error,},
342
                                  context_instance=RequestContext(request))
343
    except Exception:
344
        error = "Invalid login procedure"
345
        return render_to_response('error.html', {'error': error,},
346
                                  context_instance=RequestContext(request))
347
        # Return an 'invalid login' error message.
348
#    return HttpResponseRedirect(reverse("user-routes"))
349

    
350
def user_activation_notify(user):
351
    current_site = Site.objects.get_current()
352
    subject = render_to_string('registration/activation_email_subject.txt',
353
                                   { 'site': current_site })
354
    # Email subject *must not* contain newlines
355
    subject = ''.join(subject.splitlines())
356
    registration_profile = RegistrationProfile.objects.create_profile(user)
357
    message = render_to_string('registration/activation_email.txt',
358
                                   { 'activation_key': registration_profile.activation_key,
359
                                     'expiration_days': settings.ACCOUNT_ACTIVATION_DAYS,
360
                                     'site': current_site,
361
                                     'user': user })
362
    send_new_mail(settings.EMAIL_SUBJECT_PREFIX + subject, 
363
                              message, settings.SERVER_EMAIL,
364
                             get_peer_techc_mails(user), [])
365

    
366
@login_required
367
@never_cache
368
def add_rate_limit(request):
369
    if request.method == "GET":
370
        form = ThenPlainForm()
371
        return render_to_response('add_rate_limit.html', {'form': form,},
372
                                  context_instance=RequestContext(request))
373

    
374
    else:
375
        form = ThenPlainForm(request.POST)
376
        if form.is_valid():
377
            then=form.save(commit=False)
378
            then.action_value = "%sk"%then.action_value
379
            then.save()
380
            response_data = {}
381
            response_data['pk'] = "%s" %then.pk
382
            response_data['value'] = "%s:%s" %(then.action, then.action_value)
383
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
384
        else:
385
            return render_to_response('add_rate_limit.html', {'form': form,},
386
                                      context_instance=RequestContext(request))
387

    
388
@login_required
389
@never_cache
390
def add_port(request):
391
    if request.method == "GET":
392
        form = PortPlainForm()
393
        return render_to_response('add_port.html', {'form': form,},
394
                                  context_instance=RequestContext(request))
395

    
396
    else:
397
        form = PortPlainForm(request.POST)
398
        if form.is_valid():
399
            port=form.save()
400
            response_data = {}
401
            response_data['value'] = "%s" %port.pk
402
            response_data['text'] = "%s" %port.port
403
            return HttpResponse(json.dumps(response_data), mimetype='application/json')
404
        else:
405
            return render_to_response('add_port.html', {'form': form,},
406
                                      context_instance=RequestContext(request))
407

    
408
@login_required
409
@never_cache
410
def user_logout(request):
411
    logout(request)
412
    return HttpResponseRedirect(reverse('group-routes'))
413
    
414
@never_cache
415
def load_jscript(request, file):
416
    long_polling_timeout = int(settings.POLL_SESSION_UPDATE)*1000 + 10000
417
    return render_to_response('%s.js' % file, {'timeout': long_polling_timeout}, context_instance=RequestContext(request), mimetype="text/javascript")
418

    
419

    
420
def get_peer_techc_mails(user):
421
    mail = []
422
    additional_mail = []
423
    techmails_list = []
424
    user_mail = "%s" %user.email
425
    user_mail = user_mail.split(';')
426
    techmails = user.get_profile().peer.techc_emails.all()
427
    if techmails:
428
        for techmail in techmails:
429
            techmails_list.append(techmail.email)
430
    if settings.NOTIFY_ADMIN_MAILS:
431
        additional_mail = settings.NOTIFY_ADMIN_MAILS
432
#    mail.extend(user_mail)
433
    mail.extend(additional_mail)
434
    mail.extend(techmails_list)
435
    return mail
436

    
437

    
438
def send_new_mail(subject, message, from_email, recipient_list, bcc_list):
439
    return EmailMessage(subject, message, from_email, recipient_list, bcc_list).send()
440