Update app.py
Browse files
app.py
CHANGED
@@ -1,390 +1,390 @@
|
|
1 |
-
# =============================================================================
|
2 |
-
# Phishing Campaign Setup Assistant
|
3 |
-
# =============================================================================
|
4 |
-
# Description: A Gradio-based chatbot application using LangChain and OpenAI
|
5 |
-
# to guide users through setting up a phishing simulation campaign step-by-step.
|
6 |
-
#
|
7 |
-
# Requirements:
|
8 |
-
# - Python 3.x
|
9 |
-
# - Libraries: langchain, langchain_openai, langchain_community, gradio,
|
10 |
-
# python-dotenv, google-generativeai
|
11 |
-
# - Environment Variables (.env file):
|
12 |
-
# - OPENAI_API_KEY
|
13 |
-
# - GOOGLE_API_KEY
|
14 |
-
# - Data Files (in the same directory):
|
15 |
-
# - company_info.json
|
16 |
-
# - user_info.json
|
17 |
-
# =============================================================================
|
18 |
-
|
19 |
-
# --- 0. Required Imports ---
|
20 |
-
# Standard library imports
|
21 |
-
import os
|
22 |
-
import datetime
|
23 |
-
import json
|
24 |
-
import re
|
25 |
-
import base64
|
26 |
-
import tempfile
|
27 |
-
|
28 |
-
# Third-party imports for AI & LLMs
|
29 |
-
from dotenv import load_dotenv
|
30 |
-
from openai import OpenAI
|
31 |
-
from google import genai as google_genai
|
32 |
-
from google.genai import types as google_genai_types
|
33 |
-
from langchain.agents import create_openai_tools_agent, AgentExecutor
|
34 |
-
from langchain_openai import ChatOpenAI
|
35 |
-
from langchain_core.tools import StructuredTool
|
36 |
-
from langchain_core.messages import HumanMessage, AIMessage
|
37 |
-
from langchain import hub
|
38 |
-
from langchain_community.tools import DuckDuckGoSearchRun
|
39 |
-
|
40 |
-
# Third-party import for Web UI
|
41 |
-
import gradio as gr
|
42 |
-
|
43 |
-
# --- 1. Configuration and Initialization ---
|
44 |
-
|
45 |
-
# Load environment variables from a .env file
|
46 |
-
load_dotenv()
|
47 |
-
|
48 |
-
# Initialize the OpenAI client for the LangChain agent
|
49 |
-
# We use a low temperature (0.0) for predictable, task-oriented behavior.
|
50 |
-
llm = ChatOpenAI(model="gpt-4o", temperature=0.0)
|
51 |
-
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
52 |
-
|
53 |
-
# Initialize the Google GenAI Client for the image generation tool
|
54 |
-
# google_genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
55 |
-
genai_client = google_genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
|
56 |
-
|
57 |
-
|
58 |
-
# --- 2. Tool Definitions ---
|
59 |
-
# These functions define the actions (tools) the AI agent can perform.
|
60 |
-
|
61 |
-
def generate_image(prompt: str) -> dict:
|
62 |
-
"""
|
63 |
-
Generates an image based on a text prompt, saves it to 'generated_phishing_image.png'
|
64 |
-
in the current directory (overwriting previous images), and returns the absolute file path.
|
65 |
-
"""
|
66 |
-
# Fixed filename ensures replacement on subsequent generations.
|
67 |
-
output_filename = "generated_phishing_image.png"
|
68 |
-
|
69 |
-
print(f"INFO: Generating image with prompt: '{prompt}'")
|
70 |
-
try:
|
71 |
-
output = genai_client.models.generate_images(
|
72 |
-
prompt=prompt,
|
73 |
-
model="imagen-4.0-generate-preview-06-06",
|
74 |
-
config=google_genai_types.GenerateImagesConfig(
|
75 |
-
number_of_images=1,
|
76 |
-
aspect_ratio="16:9",
|
77 |
-
),
|
78 |
-
)
|
79 |
-
generated_img = output.generated_images[0].image
|
80 |
-
|
81 |
-
# Save the image to the fixed path in the current directory.
|
82 |
-
generated_img.save(output_filename)
|
83 |
-
|
84 |
-
# Get the absolute path for reliable referencing in the HTML.
|
85 |
-
absolute_image_path = os.path.abspath(output_filename)
|
86 |
-
|
87 |
-
print(f"INFO: Image saved to: {absolute_image_path}")
|
88 |
-
return {"status": "success", "image_path": absolute_image_path}
|
89 |
-
except Exception as e:
|
90 |
-
print(f"ERROR: Image generation failed: {e}")
|
91 |
-
return {"status": "error", "message": f"Image generation failed: {e}"}
|
92 |
-
|
93 |
-
|
94 |
-
def get_company_info() -> dict:
|
95 |
-
"""
|
96 |
-
Retrieves company information (name, logoUrl, departments, etc.) from company_info.json.
|
97 |
-
"""
|
98 |
-
print("INFO: Reading company_info.json")
|
99 |
-
try:
|
100 |
-
with open('company_info.json', 'r') as f:
|
101 |
-
data = json.load(f)
|
102 |
-
return {"status": "success", "data": data}
|
103 |
-
except FileNotFoundError:
|
104 |
-
return {"status": "error", "message": "company_info.json not found."}
|
105 |
-
except json.JSONDecodeError:
|
106 |
-
return {"status": "error", "message": "Error decoding company_info.json."}
|
107 |
-
|
108 |
-
|
109 |
-
def get_user_info() -> dict:
|
110 |
-
"""
|
111 |
-
Retrieves the current user's information (name, role, email) from user_info.json.
|
112 |
-
"""
|
113 |
-
print("INFO: Reading user_info.json")
|
114 |
-
try:
|
115 |
-
with open('user_info.json', 'r') as f:
|
116 |
-
data = json.load(f)
|
117 |
-
return {"status": "success", "data": data}
|
118 |
-
except FileNotFoundError:
|
119 |
-
return {"status": "error", "message": "user_info.json not found."}
|
120 |
-
except json.JSONDecodeError:
|
121 |
-
return {"status": "error", "message": "Error decoding user_info.json."}
|
122 |
-
|
123 |
-
|
124 |
-
def create_html_template(html_code: str) -> dict:
|
125 |
-
"""
|
126 |
-
Takes a complete HTML string, cleans it (removes newlines), and prepares it for preview.
|
127 |
-
"""
|
128 |
-
print("INFO: Formalizing agent-generated HTML template.")
|
129 |
-
# Clean HTML by removing newlines for compact storage/transmission
|
130 |
-
cleaned_html = html_code.replace("\n", "").replace("\r", "")
|
131 |
-
return {"status": "success", "template": cleaned_html}
|
132 |
-
|
133 |
-
|
134 |
-
def send_test_email(recipient: str, html_body: str) -> dict:
|
135 |
-
"""Simulates sending a test phishing email to a specified recipient."""
|
136 |
-
print(f"INFO: Test email sent to {recipient}")
|
137 |
-
return {"status": "success", "data": {"recipient": recipient}, "message": f"Test email sent to {recipient}."}
|
138 |
-
|
139 |
-
|
140 |
-
def get_or_create_employee_list(action: str, employee_data: list = None) -> dict:
|
141 |
-
"""Simulates managing employee lists (create, add, use_existing)."""
|
142 |
-
message = f"Action '{action}' on employee list was successful."
|
143 |
-
return {"status": "success", "data": {"action": action}, "message": message}
|
144 |
-
|
145 |
-
|
146 |
-
def select_target_group(group_type: str, values: list = None) -> dict:
|
147 |
-
"""
|
148 |
-
Selects the target group (all, department, individual). Includes error checking
|
149 |
-
to ensure 'values' are provided when necessary.
|
150 |
-
"""
|
151 |
-
if group_type == "all":
|
152 |
-
message = "The campaign will target all employees."
|
153 |
-
elif group_type == "department" and values:
|
154 |
-
message = f"Targeting departments: {', '.join(values)}."
|
155 |
-
elif group_type == "individual" and values:
|
156 |
-
message = f"Targeting individuals: {', '.join(values)}."
|
157 |
-
else:
|
158 |
-
# Handle cases where 'values' are missing or the group_type is unknown.
|
159 |
-
message = f"Error: Invalid selection for group type '{group_type}' or missing values."
|
160 |
-
return {"status": "success", "data": {"group_type": group_type, "targets": values}, "message": message}
|
161 |
-
|
162 |
-
|
163 |
-
def schedule_attack(date_time: str) -> dict:
|
164 |
-
"""Simulates scheduling the phishing campaign."""
|
165 |
-
return {"status": "success", "data": {"scheduled_for": date_time},
|
166 |
-
"message": f"Campaign scheduled for {date_time}."}
|
167 |
-
|
168 |
-
|
169 |
-
# --- 3. Agent and Prompt Configuration ---
|
170 |
-
|
171 |
-
# Assemble all functions into a list of StructuredTools for the agent
|
172 |
-
tools = [
|
173 |
-
StructuredTool.from_function(func=generate_image, name="GenerateImage",
|
174 |
-
description="Generates an image from a prompt and returns its local file path."),
|
175 |
-
StructuredTool.from_function(func=get_company_info, name="GetCompanyInfo",
|
176 |
-
description="Retrieves company information (including logoUrl and departments)."),
|
177 |
-
StructuredTool.from_function(func=get_user_info, name="GetUserInfo",
|
178 |
-
description="Retrieves the current user's information (including email)."),
|
179 |
-
StructuredTool.from_function(func=create_html_template, name="CreateHtmlTemplate",
|
180 |
-
description="Finalizes the phishing email's HTML code."),
|
181 |
-
StructuredTool.from_function(func=send_test_email, name="SendTestEmail",
|
182 |
-
description="Sends a test phishing email for review."),
|
183 |
-
StructuredTool.from_function(func=get_or_create_employee_list, name="ManageEmployeeList",
|
184 |
-
description="Manages the employee list for the campaign."),
|
185 |
-
StructuredTool.from_function(func=select_target_group, name="SelectTargetGroup",
|
186 |
-
description="Selects the target group for the campaign."),
|
187 |
-
StructuredTool.from_function(func=schedule_attack, name="ScheduleAttack",
|
188 |
-
description="Schedules the phishing campaign.")
|
189 |
-
]
|
190 |
-
|
191 |
-
# Pull a standard agent prompt template from the LangChain hub
|
192 |
-
prompt = hub.pull("hwchase17/openai-tools-agent")
|
193 |
-
|
194 |
-
# Define the master instructions for the AI agent (the "System Prompt")
|
195 |
-
SYSTEM_PROMPT = """
|
196 |
-
You are an AI assistant named Cbulwork, designed to set up phishing simulation campaigns. Your goal is to guide the user step-by-step with precision and clarity. The user has already been greeted, so you should start directly with the process.
|
197 |
-
|
198 |
-
**PROCESS:**
|
199 |
-
|
200 |
-
**Step 1: Gather Context & Suggest Scenario**
|
201 |
-
- Call `GetUserInfo` and `GetCompanyInfo`.
|
202 |
-
- Greet the user by name.
|
203 |
-
- If the user has NOT provided a topic, suggest 5 relevant scenarios based on company info.
|
204 |
-
- Await the user's confirmation of the scenario.
|
205 |
-
|
206 |
-
**Step 2: Choose Template Type**
|
207 |
-
- Ask the user to choose a template type: Text Only, Text + Photo, or Photo Only.
|
208 |
-
- Wait for their selection.
|
209 |
-
|
210 |
-
**Step 3: Template Design**
|
211 |
-
- Write a **highly detailed and convincing**, valid HTML code for the email based on the user's choice.
|
212 |
-
- **IMAGE & LOGO RULES (CRITICAL):**
|
213 |
-
- If 'Text + Photo' or 'Photo Only' was chosen:
|
214 |
-
1. Call `GenerateImage`. The prompt MUST be for a **flyer-style image with simple, bold text** related to the scenario (e.g., "A modern corporate flyer with the text 'Urgent Action Required: Update Your Password'").
|
215 |
-
2. Use the exact `image_path` returned by the tool in the `src` attribute of an `<img>` tag. **You MUST prefix the local path with `file:///` for the preview to work.**
|
216 |
-
- If "Text + Photo" was chosen, also include the `logoUrl` from `GetCompanyInfo` in a separate `<img>` tag.
|
217 |
-
- **CONTENT RULES:**
|
218 |
-
- The email body must have at least two convincing paragraphs.
|
219 |
-
- Generate a professional footer with fake details (address, contact info) for realism.
|
220 |
-
- Generate a compelling subject, personalized greeting ("{{recipient.name}}"), detailed body, footer, and a clear call-to-action.
|
221 |
-
- Do NOT include copyright lines.
|
222 |
-
- After writing the code, you MUST call `CreateHtmlTemplate` with the HTML as a single string.
|
223 |
-
|
224 |
-
**Step 4: Send Test Email**
|
225 |
-
- After approval, ask to send a test email. If yes, use `SendTestEmail` with the user's email.
|
226 |
-
|
227 |
-
**Step 5: Employee List**
|
228 |
-
- Ask for the list provision method (upload/manual). If manual, provide an example format (`Name,Email`). Call `ManageEmployeeList`.
|
229 |
-
|
230 |
-
**Step 6: Target Group Selection**
|
231 |
-
- Ask to target 'all', 'department', or 'individual'.
|
232 |
-
- If not 'all', ask for the specific names/departments (list available departments from `GetCompanyInfo`).
|
233 |
-
- Call `SelectTargetGroup` with the correct `group_type` and `values`.
|
234 |
-
|
235 |
-
**Step 7: Schedule Campaign**
|
236 |
-
- Ask for a future launch date/time (`dd/mm/yyyy` format). Call `ScheduleAttack`.
|
237 |
-
|
238 |
-
**Step 8: Final Summary & Confirmation**
|
239 |
-
- Provide a complete summary. Ask for final confirmation. After confirmation, ask if there is anything else.
|
240 |
-
"""
|
241 |
-
|
242 |
-
# Insert the system prompt into the template
|
243 |
-
prompt.messages[0].prompt.template = SYSTEM_PROMPT
|
244 |
-
|
245 |
-
# Create the agent (LLM + Tools + Prompt)
|
246 |
-
agent = create_openai_tools_agent(llm, tools, prompt)
|
247 |
-
|
248 |
-
# Create the agent executor (the runtime for the agent)
|
249 |
-
agent_executor = AgentExecutor(
|
250 |
-
agent=agent,
|
251 |
-
tools=tools,
|
252 |
-
verbose=True, # Set to True to see the agent's thought process and tool usage in the console
|
253 |
-
handle_parsing_errors=True,
|
254 |
-
max_iterations=15,
|
255 |
-
return_intermediate_steps=True # Required to capture tool output for the UI
|
256 |
-
)
|
257 |
-
|
258 |
-
|
259 |
-
# --- 4. Core Application Logic ---
|
260 |
-
|
261 |
-
def run_agent_turn(user_input: str, chat_history: list) -> dict:
|
262 |
-
"""
|
263 |
-
Processes one turn of the conversation: sends input to the agent, executes tools,
|
264 |
-
and collects the results (response, HTML, image path, and tool calls).
|
265 |
-
"""
|
266 |
-
# Convert Gradio chat history format to LangChain message format
|
267 |
-
langchain_messages = [
|
268 |
-
HumanMessage(content=msg["content"]) if msg["role"] == "user" else AIMessage(content=msg["content"])
|
269 |
-
for msg in chat_history
|
270 |
-
]
|
271 |
-
|
272 |
-
# Invoke the agent
|
273 |
-
response = agent_executor.invoke({
|
274 |
-
"input": user_input,
|
275 |
-
"chat_history": langchain_messages
|
276 |
-
})
|
277 |
-
|
278 |
-
agent_output = response.get("output", "Sorry, an error occurred.")
|
279 |
-
|
280 |
-
# Initialize variables to capture outputs from the agent's steps
|
281 |
-
html_to_preview = ""
|
282 |
-
generated_image_path = None
|
283 |
-
function_calls = []
|
284 |
-
intermediate_steps = response.get("intermediate_steps", [])
|
285 |
-
|
286 |
-
# Process the steps the agent took
|
287 |
-
for action, tool_output in intermediate_steps:
|
288 |
-
# Log the tool call for the JSON output box
|
289 |
-
function_calls.append({
|
290 |
-
"tool_name": action.tool,
|
291 |
-
"tool_args": action.tool_input,
|
292 |
-
"tool_output": tool_output,
|
293 |
-
})
|
294 |
-
# Capture the HTML output if the CreateHtmlTemplate tool was used
|
295 |
-
if action.tool == "CreateHtmlTemplate" and isinstance(tool_output, dict):
|
296 |
-
html_to_preview = tool_output.get("template", "")
|
297 |
-
# Capture the image path if the GenerateImage tool was used successfully
|
298 |
-
if action.tool == "GenerateImage" and tool_output.get("status") == "success":
|
299 |
-
generated_image_path = tool_output.get("image_path")
|
300 |
-
|
301 |
-
# Update the chat history
|
302 |
-
updated_chat_history = chat_history + [
|
303 |
-
{"role": "user", "content": user_input},
|
304 |
-
{"role": "assistant", "content": agent_output}
|
305 |
-
]
|
306 |
-
|
307 |
-
# Return a structured dictionary with all results
|
308 |
-
return {
|
309 |
-
"agent_response": agent_output,
|
310 |
-
"html_preview": html_to_preview,
|
311 |
-
"function_calls": function_calls,
|
312 |
-
"updated_chat_history": updated_chat_history,
|
313 |
-
"generated_image_preview": generated_image_path
|
314 |
-
}
|
315 |
-
|
316 |
-
|
317 |
-
def process_input_for_gradio(user_input: str, chat_history: list) -> tuple:
|
318 |
-
"""
|
319 |
-
Event handler for the Gradio UI. Calls the core agent logic and returns
|
320 |
-
the outputs in the order expected by the Gradio outputs list.
|
321 |
-
"""
|
322 |
-
if not user_input.strip():
|
323 |
-
# Don't process empty input
|
324 |
-
return chat_history, "", None, None
|
325 |
-
|
326 |
-
# Run the agent turn
|
327 |
-
json_output = run_agent_turn(user_input, chat_history)
|
328 |
-
|
329 |
-
# Optional: Print the backend output to the console for debugging
|
330 |
-
print(f"--- Backend JSON Output ---\n{json.dumps(json_output, indent=2)}\n--------------------------")
|
331 |
-
|
332 |
-
# Return the data in the order of the Gradio outputs=[...] list
|
333 |
-
return (
|
334 |
-
json_output["updated_chat_history"],
|
335 |
-
json_output["html_preview"],
|
336 |
-
json_output["function_calls"],
|
337 |
-
json_output["generated_image_preview"]
|
338 |
-
)
|
339 |
-
|
340 |
-
|
341 |
-
# --- 5. Gradio User Interface Definition ---
|
342 |
-
|
343 |
-
# Define the UI layout using Gradio Blocks
|
344 |
-
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="sky")) as demo:
|
345 |
-
gr.Markdown("## Phishing Campaign Setup Assistant")
|
346 |
-
gr.Markdown("I will guide you step-by-step to create and schedule a new phishing campaign.")
|
347 |
-
|
348 |
-
with gr.Row():
|
349 |
-
# Left Column: Chat Interface
|
350 |
-
with gr.Column(scale=1):
|
351 |
-
welcome_message = "Hello, I'm your AI phishing assistant. Send a message to get started."
|
352 |
-
chatbot = gr.Chatbot(
|
353 |
-
value=[{"role": "assistant", "content": welcome_message}],
|
354 |
-
label="Conversation",
|
355 |
-
height=600,
|
356 |
-
type="messages" # Ensures we use the modern {'role': '...', 'content': '...'} format
|
357 |
-
)
|
358 |
-
user_input = gr.Textbox(
|
359 |
-
placeholder="Send a message to continue...",
|
360 |
-
label="Your Message",
|
361 |
-
scale=12
|
362 |
-
)
|
363 |
-
# Right Column: Previews and Debugging
|
364 |
-
with gr.Column(scale=1):
|
365 |
-
gr.Markdown("### Email Template Preview")
|
366 |
-
html_block = gr.HTML(label="HTML Preview")
|
367 |
-
|
368 |
-
gr.Markdown("### Generated Image Preview")
|
369 |
-
# Added an Image component to display the generated flyer/image
|
370 |
-
image_preview_box = gr.Image(label="Image Preview", interactive=False)
|
371 |
-
|
372 |
-
gr.Markdown("### Function Call Output (Debugging)")
|
373 |
-
json_requests_box = gr.JSON(label="Function 'Requests' Output")
|
374 |
-
|
375 |
-
# Connect the user input submission to the event handler
|
376 |
-
user_input.submit(
|
377 |
-
fn=process_input_for_gradio,
|
378 |
-
inputs=[user_input, chatbot],
|
379 |
-
# Ensure outputs match the return tuple of process_input_for_gradio
|
380 |
-
outputs=[chatbot, html_block, json_requests_box, image_preview_box]
|
381 |
-
)
|
382 |
-
# Clear the input box after submission
|
383 |
-
user_input.submit(lambda: "", None, user_input)
|
384 |
-
|
385 |
-
# --- 6. Application Launch ---
|
386 |
-
|
387 |
-
if __name__ == "__main__":
|
388 |
-
# Launch the Gradio web server
|
389 |
-
print("Launching Phishing Campaign Setup Assistant UI...")
|
390 |
-
demo.launch(debug=
|
|
|
1 |
+
# =============================================================================
|
2 |
+
# Phishing Campaign Setup Assistant
|
3 |
+
# =============================================================================
|
4 |
+
# Description: A Gradio-based chatbot application using LangChain and OpenAI
|
5 |
+
# to guide users through setting up a phishing simulation campaign step-by-step.
|
6 |
+
#
|
7 |
+
# Requirements:
|
8 |
+
# - Python 3.x
|
9 |
+
# - Libraries: langchain, langchain_openai, langchain_community, gradio,
|
10 |
+
# python-dotenv, google-generativeai
|
11 |
+
# - Environment Variables (.env file):
|
12 |
+
# - OPENAI_API_KEY
|
13 |
+
# - GOOGLE_API_KEY
|
14 |
+
# - Data Files (in the same directory):
|
15 |
+
# - company_info.json
|
16 |
+
# - user_info.json
|
17 |
+
# =============================================================================
|
18 |
+
|
19 |
+
# --- 0. Required Imports ---
|
20 |
+
# Standard library imports
|
21 |
+
import os
|
22 |
+
import datetime
|
23 |
+
import json
|
24 |
+
import re
|
25 |
+
import base64
|
26 |
+
import tempfile
|
27 |
+
|
28 |
+
# Third-party imports for AI & LLMs
|
29 |
+
from dotenv import load_dotenv
|
30 |
+
from openai import OpenAI
|
31 |
+
from google import genai as google_genai
|
32 |
+
from google.genai import types as google_genai_types
|
33 |
+
from langchain.agents import create_openai_tools_agent, AgentExecutor
|
34 |
+
from langchain_openai import ChatOpenAI
|
35 |
+
from langchain_core.tools import StructuredTool
|
36 |
+
from langchain_core.messages import HumanMessage, AIMessage
|
37 |
+
from langchain import hub
|
38 |
+
from langchain_community.tools import DuckDuckGoSearchRun
|
39 |
+
|
40 |
+
# Third-party import for Web UI
|
41 |
+
import gradio as gr
|
42 |
+
|
43 |
+
# --- 1. Configuration and Initialization ---
|
44 |
+
|
45 |
+
# Load environment variables from a .env file
|
46 |
+
load_dotenv()
|
47 |
+
|
48 |
+
# Initialize the OpenAI client for the LangChain agent
|
49 |
+
# We use a low temperature (0.0) for predictable, task-oriented behavior.
|
50 |
+
llm = ChatOpenAI(model="gpt-4o", temperature=0.0)
|
51 |
+
client = OpenAI(api_key=os.getenv("OPENAI_API_KEY"))
|
52 |
+
|
53 |
+
# Initialize the Google GenAI Client for the image generation tool
|
54 |
+
# google_genai.configure(api_key=os.getenv("GOOGLE_API_KEY"))
|
55 |
+
genai_client = google_genai.Client(api_key=os.getenv("GOOGLE_API_KEY"))
|
56 |
+
|
57 |
+
|
58 |
+
# --- 2. Tool Definitions ---
|
59 |
+
# These functions define the actions (tools) the AI agent can perform.
|
60 |
+
|
61 |
+
def generate_image(prompt: str) -> dict:
|
62 |
+
"""
|
63 |
+
Generates an image based on a text prompt, saves it to 'generated_phishing_image.png'
|
64 |
+
in the current directory (overwriting previous images), and returns the absolute file path.
|
65 |
+
"""
|
66 |
+
# Fixed filename ensures replacement on subsequent generations.
|
67 |
+
output_filename = "generated_phishing_image.png"
|
68 |
+
|
69 |
+
print(f"INFO: Generating image with prompt: '{prompt}'")
|
70 |
+
try:
|
71 |
+
output = genai_client.models.generate_images(
|
72 |
+
prompt=prompt,
|
73 |
+
model="imagen-4.0-generate-preview-06-06",
|
74 |
+
config=google_genai_types.GenerateImagesConfig(
|
75 |
+
number_of_images=1,
|
76 |
+
aspect_ratio="16:9",
|
77 |
+
),
|
78 |
+
)
|
79 |
+
generated_img = output.generated_images[0].image
|
80 |
+
|
81 |
+
# Save the image to the fixed path in the current directory.
|
82 |
+
generated_img.save(output_filename)
|
83 |
+
|
84 |
+
# Get the absolute path for reliable referencing in the HTML.
|
85 |
+
absolute_image_path = os.path.abspath(output_filename)
|
86 |
+
|
87 |
+
print(f"INFO: Image saved to: {absolute_image_path}")
|
88 |
+
return {"status": "success", "image_path": absolute_image_path}
|
89 |
+
except Exception as e:
|
90 |
+
print(f"ERROR: Image generation failed: {e}")
|
91 |
+
return {"status": "error", "message": f"Image generation failed: {e}"}
|
92 |
+
|
93 |
+
|
94 |
+
def get_company_info() -> dict:
|
95 |
+
"""
|
96 |
+
Retrieves company information (name, logoUrl, departments, etc.) from company_info.json.
|
97 |
+
"""
|
98 |
+
print("INFO: Reading company_info.json")
|
99 |
+
try:
|
100 |
+
with open('company_info.json', 'r') as f:
|
101 |
+
data = json.load(f)
|
102 |
+
return {"status": "success", "data": data}
|
103 |
+
except FileNotFoundError:
|
104 |
+
return {"status": "error", "message": "company_info.json not found."}
|
105 |
+
except json.JSONDecodeError:
|
106 |
+
return {"status": "error", "message": "Error decoding company_info.json."}
|
107 |
+
|
108 |
+
|
109 |
+
def get_user_info() -> dict:
|
110 |
+
"""
|
111 |
+
Retrieves the current user's information (name, role, email) from user_info.json.
|
112 |
+
"""
|
113 |
+
print("INFO: Reading user_info.json")
|
114 |
+
try:
|
115 |
+
with open('user_info.json', 'r') as f:
|
116 |
+
data = json.load(f)
|
117 |
+
return {"status": "success", "data": data}
|
118 |
+
except FileNotFoundError:
|
119 |
+
return {"status": "error", "message": "user_info.json not found."}
|
120 |
+
except json.JSONDecodeError:
|
121 |
+
return {"status": "error", "message": "Error decoding user_info.json."}
|
122 |
+
|
123 |
+
|
124 |
+
def create_html_template(html_code: str) -> dict:
|
125 |
+
"""
|
126 |
+
Takes a complete HTML string, cleans it (removes newlines), and prepares it for preview.
|
127 |
+
"""
|
128 |
+
print("INFO: Formalizing agent-generated HTML template.")
|
129 |
+
# Clean HTML by removing newlines for compact storage/transmission
|
130 |
+
cleaned_html = html_code.replace("\n", "").replace("\r", "")
|
131 |
+
return {"status": "success", "template": cleaned_html}
|
132 |
+
|
133 |
+
|
134 |
+
def send_test_email(recipient: str, html_body: str) -> dict:
|
135 |
+
"""Simulates sending a test phishing email to a specified recipient."""
|
136 |
+
print(f"INFO: Test email sent to {recipient}")
|
137 |
+
return {"status": "success", "data": {"recipient": recipient}, "message": f"Test email sent to {recipient}."}
|
138 |
+
|
139 |
+
|
140 |
+
def get_or_create_employee_list(action: str, employee_data: list = None) -> dict:
|
141 |
+
"""Simulates managing employee lists (create, add, use_existing)."""
|
142 |
+
message = f"Action '{action}' on employee list was successful."
|
143 |
+
return {"status": "success", "data": {"action": action}, "message": message}
|
144 |
+
|
145 |
+
|
146 |
+
def select_target_group(group_type: str, values: list = None) -> dict:
|
147 |
+
"""
|
148 |
+
Selects the target group (all, department, individual). Includes error checking
|
149 |
+
to ensure 'values' are provided when necessary.
|
150 |
+
"""
|
151 |
+
if group_type == "all":
|
152 |
+
message = "The campaign will target all employees."
|
153 |
+
elif group_type == "department" and values:
|
154 |
+
message = f"Targeting departments: {', '.join(values)}."
|
155 |
+
elif group_type == "individual" and values:
|
156 |
+
message = f"Targeting individuals: {', '.join(values)}."
|
157 |
+
else:
|
158 |
+
# Handle cases where 'values' are missing or the group_type is unknown.
|
159 |
+
message = f"Error: Invalid selection for group type '{group_type}' or missing values."
|
160 |
+
return {"status": "success", "data": {"group_type": group_type, "targets": values}, "message": message}
|
161 |
+
|
162 |
+
|
163 |
+
def schedule_attack(date_time: str) -> dict:
|
164 |
+
"""Simulates scheduling the phishing campaign."""
|
165 |
+
return {"status": "success", "data": {"scheduled_for": date_time},
|
166 |
+
"message": f"Campaign scheduled for {date_time}."}
|
167 |
+
|
168 |
+
|
169 |
+
# --- 3. Agent and Prompt Configuration ---
|
170 |
+
|
171 |
+
# Assemble all functions into a list of StructuredTools for the agent
|
172 |
+
tools = [
|
173 |
+
StructuredTool.from_function(func=generate_image, name="GenerateImage",
|
174 |
+
description="Generates an image from a prompt and returns its local file path."),
|
175 |
+
StructuredTool.from_function(func=get_company_info, name="GetCompanyInfo",
|
176 |
+
description="Retrieves company information (including logoUrl and departments)."),
|
177 |
+
StructuredTool.from_function(func=get_user_info, name="GetUserInfo",
|
178 |
+
description="Retrieves the current user's information (including email)."),
|
179 |
+
StructuredTool.from_function(func=create_html_template, name="CreateHtmlTemplate",
|
180 |
+
description="Finalizes the phishing email's HTML code."),
|
181 |
+
StructuredTool.from_function(func=send_test_email, name="SendTestEmail",
|
182 |
+
description="Sends a test phishing email for review."),
|
183 |
+
StructuredTool.from_function(func=get_or_create_employee_list, name="ManageEmployeeList",
|
184 |
+
description="Manages the employee list for the campaign."),
|
185 |
+
StructuredTool.from_function(func=select_target_group, name="SelectTargetGroup",
|
186 |
+
description="Selects the target group for the campaign."),
|
187 |
+
StructuredTool.from_function(func=schedule_attack, name="ScheduleAttack",
|
188 |
+
description="Schedules the phishing campaign.")
|
189 |
+
]
|
190 |
+
|
191 |
+
# Pull a standard agent prompt template from the LangChain hub
|
192 |
+
prompt = hub.pull("hwchase17/openai-tools-agent")
|
193 |
+
|
194 |
+
# Define the master instructions for the AI agent (the "System Prompt")
|
195 |
+
SYSTEM_PROMPT = """
|
196 |
+
You are an AI assistant named Cbulwork, designed to set up phishing simulation campaigns. Your goal is to guide the user step-by-step with precision and clarity. The user has already been greeted, so you should start directly with the process.
|
197 |
+
|
198 |
+
**PROCESS:**
|
199 |
+
|
200 |
+
**Step 1: Gather Context & Suggest Scenario**
|
201 |
+
- Call `GetUserInfo` and `GetCompanyInfo`.
|
202 |
+
- Greet the user by name.
|
203 |
+
- If the user has NOT provided a topic, suggest 5 relevant scenarios based on company info.
|
204 |
+
- Await the user's confirmation of the scenario.
|
205 |
+
|
206 |
+
**Step 2: Choose Template Type**
|
207 |
+
- Ask the user to choose a template type: Text Only, Text + Photo, or Photo Only.
|
208 |
+
- Wait for their selection.
|
209 |
+
|
210 |
+
**Step 3: Template Design**
|
211 |
+
- Write a **highly detailed and convincing**, valid HTML code for the email based on the user's choice.
|
212 |
+
- **IMAGE & LOGO RULES (CRITICAL):**
|
213 |
+
- If 'Text + Photo' or 'Photo Only' was chosen:
|
214 |
+
1. Call `GenerateImage`. The prompt MUST be for a **flyer-style image with simple, bold text** related to the scenario (e.g., "A modern corporate flyer with the text 'Urgent Action Required: Update Your Password'").
|
215 |
+
2. Use the exact `image_path` returned by the tool in the `src` attribute of an `<img>` tag. **You MUST prefix the local path with `file:///` for the preview to work.**
|
216 |
+
- If "Text + Photo" was chosen, also include the `logoUrl` from `GetCompanyInfo` in a separate `<img>` tag.
|
217 |
+
- **CONTENT RULES:**
|
218 |
+
- The email body must have at least two convincing paragraphs.
|
219 |
+
- Generate a professional footer with fake details (address, contact info) for realism.
|
220 |
+
- Generate a compelling subject, personalized greeting ("{{recipient.name}}"), detailed body, footer, and a clear call-to-action.
|
221 |
+
- Do NOT include copyright lines.
|
222 |
+
- After writing the code, you MUST call `CreateHtmlTemplate` with the HTML as a single string.
|
223 |
+
|
224 |
+
**Step 4: Send Test Email**
|
225 |
+
- After approval, ask to send a test email. If yes, use `SendTestEmail` with the user's email.
|
226 |
+
|
227 |
+
**Step 5: Employee List**
|
228 |
+
- Ask for the list provision method (upload/manual). If manual, provide an example format (`Name,Email`). Call `ManageEmployeeList`.
|
229 |
+
|
230 |
+
**Step 6: Target Group Selection**
|
231 |
+
- Ask to target 'all', 'department', or 'individual'.
|
232 |
+
- If not 'all', ask for the specific names/departments (list available departments from `GetCompanyInfo`).
|
233 |
+
- Call `SelectTargetGroup` with the correct `group_type` and `values`.
|
234 |
+
|
235 |
+
**Step 7: Schedule Campaign**
|
236 |
+
- Ask for a future launch date/time (`dd/mm/yyyy` format). Call `ScheduleAttack`.
|
237 |
+
|
238 |
+
**Step 8: Final Summary & Confirmation**
|
239 |
+
- Provide a complete summary. Ask for final confirmation. After confirmation, ask if there is anything else.
|
240 |
+
"""
|
241 |
+
|
242 |
+
# Insert the system prompt into the template
|
243 |
+
prompt.messages[0].prompt.template = SYSTEM_PROMPT
|
244 |
+
|
245 |
+
# Create the agent (LLM + Tools + Prompt)
|
246 |
+
agent = create_openai_tools_agent(llm, tools, prompt)
|
247 |
+
|
248 |
+
# Create the agent executor (the runtime for the agent)
|
249 |
+
agent_executor = AgentExecutor(
|
250 |
+
agent=agent,
|
251 |
+
tools=tools,
|
252 |
+
verbose=True, # Set to True to see the agent's thought process and tool usage in the console
|
253 |
+
handle_parsing_errors=True,
|
254 |
+
max_iterations=15,
|
255 |
+
return_intermediate_steps=True # Required to capture tool output for the UI
|
256 |
+
)
|
257 |
+
|
258 |
+
|
259 |
+
# --- 4. Core Application Logic ---
|
260 |
+
|
261 |
+
def run_agent_turn(user_input: str, chat_history: list) -> dict:
|
262 |
+
"""
|
263 |
+
Processes one turn of the conversation: sends input to the agent, executes tools,
|
264 |
+
and collects the results (response, HTML, image path, and tool calls).
|
265 |
+
"""
|
266 |
+
# Convert Gradio chat history format to LangChain message format
|
267 |
+
langchain_messages = [
|
268 |
+
HumanMessage(content=msg["content"]) if msg["role"] == "user" else AIMessage(content=msg["content"])
|
269 |
+
for msg in chat_history
|
270 |
+
]
|
271 |
+
|
272 |
+
# Invoke the agent
|
273 |
+
response = agent_executor.invoke({
|
274 |
+
"input": user_input,
|
275 |
+
"chat_history": langchain_messages
|
276 |
+
})
|
277 |
+
|
278 |
+
agent_output = response.get("output", "Sorry, an error occurred.")
|
279 |
+
|
280 |
+
# Initialize variables to capture outputs from the agent's steps
|
281 |
+
html_to_preview = ""
|
282 |
+
generated_image_path = None
|
283 |
+
function_calls = []
|
284 |
+
intermediate_steps = response.get("intermediate_steps", [])
|
285 |
+
|
286 |
+
# Process the steps the agent took
|
287 |
+
for action, tool_output in intermediate_steps:
|
288 |
+
# Log the tool call for the JSON output box
|
289 |
+
function_calls.append({
|
290 |
+
"tool_name": action.tool,
|
291 |
+
"tool_args": action.tool_input,
|
292 |
+
"tool_output": tool_output,
|
293 |
+
})
|
294 |
+
# Capture the HTML output if the CreateHtmlTemplate tool was used
|
295 |
+
if action.tool == "CreateHtmlTemplate" and isinstance(tool_output, dict):
|
296 |
+
html_to_preview = tool_output.get("template", "")
|
297 |
+
# Capture the image path if the GenerateImage tool was used successfully
|
298 |
+
if action.tool == "GenerateImage" and tool_output.get("status") == "success":
|
299 |
+
generated_image_path = tool_output.get("image_path")
|
300 |
+
|
301 |
+
# Update the chat history
|
302 |
+
updated_chat_history = chat_history + [
|
303 |
+
{"role": "user", "content": user_input},
|
304 |
+
{"role": "assistant", "content": agent_output}
|
305 |
+
]
|
306 |
+
|
307 |
+
# Return a structured dictionary with all results
|
308 |
+
return {
|
309 |
+
"agent_response": agent_output,
|
310 |
+
"html_preview": html_to_preview,
|
311 |
+
"function_calls": function_calls,
|
312 |
+
"updated_chat_history": updated_chat_history,
|
313 |
+
"generated_image_preview": generated_image_path
|
314 |
+
}
|
315 |
+
|
316 |
+
|
317 |
+
def process_input_for_gradio(user_input: str, chat_history: list) -> tuple:
|
318 |
+
"""
|
319 |
+
Event handler for the Gradio UI. Calls the core agent logic and returns
|
320 |
+
the outputs in the order expected by the Gradio outputs list.
|
321 |
+
"""
|
322 |
+
if not user_input.strip():
|
323 |
+
# Don't process empty input
|
324 |
+
return chat_history, "", None, None
|
325 |
+
|
326 |
+
# Run the agent turn
|
327 |
+
json_output = run_agent_turn(user_input, chat_history)
|
328 |
+
|
329 |
+
# Optional: Print the backend output to the console for debugging
|
330 |
+
print(f"--- Backend JSON Output ---\n{json.dumps(json_output, indent=2)}\n--------------------------")
|
331 |
+
|
332 |
+
# Return the data in the order of the Gradio outputs=[...] list
|
333 |
+
return (
|
334 |
+
json_output["updated_chat_history"],
|
335 |
+
json_output["html_preview"],
|
336 |
+
json_output["function_calls"],
|
337 |
+
json_output["generated_image_preview"]
|
338 |
+
)
|
339 |
+
|
340 |
+
|
341 |
+
# --- 5. Gradio User Interface Definition ---
|
342 |
+
|
343 |
+
# Define the UI layout using Gradio Blocks
|
344 |
+
with gr.Blocks(theme=gr.themes.Default(primary_hue="blue", secondary_hue="sky")) as demo:
|
345 |
+
gr.Markdown("## Phishing Campaign Setup Assistant")
|
346 |
+
gr.Markdown("I will guide you step-by-step to create and schedule a new phishing campaign.")
|
347 |
+
|
348 |
+
with gr.Row():
|
349 |
+
# Left Column: Chat Interface
|
350 |
+
with gr.Column(scale=1):
|
351 |
+
welcome_message = "Hello, I'm your AI phishing assistant. Send a message to get started."
|
352 |
+
chatbot = gr.Chatbot(
|
353 |
+
value=[{"role": "assistant", "content": welcome_message}],
|
354 |
+
label="Conversation",
|
355 |
+
height=600,
|
356 |
+
type="messages" # Ensures we use the modern {'role': '...', 'content': '...'} format
|
357 |
+
)
|
358 |
+
user_input = gr.Textbox(
|
359 |
+
placeholder="Send a message to continue...",
|
360 |
+
label="Your Message",
|
361 |
+
scale=12
|
362 |
+
)
|
363 |
+
# Right Column: Previews and Debugging
|
364 |
+
with gr.Column(scale=1):
|
365 |
+
gr.Markdown("### Email Template Preview")
|
366 |
+
html_block = gr.HTML(label="HTML Preview")
|
367 |
+
|
368 |
+
gr.Markdown("### Generated Image Preview")
|
369 |
+
# Added an Image component to display the generated flyer/image
|
370 |
+
image_preview_box = gr.Image(label="Image Preview", interactive=False)
|
371 |
+
|
372 |
+
gr.Markdown("### Function Call Output (Debugging)")
|
373 |
+
json_requests_box = gr.JSON(label="Function 'Requests' Output")
|
374 |
+
|
375 |
+
# Connect the user input submission to the event handler
|
376 |
+
user_input.submit(
|
377 |
+
fn=process_input_for_gradio,
|
378 |
+
inputs=[user_input, chatbot],
|
379 |
+
# Ensure outputs match the return tuple of process_input_for_gradio
|
380 |
+
outputs=[chatbot, html_block, json_requests_box, image_preview_box]
|
381 |
+
)
|
382 |
+
# Clear the input box after submission
|
383 |
+
user_input.submit(lambda: "", None, user_input)
|
384 |
+
|
385 |
+
# --- 6. Application Launch ---
|
386 |
+
|
387 |
+
if __name__ == "__main__":
|
388 |
+
# Launch the Gradio web server
|
389 |
+
print("Launching Phishing Campaign Setup Assistant UI...")
|
390 |
+
demo.launch(debug=False)
|