Source

hbwebui / hbwebui / views.py

Full commit
  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
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
from django.http import HttpResponse
from django.template import Context, RequestContext, loader

from django.contrib.auth.decorators import login_required
from django.dispatch import receiver
from django.contrib.auth.signals import user_logged_in

from django.db import connections
from django.core import serializers
import json, csv, calendar
from django.contrib import auth
from models import Ident, IdentToGroupMapping

from decorators import login_required_simple, ident_required, ident_required_simple
import util

import queries

login_url = '/hbwebui/login'

@login_required(login_url=login_url)
@ident_required
def dashboard(request):
    idents = request.session['idents']
    
    t = loader.get_template('dashboard.html')
    c = RequestContext(request, {
            'page': 'dashboard',
            'idents': json.dumps(idents),
    })
    return HttpResponse(t.render(c))

@login_required(login_url=login_url)
@ident_required
def stats_binaries(request):
    idents = request.session['idents']
    
    q = queries.Stats_Binaries()
    q.filter_ident(idents)
    q.order_n_count(desc=True)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = []
    for d in qr:
        o = {}
        o['md5'] = d['md5']
        o['n_count'] = d['n_count']
        o['n_ident'] = d['n_ident']
        o['n_source_ip'] = d['n_source_ip']
        o['n_target_port'] = d['n_target_port']
        o['ts_last'] = calendar.timegm(d['ts_last'].utctimetuple())
        o['ts_first'] = calendar.timegm(d['ts_first'].utctimetuple())
        r.append(o)
    
    t = loader.get_template('stats_binaries.html')
    c = RequestContext(request, {
            'page': 'stats_binaries',
            'idents': json.dumps(idents),
            'r': json.dumps(r)
    })
    return HttpResponse(t.render(c))

@login_required_simple
@ident_required_simple
def r_stats_binaries(request):
    idents = request.session['idents']
    
    q = queries.Stats_Binaries()
    q.filter_ident(idents)
    q.order_n_count(desc=True)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = []
    for d in qr:
        o = {}
        o['md5'] = d['md5']
        o['n_count'] = d['n_count']
        o['n_ident'] = d['n_ident']
        o['n_source_ip'] = d['n_source_ip']
        o['n_target_port'] = d['n_target_port']
        o['ts_last'] = calendar.timegm(d['ts_last'].utctimetuple())
        o['ts_first'] = calendar.timegm(d['ts_first'].utctimetuple())
        r.append(o)
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required_simple
@ident_required_simple
def r_stats_binaries_summary(request):
    idents = request.session['idents']
    
    q = queries.Stats_Binaries_Summary()
    q.filter_ident(idents)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = {}
    r['n_count'] = qr[0]['n_count']
    r['n_ident'] = qr[0]['n_ident']
    r['n_source_ip'] = qr[0]['n_source_ip']
    r['n_target_port'] = qr[0]['n_target_port']
    r['ts_last'] = calendar.timegm(qr[0]['ts_last'].utctimetuple())
    r['ts_first'] = calendar.timegm(qr[0]['ts_first'].utctimetuple())
    r['n_total'] = qr[0]['n_total']
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required(login_url=login_url)
@ident_required
def stats_source_ips(request):
    idents = request.session['idents']
        
    t = loader.get_template('stats_source_ips.html')
    c = RequestContext(request, {
            'page': 'stats_source_ips',
            'idents': json.dumps(idents),
    })
    return HttpResponse(t.render(c))

