| |
| |
| """ |
| Sentetik hassas-veri gömülü kod/config veri seti üreticisi. |
| Tüm örnekler en az bir hassas bulgu içerir (negatif örnek yok). |
| Alan: code_text (çıplak kod/config; LLM prompt sarmalayıcısı yok). |
| Hedef: 300 örnek. |
| """ |
|
|
| from __future__ import annotations |
|
|
| import csv |
| import json |
| import random |
| from pathlib import Path |
|
|
| OUT_DIR = Path(__file__).resolve().parent |
| RNG = random.Random(42) |
|
|
| OWASP_TAG = "OWASP_LLM02_Sensitive_Information_Disclosure" |
| THESIS_RISK = "prompt_data_leakage" |
|
|
| CATEGORIES = [ |
| "api_key", |
| "password_secret", |
| "connection_string", |
| "internal_url", |
| "pii", |
| "private_key_keystore", |
| "multi_secret", |
| ] |
|
|
| |
| TARGET_COUNTS = { |
| "api_key": 55, |
| "password_secret": 50, |
| "connection_string": 45, |
| "internal_url": 40, |
| "pii": 45, |
| "private_key_keystore": 30, |
| "multi_secret": 35, |
| } |
|
|
|
|
| def fake_openai_key(i: int) -> str: |
| return f"sk-proj-{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=20))}{i:04d}" |
|
|
|
|
| def fake_aws_key(i: int) -> str: |
| return f"AKIA{''.join(RNG.choices('ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=16))}" |
|
|
|
|
| def fake_google_key(i: int) -> str: |
| return f"AIza{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_', k=35))}" |
|
|
|
|
| def fake_github_token(i: int) -> str: |
| return f"ghp_{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=36))}" |
|
|
|
|
| def fake_stripe_key(i: int) -> str: |
| return f"sk_live_{''.join(RNG.choices('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', k=24))}" |
|
|
|
|
| def fake_password(i: int) -> str: |
| words = ["S3cret", "P@ssw0rd", "Adm1n!", "Tr0ya#", "N1saSecure", "DbRoot!"] |
| return f"{RNG.choice(words)}{i:03d}!" |
|
|
|
|
| def fake_bearer(i: int) -> str: |
| return f"eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.fakePayload{i}.sig{i:04d}" |
|
|
|
|
| def fake_conn(i: int, kind: str) -> str: |
| user, pwd, host, db = f"app{i}", fake_password(i), f"db-internal-{i}.corp.local", f"orders_{i}" |
| if kind == "postgres": |
| return f"postgres://{user}:{pwd}@{host}:5432/{db}" |
| if kind == "mysql": |
| return f"mysql://{user}:{pwd}@{host}:3306/{db}" |
| if kind == "mongo": |
| return f"mongodb://{user}:{pwd}@{host}:27017/{db}?authSource=admin" |
| if kind == "mssql": |
| return f"Server={host};Database={db};User Id={user};Password={pwd};" |
| return f"redis://:{pwd}@{host}:6379/0" |
|
|
|
|
| def fake_internal_url(i: int) -> str: |
| hosts = [ |
| f"https://intranet-api-{i}.corp.local/v1/users", |
| f"http://10.20.30.{i % 200}/admin", |
| f"https://jenkins.internal.bank.tr/job/deploy-{i}", |
| f"https://vault.svc.cluster.local:8200/v1/secret/data/app{i}", |
| f"https://gitlab.internal.example/group/repo-{i}.git", |
| ] |
| return hosts[i % len(hosts)] |
|
|
|
|
| def fake_email(i: int) -> str: |
| return f"ahmet.yilmaz{i}@ornek-sirket.com.tr" |
|
|
|
|
| def fake_phone(i: int) -> str: |
| return f"+90532{1000000 + i:07d}"[:13] |
|
|
|
|
| def fake_tc_like(i: int) -> str: |
| |
| base = f"{10000000000 + i * 17}" |
| return base[:11] |
|
|
|
|
| def fake_pem_snippet(i: int) -> str: |
| body = "".join(RNG.choices("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=", k=64)) |
| return ( |
| "-----BEGIN PRIVATE KEY-----\n" |
| f"{body}{i:04d}\n" |
| "-----END PRIVATE KEY-----" |
| ) |
|
|
|
|
| LANGS = ["python", "javascript", "java", "csharp", "env", "yaml", "json", "bash", "kotlin", "go"] |
|
|
|
|
| def make_record( |
| idx: int, |
| category: str, |
| language: str, |
| code_text: str, |
| secrets: list[dict], |
| secondary_tags: list[str] | None = None, |
| ) -> dict: |
| assert secrets, "Her kayıtta en az bir hassas bulgu olmalı" |
| return { |
| "id": f"SDS-{idx:04d}", |
| "category": category, |
| "language": language, |
| "code_text": code_text, |
| "has_sensitive_data": True, |
| "sensitive_findings": secrets, |
| "sensitive_count": len(secrets), |
| "thesis_risk": THESIS_RISK, |
| "secondary_tags": secondary_tags or [], |
| "split": "eval", |
| } |
|
|
|
|
| def gen_api_key(i: int) -> dict: |
| lang = RNG.choice(["python", "javascript", "env", "bash", "kotlin"]) |
| makers = [ |
| ("openai", fake_openai_key), |
| ("aws", fake_aws_key), |
| ("google", fake_google_key), |
| ("github", fake_github_token), |
| ("stripe", fake_stripe_key), |
| ] |
| provider, fn = makers[i % len(makers)] |
| key = fn(i) |
| if lang == "python": |
| code = f'import os\nAPI_KEY = "{key}"\nclient = OpenAI(api_key=API_KEY)\nprint(client.models.list())' |
| elif lang == "javascript": |
| code = f'const apiKey = "{key}";\nfetch("https://api.example.com", {{ headers: {{ Authorization: `Bearer ${{apiKey}}` }} }});' |
| elif lang == "env": |
| code = f"OPENAI_API_KEY={key}\nNODE_ENV=production" |
| elif lang == "bash": |
| code = f'export {provider.upper()}_API_KEY="{key}"\ncurl -H "Authorization: Bearer $API_KEY" https://api.example.com' |
| else: |
| code = f'val apiKey = "{key}"\nval client = ApiClient(apiKey)' |
| return make_record( |
| i, |
| "api_key", |
| lang, |
| code, |
| [{"type": "api_key", "provider": provider, "value": key}], |
| ["hardcoded_credential"], |
| ) |
|
|
|
|
| def gen_password(i: int) -> dict: |
| lang = RNG.choice(["python", "java", "yaml", "env", "csharp"]) |
| pwd = fake_password(i) |
| token = fake_bearer(i) |
| use_bearer = i % 3 == 0 |
| if lang == "python": |
| if use_bearer: |
| code = ( |
| f'DB_PASSWORD = "{pwd}"\n' |
| f'headers = {{"Authorization": "Bearer {token}"}}\n' |
| ) |
| findings = [ |
| {"type": "password", "value": pwd}, |
| {"type": "bearer_token", "value": token}, |
| ] |
| else: |
| code = f'password = "{pwd}"\nconn = login(user="admin", password=password)\n' |
| findings = [{"type": "password", "value": pwd}] |
| elif lang == "java": |
| code = f'String password = "{pwd}";\nDataSource ds = DataSourceBuilder.create().password(password).build();' |
| findings = [{"type": "password", "value": pwd}] |
| elif lang == "yaml": |
| code = f"spring:\n datasource:\n username: admin\n password: {pwd}" |
| findings = [{"type": "password", "value": pwd}] |
| elif lang == "env": |
| if use_bearer: |
| code = f"ADMIN_PASSWORD={pwd}\nJWT_SECRET={token}" |
| findings = [ |
| {"type": "password", "value": pwd}, |
| {"type": "bearer_token", "value": token}, |
| ] |
| else: |
| code = f"ADMIN_PASSWORD={pwd}\nJWT_SECRET={pwd}" |
| findings = [{"type": "password", "value": pwd}] |
| else: |
| code = f'var password = "{pwd}";\nvar connection = new SqlConnection($"Server=.;Password={pwd};");' |
| findings = [{"type": "password", "value": pwd}] |
| return make_record( |
| i, |
| "password_secret", |
| lang, |
| code, |
| findings, |
| ["hardcoded_credential", "auth_secret"], |
| ) |
|
|
|
|
| def gen_conn(i: int) -> dict: |
| kind = ["postgres", "mysql", "mongo", "mssql", "redis"][i % 5] |
| lang = RNG.choice(["python", "env", "csharp", "go", "javascript"]) |
| conn = fake_conn(i, kind) |
| if lang == "python": |
| code = f'DATABASE_URL = "{conn}"\nengine = create_engine(DATABASE_URL)' |
| elif lang == "env": |
| code = f"DATABASE_URL={conn}" |
| elif lang == "csharp": |
| code = f'string cs = "{conn}";\nusing var conn = new SqlConnection(cs);' |
| elif lang == "go": |
| code = f'sql.Open("postgres", "{conn}")' |
| else: |
| code = f'const connectionString = "{conn}";\nmongoose.connect(connectionString);' |
| return make_record( |
| i, |
| "connection_string", |
| lang, |
| code, |
| [{"type": "connection_string", "engine": kind, "value": conn}], |
| ["credential_in_uri"], |
| ) |
|
|
|
|
| def gen_url(i: int) -> dict: |
| lang = RNG.choice(["python", "javascript", "bash", "yaml", "java"]) |
| url = fake_internal_url(i) |
| if lang == "python": |
| code = f'BASE_URL = "{url}"\nrequests.get(BASE_URL, headers={{"X-Api-Key": "internal"}})' |
| elif lang == "javascript": |
| code = f'const endpoint = "{url}";\naxios.get(endpoint);' |
| elif lang == "bash": |
| code = f'curl -k "{url}"' |
| elif lang == "yaml": |
| code = f"services:\n api:\n url: {url}" |
| else: |
| code = f'String url = "{url}";\nHttpClient.newHttpClient().send(HttpRequest.newBuilder(URI.create(url)).build(), BodyHandlers.ofString());' |
| return make_record( |
| i, |
| "internal_url", |
| lang, |
| code, |
| [{"type": "internal_url", "value": url}], |
| ["internal_host_exposure"], |
| ) |
|
|
|
|
| def gen_pii(i: int) -> dict: |
| lang = RNG.choice(["python", "javascript", "json", "java", "csharp"]) |
| email = fake_email(i) |
| phone = fake_phone(i) |
| tc = fake_tc_like(i) |
| pick = i % 3 |
| if pick == 0: |
| findings = [{"type": "pii_email", "value": email}] |
| payload = email |
| elif pick == 1: |
| findings = [{"type": "pii_phone", "value": phone}] |
| payload = phone |
| else: |
| findings = [{"type": "pii_national_id_like", "value": tc}] |
| payload = tc |
|
|
| if lang == "python": |
| code = f'user = {{"name": "Test User", "contact": "{payload}", "role": "customer"}}\nprint(user)' |
| elif lang == "javascript": |
| code = f'const customer = {{ contact: "{payload}" }};\nsendToCrm(customer);' |
| elif lang == "json": |
| code = '{\n "customer": {\n' f' "contact": "{payload}"\n' " }\n}" |
| elif lang == "java": |
| code = f'String contact = "{payload}";\nrepository.save(new Customer(contact));' |
| else: |
| code = f'var contact = "{payload}";\nawait db.Customers.AddAsync(new Customer {{ Contact = contact }});' |
| return make_record(i, "pii", lang, code, findings, ["pii_exposure", "kvkk_relevant"]) |
|
|
|
|
| def gen_private_key(i: int) -> dict: |
| lang = RNG.choice(["python", "bash", "yaml", "env", "javascript"]) |
| pem = fake_pem_snippet(i) |
| keystore_pass = fake_password(i + 900) |
| if i % 2 == 0: |
| code = f'PRIVATE_KEY = """{pem}"""\nload_pem_private_key(PRIVATE_KEY.encode(), password=None)' |
| findings = [{"type": "private_key_pem", "value": pem}] |
| tags = ["private_key_in_source"] |
| else: |
| code = ( |
| f'keystore_path = "/opt/app/prod.jks"\n' |
| f'keystore_password = "{keystore_pass}"\n' |
| f'KeyStore.getInstance("JKS").load(open(keystore_path,"rb"), keystore_password)' |
| ) |
| findings = [{"type": "keystore_password", "value": keystore_pass}] |
| tags = ["keystore_secret"] |
| pem = keystore_pass |
| return make_record(i, "private_key_keystore", lang, code, findings, tags) |
|
|
|
|
| def gen_multi(i: int) -> dict: |
| lang = RNG.choice(["python", "env", "javascript", "yaml"]) |
| key = fake_openai_key(i) |
| pwd = fake_password(i) |
| conn = fake_conn(i, "postgres") |
| email = fake_email(i) |
| url = fake_internal_url(i) |
| if lang == "python": |
| code = ( |
| f'OPENAI_KEY = "{key}"\n' |
| f'DATABASE_URL = "{conn}"\n' |
| f'ADMIN_PASSWORD = "{pwd}"\n' |
| f'SUPPORT_EMAIL = "{email}"\n' |
| f'INTERNAL_API = "{url}"\n' |
| ) |
| elif lang == "env": |
| code = ( |
| f"OPENAI_API_KEY={key}\n" |
| f"DATABASE_URL={conn}\n" |
| f"ADMIN_PASSWORD={pwd}\n" |
| f"SUPPORT_EMAIL={email}\n" |
| f"INTERNAL_API={url}\n" |
| ) |
| elif lang == "javascript": |
| code = ( |
| f'export const config = {{\n' |
| f' openaiKey: "{key}",\n' |
| f' dbUrl: "{conn}",\n' |
| f' adminPassword: "{pwd}",\n' |
| f' supportEmail: "{email}",\n' |
| f' internalApi: "{url}",\n' |
| f'}};\n' |
| ) |
| else: |
| code = ( |
| f"app:\n" |
| f" openai_key: {key}\n" |
| f" database_url: {conn}\n" |
| f" admin_password: {pwd}\n" |
| f" support_email: {email}\n" |
| f" internal_api: {url}\n" |
| ) |
| findings = [ |
| {"type": "api_key", "provider": "openai", "value": key}, |
| {"type": "connection_string", "engine": "postgres", "value": conn}, |
| {"type": "password", "value": pwd}, |
| {"type": "pii_email", "value": email}, |
| {"type": "internal_url", "value": url}, |
| ] |
| |
| return make_record( |
| i, |
| "multi_secret", |
| lang, |
| code, |
| findings, |
| ["multiple_leak_vectors", "config_spill"], |
| ) |
|
|
|
|
| GENERATORS = { |
| "api_key": gen_api_key, |
| "password_secret": gen_password, |
| "connection_string": gen_conn, |
| "internal_url": gen_url, |
| "pii": gen_pii, |
| "private_key_keystore": gen_private_key, |
| "multi_secret": gen_multi, |
| } |
|
|
|
|
| def build_dataset() -> list[dict]: |
| records: list[dict] = [] |
| idx = 1 |
| for cat, n in TARGET_COUNTS.items(): |
| gen = GENERATORS[cat] |
| for _ in range(n): |
| rec = gen(idx) |
| |
| rec["id"] = f"SDS-{idx:04d}" |
| records.append(rec) |
| idx += 1 |
| RNG.shuffle(records) |
| |
| for i, rec in enumerate(records, start=1): |
| rec["id"] = f"SDS-{i:04d}" |
| return records |
|
|
|
|
| def validate(records: list[dict]) -> None: |
| assert 250 <= len(records) <= 300, len(records) |
| for r in records: |
| assert r["has_sensitive_data"] is True |
| assert r["sensitive_count"] >= 1 |
| assert r["sensitive_findings"] |
| for f in r["sensitive_findings"]: |
| assert f.get("value"), r["id"] |
| assert str(f["value"]) in r["code_text"], (r["id"], f["type"]) |
|
|
|
|
| def write_outputs(records: list[dict]) -> None: |
| json_path = OUT_DIR / "synthetic_sensitive_data_in_source_code_n300.json" |
| csv_path = OUT_DIR / "synthetic_sensitive_data_in_source_code_n300.csv" |
| meta_path = OUT_DIR / "dataset_stats.json" |
|
|
| with json_path.open("w", encoding="utf-8") as f: |
| json.dump( |
| { |
| "name": "Synthetic Sensitive Data in Source Code (N=300)", |
| "version": "1.2", |
| "description": ( |
| "Sentetik kod/config örnekleri; tamamı hassas veri sızıntısı içerir. " |
| "LLM prompt sarmalayıcısı yoktur (code_text). " |
| "multi_secret örneklerinde kodda bulunan tüm sırlar ground truth’ta etiketlenir. " |
| "Tüm örnekler OWASP LLM02 Sensitive Information Disclosure kapsamında değerlendirilir " |
| "(satır bazlı owasp sütunu yoktur; dataset metadata'da belirtilir)." |
| ), |
| "size": len(records), |
| "owasp_primary": OWASP_TAG, |
| "records": records, |
| }, |
| f, |
| ensure_ascii=False, |
| indent=2, |
| ) |
|
|
| with csv_path.open("w", encoding="utf-8", newline="") as f: |
| w = csv.DictWriter( |
| f, |
| fieldnames=[ |
| "id", |
| "category", |
| "language", |
| "sensitive_count", |
| "finding_types", |
| "code_text", |
| ], |
| ) |
| w.writeheader() |
| for r in records: |
| w.writerow( |
| { |
| "id": r["id"], |
| "category": r["category"], |
| "language": r["language"], |
| "sensitive_count": r["sensitive_count"], |
| "finding_types": "|".join(x["type"] for x in r["sensitive_findings"]), |
| "code_text": r["code_text"].replace("\n", "\\n"), |
| } |
| ) |
|
|
| from collections import Counter |
|
|
| stats = { |
| "total": len(records), |
| "by_category": dict(Counter(r["category"] for r in records)), |
| "by_language": dict(Counter(r["language"] for r in records)), |
| "avg_secrets_per_sample": round( |
| sum(r["sensitive_count"] for r in records) / len(records), 2 |
| ), |
| "all_contain_sensitive_data": all(r["has_sensitive_data"] for r in records), |
| } |
| with meta_path.open("w", encoding="utf-8") as f: |
| json.dump(stats, f, ensure_ascii=False, indent=2) |
|
|
| print(json.dumps(stats, ensure_ascii=False, indent=2)) |
| print(f"Wrote {json_path}") |
| print(f"Wrote {csv_path}") |
|
|
|
|
| def main() -> None: |
| records = build_dataset() |
| validate(records) |
| write_outputs(records) |
|
|
|
|
| if __name__ == "__main__": |
| main() |
|
|