diwanshisharma19 commited on
Commit
7104055
·
1 Parent(s): b40a5d1

Add my app files

Browse files
Files changed (3) hide show
  1. app.py +646 -0
  2. error_analyzer.py +30 -0
  3. requirements.txt +9 -0
app.py ADDED
@@ -0,0 +1,646 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import gradio as gr
2
+ import os
3
+ import subprocess
4
+ import paramiko
5
+ import socket
6
+ from dotenv import load_dotenv
7
+ from ddgs import DDGS
8
+ from langchain_core.messages import HumanMessage, ToolMessage, SystemMessage, AIMessage
9
+ from langchain_openai import ChatOpenAI
10
+ from langchain_core.tools import tool
11
+ from typing import Annotated
12
+ from typing_extensions import TypedDict
13
+ from langgraph.checkpoint.memory import InMemorySaver
14
+ from langgraph.graph import StateGraph, START, END
15
+ from langgraph.graph.message import add_messages
16
+ from langgraph.prebuilt import ToolNode, tools_condition
17
+ from error_analyzer import analyze_error
18
+ import logging
19
+ import re
20
+ import json
21
+
22
+ # Load environment variables from .env file (for local development)
23
+ load_dotenv()
24
+
25
+ # Configure logging
26
+ logging.basicConfig(level=logging.INFO, filename="agent.log", format="%(asctime)s - %(levelname)s - %(message)s")
27
+
28
+ # SSH details from environment variables (for Hugging Face Spaces)
29
+ # These will be overridden by user input if provided
30
+ DEFAULT_SSH_DETAILS = {
31
+ "linux": {
32
+ "hostname": os.getenv("LINUX_SSH_HOST", ""),
33
+ "port": int(os.getenv("LINUX_SSH_PORT", "22")),
34
+ "username": os.getenv("LINUX_SSH_USER", ""),
35
+ "password": os.getenv("LINUX_SSH_PASS", "")
36
+ },
37
+ "windows": {
38
+ "hostname": os.getenv("WINDOWS_SSH_HOST", ""),
39
+ "port": int(os.getenv("WINDOWS_SSH_PORT", "22")),
40
+ "username": os.getenv("WINDOWS_SSH_USER", ""),
41
+ "password": os.getenv("WINDOWS_SSH_PASS", "")
42
+ }
43
+ }
44
+
45
+ # Global variable to store user-provided SSH details
46
+ user_ssh_details = {
47
+ "linux": DEFAULT_SSH_DETAILS["linux"].copy(),
48
+ "windows": DEFAULT_SSH_DETAILS["windows"].copy()
49
+ }
50
+
51
+ # System prompt
52
+ SYSTEM_PROMPT = """
53
+ You are Mr. Robot, an expert terminal assistant specializing in pentesting, capture-the-flag (CTF) challenges, and command-line operations on both Linux and Windows (PowerShell) environments. Your primary goal is to assist users by intelligently interpreting natural language inputs and generating and executing accurate, secure, and efficient commands tailored to their intent on the specified system (Linux or Windows). Follow these guidelines:
54
+
55
+ 1. **Role and Expertise**:
56
+ - You are connected to a machine via SSH and can run commands on it using the remote_execute tool, which supports both Kali Linux and Windows Server PowerShell environments.
57
+ - Act as a knowledgeable pentesting and CTF expert, proficient in Linux tools (e.g., nmap, metasploit, netcat) and Windows PowerShell commands (e.g., Get-NetIPAddress, Invoke-WebRequest).
58
+ - Dynamically generate and execute commands based on user intent, considering the target system (Linux or Windows) and task requirements (e.g., network scanning, file manipulation).
59
+ - Prioritize safe and ethical practices, warning users about potentially dangerous commands (e.g., rm, del, chmod, network scans) and ensuring they have permission.
60
+ - Always start with web_search for any query involving recent techniques, tools, installations, vulnerabilities, or CTF solutions. Craft precise, keyword-rich queries (e.g., 'latest nmap stealth scanning flags for pentesting site:github.com' instead of 'nmap commands'). Use search operators like site:, filetype:, or "exact phrase" for relevance. If results are poor, chain another web_search with refined queries.
61
+ - For installations related tasks, first prioritise knowing relevant system info and compatible versions, use web_search for installation guides and documentations and bug resolving.
62
+
63
+ 2. **Response Style**:
64
+ - Use a professional yet approachable tone, like a seasoned cybersecurity mentor.
65
+ - Break down complex tasks into clear, actionable steps with brief explanations.
66
+ - Respond concisely unless detailed explanations are requested.
67
+ - After web_search, summarize key snippets/links and directly integrate them into your reasoning or commands (e.g., 'Based on search result [snippet], use nmap -sS'). If the web_search tool returns JSON results, parse the JSON, extract relevant titles, links, and snippets, and summarize them clearly in your response.
68
+
69
+ 3. **Command Generation**:
70
+ - Interpret natural language inputs to generate appropriate commands for the target system (e.g., "find ip of machine" might generate `ip addr show` for Linux or `Get-NetIPAddress` for Windows).
71
+ - For ambiguous requests, use chat_with_human to clarify intent.
72
+ - Detect long-running commands (e.g., python3 -m http.server, Start-Process, nc -l) and:
73
+ - Apply a short timeout (e.g., 5 seconds) to capture initial output.
74
+ - Inform the user the process is running and provide instructions (e.g., `ps aux | grep <command>` for Linux, `Get-Process` for Windows, or stop with `kill <pid>`/`Stop-Process`).
75
+ - Suggest background execution (e.g., appending `&` for Linux or `Start-Process` for Windows) if appropriate.
76
+
77
+ 4. **Error Awareness and Auto-Debugging**:
78
+ - Analyze command outputs for errors (e.g., "input device is not a TTY", "Permission denied", "Host seems down" for Linux; "Access is denied", "Command not found" for Windows).
79
+ - Use reasoning to suggest context-aware fixes (e.g., add `sudo` for Linux permission issues, `Run as Administrator` for Windows, adjust nmap flags for unreachable hosts).
80
+ - If an error is unclear, escalate to chat_with_human.
81
+ - Log errors in the state to improve future responses.
82
+ - After hitting errors, gather system-specific context (e.g., directories, files, versions, libraries) using remote_execute.
83
+
84
+ 5. **Context Retention**:
85
+ - Maintain conversation context using message history for coherent multi-turn interactions.
86
+ - Track the user's current task (e.g., CTF challenge, network scan) and tailor commands to the target system.
87
+
88
+ 6. **Tool Usage**:
89
+ - Use remote_execute to execute commands on the specified system (Kali Linux or Windows Server) via SSH.
90
+ - Use error_analyzer to analyze command outputs only if you think you can't resolve error.
91
+ - Use chat_with_human for human confirmation before executing any risky commands on server, for clarifications, or casual interactions.
92
+ - Use web_search to fetch the latest articles, commands, or information from the web to assist in tasks, especially for up-to-date pentesting techniques or CTF solutions. Analyze and apply results relevantly.
93
+ - Avoid TTY issues in Docker commands by generating non-interactive commands.
94
+ - After remote_execute, call error_analyzer if the output suggests an issue or error otherwise proceed.
95
+
96
+ 7. **Constraints**:
97
+ - Do not execute commands without confirmation from human if they could modify the system (e.g., rm, del, chmod, Set-ItemProperty).
98
+ - Warn users about legal and ethical implications of network scanning (e.g., nmap, Test-NetConnection) and confirm permission.
99
+ - If unsure about command safety or user intent, use chat_with_human.
100
+ - Ensure all commands are runnable without further interaction, using techniques like `cat <<EOF` for Linux or `Out-File` for Windows for input.
101
+
102
+ 8. **Additional Tool Usage**:
103
+ - Call `respond_directly` for direct answers, summaries, or explanations without needing tools.
104
+ - Call `end_task` when the task is resolved to finalize.
105
+ - Call `chat_with_human` for user doubts or casual talk, to seek human input anytime you want.
106
+
107
+ Respond intelligently, generating commands that are accurate, safe, and tailored to the user's needs and target system. Empower the user with knowledge while maintaining security and ethical standards.
108
+ """
109
+
110
+ # LLM initialization
111
+ llm = ChatOpenAI(
112
+ api_key=os.getenv("OPENAI_API_KEY", ""),
113
+ base_url=os.getenv("OPENAI_BASE_URL", "https://api.groq.com/openai/v1"),
114
+ model=os.getenv("OPENAI_MODEL", "meta-llama/llama-4-maverick-17b-128e-instruct"),
115
+ )
116
+
117
+ # SSH connection functions
118
+ def connected_kali(command, timeout=30):
119
+ """Execute a command on a remote Kali Linux machine via SSH."""
120
+ ssh_client = paramiko.SSHClient()
121
+ ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
122
+
123
+ try:
124
+ ssh_details = user_ssh_details.get("linux", DEFAULT_SSH_DETAILS["linux"])
125
+
126
+ # Check if SSH details are configured
127
+ if not ssh_details.get("hostname") or not ssh_details.get("username"):
128
+ return "[Error]: Linux SSH details not configured. Please configure SSH settings first."
129
+
130
+ logging.info(f"Executing Linux command: {command}")
131
+ ssh_client.connect(
132
+ hostname=ssh_details["hostname"],
133
+ port=ssh_details["port"],
134
+ username=ssh_details["username"],
135
+ password=ssh_details["password"],
136
+ timeout=10
137
+ )
138
+ stdin, stdout, stderr = ssh_client.exec_command(command, get_pty=False, timeout=timeout)
139
+ output = stdout.read().decode()
140
+ error = stderr.read().decode()
141
+
142
+ logging.info(f"Output: {output}")
143
+ logging.info(f"Error: {error}")
144
+
145
+ if output:
146
+ return output
147
+ if error:
148
+ return f"[Error]: {error}"
149
+ return "[No output]"
150
+
151
+ except socket.timeout:
152
+ return f"[Timeout]: Command '{command}' timed out after {timeout} seconds. If this is a server (e.g., python3 -m http.server), it may be running. Check with `ps aux | grep {command.split()[0]}` or stop with `kill <pid>`."
153
+ except Exception as e:
154
+ return f"[Error]: Failed to execute '{command}': {str(e)}"
155
+ finally:
156
+ ssh_client.close()
157
+
158
+ def connected_windows(command, timeout=30):
159
+ """Execute a PowerShell command on a remote Windows Server via SSH."""
160
+ ssh_client = paramiko.SSHClient()
161
+ ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
162
+
163
+ try:
164
+ ssh_details = user_ssh_details.get("windows", DEFAULT_SSH_DETAILS["windows"])
165
+
166
+ # Check if SSH details are configured
167
+ if not ssh_details.get("hostname") or not ssh_details.get("username"):
168
+ return "[Error]: Windows SSH details not configured. Please configure SSH settings first."
169
+
170
+ logging.info(f"Executing Windows PowerShell command: {command}")
171
+ ssh_client.connect(
172
+ hostname=ssh_details["hostname"],
173
+ port=ssh_details["port"],
174
+ username=ssh_details["username"],
175
+ password=ssh_details["password"],
176
+ timeout=10
177
+ )
178
+ ps_command = f"powershell -Command \"{command}\""
179
+ stdin, stdout, stderr = ssh_client.exec_command(ps_command, get_pty=False, timeout=timeout)
180
+ output = stdout.read().decode()
181
+ error = stderr.read().decode()
182
+
183
+ logging.info(f"Output: {output}")
184
+ logging.info(f"Error: {error}")
185
+
186
+ if output:
187
+ return output
188
+ if error:
189
+ return f"[Error]: {error}"
190
+ return "[No output]"
191
+
192
+ except socket.timeout:
193
+ return f"[Timeout]: Command '{command}' timed out after {timeout} seconds. If this is a server process, it may be running. Check with `Get-Process` or stop with `Stop-Process -Id <pid>`."
194
+ except Exception as e:
195
+ return f"[Error]: Failed to execute '{command}': {str(e)}"
196
+ finally:
197
+ ssh_client.close()
198
+
199
+ # Tools
200
+ @tool
201
+ def remote_execute(query: str, system: str = "linux") -> str:
202
+ """Execute a command on a remote system (Kali Linux or Windows Server) via SSH."""
203
+ logging.info(f"Executing command on {system}: {query}")
204
+ try:
205
+ timeout = 30 if "nmap" in query.lower() or "Test-NetConnection" in query.lower() else 5 if any(cmd in query.lower() for cmd in ["python3 -m http.server", "nc -l", "apache2", "nginx", "flask run", "node server.js", "Start-Process"]) else 30
206
+ if system.lower() == "linux":
207
+ output = connected_kali(query, timeout=timeout)
208
+ elif system.lower() == "windows":
209
+ output = connected_windows(query, timeout=timeout)
210
+ else:
211
+ return f"[Error]: Invalid system specified: {system}. Use 'linux' or 'windows'."
212
+ return output
213
+ except Exception as e:
214
+ return f"[Error]: Failed to execute '{query}' on {system}: {str(e)}. Please check the command or use chat_with_human for clarification."
215
+
216
+ @tool
217
+ def say_hello(name: str) -> str:
218
+ """Greet a user by name."""
219
+ logging.info(f"Greeting tool called: {name}")
220
+ return f"Hello, {name} from Own_The_Net"
221
+
222
+ @tool
223
+ def error_analyzer(command: str, output: str) -> str:
224
+ """Analyze command output for errors and suggest fixes using LLM reasoning."""
225
+ logging.info(f"Analyzing output for errors: {output[:30]}...")
226
+ return analyze_error(command, output, llm_with_tools, SYSTEM_PROMPT)
227
+
228
+ @tool
229
+ def respond_directly(reasoning: str) -> str:
230
+ """Use this tool when no further execution or analysis is needed."""
231
+ logging.info(f"Direct response tool called: {reasoning}")
232
+ return reasoning
233
+
234
+ @tool
235
+ def end_task(summary: str = "Task completed.") -> str:
236
+ """Call this tool to signal that the task is complete."""
237
+ logging.info(f"End task tool called: {summary}")
238
+ return f"[END_TASK]: {summary} - Interaction finalized."
239
+
240
+ @tool
241
+ def chat_with_human(query: str, context: str = "") -> str:
242
+ """Use this for casual conversation, user doubts, clarifications, or risky command confirmations."""
243
+ logging.info(f"Chat with human tool called: {query}")
244
+ return f"[HUMAN_INPUT_REQUIRED]: {query}\nContext: {context or 'No additional context.'}"
245
+
246
+ @tool
247
+ def web_search(query: str) -> str:
248
+ """Search the web for the latest articles and commands using DuckDuckGo."""
249
+ logging.info(f"Performing web search for: {query}")
250
+ try:
251
+ results = []
252
+ with DDGS() as ddgs:
253
+ results = list(ddgs.text(query, region='us-en', max_results=5))
254
+ if not results:
255
+ broadened_query = re.sub(r'\b\d{4}\b', '', query).strip() + " OR tutorial OR guide"
256
+ logging.info(f"No results for '{query}'. Retrying with broadened query: '{broadened_query}'")
257
+ results = list(ddgs.text(broadened_query, region='us-en', max_results=5))
258
+ if results:
259
+ formatted_results = [
260
+ {"title": r['title'], "link": r['href'], "snippet": r['body']}
261
+ for r in results
262
+ ]
263
+ logging.info(f"Web search results: {formatted_results}")
264
+ return json.dumps(formatted_results, indent=2)
265
+ else:
266
+ logging.warning(f"No results found even after broadening query for '{query}'")
267
+ return json.dumps({"warning": "No search results found. Try refining the query."})
268
+ except Exception as e:
269
+ logging.error(f"Web search failed: {str(e)}")
270
+ return json.dumps({"error": f"Failed to perform web search for '{query}': {str(e)}. Try a different query."})
271
+
272
+ # State
273
+ class State(TypedDict):
274
+ messages: Annotated[list, add_messages]
275
+ command_output: str
276
+ human_reviewed: bool
277
+ error_detected: bool
278
+ target_system: str
279
+
280
+ # Build graph
281
+ def build_graph():
282
+ graph_builder = StateGraph(State)
283
+
284
+ def chatbot(state: State):
285
+ messages = [SystemMessage(content=SYSTEM_PROMPT)] + state["messages"]
286
+ logging.info(f"Invoking LLM with messages: {[msg.type for msg in messages]}")
287
+ message = llm_with_tools.invoke(messages)
288
+ if isinstance(message, AIMessage):
289
+ logging.info(f"LLM reasoning: {message.content}")
290
+ if hasattr(message, 'tool_calls') and message.tool_calls:
291
+ for tc in message.tool_calls:
292
+ logging.info(f"Agent tool call: {tc['name']} with args: {tc['args']}")
293
+ elif message.content:
294
+ logging.info(f"Agent response: {message.content[:100]}...")
295
+ else:
296
+ logging.warning("Agent returned empty response or invalid tool call")
297
+ message.content = "[Error]: Agent failed to provide a valid response or tool call."
298
+ return {
299
+ "messages": [message],
300
+ "command_output": state.get("command_output", ""),
301
+ "target_system": state.get("target_system", "linux")
302
+ }
303
+
304
+ def tools_to_next(state: State):
305
+ if not state["messages"] or not isinstance(state["messages"][-1], ToolMessage):
306
+ return "chatbot"
307
+ last_tool = state["messages"][-1].name
308
+ if last_tool in ["end_task", "respond_directly"]:
309
+ return END
310
+ else:
311
+ return "chatbot"
312
+
313
+ tools = [remote_execute, say_hello, error_analyzer, respond_directly, end_task, chat_with_human, web_search]
314
+
315
+ global llm_with_tools
316
+ llm_with_tools = llm.bind_tools(tools)
317
+ tool_node = ToolNode(tools=tools)
318
+
319
+ graph_builder.add_node("chatbot", chatbot)
320
+ graph_builder.add_node("tools", tool_node)
321
+ graph_builder.add_conditional_edges("chatbot", tools_condition)
322
+ graph_builder.add_conditional_edges("tools", tools_to_next)
323
+ graph_builder.add_edge(START, "chatbot")
324
+
325
+ return graph_builder.compile(checkpointer=InMemorySaver())
326
+
327
+ # Initialize graph globally
328
+ graph = build_graph()
329
+ config = {"configurable": {"thread_id": "1"}}
330
+
331
+ # Function to update SSH settings
332
+ def update_ssh_settings(system_type, hostname, port, username, password):
333
+ """Update SSH settings for the selected system"""
334
+ global user_ssh_details
335
+
336
+ system_key = system_type.lower()
337
+
338
+ if system_key not in user_ssh_details:
339
+ return f"❌ Invalid system type: {system_type}"
340
+
341
+ user_ssh_details[system_key] = {
342
+ "hostname": hostname,
343
+ "port": int(port),
344
+ "username": username,
345
+ "password": password
346
+ }
347
+
348
+ logging.info(f"Updated SSH settings for {system_type}")
349
+ return f"✅ {system_type} SSH settings saved successfully!"
350
+
351
+ # Function to get current SSH settings
352
+ def get_ssh_settings(system_type):
353
+ """Get current SSH settings for the selected system"""
354
+ system_key = system_type.lower()
355
+ settings = user_ssh_details.get(system_key, {})
356
+
357
+ return (
358
+ settings.get("hostname", ""),
359
+ settings.get("port", 22),
360
+ settings.get("username", ""),
361
+ settings.get("password", "")
362
+ )
363
+
364
+ # Function to test SSH connection
365
+ def test_ssh_connection(system_type):
366
+ """Test SSH connection for the selected system"""
367
+ system_key = system_type.lower()
368
+ ssh_details = user_ssh_details.get(system_key, {})
369
+
370
+ if not ssh_details.get("hostname") or not ssh_details.get("username"):
371
+ return "❌ Please configure SSH settings first!"
372
+
373
+ ssh_client = paramiko.SSHClient()
374
+ ssh_client.set_missing_host_key_policy(paramiko.AutoAddPolicy())
375
+
376
+ try:
377
+ ssh_client.connect(
378
+ hostname=ssh_details["hostname"],
379
+ port=ssh_details["port"],
380
+ username=ssh_details["username"],
381
+ password=ssh_details["password"],
382
+ timeout=10
383
+ )
384
+
385
+ # Run a simple test command
386
+ if system_key == "linux":
387
+ stdin, stdout, stderr = ssh_client.exec_command("whoami", timeout=5)
388
+ else:
389
+ stdin, stdout, stderr = ssh_client.exec_command('powershell -Command "whoami"', timeout=5)
390
+
391
+ output = stdout.read().decode().strip()
392
+
393
+ ssh_client.close()
394
+
395
+ return f"✅ Connection successful!\n\nConnected to: {ssh_details['hostname']}\nLogged in as: {output}"
396
+
397
+ except Exception as e:
398
+ return f"❌ Connection failed!\n\nError: {str(e)}\n\nPlease check your credentials and try again."
399
+
400
+ # Gradio chat function
401
+ def chat(message, history, system_choice):
402
+ """Process user message and return response"""
403
+ target_system = system_choice.lower()
404
+
405
+ # Check if SSH is configured for the selected system
406
+ ssh_details = user_ssh_details.get(target_system, {})
407
+ if not ssh_details.get("hostname") or not ssh_details.get("username"):
408
+ history = history or []
409
+ history.append([message, f"⚠️ **SSH Configuration Required**\n\nPlease configure {system_choice} SSH settings in the **⚙️ SSH Settings** tab before using the agent.\n\nRequired:\n- Hostname/IP\n- Port\n- Username\n- Password"])
410
+ return history
411
+
412
+ # Create input message
413
+ input_msg = HumanMessage(content=message)
414
+
415
+ # Prepare input for graph with target system
416
+ input_dict = {
417
+ "messages": [input_msg],
418
+ "target_system": target_system
419
+ }
420
+
421
+ response_text = ""
422
+
423
+ try:
424
+ # Stream events from graph
425
+ events = graph.stream(input_dict, config, stream_mode="values")
426
+
427
+ for event in events:
428
+ if "messages" in event:
429
+ msg = event["messages"][-1]
430
+
431
+ if isinstance(msg, ToolMessage):
432
+ tool_name = msg.name if msg.name else "Status"
433
+ response_text += f"\n**🛠️ Tool Output ({tool_name}):**\n{msg.content}\n"
434
+
435
+ elif isinstance(msg, AIMessage):
436
+ if msg.content:
437
+ response_text += f"{msg.content}\n"
438
+ if hasattr(msg, 'tool_calls') and msg.tool_calls:
439
+ for tc in msg.tool_calls:
440
+ args_str = ", ".join([f"{k}: {v}" for k, v in tc['args'].items()])
441
+ response_text += f"\n**🔧 Calling Tool: {tc['name']}**\nInputs: {args_str}\n"
442
+ else:
443
+ response_text += f"{msg.content}\n"
444
+
445
+ final_response = response_text if response_text else "No response generated."
446
+
447
+ # Return in correct format for Gradio Chatbot: history + new message
448
+ history = history or []
449
+ history.append([message, final_response])
450
+ return history
451
+
452
+ except Exception as e:
453
+ logging.error(f"Error in chat: {str(e)}")
454
+ history = history or []
455
+ history.append([message, f"❌ Error: {str(e)}"])
456
+ return history
457
+
458
+ # Create Gradio interface
459
+ with gr.Blocks(title="Server Administrator Agent", theme=gr.themes.Soft()) as demo:
460
+ gr.Markdown(
461
+ """
462
+ # 🤖 Server Administrator Agent (Mr. Robot)
463
+
464
+ An expert terminal assistant for pentesting, CTF challenges, and command-line operations.
465
+
466
+ **Features:**
467
+ - Execute commands on Linux and Windows systems via SSH
468
+ - Web search for latest techniques and solutions
469
+ - Auto-debugging and error analysis
470
+ - Safe command execution with warnings
471
+
472
+ ⚙️ **Please configure your SSH settings before starting!**
473
+ """
474
+ )
475
+
476
+ with gr.Tabs():
477
+ # Main Chat Tab
478
+ with gr.Tab("💬 Chat"):
479
+ with gr.Row():
480
+ with gr.Column(scale=3):
481
+ system_dropdown = gr.Dropdown(
482
+ choices=["Linux", "Windows"],
483
+ value="Linux",
484
+ label="Target System",
485
+ info="Select which system to execute commands on"
486
+ )
487
+
488
+ chatbot = gr.Chatbot(
489
+ height=500,
490
+ show_label=False,
491
+ avatar_images=(None, "🤖")
492
+ )
493
+
494
+ with gr.Row():
495
+ msg = gr.Textbox(
496
+ placeholder="Type your message here...",
497
+ show_label=False,
498
+ scale=9
499
+ )
500
+ submit = gr.Button("Send", variant="primary", scale=1)
501
+
502
+ clear = gr.Button("🗑️ Clear Chat")
503
+
504
+ with gr.Column(scale=1):
505
+ gr.Markdown(
506
+ """
507
+ ### ℹ️ Tips
508
+
509
+ - Ask about pentesting techniques
510
+ - Request command execution
511
+ - Get help with CTF challenges
512
+ - Search for latest security tools
513
+
514
+ ### ⚠️ Safety
515
+
516
+ - Risky commands require confirmation
517
+ - Always ensure you have permission
518
+ - Ethical hacking practices only
519
+
520
+ ### 🔧 Quick Start
521
+
522
+ 1. Configure SSH settings in Settings tab
523
+ 2. Select target system (Linux/Windows)
524
+ 3. Start chatting!
525
+ """
526
+ )
527
+
528
+ # SSH Settings Tab
529
+ with gr.Tab("⚙️ SSH Settings"):
530
+ gr.Markdown(
531
+ """
532
+ ## Configure SSH Connection Details
533
+
534
+ Enter your server credentials below. These credentials are stored only during your session.
535
+ """
536
+ )
537
+
538
+ with gr.Row():
539
+ with gr.Column():
540
+ ssh_system_selector = gr.Radio(
541
+ choices=["Linux", "Windows"],
542
+ value="Linux",
543
+ label="Select System to Configure",
544
+ info="Choose which system's SSH settings you want to update"
545
+ )
546
+
547
+ with gr.Row():
548
+ with gr.Column():
549
+ ssh_hostname = gr.Textbox(
550
+ label="SSH Hostname/IP",
551
+ placeholder="e.g., 192.168.1.100 or server.example.com",
552
+ info="The server IP address or hostname"
553
+ )
554
+
555
+ ssh_port = gr.Number(
556
+ label="SSH Port",
557
+ value=22,
558
+ precision=0,
559
+ info="SSH port (default: 22)"
560
+ )
561
+
562
+ ssh_username = gr.Textbox(
563
+ label="SSH Username",
564
+ placeholder="e.g., root or administrator",
565
+ info="Your SSH username"
566
+ )
567
+
568
+ ssh_password = gr.Textbox(
569
+ label="SSH Password",
570
+ placeholder="Enter password",
571
+ type="password",
572
+ info="Your SSH password (not stored permanently)"
573
+ )
574
+
575
+ with gr.Row():
576
+ save_ssh_btn = gr.Button("💾 Save SSH Settings", variant="primary", scale=2)
577
+ load_ssh_btn = gr.Button("🔄 Load Current Settings", scale=1)
578
+
579
+ ssh_status = gr.Textbox(
580
+ label="Status",
581
+ interactive=False,
582
+ placeholder="Configure and save your SSH settings..."
583
+ )
584
+
585
+ gr.Markdown(
586
+ """
587
+ ### 📝 Notes:
588
+ - Settings are stored only during your session
589
+ - You can configure both Linux and Windows systems
590
+ - Switch between systems using the radio button above
591
+ - Test your connection by sending a simple command in the Chat tab
592
+
593
+ ### 🔒 Security:
594
+ - Credentials are not saved to disk
595
+ - Use this on trusted networks only
596
+ - Consider using SSH keys instead of passwords for production
597
+ """
598
+ )
599
+
600
+ # Event handlers for Chat tab
601
+ submit.click(
602
+ chat,
603
+ inputs=[msg, chatbot, system_dropdown],
604
+ outputs=chatbot
605
+ ).then(
606
+ lambda: gr.update(value=""),
607
+ None,
608
+ msg
609
+ )
610
+
611
+ msg.submit(
612
+ chat,
613
+ inputs=[msg, chatbot, system_dropdown],
614
+ outputs=chatbot
615
+ ).then(
616
+ lambda: gr.update(value=""),
617
+ None,
618
+ msg
619
+ )
620
+
621
+ clear.click(lambda: [], None, chatbot, queue=False)
622
+
623
+ # Event handlers for SSH Settings tab
624
+ save_ssh_btn.click(
625
+ update_ssh_settings,
626
+ inputs=[ssh_system_selector, ssh_hostname, ssh_port, ssh_username, ssh_password],
627
+ outputs=ssh_status
628
+ )
629
+
630
+ load_ssh_btn.click(
631
+ get_ssh_settings,
632
+ inputs=ssh_system_selector,
633
+ outputs=[ssh_hostname, ssh_port, ssh_username, ssh_password]
634
+ )
635
+
636
+ # Auto-load settings when system selector changes
637
+ ssh_system_selector.change(
638
+ get_ssh_settings,
639
+ inputs=ssh_system_selector,
640
+ outputs=[ssh_hostname, ssh_port, ssh_username, ssh_password]
641
+ )
642
+
643
+ # Launch the app
644
+ if __name__ == "__main__":
645
+ demo.queue()
646
+ demo.launch()
error_analyzer.py ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/python3
2
+ from langchain_core.messages import SystemMessage, HumanMessage
3
+
4
+ def analyze_error(kali_command: str, kali_output: str, llm_with_tools, system_prompt: str) -> str:
5
+ """
6
+ Analyze kali_linux or fortinet_monitor output for errors and suggest fixes using LLM reasoning.
7
+
8
+ Args:
9
+ kali_command (str): The executed command.
10
+ kali_output (str): The command’s output.
11
+ llm_with_tools: The initialized LLM instance with bound tools.
12
+ system_prompt (str): The system prompt for context.
13
+
14
+ Returns:
15
+ str: Analysis with status, message, and suggested fix.
16
+ """
17
+ prompt = f"""
18
+ Analyze the following command and its output for errors. Suggest a fix or next steps based on the error context. Detect if it's from Kali (e.g., Linux errors) or Fortinet (e.g., 'Command fail. Return code'). If no error, confirm validity. If unclear, recommend human_assistance.
19
+
20
+ Command: {kali_command}
21
+ Output: {kali_output}
22
+
23
+ Provide a concise response with:
24
+ - [Status]: Output valid
25
+ - [Message]: Explanation of the error or confirmation
26
+ - [Suggested Fix]: Fix or next steps (if applicable)
27
+ """
28
+ messages = [SystemMessage(content=system_prompt), HumanMessage(content=prompt)]
29
+ analysis = llm_with_tools.invoke(messages).content # Use llm_with_tools instead of llm
30
+ return analysis
requirements.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ gradio==5.49.1
2
+ paramiko==3.5.1
3
+ duckduckgo-search==8.1.1
4
+ ddgs==9.6.1
5
+ langchain-core==0.3.72
6
+ langchain-openai==0.3.28
7
+ langgraph==0.5.4
8
+ typing-extensions==4.14.1
9
+ python-dotenv==1.1.1