python实现ABAC:主体、客体和环境属性集合各有10个,每一个策略中主体、客体和环境相关的规则由3-5个属性的布尔表达式随机生成,每个用户请求中也是随机生成3-5个生成策略与请求各10000个,记录决策结果
时间: 2024-02-06 22:09:03 浏览: 129
常用的多属性决策方法Python实现
以下是一个简单的 Python ABAC 实现,包括主体、客体和环境属性集合,以及随机生成的策略和请求。每个策略和请求都由3-5个属性的布尔表达式随机生成,并记录决策结果。
```python
import random
class ABAC:
def __init__(self):
self.subject_attrs = set()
self.object_attrs = set()
self.env_attrs = set()
self.policies = []
self.requests = []
self.decisions = []
def generate_attrs(self, num_attrs):
attrs = set()
while len(attrs) < num_attrs:
attrs.add(random.randint(1, 100))
return attrs
def generate_policy(self):
policy = {
'subject': set(),
'object': set(),
'environment': set(),
'rules': []
}
for i in range(random.randint(3, 5)):
subject_attr = random.choice(list(self.subject_attrs))
object_attr = random.choice(list(self.object_attrs))
env_attr = random.choice(list(self.env_attrs))
rule = f"{subject_attr} AND {object_attr} AND NOT {env_attr}"
policy['subject'].add(subject_attr)
policy['object'].add(object_attr)
policy['environment'].add(env_attr)
policy['rules'].append(rule)
return policy
def generate_request(self):
request = {
'subject': set(),
'object': set(),
'environment': set(),
'result': None
}
for i in range(random.randint(3, 5)):
subject_attr = random.choice(list(self.subject_attrs))
object_attr = random.choice(list(self.object_attrs))
env_attr = random.choice(list(self.env_attrs))
request['subject'].add(subject_attr)
request['object'].add(object_attr)
request['environment'].add(env_attr)
self.requests.append(request)
def evaluate_policy(self, policy, request):
for rule in policy['rules']:
if not eval(rule, {'subject': request['subject'],
'object': request['object'],
'environment': request['environment']}):
return False
return True
def run(self, num_subject_attrs=10, num_object_attrs=10, num_env_attrs=10, num_policies=10000, num_requests=10000):
self.subject_attrs = self.generate_attrs(num_subject_attrs)
self.object_attrs = self.generate_attrs(num_object_attrs)
self.env_attrs = self.generate_attrs(num_env_attrs)
for i in range(num_policies):
policy = self.generate_policy()
self.policies.append(policy)
for i in range(num_requests):
request = self.generate_request()
for policy in self.policies:
if self.evaluate_policy(policy, request):
request['result'] = True
break
else:
request['result'] = False
self.decisions.append(request['result'])
```
可以使用以下代码运行ABAC模拟:
```python
abac = ABAC()
abac.run()
print(sum(abac.decisions) / len(abac.decisions))
```
输出结果将为所有请求的平均决策结果。
阅读全文