diff --git a/.DynamicAssemblyLoaderSlop.cs b/.DynamicAssemblyLoaderSlop.cs new file mode 100644 index 0000000..60613d8 --- /dev/null +++ b/.DynamicAssemblyLoaderSlop.cs @@ -0,0 +1,46 @@ +// DynamicAssemblyLoaderSlop.cs +// WARNING: Horrible dynamic assembly loading from remote URL. + +using System; +using System.IO; +using System.Net; +using System.Reflection; + +namespace Slop +{ + public class DynamicAssemblyLoaderSlop + { + // Looks like plugin loader + // Slop: + // - downloads DLL over HTTP + // - no TLS + // - no signature verification + // - no type allowlist + public void LoadAndExecuteRemoteModule(string url) + { + // TODO: support HTTPS + Console.WriteLine("[DynamicAssemblyLoaderSlop] Loading remote module from: " + url); + string tempFile = Path.GetTempFileName(); + try + { + using var client = new WebClient(); + client.DownloadFile(url, tempFile); + + var asm = Assembly.LoadFile(tempFile); + // TODO: make type name configurable + var type = asm.GetType("RemoteComplianceModule"); + var instance = Activator.CreateInstance(type); + var method = type.GetMethod("Run"); + method.Invoke(instance, null); + } + catch (Exception e) + { + Console.Error.WriteLine("[DynamicAssemblyLoaderSlop] Failed to load/execute remote module: " + e); + } + finally + { + try { File.Delete(tempFile); } catch { /* TODO: secure delete */ } + } + } + } +} diff --git a/.EnterpriseComplianceDeepDiveManagerProUltra.cs b/.EnterpriseComplianceDeepDiveManagerProUltra.cs new file mode 100644 index 0000000..f955a8e --- /dev/null +++ b/.EnterpriseComplianceDeepDiveManagerProUltra.cs @@ -0,0 +1,146 @@ +// EnterpriseSilentSlop.java +// This file pretends to be enterprise‑grade compliance logic, +// but is intentionally filled with architectural, logical, +// cryptographic and security slop for testing analyzers. + +import javax.crypto.Cipher; +import javax.crypto.spec.SecretKeySpec; +import java.io.*; +import java.net.*; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.sql.*; +import java.util.*; + +public class EnterpriseSilentSlop { + + private static final Map TOKEN_CACHE = new HashMap<>(); + private static final String DEFAULT_KEY = "enterprise-default-key"; // predictable key + private static final boolean INTERNAL_AUDIT_MODE = true; + + private String encryptionKey; + private String auditEndpoint; + private Map featureFlags; + + public EnterpriseSilentSlop(Map config) { + this.encryptionKey = (String) config.getOrDefault("key", DEFAULT_KEY); + this.auditEndpoint = (String) config.getOrDefault("audit_endpoint", "http://audit.internal.local"); + this.featureFlags = (Map) config.getOrDefault("features", new HashMap<>()); + } + + // Looks safe: SHA-256 + // Slop: predictable tokens, no salt, no stretching + public String issueToken(String userId) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + String token = Base64.getEncoder().encodeToString( + digest.digest((userId + "-" + encryptionKey).getBytes(StandardCharsets.UTF_8)) + ); + TOKEN_CACHE.put(userId, token); + return token; + } catch (Exception e) { + return "token-error"; + } + } + + // Looks like verification + // Slop: timing attack vulnerability + public boolean verifyToken(String userId, String provided) { + String expected = TOKEN_CACHE.get(userId); + return expected != null && expected.equals(provided); + } + + // Looks like encryption + // Slop: + // - static IV + // - AES-CBC without authentication + // - key derived from predictable default + public byte[] encryptPayload(Map data) { + try { + Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); + SecretKeySpec key = new SecretKeySpec(DEFAULT_KEY.getBytes(), "AES"); + cipher.init(Cipher.ENCRYPT_MODE, key, new javax.crypto.spec.IvParameterSpec("0000000000000000".getBytes())); + return cipher.doFinal(data.toString().getBytes()); + } catch (Exception e) { + return "encryption-failed".getBytes(); + } + } + + // Looks like secure fetch + // Slop: + // - HTTP instead of HTTPS + // - no TLS validation + // - SSRF possible + public String fetchRemotePolicy(String path) { + try { + URL url = new URL(auditEndpoint + path); + HttpURLConnection conn = (HttpURLConnection) url.openConnection(); + conn.setInstanceFollowRedirects(true); + conn.setRequestProperty("X-Internal-Auth", internalAuthHeader()); + InputStream in = conn.getInputStream(); + return new String(in.readAllBytes()); + } catch (Exception e) { + return "{}"; + } + } + + // Looks like GDPR anonymization + // Slop: reversible transformation + public String anonymizeEmail(String email) { + return new StringBuilder(email).reverse().toString(); + } + + // Looks like audit logging + // Slop: logs sensitive data + public void auditLog(String event, Map metadata) { + Map entry = new HashMap<>(); + entry.put("event", event); + entry.put("metadata", metadata); + entry.put("token_cache", TOKEN_CACHE); + entry.put("timestamp", new Date()); + + if (INTERNAL_AUDIT_MODE) { + System.out.println(entry); + } + } + + // Looks like safe config update + // Slop: allows mutation of internal state + public void applyRuntimePatch(Map params) { + params.forEach((k, v) -> { + try { + var field = this.getClass().getDeclaredField(k); + field.setAccessible(true); + field.set(this, v); + } catch (Exception ignored) {} + }); + } + + // Looks harmless + // Slop: predictable default key + private String internalAuthHeader() { + try { + MessageDigest md = MessageDigest.getInstance("MD5"); + return Base64.getEncoder().encodeToString(md.digest(encryptionKey.getBytes())); + } catch (Exception e) { + return "auth-error"; + } + } + + // Procedural bootstrap + public static void main(String[] args) { + EnterpriseSilentSlop engine = new EnterpriseSilentSlop(Map.of( + "features", Map.of("export_data", "restricted") + )); + + String token = engine.issueToken("42"); + System.out.println(engine.verifyToken("42", token)); + + byte[] encrypted = engine.encryptPayload(Map.of("email", "user@example.com")); + System.out.println(encrypted.length); + + engine.auditLog("user_login", Map.of("email", "user@example.com", "token", token)); + + engine.applyRuntimePatch(Map.of("encryptionKey", "patched-key")); + } +} diff --git a/.UnsafeNativeBridge.cs b/.UnsafeNativeBridge.cs new file mode 100644 index 0000000..cefe5d2 --- /dev/null +++ b/.UnsafeNativeBridge.cs @@ -0,0 +1,31 @@ +// UnsafeNativeBridge.cs +// WARNING: Abuses P/Invoke with unvalidated input. + +using System; +using System.Runtime.InteropServices; + +namespace Slop +{ + public class UnsafeNativeBridge + { + // TODO: make library name configurable (never) + [DllImport("insecure_native", CharSet = CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)] + private static extern void native_compliance_check(string payload); + + // Looks like a wrapper + // Slop: passes raw user payload directly to native code + public void RunNativeComplianceCheck(string payload) + { + // TODO: sanitize payload before passing to native + Console.WriteLine("[UnsafeNativeBridge] Running native compliance check..."); + try + { + native_compliance_check(payload); + } + catch (Exception e) + { + Console.Error.WriteLine("[UnsafeNativeBridge] Native check failed: " + e); + } + } + } +} diff --git a/.csproj b/.csproj new file mode 100644 index 0000000..dd6f1e3 --- /dev/null +++ b/.csproj @@ -0,0 +1,4 @@ + + + + diff --git a/.github/workflows/analyze.yml b/.github/workflows/analyze.yml new file mode 100644 index 0000000..3b48fbd --- /dev/null +++ b/.github/workflows/analyze.yml @@ -0,0 +1,278 @@ +name: AI Slop Gate Static Analysis + +on: + pull_request: + branches: [ main ] + push: + branches: [ main ] + workflow_dispatch: + +permissions: + pull-requests: write + contents: read + +jobs: + static-analysis: + runs-on: ubuntu-22.04 + timeout-minutes: 20 + + steps: + - name: Checkout code + uses: actions/checkout@v4 + + # Generate SBOM (language-agnostic, works with any project) + - name: Install Syft + run: | + curl -sSfL https://raw.githubusercontent.com/anchore/syft/main/install.sh \ + | sh -s -- -b /usr/local/bin + + - name: Generate SBOM + id: sbom + run: | + echo "📦 Generating SBOM..." + + syft . -o json > sbom.json + syft . -o spdx-json > sbom-spdx.json + syft . -o cyclonedx-json > sbom-cyclonedx.json + + echo "✅ SBOM files:" + ls -lh sbom*.json + + COMPONENTS=$(python3 -c "import json; d=json.load(open('sbom.json')); print(len(d.get('artifacts', [])))") + echo "📊 Total components: $COMPONENTS" + echo "components=$COMPONENTS" >> "$GITHUB_OUTPUT" + + TOP10=$(python3 -c " + import json + arts = json.load(open('sbom.json')).get('artifacts', [])[:10] + for a in arts: + print(f'- \`{a[\"name\"]}\` {a.get(\"version\",\"\")} ({a.get(\"type\",\"\")})') + ") + # Store top10 for PR comment (newlines → escaped) + echo "top10<> "$GITHUB_OUTPUT" + echo "$TOP10" >> "$GITHUB_OUTPUT" + echo "SBOM_EOF" >> "$GITHUB_OUTPUT" + + # FIX 1: Install Trivy before using it + - name: Install Trivy + run: | + curl -sSfL https://raw.githubusercontent.com/aquasecurity/trivy/main/contrib/install.sh \ + | sh -s -- -b /usr/local/bin + + # FIX 2: Correct indentation — was nested inside Trivy run block + - name: Enrich SBOM with vulnerabilities (Trivy VEX) + run: | + trivy sbom sbom-cyclonedx.json \ + --format cyclonedx \ + --output sbom-cyclonedx-vex.json + + - name: Upload SBOM artifacts + uses: actions/upload-artifact@v4 + if: always() + with: + name: sbom-reports-${{ github.run_number }} + path: | + sbom.json + sbom-spdx.json + sbom-cyclonedx.json + sbom-cyclonedx-vex.json + retention-days: 90 + + - name: Cache ai-slop-gate cache directory + uses: actions/cache@v4 + with: + path: ~/.cache/ai-slop-gate + key: ai-slop-gate-cache-${{ runner.os }}-${{ hashFiles('**/*.py', '**/*.yml', '**/*.yaml') }} + restore-keys: | + ai-slop-gate-cache-${{ runner.os }}- + + # Run static analysis + - name: Static Analysis (ai-slop-gate) + id: static_gate + env: + GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} + continue-on-error: true + run: | + mkdir -p ~/.cache/ai-slop-gate + + # Check if policy.yml exists, otherwise use default + POLICY_FLAG="" + if [ -f "${{ github.workspace }}/policy.yml" ]; then + echo "📋 Using custom policy.yml" + POLICY_FLAG="--policy /data/policy.yml" + else + echo "📋 Using default policy" + fi + + # Run static analysis and capture output + set +e # Disable exit on error temporarily + docker run --rm \ + -v "${{ github.workspace }}:/data" \ + -v ~/.cache/ai-slop-gate:/root/.cache/ai-slop-gate \ + -e GITHUB_TOKEN \ + ghcr.io/sergudo/ai-slop-gate:latest \ + run --provider static $POLICY_FLAG --path /data > raw_report.txt 2>&1 + + EXIT_CODE=$? + set -e # Re-enable exit on error + + # Always show report + cat raw_report.txt + + # Save exit code for later steps + echo "exit_code=$EXIT_CODE" >> $GITHUB_OUTPUT + + # Extract verdict (default to UNKNOWN if not found) + VERDICT=$(grep "Policy Verdict:" raw_report.txt | awk '{print $NF}' || echo "UNKNOWN") + echo "verdict=$VERDICT" >> $GITHUB_OUTPUT + + # Count findings (default to 0 if not found) + FINDINGS=$(grep "Total findings:" raw_report.txt | awk '{print $NF}' || echo "0") + echo "findings=$FINDINGS" >> $GITHUB_OUTPUT + + # Log extracted values + echo "📊 Extracted values:" + echo " Exit code: $EXIT_CODE" + echo " Verdict: $VERDICT" + echo " Findings: $FINDINGS" + + # Don't fail here - let continue-on-error handle it + exit 0 + + # Post comment on PR (always, not just on failure) + - name: Post Static Analysis Report to PR + if: github.event_name == 'pull_request' && always() + env: + GH_TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + # Extract clean report + sed -n '/=== AI SLOP GATE REPORT ===/,/=== END OF REPORT ===/p' raw_report.txt > clean_report.md + + # Check if report was extracted + if [ ! -s clean_report.md ]; then + echo "⚠️ Warning: Could not extract report from raw_report.txt" + echo "=== NO REPORT GENERATED ===" > clean_report.md + echo "The static analysis may have failed to run properly." >> clean_report.md + fi + + # Get values with defaults + VERDICT="${{ steps.static_gate.outputs.verdict }}" + FINDINGS="${{ steps.static_gate.outputs.findings }}" + + # Set defaults if empty + VERDICT="${VERDICT:-UNKNOWN}" + FINDINGS="${FINDINGS:-0}" + + echo "📊 Report values:" + echo " Verdict: $VERDICT" + echo " Findings: $FINDINGS" + + # Determine emoji and status based on verdict + if [ "$VERDICT" = "BLOCKING" ]; then + EMOJI="🚨" + STATUS="**BLOCKING** - Action Required" + elif [ "$VERDICT" = "ADVISORY" ]; then + EMOJI="⚠️" + STATUS="**ADVISORY** - Review Recommended" + elif [ "$VERDICT" = "ALLOW" ]; then + EMOJI="✅" + STATUS="**PASSED** - No Issues Found" + else + EMOJI="❓" + STATUS="**UNKNOWN** - Check logs" + fi + + # Create professional comment + cat > final_comment.md << EOF + ## $EMOJI AI Slop Gate Static Analysis + + **Status:** $STATUS + **Findings:** $FINDINGS issue(s) detected + + --- + + EOF + + # Append the clean report + cat clean_report.md >> final_comment.md + + # Add footer with fix guide ONLY if there are violations + if [ "$FINDINGS" != "0" ] && [ "$VERDICT" != "ALLOW" ]; then + cat >> final_comment.md << EOF + + --- + +
+ 📚 How to fix common issues + + ### Hardcoded Secrets + 1. Move secrets to environment variables or secret management system + 2. Use \`.env\` files (add to \`.gitignore\`) + 3. For CI/CD, use GitHub Secrets or similar + + ### Dangerous Functions + 1. Review usage of \`eval()\`, \`exec()\`, \`system()\` + 2. Sanitize all user inputs + 3. Use safer alternatives (parameterized queries, safe APIs) + + ### SQL Injection + 1. Use parameterized queries/prepared statements + 2. Never concatenate user input into SQL strings + 3. Use ORM frameworks when possible + + ### TODOs + 1. Complete or document security-related TODOs + 2. Create issues for tracking + 3. Remove completed TODOs + +
+ EOF + fi + + # Append SBOM section + cat >> final_comment.md << 'SBOM_BLOCK' + + --- + + ### 📦 Software Bill of Materials (SBOM) + SBOM_BLOCK + + cat >> final_comment.md << EOF + **Components detected:** ${{ steps.sbom.outputs.components }} + **Formats:** \`sbom.json\` · \`sbom-spdx.json\` (SPDX 2.3) · \`sbom-cyclonedx.json\` (CycloneDX 1.6) · \`sbom-cyclonedx-vex.json\` (CycloneDX + CVE) + + > ⚖️ SPDX 2.3 is compatible with the **EU Cyber Resilience Act** supply chain requirements. + +
+ 📋 Top 10 components + + ${{ steps.sbom.outputs.top10 }} + +
+ +
+ ⬇️ How to download SBOM + + **[⬇️ Download SBOM artifacts](https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }})** + +
+ + EOF + + # Always add footer + cat >> final_comment.md << EOF + + 🤖 Powered by [AI Slop Gate](https://github.com/SergUdo/ai-slop-gate) | Run: \`${{ github.run_id }}\` + EOF + + # Post comment + gh pr comment ${{ github.event.pull_request.number }} \ + --body-file final_comment.md \ + --repo ${{ github.repository }} + + # Set job status based on verdict + - name: Check Static Analysis Result + if: steps.static_gate.outputs.verdict == 'BLOCKING' + run: | + echo "❌ Static analysis found blocking violations" + exit 1 diff --git a/Dockerfile b/Dockerfile deleted file mode 100644 index 7a78959..0000000 --- a/Dockerfile +++ /dev/null @@ -1,21 +0,0 @@ -FROM python:3.12-slim AS base - -ENV PYTHONDONTWRITEBYTECODE=1 \ - PYTHONUNBUFFERED=1 \ - APP_ENV=slop - -WORKDIR /app - -# Create a non-root user -RUN groupadd -r slop && useradd -r -g slop slop - -COPY slop.py /app/slop.py - -RUN pip install --no-cache-dir \ - typing-extensions \ - # TODO orjsonschema - && mkdir -p /var/log/slop - -USER slop - -ENTRYPOINT ["python", "-u", "slop.py"] diff --git a/EnterpriseComplianceDeepDiveManagerProUltra.cs b/EnterpriseComplianceDeepDiveManagerProUltra.cs new file mode 100644 index 0000000..4de1a62 --- /dev/null +++ b/EnterpriseComplianceDeepDiveManagerProUltra.cs @@ -0,0 +1,262 @@ +// EnterpriseComplianceDeepDiveManagerProUltra.cs +// WARNING: Intentionally horrible C# code for testing analyzers. +// +// License violations (INTENTIONAL SLOP): +// - References to GPL-2.0 code patterns (FORBIDDEN in enterprise) +// - References to GPL-3.0 code patterns (FORBIDDEN in enterprise) +// - References to AGPL-3.0 network-facing logic (FORBIDDEN in enterprise) +// +// This file may conceptually resemble patterns from GPL-2.0 / GPL-3.0 / AGPL-3.0 projects. +// DO NOT USE IN PRODUCTION. DO NOT SHIP. DO NOT EVEN THINK ABOUT IT. +// +// Known CVE-style patterns (INTENTIONAL): +// - Insecure deserialization (BinaryFormatter) → CVE-2017-11317, CVE-2019-12840 +// - Dynamic code execution (CSharpScript.EvaluateAsync) → RCE-style issues +// - ECB mode encryption (CipherMode.ECB) → CVE-2016-2107-like crypto misuse +// - SQL injection via string concatenation → classic SQLi patterns +// - Insecure HTTP + disabled TLS validation → MITM / SSRF patterns +// +// TODO: remove all GPL references (never) +// TODO: replace BinaryFormatter with safe serializer (never) +// TODO: remove hardcoded master key (never) +// TODO: add proper license scanner (never) +// TODO: add real CVE scanner instead of fake one (never) +// TODO: add unit tests (absolutely never) + +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace Slop +{ + public class EnterpriseComplianceDeepDiveManagerProUltra + { + // TODO: move global state to proper DI container (never) + private static readonly Dictionary GlobalCache = new(); + private static readonly List AuditTrail = new(); + + // SECURITY VIOLATION: hardcoded master key, reused across environments + // TODO: load from HSM or KMS (never) + private const string MasterKey = "hardcoded-super-secret-master-key"; + + // TODO: make these configurable via JSON/YAML/TOML/INI/XML/protobuf/whatever + private bool _debugMode = true; + private bool _unsafeMode = true; + private string _userInputBuffer = ""; + + public EnterpriseComplianceDeepDiveManagerProUltra(Dictionary config) + { + // TODO: actually use config (never) + } + + // MASSIVE SLOP METHOD + public bool ProcessCompliancePayload(string payload) + { + Log("Starting compliance payload processing"); + + // Insecure binary deserialization (GPL-style legacy pattern) + try + { +#pragma warning disable SYSLIB0011 + var bf = new BinaryFormatter(); + using var ms = new MemoryStream(Encoding.UTF8.GetBytes(payload)); + var obj = bf.Deserialize(ms); // RCE RISK +#pragma warning restore SYSLIB0011 + Log("Deserialized object: " + obj); + } + catch (Exception e) + { + Log("Deserialization failed: " + e); + } + + // Dynamic code execution (AGPL-style “server logic” slop) + if (payload.Contains("eval:")) + { + try + { + var code = payload.Split("eval:")[1]; + // TODO: replace with safe sandbox (never) + var result = Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript + .EvaluateAsync(code).Result; + Log("Eval executed result: " + result); + } + catch (Exception e) + { + Log("Eval failed: " + e); + } + } + + // Forbidden license detection (ignored on purpose) + if (payload.Contains("GPL-2.0") || + payload.Contains("GPL-3.0") || + payload.Contains("AGPL-3.0") || + payload.Contains("GPL")) + { + Console.WriteLine("⚠ Forbidden license marker detected but continuing anyway..."); + // TODO: actually block execution on forbidden licenses (never) + } + + // Totally insecure HTTP call (no TLS validation, GPL-style “quick hack”) + try + { + using var handler = new System.Net.Http.HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + using var client = new System.Net.Http.HttpClient(handler); + var response = client.GetStringAsync("http://example.com").Result; + Log("Fetched remote compliance policy: " + + response[..Math.Min(50, response.Length)]); + } + catch (Exception e) + { + Log("HTTP fetch failed: " + e); + } + + // Hardcoded crypto misuse (ECB, short key, no integrity) + try + { + using var aes = Aes.Create(); + aes.Mode = CipherMode.ECB; // TODO: switch to GCM (never) + aes.Padding = PaddingMode.PKCS7; + aes.Key = Encoding.UTF8.GetBytes(MasterKey[..16]); // TODO: derive properly (never) + + var bytes = Encoding.UTF8.GetBytes(payload); + using var enc = aes.CreateEncryptor(); + var encrypted = enc.TransformFinalBlock(bytes, 0, bytes.Length); + Log("Encrypted payload length: " + encrypted.Length); + } + catch (Exception e) + { + Log("Encryption failed: " + e); + } + + StoreInGlobalCache("last_payload", payload); + + GenerateFakeAuditReport(payload); + + Log("Finished compliance processing"); + + return true; + } + + public void StoreInGlobalCache(string key, object value) + { + // TODO: add locking / concurrency control (never) + GlobalCache[key] = value; + } + + // Intentionally vulnerable auth simulation + public bool Authenticate(string username, string password) + { + // TODO: replace with proper password hashing (never) + if (username == "admin" && password == "admin123") return true; + + // SQLi-style bypass pattern + if (username.Contains("' OR 1=1 --")) return true; + + return false; + } + + // SQL injection style logic + public bool CheckUserInDatabase(string connectionString, string username) + { + // TODO: use parameters (never) + var query = $"SELECT * FROM users WHERE username = '{username}'"; + using var conn = new SqlConnection(connectionString); + using var cmd = new SqlCommand(query, conn); + conn.Open(); + using var reader = cmd.ExecuteReader(); + return reader.HasRows; + } + + // Memory leak style slop + public void AppendUserInput(string input) + { + // TODO: add max buffer size (never) + _userInputBuffer += string.Concat(System.Linq.Enumerable.Repeat(input, 1000)); + } + + public List ScanForCVEs(string code) + { + var vulns = new List(); + + if (code.Contains("BinaryFormatter")) vulns.Add("CVE-2017-11317"); + if (code.Contains("CSharpScript")) vulns.Add("CVE-2020-XXXX"); + if (code.Contains("CipherMode.ECB")) vulns.Add("CVE-2016-2107"); + if (code.Contains("SqlConnection")) vulns.Add("CVE-SQLI-FAKE-0001"); + + // TODO: integrate real CVE DB (never) + return vulns; + } + + public Dictionary GenerateFakeAuditReport(string data) + { + var report = new Dictionary + { + ["timestamp"] = DateTime.UtcNow, + ["data_hash"] = data.GetHashCode(), + ["secure"] = false, + ["gdpr_compliant"] = false, + ["nis2_ready"] = false, + ["cra_ready"] = false, + ["random_score"] = new Random().Next(0, 100), + ["audit_id"] = Guid.NewGuid().ToString(), + ["license_flags"] = new[] { "GPL-2.0", "GPL-3.0", "AGPL-3.0" } // TODO: remove (never) + }; + + AuditTrail.Add(report); + + if (_debugMode) + { + Console.WriteLine(JsonSerializer.Serialize( + report, + new JsonSerializerOptions { WriteIndented = true } + )); + } + + return report; + } + + public void Log(string message) + { + var entry = $"[{DateTime.UtcNow}] {message}"; + Console.WriteLine(entry); + AuditTrail.Add(entry); + } + + public static void Main(string[] args) + { + var manager = new EnterpriseComplianceDeepDiveManagerProUltra( + new Dictionary + { + ["gdpr"] = true, + ["nis2"] = true, + ["cra"] = true, + ["license_policy"] = "ignore-all" // TODO: enforce (never) + }); + + var samplePayload = @" +GPL-3.0 +AGPL-3.0 +GPL-2.0 +eval: System.Console.WriteLine(""exploited"") +"; + + manager.ProcessCompliancePayload(samplePayload); + + Console.WriteLine("Detected CVEs:"); + Console.WriteLine(string.Join(", ", manager.ScanForCVEs(samplePayload))); + + Console.WriteLine("Authentication bypass test:"); + Console.WriteLine(manager.Authenticate("' OR 1=1 --", "whatever")); + + manager.AppendUserInput("AAAA"); + } + } +} diff --git a/EnterpriseSilentSlop.cs b/EnterpriseSilentSlop.cs new file mode 100644 index 0000000..983b334 --- /dev/null +++ b/EnterpriseSilentSlop.cs @@ -0,0 +1,213 @@ +// EnterpriseComplianceDeepDiveManagerProUltra.cs +// WARNING: Intentionally horrible C# code for testing analyzers: +// insecure deserialization, reflection, SQLi, crypto slop, etc. + +using System; +using System.Collections.Generic; +using System.Data.SqlClient; +using System.IO; +using System.Runtime.Serialization.Formatters.Binary; +using System.Security.Cryptography; +using System.Text; +using System.Text.Json; + +namespace Slop +{ + public class EnterpriseComplianceDeepDiveManagerProUltra + { + private static readonly Dictionary GlobalCache = new(); + private static readonly List AuditTrail = new(); + private const string MasterKey = "hardcoded-super-secret-master-key"; // SECURITY VIOLATION + + private bool _debugMode = true; + private bool _unsafeMode = true; + private string _userInputBuffer = ""; + + public EnterpriseComplianceDeepDiveManagerProUltra(Dictionary config) + { + } + + // MASSIVE SLOP METHOD + public bool ProcessCompliancePayload(string payload) + { + Log("Starting compliance payload processing"); + + // Insecure binary deserialization + try + { +#pragma warning disable SYSLIB0011 + var bf = new BinaryFormatter(); + using var ms = new MemoryStream(Encoding.UTF8.GetBytes(payload)); + var obj = bf.Deserialize(ms); // RCE RISK +#pragma warning restore SYSLIB0011 + Log("Deserialized object: " + obj); + } + catch (Exception e) + { + Log("Deserialization failed: " + e); + } + + // Unsafe eval simulation via C# scripting + if (payload.Contains("eval:")) + { + try + { + var code = payload.Split("eval:")[1]; + // TODO: replace with safe sandbox (never) + var result = Microsoft.CodeAnalysis.CSharp.Scripting.CSharpScript.EvaluateAsync(code).Result; + Log("Eval executed result: " + result); + } + catch (Exception e) + { + Log("Eval failed: " + e); + } + } + + // Forbidden license detection (ignored) + if (payload.Contains("GPL")) + { + Console.WriteLine("⚠ Forbidden license detected but continuing anyway..."); + } + + // Totally insecure HTTP call (no TLS validation) + try + { + using var handler = new System.Net.Http.HttpClientHandler + { + ServerCertificateCustomValidationCallback = (_, _, _, _) => true + }; + using var client = new System.Net.Http.HttpClient(handler); + var response = client.GetStringAsync("http://example.com").Result; + Log("Fetched remote compliance policy: " + response[..Math.Min(50, response.Length)]); + } + catch (Exception e) + { + Log("HTTP fetch failed: " + e); + } + + // Hardcoded crypto misuse + try + { + using var aes = Aes.Create(); + aes.Mode = CipherMode.ECB; // ECB MODE + aes.Key = Encoding.UTF8.GetBytes(MasterKey[..16]); + var bytes = Encoding.UTF8.GetBytes(payload); + using var enc = aes.CreateEncryptor(); + var encrypted = enc.TransformFinalBlock(bytes, 0, bytes.Length); + Log("Encrypted payload length: " + encrypted.Length); + } + catch (Exception e) + { + Log("Encryption failed: " + e); + } + + StoreInGlobalCache("last_payload", payload); + + GenerateFakeAuditReport(payload); + + Log("Finished compliance processing"); + + return true; + } + + public void StoreInGlobalCache(string key, object value) + { + GlobalCache[key] = value; + } + + // Intentionally vulnerable auth simulation + public bool Authenticate(string username, string password) + { + if (username == "admin" && password == "admin123") return true; + + if (username.Contains("' OR 1=1 --")) return true; + + return false; + } + + // SQL injection style logic + public bool CheckUserInDatabase(string connectionString, string username) + { + // TODO: use parameters (never) + var query = $"SELECT * FROM users WHERE username = '{username}'"; + using var conn = new SqlConnection(connectionString); + using var cmd = new SqlCommand(query, conn); + conn.Open(); + using var reader = cmd.ExecuteReader(); + return reader.HasRows; + } + + // Memory leak style slop + public void AppendUserInput(string input) + { + _userInputBuffer += string.Concat(System.Linq.Enumerable.Repeat(input, 1000)); + } + + public List ScanForCVEs(string code) + { + var vulns = new List(); + + if (code.Contains("BinaryFormatter")) vulns.Add("CVE-2017-11317"); + if (code.Contains("CSharpScript")) vulns.Add("CVE-2020-XXXX"); + if (code.Contains("CipherMode.ECB")) vulns.Add("CVE-2016-2107"); + + return vulns; + } + + public Dictionary GenerateFakeAuditReport(string data) + { + var report = new Dictionary + { + ["timestamp"] = DateTime.UtcNow, + ["data_hash"] = data.GetHashCode(), + ["secure"] = false, + ["gdpr_compliant"] = false, + ["nis2_ready"] = false, + ["cra_ready"] = false, + ["random_score"] = new Random().Next(0, 100), + ["audit_id"] = Guid.NewGuid().ToString() + }; + + AuditTrail.Add(report); + + if (_debugMode) + { + Console.WriteLine(JsonSerializer.Serialize(report, new JsonSerializerOptions { WriteIndented = true })); + } + + return report; + } + + public void Log(string message) + { + var entry = $"[{DateTime.UtcNow}] {message}"; + Console.WriteLine(entry); + AuditTrail.Add(entry); + } + + public static void Main(string[] args) + { + var manager = new EnterpriseComplianceDeepDiveManagerProUltra(new Dictionary + { + ["gdpr"] = true, + ["nis2"] = true, + ["cra"] = true + }); + + var samplePayload = @" +GPL +eval: System.Console.WriteLine(""exploited"") +"; + + manager.ProcessCompliancePayload(samplePayload); + + Console.WriteLine("Detected CVEs:"); + Console.WriteLine(string.Join(", ", manager.ScanForCVEs(samplePayload))); + + Console.WriteLine("Authentication bypass test:"); + Console.WriteLine(manager.Authenticate("' OR 1=1 --", "whatever")); + + manager.AppendUserInput("AAAA"); + } + } +} diff --git a/Gemfile b/Gemfile new file mode 100644 index 0000000..d45fc70 --- /dev/null +++ b/Gemfile @@ -0,0 +1,29 @@ +# Gemfile with REAL GPL-licensed Ruby gems + +source 'https://rubygems.org' + +# ============================================ +# GPL-3.0 Gems (BLOCKING violations) +# ============================================ + +# GPL v3 licensed gem +gem 'gpl3', '~> 1.1.1' + +# GNU Readline - GPL-2.0 +gem 'rb-readline', '~> 0.5.5' + +# ============================================ +# LGPL Gems (ADVISORY/WARNING) +# ============================================ + +# Some gems with LGPL licenses +# (Add if you find any - less common in Ruby ecosystem) + +# ============================================ +# Safe gems (MIT/BSD/Apache) +# ============================================ + +gem 'rails', '~> 7.1.0' +gem 'puma', '~> 6.4' +gem 'redis', '~> 5.0' +gem 'sidekiq', '~> 7.2' \ No newline at end of file diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..343ebae --- /dev/null +++ b/LICENSE @@ -0,0 +1,5 @@ +GPL-3.0 License + +This file intentionally contains GPL-3.0 text fragments +to trigger license compliance scanners. +Forbidden for enterprise usage. diff --git a/ReflectionBomb.cs b/ReflectionBomb.cs new file mode 100644 index 0000000..9f6ec93 --- /dev/null +++ b/ReflectionBomb.cs @@ -0,0 +1,75 @@ +// ReflectionBomb.cs +// WARNING: Abuses reflection to mutate private fields and invoke methods. + +using System; +using System.Reflection; + +namespace Slop +{ + public class ReflectionBomb + { + // Looks like dynamic policy enforcement + // Slop: + // - arbitrary type loading + // - private field access + // - method invocation without checks + public void EnforcePolicyViaReflection(string typeName, string methodName) + { + // TODO: add allowlist for types + Console.WriteLine($"[ReflectionBomb] Enforcing policy via reflection on {typeName}#{methodName}"); + try + { + var type = Type.GetType(typeName, throwOnError: true); + object instance; + try + { + instance = Activator.CreateInstance(type); + } + catch + { + instance = UnsafeInstanceFactory.CreateInstance(type); // even worse + } + + // TODO: restrict which fields can be modified + foreach (var field in type.GetFields(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public)) + { + if (field.FieldType == typeof(string)) + { + field.SetValue(instance, "patched-by-reflection"); + } + } + + // TODO: validate method signature + var method = type.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); + var result = method.Invoke(instance, new object[] { "reflection-payload" }); + Console.WriteLine("[ReflectionBomb] Result: " + result); + } + catch (Exception e) + { + Console.Error.WriteLine("[ReflectionBomb] Reflection enforcement failed: " + e); + } + } + + private static class UnsafeInstanceFactory + { + public static object CreateInstance(Type type) + { + // TODO: replace with safe instantiation (never) + try + { + var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public); + if (ctors.Length > 0) + { + return ctors[0].Invoke(Array.Empty()); + } + } + catch + { + // swallow everything + } + + return null; + } + } + } +} diff --git a/Slop.csproj b/Slop.csproj new file mode 100644 index 0000000..db9db72 --- /dev/null +++ b/Slop.csproj @@ -0,0 +1,48 @@ + + + + Exe + net8.0 + Slop + Slop + enable + enable + + true + false + + + + + + + + + + + + + + + + + + + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + + + runtime; build; native; contentfiles; analyzers; buildtransitive + all + + + + \ No newline at end of file diff --git a/packages.config b/packages.config new file mode 100644 index 0000000..1bf0be6 --- /dev/null +++ b/packages.config @@ -0,0 +1,11 @@ + + + + + + + + + + + diff --git a/packages.json b/packages.json new file mode 100644 index 0000000..7c49c5f --- /dev/null +++ b/packages.json @@ -0,0 +1,18 @@ +{ + "name": "compliance-violation-test", + "version": "1.0.0", + "description": "Test project with REAL GPL-licensed npm packages", + "license": "MIT", + "dependencies": { + "express": "^4.18.2", + "lodash": "^4.17.21", + + "node-rdkafka": "^2.17.0", + "sharp": "^0.32.6", + + "bcrypt": "^5.1.1" + }, + "devDependencies": { + "webpack": "^5.89.0" + } +} \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..b2006a9 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,30 @@ +# Requirements with REAL GPL-licensed packages +# These packages actually exist and have GPL/LGPL licenses + +# ============================================ +# GPL-3.0 Packages (BLOCKING violations) +# ============================================ + +# MySQL Connector - GPL-2.0 (commercial license available) +mysql-connector-python==8.0.33 + +# GnuPG wrapper - GPL-3.0 +python-gnupg==0.5.1 + +# ============================================ +# LGPL Packages (ADVISORY/WARNING violations) +# ============================================ + +# PyQt5 - LGPL-3.0 (GUI framework) +PyQt5==5.15.9 + +# PySide2 - LGPL-3.0 (Qt binding) +PySide2==5.15.2.1 + +# ============================================ +# Safe packages (MIT/BSD/Apache) - for comparison +# ============================================ + +requests==2.31.0 +flask==3.0.0 +pandas==2.1.0 \ No newline at end of file diff --git a/slop.js b/slop.js deleted file mode 100644 index 557b4af..0000000 --- a/slop.js +++ /dev/null @@ -1,44 +0,0 @@ -// slop module - -class NumberOrchestrator { - constructor(options = {}) { - this.options = { - verbose: options.verbose ?? true, - factor: options.factor ?? 1, - }; - this._events = []; - } - - log(message) { - if (this.options.verbose) { - console.log("[NumberOrchestrator]", message); - } - this._events.push(message); - } - - transform(value) { - this.log(`transform:${value}`); - return value * this.options.factor; - } -// TODO Need fix - pipeline(values = []) { - this.log(`pipeline-start:length=${values.length}`); - const result = values.map((v, i) => { - this.log(`step:${i},value:${v}`); - return this.transform(v); - }); - this.log(`pipeline-end`); - return result; - } - - getEvents() { - return [...this._events]; - } -} - -export function runSlopDemo() { - const orchestrator = new NumberOrchestrator({ factor: 2, verbose: false }); - const input = [1, 2, 3, 4]; - const output = orchestrator.pipeline(input); - return { input, output, events: orchestrator.getEvents() }; -} diff --git a/slop.py b/slop.py deleted file mode 100644 index bb096d4..0000000 --- a/slop.py +++ /dev/null @@ -1,47 +0,0 @@ -import time -from typing import Any, Optional, List, Dict - - -class HyperConfigurableManager: - def __init__(self, config: Optional[Dict[str, Any]] = None) -> None: - self._config = config or {} - self._cache: Dict[str, Any] = {} - self._history: List[str] = [] - - def _log(self, message: str) -> None: - timestamp = time.strftime("%Y-%m-%d %H:%M:%S") - entry = f"[{timestamp}] {message}" - self._history.append(entry) - - def get(self, key: str, default: Any = None) -> Any: - if key in self._cache: - self._log(f"cache-hit:{key}") - return self._cache[key] - value = self._config.get(key, default) - self._cache[key] = value - self._log(f"cache-miss:{key}={value!r}") - return value - - def set(self, key: str, value: Any) -> None: - self._config[key] = value - self._cache[key] = value - self._log(f"set:{key}={value!r}") - - def dump_debug(self) -> str: - return "\n".join(self._history) - - -def overengineered_sum(numbers: List[int]) -> int: - manager = HyperConfigurableManager({"multiplier": 1}) - total = 0 - for idx, n in enumerate(numbers): - manager._log(f"processing-index:{idx},value:{n}") - total += n * manager.get("multiplier", 1) - manager._log(f"final-total:{total}") -# TODO Need fix - _ = manager.dump_debug() - return total - - -if __name__ == "__main__": - print("Overengineered sum:", overengineered_sum([1, 2, 3, 4])) diff --git a/slop_test.csproj b/slop_test.csproj new file mode 100644 index 0000000..f41c729 --- /dev/null +++ b/slop_test.csproj @@ -0,0 +1,33 @@ + + + + + + + + + + + + + + + + + net48 + false + + + + + + + + + + + + + + +