aboutsummaryrefslogtreecommitdiff
path: root/cowrieder.py
blob: cee7ee89d24195142187cb83e348e53e48a24287 (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
import json
import sys
import random
import os
import argparse
import hashlib
import ipaddress
from pprint import pprint
import time

start_time = time.time()
cmdping_commands = ['uname', 'nproc'] # List of commands that, if used exclusively, qualify a session as a "command ping"
pubkey_attempt_str = "[SSH_PUBKEY_ATTEMPT]"

# Definitions if you're reading this code for some reason:
# - An empty ping is when a client connects and then does nothing, not even a log in attempt, presumably just to check if an SSH server exists
# - A login ping is when a client logs in successfully and leaves without doing anything
# - A "command ping" is when a client logs in and then only runs the handful of common test/query commands listed above. These make up such a
#   large percentage of sessions where any command is run that I felt the need to create a distinction in order to make finding the most interesting log entires easier

# ArgParse crap coming in hot

parser = argparse.ArgumentParser(
  description="Script to parse JSON logs from popular SSH honeypot Cowrie, print them in a more readable format, and gather some statistics about them"
)

parser.add_argument('filepath', help="The path to the cowrie JSON log file you want to analyze, or a folder of them. If given a folder, looks for any .json file or any file starting with \"cowrie.json\" and ingests them sorted by file modification timestamp")

parser.add_argument('-v', '--verbose', action='store_true', help="Make the output more verbose (do less to collapse less-interesting information)")
parser.add_argument('-V', '--verboser', action='store_true', help="Make the output even more verbose (one line per event)")
parser.add_argument('-W', '--verbosest', action='store_true', help="Make the output even more verboserer (dump as much information as possible as pretty-printed JSON)")

parser.add_argument('-P', '--pings', action='store_true', help='Include only connections where no authentication attempt was made')
parser.add_argument('-F', '--fails', action='store_true', help='Include only failed logins')
parser.add_argument('-L', '--logins', action='store_true', help='Include only successful logins where no commands were run')
parser.add_argument('-C', '--commands', action='store_true', help='Include only logins where only this list of basic test commands were run: ' + str(cmdping_commands))
parser.add_argument('-E', '--eventful', action='store_true', help='Include only the cool interesting sessions that aren\'t any of that other stuff')

parser.add_argument('-u', '--filter-username', help='Filter data to uses of a specific username')
parser.add_argument('-p', '--filter-password', help='Filter data to uses of a specific password. Pass "'+pubkey_attempt_str+'" to filter for attempts to log in using an SSH public key instead of a password, which does happen')
parser.add_argument('-z', '--filter-sensor', help='Filter data to a certain \"sensor\". Useful if Cowrie is running in proxy mode to multiple endpoints')
parser.add_argument('-i', '--filter-ip', help='Filter data to a specific IP, censored hash thereof, or netmask (127.0.0.1 / 0b39f7265d91e7c3 / 127.0.0.0/16)')

parser.add_argument('-r', '--redact-ip', action='store_true', help='Redact IP addresses by converting them to 16-character hashes')
parser.add_argument('-c', '--no-color', action='store_true', help="Don't color-code terminal output")

parser.add_argument('-s', '--stats', action='store_true', help='Print aggregated statistics')
parser.add_argument('-S', '--only-stats', action='store_true', help='Print only aggregated statistics')
parser.add_argument('-m', '--html', action='store_true', help="Output an overview as an HTML webpage, GoAccess-style. Ignores previous two options.")

def ccgen(seed=""): # Color code generator
  if(not os.isatty(1) or args.no_color): # Do not output color code at all if output is not a TTY that can accept them
    return ""

  match(seed): # Match color keywords to control codes
    case "RED":
      return "\x1b[31m"
    case "GREEN":
      return "\x1b[32m"
    case "YELLOW":
      return "\x1b[33m"
    case "BLUE":
      return "\x1b[34m"
    case "PURPLE":
      return "\x1b[35m"
    case "CYAN":
      return "\x1b[36m"
    case "GREY":
      return "\x1b[37m"
    case "RESET":
      return "\x1b[0m"

  if(seed): # If seed is provided, use it to generate a color
    random.seed(seed)
    return "\x1b[38;2;{r};{g};{b}m".format(r=random.randrange(50, 256), g=random.randrange(50, 256), b=random.randrange(50, 256))
  return "\x1b[0m"

def ttylog(mystring): #mystring
  if(os.isatty(1)):
    print(mystring)

def ppip(addr, spacing = False, ttycolor = False): # Pretty-print an address with colour and, if it's IPv4 or hashed, a consistent width
  rs = addr
  if(ttycolor):
    rs = ccgen(rs) + rs + ccgen()
  if(len(addr) <= 16 and spacing):
    rs = rs + (" " * (15 - len(addr)))
  return rs

def hashgen(seed, length=16):
  if(length % 2):
    raise Warning("Due to strange behaviour on the part of the hexdigest() function, length should be a multiple of 2")
  return hashlib.shake_256(str(seed).encode("utf-8")).hexdigest(int(length / 2))

args = parser.parse_args()

verbosity = 0
if(args.verbosest):
  verbosity = 3
elif(args.verboser):
  verbosity = 2
elif(args.verbose):
  verbosity = 1

filepath = args.filepath

blankmode = (args.pings or args.fails or args.logins or args.commands or args.eventful)

include_empty_pings   = (not blankmode or args.pings)
include_failed_logins = (not blankmode or args.fails)
include_login_pings   = (not blankmode or args.logins)
include_command_pings = (not blankmode or args.commands)
include_eventful      = (not blankmode or args.eventful)

print_stats = args.stats or args.only_stats

sessions = {} # Dict - session_id : list of events in session

def session_ip(session): # Grab IP from session
  return session[0]['src_ip']

def session_timestamp(session): # Grab initial timestamp of session
  return session[0]['timestamp']

def session_duration(session): # Grab duration of session -- if session never closed return -1
  if(session[-1]['eventid'] == "cowrie.session.closed"):
    return float(session[-1]['duration'])
  return -1

def session_sensor(session): # Grab sensor from session
  return session[0]['sensor']

def session_attempted_login(session): # Determine whether a login was attempted
  for event in session:
    if(event['eventid'] == "cowrie.login.failed" or event['eventid'] == "cowrie.login.success"):
      return True
  return False

def session_login_succeeded(session): # Determine whether a login attempt was successful
  for event in session:
    if(event['eventid'] == "cowrie.login.success"):
      return True
  return False

def session_cred_combos(session): # List passwords used in login attempt
  ra = []
  if(session_attempted_login(session)):
    for event in session:
      if(event['eventid'] == "cowrie.login.failed" or event['eventid'] == "cowrie.login.success"):
        if('password' in event):
          ra.append((event['username'], event['password']))
        elif('key' in event):
          ra.append((event['username'], pubkey_attempt_str)) # This means that the login attempt was made using a pubkey instead of a password
  return ra

def session_ran_command(session): # Was a command run during the session
  for event in session:
    if(event['eventid'] == "cowrie.command.input"):
      return True
  return False

def session_saved_file(session): # Were any files saved to disk during the session
  for event in session:
    if(event['eventid'] == "cowrie.session.file_download"):
      return True
  return False

def session_is_cmdping(session): # Determine if a session qualifies as a "command ping"
  if(session_ran_command(session)):
    for event in session:
      if(event['eventid'] == "cowrie.command.input"):
        argv0 = event['input'] # Isolate the name of the command
        if(" " in argv0):
          argv0 = event['input'][:event['input'].index(" ")]

        if(argv0 not in cmdping_commands):
          return False
    return True
  return False

def session_pingcmds(session): # Return array of all "command ping" commands used in a session
  ra = []
  if(session_ran_command(session)):
    for event in session:
      if(event['eventid'] == "cowrie.command.input"):
        argv0 = event['input'] # Isolate the name of the command
        if(" " in argv0):
          argv0 = event['input'][:event['input'].index(" ")]

        if(argv0 in cmdping_commands):
          ra.append(event['input'])
  return ra

# File loading stuff

total_filesize = 0
def sizeof_fmt(num, suffix="B"): # Shamelessly stolen from StackOverflow
    for unit in ("", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi"):
        if abs(num) < 1024.0:
            return f"{num:3.1f}{unit}{suffix}"
        num /= 1024.0
    return f"{num:.1f}Yi{suffix}"

def load_json_to_array(fp):
  with open(fp, "r") as logfile:
    for line in logfile:
      entry = json.loads(line)

      if(
        (not args.filter_ip or hashgen(entry['src_ip']) == args.filter_ip or ipaddress.ip_address(entry['src_ip']) in ipaddress.ip_network(args.filter_ip)) and
        (not args.filter_sensor or args.filter_sensor == entry['sensor']) # If it's not the IP/sensor we're filtering for don't even bother man
        ):
        session_id = entry['session']

        if(session_id not in sessions):
          sessions.update({session_id: [entry]})
        else:
          sessions[session_id].append(entry)

if(os.path.isfile(filepath)):
  load_json_to_array(filepath)
  total_filesize += os.path.getsize(filepath)
elif(os.path.isdir(filepath)):
  # run load_json_to_array for every json file in the directory
  files = {}
  for f in os.listdir(filepath):
    if(f[:11] == "cowrie.json" or f[-5:] == ".json"):
      fi = os.path.join(filepath, f)
      files.update({fi: os.path.getmtime(fi)})
  for g in dict(sorted(files.items(), key=lambda item: item[1])):
    load_json_to_array(g)
    total_filesize += os.path.getsize(g)
else:
  raise FileNotFoundError

if(len(sessions) < 1):
  print("No logs were loaded")
  exit(1)

# Filtering

newsessions = sessions.copy()

for session_id in sessions:
  session = sessions[session_id]
  
  if(args.redact_ip):
    src_ip = session_ip(session)
    dst_ip = session[0]['dst_ip']
    for i, event in enumerate(session):
      for a in event:
        if(isinstance(event[a], str)):
          newsessions[session_id][i][a] = event[a].replace('127.0.0.1', 'localhost').replace(src_ip, hashgen(src_ip)).replace(dst_ip, 'Host IP')

  s_u = []
  s_p = []
  for a in session_cred_combos(session):
    s_u.append(a[0])
    s_p.append(a[1])

  if(
    (blankmode and (
         (not include_empty_pings   and not session_attempted_login(session))
      or (not include_failed_logins and     session_attempted_login(session) and not session_login_succeeded(session))
      or (not include_login_pings   and     session_login_succeeded(session) and not session_ran_command(session))
      or (not include_command_pings and     session_is_cmdping(session))
      or (not include_eventful      and     session_ran_command(session)     and not session_is_cmdping(session))))
    or (args.filter_username and args.filter_username not in s_u)
    or (args.filter_password and args.filter_password not in s_p)):
    newsessions.pop(session_id)

sessions = newsessions

# Statistics Aggregation

def percent_of_all_sessions(num):
  if(verbosity < 2):
    return int(num / len(sessions) * 100)
  return num / len(sessions) * 100

login_combos = []
attempt_counts_by_username = {}
attempt_counts_by_password = {}
passwords_by_username = {}

cnt_pings = 0
cnt_fails = 0
cnt_lping = 0
cnt_cmdping = 0
cnt_eventful = 0
cnt_filessaved = 0

login_combos_by_ip = {}
attempt_counts_by_ip = {} # Stats pertaining to source IPs
def top_n_percent_of_ips_session_percent(n): # pretty self explanatory. Pass a float between 0 and 1
  i = 0
  maxi = len(attempt_counts_by_ip) * n
  c = 0
  for ip in attempt_counts_by_ip:
    if(i > maxi):
      break
    c += attempt_counts_by_ip[ip]
    i += 1
  return percent_of_all_sessions(c)

def update_cnt_by(item, cnt_by):
  if(item not in cnt_by):
    cnt_by.update({item: 1})
  else:
    cnt_by[item] += 1

for s_id in sessions:
  s = sessions[s_id]
  ip = session_ip(s)
  # Count how many attempts this source IP has made
  update_cnt_by(ip, attempt_counts_by_ip)
  # Create list of credential combos used
  for a in session_cred_combos(s):
    login_combos.append(a)
  # Group credential combos by IP
  if(ip not in login_combos_by_ip):
    login_combos_by_ip.update({ip: session_cred_combos(s)})
  else:
    for a in session_cred_combos(s):
      login_combos_by_ip[ip].append(a)
  # Count sessions by type
  if(not session_attempted_login(s)):
    cnt_pings += 1
  elif(session_attempted_login(s) and not session_login_succeeded(s)):
    cnt_fails += 1
  elif(session_login_succeeded(s) and not session_ran_command(s)):
    cnt_lping += 1
  elif(session_is_cmdping(s)):
    cnt_cmdping += 1
  elif(session_ran_command(s) and not session_is_cmdping(s)):
    cnt_eventful += 1
  if(session_saved_file(s)):
    cnt_filessaved += 1

for a in login_combos:
  update_cnt_by(a[0], attempt_counts_by_username)
  update_cnt_by(a[1], attempt_counts_by_password)

  if(a[0] not in passwords_by_username):
    passwords_by_username.update({a[0]: [a[1]]})
  elif(a[1] not in passwords_by_username[a[0]]):
    passwords_by_username[a[0]].append(a[1])

def cnt_by_to_by_cnt(cnt_by):
  by_cnt = {}
  for item in cnt_by:
    if(cnt_by[item] not in by_cnt):
      by_cnt.update({cnt_by[item]: []})
    by_cnt[cnt_by[item]].append(item)
  return by_cnt.copy()

attempt_counts_by_ip = dict(sorted(attempt_counts_by_ip.items(), key=lambda item: item[1], reverse=True))
attempt_counts_by_username = dict(sorted(attempt_counts_by_username.items(), key=lambda item: item[1], reverse=True))
attempt_counts_by_password = dict(sorted(attempt_counts_by_password.items(), key=lambda item: item[1], reverse=True))
passwords_by_username = dict(sorted(passwords_by_username.items(), key=lambda item: len(item[1]), reverse=True))
login_combos_by_ip = dict(sorted(login_combos_by_ip.items(), key=lambda item: len(item[1]), reverse=True))

ips_by_attempt_count = cnt_by_to_by_cnt(attempt_counts_by_ip)
usernames_by_attempt_count = cnt_by_to_by_cnt(attempt_counts_by_username)
passwords_by_attempt_count = cnt_by_to_by_cnt(attempt_counts_by_password)

log_parsing_time = time.time() - start_time

# Printing logic coming up

def print_dict_of_lists(by_cnt, is_ip = False, key_is_ip = False, truncate = 3, limit = -1):
  name_max_length = 0
  for item in by_cnt:
    if(name_max_length < len(str(item))):
      name_max_length = len(str(item))

  entries_printed = 0
  for num in by_cnt:
    if(limit > 0 and entries_printed >= limit):
      break
    if(key_is_ip):
      out = (" " * (name_max_length - len(str(num)))) + ppip(str(num), ttycolor=True) + ": "
    else:
      out = (" " * (name_max_length - len(str(num)))) + str(num) + ": "
    cnt = 0
    for item in by_cnt[num]:
      if(verbosity == 0 and cnt >= truncate):
        out += str(len(by_cnt[num])) + " more"
        break
      if(is_ip):
        out += ppip(item, ttycolor=True)
      else:
        out += str(item)
      if(cnt < len(by_cnt[num]) - 1):
        out += ", "
      cnt += 1
    print(out)
    entries_printed += 1

def print_percentage_stats():
  if(len(attempt_counts_by_ip) > 1):
    print("\n--- Of a total " + str(len(sessions)) + " sessions from " + str(len(attempt_counts_by_ip)) + " IPs: ---")
    print()
    if(verbosity > 0):
      print("The top 75% of IPs were responsible for " + str(top_n_percent_of_ips_session_percent(0.75)) + "%")
    print("The top 50% of IPs were responsible for " + str(top_n_percent_of_ips_session_percent(0.5)) + "%")
    if(verbosity > 0):
      print("The top 25% of IPs were responsible for " + str(top_n_percent_of_ips_session_percent(0.25)) + "%")
    print("The top 10% of IPs were responsible for " + str(top_n_percent_of_ips_session_percent(0.1)) + "%")
    print("The top 1% of IPs were responsible for " + str(top_n_percent_of_ips_session_percent(0.01)) + "%")
    print("The top single IP was responsible for " + str(percent_of_all_sessions(attempt_counts_by_ip[next(iter(attempt_counts_by_ip))])) + "%")
    print()
  else:
    num = next(iter(ips_by_attempt_count))
    print("\n--- Of a total " + str(num) + " sessions from " + ips_by_attempt_count[num][0] + ": ---")
  if(include_empty_pings):
    print(str(percent_of_all_sessions(cnt_pings)) + "% (" + str(cnt_pings) + ") made no attempt to log in")
  if(include_failed_logins):
    print(str(percent_of_all_sessions(cnt_fails)) + "% (" + str(cnt_fails) + ") attempted to log in and failed")
  if(include_login_pings):
    print(str(percent_of_all_sessions(cnt_lping)) + "% (" + str(cnt_lping) + ") logged in and then left without doing anything")
  if(include_command_pings):
    print(str(percent_of_all_sessions(cnt_cmdping)) + "% (" + str(cnt_cmdping) + ") logged in and then ran only a subset of these commands: " + str(cmdping_commands))
  if(include_eventful):
    print(str(percent_of_all_sessions(cnt_eventful)) + "% (" + str(cnt_eventful) + ") logged in and then did something else")
    print(str(percent_of_all_sessions(cnt_filessaved)) + "% (" + str(cnt_filessaved) + ") saved a file")

if(verbosity == 3): # Maximum verbosity: literally just dump everything we have as pretty-printed JSON
  outjson = {}

  if(not args.only_stats):
    outjson.update({'sessions': sessions})
  if(print_stats):
    percentages = {
      'top_90_percent_ips': top_n_percent_of_ips_session_percent(0.9),
      'top_80_percent_ips': top_n_percent_of_ips_session_percent(0.8),
      'top_75_percent_ips': top_n_percent_of_ips_session_percent(0.75),
      'top_70_percent_ips': top_n_percent_of_ips_session_percent(0.7),
      'top_60_percent_ips': top_n_percent_of_ips_session_percent(0.6),
      'top_50_percent_ips': top_n_percent_of_ips_session_percent(0.5),
      'top_40_percent_ips': top_n_percent_of_ips_session_percent(0.4),
      'top_30_percent_ips': top_n_percent_of_ips_session_percent(0.3),
      'top_25_percent_ips': top_n_percent_of_ips_session_percent(0.25),
      'top_20_percent_ips': top_n_percent_of_ips_session_percent(0.2),
      'top_10_percent_ips': top_n_percent_of_ips_session_percent(0.1),
      'top_5_percent_ips': top_n_percent_of_ips_session_percent(0.05),
      'top_1_percent_ips': top_n_percent_of_ips_session_percent(0.01),
      'top_ip': percent_of_all_sessions(attempt_counts_by_ip[next(iter(attempt_counts_by_ip))]),
      'no_login': percent_of_all_sessions(cnt_pings),
      'failed_login': percent_of_all_sessions(cnt_fails),
      'login_no_action': percent_of_all_sessions(cnt_lping),
      'login_uneventful': percent_of_all_sessions(cnt_cmdping),
      'eventful': percent_of_all_sessions(cnt_eventful),
      'saved_file': percent_of_all_sessions(cnt_filessaved)
    }
    counts = {
      'no_login': cnt_pings,
      'failed_login': cnt_fails,
      'login_no_action': cnt_lping,
      'login_uneventful': cnt_cmdping,
      'eventful': cnt_eventful,
      'saved_file': cnt_filessaved
    }
    all_stats = {
      'percentages': percentages,
      'counts': counts,
      'login_combos': login_combos,
      'attempt_counts_by_ip': attempt_counts_by_ip,
      'attempt_counts_by_username': attempt_counts_by_username,
      'attempt_counts_by_password': attempt_counts_by_password,
      'ips_by_attempt_count': ips_by_attempt_count,
      'usernames_by_attempt_count': usernames_by_attempt_count,
      'passwords_by_attempt_count': passwords_by_attempt_count,
      'passwords_by_username': passwords_by_username,
      'login_combos_by_ip': login_combos_by_ip,
      'log_parsing_time': log_parsing_time,
      'total_log_size': total_filesize
    }
    outjson.update({'stats': all_stats})

  print(json.dumps(outjson, indent=4))
  exit()

elif(verbosity == 2): # High verbosity mode: print timestamp, event type and message (if applicable) for every event. I could probably do better but I'm lazy
  if(not args.only_stats):
    for session_id in sessions:
      session = sessions[session_id]
      ip = session_ip(session)
      print("\n--- Session " + ccgen(session_id) + session_id + ccgen() + " from " + ppip(ip, ttycolor=True) + " to " + session_sensor(session) + " ---")
      for entry in session:
        eventid = entry['eventid']
        if(entry['eventid'] == "cowrie.session.params"):
          print(entry["timestamp"] + " > " + eventid + (" " * (29 - len(eventid))) + ": ARCH: " + entry["arch"])
        else:
          print(entry["timestamp"] + " > " + eventid + (" " * (29 - len(eventid))) + ": " + entry['message'])
  if(print_stats):
    print("\n--- Source IPs and number of connections originating from them: ---")
    pprint(attempt_counts_by_ip, sort_dicts=False)
    print("\n--- Credential combinations used: ---")
    pprint(login_combos, sort_dicts=False)
    print("\n--- Usernames and number of times they were tried: ---")
    pprint(attempt_counts_by_username, sort_dicts=False)
    print("\n--- Passwords and number of times they were tried: ---")
    pprint(attempt_counts_by_password, sort_dicts=False)
    print("\n--- Passwords grouped by corresponding username: ---")
    pprint(passwords_by_username, sort_dicts=False)
    print("\n--- Credential combos grouped by source IP: ---")
    pprint(login_combos_by_ip, sort_dicts=False)
    print_percentage_stats()
    print("---\nTook {}s to parse {} of logs".format(str(log_parsing_time)[:4], sizeof_fmt(total_filesize)))



elif(not args.html): # Default (low) verbosity: just the good stuff
  if(not args.only_stats):
    for session_id in sessions:
      
      # Declaring initial variables
      session = sessions[session_id]
      ip = session_ip(session)
      timestamp = session_timestamp(session)[:22].replace("T", " ") # clean up the timestamp text all pretty like
      durationstring = "closed after " + str(session_duration(session)) + "s"
      if(session_duration(session) < 0):
        durationstring = "active as of processing"

      if(not session_attempted_login(session)): # Printing empty pings
        print(timestamp + " > " + ppip(ip, True, True) + " > Connection opened and " + durationstring)

      elif(session_attempted_login(session) and not session_login_succeeded(session)): # Printing failed logins
        print(timestamp + " > " + ppip(ip, True, True) + " > " + ccgen("RED") +"Failed login" + ccgen() + " with credentials: " + str(session_cred_combos(session)))

      elif(session_ran_command(session)): # Printing logic for sessions in which a command was run

        if(not verbosity == 1 and session_is_cmdping(session)): # If -v is not enabled, collapse "command pings" to one-liners
          print(timestamp + " > " + ppip(ip, True, True) + " > " + ccgen("GREEN") + "Login" + ccgen() + " with credentials: " + str(session_cred_combos(session)) + ccgen("BLUE") + " ran commands " + ccgen() + str(session_pingcmds(session)))

        else: # Printing logic for un-collapsed sessions where commands were run
          print(timestamp + " > " + ppip(ip, True, True) + " > " + ccgen("CYAN") + "Session" + ccgen() + ":")
          for entry in session:
            match(entry["eventid"]):
              case "cowrie.login.failed":
                pw = []
                if("password" in entry):
                  pw = entry["password"]
                print(" | Failed login: " + entry["username"] + "/" + str(pw))
              case "cowrie.login.success":
                print(" | Successful login: " + entry["username"] + "/" + entry["password"])
              case "cowrie.command.input":
                print(" | CMD: " + entry["input"])
              case "cowrie.session.file_download":
                df = ""
                if("url" in entry):
                  df = entry["url"]
                elif("destfile" in entry):
                  df = entry["destfile"]
                if(verbosity == 1):
                  print(" | Saved file " + df + " to " + entry["outfile"])
                else:
                  print(" | Saved file " + df + " to " + entry["outfile"][:40] + "...")
          print(" X Session " + durationstring)
          
      else: # Printing logic for successful logins in which no commands were run
        print(timestamp + " > " + ppip(ip, True, True) + " > " + ccgen("GREEN") + "Login" + ccgen() + " with credentials: " + str(session_cred_combos(session)))
  if(print_stats):
    if(verbosity > 0):
      print("\n--- Source IP addresses by attempt count: ---")
      print_dict_of_lists(ips_by_attempt_count, True)
      print("\n--- Credential combos used: ---")
      print(str(login_combos))
      print("\n--- Usernames by attempt count: ---")
      print_dict_of_lists(usernames_by_attempt_count)
      print("\n--- Passwords by attempt count: ---")
      print_dict_of_lists(passwords_by_attempt_count)
      print("\n--- Passwords by username: ---")
      print_dict_of_lists(passwords_by_username)
      print("\n--- IPs with credential combos tried: ---")
      print_dict_of_lists(login_combos_by_ip, key_is_ip=True)
    else:
      print("\n--- Top source IP addresses by attempt count: ---")
      print_dict_of_lists(ips_by_attempt_count, True, limit = 20)
      print("\n--- Top usernames by attempt count: ---")
      print_dict_of_lists(usernames_by_attempt_count, truncate=10, limit = 20)
      print("\n--- Top passwords by attempt count: ---")
      print_dict_of_lists(passwords_by_attempt_count, truncate=10, limit = 20)
      print("\n--- Top usernames with passwords tried: ---")
      print_dict_of_lists(passwords_by_username, truncate=10, limit = 20)
      print("\n--- Top IPs with credential combos tried: ---")
      print_dict_of_lists(login_combos_by_ip, truncate=7, limit = 20, key_is_ip=True)
    print_percentage_stats()
    print("---\nTook {}s to parse {} of logs".format(str(log_parsing_time)[:4], sizeof_fmt(total_filesize)))

elif(args.html):
  # This is a bad way to do it but it's the way I'm gonna. fuck you
  print('<!DOCTYPE html>')
  print('<head>')
  print('  <meta charset="utf-8">')
  print('  <meta name="viewport" content="width=device-width, initial-scale=1">')
  print('  <title>Cowrie Stats</title>')
  print('  <style>')
  print('    :root {')
  print('      --black: #181a1c;')
  print('      --bg_dim: #252630;')
  print('      --bg0: #2b2d3a;')
  print('      --bg1: #333648;')
  print('      --bg2: #363a4e;')
  print('      --bg3: #393e53;')
  print('      --bg4: #3f445b;')
  print('      --gray_dim: #5a5e7a;')
  print('      --gray: #7e8294;')
  print('      --fg: #e1e3e4;')
  print('      --red: #fb617e;')
  print('      --orange: #f89860;')
  print('      --yellow: #edc763;')
  print('      --green: #9ed06c;')
  print('      --blue: #6dcae8;')
  print('      --purple: #bb97ee;')
  print('')
  print('      --bg: var(--bg0);')
  print('      --fontcolor: var(--fg);')
  print('      --linkcolor: var(--red);')
  print('      --linkhover: var(--blue);')
  print('')
  print('      --pc1: var(--red);')
  print('      --pc2: var(--orange);')
  print('      --pc3: var(--green);')
  print('      --pc4: var(--blue);')
  print('      --pc5: var(--purple);')
  print('')
  print('')
  print('      --stdpadding: 1rem;')
  print('    }')
  print('    body {')
  print('      background-color: var(--bg);')
  print('      font-family: sans-serif;')
  print('      color: var(--fontcolor);')
  print('      padding: var(--stdpadding);')
  print('      margin: 0;')
  print('      box-sizing: border-box;')
  print('      min-height: 100vh;')
  print('      display: flex;')
  print('      flex-direction: column;')
  print('    }')
  print('    header {')
  print('      display: flex;')
  print('      padding: var(--stdpadding);')
  print('      align-items: center;')
  print('    }')
  print('    header div {')
  print('      margin-left: var(--stdpadding);')
  print('    }')
  print('    header div h1, header div p {')
  print('      margin: 0')
  print('    }')
  print('    footer {')
  print('      display: flex;')
  print('      margin-top: var(--stdpadding);')
  print('      gap: var(--stdpadding);')
  print('      flex-wrap: wrap;')
  print('    }')
  print('    main {')
  print('      flex: 1;')
  print('    }')
  print('    a {')
  print('      color: var(--linkcolor);')
  print('    }')
  print('    a:hover {')
  print('      color: var(--linkhover);')
  print('    }')
  print('    section {')
  print('      margin: var(--stdpadding) 0;')
  print('    }')
  print('    .smallstats {')
  print('      display: flex;')
  print('      gap: var(--stdpadding);')
  print('      flex-wrap: wrap;')
  print('    }')
  print('    .smallstats article {')
  print('      padding: var(--stdpadding);')
  print('      flex: 1;')
  print('      background-color: #fff2;')
  print('      border-left: 3px solid var(--fontcolor);')
  print('    }')
  print('    .smallstats article h5 {')
  print('      margin: 0;')
  print('      font-weight: normal;')
  print('    }')
  print('')
  print('    .bigstats {')
  print('      display: flex;')
  print('      gap: var(--stdpadding);')
  print('      flex-wrap: wrap;')
  print('    }')
  print('    .bigstats p {')
  print('      margin: 0;')
  print('    }')
  print('    .bigstats article {')
  print('      padding: var(--stdpadding);')
  print('      flex: 1;')
  print('      background-color: var(--bg_dim);')
  print('      box-shadow: 0 0 calc(var(--stdpadding) / 2) black inset;')
  print('      border-left: 3px solid var(--fontcolor);')
  print('      display: flex;')
  print('      flex-direction: column;')
  print('      justify-content: center;')
  print('      align-items: center;')
  print('      min-width: min(30rem, calc(100% - (var(--stdpadding) * 2) - 3px));')
  print('    }')
  print('    .bigstats article h3 {')
  print('      margin-top: 0;')
  print('    }')
  print('    .bigstats article > ul {')
  print('      overflow-y: scroll;')
  print('      max-height: 30rem;')
  print('      padding-left: 0;')
  print('      width: 100%;')
  print('      margin: 0;')
  print('    }')
  print('    .bigstats article > ul > li {')
  print('      list-style-type: none;')
  print('      background-color: var(--bg0);')
  print('      padding: var(--stdpadding);')
  print('      margin: var(--stdpadding);')
  print('    }')
  print('    .bigstats article > ul > li > details > ul {')
  print('      display: flex;')
  print('      flex-wrap: wrap;')
  print('      gap: calc(var(--stdpadding)/2);')
  print('      overflow-y: scroll;')
  print('      max-height: 20rem;')
  print('      padding-left: 0;')
  print('      margin-top: var(--stdpadding);')
  print('    }')
  print('    .bigstats article > ul > li > details > ul > li {')
  print('      list-style-type: none;')
  print('      padding: .5rem;')
  print('      background-color: var(--bg2);')
  print('    }')
  print('')
  print('    .bigstats article > ul > li > ul {')
  print('      list-style-type: none;')
  print('      padding-left: 0;')
  print('      display: flex;')
  print('      flex-direction: column;')
  print('      gap: calc(var(--stdpadding) / 2);')
  print('      margin-top: calc(var(--stdpadding) / 2);')
  print('    }')
  print('    .bigstats article > ul > li > ul > li {')
  print('      padding: calc(var(--stdpadding) / 2);')
  print('      background-color: var(--bg2);')
  print('      display: flex;')
  print('      align-items: center;')
  print('      gap: calc(var(--stdpadding) / 2);')
  print('    }')
  print('    .bigstats article > ul > li > ul > li svg {')
  print('      max-width: 1.5em;')
  print('      min-width: 1.5em;')
  print('    }')
  print('    .slfail svg, .slend svg {')
  print('      color: var(--red);')
  print('    }')
  print('    .slsuccess svg {')
  print('      color: var(--green);')
  print('    }')
  print('    .slsave svg {')
  print('      color: var(--blue);')
  print('    }')
  print('    .sessionlog * {')
  print('      word-wrap: anywhere;')
  print('    }')
  print('')
  print('    .piecontainer {')
  print('      display: flex;')
  print('      gap: var(--stdpadding);')
  print('      align-items: center;')
  print('      --sliceangle1: 72deg;')
  print('      --sliceangle2: 144deg;')
  print('      --sliceangle3: 216deg;')
  print('      --sliceangle4: 288deg;')
  print('    }')
  print('    .piechart {')
  print('      border-radius: 100%;')
  print('      width: min(20rem, 70vw);')
  print('      aspect-ratio: 1;')
  print('      display: flex;')
  print('      justify-content: center;')
  print('      align-items: center;')
  print('      filter: drop-shadow(2px 2px 2px #0004);')
  print('      background: conic-gradient(var(--pc1) 0deg 360deg);')
  print('    }')
  print('    .piechart > .piechart {')
  print('      background: conic-gradient(#0000 0deg var(--sliceangle1), var(--pc2) var(--sliceangle1) 360deg);')
  print('    }')
  print('    .piechart > .piechart > .piechart {')
  print('      background: conic-gradient(#0000 0deg var(--sliceangle2), var(--pc3) var(--sliceangle2) 360deg);')
  print('    }')
  print('    .piechart > .piechart > .piechart > .piechart {')
  print('      background: conic-gradient(#0000 0deg var(--sliceangle3), var(--pc4) var(--sliceangle3) 360deg);')
  print('    }')
  print('    .piechart > .piechart > .piechart > .piechart > .piechart {')
  print('      background: conic-gradient(#0000 0deg var(--sliceangle4), var(--pc5) var(--sliceangle4) 360deg);')
  print('    }')
  print('    .pielabel1::marker {')
  print('      content: "■ ";')
  print('      color: var(--pc1);')
  print('    }')
  print('    .pielabel2::marker {')
  print('      content: "■ ";')
  print('      color: var(--pc2);')
  print('    }')
  print('    .pielabel3::marker {')
  print('      content: "■ ";')
  print('      color: var(--pc3);')
  print('    }')
  print('    .pielabel4::marker {')
  print('      content: "■ ";')
  print('      color: var(--pc4);')
  print('    }')
  print('    .pielabel5::marker {')
  print('      content: "■ ";')
  print('      color: var(--pc5);')
  print('    }')
  print('')
  print('    @media screen and (max-width: 100vh) {')
  print('      .smallstats {')
  print('        flex-direction: column;')
  print('      }')
  print('      .piecontainer {')
  print('        flex-direction: column;')
  print('      }')
  print('    }')
  print('  </style>')
  print('</head>')
  print('<body>')
  print('  <header>')
  print('    <svg fill="gainsboro" height="3rem" viewBox="0 0 64 64" xmlns="http://www.w3.org/2000/svg"><g id="am"><path d="M57.13,42.78c-4.63-10.07-9.17-20.1-14.56-32.06-.38-.85-1.32-1.5-2.26-1.61l-.61-2.03c-.3-1.02-1.14-1.79-2.17-2.01l-4.21-.92c-.86-.19-1.77-.19-2.64,0l-4.21,.92c-1.04,.23-1.87,1-2.17,2.01l-.61,2.03c-.94,.1-1.88,.76-2.26,1.61-4.24,9.46-8.62,19.05-12.86,28.33l-1.71,3.73c-.21,.47-.27,1.02-.16,1.57,.11,.54,.38,1.03,.76,1.38l15.18,13.85c.44,.4,1.06,.53,1.61,.34,.56-.19,.98-.66,1.09-1.24l.99-5.11,4.17,2.54c.92,.56,2.05,.56,2.97,0l4.17-2.54,.99,5.11c.11,.58,.53,1.06,1.09,1.24,.17,.06,.34,.08,.51,.08,.4,0,.8-.15,1.1-.43l15.18-13.85c.78-.71,1.04-1.98,.6-2.94Zm-28.49-1.55l1.08-5.81h4.56l1.08,5.81h-6.72Zm7.09,2l.71,3.85h-8.89l.71-3.85h7.46Zm-2.53-13.66l.71,3.85h-3.82l.71-3.85h2.39Zm-2.02-2l.83-4.45,.82,4.45h-1.65Zm2.03-8.93h10.74c3.63,8.05,6.95,15.35,10.26,22.56l-19.71-15.6-1.29-6.96Zm-6.31-11.62l4.21-.92c.58-.13,1.2-.13,1.78,0l4.21,.92c.33,.07,.59,.31,.68,.63l.43,1.44h-12.44l.43-1.44c.1-.32,.36-.56,.68-.63Zm-3.64,4.52c.09-.21,.45-.44,.68-.44h16.12c.23,0,.59,.23,.68,.44,.8,1.77,1.54,3.41,2.3,5.1H20.95c.77-1.7,1.55-3.41,2.31-5.1Zm-3.21,7.1h10.75l-1.29,6.96-19.73,15.61,.61-1.34c3.18-6.96,6.43-14.1,9.66-21.24Zm3.47,39.02l-14.54-13.26,19.98-15.81-5.44,29.06Zm8.93-3.26c-.27,.17-.62,.17-.89,0l-4.81-2.93,.44-2.39h9.63l.44,2.39-4.81,2.93Zm8.04,3.26l-5.43-29.06,19.97,15.8-14.54,13.26Z" /></g></svg>')
  print('    <div>')
  print('      <h1>Cowrie Stats</h1>')
  print('      <p>' + session_timestamp(sessions[next(iter(sessions))])[:10] + ' &ndash; ' + session_timestamp(sessions[next(reversed(sessions))])[:10] + '</p>')
  print('    </div>')
  print('  </header>')
  print('  <main>')
  print('    <section class="smallstats">')
  print('      <article>')
  print('        <h5>Total Sessions</h5>')
  print('        '+str(len(sessions)))
  print('      </article>')
  print('      <article>')
  print('        <h5>Distinct Visitors</h5>')
  print('        '+str(len(attempt_counts_by_ip)))
  print('      </article>')
  print('      <article>')
  print('        <h5>Files Saved</h5>')
  print('        '+str(cnt_filessaved))
  print('      </article>')
  print('      <article>')
  print('        <h5>Log Parsing Time</h5>')
  print('        '+str(log_parsing_time)[:4]+'s')
  print('      </article>')
  print('      <article>')
  print('        <h5>Total Log Size</h5>')
  print('        '+sizeof_fmt(total_filesize))
  print('      </article>')
  print('      <article>')
  print('        <h5>Updated</h5>')
  print('        '+time.strftime("%Y-%m-%d %H:%M:%S%z"))
  print('      </article>')
  print('    </section>')

  if(args.pings or args.fails or args.logins or args.commands or args.eventful or args.filter_username or args.filter_password or args.filter_sensor or args.filter_ip):
    print('    <h2>Active Filters</h2>')
    print('    <section class="smallstats">')
    if(args.filter_ip):
      print('      <article>')
      print('        <h5>By IP</h5>')
      print('        '+args.filter_ip)
      print('      </article>')
    if(args.filter_username):
      print('      <article>')
      print('        <h5>By Username Used</h5>')
      print('        '+args.filter_username)
      print('      </article>')
    if(args.filter_password):
      print('      <article>')
      print('        <h5>By Password Used</h5>')
      print('        '+args.filter_password)
      print('      </article>')
    if(args.filter_sensor):
      print('      <article>')
      print('        <h5>By Sensor</h5>')
      print('        '+args.filter_sensor)
      print('      </article>')
    if(args.pings or args.fails or args.logins or args.commands or args.eventful):
      print('      <article>')
      print('        <h5>By Session Type</h5>')
      h_typefilters = '        '
      h_typefiltercnt = 0
      if(args.pings):
        h_typefilters += 'NoLogin'
        h_typefiltercnt += 1
      if(args.fails):
        if(h_typefiltercnt > 0):
          h_typefilters += ', '
        h_typefilters += 'Failed'
        h_typefiltercnt += 1
      if(args.logins):
        if(h_typefiltercnt > 0):
          h_typefilters += ', '
        h_typefilters += 'NoCommands'
        h_typefiltercnt += 1
      if(args.commands):
        if(h_typefiltercnt > 0):
          h_typefilters += ', '
        h_typefilters += 'Commands'
        h_typefiltercnt += 1
      if(args.eventful):
        if(h_typefiltercnt > 0):
          h_typefilters += ', '
        h_typefilters += 'Eventful'
      print(h_typefilters)
      print('      </article>')
    print('    </section>')
  print('    <section class="bigstats">')
  print('      <article>')
  print('        <h3>Sessions by Source IP</h3>')
  print('        <div class="piecontainer" style="')
  print('        --sliceangle1: '+str(1 - (top_n_percent_of_ips_session_percent(0.5)) / 100)+'turn;')
  print('        --sliceangle2: '+str(1 - (top_n_percent_of_ips_session_percent(0.1)) / 100)+'turn;')
  print('        --sliceangle3: '+str(1 - (top_n_percent_of_ips_session_percent(0.01)) / 100)+'turn;')
  print('        --sliceangle4: '+str(1 - (percent_of_all_sessions(attempt_counts_by_ip[next(iter(attempt_counts_by_ip))])) / 100)+'turn;')
  print('        ">')
  print('          <div class="piechart">')
  print('            <div class="piechart">')
  print('              <div class="piechart" style="width: 95%;">')
  print('                <div class="piechart" style="width: 95%;">')
  print('                  <div class="piechart" style="width: 95%;">')
  print('')
  print('                  </div>')
  print('                </div>')
  print('              </div>')
  print('            </div>')
  print('          </div>')
  print('          <div>')
  print('            <ul>')
  print('              <li class="pielabel1">'+str(100 - top_n_percent_of_ips_session_percent(0.5))+'% &ndash; Bottom 50%</li>')
  print('              <li class="pielabel2">'+str(top_n_percent_of_ips_session_percent(0.5))+'% &ndash; Top 50%</li>')
  print('              <li class="pielabel3">'+str(top_n_percent_of_ips_session_percent(0.1))+'% &ndash; Top 10%</li>')
  print('              <li class="pielabel4">'+str(top_n_percent_of_ips_session_percent(0.01))+'% &ndash; Top 1%</li>')
  print('              <li class="pielabel5">'+str(percent_of_all_sessions(attempt_counts_by_ip[next(iter(attempt_counts_by_ip))]))+'% &ndash; Top 1 ('+next(iter(attempt_counts_by_ip))+')</li>')
  print('            </ul>')
  print('          </div>')
  print('        </div>')
  print('      </article>')
  print('      <article>')
  print('        <h3>Sessions by Type</h3>')
  print('        <div class="piecontainer" style="')
  print('        --sliceangle1: '+str(1 - (percent_of_all_sessions(cnt_fails + cnt_lping + cnt_cmdping + cnt_eventful) / 100))+'turn;')
  print('        --sliceangle2: '+str(1 - (percent_of_all_sessions(cnt_lping + cnt_cmdping + cnt_eventful) / 100))+'turn;')
  print('        --sliceangle3: '+str(1 - (percent_of_all_sessions(cnt_cmdping + cnt_eventful) / 100))+'turn;')
  print('        --sliceangle4: '+str(1 - (percent_of_all_sessions(cnt_eventful) / 100))+'turn;')
  print('        ">')
  print('          <div class="piechart">')
  print('            <div class="piechart">')
  print('              <div class="piechart">')
  print('                <div class="piechart" style="width: 95%;">')
  print('                  <div class="piechart" style="width: 95%;">')
  print('')
  print('                  </div>')
  print('                </div>')
  print('              </div>')
  print('            </div>')
  print('          </div>')
  print('          <div>')
  print('            <ul>')
  print('              <li class="pielabel1">'+str(percent_of_all_sessions(cnt_pings))+'% &ndash; No attempt to log in</li>')
  print('              <li class="pielabel2">'+str(percent_of_all_sessions(cnt_fails))+'% &ndash; Failed logins</li>')
  print('              <li class="pielabel3">'+str(percent_of_all_sessions(cnt_lping + cnt_cmdping + cnt_eventful))+'% &ndash; Successful logins</li>')
  print('              <li class="pielabel4">'+str(percent_of_all_sessions(cnt_cmdping + cnt_eventful))+'% &ndash; Logins that ran commands</li>')
  print('              <li class="pielabel5">'+str(percent_of_all_sessions(cnt_eventful))+'% &ndash; Logins that ran unusual* commands</li>')
  print('            </ul>')
  print('            <p>*Not a subset of <code>'+str(cmdping_commands)+'</code></p>')
  print('          </div>')
  print('        </div>')
  print('      </article>')
  print('    </section>')
  print('    <section class="bigstats">')
  print('      <article>')
  print('        <h3>Attempts by username</h3>')
  print('        <p>Expand to show corresponding passwords</p>')
  print('        <ul>')
  for uname in passwords_by_username:
    print('          <li>')
    print('            <details>')
    print('              <summary>'+uname+' &ndash; '+str(attempt_counts_by_username[uname])+' Attempts</summary>')
    print('              <ul>')
    for pw in passwords_by_username[uname]:
      print('                <li>'+pw+'</li>')
    print('              </ul>')
    print('            </details>')
    print('          </li>')
  print('        </ul>')
  print('      </article>')
  print('      <article>')
  print('        <h3>Attempts by IP</h3>')
  print('        <p>Expand to show corresponding credential combos</p>')
  print('        <ul>')
  for ip in login_combos_by_ip:
    print('          <li>')
    print('            <details>')
    print('              <summary>'+ip+' &ndash; '+str(attempt_counts_by_ip[ip])+' Attempts</summary>')
    print('              <ul>')
    for combo in login_combos_by_ip[ip]:
      print('                <li>'+combo[0]+' : '+combo[1]+'</li>')
    print('              </ul>')
    print('            </details>')
    print('          </li>')
  print('        </ul>')
  print('      </article>')
  print('      <article>')
  print('        <h3>Total Attempts Per Password</h3>')
  print('        <ul>')
  for pw in attempt_counts_by_password:
    if(pw =='[SSH_PUBKEY_ATTEMPT]'):
      print('          <li style="display: flex; align-items: center; gap: calc(var(--stdpadding) / 2)"><svg style="width: 1.5em;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M15.75 1.5a6.75 6.75 0 0 0-6.651 7.906c.067.39-.032.717-.221.906l-6.5 6.499a3 3 0 0 0-.878 2.121v2.818c0 .414.336.75.75.75H6a.75.75 0 0 0 .75-.75v-1.5h1.5A.75.75 0 0 0 9 19.5V18h1.5a.75.75 0 0 0 .53-.22l2.658-2.658c.19-.189.517-.288.906-.22A6.75 6.75 0 1 0 15.75 1.5Zm0 3a.75.75 0 0 0 0 1.5A2.25 2.25 0 0 1 18 8.25a.75.75 0 0 0 1.5 0 3.75 3.75 0 0 0-3.75-3.75Z" clip-rule="evenodd" /></svg> (SSH Public Key) × '+str(attempt_counts_by_password[pw])+'</li>')
    else:
      print('          <li>'+pw+' × '+str(attempt_counts_by_password[pw])+'</li>')
  print('        </ul>')
  print('      </article>')
  if(cnt_eventful > 0):
    print('      <article>')
    print('        <h3>')
    print('          <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6" style="color: var(--pc5); height: 1.2em;">')
    print('            <path fill-rule="evenodd" d="M2.25 13.5a8.25 8.25 0 0 1 8.25-8.25.75.75 0 0 1 .75.75v6.75H18a.75.75 0 0 1 .75.75 8.25 8.25 0 0 1-16.5 0Z" clip-rule="evenodd" />')
    print('            <path fill-rule="evenodd" d="M12.75 3a.75.75 0 0 1 .75-.75 8.25 8.25 0 0 1 8.25 8.25.75.75 0 0 1-.75.75h-7.5a.75.75 0 0 1-.75-.75V3Z" clip-rule="evenodd" />')
    print('          </svg>')
    print('          Sessions of Particular Note')
    print('        </h3>')
    print('        <ul>')
    for s_id in sessions:
      session = sessions[s_id]
      if(session_ran_command(session) and not session_is_cmdping(session)):
        print('          <li>')
        print('            '+session_ip(session)+' @ '+session_timestamp(session)[:19].replace('T', ' ')+':')
        print('            <ul class="sessionlog">')
        for entry in session:
          match(entry["eventid"]):
            case "cowrie.login.failed":
              print('              <li class="slfail">')
              print('                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M12 2.25c-5.385 0-9.75 4.365-9.75 9.75s4.365 9.75 9.75 9.75 9.75-4.365 9.75-9.75S17.385 2.25 12 2.25Zm-1.72 6.97a.75.75 0 1 0-1.06 1.06L10.94 12l-1.72 1.72a.75.75 0 1 0 1.06 1.06L12 13.06l1.72 1.72a.75.75 0 1 0 1.06-1.06L13.06 12l1.72-1.72a.75.75 0 1 0-1.06-1.06L12 10.94l-1.72-1.72Z" clip-rule="evenodd" /></svg>')
              pw = entry['password']
              if(pw =='[SSH_PUBKEY_ATTEMPT]'):
                pw = '<svg style="width: 1.5em;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M15.75 1.5a6.75 6.75 0 0 0-6.651 7.906c.067.39-.032.717-.221.906l-6.5 6.499a3 3 0 0 0-.878 2.121v2.818c0 .414.336.75.75.75H6a.75.75 0 0 0 .75-.75v-1.5h1.5A.75.75 0 0 0 9 19.5V18h1.5a.75.75 0 0 0 .53-.22l2.658-2.658c.19-.189.517-.288.906-.22A6.75 6.75 0 1 0 15.75 1.5Zm0 3a.75.75 0 0 0 0 1.5A2.25 2.25 0 0 1 18 8.25a.75.75 0 0 0 1.5 0 3.75 3.75 0 0 0-3.75-3.75Z" clip-rule="evenodd" /></svg> (SSH Public Key)'
              print('                ' + entry["username"] + ' : ' + pw)
              print('              </li>')
            case "cowrie.login.success":
              print('              <li class="slsuccess">')
              print('                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M2.25 12c0-5.385 4.365-9.75 9.75-9.75s9.75 4.365 9.75 9.75-4.365 9.75-9.75 9.75S2.25 17.385 2.25 12Zm13.36-1.814a.75.75 0 1 0-1.22-.872l-3.236 4.53L9.53 12.22a.75.75 0 0 0-1.06 1.06l2.25 2.25a.75.75 0 0 0 1.14-.094l3.75-5.25Z" clip-rule="evenodd" /></svg>')
              pw = entry['password']
              if(pw =='[SSH_PUBKEY_ATTEMPT]'):
                pw = '<svg style="width: 1.5em;" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M15.75 1.5a6.75 6.75 0 0 0-6.651 7.906c.067.39-.032.717-.221.906l-6.5 6.499a3 3 0 0 0-.878 2.121v2.818c0 .414.336.75.75.75H6a.75.75 0 0 0 .75-.75v-1.5h1.5A.75.75 0 0 0 9 19.5V18h1.5a.75.75 0 0 0 .53-.22l2.658-2.658c.19-.189.517-.288.906-.22A6.75 6.75 0 1 0 15.75 1.5Zm0 3a.75.75 0 0 0 0 1.5A2.25 2.25 0 0 1 18 8.25a.75.75 0 0 0 1.5 0 3.75 3.75 0 0 0-3.75-3.75Z" clip-rule="evenodd" /></svg> (SSH Public Key)'
              print('                ' + entry["username"] + ' : ' + pw)
              print('              </li>')
            case "cowrie.command.input":
              print('              <li class="slcmd">')
              print('                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M2.25 6a3 3 0 0 1 3-3h13.5a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3H5.25a3 3 0 0 1-3-3V6Zm3.97.97a.75.75 0 0 1 1.06 0l2.25 2.25a.75.75 0 0 1 0 1.06l-2.25 2.25a.75.75 0 0 1-1.06-1.06l1.72-1.72-1.72-1.72a.75.75 0 0 1 0-1.06Zm4.28 4.28a.75.75 0 0 0 0 1.5h3a.75.75 0 0 0 0-1.5h-3Z" clip-rule="evenodd" /></svg>')
              print('                <code>'+entry['input']+'</code>')
              print('              </li>')
            case "cowrie.session.file_download":
              df = "file"
              if("url" in entry):
                df = entry["url"]
              elif("destfile" in entry):
                df = entry["destfile"]
              print('              <li class="slsave">')
              print('                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M12 2.25a.75.75 0 0 1 .75.75v11.69l3.22-3.22a.75.75 0 1 1 1.06 1.06l-4.5 4.5a.75.75 0 0 1-1.06 0l-4.5-4.5a.75.75 0 1 1 1.06-1.06l3.22 3.22V3a.75.75 0 0 1 .75-.75Zm-9 13.5a.75.75 0 0 1 .75.75v2.25a1.5 1.5 0 0 0 1.5 1.5h13.5a1.5 1.5 0 0 0 1.5-1.5V16.5a.75.75 0 0 1 1.5 0v2.25a3 3 0 0 1-3 3H5.25a3 3 0 0 1-3-3V16.5a.75.75 0 0 1 .75-.75Z" clip-rule="evenodd" /></svg>')
              print('                Saved '+df+' to '+entry["outfile"][:50]+'...')
              print('              </li>')
        print('              <li class="slend">')
        print('                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="currentColor" class="size-6"><path fill-rule="evenodd" d="M5.47 5.47a.75.75 0 0 1 1.06 0L12 10.94l5.47-5.47a.75.75 0 1 1 1.06 1.06L13.06 12l5.47 5.47a.75.75 0 1 1-1.06 1.06L12 13.06l-5.47 5.47a.75.75 0 0 1-1.06-1.06L10.94 12 5.47 6.53a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" /></svg>')
        print('                Closed after '+str(session_duration(session))+'s')
        print('              </li>')
        print('            </ul>')
        print('          </li>')
    print('        </ul>')
    print('      </article>')
    print('    </section>')
  print('  </main>')
  print('  <footer><span>Generated by Cowrieder</span> <a href="https://git.isopod.cool/root/cowrieder">Source</a> <a href="https://www.cowrie.org/">Cowrie</a> <a href="https://www.svgrepo.com/svg/423906/bee-origami-paper">Bee</a> <a href="https://heroicons.com/solid">Other Icons</a> <a href="https://github.com/sainnhe/sonokai">Colours</a> <span style="text-align: right; flex: 1;">🏳️‍⚧️ 🇵🇸</span></footer>')
  print('</body>')