-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy path__init__.py
1387 lines (1236 loc) · 70.4 KB
/
__init__.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
"""
**title**: TinyWeatherForecastGermany - exodusprivacy local apk scan
**author**: Jean-Luc Tibaux (https://gitlab.com/eUgEntOptIc44)
**license**: GPLv3 (https://github.com/twfgcicdbot/TinyWeatherForecastGermanyScan/blob/d19eb5eeeda3649ecd93a3b52f018878dd24ec81/LICENSE)
**since**: August 2021
**url**: https://twfgcicdbot.github.io/TinyWeatherForecastGermanyScan/
## Disclaimer
No warranty of any kind provided. Use at your own risk only.
Not meant to be used in commercial or in general critical/productive environments at all.
"""
import json
import logging
import shutil
import sys
from collections import defaultdict
from datetime import datetime
from pathlib import Path
from pprint import pprint
from random import SystemRandom
import htmlmin
import markdown
import regex
import requests
from bs4 import BeautifulSoup
from dateutil.tz import (
tzutc, # timezone UTC -> docs: https://dateutil.readthedocs.io/en/stable/tz.html#dateutil.tz.tzutc
)
from exodus_core.analysis.static_analysis import StaticAnalysis
from markdown.extensions.toc import TocExtension
from permissions_en import AOSP_PERMISSIONS_EN
# required to use cryptographically secure random functions
cryptogen = SystemRandom()
working_dir = Path("TinyWeatherForecastGermanyScan")
# create directory if not exists
working_dir.mkdir(parents=True, exist_ok=True)
log_p = working_dir / "debug.log"
try:
logging.basicConfig(
format="%(asctime)-s %(levelname)s [%(name)s]: %(message)s",
level=logging.DEBUG,
handlers=[
logging.FileHandler(str(log_p.absolute()), encoding="utf-8"),
logging.StreamHandler(),
],
)
except Exception as error_msg:
logging.error(f"while logger init! -> error: {error_msg}")
java_dir = Path("TinyWeatherForecastGermanyMirror")
if not java_dir.exists():
logging.error(
f"failed to locate '{java_dir.absolute()}' -> permissions missing or the directory does not exists!"
)
gitlab_pages_url = "https://tinyweatherforecastgermanygroup.gitlab.io/index/"
# sources of user agent data -> License: MIT
# -> https://github.com/tamimibrahim17/List-of-user-agents/blob/master/Chrome.txt
# -> https://github.com/tamimibrahim17/List-of-user-agents/blob/master/Firefox.txt
user_agents = [
"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2919.83 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/54.0.2866.71 Safari/537.36",
"Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2820.59 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2762.73 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/49.0.2656.18 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML like Gecko) Chrome/44.0.2403.155 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2228.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.1 Safari/537.36",
"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2227.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2226.0 Safari/537.36",
"Mozilla/5.0 (Windows NT 6.4; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2225.0 Safari/537.36",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10; rv:33.0) Gecko/20100101 Firefox/33.0",
"Mozilla/5.0 (Windows ME 4.9; rv:31.0) Gecko/20100101 Firefox/31.7",
"Mozilla/5.0 (X11; Linux i586; rv:31.0) Gecko/20100101 Firefox/31.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:31.0) Gecko/20130401 Firefox/31.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:28.0) Gecko/20100101 Firefox/31.0",
"Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:29.0) Gecko/20120101 Firefox/29.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/29.0",
"Mozilla/5.0 (X11; OpenBSD amd64; rv:28.0) Gecko/20100101 Firefox/28.0",
"Mozilla/5.0 (X11; Linux x86_64; rv:28.0) Gecko/20100101 Firefox/28.0",
"Mozilla/5.0 (Windows NT 6.1; rv:27.3) Gecko/20130101 Firefox/27.3",
"Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:27.0) Gecko/20121011 Firefox/27.0",
"Mozilla/5.0 (Windows NT 6.2; rv:20.0) Gecko/20121202 Firefox/26.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.6; rv:25.0) Gecko/20100101 Firefox/25.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0) Gecko/20100101 Firefox/24.0",
"Mozilla/5.0 (Windows NT 6.0; WOW64; rv:24.0) Gecko/20100101 Firefox/24.0",
"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:24.0) Gecko/20100101 Firefox/24.0",
"Mozilla/5.0 (Windows NT 6.2; rv:22.0) Gecko/20130405 Firefox/23.0",
"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20130406 Firefox/23.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:23.0) Gecko/20131011 Firefox/23.0",
"Mozilla/5.0 (Windows NT 6.2; rv:22.0) Gecko/20130405 Firefox/22.0",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:22.0) Gecko/20130328 Firefox/22.0",
"Mozilla/5.0 (Windows NT 6.1; rv:22.0) Gecko/20130405 Firefox/22.0",
"Mozilla/5.0 (Microsoft Windows NT 6.2.9200.0); rv:22.0) Gecko/20130405 Firefox/22.0",
"Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/21.0.1",
"Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:16.0.1) Gecko/20121011 Firefox/21.0.1",
"Mozilla/5.0 (Windows NT 6.2; Win64; x64; rv:21.0.0) Gecko/20121011 Firefox/21.0.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20130331 Firefox/21.0",
"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:21.0) Gecko/20100101 Firefox/21.0",
"Mozilla/5.0 (X11; Linux i686; rv:21.0) Gecko/20100101 Firefox/21.0",
]
cryptogen.shuffle(user_agents)
user_agent = str(cryptogen.choice(user_agents))
logging.debug(f"querying data as '{user_agent}'")
headers = {"User-Agent": user_agent, "DNT": "1"}
search_cb_req = requests.get(
"https://codeberg.org/api/v1/repos/Starfish/TinyWeatherForecastGermany/releases?limit=1",
headers=headers,
timeout=50,
)
try:
search_cb_json = search_cb_req.json()
logging.debug("fetched Codeberg data")
except Exception as error_msg:
logging.error(f"codeberg api request failed! -> error: {error_msg}")
if len(search_cb_json) == 1 and search_cb_json is not None:
twfg_json = search_cb_json[0]
pprint(twfg_json)
if twfg_json is None:
logging.error("content of key 'results' in codeberg json response is 'None'")
try:
pprint(str(search_cb_req.headers))
pprint(str(search_cb_req.text))
except Exception as error_msg:
logging.error(
f"failed to print request raw data to console! -> error: {error_msg}"
)
sys.exit(1)
twfg_asset = twfg_json["assets"][0]
apk_url = str(twfg_asset["browser_download_url"])
apk_name = str(twfg_asset["name"])
apk_path = working_dir / apk_name
if not apk_path.exists():
logging.debug(f"downloading '{apk_name}' from -> {apk_url} ...")
response = requests.get(apk_url, stream=True, headers=headers, timeout=30)
with open(str(apk_path.absolute()), "wb") as out_file:
shutil.copyfileobj(response.raw, out_file)
del response
else:
logging.info(
f"skipped download of '{apk_name}' file '{apk_path}' already exists"
)
logging.debug(f"file name: {apk_name}")
logging.debug(f"file path: {apk_path.absolute()}")
try:
apk_files = list(working_dir.glob("*.apk"))
pprint(apk_files)
if len(apk_files) > 0:
for apk_file_tmp in apk_files:
try:
logging.debug(
f"apk file '{apk_file_tmp.absolute()}' "
f"-> size: {apk_file_tmp.stat().st_size}"
)
result_dict = {}
result_markdown = ""
# init ExodusPrivacy StaticAnalysis for 'apkFileTemp'
analysis_temp = StaticAnalysis(str(apk_file_tmp.absolute()))
try:
analysis_temp.print_apk_infos()
except Exception as error_msg:
logging.error(
f"printing of 'apk_infos' to console failed!"
f" -> error: {error_msg}"
)
# --- start of apk_infos ---
try:
apk_name = str(analysis_temp.get_app_name())
if apk_name != "None":
logging.debug(
f"static analysis returned app name: {apk_name}"
)
result_dict["name"] = apk_name
result_markdown += "# " + apk_name + "\n\n"
else:
result_markdown += "# apk name missing \n\n"
logging.error(
f"parsing of 'get_app_name()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is 'None'!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_app_name()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "# apk name missing \n\n"
result_markdown += "\n\n[TOC]\n\n"
result_markdown += "\n## Metadata\n\n"
try:
apk_package = str(analysis_temp.get_package())
if apk_package != "None":
logging.debug(
f"static analysis returned app package: {apk_package}"
)
result_dict["package"] = apk_package
result_markdown += (
f"* **package**: [{apk_package}](https://f-droid.org/packages/{apk_package}/)"
+ "{ title='F-Droid Store package site' #fdroidproductpage } \n"
)
else:
result_markdown += "* **package**: *unknown* \n"
logging.error(
f"parsing of 'get_package()' for apk '{apk_file_tmp}' failed! -> error: result is 'None'!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_package()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "* **package**: *unknown* \n"
try:
apk_sum = str(analysis_temp.get_sha256())
if apk_sum != "None":
logging.debug(
f"static analysis returned apk hash (sha256): {apk_sum}"
)
result_dict["hash_sha256"] = apk_sum
result_markdown += (
f"* **sha256 hash**: [{apk_sum}](https://www.virustotal.com/gui/file/{apk_sum}/detection)"
+ "{ title='click to get the VirusTotal report' #virustotalhash } \n"
)
try:
sha_path = Path(working_dir / "sha256.html")
with open(
str(sha_path.absolute()), "w+", encoding="utf-8"
) as fh:
fh.write(str(apk_sum))
except Exception as error_msg:
logging.error(
f"failed to write sha256 hash to '{sha_path}' -> error: {error_msg}"
)
else:
result_markdown += "* **sha256 hash**: *unknown* \n"
logging.error(
f"parsing of 'get_sha256()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is 'None'!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_sha256()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "* **sha256 hash**: *unknown* \n"
try:
apk_version = str(analysis_temp.get_version())
if apk_version != "None":
logging.debug(
f"static analysis returned apk version: {apk_version}"
)
result_dict["version"] = apk_version
result_markdown += f"* **version**: {apk_version}\n"
else:
result_markdown += "* **version**: *unknown* \n"
logging.error(
f"parsing of 'get_version()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is 'None'!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_version()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "* **version**: *unknown* \n"
try:
apk_v_code = str(analysis_temp.get_version_code()).replace("None", "")
if len(apk_v_code) > 1:
logging.debug(
f"static analysis returned apk version code: {apk_v_code}"
)
result_dict["version_code"] = apk_v_code
result_markdown += f"* **version code**: {apk_v_code}\n"
else:
result_markdown += "* **version code**: *unknown* \n"
logging.error(
f"parsing of 'get_version_code()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is None!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_version_code()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "* **version code**: *unknown* \n"
try:
apk_uid = str(analysis_temp.get_application_universal_id())
if apk_uid != "None":
logging.debug(
f"static analysis returned apk UID: {apk_uid}"
)
result_dict["UID"] = apk_uid
result_markdown += (
"* [**app UID**](https://stackoverflow.com/a/5709279){ title='android app UID"
" explanation on StackOverflow' }: "
f"{apk_uid} \n"
)
else:
result_markdown += "* [**app UID**](https://stackoverflow.com/a/5709279){ title='android app UID explanation on StackOverflow' }: *unknown* \n"
logging.error(
f"parsing of 'get_application_universal_id()' (UID) for apk '{apk_file_tmp}' failed!"
f" -> error: result is None!"
)
except Exception as error_msg:
logging.error(
f"parsing of 'get_application_universal_id()' (UID) for apk '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
)
result_markdown += "* **app UID**: *unknown* \n"
logging.debug("working on permissions ... ")
result_markdown += "\n## Permissions \n"
try:
permissions = analysis_temp.get_permissions()
if permissions is not None:
len_perms = len(permissions)
logging.debug(
f"static analysis returned {len_perms} permission(s)"
)
result_markdown += (
f"\n {len_perms} permissions detected \n\n"
)
result_dict["permissions"] = []
if len_perms > 0:
# pprint(permissions)
result_markdown += '<ul id="permissions-list">'
for permission_tmp in permissions:
try:
permissionDictTemp = AOSP_PERMISSIONS_EN[
"permissions"
][str(permission_tmp).strip()]
permission_desc = (
str(permissionDictTemp["description"])
.replace("\n", "")
.strip()
)
permission_desc = regex.sub(
r"(?im)\n", "", permission_desc
)
while " " in permission_desc:
permission_desc = regex.sub(
r"(?im)( )+", " ", permission_desc
)
permissionDictTemp[
"description"
] = permission_desc
pprint(permissionDictTemp)
except Exception as error_msg:
permissionDictTemp = {
"name": str(permission_tmp)
}
permission_desc = ""
logging.error(
f"parsing of exodus knowledge data for permission '{permission_tmp}'"
f" of '{apk_file_tmp}' failed! -> error: {error_msg}"
)
try:
result_dict["permissions"].append(
permissionDictTemp
)
result_markdown += f'<li><b class="permission-title">{permission_tmp}</b> '
if (
len(
str(permission_desc)
.lower()
.replace("none", "")
)
> 5
):
p_desc_slug = regex.sub(
r"(?im)[^A-z\d]+",
"",
str(permission_tmp),
)
result_markdown += f'<p id="permission-desc-{p_desc_slug} class="permission-description">{permission_desc}</p>'
result_markdown += "</li>\n"
except Exception as error_msg:
logging.error(
f"saving of permission '{permission_tmp}' of '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
)
result_markdown += "</ul>"
else:
logging.debug(
"skipping iteration of permissions as 'lenPermissions' is "
+ str(len_perms)
)
else:
result_markdown += (
"\n **failed** to detect permissions! \n\n"
)
logging.error(
f"parsing of 'permissions' for apk '{apk_file_tmp}' failed! -> error: result is None!"
)
except Exception as error_msg:
result_markdown += "\n **failed** to detect permissions! \n\n"
logging.error(
f"parsing of 'permissions' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
logging.debug("working on libraries ... ")
result_markdown += "\n## Libraries \n"
try:
libraries = analysis_temp.get_libraries()
if libraries is not None:
len_libraries = len(libraries)
logging.debug(
f"static analysis returned {len_libraries} libraries "
)
result_markdown += (
f"\n {len_libraries} libraries detected \n\n"
)
result_dict["libraries"] = []
if len_libraries > 0:
for libraryTemp in libraries:
try:
result_dict["libraries"].append(
str(libraryTemp)
)
result_markdown += (
"* " + str(libraryTemp) + " \n"
)
except Exception as error_msg:
logging.error(
f"saving of library '{libraryTemp}' of '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
)
else:
logging.debug(
f"skipping iteration of libraries as 'lenLibraries' is {len_libraries}"
)
else:
result_markdown += "\n **failed** to detect libraries! \n\n"
logging.error(
f"parsing of 'libraries' for apk '{apk_file_tmp}' failed! -> error: result is None!"
)
except Exception as error_msg:
result_markdown += "\n **failed** to detect libraries! \n\n"
logging.error(
f"parsing of 'libraries' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
result_markdown += "\n## Certificates\n"
try:
certificates = analysis_temp.get_certificates()
if certificates is not None:
len_certs = len(certificates)
logging.debug(
f"static analysis returned {len_certs} certificate(s)"
)
result_markdown += (
f"\n {len_certs} certificate(s) detected \n\n"
)
result_dict["certificates"] = []
if len_certs > 0:
for cert_tmp in certificates:
cert_temp_str = str(cert_tmp)
cert_temp_md = cert_temp_str
try:
cert_temp_str = "Issuer: {} \n Subject: {} \n Fingerprint: {} \n Serial: {}".format(
cert_tmp.issuer,
cert_tmp.subject,
cert_tmp.fingerprint,
cert_tmp.serial,
)
if (
str(cert_tmp.issuer).strip().lower()
== str(cert_tmp.subject)
.strip()
.lower()
):
cert_temp_md = '\n<details class="cert-details">\n<summary>click to expand</summary>\n\n<b>Issuer</b>: {} <br><b>Fingerprint</b>: <span>{}</span> <br><b>Serial</b>: {}<br></details>\n'.format(
cert_tmp.issuer,
cert_tmp.fingerprint,
cert_tmp.serial,
)
else:
cert_temp_md = '\n<details class="cert-details">\n<summary>click to expand</summary>\n\n<b>Issuer</b>: {} <br><b>Subject</b>: {} <br><b>Fingerprint</b>: <span>{}</span> <br><b>Serial</b>: {}<br></details>\n'.format(
cert_tmp.issuer,
cert_tmp.subject,
cert_tmp.fingerprint,
cert_tmp.serial,
)
except Exception as error_msg:
logging.warning(
f"serializing of certificate '{cert_tmp}' of '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
f" using fallback solution"
)
try:
result_dict["certificates"].append(
str(cert_temp_str)
)
result_markdown += f"{cert_temp_md} \n\n"
except Exception as error_msg:
logging.error(
f"saving of certificate '{cert_tmp}' of '{apk_file_tmp}'"
f" failed! -> error: {error_msg}"
)
else:
logging.debug(
f"skipping iteration of certificates as 'lenCertificates' is {len_certs}"
)
else:
result_markdown += (
"\n **failed** to detect certificates! \n\n"
)
logging.error(
f"parsing of 'certificates' for apk '{apk_file_tmp}' failed! -> error: result is None!"
)
except Exception as error_msg:
result_markdown += "\n **failed** to detect certificates! \n\n"
logging.error(
f"parsing of 'certificates' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
# --- end of apk_infos ---
# --- start of embedded_trackers ---
logging.debug("working on embedded_trackers ... ")
try:
analysis_temp.print_embedded_trackers()
except Exception as error_msg:
logging.error(
f"printing of 'embedded_trackers' to console failed! -> error: {error_msg}"
)
result_markdown += "\n## Trackers\n"
try:
embed_trackers = analysis_temp.detect_trackers()
if embed_trackers is not None:
len_embed_trackers = len(embed_trackers)
logging.debug(
f"static analysis returned {len_embed_trackers} tracker(s): {embed_trackers}"
)
result_markdown += f"\n<details>\n<summary>{len_embed_trackers} tracker(s) detected</summary>\n\n<ul>"
result_dict["trackers"] = []
if len_embed_trackers > 0:
for embed_tracker_tmp in embed_trackers:
try:
result_dict["trackers"].append(
str(embed_tracker_tmp)
)
result_markdown += (
f"<li>{embed_tracker_tmp}</li> \n"
)
except Exception as error_msg:
logging.error(
f"saving of tracker '{embed_tracker_tmp}' from '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
)
else:
logging.debug(
f"skipping iteration of trackers as 'len_embed_trackers' is {len_embed_trackers}"
)
result_markdown += "\n</ul>\n</details>\n\n"
else:
result_markdown += "\n **failed** to detect trackers! \n\n"
logging.error(
f"parsing of 'detect_trackers()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is 'None'!"
)
except Exception as error_msg:
result_markdown += "\n **failed** to detect trackers! \n\n"
logging.error(
f"parsing of 'detect_trackers()' for apk '{apk_file_tmp}' failed! -> error: {error_msg}"
)
# --- end of embedded_trackers ---
# --- start of embedded_classes ---
logging.debug("working on classes ... ")
result_markdown += "\n## Classes\n"
try:
embbed_classes = analysis_temp.get_embedded_classes()
if embbed_classes is not None:
len_embbed_cls = len(embbed_classes)
logging.debug(
f"static analysis returned {len_embbed_cls} class(es): {embbed_classes}"
)
# based on: https://gist.github.com/hrldcpr/2012250
def tree():
return defaultdict(tree)
def add_leafs(t, node_list):
for node in node_list:
t = t[node]
# classes tree
cls_tree = tree()
cls_dict = {}
for class_tmp in embbed_classes:
try:
class_parts = list(class_tmp.split("/"))
add_leafs(cls_tree, class_parts)
cls_dict[class_parts[-1]] = class_tmp.replace(
class_parts[-1], ""
).strip("/")
except Exception as error_msg:
logging.error(
f"failed to parse class -> error: {error_msg}"
)
print_cls_result = f"<details><summary>{len(list(class_tmp))} class(es) detected</summary>\n"
def print_classes_tree(tree, result, level):
for leaf in list(tree):
lvl_indent = ""
for level_index in range(0, level):
lvl_indent += "-"
sub_classes_count = len(list(dict(tree[leaf])))
leaf_name = str(leaf)
if level == 1:
leaf_name = f"<b>{leaf_name}</b>"
if sub_classes_count > 0:
result += (
'\t<details><summary class="classes-tree-child" id="classes-tree-child-'
+ str(level + 1)
+ "-"
+ str(sub_classes_count)
+ '" title="contains '
+ str(sub_classes_count)
+ ' subclass(es)">|'
+ str(lvl_indent)
+ "> "
+ str(leaf_name)
+ "</summary>\n"
)
else:
docs_a = ""
source_a = ""
if leaf_name in cls_dict:
class_path = cls_dict[leaf_name]
if (
class_path[0:3] == "de/"
or "nodomain/freeyourgadget"
in class_path
or "org/astronomie" in class_path
):
c_java_p = Path(
f"app/src/main/java/{class_path}/{leaf_name}.java"
)
c_java_p_local = java_dir / c_java_p
# parsing files to get line numbers
if c_java_p_local.exists():
try:
java_lines = []
with open(
c_java_p_local,
"r",
encoding="utf-8",
) as file_handle:
java_lines = file_handle.read().split(
"\n"
)
for (
jl_index,
java_line,
) in enumerate(java_lines):
if (
f"class {c_java_p_local.stem}"
in java_line
):
logging.debug(
f"found class in line #{jl_index+1}"
f" -> '{java_line.strip()}'"
)
c_java_p = f"{c_java_p}#L{jl_index+1}"
break
except Exception as error_msg:
logging.error(
f"while searching line number of class "
f"'{c_java_p_local.stem}' in {c_java_p_local}"
f" -> error: {error_msg}"
)
else:
logging.error(
f"failed to search line number of class '{c_java_p_local.stem}'"
f" in {c_java_p_local.absolute()}"
f" -> error: failed to find java file."
)
source_a = (
' -> <a class="subclass-source" title="open source at codeberg.org"'
+ ' target="_blank" href="https://codeberg.org/Starfish/TinyWeatherForecastGermany/src/branch/master/'
+ str(c_java_p)
+ '">source</a>'
)
docs_a = (
' -> <a class="subclass-docs" title="open javadocs" target="_blank"'
+ ' href="https://tinyweatherforecastgermanygroup.gitlab.io/twfg-javadoc/'
+ str(class_path)
+ "/"
+ str(leaf_name)
+ '.html">docs</a>'
)
result += (
'\t<span class="classes-tree-child subclass-child" id="classes-tree-child-'
+ str(level + 1)
+ "-"
+ str(sub_classes_count)
+ '" data-path="'
+ str(class_path)
+ str(leaf_name)
+ '.java" title="subclass '
+ str(leaf_name)
+ '">|'
+ str(lvl_indent)
+ "> "
+ str(leaf_name)
+ str(source_a)
+ str(docs_a)
+ "</span>\n"
)
if sub_classes_count > 0:
result = print_classes_tree(
tree[leaf], result, level + 1
)
if sub_classes_count > 0:
result += "</details>"
return result
print_cls_result = str(
print_classes_tree(dict(cls_tree), print_cls_result, 1)
)
print_cls_result += "</details>\n"
result_markdown += "\n" + print_cls_result + "\n"
else:
result_markdown += "\n **failed** to detect classes! \n\n"
logging.error(
f"parsing of 'get_embedded_classes()' for apk '{apk_file_tmp}' failed!"
f" -> error: result is 'None'!"
)
except Exception as error_msg:
result_markdown += "\n **failed** to detect classes! \n\n"
logging.error(
f"parsing of 'get_embedded_classes()' for apk '{apk_file_tmp}' failed!"
f" -> error: {error_msg}"
)
# --- end of embedded_classes ---
utc_timestamp = str(
datetime.now(tzutc()).strftime("%Y-%m-%d at %H:%M (%Z)")
)
result_markdown += f"\n\nThis report was generated on {utc_timestamp} using [`exodus-core`](https://github.com/Exodus-Privacy/exodus-core/).\n"
try:
try:
# list of named tuples -> also see: https://stackoverflow.com/questions/26180528/convert-a-namedtuple-into-a-dictionary
tracker_sigs = list(analysis_temp.signatures)
except Exception as error_msg:
tracker_sigs = []
logging.error(
f"while trying to save tracker signatures -> error: {error_msg}"
)
if len(tracker_sigs) > 0:
tracker_sigs_raw = tracker_sigs
tracker_sigs = []
for tracker_sig in tracker_sigs_raw:
try:
tracker_sigs.append(tracker_sig._asdict())
except Exception as error_msg:
logging.error(
f"while trying to parse tracker signature '{tracker_sig}'"
f" -> error: {error_msg}"
)
else:
logging.error(
"while trying to parse tracker signatures -> error: data length is invalid!"
)
tracker_sigs_file = working_dir / "tracker-signatures.json"
with open(tracker_sigs_file, "w+", encoding="utf-8") as fh:
fh.write(str(json.dumps(tracker_sigs, indent=4)))
logging.debug(
f"created tracker signature dump '{tracker_sigs_file}'"
f" ({tracker_sigs_file.stat().st_size}) "
)
result_markdown += (
"\nThe analysis has been conducted using "
+ str(len(analysis_temp.signatures))
+ " tracker signatures by [ExodusPrivacy](https://exodus-privacy.eu.org/)."
)
except Exception as error_msg:
logging.error(
f"while trying to save tracker signatures -> error: {error_msg}"
)
an_json_p = working_dir / "analysis-result.json"
try:
with open(an_json_p, "w+", encoding="utf-8") as fh:
fh.write(str(json.dumps(result_dict, indent=4)))
logging.debug(
f"created report '{an_json_p}' ({an_json_p.stat().st_size}) "
)
except Exception as error_msg:
logging.error(
f"while trying to save analysis result as json file '{an_json_p}' -> error: {error_msg}"
)
an_md_p = working_dir / "analysis-result.md"
try:
with open(an_md_p, "w+", encoding="utf-8") as fh:
fh.write(str(result_markdown))
logging.debug(
f"created report '{an_md_p}' ({an_md_p.st_size}) "
)
except Exception as error_msg:
logging.error(
f"while trying to save analysis result as markdown file '{an_md_p}' -> error: {error_msg}"
)
try:
index_html_req = requests.get(
f"{gitlab_pages_url}index.html",
headers=headers,
timeout=20,
)
ix_html_content = str(index_html_req.text).strip()
ix_html_content = ix_html_content.replace(
"Last update of this GitLab Pages page",
"Last update of this GitHub Pages page",
)
index_html_soup = BeautifulSoup(
ix_html_content, features="html.parser"
)
for tagGroup in [
index_html_soup.select("#repo-latest-release-container"),
index_html_soup.select("#readme-content-container"),
index_html_soup.select("#readme-content-container"),
]:
for tag in tagGroup:
tag.decompose()
indexMarkdownSoup = BeautifulSoup(
'<div role="document" aria-label="ExodusPrivacy tracker report'
+ ' about TinyWeatherForecastGermany" id="exodus-privacy-report">'
+ str(
markdown.markdown(
result_markdown,
extensions=[
"extra",
"sane_lists",
TocExtension(
baselevel=2,
title="Table of contents",
anchorlink=True,
),
],
)
)
+ "</div>",
features="html.parser",
)
if len(index_html_soup.select("#repo-metadata-container")) > 0:
index_html_soup.select("#repo-metadata-container")[
0
].insert_after(indexMarkdownSoup)
else:
logging.error(
" could NOT insert converted markdown markup from report! "
)
index_html_soup.title.string = (
"ExodusPrivacy report | Tiny Weather Forecast Germany"
)
if (
len(
list(
index_html_soup.select(
'meta[name="google-site-verification"]'
)
)
)
> 0
):
index_html_soup.select(
'meta[name="google-site-verification"]'
)[0].decompose()
try:
page_timestamp = index_html_soup.select(
"#page-timestamp-last-update"
)
if len(page_timestamp) > 0:
page_timestamp[0].string = str(
datetime.now(tzutc()).strftime(
"%Y-%m-%d at %H:%M (%Z)"
)
)
page_timestamp[0]["data-timestamp"] = str(
datetime.now(tzutc()).strftime("%Y-%m-%dT%H:%M:000")
)
else:
logging.error(
"failed to change contents of '#page-timestamp-last-update' in index.html"
" -> error: selector did not match!"
)
except Exception as error_msg:
logging.error(
f"failed to change contents of '#page-timestamp-last-update' in index.html"
f" -> error: {error_msg}"
)
schema_org_meta = ",".join(
list(
index_html_soup.select(
'script[type="application/ld+json"]'