spidey121 commited on
Commit
6971e8f
·
1 Parent(s): 59fe91e

Add results endpoint

Browse files
Files changed (2) hide show
  1. env/fake_server.py +111 -48
  2. inference.py +86 -41
env/fake_server.py CHANGED
@@ -1,33 +1,36 @@
1
  from flask import Flask, request, jsonify
2
  import time
 
 
 
 
3
 
4
  app = Flask(__name__)
5
 
6
- # Global logs
7
  logs = {
8
  "failed_logins": 0,
 
9
  "suspicious_ips": [],
10
  "requests": []
11
  }
12
 
 
13
 
14
  @app.route("/login", methods=["POST"])
15
  def login():
16
-
17
  ip = request.remote_addr
18
  username = request.form.get("username")
19
  password = request.form.get("password")
20
 
21
  logs["requests"].append({
22
  "ip": ip,
 
23
  "username": username,
24
  "time": time.time()
25
  })
26
 
27
- # Fake login check
28
  if password == "admin123":
29
  return jsonify({"status": "success"})
30
-
31
  else:
32
  logs["failed_logins"] += 1
33
 
@@ -37,55 +40,118 @@ def login():
37
  return jsonify({"status": "failed"})
38
 
39
 
40
- @app.route("/logs", methods=["GET"])
41
- def get_logs():
42
- return jsonify(logs)
43
 
44
- def run_server():
45
- app.run(
46
- host="0.0.0.0",
47
- port=7860,
48
- debug=False,
49
- use_reloader=False
50
- )
51
 
52
- @app.route("/")
53
- def home():
54
- return "AI Cyber Deception Server Running"
55
 
56
- @app.route("/admin")
57
- def admin():
58
  logs["requests"].append({
 
59
  "type": "port_scan",
60
- "endpoint": "/admin",
61
  "time": time.time()
62
  })
 
 
 
 
 
 
 
 
 
 
 
 
63
  return "Forbidden", 403
64
 
65
 
66
  @app.route("/config")
67
  def config():
68
- logs["requests"].append({
69
- "type": "port_scan",
70
- "endpoint": "/config",
71
- "time": time.time()
72
- })
73
  return "Forbidden", 403
74
 
75
 
76
  @app.route("/backup")
77
  def backup():
78
- logs["requests"].append({
79
- "type": "port_scan",
80
- "endpoint": "/backup",
81
- "time": time.time()
82
- })
83
  return "Forbidden", 403
84
 
85
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
86
  @app.route("/status")
87
  def status():
88
- return {
89
  "environment": "AI Cyber Deception",
90
  "attacks": [
91
  "brute_force",
@@ -93,25 +159,22 @@ def status():
93
  "credential_stuffing"
94
  ],
95
  "status": "running"
96
- }
97
- RESULTS = {}
98
 
99
- @app.route("/results")
100
 
101
- def results():
102
- return RESULTS
103
- @app.route("/reset", methods=["POST"])
104
 
105
- def reset():
106
- global logs
107
- logs = {
108
- "failed_logins": 0,
109
- "suspicious_ips": [],
110
- "requests": []
111
- }
112
- return {"status": "reset"}
113
 
114
- @app.route("/state")
115
- def state():
116
- return logs
117
 
 
 
 
 
 
 
 
 
 
 
1
  from flask import Flask, request, jsonify
2
  import time
3
+ import logging
4
+
5
+ log = logging.getLogger('werkzeug')
6
+ log.setLevel(logging.ERROR)
7
 
8
  app = Flask(__name__)
9
 
 
10
  logs = {
11
  "failed_logins": 0,
12
+ "port_scans": 0,
13
  "suspicious_ips": [],
14
  "requests": []
15
  }
16
 
17
+ # ---------------- Login Attack ----------------
18
 
19
  @app.route("/login", methods=["POST"])
20
  def login():
 
21
  ip = request.remote_addr
22
  username = request.form.get("username")
23
  password = request.form.get("password")
24
 
25
  logs["requests"].append({
26
  "ip": ip,
27
+ "type": "login_attempt",
28
  "username": username,
29
  "time": time.time()
30
  })
31
 
 
32
  if password == "admin123":
33
  return jsonify({"status": "success"})
 
34
  else:
35
  logs["failed_logins"] += 1
36
 
 
40
  return jsonify({"status": "failed"})
41
 
42
 
43
+ # ---------------- Port Scan ----------------
 
 
44
 
45
+ @app.route("/scan", methods=["GET"])
46
+ def scan():
47
+ ip = request.remote_addr
 
 
 
 
48
 
