views.py 21.2 KB
Newer Older
1
# Create your views here.
2
3
import urllib2
import socket
4
import json
5
6
from django import forms
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
12
from django.contrib.sites.models import Site
from django.contrib.auth.models import User
13
14
15
16
from django.http import HttpResponseRedirect, HttpResponseForbidden, HttpResponse
from django.shortcuts import get_object_or_404, render_to_response
from django.core.context_processors import request
from django.template.context import RequestContext
17
from django.template.loader import get_template, render_to_string
18
19
from django.core.urlresolvers import reverse
from django.contrib import messages
20
from flowspy.accounts.models import *
21
from ipaddr import *
22

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

25
26
from django.forms.models import model_to_dict

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

31
from registration.models import RegistrationProfile
32

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

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

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

logger = logging.getLogger(__name__)
logger.setLevel(logging.DEBUG)
handler = logging.FileHandler(LOG_FILENAME)
handler.setFormatter(formatter)
logger.addHandler(handler)

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

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

62
@login_required
63
@never_cache
64
def group_routes(request):
65
    group_routes = []
66
67
68
69
70
    try:
        peer = request.user.get_profile().peer
    except UserProfile.DoesNotExist:
        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
        return render_to_response('error.html', {'error': error})
71
72
73
74
    if peer:
       peer_members = UserProfile.objects.filter(peer=peer)
       users = [prof.user for prof in peer_members]
       group_routes = Route.objects.filter(applier__in=users)
75
76
       if request.user.is_superuser:
           group_routes = Route.objects.all()
77
       return render_to_response('user_routes.html', {'routes': group_routes},
78
79
80
                              context_instance=RequestContext(request))


81
@login_required
82
@never_cache
83
def add_route(request):
84
    applier = request.user.pk
85
86
87
    applier_peer_networks = request.user.get_profile().peer.networks.all()
    if not applier_peer_networks:
         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
93
        if not request.user.is_superuser:
            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
97
98
                                  context_instance=RequestContext(request))

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

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

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

@login_required
257
@never_cache
258
259
def user_profile(request):
    user = request.user
260
261
    try:
        peer = request.user.get_profile().peer
262
263
264
        peers = Peer.objects.filter(pk=peer.pk)
        if user.is_superuser:
            peers = Peer.objects.all()
265
266
267
    except UserProfile.DoesNotExist:
        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
        return render_to_response('error.html', {'error': error})
268
    return render_to_response('profile.html', {'user': user, 'peers':peers},
269
270
                                  context_instance=RequestContext(request))

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

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

360
@login_required
361
@never_cache
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
def add_rate_limit(request):
    if request.method == "GET":
        form = ThenPlainForm()
        return render_to_response('add_rate_limit.html', {'form': form,},
                                  context_instance=RequestContext(request))

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

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

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

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


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


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