1. György Kohut
  2. hbwebui

Source

hbwebui / hbwebui / queries.py

  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
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
from django.db import connections

class QueryBase(object):
    def __init__(self):
        self.parts_map = {}
        self.parts_list = []
        self.cursor = None
    
    def part_init(self, part):
        self.parts_map[part] = []
        self.parts_map[part].append(set()) # [0]: set of subpart names, to filter duplicates, trigger insertion
        self.parts_map[part].append('') # [1]: query fragment text
        self.parts_map[part].append([]) # [2]: query params
        self.parts_list.append(part)
    
    def part_append(self, part, subpart, sep, text, params):
        if subpart in self.parts_map[part][0]: # filter duplicate subparts
            return False
        else:
            if len(self.parts_map[part][0]):
                self.parts_map[part][1] += sep + text
            else:
                self.parts_map[part][1] += text
            self.parts_map[part][2].extend(params)
            self.parts_map[part][0].add(subpart)
            return True
    
    def part_append2(self, part, text):
        self.parts_map[part][1] += text
    
    def part_init2(self, part, text):
        self.part_init(part)
        self.part_append2(part, text)
        
    def where_init(self):
        self.part_init2('where_clause', 'WHERE ')
    
    def order_by_init(self):
        self.part_init2('order_by_clause', 'ORDER BY ')
    
    def with_init(self):
        self.part_init2('with_clause', 'WITH ')
        self.part_init2('with_tables', ', ')
    
    def limit_init(self):
        self.part_init2('limit_clause', 'LIMIT ')
    
    def offset_init(self):
        self.part_init2('offset_clause', 'OFFSET ')
    
    def where_append(self, subpart, text, params):
        return self.part_append('where_clause', subpart, ' AND ', text, params)
    
    def order_by_append(self, subpart, text, desc=False):
        return self.part_append('order_by_clause', subpart, ', ', text + (' DESC' if desc else ''), [])
    
    def with_append(self, subpart, query, table, params):
        b = self.part_append('with_clause', subpart, ', ', query, params)
        if b:
            self.part_append('with_tables', subpart, ', ', table, [])
            return True
        else:
            return False
    
    def limit(self, limit):
        return self.part_append('limit_clause', 'limit_clause', '', '%s', [limit])
    
    def offset(self, offset):
        return self.part_append('offset_clause', 'offset_clause', '', '%s', [offset])
    
    def build(self):
        query = ''
        params = []
        format_params = {}
        
        for part in self.parts_list:
            if len(self.parts_map[part][0]): # got subparts
                format_params[part] = self.parts_map[part][1]
                params.extend(self.parts_map[part][2])
            else:
                format_params[part] = ''
        
        query = self.tpl % format_params
        return [query, params]
    
    def execute(self):
        self.cursor = connections[self.db].cursor()
        query, params = self.build()
        
        self.cursor.execute(query, params)
        return self.cursor


class Stats_Binaries(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                md5, sum(agg_main.n_count)::bigint as n_count,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT source_ip) AS n_source_ip,
                count(DISTINCT asn) AS n_asn, count(DISTINCT cc) AS n_cc,
                count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            JOIN
                dim_binary ON agg_main.binary_id = dim_binary.id
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY md5
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Binaries, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
        
    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])
        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_Binaries_Summary(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                count(DISTINCT binary_id) as n_count,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT source_ip) AS n_source_ip,
                count(DISTINCT asn) AS n_asn, count(DISTINCT cc) AS n_cc,
                count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first,
                sum(n_count)::bigint as n_total
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s"""
    
    def __init__(self):
        super(Stats_Binaries_Summary, self).__init__()
        self.where_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
        


class Stats_Source_IPs(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                source_ip, sum(agg_main.n_count)::bigint as n_count,
                cc, asn, as_name,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY source_ip, cc, asn, as_name
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Source_IPs, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
        
    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])
        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_Source_IPs_Summary(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                count(DISTINCT source_ip) as n_count,
                count(DISTINCT cc) as n_cc, count(DISTINCT asn) as n_asn,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first,
                sum(n_count)::bigint as n_total
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s"""
    
    def __init__(self):
        super(Stats_Source_IPs_Summary, self).__init__()
        self.where_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])


class Stats_ASNs(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                as_name, asn, cc,
                sum(agg_main.n_count)::bigint as n_count,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT source_ip) AS n_source_ip, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY as_name, asn, cc
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_ASNs, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])

    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])
        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_ASNs_Summary(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                count(DISTINCT asn) as n_count,
                count(DISTINCT cc) as n_cc, count(DISTINCT source_ip) as n_source_ip,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first,
                sum(n_count)::bigint as n_total
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s"""
    
    def __init__(self):
        super(Stats_ASNs_Summary, self).__init__()
        self.where_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])


class Stats_Countries(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                cc,
                sum(agg_main.n_count)::bigint as n_count,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT source_ip) AS n_source_ip, count(DISTINCT asn) AS n_asn, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY cc
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Countries, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
    
    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])
        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_Countries_Summary(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                count(DISTINCT cc) as n_count,
                count(DISTINCT asn) as n_asn, count(DISTINCT source_ip) as n_source_ip,
                count(DISTINCT ident_id) AS n_ident, count(DISTINCT binary_id) AS n_binary, count(DISTINCT target_port) AS n_target_port,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first,
                sum(n_count)::bigint as n_total
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s"""
    
    def __init__(self):
        super(Stats_Countries_Summary, self).__init__()
        self.where_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])


