-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathpeba.py
executable file
·1494 lines (1280 loc) · 50.5 KB
/
peba.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
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# PEBA (Python EWS Backend API)
# v0.91 2020-05-05
# Authors: @vorband
import xml.etree.ElementTree as ET
import defusedxml.ElementTree as ETdefused
import logging
import hashlib
import urllib.request, urllib.parse, urllib.error
import html
import datetime
import ipaddress
import sys
from os.path import exists
from functools import wraps
from dateutil.relativedelta import relativedelta
from flask import Flask, request, abort, jsonify, Response, redirect
from flask_cors import CORS
from flask_elasticsearch import FlaskElasticsearch
from elasticsearch import ElasticsearchException
from werkzeug.middleware.proxy_fix import ProxyFix
from modules.tpotstats import getTPotAlertStatsJson, getStats, getTops
from modules.usercache import cacheGetUserToken, cacheSaveUser, UserNotFoundException
###################
### Initialization
###################
app = Flask(__name__)
if exists('/etc/peba/peba.cfg'):
app.config.from_pyfile('/etc/peba/peba.cfg')
else:
app.config.from_prefixed_env(prefix='PEBA')
for index in ['DEFAULTRESPONSE', 'BINDHOST', 'CORSDOMAIN', 'ELASTICSEARCH_HOST',
'ALERTINDEX', 'USERINDEX', 'STATISTICINDEX', 'ELASTICTIMEOUT',
'MAXALERTS', 'BADIPTIMESPAN', 'COMMUNITYUSER', 'COMMUNITYTOKEN']:
if index not in app.config:
print(f'Config Parameter \'{index}\' not in Config File or Enviroment! Exit.')
sys.exit()
app.wsgi_app = ProxyFix(app.wsgi_app)
cors = CORS(app, resources={r"/alert/*": {"origins": app.config['CORSDOMAIN']}})
es = FlaskElasticsearch(app,
timeout=app.config['ELASTICTIMEOUT']
)
statisticIndex=app.config['STATISTICINDEX']
###############
### Functions
###############
def authentication_required(f):
""" This login decorator verifies that the correct username
and password are sent over POST in the XML format.
"""
@wraps(f)
def decorated_function(*args, **kwargs):
postdata = request.data.decode('utf-8')
if len(postdata) == 0:
app.logger.error('Authentication: No xml post data in request')
return abort(403)
else:
root = ETdefused.fromstring(postdata)
user_data = root.find("./Authentication/username")
pass_data = root.find("./Authentication/token")
if user_data is None or pass_data is None:
app.logger.error('Authentication: Invalid XML, token not present or empty')
return abort(403)
username = user_data.text
password = pass_data.text
if not authenticate(username, password):
app.logger.error("Authentication failure for user %s", username)
return abort(403)
return f(*args, **kwargs)
return decorated_function
@app.after_request
def add_header(response):
response.headers["Access-Control-Allow-Credentials"] = "true"
return response
def testElasticsearch():
try:
return es.ping()
except:
return False
def testMemcached():
try:
getCache("heartbeat", "test")
return True
except:
return False
def authenticate(username, token):
""" Authenticate user from cache or in ES """
# check for user in cache
try:
authtoken = cacheGetUserToken(username)
if len(authtoken) == 128:
tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
return True
elif len(authtoken) == 32:
tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
return True
except UserNotFoundException:
app.logger.debug('authenticate(): User "%s" not found in cache!' % username)
# query ES
try:
res = es.search(index=app.config['USERINDEX'], body={
"query": {
"term": {
"peerName": username
}
}
})
if res["hits"]["total"] > 1:
app.logger.error('authenticate(): More than one user "%s" in ES index "users" found!' % username)
elif res["hits"]["total"] < 1:
app.logger.error('authenticate(): No user "%s" in ES index "users" found!' % username)
elif res["hits"]["total"] == 1:
authtoken = res["hits"]["hits"][0]["_source"]["token"]
if len(authtoken) == 128:
tokenhash = hashlib.sha512(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
# add user and token to cache for 24h
cacheSaveUser(username, authtoken)
return True
elif len(authtoken) == 32:
tokenhash = hashlib.md5(token.encode('utf-8')).hexdigest()
if authtoken == tokenhash:
# add user and token to cache for 24h
cacheSaveUser(username, authtoken)
return True
else:
app.logger.error('authenticate(): Hash "{0}" for user "{1}" is not matching md5 or sha512 length! Needs to be checked in ES index!'.format(authtoken, username))
return False
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def checkCommunityUser():
""" Checks if community credentials are used
"""
postdata = request.data.decode('utf-8')
if len(postdata) == 0:
app.logger.error('no xml post data in request')
return abort(403)
else:
root = ETdefused.fromstring(postdata)
user_data = root.find("./Authentication/username")
pass_data = root.find("./Authentication/token")
if user_data is None or pass_data is None:
app.logger.error('Invalid XML: token not present or empty')
return abort(403)
username = user_data.text
password = pass_data.text
if username == app.config['COMMUNITYUSER'] and password == app.config['COMMUNITYTOKEN']:
return True
if not authenticate(username, password):
app.logger.error("simplePostMessage-Authentication failure for user %s", username)
return abort(403)
return False
def checkCommunityIndex(request):
"""check if request is agains community index or production index"""
if not request.args.get('ci'):
return "true"
elif request.args.get('ci') == "0":
return "false"
elif request.args.get('ci') == "-1":
return "true, false"
return "true"
def getRelevantIndices(dayIndices):
"""calculate the relevant indices to be queried in days
use ews-* if false
"""
if not dayIndices:
app.logger.debug('getRelevantIndices: Returning search over all indices: ews-*')
return app.config['ALERTINDEX']+"-*"
else:
allDates=""
currentDay = "<" + app.config['ALERTINDEX'] + "-{now/d}-*>"
allDates+=currentDay
for i in range (1, dayIndices):
prevDay = "<" + app.config['ALERTINDEX']+ "-{now/d-"+str(i)+"d}-*>"
allDates+=","+prevDay
app.logger.debug('getRelevantIndices: Returning search over %s' % allDates)
return allDates
# GET functions
def queryBadIPs(badIpTimespan, clientDomain, relevantIndex):
""" Get IP addresses from alerts in elasticsearch """
esquery="""
{
"query": {
"bool": {
"must": [
{
"range": {
"recievedTime": {
"gte": "now-%sm"
}
}
},
{
"terms": {
"clientDomain": [ %s ]
}
}
]
}
},
"aggs": {
"ips": {
"terms": {
"field": "sourceEntryIp",
"size": 1000000
}
}
},
"size": 0
}
""" % (badIpTimespan, clientDomain)
try:
res = es.search(index=relevantIndex, body=esquery)
if 'aggregations' in res:
return res["aggregations"]["ips"]
else:
return False
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryAlerts(maxAlerts, clientDomain, relevantIndex):
""" Get IP addresses from alerts in elasticsearch """
esquery="""{
"query": {
"terms": {
"clientDomain": [ %s ]
}
},
"sort": {
"recievedTime": {
"order": "desc"
}
},
"size": %s,
"_source": [
"createTime",
"recievedTime",
"peerIdent",
"peerType",
"country",
"targetCountry",
"originalRequestString",
"location",
"sourceEntryIp"
]
}""" % (clientDomain, maxAlerts)
try:
res = es.search(index=relevantIndex, body=esquery)
return res["hits"]["hits"]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryAlertsWithoutIP(maxAlerts, clientDomain, relevantIndex):
""" Get IP addresses from alerts in elasticsearch """
esquery="""
{
"query": {
"terms": {
"clientDomain": [ %s ]
}
},
"sort": {
"recievedTime": {
"order": "desc"
}
},
"size": %s,
"_source": [
"createTime",
"peerType",
"country",
"originalRequestString",
"location",
"targetCountry",
"countryName",
"locationDestination",
"recievedTime",
"username",
"password",
"login",
"clientDomain"
]
}""" % (clientDomain, maxAlerts)
try:
res = es.search(index=relevantIndex, body=esquery)
return res["hits"]["hits"]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryAlertsCount(timeframe, clientDomain, relevantIndex):
""" Get number of Alerts in timeframe in elasticsearch """
# check if timespan = d or number
if timeframe == "day":
span = "now/d"
elif timeframe.isdecimal():
span = "now-%sm" % timeframe
else:
app.logger.error('Non numeric value in retrieveAlertsCount timespan. Must be decimal number (in minutes) or string "day"')
return False
esquery="""{
"query": {
"bool": {
"must": [
{
"terms": {
"clientDomain": [ %s ]
}
}
],
"filter": [
{
"range": {
"recievedTime": {
"gte": "%s"
}
}
}
]
}
},
"size": 0
}
""" % (clientDomain, str(span))
try:
res = es.search(index=relevantIndex, body=esquery)
return res['hits']['total']
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryAlertsCountWithType(timeframe, clientDomain, relevantIndex):
""" Get number of Alerts in timeframe in elasticsearch """
# check if timespan = d or number
if timeframe == "day":
span = "now/d"
elif timeframe.isdecimal():
span = "now-%sm" % timeframe
else:
app.logger.error('Non numeric value in retrieveAlertsCountWithType timespan. Must be decimal number (in minutes) or string "day"')
return False
esquery="""
{
"query": {
"range": {
"recievedTime": {
"gte": "%s"
}
}
},
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"honeypotTypes": {
"terms": {
"field": "peerType"
}
}
}
}
},
"size": 0
}
""" % (span, clientDomain)
try:
res = es.search(index=relevantIndex, body=esquery)
return res
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryDatasetAlertsPerMonth(days, clientDomain, relevantIndex):
# check if months is a number
if days is None:
span = "now-1M/d"
elif days.isdecimal():
span = "now-%sd/d" % days
else:
app.logger.error('Non numeric value in datasetAlertsPerMonth timespan. Must be decimal number in days')
return False
esquery="""{
"query": {
"range": {
"createTime": {
"gte": "%s"
}
}
},
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ % s ]
}
},
"aggs": {
"range": {
"date_histogram": {
"field": "createTime",
"interval": "day"
}
}
}
}
},
"size": 0
}""" % (str(span), clientDomain)
try:
res = es.search(index=relevantIndex, body=esquery)
return res["aggregations"]["communityfilter"]["range"]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryDatasetAlertTypesPerMonth(days, clientDomain, relevantIndex):
# check if days is a number
if days is None:
span = "now-1M/d"
elif days.isdecimal():
span = "now-%sd/d" % days
else:
app.logger.error('Non numeric value in datasetAlertsTypesPerMonth timespan. Must be decimal number in days')
return False
esquery="""
{
"query": {
"range": {
"createTime": {
"gte": "%s"
}
}
},
"_source": [
"clientDomain",
"createTime",
"peerType"
],
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"range": {
"date_histogram": {
"field": "createTime",
"interval": "day"
},
"aggs": {
"nested_terms_agg": {
"terms": {
"field": "peerType"
}}}
}
}
}
},
"size": 0
}
""" % (str(span), clientDomain )
try:
res = es.search(index=relevantIndex, body=esquery)
return res["aggregations"]["communityfilter"]["range"]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryAlertStats(clientDomain, relevantIndex):
""" Get combined statistics from elasticsearch """
esquery="""{
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"ctr": {
"range": {
"field": "recievedTime",
"ranges": [
{
"key": "1d",
"from": "now-1440m"
},
{
"key": "1h",
"from": "now-60m"
},
{
"key": "5m",
"from": "now-5m"
},
{
"key": "1m",
"from": "now-1m"
}
]
}
}}}
},
"size": 0
}""" % clientDomain
try:
res = es.search(index=relevantIndex, body=esquery)
if 'aggregations' in res:
return res['aggregations']['communityfilter']['ctr']['buckets']
else:
return False
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryTopCountriesAttacks(monthOffset, topX, clientDomain, relevantIndex):
# use THIS month
if monthOffset is None or monthOffset == "0" :
span = "now/M"
monthOffset = 0
span2 = "now"
# check if months is a number
elif monthOffset.isdecimal():
span = "now-%dM/M" % int(monthOffset)
span2 = "now-%dM/M" % (int(monthOffset)-1)
else:
app.logger.error('Non numeric value in topCountriesAttacks monthOffset. Must be decimal number in months')
return False
# use top10 default
if topX is None:
topx = 10
# check if months is a number
elif topX.isdecimal():
topx = topX
else:
app.logger.error(
'Non numeric value in topCountriesAttacks topX. Must be decimal number.')
return False
esquery="""{
"query": {
"range": {
"recievedTime": {
"gte": "%s",
"lt": "%s"
}
}
},
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"countries": {
"terms": {
"field": "country",
"size" : %s
},
"aggs": {
"country": {
"top_hits": {
"size": 1,
"_source": {
"includes": [
"countryName"
]
}
}
}}}
}
}
},
"size": 0
}""" % (span, span2, clientDomain, str(topx))
# Get top 10 attacker countries
try:
res = es.search(index=relevantIndex, body=esquery)
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
esquery2="""{
"query": {
"range": {
"recievedTime": {
"gte": "%s",
"lt": "%s"
}
}
},
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"countries": {
"terms": {
"field": "targetCountry",
"size" : %s
},
"aggs": {
"country": {
"top_hits": {
"size": 1,
"_source": {
"includes": [
"targetCountryName"
]
}
}}}
}
}
}
},
"size": 0,
"_source": [
"createTime"
]
} """ % (span, span2, clientDomain, str(topx))
# Get top 10 attacked countries
try:
res2 = es.search(index=relevantIndex, body=esquery2)
monthData = (datetime.date.today()+ relativedelta(months=-(int(monthOffset)))).strftime('%Y-%m')
return [ res["aggregations"]["communityfilter"]["countries"]["buckets"], monthOffset, monthData, res2["aggregations"]["communityfilter"]["countries"]["buckets"] ]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryLatLonAttacks(direction, topX, dayoffset, clientDomain, relevantIndex):
# use default: Lat long of source
if direction is None:
locationString = "location"
elif direction == "src":
locationString = "location"
elif direction == "dst":
locationString = "locationDestination"
else:
app.logger.error('Invalid value in /retrieveLatLonAttacks direction. Must be "src" or "dest"')
return False
# use top10 default
if topX is None:
topx = 10
# check if months is a number
elif topX.isdecimal():
topx = topX
else:
app.logger.error(
'Non numeric value in /retrieveLatLonAttacks topX. Must be decimal number.')
return False
# statistics for 24 hours
if dayoffset is None or dayoffset == "0":
span = "now-24h"
span2 = "now"
dayoffset = 0
# check if days is a number
elif dayoffset.isdecimal():
span = "now-%dd/d" % int(dayoffset)
span2 = "now-%dd/d" % (int(dayoffset)-1)
else:
app.logger.error(
'Non numeric value in /retrieveLatLonAttacks day offset. Must be decimal number.')
return False
esquery="""{
"query": {
"range": {
"createTime": {
"gte": "%s",
"lt": "%s"
}
}
},
"_source": [
"location",
"createTime"
],
"size": 1,
"aggs": {
"communityfilter": {
"filter": {
"terms": {
"clientDomain": [ %s ]
}
},
"aggs": {
"topLocations": {
"terms": {
"field": "%s.keyword",
"size": "%s"
}
}}}
}
}""" % (str(span), str(span2), clientDomain, locationString, topx)
print(esquery)
# Get location strings
try:
res = es.search(index=relevantIndex, body=esquery)
dayData = (datetime.date.today()+ relativedelta(days=-(int(dayoffset))))
return [ res["aggregations"]["communityfilter"]["topLocations"]["buckets"], dayData.strftime('%Y-%m-%d') ]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
def queryForSingleIP(maxAlerts, ip, clientDomain, relevantIndex):
""" Get data for specific IP addresse from elasticsearch """
try:
ipaddress.IPv4Address(ip)
if not ipaddress.ip_address(ip).is_global:
app.logger.debug('No global IP address given on /querySingleIP: %s' % str(request.args.get('ip')))
return False
except:
app.logger.debug('No valid IP given on /querySingleIP: %s' % str(request.args.get('ip')))
return False
esquery="""{
"query": {
"bool": {
"must": [
{
"term": {
"sourceEntryIp": "%s"
}
},
{
"terms": {
"clientDomain": [ %s ]
}
}
]
}
},
"size": %s,
"sort": {
"createTime": {
"order": "desc"
}
},
"_source": [
"createTime",
"peerType",
"targetCountry",
"originalRequestString"
]
}""" % (ip, clientDomain, maxAlerts)
try:
res = es.search(index=relevantIndex, body=esquery)
return res["hits"]["hits"]
except ElasticsearchException as err:
app.logger.error('ElasticSearch error: %s' % err)
return False
# Formatting functions
def prettify(elem, level=0):
""" Prettify the xml output """
i = "\n" + level*" "
if len(elem):
if not elem.text or not elem.text.strip():
elem.text = i + " "
if not elem.tail or not elem.tail.strip():
elem.tail = i
for elem in elem:
prettify(elem, level+1)
if not elem.tail or not elem.tail.strip():
elem.tail = i
else:
if level and (not elem.tail or not elem.tail.strip()):
elem.tail = i
def formatBadIP(iplist, outformat):
""" Create XML Strucure for BadIP list """
if outformat=='xml':
if iplist:
ewssimpleinfo = ET.Element('EWSSimpleIPInfo')
sources = ET.SubElement(ewssimpleinfo, 'Sources')
for ip in iplist['buckets']:
if ipaddress.ip_address(ip['key']).is_global:
source = ET.SubElement(sources, 'Source')
address = ET.SubElement(source, 'Address')
address.text = ip['key']
counter = ET.SubElement(source, 'Count')
counter.text = str(ip['doc_count'])
prettify(ewssimpleinfo)
iplistxml = '<?xml version="1.0" encoding="UTF-8"?>'
iplistxml += (ET.tostring(ewssimpleinfo, encoding="utf-8", method="xml")).decode('utf-8')
return iplistxml
else:
return app.config['DEFAULTRESPONSE']
elif outformat == 'json':
if iplist:
iplistjson=[]
for ip in iplist['buckets']:
if ipaddress.ip_address(ip['key']).is_global:
iplistjson.append({
"ip" : ip['key'],
"count" : ip['doc_count']
})
return iplistjson
else:
return app.config['DEFAULTRESPONSE']
else:
return app.config['DEFAULTRESPONSE']
def formatAlertsXml(alertslist):
""" Create XML Strucure for Alerts list """
EWSSimpleAlertInfo = ET.Element('EWSSimpleAlertInfo')
alertsElement = ET.SubElement(EWSSimpleAlertInfo, 'Alerts')
if alertslist:
for alert in alertslist:
if datetime.datetime.strptime(alert['_source']['createTime'],"%Y-%m-%d %H:%M:%S") > datetime.datetime.utcnow():
returnDate = alert['_source']['recievedTime']
app.logger.debug('formatAlertsJson: createTime > now, returning recievedTime, honeypot timezone probably manually set to eastern timezone')
else:
returnDate = alert['_source']['recievedTime']
alertElement = ET.SubElement(alertsElement, 'Alert')
alertId = ET.SubElement(alertElement, 'Id')
alertId.text = alert['_id']
alertDate = ET.SubElement(alertElement, 'DateCreated')
alertDate.text = returnDate
peerElement = ET.SubElement(alertElement, 'Peer')
peerId = ET.SubElement(peerElement, 'Id')
peerId.text = alert['_source']['peerIdent']
peerType = ET.SubElement(peerElement, 'Type')
peerType.text = alert['_source']['peerType']
peerCountry = ET.SubElement(peerElement, 'Country')
peerCountry.text = alert['_source']['targetCountry']
requestElement = ET.SubElement(alertElement, 'Request')
requestElement.text = alert['_source']['originalRequestString']
sourceElement = ET.SubElement(alertElement, 'Source')
sourceAddress = ET.SubElement(sourceElement, 'Address')
sourceAddress.text = alert['_source']['sourceEntryIp']
sourceCountry = ET.SubElement(sourceElement, 'Country')
sourceCountry.text = alert['_source']['country']
sourceCoordinates = alert['_source']['location'].split(',')
sourceLatitude = ET.SubElement(sourceElement, 'Latitude')
sourceLatitude.text = sourceCoordinates[0].strip()
sourceLongitude = ET.SubElement(sourceElement, 'Longitude')
sourceLongitude.text = sourceCoordinates[1].strip()
prettify(EWSSimpleAlertInfo)
alertsxml = '<?xml version="1.0" encoding="UTF-8"?>'
alertsxml += (ET.tostring(EWSSimpleAlertInfo, encoding="utf-8", method="xml")).decode('utf-8')
return alertsxml
def formatAlertsJson(alertslist):
""" Create JSON Structure for Alerts list """
jsonarray = []
if alertslist:
for alert in alertslist:
if datetime.datetime.strptime(alert['_source']['createTime'], "%Y-%m-%d %H:%M:%S") > datetime.datetime.utcnow():
returnDate = alert['_source']['recievedTime']
app.logger.debug('formatAlertsJson: createTime > now, returning recievedTime, honeypot timezone probably manually set to eastern timezone')
else:
returnDate = alert['_source']['recievedTime']
latlong = alert['_source']['location'].split(' , ')
destlatlong = alert['_source']['locationDestination'].split(' , ')
# cowrie/heralding attack details
if (("SSH/console(cowrie)" in alert['_source']['peerType']
or "Passwords(heralding)" in alert['_source']['peerType'] )
and alert['_source']['originalRequestString'] == ""):
requestString = ""
if alert['_source']['username'] is not None:
requestString+= "Username: \"" + str(urllib.parse.unquote(alert['_source']['username'])) + "\""
else:
requestString += "Username: <none>"
if alert['_source']['password'] is not None:
requestString+= " | Password: \"" + str(urllib.parse.unquote(alert['_source']['password'])) + "\""
else:
requestString += " | Password: <none>"
# only show login status for cowrie
if "SSH/console(cowrie)" in alert['_source']['peerType'] and alert['_source']['login'] is not None:
requestString+= " | Status: "+ str(alert['_source']['login'])
requestStringOut = html.escape(requestString)
elif ("SSH/console(cowrie)" in alert['_source']['peerType']
and alert['_source']['originalRequestString'] != ""):
requestStringOut = html.escape(alert['_source']['originalRequestString']).replace("\n", "; " )[2:]
else:
requestStringOut = html.escape(urllib.parse.unquote(alert['_source']['originalRequestString']))
# map private IP ranges 0:0 Locations to DTAG HQ in Bonn :) # 50.708021, 7.129191
if latlong == ["0.0","0.0"]:
latlong = ["50.708021", "7.129191"]
app.logger.debug('formatAlertsJson: mapping location 0.0/0.0 to DTAG HQ')
if destlatlong == ["0.0","0.0"]:
destlatlong = ["50.708021", "7.129191"]
app.logger.debug('formatAlertsJson: mapping location 0.0/0.0 to DTAG HQ')
jsondata = {
'id': alert['_id'],
'dateCreated': "%s" % returnDate,