Description:Code optimization

Feature or Bugfix:Bugfix
Binary Source:No

Signed-off-by: lwx1281857 <linnanmu@h-partners.com>
This commit is contained in:
lwx1281857 2024-07-11 19:51:10 +08:00
parent 9f00689092
commit 43392e239e
7 changed files with 157 additions and 143 deletions

View File

@ -23,6 +23,7 @@ sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,
os.pardir, os.pardir, os.pardir, os.pardir, "build"))
from scripts.util import build_utils # noqa: E402
def parse_args(args):
args = build_utils.expand_file_args(args)
@ -35,6 +36,7 @@ def parse_args(args):
options, _ = parser.parse_args(args)
return options
def parse_params(line, contents):
line = line.strip()
pos = line.find('=')
@ -46,11 +48,13 @@ def parse_params(line, contents):
value = value.strip()
contents[name] = value
def parse_extra_params(extras, contents):
for extra in extras:
extra = extra.strip()
parse_params(extra, contents)
def fix_para_file(options):
contents = {}
@ -73,6 +77,7 @@ def fix_para_file(options):
for key in contents:
f.write("".join([key, "=", contents[key], '\n']))
def main(args):
options = parse_args(args)

View File

@ -106,72 +106,80 @@ def append_group_files(target_f, options):
for item in source_dict:
target_f.write(f"{item}:{':'.join(source_dict[item])}\n")
def handle_passwd_info(passwdInfo, limits):
isPassed = True
name = passwdInfo[0].strip()
gid = int(passwdInfo[3], 10)
uid = int(passwdInfo[2], 10)
def handle_passwd_info(passwd_info, limits):
is_passed = True
name = passwd_info[0].strip()
gid = int(passwd_info[3], 10)
uid = int(passwd_info[2], 10)
if gid >= int(limits[0]) and gid <= int(limits[1]):
pass
else:
isPassed = False
is_passed = False
log_str = "error: name={} gid={} is not in range {}".format(name, gid, limits)
print(log_str)
if uid >= int(limits[0]) and uid <= int(limits[1]):
pass
else:
isPassed = False
is_passed = False
log_str = "error: name={} uid={} is not in range {}".format(name, gid, limits)
print(log_str)
return isPassed
return is_passed
def check_passwd_file(file_name, limits):
isPassed = True
is_passed = True
with open(file_name, encoding='utf-8') as fp:
line = fp.readline()
while line :
if line.startswith("#") or len(line) < 3:
line = fp.readline()
continue
passwdInfo = line.strip("\n").split(":")
if len (passwdInfo) < 4:
passwd_info = line.strip("\n").split(":")
if len(passwd_info) < 4:
line = fp.readline()
continue
if not handle_passwd_info(passwdInfo, limits):
isPassed = False
if not handle_passwd_info(passwd_info, limits):
is_passed = False
line = fp.readline()
return isPassed
return is_passed
def load_file(file_name, limit):
if not os.path.exists(file_name):
print("error: %s is not exit", file_name)
return False
isPassed = True
is_passed = True
limits = limit.split("-")
try:
isPassed = check_passwd_file(file_name, limits)
is_passed = check_passwd_file(file_name, limits)
except:
raise Exception("Exception in reading passwd, file name:", file_name)
return isPassed
return is_passed
def append_passwd_files(target_f, options):
# Read source file
file_list = options.source_file.split(":")
range_list = options.input_ranges.split(":")
for i in range(len(file_list)):
if not load_file(file_list[i], range_list[i]):
# check gid/uid Exception log: raise Exception("Exception, check passwd file error, ", file_list[i])
print("error: heck passwd file error, file path: ", file_list[i])
for i, file in enumerate(file_list):
if i >= len(range_list):
print("error: %s is error", file)
return
if not load_file(file, range_list[i]):
# check gid/uid Exception log: raise Exception("Exception, check passwd file error, ", file)
print("error: heck passwd file error, file path: ", file)
pass
try:
with open(file_list[i], 'r') as source_f:
with open(file, 'r') as source_f:
source_contents = source_f.read()
target_f.write(source_contents)
except:
raise Exception("Exception in appending passwd, file name:", file_list[i])
raise Exception("Exception in appending passwd, file name:", file)
def main(args):
sys.path.append(os.path.join(os.path.dirname(__file__), os.pardir, os.pardir,

View File

@ -27,7 +27,7 @@ supported_parse_item = ['labelName', 'priority', 'allowList', 'blockList', 'prio
'allowListWithArgs', 'headFiles', 'selfDefineSyscall', 'returnValue', \
'mode', 'privilegedProcessName', 'allowBlockList']
supported_architecture = ['arm', 'arm64','riscv64']
supported_architecture = ['arm', 'arm64', 'riscv64']
BPF_JGE = 'BPF_JUMP(BPF_JMP|BPF_JGE|BPF_K, {}, {}, {}),'
BPF_JGT = 'BPF_JUMP(BPF_JMP|BPF_JGT|BPF_K, {}, {}, {}),'
@ -343,6 +343,89 @@ class GenBpfPolicy:
'&' : self.gen_bpf_set,
}
@staticmethod
def gen_bpf_eq32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JEQ.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_eq64(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JEQ.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_gt32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JGT.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_gt64(const_str, jt, jf):
bpf_policy = []
number, digit_flag = str_convert_to_int(const_str)
hight = int(number / (2**32))
low = number & 0xffffffff
if digit_flag and hight == 0:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
else:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 3, 0))
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JGT.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_ge32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JGE.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_ge64(const_str, jt, jf):
bpf_policy = []
number, digit_flag = str_convert_to_int(const_str)
hight = int(number / (2**32))
low = number & 0xffffffff
if digit_flag and hight == 0:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
else:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 3, 0))
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JGE.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_set32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JSET.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_set64(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JSET.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JSET.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_valid_syscall_nr(syscall_nr, cur_size):
bpf_policy = []
bpf_policy.append(BPF_LOAD.format(0))
bpf_policy.append(BPF_JEQ.format(syscall_nr, 0, cur_size))
return bpf_policy
def update_arch(self, arch):
self.arch = arch
self.syscall_nr_range = []
@ -377,20 +460,6 @@ class GenBpfPolicy:
self.return_value = return_value
@staticmethod
def gen_bpf_eq32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JEQ.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_eq64(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JEQ.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
def gen_bpf_eq(self, const_str, jt, jf):
if self.arch == 'arm':
return self.gen_bpf_eq32(const_str, jt, jf)
@ -401,31 +470,6 @@ class GenBpfPolicy:
def gen_bpf_ne(self, const_str, jt, jf):
return self.gen_bpf_eq(const_str, jf, jt)
@staticmethod
def gen_bpf_gt32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JGT.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_gt64(const_str, jt, jf):
bpf_policy = []
number, digit_flag = str_convert_to_int(const_str)
hight = int(number / (2**32))
low = number & 0xffffffff
if digit_flag and hight == 0:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
else:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 3, 0))
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JGT.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
def gen_bpf_gt(self, const_str, jt, jf):
if self.arch == 'arm':
return self.gen_bpf_gt32(const_str, jt, jf)
@ -436,29 +480,6 @@ class GenBpfPolicy:
def gen_bpf_le(self, const_str, jt, jf):
return self.gen_bpf_gt(const_str, jf, jt)
@staticmethod
def gen_bpf_ge32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JGE.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_ge64(const_str, jt, jf):
bpf_policy = []
number, digit_flag = str_convert_to_int(const_str)
hight = int(number / (2**32))
low = number & 0xffffffff
if digit_flag and hight == 0:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
else:
bpf_policy.append(BPF_JGT.format('((unsigned long)' + const_str + ') >> 32', jt + 3, 0))
bpf_policy.append(BPF_JEQ.format('((unsigned long)' + const_str + ') >> 32', 0, jf + 2))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JGE.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
def gen_bpf_ge(self, const_str, jt, jf):
if self.arch == 'arm':
return self.gen_bpf_ge32(const_str, jt, jf)
@ -469,20 +490,6 @@ class GenBpfPolicy:
def gen_bpf_lt(self, const_str, jt, jf):
return self.gen_bpf_ge(const_str, jf, jt)
@staticmethod
def gen_bpf_set32(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JSET.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
@staticmethod
def gen_bpf_set64(const_str, jt, jf):
bpf_policy = []
bpf_policy.append(BPF_JSET.format('((unsigned long)' + const_str + ') >> 32', jt + 2, 0))
bpf_policy.append(BPF_LOAD_MEM.format(0))
bpf_policy.append(BPF_JSET.format(const_str + ' & 0xffffffff', jt, jf))
return bpf_policy
def gen_bpf_set(self, const_str, jt, jf):
if self.arch == 'arm':
return self.gen_bpf_set32(const_str, jt, jf)
@ -490,13 +497,6 @@ class GenBpfPolicy:
return self.gen_bpf_set64(const_str, jt, jf)
return []
@staticmethod
def gen_bpf_valid_syscall_nr(syscall_nr, cur_size):
bpf_policy = []
bpf_policy.append(BPF_LOAD.format(0))
bpf_policy.append(BPF_JEQ.format(syscall_nr, 0, cur_size))
return bpf_policy
def gen_range_list(self, syscall_nr_list):
if len(syscall_nr_list) == 0:
return

View File

@ -28,27 +28,6 @@ class MergePolicy:
self.arches = set()
self.seccomp_policy_param = dict()
def update_parse_item(self, line):
item = line[1:]
if item in gen_policy.supported_parse_item:
self.cur_parse_item = item
print('start deal with {}'.format(self.cur_parse_item))
def parse_line(self, line):
if not self.cur_parse_item :
return
line = line.replace(' ', '')
pos = line.rfind(';')
if pos < 0:
for arch in self.arches:
self.seccomp_policy_param.get(arch).value_function.get(self.cur_parse_item)(line)
else:
arches = line[pos + 1:].split(',')
if arches[0] == 'all':
arches = gen_policy.supported_architecture
for arch in arches:
self.seccomp_policy_param.get(arch).value_function.get(self.cur_parse_item)(line[:pos])
@staticmethod
def get_item_content(name_nr_table, item_str, itme_dict):
syscall_name_dict = {}
@ -89,6 +68,28 @@ class MergePolicy:
[func_name for func_name, _ in syscall_name_dict.get('riscv64')]))
return content
def update_parse_item(self, line):
item = line[1:]
if item in gen_policy.supported_parse_item:
self.cur_parse_item = item
print('start deal with {}'.format(self.cur_parse_item))
def parse_line(self, line):
if not self.cur_parse_item :
return
line = line.replace(' ', '')
pos = line.rfind(';')
if pos < 0:
for arch in self.arches:
self.seccomp_policy_param.get(arch).value_function.get(self.cur_parse_item)(line)
else:
arches = line[pos + 1:].split(',')
if arches[0] == 'all':
arches = gen_policy.supported_architecture
for arch in arches:
self.seccomp_policy_param.get(arch).value_function.get(self.cur_parse_item)(line[:pos])
def parse_open_file(self, fp):
for line in fp:
line = line.strip()