forked from CryptoGuardOSS/cryptoguard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cryptosouple.py
executable file
·1855 lines (1556 loc) · 72.4 KB
/
cryptosouple.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 python3
import argparse
import glob
import shutil
import datetime
import hashlib
import json
import os
import shlex
import signal
import subprocess
import sys
import time
from collections import OrderedDict
import re
import nbformat as nb
# TODO - Add xml/json results verification
'''####################################
#A utility class that contains the rest of the main common files
''' ####################################
curdir = os.path.abspath(os.curdir)
gitPath = os.path.join(curdir, '.git')
failFast, offline = False, not os.path.exists(gitPath)
android, java7, java = os.environ.get('ANDROID_HOME'), os.environ.get('JAVA7_HOME'), os.environ.get('JAVA_HOME')
generalArg, streamTests, generalCmd, generalFile = None, False, None, None
verify = False
# // @formatter:off
# region Offline information
archivedInformation = {'properties': {'projectName': 'cryptoguard', 'groupName': 'vt.edu', 'versionNumber': '04.05.01', 'buildFrameWork': 'Java', 'buildVersion': '1.8.252', 'org.gradle.daemon': 'false', 'gradle.version': '6.0'}, 'rawArgs': {}, 'engineType': {}, 'outputType': {' Legacy': {'type': 'Legacy', 'flag': 'L', 'outputExtension': '.txt'}, ' ScarfXML': {'type': 'ScarfXML', 'flag': 'SX', 'outputExtension': '.xml'}, ' Default': {'type': 'Default', 'flag': 'D', 'outputExtension': '.json'}, ' YAMLGeneric': {'type': 'Default', 'flag': 'Y', 'outputExtension': '.yaml'}, ' XMLGeneric': {'type': 'Default', 'flag': 'X', 'outputExtension': '.xml'}, ' CSVDefault': {'type': 'CSVDefault', 'flag': 'CSV', 'outputExtension': '.csv'}}, 'exceptionType': {' SUCCESS': {'id': '0', 'messageType': 'Successful'}, ' HELP': {'id': '0', 'messageType': 'Asking For Help'}, ' VERSION': {'id': '0', 'messageType': 'Asking For Version'}, ' GEN_VALID': {'id': '1', 'messageType': 'General Argument Validation'}, ' ARG_VALID': {'id': '2', 'messageType': 'Argument Value Validation'}, ' FORMAT_VALID': {'id': '7', 'messageType': 'Format Specific Argument Validation'}, ' FILE_I': {'id': '15', 'messageType': 'File Input Error'}, ' FILE_READ': {'id': '16', 'messageType': 'Reading File Error'}, ' FILE_AFK': {'id': '17', 'messageType': 'File Not Available'}, ' FILE_O': {'id': '30', 'messageType': 'File Output Error'}, ' FILE_CON': {'id': '31', 'messageType': 'Output File Creation Error'}, ' FILE_CUT': {'id': '32', 'messageType': 'Error Closing The File'}, ' ENV_VAR': {'id': '45', 'messageType': 'Environment Variable Not Set'}, ' MAR_VAR': {'id': '100', 'messageType': 'Error Marshalling The Output'}, ' SCAN_GEN': {'id': '120', 'messageType': 'General Error Scanning The Program'}, ' LOADING': {'id': '121', 'messageType': 'Error Loading Class'}, ' UNKWN': {'id': '127', 'messageType': 'Unknown'}}}
# endregion
# // @formatter:on
# region Loading
class Loading(object):
# region Online Reading
def retrieveProperties(file='gradle.properties'):
dyct = {}
with open(file, 'r') as props:
for line in props:
if '=' in line:
key, value = line.split('=')
dyct[str(key.strip())] = str(value.strip())
return dyct
def parseEngineType(file='src/main/java/rule/engine/EngineType.java'):
properties, starter, stopper = {}, False, False
try:
with open(file, 'r') as java:
line = java.readline()
while line and not stopper:
if line.strip().startswith("//endregion"):
stopper = True
elif (starter and not line.strip().startswith("//") and not line.strip().startswith(";")):
name, rest = line.split("(\"")
broken = rest.split(",")
properties[name] = {
'name': broken[0].replace("\"", "").strip(),
'flag': broken[1].replace("\"", "").strip(),
'extension': broken[2].replace("\"", "").strip(),
'helpInfo': broken[3].replace("\"", "").strip()
}
elif line.strip().startswith("//region Values"):
starter = True
line = java.readline()
except:
properties = {}
return properties
def parseExceptionType(file='src/main/java/frontEnd/Interface/outputRouting/ExceptionId.java'):
properties, starter, stopper = {}, False, False
with open(file, 'r') as java:
line = java.readline()
while line and not stopper:
if starter and line.strip().startswith(";"):
stopper = True
elif (starter and line.strip() != '' and not line.strip().startswith(
"//") and not line.strip().startswith(";")):
name, rest = line.split("(")
broken = rest.split(",")
properties[name] = {
'id': broken[0].replace("\"", "").strip(),
'messageType': broken[1].replace("\"", "").replace(")", "").strip()
}
elif line.strip().startswith("//region Values"):
starter = True
line = java.readline()
return properties
def parseArgs(file='src/main/java/frontEnd/argsIdentifier.java'):
properties, starter, stopper = {}, False, False
try:
with open(file, 'r') as java:
line = java.readline()
while line and not stopper:
if line.strip().startswith("//endregion"):
stopper = True
elif (starter and not line.strip().startswith("//") and not line.strip().startswith(";")):
name, rest = line.split("(\"")
broken = rest.split(",")
properties[name] = {
'id': broken[0].replace("\"", "").strip(),
'defaultArg': broken[1].replace("\"", "").strip(),
'desc': broken[2].replace("\"", "").strip(),
'Required': 'Required' in broken[2]
}
elif line.strip().startswith("//region Values"):
starter = True
line = java.readline()
except:
properties = {}
return properties
def parseOutputType(file='src/main/java/frontEnd/MessagingSystem/routing/Listing.java'):
properties, starter, stopper = {}, False, False
with open(file, 'r') as java:
line = java.readline()
while line and not stopper:
if line.strip().startswith("//endregion"):
stopper = True
elif (starter and not line.strip().startswith("//") and not line.strip().startswith(";")):
name, rest = line.split("(\"")
broken = rest.split(",")
ext = broken[2].replace("\"", "").strip()
if ext == 'null':
ext = broken[4].split('.')
ext = ext[-1]
ext = "." + ext[:int(ext.index(')'))].lower()
properties[name] = {
'type': broken[0].replace("\"", "").strip(),
'flag': broken[1].replace("\"", "").strip(),
'outputExtension': ext
}
elif line.strip().startswith("//region Values"):
starter = True
line = java.readline()
return properties
# endregion
# region Online/Offline Reading
def getProperties():
if offline:
return archivedInformation['properties']
else:
return Loading.retrieveProperties()
def getRawArgs():
if offline:
return archivedInformation['rawArgs']
else:
return Loading.parseArgs()
def getEngineType():
if offline:
return archivedInformation['engineType']
else:
return Loading.parseEngineType()
def getDisplayOutputTypes():
if offline:
return archivedInformation['outputType']
else:
return Loading.parseOutputType()
def getDisplayExceptionTypes():
if offline:
return archivedInformation['exceptionType']
else:
return Loading.parseExceptionType()
# endregion
# endregion
# region Reading
class Reading(object):
def prepareOffline():
print('Writing offline information internally')
data = {
'properties': Loading.getProperties(),
'rawArgs': Loading.getRawArgs(),
'engineType': Loading.getEngineType(),
'outputType': Loading.getDisplayOutputTypes(),
'exceptionType': Loading.getDisplayExceptionTypes()
}
return data
def overWriting(replaceWith=None):
if replaceWith == None:
replaceWith = Reading.prepareOffline()
foil = 'cryptosouple.py'
replace = "archivedInformation = "
lines = []
with open(foil) as reading:
for line in reading.readlines():
if line.startswith(replace):
line = replace + str(replaceWith) + '\n'
lines += [line]
with open(foil, 'w') as writing:
for line in lines:
writing.write(line)
# endregion
# region Utils
class Utils(object):
def prettyTime(num):
H, M, S = str(datetime.timedelta(seconds=num)).split(':')
string = "S:" + str(S)
if (int(M) > 0):
string = "M:" + str(M) + " " + string
if (int(H) > 0):
string = "H:" + str(H) + " " + string
return string
def hash():
Utils.build()
print(Utils.halfRows())
foil = Loading.getProperties()['projectName'] + '.jar'
print("Determing the sha512 for " + foil, end=' | ')
print(Utils.retrieveSha(foil))
def retrieveSha(inFile):
sha = None
with open(inFile, 'rb') as new:
contents = new.read()
sha = hashlib.sha512(contents).hexdigest()
return sha
def stringMult(num, string='='):
return ''.join([string for x in range(int(num))])
def printSurveyURL():
print(Loading.getProperties()['surveyURL'])
def halfRows(kar='='):
return Utils.stringMult(Utils.getWidthOfTerminal() / 2, kar)
def splitRows(kar='='):
return Utils.stringMult(Utils.getWidthOfTerminal(), kar)
def getWidthOfTerminal():
try:
value = int(os.popen('stty size', 'r').read().split()[1])
value = value * .75
except:
value = 50
return value
def lremove(string, find):
return Utils.lreplace(string, find, '')
def lreplace(string, find, replace):
reverse = string[::-1]
replace = reverse.replace(find[::-1],replace[::-1],1)
return replace[::-1]
def printVersion():
props = Loading.getProperties()
print(props['projectName'] + ': ' + props['versionNumber'])
print('Gradle Version: ' + props['gradle.version'])
print('Java Build Version: ' + props['buildVersion'])
def percent(x, y):
return Utils.outOf(x, x + y)
def outOf(x, y):
if (x == 0):
return 0
return round((x / y) * 100, 2)
def clean():
print("Cleaning the project")
print(Utils.halfRows())
cmd = str(os.path.join(os.path.abspath(os.curdir), 'gradlew')) + ' clean'
print('Cleaning the project using | ./gradlew clean ', end='| ', flush=True)
try:
proc = subprocess.Popen(
shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = proc.communicate()
except Exception as e:
print('Unknown Error ' + str(e))
sys.exit(0)
stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
print('Removing the Generated files')
for foil in glob.glob("*Generate*"):
print('Removing the file' + str(foil))
os.remove(foil)
for foil in glob.glob("_CryptoGuard-V*_*_*"):
print('Removing the file' + str(foil))
os.remove(foil)
print('Removing the build file')
try:
shutil.rmtree('build')
except:
pass
if 'BUILD SUCCESSFUL' not in stdout:
print('The build broke, exiting now')
sys.exit(0)
print('Successful')
def custom(argz):
print("Custom command " + str(argz))
print(Utils.halfRows())
print('Building the project using | ./gradlew ' + str(argz) + ' ' , end='| ', flush=True)
start = time.time()
cmd = str(os.path.join(os.path.abspath(os.curdir), 'gradlew')) + ' ' + str(argz)
try:
proc = subprocess.Popen(
shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = proc.communicate()
except Exception as e:
print('Unknown Error ' + str(e))
sys.exit(0)
stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
if 'BUILD SUCCESSFUL' not in stdout:
print('The build broke, exiting now')
sys.exit(0)
print('Successful | ' + str(int(time.time() - start)) + ' (s)')
def build():
print("Building the project")
print(Utils.halfRows())
argz = ' clean build -x test '
print('Building the project using | ./gradlew' + str(argz), end='| ', flush=True)
start = time.time()
cmd = str(os.path.join(os.path.abspath(os.curdir), 'gradlew')) + str(argz)
try:
proc = subprocess.Popen(
shlex.split(cmd),
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
)
stdout, stderr = proc.communicate()
except Exception as e:
print('Unknown Error ' + str(e))
sys.exit(0)
stdout, stderr = stdout.decode('utf-8'), stderr.decode('utf-8')
if 'BUILD SUCCESSFUL' not in stdout:
print('The build broke, exiting now')
sys.exit(0)
print('Successful | ' + str(int(time.time() - start)) + ' (s)')
print('Copying the jar file to the current directory ', end='| ', flush=True)
projectName = Loading.getProperties()['projectName']
projectVersion = Loading.getProperties()['versionNumber']
os.system('cp build/libs/' + projectName + '-' + projectVersion + '.jar ./' + projectName + '.jar')
os.system('cp build/libs/' + projectName + '-' + projectVersion + '.jar ./Notebook/' + projectName + '.jar')
if os.path.exists(projectName + '.jar'):
print("Successful")
else:
print("Failure")
def refresh():
Utils.clean()
Utils.custom('spotlessApply')
Utils.build()
# Setting the arguments to be handled by the parser
def arguments(parser, curChoices):
parser.add_argument("switch", choices=curChoices, nargs='?', default='help',
help='Use the q flag to show detailed help')
parser.add_argument("extraArg", nargs='?', default=None,
help='Extra argument to be used to tune commands')
parser.add_argument("extraArgFile", nargs='?', default=None,
help='Extra file to be used to tune commands')
parser.add_argument("-v", action='store_true', help='Print the project version')
return parser
def help(exit=True):
Utils.printVersion()
print(Utils.halfRows())
Utils.routingInfo('./cryptosouple.py')
if exit:
sys.exit(0)
def routing(switch):
offline = not os.path.exists(gitPath)
func = routers.get(switch, Utils.routingInfo)
if offline and not func['offline']:
print('Cannot run ' + switch + ' in Offline Mode')
sys.exit(0)
return func
def routingInfo(useage=''):
global offline
for val in routers:
if (not offline or (offline and routers[val]['offline'])):
print('\t' + str(useage) + ' ' + str(val) + ': ' + str(routers[val]['def']))
return
def start():
print("Running CryptoSoule")
global offline
if offline:
print('This is running in an offline mode')
curChoices = list(routers.keys())
args = Utils.arguments(argparse.ArgumentParser(), curChoices).parse_args()
if (args.v):
Utils.printVersion()
sys.exit()
print(Utils.splitRows() + '\n')
global generalArg
global generalFile
if (args.extraArg):
_temp = args.extraArg
if ("-c" in _temp):
global generalCmd
generalCmd = _temp.replace('-c ','')
elif ('-s' in _temp):
global streamTests
streamTests = True
_temp = _temp.replace('-s', '')
generalArg = _temp
if (args.extraArgFile):
generalFile = args.extraArgFile
Utils.routing(args.switch)["func"]()
# endregion
# region envVars
class envVars(object):
def checkVariables(outFile='_cryptoguard.source'):
Utils.splitRows()
fail = True
global android
global java7
global java
exports = []
if (not android or not os.path.exists(android)):
print("ANDROID_HOME is not set")
yaynay = input('Do you want to set it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to JAVA_HOME? ').strip()
exports += ['export ANDROID_HOME=' + newHome]
else:
print("ANDROID_HOME is set to " + android)
yaynay = input('Do you want to reset it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to ANDROID_HOME? ').strip()
exports += ['export ANDROID_HOME=' + newHome]
if (not java7 or not os.path.exists(java7)):
print("JAVA7_HOME is not set")
yaynay = input('Do you want to set it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to JAVA7_HOME? ').strip()
exports += ['export JAVA7_HOME=' + newHome]
else:
print("JAVA7_HOME is set to " + java7)
yaynay = input('Do you want to reset it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to JAVA7_HOME? ').strip()
exports += ['export JAVA7_HOME=' + newHome]
if (not java or not os.path.exists(java)):
print("JAVA_HOME is not set")
yaynay = input('Do you want to set it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to JAVA_HOME? ').strip()
exports += ['export JAVA_HOME=' + newHome]
else:
print("JAVA_HOME is set to " + java)
yaynay = input('Do you want to reset it (y/n-default)? ') == 'y'
if yaynay:
newHome = input('What is the new path to JAVA_HOME? ').strip()
exports += ['export JAVA_HOME=' + newHome]
if len(exports) > 0:
with open(outFile, 'w') as out:
for arg in exports:
out.write(arg + '\n')
os.chmod(outFile, 0o777)
print("Please run the following command: source " + outFile)
return fail
# endregion
# region ArgUtils
class argsUtils(object):
def fileStringLooper(strings):
global verify
output = []
for string in strings.split(':'):
string = string.strip()
if verify:
if os.path.isfile(string):
output += [string]
else:
print("File doesn't exist: " + str(string))
raise TypeError('Empty')
else:
output += [string]
return output
def customFileDir(string):
global verify
output = []
if isinstance(string, list):
if len(string) == 0 and not verify:
raise TypeError('Empty')
for rawString in string:
_temp = argsUtils.fileStringLooper(rawString)
if _temp is None:
_temp = [argsUtils.customDir(rawString)]
if _temp is not None:
output = output + _temp
if isinstance(string, str):
output = argsUtils.fileStringLooper(string)
if len(output) == 0 and not verify:
raise TypeError('Empty')
return output
def customDir(string):
global verify
output = []
for string in strings.split(':'):
string = string.strip()
if verify:
if os.path.isdir(string):
output += [string]
else:
raise NotADirectoryError(string)
else:
output += [string]
return output
def createCryptoArgs():
cryptoParse = argparse.ArgumentParser()
cryptoParse.add_argument("-in", nargs=1, type=str, choices=['jar','apk','source','java','class'], dest="format", help="The format of input you want to scan.")
cryptoParse.add_argument("-s", nargs='+', type=argsUtils.customFileDir, dest="source", help="The source to be scanned use the absolute path or send all of the source files via the file input.in; ex. find -type f *.java >> input.in.")
cryptoParse.add_argument("-d", nargs='*', type=argsUtils.customFileDir, dest="dependency", help="The dependency to be scanned use the relative path.")
cryptoParse.add_argument("-o", nargs='?', type=argparse.FileType('w'), dest="out", help="The file to be created with the output default will be the project name.")
cryptoParse.add_argument("-new", nargs='?', dest="new", help="The file to be created with the output if existing will be overwritten.")
cryptoParse.add_argument("-t", nargs='?', dest="timemeasure", help="Output the time of the internal processes.")
cryptoParse.add_argument("-m", nargs='?', type=str, choices=['L','SX','D'], default='D', dest="formatout", help="The output format you want to produce")
cryptoParse.add_argument("-n", nargs='?', dest="pretty", help="Output the analysis information in a 'pretty' format.")
cryptoParse.add_argument("-X", nargs='?', dest="noexit", help="Upon completion of scanning, don't kill the JVM")
cryptoParse.add_argument("-v", nargs='?', dest="version", help="Output the version number.")
cryptoParse.add_argument("-VX", nargs='?', dest="nologs", help="Display logs only from the fatal logs")
cryptoParse.add_argument("-V", nargs='?', dest="verbose", help="Display logs from debug levels")
cryptoParse.add_argument("-VV", nargs='?', dest="veryverbose", help="Display logs from trace levels")
cryptoParse.add_argument("-ts", nargs='?', dest="timestamp", help="Add a timestamp to the file output.")
cryptoParse.add_argument("-depth", nargs='?', type=int, dest="depth", help="The depth of slicing to go into")
cryptoParse.add_argument("-java", nargs='?', type=argsUtils.customDir, dest="java", help="Directory of Java to be used JDK 7 for JavaFiles/Project and JDK 8 for ClassFiles/Jar")
cryptoParse.add_argument("-android", nargs='?', type=argsUtils.customDir, dest="android", help="Specify of Android SDK")
cryptoParse.add_argument("-H", nargs='?', dest="heuristics", help="The flag determining whether or not to display heuristics.")
cryptoParse.add_argument("-st", nargs='?', dest="stream", help="Stream the analysis to the output file.")
cryptoParse.add_argument("-main", nargs='?', dest="main", help="Choose the main class if there are multiple main classes in the files given.")
cryptoParse.add_argument("-Sconfig", nargs='?', type=argparse.FileType('r'), dest="Sconfig", help="Choose the Scarf property configuration file.")
cryptoParse.add_argument("-Sassessfw", nargs='?', type=str, dest="Sassessfw", help="The assessment framework")
cryptoParse.add_argument("-Sassessfwversion", nargs='?', type=str, dest="Sassessfwversion", help="The assessment framework version")
cryptoParse.add_argument("-Sassessmentstartts", nargs='?', type=str, dest="Sassessmentstartts", help="The assessment start timestamp")
cryptoParse.add_argument("-Sbuildfw", nargs='?', type=str, dest="Sbuildfw", help="The build framework")
cryptoParse.add_argument("-Sbuildfwversion", nargs='?', type=str, dest="Sbuildfwversion", help="The build framework version")
cryptoParse.add_argument("-Sbuildrootdir", nargs='?', type=str, dest="Sbuildrootdir", help="The build root directory")
cryptoParse.add_argument("-Spackagename", nargs='?', type=str, dest="Spackagename", help="The package name")
cryptoParse.add_argument("-Spackagerootdir", nargs='?', type=str, dest="Spackagerootdir", help="The package root directory")
cryptoParse.add_argument("-Spackageversion", nargs='?', type=str, dest="Spackageversion", help="The package version")
cryptoParse.add_argument("-Sparserfw", nargs='?', type=str, dest="Sparserfw", help="The parser framework")
cryptoParse.add_argument("-Sparserfwversion", nargs='?', type=str, dest="Sparserfwversion", help="The parser framework version")
cryptoParse.add_argument("-Suuid", nargs='?', type=str, dest="Suuid", help="The uuid of the current pipeline progress")
return cryptoParse
def generateTest():
global generalCmd
global generalFile
if generalCmd is None:
print('No commands passed in')
sys.exit(0)
if 'cryptoguard.jar' in generalCmd:
generalCmd = generalCmd.split('cryptoguard.jar')[1]
options = argsUtils.createCryptoArgs().parse_args(shlex.split(generalCmd))
lineEnding = ".json"
checker = """Report report = Report.deserialize(new File(outputFile));
assertFalse(report.getIssues().isEmpty());
assertTrue(report.getIssues().stream().anyMatch(bugInstance -> {
try {
return Utils.containsAny(bugInstance.getFullPath(), Utils.retrieveFullyQualifiedNameFileSep(tempSource));
} catch (ExceptionHandler e) {
assertNull(e);
e.printStackTrace();
}
return false;
}));
"""
listing = "Default"
if options.formatout == "L":
lineEnding = ".txt"
checker = """List<String> results = Files.readAllLines(Paths.get(outputFile), StandardCharsets.UTF_8);
assertTrue(results.size() >= 10);
List<String> filesFound = Utils.retrieveFilesPredicate(tempSource, s -> s.endsWith(".java"), file -> {
try {
return Utils.retrieveFullyQualifiedName(file.getAbsolutePath()) + ".java";
} catch (ExceptionHandler exceptionHandler) {
exceptionHandler.printStackTrace();
return null;
}
});
assertTrue(results.stream().anyMatch(str -> filesFound.stream().anyMatch(str::contains)));
"""
listing = "Legacy"
elif options.formatout == "SX":
lineEnding = ".xml"
checker = """AnalyzerReport report = AnalyzerReport.deserialize(new File(outputFile));
assertFalse(report.getBugInstance().isEmpty());
assertTrue(report.getBugInstance().stream().anyMatch(bugInstance -> {
try {
return Utils.containsAny(bugInstance.getClassName(), Utils.retrieveFullyQualifiedName(tempSource));
} catch (ExceptionHandler exceptionHandler) {
exceptionHandler.printStackTrace();
return false;
}
}));
"""
listing = "ScarfXML"
engineType = {
'jar': 'JAR',
'apk': 'APK',
'source': 'DIR',
'java': 'JAVAFILES',
'class': 'CLASSFILES'
}.get(options.format[0])
if options.out is not None:
fileOut = options.out.name
else:
fileOut = "_GeneratedTestFile" + str(lineEnding)
sourcez = ""
for string in options.source:
sourcez = sourcez + " " + f"add(\"{string[0]}\");\n "
depz = ""
if options.dependency is not None:
for _temp in options.dependency:
for _itr in _temp:
for string in _itr.split(":"):
depz = depz + " " + f"add(\"{string}\");\n "
dependency = ""
if depz.strip():
dependency = f"""String tempDependency = Utils.join(" ", new ArrayList<String>(){{{{
{depz}
}}}});
String dependency = Utils.join(" ", tempDependency);
"""
argz = f"""
String args =
makeArg(argsIdentifier.FORMAT, EngineType.{engineType}) +
makeArg(argsIdentifier.OUT, fileOut) +
makeArg(argsIdentifier.FORMATOUT, Listing.{listing}) + """
clean = argsUtils.createCryptoArgs()
# Adding the out
if depz.strip():
argz = argz + f"""
makeArg(argsIdentifier.DEPENDENCY, dependency) + """
# Adding the flags
for arg in [x.dest for x in clean.__dict__['_actions'] if
x.type is None and x.dest.strip() != 'help' and options.__dict__[x.dest] is not None]:
argz = argz + f"""
makeArg(argsIdentifier.{arg.upper()}) + """
# Adding the strings
for arg in [x.dest for x in clean.__dict__['_actions'] if
x.type is str and x.nargs is '?' and x.dest.strip().upper() != 'FORMATOUT' and options.__dict__[
x.dest] is not None]:
argz = argz + f"""
makeArg(argsIdentifier.{arg.upper()}, "{options.__dict__[arg]}") + """
# Adding the new
if options.new is not None:
argz = argz + f"""
makeArg(argsIdentifier.NEW, \"{options.new.name}\") + """
# Adding the depth
if options.depth is not None:
argz = argz + f"""
makeArg(argsIdentifier.DEPTH, {options.depth}) + """
# Adding the java
if options.java is not None:
argz = argz + f"""
makeArg(argsIdentifier.JAVA, \"{options.java[0]}\") + """
# Adding the android
if options.android is not None:
argz = argz + f"""
makeArg(argsIdentifier.ANDROID, \"{options.android[0]}\") + """
# Adding the Sconfig
if options.Sconfig is not None:
argz = argz + f"""
makeArg(argsIdentifier.SCONFIG, \"{options.Sconfig.name}\") + """
argz = argz + """
makeArg(argsIdentifier.SOURCE, source) +
makeArg(argsIdentifier.PRETTY) +
makeArg(argsIdentifier.NOEXIT);
"""
output = f"""
/**
* Generated Test
*/
@Test
public void generatedTest() {{
String fileOut = "{fileOut}";
new File(fileOut).delete();
ArrayList<String> tempSource = new ArrayList<String>(){{{{
{sourcez}
}}}};
String source = Utils.join(" ", tempSource);
{dependency}
if (isLinux) {{
{argz}
try {{
String outputFile = captureNewFileOutViaStdOut(args.split(" "));
{checker}
}} catch (Exception e) {{
e.printStackTrace();
assertNull(e);
}}
}}
}}
"""
if (generalFile is not None):
if os.path.exists(generalFile):
os.remove(generalFile)
with open(generalFile, 'w') as file:
file.write(output)
else:
print(output)
print('Completed')
def basicBuildCommand():
print("Building a basic command")
print('Please Note this does not verify whether the directory/files exist')
print("Common abreviations:")
print("\tn = no")
print("\ty = yes")
print(Utils.halfRows())
projectName = Loading.getProperties()['projectName']
cmd = 'java -jar ' + projectName + '.jar '
lookup = Loading.parseEngineType()
for value in lookup.values():
print(value['name'] + ' flag: ' + value['flag'])
print()
typeOfProject = input("What type of project by flag (jar/apk/source/java/class)? ")
if typeOfProject not in [x['flag'] for x in lookup.values()]:
print("Please enter a valid type of project");
sys.exit()
cmd += '-in ' + typeOfProject + ' '
for key, value in lookup.items():
if value['flag'] == typeOfProject:
typeOfProject = value
print()
print(Utils.halfRows())
source = input(
"What file/project directory would you like to scan (java/class files please enter class path or single file)? ")
cmd += '-s ' + source + ' '
print()
if (typeOfProject['flag'] != 'source' and not source.endswith(
typeOfProject['extension']) and not source.endswith(
".in")):
print("Please enter a valid file for Scanning");
sys.exit()
print(Utils.halfRows())
global android
global java7
global java
javaHome = sdkHome = None
if (typeOfProject['flag'] == 'apk'):
print("Current ANDROID_HOME is set to " + android)
sdkHome = input("Would you like to specify the Android Home (n/sdk directory)? ")
print()
if sdkHome and sdkHome != 'n':
cmd += '-android ' + sdkHome + ' '
if (typeOfProject['flag'] == 'apk' or typeOfProject['flag'] == 'jar' or typeOfProject['flag'] == 'class'):
print("Current JAVA_HOME is set to " + java)
javaHome = input("Would you like to specify the Java 8 Home (n/jdk directory)? ")
if (typeOfProject['flag'] == 'dir' or typeOfProject['flag'] == 'java'):
print("Current JAVA7_HOME is set to " + java7)
javaHome = input("Would you like to specify the Java 7 Home (n/jdk directory)? ")
print()
if javaHome and javaHome != 'n':
cmd += '-java ' + javaHome + ' '
dependency = input("Would you like to add a dependency folder (n/directory)? ")
if (dependency != 'n'):
cmd += '-in ' + dependency + ' '
print()
main = input("Would you like to specify the main class (n/file)? ")
if (main != 'n'):
cmd += '-main ' + main + ' '
print()
print(Utils.halfRows())
print('Output formats')
lookup = Loading.parseOutputType()
for value in lookup.values():
print(value['type'] + " flag: " + value['flag'] + ' extension: ' + value['outputExtension'])
print()
outType = input("Would you like to specify the output format by flag (n/SX/L/D)? ")
if (outType != 'n'):
if outType not in [x['flag'] for x in lookup.values()]:
print('Please enter a valid output format');
sys.exit(0)
cmd += '-m ' + outType + ' '
for key, value in lookup.items():
if value['flag'] == outType:
lookup = value
print()
foil = input("Would you like to specify the output file (n/file)? ")
if (foil != 'n'):
if not foil.endswith(lookup['outputExtension']):
print('Please enter a valid file for the output type.');
sys.exit(0)
cmd += '-o ' + foil + ' '
print()
if (outType == 'n' and foil != 'n' or outType != 'n' and foil == 'n'):
print('Please enter both the output format and the output file.');
sys.exit(0)
if foil != 'n':
overwrite = input("Would you like to overwrite the output file (y/n)? ") == 'y'
if (overwrite):
cmd += '-new '
print()
print(Utils.halfRows())
logging = input("Would you like to set the logging high/medium/low/off/no (h/m/l/o/n)? ")
if (logging == 'h'):
cmd += '-vv '
elif (logging == 'm'):
cmd += '-v '
elif (logging == 'o'):
cmd += '-vx '
print()
print(Utils.halfRows())
result = input("Would you like to stream the results (y/n)? ") == 'y'
if (result):
cmd += '-st '
print()
result = input("Would you like to the time measurement to the output (y/n)? ") == 'y'
if (result):
cmd += '-t '
print()
result = input("Would you like to format the results (y/n)? ") == 'y'
if (result):
cmd += '-n '
print()
result = input("Would you like to add heuristics to the results (y/n)? ") == 'y'
if (result):
cmd += '-H '
print()
result = input("Would you like to specify the depth of heuristics to the results (y/n)? ") == 'y'
if (result):
result = input("What number? ")
try:
result = int(result)
except ValueError:
print("Please enter a valid depth number.");
sys.exit(0)
cmd += '-depth ' + str(result) + ' '
print()
print(Utils.halfRows())
print('The build up command is:' + cmd)
print(Utils.halfRows())
run = input('Would you like to run the command (y/n)?') == 'y'
if (run):
os.system(cmd)
def displayProjectTypes():
print("Can scan the following project types:")
print(Utils.halfRows())
for key, value in Loading.parseEngineType().items():
print('\t' + value['name'] + " accepts a " + value['extension'])
def displayOutputTypes():
print("Can write the results as the following output types:")
print(Utils.halfRows())
for key, value in Loading.parseOutputType().items():
print('\t' + value['type'] + " accepts a " + value['outputExtension'] + ' file output type.')
def displayExceptionTypes():
print("Uses the following error codes:")
print(Utils.halfRows())
for key, value in Loading.parseExceptionType().items():
print('\t' + value['id'] + " is a " + value['messageType'] + ' Exception.')
def writeUsage():
argsUtils.helpfulArgs(writeOut=True)
def helpfulArgs(filter=None, writeOut=False, writeOutFile='USAGE.md'):