Spaces:
Running
Running
File size: 10,272 Bytes
34d1b87 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 |
import os
from dotenv import load_dotenv
import requests
from bs4 import BeautifulSoup
import whois
from openai import OpenAI
import gradio as gr
from playwright.sync_api import sync_playwright
import time
import json
load_dotenv()
class PhishingToolkit:
"""toolkit sınıfı"""
def __init__(self, api_key=None, model="gpt-4o"):
# API anahtarı ve model bilgisini sakla
self.api_key = api_key or os.getenv('OPENAI_API_KEY')
self.model = model
# OpenAI istemcisini oluştur
self.client = OpenAI(api_key=self.api_key) if self.api_key else None
def fetch_content(self, url):
"""Verilen URL'nin içeriğini döndürür."""
try:
headers = {
'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
}
response = requests.get(url, headers=headers, timeout=10)
response.raise_for_status() # HTTP hatalarını kontrol et
soup = BeautifulSoup(response.text, "html.parser")
# Sadece görünür metin içeriğini al
for script in soup(["script", "style"]):
script.decompose()
text = soup.get_text(separator=' ', strip=True)
# İçeriği makul bir uzunlukta tut
return text[:5000] + "..." if len(text) > 5000 else text
except requests.exceptions.RequestException as e:
return f"URL erişim hatası: {e}"
except Exception as e:
return f"İçerik çekme hatası: {e}"
def capture_screenshot(self, url):
"""Verilen URL'nin ekran görüntüsünü alır."""
try:
# Temiz bir dosya adı oluştur
domain = url.split("//")[-1].split("/")[0]
timestamp = int(time.time())
filename = f"{domain.replace('.', '_')}_{timestamp}.png"
screenshot_path = os.path.join("screenshots", filename)
# Klasörün var olduğundan emin ol
os.makedirs("screenshots", exist_ok=True)
with sync_playwright() as p:
browser = p.chromium.launch()
page = browser.new_page()
page.goto(url, wait_until="networkidle", timeout=30000)
page.screenshot(path=screenshot_path)
browser.close()
return screenshot_path
except Exception as e:
print(f"Ekran görüntüsü hatası: {e}")
return None
def get_whois_info(self, url):
"""Verilen URL'nin WHOIS bilgilerini alır."""
try:
# URL'den domain adını çıkar
domain = url.split("//")[-1].split("/")[0]
w = whois.whois(domain)
# WHOIS verilerini düzenle
whois_info = {
"Domain Adı": w.domain_name,
"Kayıt Tarihi": w.creation_date,
"Son Kullanma Tarihi": w.expiration_date,
"Kayıt Eden": w.registrar,
"WHOIS Sunucusu": w.whois_server,
"Durum": w.status
}
# None değerleri filtrele ve formatla
formatted_info = {}
for key, value in whois_info.items():
if value is not None:
if isinstance(value, list):
formatted_info[key] = str(value[0]) if value else "Bilgi yok"
else:
formatted_info[key] = str(value)
else:
formatted_info[key] = "Bilgi yok"
# Dictionary'yi okunabilir formata çevir
return json.dumps(formatted_info, indent=2, ensure_ascii=False)
except Exception as e:
return f"WHOIS bilgisi alınamadı: {e}"
def analyze_phishing(self, url, content, whois_info):
"""Verilen içerik ve WHOIS bilgileri ile phishing analizi yapar."""
# API anahtarı kontrolü
if not self.api_key:
return "API anahtarı girilmediği için analiz yapılamıyor. Lütfen OpenAI API anahtarınızı girin."
# İçeriği kısalt
content_summary = content[:3000] + "..." if len(content) > 3000 else content
prompt = f"""
Aşağıdaki site için phishing analizi yap:
URL: {url}
İçerik: {content_summary}
WHOIS Bilgileri: {whois_info}
Aşağıdaki kriterlere göre değerlendir:
1. Domain adının yaşı ve güvenilirliği
2. SSL sertifikası varlığı ("https" kullanımı)
3. URL yapısındaki şüpheli karakterler veya yönlendirmeler
4. İçerikte bulunan şüpheli formlar, giriş alanları
5. İçerikteki dil ve yazım hataları
6. Profesyonel görünüm eksikliği
7. WHOIS bilgilerinin gizliliği veya şüpheli durumu
Analizini şu formatta döndür:
Risk Seviyesi: [Düşük/Orta/Yüksek]
Tespitler: [Kısa ve net maddeler halinde]
Sonuç: [Phishing olup olmadığı hakkında nihai karar]
"""
try:
response = self.client.chat.completions.create(
model=self.model,
messages=[{"role": "user", "content": prompt}],
temperature=0.5,
max_tokens=800
)
return response.choices[0].message.content
except Exception as e:
return f"AI analiz hatası: {e}"
def analyze_url(url, api_key, model):
"""URL'yi analiz edip sonuçları döndürür"""
if not url or url.strip() == "":
return "Lütfen bir URL girin.", None, "URL girin.", "URL girin."
if not url.startswith(('http://', 'https://')):
url = 'https://' + url
try:
# API anahtarı kontrolü
if not api_key or api_key.strip() == "":
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
return ("API anahtarı eksik. Lütfen ayarlar bölümünden OpenAI API anahtarınızı girin veya .env dosyasına ekleyin.",
None, "API anahtarı eksik.", "API anahtarı eksik.")
# Toolkit oluştur
toolkit = PhishingToolkit(api_key=api_key, model=model)
# Adım 1: İçerik çek
content = toolkit.fetch_content(url)
# Adım 2: WHOIS bilgisi al
whois_info = toolkit.get_whois_info(url)
# Adım 3: Ekran görüntüsü al
screenshot_path = toolkit.capture_screenshot(url)
# Adım 4: Phishing analizi yap
analysis = toolkit.analyze_phishing(url, content, whois_info)
return content, screenshot_path, whois_info, analysis
except Exception as e:
error_message = f"Analiz sırasında hata oluştu: {str(e)}"
return error_message, None, error_message, error_message
# Gradio arayüzü oluştur
def create_interface():
with gr.Blocks(title="Gelişmiş Phishing Tespit Sistemi") as iface:
gr.Markdown("## 🛡️ Gelişmiş Phishing Tespit Sistemi")
gr.Markdown("Bir URL girerek phishing analizi yapın. Sistem web sitesinin içeriğini, ekran görüntüsünü ve alan adı bilgilerini analiz ederek phishing olasılığını değerlendirir.")
# Ayarlar sekmesi
with gr.Accordion("⚙️ AI Ayarları", open=False):
with gr.Row():
api_key = gr.Textbox(
label="OpenAI API Anahtarı",
placeholder="sk-...",
type="password",
value=os.getenv('OPENAI_API_KEY', ""),
info="API anahtarınızı girin (varsa .env dosyasından yüklenir)"
)
model = gr.Dropdown(
label="Model Seçimi",
choices=["gpt-4o", "gpt-3.5-turbo", "gpt-4", "gpt-4-turbo"],
value="gpt-4o",
info="Kullanılacak OpenAI modelini seçin"
)
with gr.Row():
url_input = gr.Textbox(
label="URL (örn: example.com veya https://example.com)",
placeholder="example.com"
)
analyze_button = gr.Button("🔍 Analiz Et", variant="primary")
with gr.Row():
with gr.Column(scale=1):
gr.Markdown("### 🖼️ Site Görünümü")
screenshot_output = gr.Image(label="Ekran Görüntüsü", type="filepath")
gr.Markdown("### 📋 WHOIS Bilgileri")
whois_output = gr.Textbox(label="", lines=10)
with gr.Column(scale=1):
gr.Markdown("### 🔒 Güvenlik Analizi")
analysis_output = gr.Textbox(label="", lines=15)
gr.Markdown("### 📄 Site İçeriği")
content_output = gr.Textbox(
label="",
lines=10,
max_lines=20,
show_copy_button=True
)
# Analiz fonksiyonunu bağla
analyze_button.click(
fn=analyze_url,
inputs=[url_input, api_key, model],
outputs=[content_output, screenshot_output, whois_output, analysis_output]
)
# Örnek URL'ler
gr.Examples(
examples=["google.com", "amazon.com", "facebook.com"],
inputs=url_input
)
gr.Markdown("---")
gr.Markdown("### ℹ️ Nasıl Kullanılır")
gr.Markdown("""
1. '⚙️ AI Ayarları' bölümünden OpenAI API anahtarınızı girin ve istediğiniz modeli seçin
2. Analiz etmek istediğiniz web sitesinin URL'sini girin
3. 'Analiz Et' butonuna tıklayın
4. Sistem web sitesinin ekran görüntüsünü, WHOIS bilgilerini ve içerik analizini gösterecektir
5. Phishing analizi sonucunu değerlendirin
""")
return iface
if __name__ == "__main__":
# Uygulama başlatılmadan önce klasör kontrolü
os.makedirs("screenshots", exist_ok=True)
# Arayüzü oluştur ve başlat
iface = create_interface()
iface.launch() |