csp字符串匹配python
时间: 2025-04-18 16:47:43 浏览: 26
### Python 中实现 CSP 内容安全策略的字符串匹配
为了实现在 Python 中对 CSP (内容安全策略) 的字符串匹配,可以创建一个函数来解析并验证给定的内容是否遵循指定的安全策略。下面是一个简单的例子,该例子展示了如何定义和应用基本的 CSP 规则到 HTML 文档中的脚本源。
#### 定义 CSP 类来进行规则匹配
```python
class ContentSecurityPolicy:
def __init__(self, policy_string):
self.rules = {}
parts = policy_string.split(';')
for part in parts:
key_value = part.strip().split(' ', 1)
if len(key_value) == 2:
directive, value = key_value
self.rules[directive] = value
def is_allowed(self, directive, resource_uri):
allowed_values = self.rules.get(directive, '').split()
# Handle special cases like 'self', 'none'
if "'self'" in allowed_values and resource_uri.startswith(('http://localhost', 'https://localhost')):
return True
if "'none'" in allowed_values or not allowed_values:
return False
# Check exact matches or domain-based rules
for val in allowed_values:
if resource_uri == val or resource_uri.startswith(val.rstrip('/').rstrip('*') + '/'):
return True
return False
```
此 `ContentSecurityPolicy` 类接收一个表示 CSP 设置的字符串作为输入,并将其分解成各个指令及其对应的允许值列表。对于每个要检查的 URI 或者资源路径,可以通过调用 `is_allowed()` 方法传入相应的指令名称以及待检测的目标 URL 来判断其合法性[^1]。
#### 使用示例
假设有一个如下所示的 CSP 策略:
```plaintext
script-src 'self'; object-src 'none'; style-src cdn.example.org third-party.org; child-src https:
```
那么就可以这样实例化对象并对特定资源进行权限查询:
```python
csp_policy = ContentSecurityPolicy(
"script-src 'self'; object-src 'none'; style-src cdn.example.org third-party.org; child-src https:"
)
print(csp_policy.is_allowed('script-src', 'https://example.com/script.js')) # 输出: False
print(csp_policy.is_allowed('style-src', 'https://cdn.example.org/style.css')) # 输出: True
print(csp_policy.is_allowed('object-src', 'data:image/png;base64,...')) # 输出: False
```
上述代码片段中,针对不同的资源请求进行了合规性的检验操作,返回的结果表明这些资源是否符合预先设定好的 CSP 政策约束条件。
阅读全文
相关推荐


















