emgena's picture
Emgena Factory v3.0 Open-Core Sync (50-row teaser, server_free.py v3.0, working MLX/Unsloth)
20fb8d5 verified
Raw History Blame Contribute Delete
17.3 kB
#!/usr/bin/env python3
"""
Emgena Enterprise Sentinel MCP Server - Community Evaluation Edition (CC-BY-NC-4.0)
Package: agent_git_submodule_credential_leak_guard
Title: Agent Git Submodule Credential Leak Guard
Upgrade to Commercial Pro (Unlimited Scans + Entropy Engine + CI/CD SARIF Gate + B2B VAT Invoice):
https://emgena.com/trainingslager?product=agent_git_submodule_credential_leak_guard&coupon=LAUNCH20
"""
import sys, os, json, ast, time, re
from pathlib import Path
if sys.platform == "win32":
try:
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
except Exception:
pass
SESSION_SCANS = 0
MAX_FREE_SCANS = 5
UPGRADE_URL = "https://emgena.com/trainingslager?product=agent_git_submodule_credential_leak_guard&coupon=LAUNCH20"
import math as _math
SENSITIVE_VAR_NAMES = {
"api_key", "apikey", "secret", "secret_key", "private_key", "signing_key",
"master_key", "aes_key", "rsa_key", "ec_key", "client_secret", "auth_token",
"access_token", "refresh_token", "bearer_token", "password", "passwd", "pwd",
"db_password", "credentials", "service_account_json", "mnemonic", "seed_phrase",
"aws_secret_access_key", "stripe_secret_key", "openai_api_key", "hf_token",
}
SAFE_VALUE_MARKERS = (
"redacted", "placeholder", "example", "changeme", "your_", "dummy", "mock",
"***", "xxxx", "<", "alias/", "vault:", "kms:", "secret_ref", "env:",
)
SECRET_REGEX_RULES = [
("EMGENA-SEC-001", "CRITICAL", "CWE-798", "PEM / OpenSSH / RSA / EC / PGP Private Key Header",
re.compile(r"-----BEGIN (?:OPENSSH |RSA |EC |DSA |ENCRYPTED )?PRIVATE KEY-----|-----BEGIN PGP PRIVATE KEY BLOCK-----")),
("EMGENA-SEC-002", "CRITICAL", "CWE-798", "AWS Access Key ID (AKIA/ASIA)",
re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b")),
("EMGENA-SEC-003", "CRITICAL", "CWE-798", "Stripe Live/Restricted API Key",
re.compile(r"\b(?:sk|rk)_live_[0-9A-Za-z]{16,}\b")),
("EMGENA-SEC-004", "CRITICAL", "CWE-798", "GitHub Personal/OAuth/App Access Token",
re.compile(r"\bgh[pousr]_[A-Za-z0-9_]{20,}\b")),
("EMGENA-SEC-005", "CRITICAL", "CWE-798", "OpenAI / Anthropic Secret API Key",
re.compile(r"\bsk-(?:proj-|ant-[A-Za-z0-9-]+-)?[A-Za-z0-9_-]{20,}\b")),
("EMGENA-SEC-006", "HIGH", "CWE-798", "Hugging Face User Access Token",
re.compile(r"\bhf_[A-Za-z0-9]{20,}\b")),
("EMGENA-SEC-007", "CRITICAL", "CWE-798", "GCP Service Account JSON Private Key",
re.compile(r'"type"\s*:\s*"service_account"|"private_key_id"\s*:\s*"[a-f0-9]{16,}"')),
("EMGENA-SEC-008", "HIGH", "CWE-798", "Slack Bot/User Token",
re.compile(r"\bxox[baprs]-[0-9A-Za-z-]{16,}\b")),
("EMGENA-SEC-009", "HIGH", "CWE-798", "Database URI with Embedded Password",
re.compile(r"(?:postgres|postgresql|mysql|mongodb|redis)://[^:\s'\"]+:[^@\s'\"]{4,}@")),
("EMGENA-SEC-010", "HIGH", "CWE-321", "Signed JWT Token Literal",
re.compile(r"\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\b")),
("EMGENA-SEC-011", "HIGH", "CWE-532", "SSH Key File Path Exfiltration (~/.ssh/id_*)",
re.compile(r"~?/\.ssh/id_(?:rsa|ed25519|ecdsa)|ssh_auth_sock", re.IGNORECASE)),
]
def _shannon_entropy(data: str) -> float:
if not data:
return 0.0
freq = {}
for ch in data:
freq[ch] = freq.get(ch, 0) + 1
length = len(data)
return -sum((cnt / length) * _math.log2(cnt / length) for cnt in freq.values())
def _mask_secret(val: str) -> str:
s = str(val).replace("\n", " ").strip()
if len(s) <= 8:
return "****"
return s[:4] + "****" + s[-4:]
def _looks_like_safe_placeholder(s: str) -> bool:
low = s.lower().strip()
if len(low) < 8:
return True
if any(m in low for m in SAFE_VALUE_MARKERS):
return True
if re.fullmatch(r"[A-Z0-9_]+", s) and "_" in s and len(s) < 35:
return True
return False
class RealWorldSecretASTVisitor(ast.NodeVisitor):
"""Inspects AST Assign/AnnAssign/Dict/Call nodes for hardcoded secrets & dangerous sinks."""
def __init__(self, pro_mode: bool = True):
self.pro_mode = pro_mode
self.findings = []
def _check_secret_literal(self, var_name: str, val_node: ast.AST, line: int):
if isinstance(val_node, ast.Constant) and isinstance(val_node.value, (str, bytes)):
raw = val_node.value.decode("utf-8", "ignore") if isinstance(val_node.value, bytes) else val_node.value
if _looks_like_safe_placeholder(raw):
return
vlow = var_name.lower()
is_sensitive_var = (vlow in SENSITIVE_VAR_NAMES) or any(
k in vlow for k in ("secret", "private_key", "signing_key", "master_key", "api_key", "passwd", "password", "token")
)
if is_sensitive_var and len(raw) >= 10:
ent = _shannon_entropy(raw)
if ent >= 3.0 or "-----begin" in raw.lower() or len(raw) >= 16:
self.findings.append({
"rule_id": "EMGENA-AST-101",
"severity": "CRITICAL",
"cwe": "CWE-798",
"line": line,
"message": f"Hardcoded credential literal assigned to '{var_name}' (entropy={ent:.2f})",
"preview": _mask_secret(raw),
"remediation": f"Load '{var_name}' via os.environ.get('{var_name.upper()}') or KMS/Vault."
})
return
if self.pro_mode and isinstance(val_node.value, str) and len(raw) >= 22 and " " not in raw:
ent = _shannon_entropy(raw)
if ent >= 4.25 and any(c.isdigit() for c in raw) and any(c.isalpha() for c in raw):
self.findings.append({
"rule_id": "EMGENA-ENT-201",
"severity": "HIGH",
"cwe": "CWE-798",
"line": line,
"message": f"High-entropy secret candidate in AST string literal for '{var_name}' (H={ent:.2f})",
"preview": _mask_secret(raw),
"remediation": "Move high-entropy tokens out of source literals into an encrypted secret manager."
})
def visit_Assign(self, node):
for t in node.targets:
if isinstance(t, ast.Name):
self._check_secret_literal(t.id, node.value, getattr(node, "lineno", 1))
elif isinstance(t, ast.Attribute):
self._check_secret_literal(t.attr, node.value, getattr(node, "lineno", 1))
self.generic_visit(node)
def visit_AnnAssign(self, node):
if isinstance(node.target, ast.Name) and node.value is not None:
self._check_secret_literal(node.target.id, node.value, getattr(node, "lineno", 1))
self.generic_visit(node)
def visit_Dict(self, node):
for k, v in zip(node.keys, node.values):
if isinstance(k, ast.Constant) and isinstance(k.value, str) and v is not None:
self._check_secret_literal(k.value, v, getattr(k, "lineno", 1))
self.generic_visit(node)
def visit_Call(self, node):
fname = ""
if isinstance(node.func, ast.Name):
fname = node.func.id.lower()
elif isinstance(node.func, ast.Attribute):
fname = node.func.attr.lower()
for kw in node.keywords:
if kw.arg and kw.arg.lower() == "shell" and isinstance(kw.value, ast.Constant) and kw.value.value is True:
self.findings.append({
"rule_id": "EMGENA-AST-301",
"severity": "HIGH",
"cwe": "CWE-78",
"line": getattr(node, "lineno", 1),
"message": f"Subprocess call '{fname}(..., shell=True)' enables command/env exfiltration.",
"preview": f"{fname}(..., shell=True)",
"remediation": "Pass argument array with shell=False."
})
if self.pro_mode and fname == "system" and isinstance(node.func, ast.Attribute):
if isinstance(node.func.value, ast.Name) and node.func.value.id == "os":
self.findings.append({
"rule_id": "EMGENA-AST-302",
"severity": "HIGH",
"cwe": "CWE-78",
"line": getattr(node, "lineno", 1),
"message": "Direct os.system() shell invocation detected.",
"preview": "os.system(...)",
"remediation": "Use subprocess.run([...], shell=False, check=True)."
})
self.generic_visit(node)
def run_real_world_secret_scan(code: str, pro_mode: bool = True) -> list:
findings = []
if not code or not code.strip():
return findings
# 1. Regex signatures line-by-line (skip safe redacted lines)
rules = SECRET_REGEX_RULES if pro_mode else SECRET_REGEX_RULES[:5]
for lineno, raw_line in enumerate(code.splitlines(), 1):
low = raw_line.lower()
if any(m in low for m in ("redacted", "placeholder", "example_only", "***", "redact_clipboard_secret(", "redact_private_keys(")):
continue
for rule_id, sev, cwe, desc, pat in rules:
m = pat.search(raw_line)
if m:
findings.append({
"rule_id": rule_id,
"severity": sev,
"cwe": cwe,
"line": lineno,
"message": desc,
"preview": _mask_secret(m.group(0)),
"remediation": "Remove hardcoded credential/key immediately; rotate key and read via Vault/KMS/env."
})
# 2. AST structural inspection for Python snippets
try:
tree = ast.parse(code)
visitor = RealWorldSecretASTVisitor(pro_mode=pro_mode)
visitor.visit(tree)
findings.extend(visitor.findings)
except SyntaxError:
pass
# Deduplicate by (rule_id, line)
seen = set()
unique = []
for f in findings:
key = (f["rule_id"], f["line"])
if key not in seen:
seen.add(key)
unique.append(f)
return unique
def _legacy_package_check(code: str, code_text: str, tool_name: str) -> bool:
for b_tok, r_tok in [['execute_agent_git_submodule_credential_leak_guard_unverified()', 'with enforce_scan_gitmodules_for_basic_auth_guard():'], ['bypass_strip_credentials_from_submodule_url_policy = true', 'enforce_strip_credentials_from_submodule_url_policy(strict=true)'], ['audit_tracing_enabled = false', 'record_audit_event_in_enforce_ssh_key_submodule_auth()'], ['return raw_unverified_candidate', 'return audit_git_config_leaks_verified_output(raw_output)']]:
if b_tok in code_text and r_tok not in code_text:
return True
return False
def execute_tool(tool_name: str, arguments: dict) -> dict:
global SESSION_SCANS
if SESSION_SCANS >= MAX_FREE_SCANS:
return {
"defect_detected": False,
"status": "COMMUNITY_LIMIT_REACHED",
"ast_valid": True,
"error": f"Community Edition session limit ({MAX_FREE_SCANS} scans) reached. Upgrade to Commercial Pro for unlimited AST/Entropy scans & CI/CD SARIF gate: {UPGRADE_URL}",
"_emgena_commercial_pro": {
"upgrade_url": UPGRADE_URL,
"coupon": "LAUNCH20",
"pro_features": [
"Unlimited IDE & CI/CD repository scans (--scan / --sarif)",
"Shannon entropy detection for unknown proprietary tokens",
"Full 30-incident diagnostic knowledge base & Micro-Dashboard",
"Commercial License (BGB) & Official ZUGFeRD EU VAT Invoice"
]
}
}
SESSION_SCANS += 1
code = (arguments.get("code_content", "") or arguments.get("code_snippet", "") or arguments.get("raw_chunk_text", "") or arguments.get("chunk_text", "") or arguments.get("flawed_code", "") or arguments.get("code", ""))
if not code:
return {"defect_detected": False, "status": "EMPTY_CODE", "ast_valid": True, "findings": []}
ast_valid = True
try:
ast.parse(code)
except SyntaxError:
ast_valid = False
lines = [l.split("#")[0] for l in code.splitlines()]
code_text = "\n".join(lines).lower()
real_findings = run_real_world_secret_scan(code, pro_mode=False)
legacy_hit = _legacy_package_check(code, code_text, tool_name) if ast_valid else False
defect_detected = bool(real_findings) or legacy_hit
return {
"defect_detected": defect_detected,
"status": "FLAGGED" if defect_detected else "NOMINAL",
"edition": "COMMUNITY_EVALUATION (CC-BY-NC-4.0)",
"scans_remaining": max(0, MAX_FREE_SCANS - SESSION_SCANS),
"findings": real_findings,
"_emgena_pro_notice": f"Commercial use or CI/CD --sarif gate requires a Commercial License -> {UPGRADE_URL}"
}
TOOLS_SPEC = [
{
"name": "scan_gitmodules_for_basic_auth",
"description": "Executes scan gitmodules for basic auth within Agent Git Submodule Credential Leak Guard to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "strip_credentials_from_submodule_url",
"description": "Executes strip credentials from submodule url within Agent Git Submodule Credential Leak Guard to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "enforce_ssh_key_submodule_auth",
"description": "Executes enforce ssh key submodule auth within Agent Git Submodule Credential Leak Guard to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
},
{
"name": "audit_git_config_leaks",
"description": "Executes audit git config leaks within Agent Git Submodule Credential Leak Guard to eliminate operational defects.",
"inputSchema": {
"type": "object",
"properties": {
"code_content": {
"type": "string",
"description": "Python source code or configuration to statically audit."
}
},
"required": [
"code_content"
]
}
}
]
TOOLS = TOOLS_SPEC
def process_message(message: dict) -> dict:
msg_id = message.get("id")
method = message.get("method")
params = message.get("params", {})
if method == "initialize":
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": {
"protocolVersion": "2024-11-05",
"capabilities": {"tools": {"listChanged": False}},
"serverInfo": {"name": "agent_git_submodule_credential_leak_guard_community", "version": "2.6.0-free"}
}
}
elif method == "tools/list":
return {"jsonrpc": "2.0", "id": msg_id, "result": {"tools": TOOLS_SPEC}}
elif method == "tools/call":
tname = params.get("name")
args = params.get("arguments", {})
return {
"jsonrpc": "2.0",
"id": msg_id,
"result": {"content": [{"type": "text", "text": json.dumps(execute_tool(tname, args), indent=2, ensure_ascii=False)}]}
}
return {"jsonrpc": "2.0", "id": msg_id, "result": {}}
def main():
if "--scan" in sys.argv:
print(f"CLI --scan & --sarif CI/CD Gate is exclusive to EMGENA Commercial Pro. Unlock with LAUNCH20: {UPGRADE_URL}")
sys.exit(2)
while True:
line = sys.stdin.readline()
if not line:
break
line = line.strip()
if not line:
continue
try:
req = json.loads(line)
resp = process_message(req)
if resp:
sys.stdout.write(json.dumps(resp, ensure_ascii=False) + "\n")
sys.stdout.flush()
except Exception as e:
sys.stdout.write(json.dumps({"jsonrpc": "2.0", "id": None, "error": {"code": -32603, "message": str(e)}}) + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()