@login_required_simple
@ident_required_simple
def r_stats_source_ips(request):
    idents = request.session['idents']
    
    q = queries.Stats_Source_IPs()
    q.filter_ident(idents)
    q.order_n_count(desc=True)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = []
    for d in qr:
        o = {}
        o['source_ip'] = d['source_ip']
        o['cc'] = d['cc']
        o['asn'] = d['asn']
        o['n_count'] = d['n_count']
        o['n_ident'] = d['n_ident']
        o['n_binary'] = d['n_binary']
        o['n_target_port'] = d['n_target_port']
        o['ts_last'] = calendar.timegm(d['ts_last'].utctimetuple())
        o['ts_first'] = calendar.timegm(d['ts_first'].utctimetuple())
        r.append(o)
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required_simple
@ident_required_simple
def r_stats_source_ips_summary(request):
    idents = request.session['idents']
    
    q = queries.Stats_Source_IPs_Summary()
    q.filter_ident(idents)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = {}
    r['n_count'] = qr[0]['n_count']
    r['n_cc'] = qr[0]['n_cc']
    r['n_asn'] = qr[0]['n_asn']
    r['n_ident'] = qr[0]['n_ident']
    r['n_binary'] = qr[0]['n_binary']
    r['n_target_port'] = qr[0]['n_target_port']
    r['ts_last'] = calendar.timegm(qr[0]['ts_last'].utctimetuple())
    r['ts_first'] = calendar.timegm(qr[0]['ts_first'].utctimetuple())
    r['n_total'] = qr[0]['n_total']
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required(login_url=login_url)
@ident_required
def stats_asns(request):
    idents = request.session['idents']
        
    t = loader.get_template('stats_asns.html')
    c = RequestContext(request, {
            'page': 'stats_asns',
            'idents': json.dumps(idents),
    })
    return HttpResponse(t.render(c))

@login_required_simple
@ident_required_simple
def r_stats_asns(request):
    idents = request.session['idents']
    
    q = queries.Stats_ASNs()
    q.filter_ident(idents)
    q.order_n_count(desc=True)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = []
    for d in qr:
        o = {}
        o['as_name'] = d['as_name']
        o['asn'] = d['asn']
        o['cc'] = d['cc']
        o['n_count'] = d['n_count']
        o['n_ident'] = d['n_ident']
        o['n_binary'] = d['n_binary']
        o['n_source_ip'] = d['n_source_ip']
        o['n_target_port'] = d['n_target_port']
        o['ts_last'] = calendar.timegm(d['ts_last'].utctimetuple())
        o['ts_first'] = calendar.timegm(d['ts_first'].utctimetuple())
        r.append(o)
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required_simple
@ident_required_simple
def r_stats_asns_summary(request):
    idents = request.session['idents']
    
    q = queries.Stats_ASNs_Summary()
    q.filter_ident(idents)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = {}
    r['n_count'] = qr[0]['n_count']
    r['n_cc'] = qr[0]['n_cc']
    r['n_source_ip'] = qr[0]['n_source_ip']
    r['n_ident'] = qr[0]['n_ident']
    r['n_binary'] = qr[0]['n_binary']
    r['n_target_port'] = qr[0]['n_target_port']
    r['ts_last'] = calendar.timegm(qr[0]['ts_last'].utctimetuple())
    r['ts_first'] = calendar.timegm(qr[0]['ts_first'].utctimetuple())
    r['n_total'] = qr[0]['n_total']
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required(login_url=login_url)
@ident_required
def stats_countries(request):
    idents = request.session['idents']
        
    t = loader.get_template('stats_countries.html')
    c = RequestContext(request, {
            'page': 'stats_countries',
            'idents': json.dumps(idents),
    })
    return HttpResponse(t.render(c))

@login_required_simple
@ident_required_simple
def r_stats_countries(request):
    idents = request.session['idents']
    
    q = queries.Stats_Countries()
    q.filter_ident(idents)
    q.order_n_count(desc=True)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = []
    for d in qr:
        o = {}
        o['cc'] = d['cc']
        o['n_count'] = d['n_count']
        o['n_ident'] = d['n_ident']
        o['n_binary'] = d['n_binary']
        o['n_asn'] = d['n_asn']
        o['n_source_ip'] = d['n_source_ip']
        o['n_target_port'] = d['n_target_port']
        o['ts_last'] = calendar.timegm(d['ts_last'].utctimetuple())
        o['ts_first'] = calendar.timegm(d['ts_first'].utctimetuple())
        r.append(o)
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

