/
workflow
executable file
·1721 lines (1632 loc) · 75.2 KB
/
workflow
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python
import sys, getopt, re, os, sqlite3, types
"""
================================================================================
=
= This file is part of seorigin
= Copyright (C) 2012 Devan Franchini, Anthony G. Basile, Sven Vermeulen
=
= seorigin is free software: you can redistribute it and/or modify
= it under the terms of the GNU General Public License as published by
= the Free Software Foundation, either version 3 of the License, or
=
= seorigin is distributed in the hope that it will be useful,
= but WITHOUT ANY WARRANTY; without even the implied warranty of
= MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
= GNU General Public License for more details.
=
= You should have received a copy of the GNU General Public License
= along with seorigin. If not, see <http://www.gnu.org/licenses/>.
=
= ----
= policy-parser.py is the parsing component of seorigin, the SELinux Policy originator.
=
= Purpose:
= The parser takes the m4 marco expansion of SELinux policies and parses it into a suitable and
= useful manner for the workflow component of the policy originator to database.
=
= See README for more information.
=
================================================================================
"""
def usage():
print("Proper usage:\nworkflow -i(--input) [file to parse] -o(--output) [database location]")
#TODO find range in range_transition statements such as:
# range_transition $1 initrc_exec_t:process s0 - mls_systemhigh
# understand what they mean and how to handle them.
# Add -d flag for debugging.
"""
parse_cmd_agrs() sets up the -i -o and -h flags for the policy-parser script. See usage for what each flag is.
"""
def parse_cmd_args():
shortOpts = 'i:o:h'
longOpts = ['input=','output=','help']
opts, extraparams = getopt.getopt(sys.argv[1:], shortOpts, longOpts)
inputCheck = False # Boolean check to see if input location has been set.
outputCheck = False # Boolean check to see if output location has been set.
#Set up arguement flags for script execution.
for o, p in opts:
if o in ['-i', '--input']:
if os.path.exists(p):
inputFile=p
if not os.access(p, os.R_OK):
print("\nFile %s does not have read permissions!\nPlease specify new input file or resort to default.\n" % p)
sys.exit()
else:
print("\nFile %s does not exist!\nPlease specify new input file.\n" % p)
sys.exit()
inputCheck = True
elif o in ['-o', '--output']:
try:
outputFile = sqlite3.connect(p)
except sqlite3.OperationalError as err:
print("\nCritical error: {0}".format(err))
print("\nSuggestions:\n\n *Try new output file location.\n *Check permissions of database.\n *Gently weep.\n")
sys.exit()
outputCheck=True
elif o in ['-h', '--help']:
print("\n")
usage()
sys.exit()
# Sanity check to make sure the parsed information is getting written to some location.
if not inputCheck and outputCheck:
print("\nInput file not specified, please specify input file to continue.")
sys.exit()
if not outputCheck and inputCheck:
print ("\nOutput file not specified, please specify new output file to continue.")
sys.exit()
if not outputCheck and not inputCheck:
print("\nInput file and output file are not specified.\n\nPlease specify both files in order to continue.")
sys.exit()
return( inputFile, outputFile )
"""
readInput( inputFile (File) ) reads in the specified file. If a file does not exist it will shoot an exception.
"""
def readInput( inputFile ):
try:
f=open(inputFile, 'r') # This creates the function for opening the file, and assigns it to f.
except Exception as err:
print("\nreadInput() Error: {0}".format(err),"\n")
fileLines = f.readlines()
f.close()
return fileLines
"""
getStatementType( line (String) ) read through a line of the input and searches for each statement type and assigns
a certain value to each statement and then returns the value of the statement.
"""
def getStatementType( line ):
statementValue = 69
# Checks for record lines.
line = re.sub('^\s+', '', line)
if re.search('#', line):
pass
elif re.search('^}', line):
pass
elif re.search('\',`', line):
pass
elif re.search('^if', line):
pass
elif line == '':
pass
# Checks for rule calls
elif re.search('^allow .*:.*;', line):
statementValue = 0
elif re.search('^type_change', line):
statementValue = 0
elif re.search('^dontaudit', line):
statementValue = 0
elif re.search('^auditallow', line):
statementValue = 0
elif re.search('^neverallow', line):
statementValue = 0
elif re.search('^range_transition', line):
statementValue = 0
elif re.search('^type_member', line):
statementValue = 0
# Checks for interface calls
elif re.search('^.*\(', line):
statementValue = 1
# Checks for assign calls
elif re.search('^.*attribute', line):
statementValue = 2
elif re.search('^typealias', line):
statementValue = 2
elif re.search('^class', line):
statementValue = 2
elif re.search('^role.*types', line):
statementValue = 2
elif re.search('^type.*,.*', line):
statementValue = 2
elif re.search('^allow ', line):
statementValue = 2
# Checks for declaration calls
elif re.search('^type ', line):
statementValue = 3
elif re.search('^role ', line):
statementValue = 3
elif re.search('^attribute', line):
statementValue = 3
elif re.search('^\{', line):
statementValue = 3
# Checks for role_transition calls
elif re.search('^role_transition', line):
statementValue = 4
# Checks for type_transition calls
elif re.search('^type_transition', line):
statementValue = 5
else:
print('Unknown line: ' + line)
pass
return statementValue
"""
getDeclareFromType( declareLine (String) ) goes through the lines of declaration statements and returns the declare type
of the declaration line as int.
"""
def getDeclareType( declareLine ):
try:
declareType = 0
if re.search('^type', declareLine):
declareType = 1
elif re.search('^role', declareLine):
declareType = 2
elif re.search('^attribute', declareLine):
declareType = 3
elif re.search('^{', declareLine):
declareType = 4
return declareType
except Exception as err:
print("getDeclareType() Error: {0}".format(err))
print("While determining type of line: %s" % declareLine,"\n")
"""
getRuleType( ruleLine (String) ) goes through the lines of rules statements and returns the rule type as an int.
"""
def getRuleType( ruleLine ):
try:
ruleType = 0
if re.search('^allow', ruleLine):
ruleType = 1
elif re.search('^dontaudit', ruleLine):
ruleType = 2
elif re.search('^auditallow', ruleLine):
ruleType = 3
elif re.search('^range_transition', ruleLine):
ruleType = 4
elif re.search('^neverallow', ruleLine):
ruleType = 5
elif re.search('^type_member', ruleLine):
ruleType = 6
elif re.search('^type_change', ruleLine):
ruleType = 7
return ruleType
except Exception as err:
print("getRuleType() Error: {0}".format(err))
print("While determining rule type of line: %s" % ruleLine,"\n")
'''
getAssignationType( assignLine (String) ) takes in a statement assign line from the input and returns the type
of assign statement it is in a numerical value.
'''
def getAssignationType( assignLine ):
try:
assignType = 0
if re.search('^typeattribute', assignLine):
assignType = 1
elif re.search('^roleattribute', assignLine):
assignType = 2
elif re.search('^typealias', assignLine):
assignType = 3
elif re.search('^class', assignLine):
assignType = 4
elif re.search('^role', assignLine):
assignType = 5
elif re.search('^type', assignLine):
assignType = 6
elif re.search('^allow', assignLine):
assignType = 7
return assignType
except Exception as err:
print('\ngetAssignationType() Error: {0}'.format(err))
print("While determining assignment type from: %s.\n" % assignLine)
"""
getLabelClass( label(File), classList (File), permList(File) ) read through the labels of the input and searches for each statement type and assigns
a certain value to each label and then returns the value of the label.
"""
def getLabelClass( label, classList, permsList ):
labelClass = 1
if label in classList:
labelClass = 3
elif label in permsList:
labelClass = 4
elif re.search('.*_perms', label):
labelClass = 4
elif re.search('.*\_t$', label):
labelClass = 1
elif re.search('.*_type$', label):
labelClass = 1
elif re.search('\".*\"', label):
labelClass = 5
elif re.search('^\$.', label):
labelClass = 6
elif re.search('._*\_r$', label):
labelClass = 7
else:
labelClass = 2
return labelClass
"""
getFileName( record (String) ) goes through a source record and returns the file name.
"""
def getFileName( record ):
try:
sourceFile = ''
oldRecord = record
if re.search('^# \w+/.*$', record):
record = re.sub('^# ', '', record)
sourceFile = record
return sourceFile
except Exception as err:
print("\ngetFileName Error: {0}".format(err))
print("While parsing file name from line: %s" % oldRecord,"\n")
"""
getDefinitionName( record (String) ) goes through a definition record and returns the definition name.
"""
def getDefinitionName( record ):
try:
definitionName = ''
oldRecord = record
if re.search('^# ', record):
record = re.sub('^# ', '', record)
definitionName = record
return definitionName
except Exception as err:
print("\ngetDefinitionName() Error: {0}".format(err))
print("While parsing definition name from line: %s" % oldRecord,"\n")
"""
getSourceLine( record (String) ) detects the source line of a source record, parses it out using regular expressions,
then returns it.
"""
def getSourceLine( record ):
try:
recordLine = ''
sourceCheck = False
oldRecord = record
if re.search('^## source.*$', record):
sourceCheck = True
elif re.search('^\w*.*$', record):
sourceCheck = True
elif re.search('^\n', record):
sourceCheck = False
if sourceCheck:
record = re.sub('^## source.*$', '', record)
record = re.sub('^# .*$', '', record)
return record
except Exception as err:
print("\ngetSourceLine() Error: {0}".format(err))
print("While parsing source line from line: %s" % oldRecord,"\n")
"""
getLineNumber( record (String) ) goes through a source record and returns the line number.
"""
def getLineNumber( record ):
lineNum = 0
if re.search('^# line: ', record):
record = re.sub('^# line: ', '', record)
lineNum = record
elif re.search('^# Line: ', record):
record = re.sub('^# Line: ', '', record)
lineNum = record
elif re.search('# \w+/.*\.te:\d+', record):
print('\nOlder parsed file format detected in source record line: \n' + record,'\n')
print('Please use a new input file with the updated parsed format.')
sys.exit()
return lineNum
"""
getSourceFromRule( line (String) ) goes through a rule statement such as this:
"allow $1 $2:file { mmap_file_perms ioctl lock };"
and would return the source labels which in this case would be: $1.
"""
def getSourceFromRule( line ):
try:
setCheck = False
if re.search('^ ', line):
line = re.sub('^ ', '', line)
oldLine = line
line = re.sub(':.*$', '', line)
source = re.sub('^\w+[_\w+] ', '', line)
if re.search('^{', source):
setCheck = True
elif re.search('}', source):
setCheck = False
if setCheck:
source = re.sub('}.*$', '}', source)
else:
source = re.sub(' .*$', '', source)
return source
except Exception as err:
print('\ngetSourceFromRule() Error{0}'.format(err))
print("While parsing source from line: %s" % oldLine,"\n")
"""
getDestinationFromRule( line (String) ) goes through a rule statement such as this:
"allow $1 $2:file { mmap_file_perms ioctl lock };"
and would return the destination label which in this case would be: $2.
"""
def getDestinationFromRule( line ):
try:
destination = ''
setCheck = False
if re.search('^ ', line):
line = re.sub('^ ', '', line)
line = re.sub(':.*$', '', line)
if re.search('{', line):
setCheck = True
elif re.search('}', line):
setCheck = False
if setCheck:
destination = re.sub('^\w+[_\w+] ', '', line)
if re.search('^\w+_\$\d+_\w+ ', destination):
destination = re.sub('^\w+_\$\d+_\w+ ', '', destination)
if re.search('^\$\d+[_w+]', destination):
destination = re.sub('^\$\d+_\w+ ', '', destination)
elif re.search('^\$\d+', destination):
destination = re.sub('^\$\d+ ', '', destination)
elif re.search('^\$\d+[_w+]', destination):
destination = re.sub('^\$\d+_\w+ ', '', destination)
elif re.search('^\w+', destination):
destination = re.sub('^\w+ ', '', destination)
elif re.search('^[~{].*} ', destination):
destination = re.sub('^[~{].*} ', '', destination)
else:
destination = re.sub('^\w+[_\w+] ', '', line)
if re.search('^\w+_\$\d+_\w+ ', destination):
destination = re.sub('^\w+_\$\d+_\w+ ', '', destination)
if re.search('^\$\d+[_w+]', destination):
destination = re.sub('^\$\d+_\w+ ', '', destination)
elif re.search('^\$\d+', destination):
destination = re.sub('^\$\d+ ', '', destination)
elif re.search('^\w+', destination):
destination = re.sub('^\w+ ', '', destination)
elif re.search('^[~{].*} ', destination):
destination = re.sub('^[~{].*} ', '', destination)
return destination
except Exception as err:
print("getDestinationFromRule() Error: {0}".format(err))
print("While parsing destination from line: %s" % oldLine,'\n')
"""
getClassFromRule( line (String) ) goes through a rule statement such as this:
"allow $1 $2:file { mmap_file_perms ioctl lock };"
and would return the destination label which in this case would be: file.
"""
def getClassesFromRule( line ):
try:
classes = ''
setCheck = False
oldLine = line
line = re.sub('^.*:', '', line)
line = re.sub(';', '', line)
if re.search('^{', line):
setCheck = True
elif re.search('}', line):
setCheck = False
if setCheck:
classes = re.sub('}.*$', '}', line)
else:
classes = re.sub(' .*$', '', line)
return classes
except Exception as err:
print("\ngetClassFromRule() Error: {0}".format(err))
print("While parsing classes from line: %s" % oldLine,"\n")
"""
getPrivilegesFromRule( line (String) ) goes through a rule statement such as this:
"allow $1 $2:file { mmap_file_perms ioctl lock };"
and would return the destination label which in this case would be:
the label set { mmap_file_perms ioctl lock }.
"""
def getPrivilegesFromRule( line ):
try:
permissions = ''
setCheck = False
oldLine = line
line = re.sub('^.*:', '', line)
line = re.sub(';', '', line)
if re.search('^{.*}', line):
permissions = re.sub('^{.*} ', '', line)
elif re.search('^\w+ ', line):
permissions = re.sub('^\w+ ', '', line)
elif re.search('^\$\d+ ', line):
permissions = re.sub('^\$\d+ ', '', line)
return permissions
except Exception as err:
print("\ngetPrivilegesFromRule() Error{0}".format(err))
print("While parsing privileges from line: %s" % oldLine,'\n')
"""
getInterfaceArgs( line (String) ) reads in the line of an interface statement and returns in interface
arguments as a list.
If we get an interface statement such as:
domain_entry_file($1,$2)
We would return the arguments in as list like: ['$1', '$2']
"""
def getInterfaceArgs( line ):
try:
oldLine = line
line = re.sub('^.*\(', '(', line)
args = re.sub('[\(\)]', '', line)
if re.search('^\w+[_\w+]$', args):
args = args.split()
elif re.search('^\$\d+$', args):
args = args.split()
else:
args = args.split(',')
return args
except Exception as err:
print('\ngetInterfaceArgs() Error: {0}'.format(err))
print("While parsing interface args from line: %s" % line,'\n')
'''
getInterfaceName( interfaceLine (String) ) grabs the name of the interface statement and returns the name as a string
'''
def getInterfaceName( interfaceLine ):
try:
name = ''
if re.search('^ ', interfaceLine):
interfaceLine = re.sub('^ *', '', interfaceLine)
name = re.sub('\(.*\)', '', interfaceLine)
return name
except Exception as err:
print('\ngetInterfaceName() Error: {0}'.format(err))
print("While parsing interface name from line: %s" % interfaceLine,"\n")
'''
getTargetFromAssignation( line (String) ) takes in an assignation line such as:
role system_r types $1;
or
typeattribute file domain, foo_t, bar_t;
and returns the target label in the first case it would be: system_r
in the second case it would be: file
'''
def getTargetFromAssignation( line ):
try:
target = ''
oldLine = line
line = re.sub('^ ', '', line)
line = re.sub('^\w+ ', '', line)
target = re.sub(' .*;', '', line)
target = re.sub('[, ]', '', target)
return target
except Exception as err:
print('\ngetTargetFromAssignation() Error: {0}'.format(err))
print("While parsing Target from line: %s " % oldLine,"\n")
'''
getAssignedFromAssignation( line (String) ) takes in an assignation line such as:
role system_r types $1;
or
typeattribute file domain, foo_t, bar_t;
and returns the assigned labels in the first case it would simply be: $1
but if more than one assigned label is found they would be returned as a label set
in this case it would be: { domain foo_t bar_t }
'''
def getAssignedFromAssignation( line ):
try:
assigned = ''
assigned = re.sub('^ ', '', line)
assigned = re.sub('^\w+ ', '', assigned)
if re.search('^\w+[_\w+]', assigned):
assigned = re.sub('^\w+[_\w+] ', '', assigned)
elif re.search('^\$\d+[_\w+]', assigned):
assigned = re.sub('^\$\d+_\w+ ', '', assigned)
elif re.search('^\$\d+', assigned):
assigned = re.sub('^\$\d+ ', '', assigned)
if re.search('^\w+_\$\d+_\w+ ', assigned):
assigned = re.sub('^\w+_\$\d+_\w+ ', '', assigned)
assigned = re.sub('^types ', '', assigned)
if re.search('^alias', assigned):
assigned = re.sub('^alias ', '', assigned)
if re.search('^.*, .*', assigned):
assigned = re.sub(',', '', assigned)
assigned = re.sub('^', '{ ', assigned)
assigned = re.sub(';', ' }', assigned)
else:
assigned = re.sub(';', '', assigned)
return assigned
except Exception as err:
print('\ngetAssignedFromAssignation() Error: {0}'.format(err))
print("While parsing assigned from line: %s" % line,"\n")
'''
getTargetFromDeclare( declareLine (String) ) takes in a declaration line such as:
role system_r
and returns the target of the declaration, which would be: system_r
'''
def getTargetFromDeclare( declareLine ):
try:
target = ''
oldDeclare = declareLine
if re.search('^ ', declareLine):
declareLine = re.sub('^ ', '', declareLine)
target = re.sub('^\w+[_\w+] ', '', declareLine)
target = re.sub(' alias .*$', '', target)
target = re.sub(';', '', target)
return target
except Exception as err:
print("\ngetTargetFromDeclare() Error: {0}".format(err))
print("While parsing target from line: %s.\n" % oldDeclare)
'''
getAliasFromDeclare( declareLine (String) ) takes in a declaration line like this:
role system_r alias $1
and returns the alias, which would be: $1
'''
def getAliasFromDeclare( declareLine ):
try:
alias = ''
alias = re.sub('^.* alias ', '', declareLine)
alias = re.sub(';', '', alias)
return alias
except Exception as err:
print('\ngetAliasFromDeclare() Error: {0}'.format(err))
print("While parsing alias from line: %s.\n" % declareLine)
'''
getArgFromRoleTrans( roleTransLine (String) ) takes in a role_transition line like:
role_transition $2 amavis_initrc_exec_t system_r;
and returns the argument which in this case would be: $2
'''
def getArgFromRoleTrans( roleTransLine ):
try:
arg = ''
if re.search('^ ', roleTransLine ):
roleTransLine = re.sub('^ *', '', roleTransLine )
oldLine = roleTransLine
arg = re.sub('role_transition ', '', roleTransLine)
arg = re.sub(' .*_t', '', arg)
arg = re.sub(' .*_r;', '', arg)
return arg
except Exception as err:
print('\ngetArgFromRoleTrans() Error: {0}'.format(err))
print('While parsing argument from line: %s.\n' % oldLine)
'''
getTypeFromRoleTrans( roleTransLine (String) ) takes in a role_transition line like:
role_transition $2 amavis_initrc_exec_t system_r;
and returns the target which in this case would be: amavis_initrc_exec_t
'''
def getTypeFromRoleTrans( roleTransLine ):
try:
roleTransTarget = ''
if re.search('^ ', roleTransLine ):
roleTransLine = re.sub('^ *', '', roleTransLine )
oldLine = roleTransLine
roleTransTarget = re.sub('^role_transition ', '', roleTransLine)
if re.search('^\$\d+[_\w+]', roleTransTarget):
roleTransTarget = re.sub('^\$\d+_\w+ ', '', roleTransTarget)
elif re.search('^\$\d+', roleTransTarget):
roleTransTarget = re.sub('^\$\d+ ', '', roleTransTarget)
if re.search('^\w+_\$\d+_\w+ ', roleTransTarget):
roleTransTarget = re.sub('^\w+_\$\d+_\w+ ', '', roleTransTarget)
elif re.search('^\w+[_\w+]', roleTransTarget):
roleTransTarget = re.sub('^\w+[_\w+] ', '', roleTransTarget)
roleTransTarget = re.sub(' .*_r;', '', roleTransTarget)
return roleTransTarget
except Exception as err:
print('\ngetTypeFromRoleTrans() Error: {0}'.format(err))
print('While parsing type from line: %s.\n' % oldLine)
'''
getRoleFromRoleTrans( roleTransLine (String) ) takes in a role_transition line like:
role_transition $2 amavis_initrc_exec_t system_r;
and returns the assignation which in this case would be: system_r
'''
def getRoleFromRoleTrans( roleTransLine ):
try:
roleTransAssign = ''
if re.search('^ ', roleTransLine ):
roleTransLine = re.sub('^ *', '', roleTransLine )
oldLine = roleTransLine
roleTransAssign = re.sub('^role_transition .*\w+ ', '', roleTransLine)
roleTransAssign = re.sub(';', '', roleTransAssign)
return roleTransAssign
except Exception as err:
print('\ngetTypeFromRoleTrans() Error: {0}'.format(err))
print('While parsing role from line: %s.\n' % oldLine)
'''
getSourceFromTypeTrans( typeTransLine (String) ) takes in a type_transition line like:
type_transition $2 input_xevent_t:x_event $1_input_xevent_t;
and returns the source which in this case would be: $2
'''
def getSourceFromTypeTrans( typeTransLine ):
try:
source = ''
if re.search('^ ', typeTransLine ):
typeTransLine = re.sub('^ *', '', typeTransLine)
source = re.sub('^type_transition ', '', typeTransLine)
source = re.sub(':.*$', ':', source)
source = re.sub(' .*:', '', source)
return source
except Exception as err:
print("\ngetSourceFromTypeTrans() Error: {0}".format(err))
print("While parsing source from line: %s" % typeTransLine,"\n")
'''
getResourceFromTypeTrans( typeTransLine (String) ) takes in a type_transition line like:
type_transition $2 input_xevent_t:x_event $1_input_xevent_t;
and returns the resource which in this case would be: input_xevent_t
'''
def getResourceFromTypeTrans( typeTransLine ):
try:
resource = ''
if re.search('^ ', typeTransLine ):
typeTransLine = re.sub('^ *', '', typeTransLine)
resource = re.sub('^type_transition ', '', typeTransLine)
resource = re.sub(':.*$', '', resource)
resource = re.sub(' ', ':', resource)
resource = re.sub('.*:', '', resource)
return resource
except Exception as err:
print("\ngetResourceFromTypeTrans() Error: {0}".format(err))
print("While parsing resource from line: %s" % typeTransLine,"\n")
'''
getTargetFromTypeTrans( typeTransLine (String) ) takes in a type_transition line like:
type_transition $2 input_xevent_t:x_event $1_input_xevent_t;
and returns the target which in this case would be: x_event
'''
def getTargetFromTypeTrans( typeTransLine ):
try:
target = ''
setCheck = False
if re.search('^ ', typeTransLine ):
typeTransLine = re.sub('^ *', '', typeTransLine)
target = re.sub('^type_transition ', '', typeTransLine)
target = re.sub('.*:', '', target)
if re.search('^{', target):
target = re.sub('}.*$', '}', target)
else:
target = re.sub(' .*$', '', target)
return target
except Exception as err:
print("\ngetTargetFromTypeTrans() Error: {0}".format(err))
print("While parsing target from line: %s" % typeTransLine,"\n")
'''
getClassFromTypeTrans( typeTransLine (String) ) takes in a type_transition line like:
type_transition $2 input_xevent_t:x_event $1_input_xevent_t;
and returns the class which in this case would be: $1_input_xevent_t
'''
def getClassFromTypeTrans( typeTransLine ):
try:
Class = ''
if re.search('^ ', typeTransLine ):
typeTransLine = re.sub('^ *', '', typeTransLine)
Class = re.sub('^type_transition ', '', typeTransLine)
Class = re.sub('.*:', '', Class)
if re.search('^\$\d+[_\w+]', Class):
Class = re.sub('^\$\d+_\w+ ', '', Class)
elif re.search('^\$\d+', Class):
Class = re.sub('^\$\d+ ', '', Class)
if re.search('^\w+_\$\d+_\w+ ', Class):
Class = re.sub('^\w+_\$\d+_\w+ ', '', Class)
elif re.search('^\w+[_\w+]', Class):
Class = re.sub('^\w+[_\w+] ', '', Class)
elif re.search('^{', Class):
Class = re.sub('{.*} ', '', Class)
if re.search('.* .*', Class):
Class = re.sub(' .*;', '', Class)
else:
Class = re.sub(';', '', Class)
return Class
except Exception as err:
print("\ngetClassFromTypeTrans() Error: {0}".format(err))
print("While parsing class from line: %s" % typeTransLine,"\n")
'''
getFileFromTypeTrans( typeTransLine (String) ) takes in a type_transition line like:
type_transition $1 sepgsql_database_type:db_schema sepgsql_temp_object_t "pg_temp";
and returns the file which in this case would be: "pg_tep"
'''
def getFileFromTypeTrans( typeTransLine ):
try:
File = ''
if re.search('^ ', typeTransLine ):
typeTransLine = re.sub('^ *', '', typeTransLine)
File = re.sub('.*:', '', typeTransLine)
if re.search('^\$\d+[_\w+]', File):
File = re.sub('^\$\d+_\w+ ', '', File)
elif re.search('^\$\d+', File):
File = re.sub('^\$\d+ ', '', File)
if re.search('^\w+_\$\d+_\w+ ', File):
File = re.sub('^\w+_\$\d+_\w+ ', '', File)
elif re.search('^\w+[_\w+]', File):
File = re.sub('^\w+[_\w+] ', '', File)
elif re.search('^{', File):
File = re.sub('{.*} ', '', File)
if re.search('.* .*', File):
File = re.sub('.* ', '', File)
File = re.sub(';', '', File)
else:
File = '' # No file label found.
return File
except Exception as err:
print("\ngetFileFromTypeTrans() Error: {0}".format(err))
print("While parsing file name from line: %s" % typeTransLine,"\n")
"""
getClassList() grabs the information from "SELinux Class list" and returns it as a list.
"""
def getClassList():
try:
if os.path.exists(os.path.join(os.environ["PWD"], 'SELinux_Class_list.txt')):
classList = readInput(os.path.join(os.environ["PWD"], 'SELinux_Class_list.txt'))
if not os.access(os.path.join(os.environ["PWD"], 'SELinux_Class_list.txt'), os.R_OK):
print("\nFile SELinux_Class_list.txt does not have read permissions!\nPlease change file permissions.\n")
sys.exit()
else:
print("Critical Error!: SELinux_Class_list.txt not found in " + os.path.join(os.environ["PWD"]))
print("Please be sure it is under the correct name and in the present working directory.\n")
sys.exit()
result = ['']
for List in classList:
List = re.sub('\n', '', List)
result.append(List)
return result
except Exception as err:
print("\ngetClassList() Error: {0}".format(err),"\n")
"""
getPermsList() grabs the information from "SELinux Perms list" and returns it as a list.
"""
def getPermsList():
try:
if os.path.exists(os.path.join(os.environ["PWD"], 'SELinux_Perms_list.txt')):
permsList = readInput(os.path.join(os.environ["PWD"], 'SELinux_Perms_list.txt'))
if not os.access(os.path.join(os.environ["PWD"], 'SELinux_Perms_list.txt'), os.R_OK):
print("\nFile SELinux_Perms_list.txt does not have read permissions!\nPlease change file permissions.\n")
sys.exit()
else:
print("Critical Error!: SELinux_Perms_list.txt not found in " + os.path.join(os.environ["PWD"]))
print("Please be sure it is under the correct name and in the present working directory.\n")
sys.exit()
result = ['']
for List in permsList:
List = re.sub('\n', '', List)
result.append(List)
return result
except Exception as err:
print("\ngetPermList() Error: {0}".format(err),"\n")
'''
Globaly declares classList for later use in the script.
'''
try:
classList = getClassList()
except Exception as err:
print("Error declaring global variable classList: {0}".format(err),"\n")
sys.exit()
'''
Globaly declares permsList for later use in the script.
'''
try:
permsList = getPermsList()
except Exception as err:
print("Error declaring global variable permsList: {0}".format(err),"\n")
sys.exit()
"""
createTables( outputFile (sqlite3 database) ) creates the necessary tables for the SQLite3 database
"""
def createTables( outputFile ):
try:
database = outputFile.cursor()
database.execute('''Pragma foreign_keys=off''')
database.execute('''create table if not exists tb_files
(FileId Integer primary key AUTOINCREMENT, Filename text)''')
database.execute('''create table if not exists tb_definitionNames
(definitionId Integer primary key AUTOINCREMENT NOT NULL, DefinitionName
Text NOT NULL)''')
database.execute('''create table if not exists tb_label
(LabelId Integer PRIMARY KEY AUTOINCREMENT NOT NULL, LabelClass INTEGER NOT NULL,
Name Text NOT NULL)''')
database.execute('''create table if not exists tb_labelSet
(LabelSetId Integer NOT NULL, LabelId NOT NULL, Modifier Integer NOT NULL,
primary key(LabelSetID, LabelId), foreign key(LabelId) references tb_label(LabelId))''')
database.execute('''create table if not exists tb_statement_declare
(StatementId Integer primary key AUTOINCREMENT NOT NULL, DeclarationClass Integer NOT NULL,
TargetId Integer NOT NULL, AliasId Integer, foreign key(TargetId) references tb_labelSet(LabelSetId),
foreign key(AliasId) references tb_labelSet(LabelSetId))''')
database.execute('''create table if not exists tb_statement_rule
(StatementId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, RuleClass Integer NOT NULL,
SourceId INTEGER NOT NULL, TargetId INTEGER NOT NULL, ClassesId INTEGER NOT NULL,
PrivilegeId INTEGER NOT NULL, FOREIGN KEY(SourceId) REFERENCES TB_LABELSET(LabelSetId),
FOREIGN KEY(TargetId) REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(ClassesId)
REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(PrivilegeId)
REFERENCES TB_LABELSET(LabelSetId))''')
database.execute('''create table if not exists tb_statement_interface
(StatementId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, InterfaceId INTEGER NOT NULL,
Arg1LabelId INTEGER NOT NULL, Arg2LabelId INTEGER, Arg3LabelId INTEGER, Arg4LabelId INTEGER,
Arg5LabelId INTEGER, FOREIGN KEY(InterfaceId) REFERENCES TB_DEFINITIONNAMES(DefinitionId),
FOREIGN KEY(Arg1LabelId) REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(Arg2LabelId)
REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(Arg3LabelId) REFERENCES TB_LABELSET(LabelSetId),
FOREIGN KEY(Arg4LabelId) REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(Arg5LabelId)
REFERENCES TB_LABELSET(LabelSetId))''')
database.execute('''create table if not exists tb_statement_assign
(StatementId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, AssignationType INTEGER NOT NULL,
TargetLabelId INTEGER NOT NULL, AssignedLabelId INTEGER NOT NULL, FOREIGN KEY(TargetLabelId)
REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(AssignedLabelId) REFERENCES TB_LABELSET(LabelSetId))''')
database.execute('''create table if not exists tb_statement_roletrans
(StatementId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, ArgId INTEGER NOT NULL,
TypeId INTEGER NOT NULL, RoleId INTEGER NOT NULL, FOREIGN KEY(ArgId)
REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(TypeId) REFERENCES TB_LABELSET(LabelSetId),
FOREIGN KEY(RoleId) REFERENCES TB_LABELSET(LabelSetId))''')
database.execute('''create table if not exists tb_statement_typetrans
(StatementId INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, SourceId INTEGER NOT NULL,
ResourceId INTEGER NOT NULL, TargetId INTEGER NOT NULL, ClassId INTEGER NOT NULL,
FileId INTEGER, FOREIGN KEY(SourceId) REFERENCES TB_LABELSET(LabelSetId),
FOREIGN KEY(ResourceId) REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(TargetId)
REFERENCES TB_LABELSET(LabelSetId), FOREIGN KEY(ClassId) REFERENCES TB_LABELSET(LabelSetId),
FOREIGN KEY(FileId) REFERENCES TB_LABELSET(LabelSetId))''')
database.execute('''create table if not exists tb_definition_content
(DefinitionId INTEGER NOT NULL, StatementDeclareId INTEGER, StatementRuleId INTEGER,
StatementInterfaceId INTEGER, StatementAssignId INTEGER, StatementRoleTransId, StatementTypeTransId,
FOREIGN KEY(DefinitionId) REFERENCES TB_DEFINITIONNAMES(DefinitionId),
FOREIGN KEY(StatementDeclareId) REFERENCES TB_STATEMENT_DECLARE(StatementId),
FOREIGN KEY(StatementRuleId) REFERENCES TB_STATEMENT_RULE(StatementId),
FOREIGN KEY(StatementInterfaceId) REFERENCES TB_STATEMENT_INTERFACE(StatementId),
FOREIGN KEY(StatementAssignId) REFERENCES TB_STATEMENT_ASSIGN(StatementId)
FOREIGN KEY(StatementRoleTransId) REFERENCES TB_STATEMENT_ROLETRANS(StatementId)
FOREIGN KEY(StatementTypeTransId) REFERENCES TB_STATEMENT_TYPETRANS(StatementId))''')
database.execute('''create table if not exists tb_source
(FileId INTEGER NOT NULL, LineNumber INTEGER NOT NULL, StatementDeclareId INTEGER,
StatementRuleId INTEGER, StatementInterfaceId INTEGER, StatementAssignId INTEGER,
StatementRoleTransId INTEGER, StatementTypeTransId INTEGER,
FOREIGN KEY(StatementDeclareId) REFERENCES TB_STATEMENT_DECLARE(StatementId),
FOREIGN KEY(StatementRuleId) REFERENCES TB_STATEMENT_RULE(StatementId),
FOREIGN KEY(StatementInterfaceId) REFERENCES TB_STATEMENT_INTERFACE(StatementId),
FOREIGN KEY(StatementAssignId) REFERENCES TB_STATEMENT_ASSIGN(StatementId),
FOREIGN KEY(StatementRoleTransId) REFERENCES TB_STATEMENT_ROLETRANS(StatementId)
FOREIGN KEY(StatementTypeTransId) REFERENCES TB_STATEMENT_TYPETRANS(StatementId))''')
except sqlite3.OperationalError as err:
print("\ncreateTables() Error: {0}".format(err),"\n")
sys.exit()
except Exception as err:
print("\ncreateTables() Error: {0}".format(err),"\n")
outputFile.commit()
database.close()
"""
cleanDefine( lines (String) ) reads in lines of the input files and "cleans" them up, removing any unnecessary new lines for
the definition records and returns them in a clean array.
"""
def cleanDefine( lines ):
try:
cleanDefine = []
record = []
defineCheck = False
for line in lines:
#line = re.sub('## .*$', '', line) # Removes the ## <record type> record from parsed output
if re.search('^## definition', line):
defineCheck = True
record = []
elif re.search('^\n', line):
defineCheck = False
cleanDefine.append(record)
if defineCheck:
#line = re.sub('^# ', '', line)
if line == '\n':
continue
line = re.sub('\n', '', line)
record.append(line)
cleanDefine.append(record) # Grabs final record in definition records.
return cleanDefine
except Exception as err:
print("\ncleanDefine() Error: {0}".format(err),"\n")
print("With record:\n " + record)
sys.exit()
"""
cleanSource( lines (String) ) reads in lines of the input files and "cleans" them up, removing any unnecessary new lines for
source records and returns them in a clean array.
"""
def cleanSource( lines ):
try:
cleanSource = []
record = []
sourceCheck = False
for line in lines:
#line = re.sub('# line: ', '', line)# Removes "# line: " from input.
if re.search('^## source', line):
sourceCheck = True
record = []
elif re.search('^\n', line):
sourceCheck = False
cleanSource.append(record)
if sourceCheck:
#line = re.sub('^# ', '', line)
if line == '\n':
continue
line = re.sub('\n', '', line)
record.append(line)
cleanSource.append(record) # Grabs final source record.
return cleanSource
except Exception as err:
print("\ncleanSource() Error: {0}".format(err),"\n")
print("With record:\n " + record)
sys.exit()
"""