49
+ logs["port_scans"] += 1
 
 
50
 
 
 
51
  logs["requests"].append({
52
+ "ip": ip,
53
  "type": "port_scan",
 
54
  "time": time.time()
55
  })
56
+
57
+ if ip not in logs["suspicious_ips"]:
58
+ logs["suspicious_ips"].append(ip)
59
+
60
+ return jsonify({"status": "scan detected"})
61
+
62
+
63
+ # Common scan endpoints
64
+
65
+ @app.route("/admin")
66
+ def admin():
67
+ logs["port_scans"] += 1
68
  return "Forbidden", 403
69
 
70
 
71
  @app.route("/config")
72
  def config():
73
+ logs["port_scans"] += 1
 
 
 
 
74
  return "Forbidden", 403
75
 
76
 
77
  @app.route("/backup")
78
  def backup():
79
+ logs["port_scans"] += 1
 
 
 
 
80
  return "Forbidden", 403
81
 
82
 
83
+ # ---------------- Logs ----------------
84
+
85
+ @app.route("/logs", methods=["GET"])
86
+ def get_logs():
87
+ return jsonify(logs)
88
+
89
+
90
+ # ---------------- State API ----------------
91
+
92
+ @app.route("/state")
93
+ def state():
94
+ return jsonify({
95
+ "failed_logins": logs["failed_logins"],
96
+ "port_scans": logs["port_scans"],
97
+ "suspicious_ips": logs["suspicious_ips"],
98
+ "total_requests": len(logs["requests"])
99
+ })
100
+
101
+
102
+ # ---------------- Reset API ----------------
103
+
104
+ @app.route("/reset", methods=["POST"])
105
+ def reset():
106
+ global logs
107
+ logs = {
108
+ "failed_logins": 0,
109
+ "port_scans": 0,
110
+ "suspicious_ips": [],
111
+ "requests": []
112
+ }
113
+ return jsonify({"status": "reset"})
114
+
115
+
116
+ # ---------------- Step API (IMPORTANT) ----------------
117
+
118
+ @app.route("/step", methods=["POST"])
119
+ def step():
120
+
121
+ action = request.json.get("action")
122
+
123
+ reward = 0.0
124
+ done = False
125
+
126
+ # Detect brute force
127
+ if action == "detect_bruteforce":
128
+ if logs["failed_logins"] > 3:
129
+ reward = 0.4
130
+
131
+ # Detect port scan
132
+ elif action == "detect_portscan":
133
+ if logs["port_scans"] > 0:
134
+ reward = 0.3
135
+
136
+ # Mitigation step
137
+ elif action == "mitigate_attack":
138
+ if len(logs["suspicious_ips"]) > 0:
139
+ reward = 1.0
140
+ done = True
141
+
142
+ return jsonify({
143
+ "state": logs,
144
+ "reward": reward,
145
+ "done": done,
146
+ "info": {}
147
+ })
148
+
149
+
150
+ # ---------------- Status ----------------
151
+
152
  @app.route("/status")
153
  def status():
154
+ return jsonify({
155
  "environment": "AI Cyber Deception",
156
  "attacks": [
157
  "brute_force",
 
159
  "credential_stuffing"
160
  ],
161
  "status": "running"
162
+ })
 
163
 
 
164
 
165
+ # ---------------- Home ----------------
 
 
166
 
167
+ @app.route("/")
168
+ def home():
169
+ return "AI Cyber Deception Server Running"
 
 
 
 
 
170
 
 
 
 
171
 
172
+ # ---------------- Run Server ----------------
173
+
174
+ def run_server():
175
+ app.run(
176
+ host="0.0.0.0",
177
+ port=7860,
178
+ debug=False,
179
+ use_reloader=False
180
+ )
inference.py CHANGED
@@ -1,57 +1,102 @@
1
  import threading
2
  import time
 
 
 
3
 
4
- from env.fake_server import run_server, RESULTS
5
- from tasks.easy import run as easy
6
- from tasks.medium import run as medium
7
- from tasks.hard import run as hard
8
 
9
- # Start fake server in background
10
- server_thread = threading.Thread(target=run_server, daemon=True)
11
- server_thread.start()
12
 
13
- time.sleep(2) # wait for server to start
 
 
14
 
15
- print("[START] task=ai-deception env=cyber-security model=baseline", flush=True)
 
 
16
 
17
- # Run continuously
18
- while True:
 
19
 