@login_required_simple
@ident_required_simple
def r_stats_countries_summary(request):
    idents = request.session['idents']
    
    q = queries.Stats_Countries_Summary()
    q.filter_ident(idents)
    cursor = q.execute()
    qr = util.dictfetchall(cursor)
    
    r = {}
    r['n_count'] = qr[0]['n_count']
    r['n_asn'] = qr[0]['n_asn']
    r['n_source_ip'] = qr[0]['n_source_ip']
    r['n_ident'] = qr[0]['n_ident']
    r['n_binary'] = qr[0]['n_binary']
    r['n_target_port'] = qr[0]['n_target_port']
    r['ts_last'] = calendar.timegm(qr[0]['ts_last'].utctimetuple())
    r['ts_first'] = calendar.timegm(qr[0]['ts_first'].utctimetuple())
    r['n_total'] = qr[0]['n_total']
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

# example
@login_required_simple
@ident_required_simple
def myidents(request):
    idents = request.session['idents']
    
    response = HttpResponse(mimetype='application/json')
    json.dump(idents, response)
        
    return response

#example
@login_required_simple
@ident_required_simple
def sensoractivity(request, hours):
    idents = request.session['idents']
    
    cursor = connections['hbstats'].cursor()
    cursor.execute(
         """WITH tr AS
            (SELECT max(ts_min) AS tr_from, max(ts_min) - interval '%s hour' AS tr_until from ts_main_min)
            
            SELECT
                ident, sum(t.n_count)::bigint AS n_count,
                max(ts_min) as ts_last, min(ts_min) as ts_first,
                now()
            FROM
                (SELECT
                     ts_min, agg_id, n_count
                 FROM ts_main_min
                 WHERE
                     ts_min <= (SELECT tr_from FROM tr) AND ts_min > (SELECT tr_until FROM tr) AND
                     agg_id IN (SELECT agg_id from agg_main WHERE ident_id IN (SELECT id FROM dim_ident WHERE ident IN %s))
                ) as t
            JOIN
                agg_main ON t.agg_id = agg_main.agg_id
            JOIN
                dim_ident ON ident_id = dim_ident.id
                
            GROUP BY ident ORDER BY ident, n_count desc""",
            [hours, tuple(idents)]
    )
    qr = util.dictfetchall(cursor)
    r = []
    for d in qr:
        o = {}
        o['ident'] = d['ident']
        o['n_count'] = d['n_count']
        o['ts_last'] = d['ts_last'].isoformat()
        o['ts_first'] = d['ts_first'].isoformat()
        r.append(o)
    
    response = HttpResponse(mimetype='application/json')
    json.dump(r, response)
    
    return response

# example
@login_required_simple
@ident_required_simple
def ts_sensoractivity_x(request, hours):
    idents = request.session['idents']
    
    cursor = connections['hbstats'].cursor()
    cursor.execute(
        """WITH tr AS
            (SELECT max(ts_min) AS tr_from, max(ts_min) - interval '%s hour' AS tr_until from ts_main_min)
            
            SELECT
                extract(epoch from ts_min)::bigint AS ts_min,
                ident, md5, source_ip,
                sum(t.n_count) AS n_count       
            FROM
                (SELECT
                     ts_min, agg_id, n_count
                 FROM ts_main_min
                 WHERE
                     ts_min <= (SELECT tr_from FROM tr) AND ts_min > (SELECT tr_until FROM tr) AND
                     agg_id IN (SELECT agg_id from agg_main WHERE ident_id IN (SELECT id FROM dim_ident WHERE ident IN %s))
                ) as t
            JOIN
                agg_main ON t.agg_id = agg_main.agg_id
            JOIN
                dim_ident ON ident_id = dim_ident.id
            JOIN
                dim_binary ON binary_id = dim_binary.id
                
            GROUP BY ts_min, ident, md5, source_ip ORDER BY ts_min""",
            [hours, tuple(idents)]
    )
    
    response = HttpResponse(mimetype='text/plain')
    
    csvwriter = csv.writer(response)
    csvwriter.writerow(['ts_min', 'ident', 'md5', 'source_ip', 'n_count'])
    
    while True:
        rows = cursor.fetchmany()
        if not rows: break
        for row in rows:
            csvwriter.writerow([row[0], row[1], row[2], row[3], row[4]])
    
    return HttpResponse(response);


@receiver(user_logged_in)
def session_set_idents(sender, **kwargs):
    request = kwargs['request']
    idents = util.get_idents(request.user)
    if idents:
        request.session['idents'] = idents