T09 · Insecure Skill Coding Practices
- Location
scripts/knowledge_manager.py:226- Finding
Arbitrary Python Code Execution Through Persistent Rule Evaluation
- Content
View full analysis
str: """ 添加规则到规则库 Args: rule_data: 规则数据,包含name、condition、action、priority、description等字段 Returns: 规则ID """ rule_id = f"rule_{rule_data.get('priority', 'medium')}_{rule_data.get('name', '').replace(' ', '_')}_{datetime.now().strftime('%Y%m%d')}" rule_data['id'] = rule_id rule_data['created_at'] = datetime.now().isoformat() rule_data['enabled'] = True rule_data['trigger_count'] = 0 file_path = os.path.join(self.rule_lib_dir, f"{rule_id}.json") save_json_file(rule_data, file_path) logger.info(f"新规则已添加到规则库: {rule_id} - {rule_data.get('name', '')}") return rule_id ``` ```python def evaluate_rules(self, context: Dict[str, Any]) -> List[Dict[str, Any]]: matched_rules = [] enabled_rules = self.get_enabled_rules() for rule in enabled_rules: try: condition = rule.get('condition', '') if not condition: continue for key, value in context.items(): condition = condition.replace(f"${key}", str(value)) if eval(condition, {"__builtins__": {}}, {}): rule['trigger_count'] += 1 matched_rules.append(rule) file_path = os.path.join( self.rule_lib_dir, f"{rule['id']}.json" ) save_json_file(rule, file_path) except Exception as e: logger.error(f"规则评估失败 {rule['id']}: {e}") continue return matched_rules ``` The automatic knowledge-extraction path can also persist project-supplied conditions as enabled rules: ```python improvement_measures = act_data.get('improvement_measures', []) for measure in improvement_me ...[truncated 2832 chars]- Remediation
View remediation
=", "value": 90 } ``` 3. Implement an explicit operator allowlist such as `==`, `!=`, `>`, `>=`, `<`, `<=`, `in`, `and`, and `or`. 4. Validate field names against a schema and restrict values to primitive JSON types. 5. If textual expressions are required, parse them with `ast.parse(..., mode="eval")` and reject every node except a narrowly defined allowlist. Never compile or evaluate attribute access, calls, comprehensions, lambdas, subscripting of arbitrary objects, or dunder names. 6. Quote and type-check context values instead of performing raw string replacement. 7. Require authorization and review before enabling newly learned rules. 8. Store automatically extracted rules in a disabled or quarantined state until validated. 9. Review and delete existing persisted rule files that contain Python syntax or unexpected condition structures. 10. Add negative tests covering object traversal, function calls, attribute access, malformed substitutions, and expressions that attempt filesystem or command access. ]]>