class Stats_Idents(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                ident,
                sum(agg_main.n_count)::bigint as n_count,
                count(DISTINCT binary_id) AS n_binary, count(DISTINCT source_ip) AS n_source_ip, count(DISTINCT target_port) AS n_target_port,
                count(DISTINCT asn) as n_asn, count(DISTINCT cc) as n_cc,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            JOIN
                dim_ident ON agg_main.ident_id = dim_ident.id
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY ident
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Idents, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
    
    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])

        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_Idents_Summary(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                count(DISTINCT ident_id) as n_count,
                count(DISTINCT binary_id) AS n_binary, count(DISTINCT source_ip) as n_source_ip,
                count(DISTINCT asn) as n_asn, count(DISTINCT cc) as n_cc,
                count(DISTINCT target_port) AS n_target_port, 
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first,
                sum(n_count)::bigint as n_total
            FROM
                agg_main
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s"""
    
    def __init__(self):
        super(Stats_Idents_Summary, self).__init__()
        self.where_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])


class Stats_Target_Ports(QueryBase):
    db = 'hbstats'
    tpl = \
        """SELECT
                target_port,
                sum(agg_main.n_count)::bigint as n_count,
                count(DISTINCT ident_id) as n_ident, count(DISTINCT binary_id) AS n_binary,
                count(DISTINCT source_ip) AS n_source_ip, count(DISTINCT asn) as n_asn, count(DISTINCT cc) as n_cc,
                max(agg_main.ts_last) as ts_last, min(agg_main.ts_first) as ts_first
            FROM
                agg_main
            JOIN
                dim_ident ON agg_main.ident_id = dim_ident.id
            LEFT JOIN
                att_asn_shadowserver ON agg_main.source_ip = att_asn_shadowserver.ip
            %(where_clause)s
            GROUP BY target_port
            %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Target_Ports, self).__init__()
        self.where_init()
        self.order_by_init()
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
    
    def filter_md5(self, md5s):
        self.where_append('filter_md5', 'binary_id IN (SELECT id from dim_binary WHERE md5 IN %s)', [tuple(md5s)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def filter_asn(self, asns):
        self.where_append('filter_asn', 'asn IN %s', [tuple(asns)])
    
    def filter_cc(self, ccs):
        self.where_append('filter_cc', 'cc IN %s', [tuple(ccs)])

        
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)


class Stats_Binaries_TimeRange(QueryBase):
    db = 'hbstats'
    tpl = \
        """%(with_clause)s
        
        SELECT
            md5, sum(t.n_count)::bigint as n_count,
            count(DISTINCT ident_id) AS n_ident, count(DISTINCT source_ip) AS n_source_ip, count(DISTINCT target_port) AS n_target_port,
            max(t.ts_last) AS ts_last, min(t.ts_first) AS ts_first
        FROM
            (SELECT
                agg_id, sum(n_count) as n_count, max(ts_min) as ts_last, min(ts_min) as ts_first
                FROM ts_main_min
                WHERE agg_id IN (SELECT agg_id FROM agg_main %(where_clause)s)
                GROUP BY agg_id
            ) as t  %(with_tables)s
        JOIN
            agg_main ON t.agg_id = agg_main.agg_id
        JOIN
            dim_binary ON agg_main.binary_id = dim_binary.id
        GROUP BY md5
        %(order_by_clause)s"""
    
    def __init__(self):
        super(Stats_Binaries_TimeRange, self).__init__()
        self.with_init()
        self.where_init()
        self.order_by_init()
        
    def filter_time_range_recent(self, hours):
        b = self.where_append('filter_time_range', 'ts_min <= tr_end AND ts_min > tr_begin', [begin, end])
        if b:
            self.with_append('filter_time_range',
                "tr AS SELECT max(ts_min) AS tr_end, max(ts_min) - interval '%s hour' AS tr_begin from ts_main_min)",
                'tr',
                [hours]
            )
    
    def filter_time_range(self, begin, end):
        self.where_append('filter_time_range', 'ts_min >= %s AND ts_min <= %s', [begin, end])
    
    def filter_ident(self, idents):
        self.where_append('filter_ident', 'ident_id IN (SELECT id from dim_ident WHERE ident IN %s)', [tuple(idents)])
    
    def filter_source_ip(self, source_ips):
        self.where_append('filter_source_ip', 'source_ip IN %s', [tuple(source_ips)])
    
    def order_n_count(self, desc=False):
        self.order_by_append('order_n_count', 'n_count', desc)