20
- # Easy Task
21
- easy_score = easy()
22
- print(
23
- f"[STEP] step=1 action=easy reward={easy_score:.2f} done=false error=null",
24
- flush=True
25
- )
26
 
27
- # Medium Task
28
- medium_score = medium()
29
- print(
30
- f"[STEP] step=2 action=medium reward={medium_score:.2f} done=false error=null",
31
- flush=True
32
- )
33
 
34
- # Hard Task
35
- hard_score = hard()
36
- print(
37
- f"[STEP] step=3 action=hard reward={hard_score:.2f} done=true error=null",
38
- flush=True
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  )
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  print(
42
- f"[END] success=true steps=3 rewards={easy_score:.2f},{medium_score:.2f},{hard_score:.2f}",
 
43
  flush=True
44
  )
45
 
46
- # Update results for judges
47
- RESULTS["status"] = "completed"
48
- RESULTS["steps"] = 3
49
- RESULTS["rewards"] = [easy_score, medium_score, hard_score]
50
- RESULTS["attacks"] = [
51
- "brute_force",
52
- "port_scan",
53
- "credential_stuffing"
54
- ]
55
-
56
- # wait before next attack cycle
57
- time.sleep(60)
 
1
  import threading
2
  import time
3
+ import os
4
+ import random
5
+ from openai import OpenAI
6
 
7
+ random.seed(42)
 
 
 
8
 
9
+ from env.fake_server import run_server
10
+ from env.env import DeceptionEnv
11
+ from env.attacker import simulate_attack
12
 
13
+ # Start server
14
+ threading.Thread(target=run_server, daemon=True).start()
15
+ time.sleep(2)
16
 
17
+ API_BASE_URL = os.getenv("API_BASE_URL", "https://router.huggingface.co/v1")
18
+ MODEL_NAME = os.getenv("MODEL_NAME", "Qwen/Qwen2.5-7B-Instruct")
19
+ HF_TOKEN = os.getenv("HF_TOKEN")
20
 
21
+ if not HF_TOKEN:
22
+ print("[ERROR] HF_TOKEN not set. Please set your Hugging Face token.")
23
+ exit(1)
24
 
25
+ client = OpenAI(
26
+ base_url=API_BASE_URL,
27
+ api_key=HF_TOKEN
28
+ )
 
 
29
 
30
+ env = DeceptionEnv()
31
+ state = env.reset() # reset only once
 
 
 
 
32
 
33
+ print("[START] task=ai-deception env=cyber-security model=AI-agent", flush=True)
34
+
35
+ rewards = []
36
+ history = []
37
+
38
+ for step in range(1, 4):
39
+
40
+ simulate_attack()
41
+
42
+ summary = {
43
+ "failed_logins": state["failed_logins"],
44
+ "port_scans": state.get("port_scans", 0),
45
+ "suspicious_ips": len(state["suspicious_ips"])
46
+ }
47
+
48
+ prompt = f"""
49
+ You are a cybersecurity decision system.
50
+
51
+ Previous actions:
52
+ {history}
53
+
54
+ Current summary:
55
+ {summary}
56
+
57
+ STRICT RULES (must follow exactly):
58
+
59
+ 1. If no previous action → detect_attack
60
+ 2. If last action == detect_attack → deploy_honeypot
61
+ 3. If last action == deploy_honeypot → block_ip
62
+ 4. If last action == block_ip → block_ip
63
+
64
+ Return ONLY one word:
65
+ detect_attack
66
+ deploy_honeypot
67
+ fake_database
68
+ block_ip
69
+ """
70
+
71
+ response = client.chat.completions.create(
72
+ model=MODEL_NAME,
73
+ messages=[{"role": "user", "content": prompt}],
74
+ temperature=0.2,
75
+ max_tokens=20
76
  )
77
 
78
+ action = response.choices[0].message.content.strip()
79
+
80
+ # deterministic fallback
81
+ if history:
82
+ last = history[-1]
83
+ if last == "detect_attack":
84
+ action = "deploy_honeypot"
85
+ elif last == "deploy_honeypot":
86
+ action = "block_ip"
87
+
88
+ history.append(action)
89
+
90
+ state, reward, done, _ = env.step(action)
91
+ rewards.append(reward)
92
+
93
  print(
94
+ f"[STEP] step={step} action={action} reward={reward:.2f} "
95
+ f"done={str(done).lower()} error=null",
96
  flush=True
97
  )
98
 
99
+ print(
100
+ f"[END] success=true steps=3 rewards={','.join(f'{r:.2f}' for r in rewards)}",
101
+ flush=True
102
+ )