Spaces:
Paused
Paused
Upload 3 files
Browse files- cred.json +13 -0
- external_knowledge_service.py +409 -0
- knowledge_base.json +49 -0
cred.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"type": "service_account",
|
| 3 |
+
"project_id": "citadel4travels",
|
| 4 |
+
"private_key_id": "21448d98eecc8d76e37245f2d81384dbb19035fd",
|
| 5 |
+
"private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCmPDARBZvmkPQe\nmsuC7M1cnuQLGD4nuNWLCrcMUBGJ1pHTdXJiyw5xSCahecAQSvYsiO3qckEob35P\nBGdFEh+JZzMuoicxBp9TEaD+v+uFphteTqAZm3kZv66V2qAM34uLT6bCSXI21YL6\nyNeKUoNqyWxMM6KEbRnJ+tYyTgo6fmjy+mfhfjndwjRqlIZgPN0n7uJlmaJtONZT\nu8pVYn5bfffwMPZFQz3ZwJ/d95MGMUEUCXlDKRqCf7la8/Z9aRkmyeaW87MUw/sS\nN/jDgSrlLBdCYI5usVfuiWQfH1oLvvIUR2POZb4lQlTaJI3lQZn7pkmjMLwNBLEA\nenyZ/Ae9AgMBAAECggEAIM6kFdfrird01k1qeK5PYUYib2Ybbi92RXiZ454xt+hW\n40q8hm7YrNa2eQvUMeL5bpSfj7N41Igcf2+5CdKn0rBBU6TA41YRP42tHlm2G6xK\nnnQZ+LPMVJ6V0BFToPbFTXssyA9CsTu2G9RjZXMfaIXUD73pBwWZH1mXyFnKfvx9\nzGngwroITKHmARVKP+wS6hrfOpK1XdEbr76nrnQt3yLmSA+n2WDZFbjwGLUDlyVJ\nqDPfiBWGsFEx5s9EwU14dTxHpBND7eXmD7K7c3nmpmvkui8ZZ7tUdnCa+0vMThBK\nqkuWiFnicFWlvWHtJAK5hVHmLRQtb4qg/3Zl3n2EQQKBgQDlRZWy3YhaWE3Rqdcx\n3Jf65Uu6NKjFqo6GUK4srCkQCGblkQJ7SZBbuyK35DhX+EBYLd/yjeHilnW44Ylb\n9FJJw6ofD777BekZSZz7GU0z9jw/YopmUHGVH1+1wIzkkP0uL259ip5R9hzYfOHF\nkaI4v9LpWfwPZ9hW9hVWza8J2QKBgQC5nVP6ji14d4Q/OaXefFB4hg5J7dgzo+/+\nNhJ/ChfQ/EN/kcXvx6FCLrpK6DBH/uu1SiAH6pQ8mKJxDjwtqfDQC9LEoaGUSgnz\nNZGgPR4wpIt4lx8Kuq1AOI7fk4WuP3xHMA4L6W+5kdTjWHpFaxl4lptfWyuto/Hf\nhXqJfx76hQKBgDnrNkIVTNjl7eLFcSObgplTS6oim3A0AgVUZGvMoiL2vGfKFkJm\n9xz1TXP/J2yxvi+Ih0aTKTlAoUSvVS/xrMgNsfBe3fQ0LgrBWfLlFWfHELlCf4wR\nTmBJqLgViIJFTnBYcyUr24sBDZBzG+X5QG3tp65jmRWbOj/dss5W750hAoGALbew\njZAjZv6ZFjGOx0P7VhQ+xLrOe7mvTP/ogl3sC892mJ9BD5QuBe0YeYbDDZieWeLO\nDOUcaeh2aj5FWEH5TGT9Hu1orOunk73oBn3HR9ffem5OeQgN0DmeBzeAv7BnXela\nLFjs6dofg3exdhOxDGCcGFqOYZB17MYlrmQfLzkCgYBPNs4MB4PyNBzjMhlpjk+b\nPQNbi5yN/hcNxiPAdyXiKvKEz8mcLDAowQnlqnS9gbENJ79+BNchb0eUC8kT+9di\nDGTSCa1MMy+M6KmEvtczcZ7x9iq6i1PFIWGF2B3xkLa8MpBrQWZrdGDuy9ixPNpq\nRR1gkot+ZbldyYR94BXy4Q==\n-----END PRIVATE KEY-----\n",
|
| 6 |
+
"client_email": "firebase-adminsdk-479uz@citadel4travels.iam.gserviceaccount.com",
|
| 7 |
+
"client_id": "112345416933732340369",
|
| 8 |
+
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
|
| 9 |
+
"token_uri": "https://oauth2.googleapis.com/token",
|
| 10 |
+
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
|
| 11 |
+
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/firebase-adminsdk-479uz%40citadel4travels.iam.gserviceaccount.com",
|
| 12 |
+
"universe_domain": "googleapis.com"
|
| 13 |
+
}
|
external_knowledge_service.py
ADDED
|
@@ -0,0 +1,409 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# external_knowledge_service.py (Updated with Firebase and Deep Search)
|
| 2 |
+
import os
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import numpy as np
|
| 6 |
+
import requests
|
| 7 |
+
from fastapi import FastAPI, HTTPException, Depends, status
|
| 8 |
+
from pydantic import BaseModel, Field, constr
|
| 9 |
+
from sentence_transformers import SentenceTransformer
|
| 10 |
+
from sklearn.metrics.pairwise import cosine_similarity
|
| 11 |
+
from datetime import datetime
|
| 12 |
+
import firebase_admin
|
| 13 |
+
from firebase_admin import credentials, firestore
|
| 14 |
+
from bs4 import BeautifulSoup
|
| 15 |
+
import re
|
| 16 |
+
from fastapi.security import APIKeyHeader
|
| 17 |
+
# For encryption (optional, requires 'cryptography' library)
|
| 18 |
+
# from cryptography.fernet import Fernet
|
| 19 |
+
# For rate limiting (optional, requires 'slowapi' library)
|
| 20 |
+
# from slowapi import Limiter, _rate_limit_exceeded_handler
|
| 21 |
+
# from slowapi.util import get_remote_address
|
| 22 |
+
# from slowapi.errors import RateLimitExceeded
|
| 23 |
+
|
| 24 |
+
app = FastAPI()
|
| 25 |
+
|
| 26 |
+
# --- Configuration ---
|
| 27 |
+
MODELS_DIR = "/home/kabo/Desktop/p/models/"
|
| 28 |
+
|
| 29 |
+
# Initialize Firebase
|
| 30 |
+
# استخدام متغيرات البيئة لاعتمادات Firebase:
|
| 31 |
+
firebase_creds_path = os.getenv("FIREBASE_CREDS_PATH", "path/to/your/firebase-credentials.json")
|
| 32 |
+
if not firebase_admin._apps:
|
| 33 |
+
try:
|
| 34 |
+
cred = credentials.Certificate(firebase_creds_path)
|
| 35 |
+
firebase_admin.initialize_app(cred)
|
| 36 |
+
db = firestore.client()
|
| 37 |
+
logger.info("Firebase initialized successfully.")
|
| 38 |
+
except Exception as e:
|
| 39 |
+
logger.error(f"Failed to initialize Firebase: {e}. Ensure FIREBASE_CREDS_PATH is set correctly and the file exists.")
|
| 40 |
+
db = None # Set db to None if initialization fails
|
| 41 |
+
|
| 42 |
+
# --- Logging Setup ---
|
| 43 |
+
logging.basicConfig(
|
| 44 |
+
level=logging.INFO,
|
| 45 |
+
format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'
|
| 46 |
+
)
|
| 47 |
+
logger = logging.getLogger(__name__)
|
| 48 |
+
|
| 49 |
+
# --- API Key Authentication ---
|
| 50 |
+
API_KEY_NAME = "X-API-KEY"
|
| 51 |
+
api_key_header = APIKeyHeader(name=API_KEY_NAME, auto_error=True)
|
| 52 |
+
|
| 53 |
+
async def get_api_key(api_key: str = Depends(api_key_header)):
|
| 54 |
+
if api_key != os.getenv("API_SECRET_KEY"):
|
| 55 |
+
raise HTTPException(
|
| 56 |
+
status_code=status.HTTP_401_UNAUTHORIZED,
|
| 57 |
+
detail="مفتاح API غير صالح"
|
| 58 |
+
)
|
| 59 |
+
return api_key
|
| 60 |
+
|
| 61 |
+
# --- Rate Limiting (Optional) ---
|
| 62 |
+
# limiter = Limiter(key_func=get_remote_address)
|
| 63 |
+
# app.state.limiter = limiter
|
| 64 |
+
# app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)
|
| 65 |
+
|
| 66 |
+
# --- Encryption Functions (Optional) ---
|
| 67 |
+
# def encrypt_data(data: str, key: bytes) -> bytes:
|
| 68 |
+
# cipher = Fernet(key)
|
| 69 |
+
# return cipher.encrypt(data.encode())
|
| 70 |
+
|
| 71 |
+
# def decrypt_data(encrypted_data: bytes, key: bytes) -> str:
|
| 72 |
+
# cipher = Fernet(key)
|
| 73 |
+
# return cipher.decrypt(encrypted_data).decode()
|
| 74 |
+
|
| 75 |
+
# --- Firebase Knowledge Base Integration ---
|
| 76 |
+
class FirebaseKnowledgeBase:
|
| 77 |
+
def __init__(self):
|
| 78 |
+
self.collection = db.collection('knowledge_base') if db else None
|
| 79 |
+
|
| 80 |
+
def query(self, goal: str, phase: str = None, limit: int = 10) -> list:
|
| 81 |
+
if not self.collection:
|
| 82 |
+
logger.error("Firestore client not initialized. Cannot query knowledge base.")
|
| 83 |
+
return []
|
| 84 |
+
|
| 85 |
+
keywords = [goal.lower(), 'android', 'pentest', 'mobile', 'device']
|
| 86 |
+
if phase:
|
| 87 |
+
keywords.append(phase.lower())
|
| 88 |
+
|
| 89 |
+
try:
|
| 90 |
+
# Build Firestore query
|
| 91 |
+
query = self.collection
|
| 92 |
+
|
| 93 |
+
# Execute query and filter results
|
| 94 |
+
results = []
|
| 95 |
+
docs = query.stream()
|
| 96 |
+
|
| 97 |
+
for doc in docs:
|
| 98 |
+
data = doc.to_dict()
|
| 99 |
+
text = f"{data.get('prompt', '').lower()} {data.get('completion', '').lower()} {data.get('metadata', '').lower()}"
|
| 100 |
+
if any(keyword in text for keyword in keywords):
|
| 101 |
+
results.append(data)
|
| 102 |
+
if len(results) >= limit:
|
| 103 |
+
break
|
| 104 |
+
|
| 105 |
+
# Sort by priority (high, medium, low) and then by timestamp
|
| 106 |
+
priority_order = {"high": 1, "medium": 2, "low": 3}
|
| 107 |
+
results.sort(key=lambda x: (
|
| 108 |
+
priority_order.get(x.get('metadata', {}).get('priority', 'low').lower(),
|
| 109 |
+
x.get('metadata', {}).get('timestamp', 0)
|
| 110 |
+
))
|
| 111 |
+
return results[:limit]
|
| 112 |
+
except Exception as e:
|
| 113 |
+
logger.error(f"Failed to query knowledge base: {e}")
|
| 114 |
+
return []
|
| 115 |
+
|
| 116 |
+
# --- RAG Knowledge Index ---
|
| 117 |
+
class KnowledgeIndex:
|
| 118 |
+
def __init__(self, model_name="all-MiniLM-L6-v2"):
|
| 119 |
+
self.model = SentenceTransformer(model_name)
|
| 120 |
+
self.knowledge_base = [] # Stores {'text': '...', 'embedding': [...] }
|
| 121 |
+
self.load_knowledge_from_file(os.path.join(os.path.dirname(__file__), 'knowledge_base.json'))
|
| 122 |
+
|
| 123 |
+
def load_knowledge_from_file(self, file_path):
|
| 124 |
+
if os.path.exists(file_path):
|
| 125 |
+
with open(file_path, 'r', encoding='utf-8') as f:
|
| 126 |
+
data = json.load(f)
|
| 127 |
+
for item in data:
|
| 128 |
+
text = item.get('text', '')
|
| 129 |
+
if text:
|
| 130 |
+
embedding = self.model.encode(text).tolist()
|
| 131 |
+
self.knowledge_base.append({'text': text, 'embedding': embedding, 'source': item.get('source', 'local')})
|
| 132 |
+
logger.info(f"Loaded {len(self.knowledge_base)} items into RAG knowledge base.")
|
| 133 |
+
else:
|
| 134 |
+
logger.warning(f"Knowledge base file not found: {file_path}. RAG will operate on an empty knowledge base.")
|
| 135 |
+
|
| 136 |
+
def retrieve(self, query: str, top_k: int = 5) -> List[Dict]:
|
| 137 |
+
if not self.knowledge_base:
|
| 138 |
+
return []
|
| 139 |
+
|
| 140 |
+
query_embedding = self.model.encode(query).reshape(1, -1)
|
| 141 |
+
|
| 142 |
+
texts = [item['text'] for item in self.knowledge_base]
|
| 143 |
+
embeddings = np.array([item['embedding'] for item in self.knowledge_base])
|
| 144 |
+
|
| 145 |
+
similarities = cosine_similarity(query_embedding, embeddings)[0]
|
| 146 |
+
|
| 147 |
+
# Get top_k indices
|
| 148 |
+
top_indices = similarities.argsort()[-top_k:][::-1]
|
| 149 |
+
|
| 150 |
+
results = []
|
| 151 |
+
for i in top_indices:
|
| 152 |
+
results.append({
|
| 153 |
+
"text": self.knowledge_base[i]['text'],
|
| 154 |
+
"similarity": similarities[i],
|
| 155 |
+
"source": self.knowledge_base[i].get('source', 'RAG')
|
| 156 |
+
})
|
| 157 |
+
return results
|
| 158 |
+
|
| 159 |
+
# --- Deep Search Engine ---
|
| 160 |
+
class DeepSearchEngine:
|
| 161 |
+
def __init__(self):
|
| 162 |
+
self.headers = {
|
| 163 |
+
"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"
|
| 164 |
+
}
|
| 165 |
+
|
| 166 |
+
def search_device_info(self, device_info: str, os_version: str) -> dict:
|
| 167 |
+
"""Search for device and OS vulnerabilities"""
|
| 168 |
+
results = {
|
| 169 |
+
"device": device_info,
|
| 170 |
+
"os_version": os_version,
|
| 171 |
+
"vulnerabilities": [],
|
| 172 |
+
"exploits": [],
|
| 173 |
+
"recommendations": []
|
| 174 |
+
}
|
| 175 |
+
|
| 176 |
+
try:
|
| 177 |
+
# Search for CVEs related to the device and OS
|
| 178 |
+
cve_results = self.search_cve(device_info, os_version)
|
| 179 |
+
results["vulnerabilities"] = cve_results
|
| 180 |
+
|
| 181 |
+
# Search for exploits
|
| 182 |
+
exploit_results = self.search_exploits(device_info, os_version)
|
| 183 |
+
results["exploits"] = exploit_results
|
| 184 |
+
|
| 185 |
+
# Get security recommendations
|
| 186 |
+
recommendations = self.get_security_recommendations(os_version)
|
| 187 |
+
results["recommendations"] = recommendations
|
| 188 |
+
|
| 189 |
+
except Exception as e:
|
| 190 |
+
logger.error(f"Deep search failed: {e}")
|
| 191 |
+
|
| 192 |
+
return results
|
| 193 |
+
|
| 194 |
+
def search_cve(self, device: str, os_version: str) -> list:
|
| 195 |
+
"""Search for CVEs related to the device and OS"""
|
| 196 |
+
cves = []
|
| 197 |
+
try:
|
| 198 |
+
# Search CVE databases
|
| 199 |
+
query = f"{device} {os_version} CVE"
|
| 200 |
+
search_url = f"https://cve.mitre.org/cgi-bin/cvekey.cgi?keyword={query}"
|
| 201 |
+
response = requests.get(search_url, headers=self.headers)
|
| 202 |
+
|
| 203 |
+
if response.status_code == 200:
|
| 204 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 205 |
+
table = soup.find('div', id='TableWithRules')
|
| 206 |
+
|
| 207 |
+
if table:
|
| 208 |
+
rows = table.find_all('tr')[1:] # Skip header
|
| 209 |
+
for row in rows:
|
| 210 |
+
cols = row.find_all('td')
|
| 211 |
+
if len(cols) >= 2:
|
| 212 |
+
cve_id = cols[0].get_text(strip=True)
|
| 213 |
+
description = cols[1].get_text(strip=True)
|
| 214 |
+
cves.append({
|
| 215 |
+
"cve_id": cve_id,
|
| 216 |
+
"description": description,
|
| 217 |
+
"source": "CVE Mitre"
|
| 218 |
+
})
|
| 219 |
+
|
| 220 |
+
# Limit results
|
| 221 |
+
return cves[:10]
|
| 222 |
+
except Exception as e:
|
| 223 |
+
logger.error(f"CVE search failed: {e}")
|
| 224 |
+
return []
|
| 225 |
+
|
| 226 |
+
def search_exploits(self, device: str, os_version: str) -> list:
|
| 227 |
+
"""Search for exploits related to the device and OS"""
|
| 228 |
+
exploits = []
|
| 229 |
+
try:
|
| 230 |
+
# Search ExploitDB
|
| 231 |
+
query = f"{device} {os_version}"
|
| 232 |
+
search_url = f"https://www.exploit-db.com/search?q={query}"
|
| 233 |
+
response = requests.get(search_url, headers=self.headers)
|
| 234 |
+
|
| 235 |
+
if response.status_code == 200:
|
| 236 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 237 |
+
cards = soup.select('.card .card-title')
|
| 238 |
+
|
| 239 |
+
for card in cards:
|
| 240 |
+
title = card.get_text(strip=True)
|
| 241 |
+
link = card.find('a')['href']
|
| 242 |
+
if not link.startswith('http'):
|
| 243 |
+
link = f"https://www.exploit-db.com{link}"
|
| 244 |
+
exploits.append({
|
| 245 |
+
"title": title,
|
| 246 |
+
"link": link,
|
| 247 |
+
"source": "ExploitDB"
|
| 248 |
+
})
|
| 249 |
+
|
| 250 |
+
# Limit results
|
| 251 |
+
return exploits[:10]
|
| 252 |
+
except Exception as e:
|
| 253 |
+
logger.error(f"Exploit search failed: {e}")
|
| 254 |
+
return []
|
| 255 |
+
|
| 256 |
+
def get_security_recommendations(self, os_version: str) -> list:
|
| 257 |
+
"""Get security recommendations for the OS version"""
|
| 258 |
+
recommendations = []
|
| 259 |
+
try:
|
| 260 |
+
# For Android devices
|
| 261 |
+
if "android" in os_version.lower():
|
| 262 |
+
# Search Android security bulletins
|
| 263 |
+
url = "https://source.android.com/docs/security/bulletin"
|
| 264 |
+
response = requests.get(url, headers=self.headers)
|
| 265 |
+
|
| 266 |
+
if response.status_code == 200:
|
| 267 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 268 |
+
versions = soup.select('.devsite-article-body h2')
|
| 269 |
+
|
| 270 |
+
for version in versions:
|
| 271 |
+
if os_version in version.get_text():
|
| 272 |
+
# Find recommendations for this version
|
| 273 |
+
next_ul = version.find_next('ul')
|
| 274 |
+
if next_ul:
|
| 275 |
+
items = next_ul.select('li')
|
| 276 |
+
for item in items:
|
| 277 |
+
recommendations.append(item.get_text(strip=True))
|
| 278 |
+
|
| 279 |
+
# For iOS devices
|
| 280 |
+
elif "ios" in os_version.lower():
|
| 281 |
+
# Search Apple security updates
|
| 282 |
+
url = "https://support.apple.com/en-us/HT201222"
|
| 283 |
+
response = requests.get(url, headers=self.headers)
|
| 284 |
+
|
| 285 |
+
if response.status_code == 200:
|
| 286 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 287 |
+
sections = soup.select('#sections')
|
| 288 |
+
|
| 289 |
+
for section in sections:
|
| 290 |
+
if os_version in section.get_text():
|
| 291 |
+
# Find recommendations in this section
|
| 292 |
+
items = section.select('li')
|
| 293 |
+
for item in items:
|
| 294 |
+
recommendations.append(item.get_text(strip=True))
|
| 295 |
+
|
| 296 |
+
# Limit results
|
| 297 |
+
return recommendations[:5]
|
| 298 |
+
except Exception as e:
|
| 299 |
+
logger.error(f"Security recommendations search failed: {e}")
|
| 300 |
+
return []
|
| 301 |
+
|
| 302 |
+
def search_public_resources(self, device_info: str) -> list:
|
| 303 |
+
"""Search for public resources related to the device"""
|
| 304 |
+
resources = []
|
| 305 |
+
try:
|
| 306 |
+
# Search GitHub for device-related projects
|
| 307 |
+
github_url = f"https://github.com/search?q={device_info.replace(' ', '+')}+pentest"
|
| 308 |
+
response = requests.get(github_url, headers=self.headers)
|
| 309 |
+
|
| 310 |
+
if response.status_code == 200:
|
| 311 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 312 |
+
repos = soup.select('.repo-list-item')
|
| 313 |
+
|
| 314 |
+
for repo in repos:
|
| 315 |
+
title = repo.select_one('.v-align-middle').get_text(strip=True)
|
| 316 |
+
description = repo.select_one('.mb-1').get_text(strip=True) if repo.select_one('.mb-1') else ""
|
| 317 |
+
url = f"https://github.com{repo.select_one('.v-align-middle')['href']}"
|
| 318 |
+
resources.append({
|
| 319 |
+
"title": title,
|
| 320 |
+
"description": description,
|
| 321 |
+
"url": url,
|
| 322 |
+
"source": "GitHub"
|
| 323 |
+
})
|
| 324 |
+
|
| 325 |
+
# Search Hack Forums for device-related discussions
|
| 326 |
+
forum_url = f"https://hackforums.net/search.php?action=finduserthreads&keywords={device_info.replace(' ', '+')}"
|
| 327 |
+
response = requests.get(forum_url, headers=self.headers)
|
| 328 |
+
|
| 329 |
+
if response.status_code == 200:
|
| 330 |
+
soup = BeautifulSoup(response.text, 'html.parser')
|
| 331 |
+
threads = soup.select('.thread')
|
| 332 |
+
|
| 333 |
+
for thread in threads:
|
| 334 |
+
title = thread.select_one('.threadtitle').get_text(strip=True)
|
| 335 |
+
url = f"https://hackforums.net{thread.select_one('.threadtitle a')['href']}"
|
| 336 |
+
resources.append({
|
| 337 |
+
"title": title,
|
| 338 |
+
"description": "Forum discussion",
|
| 339 |
+
"url": url,
|
| 340 |
+
"source": "HackForums"
|
| 341 |
+
})
|
| 342 |
+
|
| 343 |
+
# Limit results
|
| 344 |
+
return resources[:10]
|
| 345 |
+
except Exception as e:
|
| 346 |
+
logger.error(f"Public resources search failed: {e}")
|
| 347 |
+
return []
|
| 348 |
+
|
| 349 |
+
# --- Initialize Services ---
|
| 350 |
+
firebase_kb = FirebaseKnowledgeBase()
|
| 351 |
+
rag_index = KnowledgeIndex()
|
| 352 |
+
deep_search_engine = DeepSearchEngine()
|
| 353 |
+
|
| 354 |
+
# --- Request Models ---
|
| 355 |
+
class RAGRequest(BaseModel):
|
| 356 |
+
# التحقق من صحة المدخلات:
|
| 357 |
+
query: constr(min_length=3, max_length=500)
|
| 358 |
+
top_k: int = Field(5, gt=0, le=20)
|
| 359 |
+
|
| 360 |
+
class FirebaseQueryRequest(BaseModel):
|
| 361 |
+
goal: str
|
| 362 |
+
phase: str = None
|
| 363 |
+
limit: int = 10
|
| 364 |
+
|
| 365 |
+
class DeepSearchRequest(BaseModel):
|
| 366 |
+
device_info: str
|
| 367 |
+
os_version: str
|
| 368 |
+
|
| 369 |
+
# --- API Endpoints ---
|
| 370 |
+
@app.get("/health")
|
| 371 |
+
async def health_check():
|
| 372 |
+
"""Endpoint to check the health of the service."""
|
| 373 |
+
return {"status": "ok", "message": "Knowledge service is running."}
|
| 374 |
+
|
| 375 |
+
@app.post("/rag/retrieve")
|
| 376 |
+
# @limiter.limit("5/minute") # الحد من معدل الطلبات:
|
| 377 |
+
async def rag_retrieve(request: RAGRequest, api_key: str = Depends(get_api_key)):
|
| 378 |
+
try:
|
| 379 |
+
results = rag_index.retrieve(request.query, request.top_k)
|
| 380 |
+
return {"success": True, "data": {"results": results}, "error": None}
|
| 381 |
+
except Exception as e:
|
| 382 |
+
logger.error(f"RAG retrieval failed: {e}")
|
| 383 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 384 |
+
|
| 385 |
+
@app.post("/firebase/query")
|
| 386 |
+
# @limiter.limit("5/minute") # الحد من معدل الطلبات:
|
| 387 |
+
async def firebase_query(request: FirebaseQueryRequest, api_key: str = Depends(get_api_key)):
|
| 388 |
+
try:
|
| 389 |
+
results = firebase_kb.query(request.goal, request.phase, request.limit)
|
| 390 |
+
return {"success": True, "data": {"results": results}, "error": None}
|
| 391 |
+
except Exception as e:
|
| 392 |
+
logger.error(f"Firebase query failed: {e}")
|
| 393 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 394 |
+
|
| 395 |
+
@app.post("/deep_search")
|
| 396 |
+
# @limiter.limit("5/minute") # الحد من معدل الطلبات:
|
| 397 |
+
async def deep_search(request: DeepSearchRequest, api_key: str = Depends(get_api_key)):
|
| 398 |
+
try:
|
| 399 |
+
results = deep_search_engine.search_device_info(request.device_info, request.os_version)
|
| 400 |
+
# Add public resources
|
| 401 |
+
results["public_resources"] = deep_search_engine.search_public_resources(request.device_info)
|
| 402 |
+
return {"success": True, "data": results, "error": None}
|
| 403 |
+
except Exception as e:
|
| 404 |
+
logger.error(f"Deep search failed: {e}")
|
| 405 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 406 |
+
|
| 407 |
+
if __name__ == "__main__":
|
| 408 |
+
import uvicorn
|
| 409 |
+
uvicorn.run(app, host="0.0.0.0", port=8000)
|
knowledge_base.json
ADDED
|
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
{
|
| 2 |
+
"successful_commands": [
|
| 3 |
+
"nmap -sV -O 192.168.1.0/24",
|
| 4 |
+
"sqlmap -u http://example.com/login --dbs",
|
| 5 |
+
"subfinder -d example.com",
|
| 6 |
+
"gobuster dir -u http://example.com -w /path/to/wordlist.txt"
|
| 7 |
+
],
|
| 8 |
+
"vulnerability_patterns": [
|
| 9 |
+
"SQL injection vulnerability detected",
|
| 10 |
+
"XSS vulnerability in search parameter",
|
| 11 |
+
"Open port 22 (SSH) detected, potential brute-force target",
|
| 12 |
+
"Outdated Apache version found, check CVEs for version X.Y.Z",
|
| 13 |
+
"Directory listing enabled on /admin",
|
| 14 |
+
"Weak credentials found for service XYZ"
|
| 15 |
+
],
|
| 16 |
+
"effective_payloads": {
|
| 17 |
+
"windows": [
|
| 18 |
+
"windows/x64/meterpreter/reverse_tcp",
|
| 19 |
+
"windows/meterpreter/reverse_tcp"
|
| 20 |
+
],
|
| 21 |
+
"linux": [
|
| 22 |
+
"linux/x64/meterpreter/reverse_tcp",
|
| 23 |
+
"linux/x86/meterpreter/reverse_tcp"
|
| 24 |
+
],
|
| 25 |
+
"web": [
|
| 26 |
+
"<script>alert('XSS');</script>",
|
| 27 |
+
"' OR 1=1--",
|
| 28 |
+
"UNION SELECT null,null,null,version()-- -"
|
| 29 |
+
]
|
| 30 |
+
},
|
| 31 |
+
"error_corrections": {
|
| 32 |
+
"Command not found": "Try installing the required package. Use `sudo apt install <package_name>` or `pip install <package_name>`.",
|
| 33 |
+
"Permission denied": "Try running with sudo or check file permissions.",
|
| 34 |
+
"Connection refused": "Target host or port might be down or blocked by firewall.",
|
| 35 |
+
"No targets specified": "Ensure you provide a valid IP address or URL.",
|
| 36 |
+
"Shodan API Key not configured": "Set the SHODAN_API_KEY environment variable."
|
| 37 |
+
},
|
| 38 |
+
"reconnaissance_tips": [
|
| 39 |
+
"Always start with basic network scanning (nmap).",
|
| 40 |
+
"Enumerate subdomains for larger attack surface.",
|
| 41 |
+
"Check for open ports and services, then research known vulnerabilities for those services.",
|
| 42 |
+
"Use OSINT tools to gather information about the target organization and its employees."
|
| 43 |
+
],
|
| 44 |
+
"exploitation_tips": [
|
| 45 |
+
"After finding a vulnerability, check ExploitDB and Metasploit for existing exploits.",
|
| 46 |
+
"Always verify payload delivery and listener setup.",
|
| 47 |
+
"Prioritize remote code execution (RCE) vulnerabilities."
|
| 48 |
+
]
|
| 49 |
+
}
|