Я работаю над отправкой оповещений из Wazuh в Telegram и интегрировал ChatGPT, чтобы включать рекомендации в оповещения перед их отправкой. До добавления ChatGPT интеграция работала нормально, но теперь оповещения не отправляются. Когда я тестирую функции по отдельности, они работают должным образом, но при объединении оповещения не проходят. Все ключи API верны. Буду признателен за любую помощь или предложения.
#!/usr/bin/env python
import sys
import json
import requests
from datetime import datetime
import openai # Ensure openai module is imported
# CHAT_ID="xxxx"
CHAT_ID = "00000000"
# AbuseIPDB API keys list
ABUSEIPDB_API_KEYS = [
"00000000000000000000000000000000000000000000", # Replace with your actual API keys
"0000000000000000000000000000000000000000000000000000000000000000000000"
]
# OpenAI API key
openai.api_key = "00000000000000000000000000000000000000000000000000000"
# Index to keep track of which API key to use
current_api_key_index = 0
# Malicious IP file path
MALICIOUS_IP_FILE = "/var/ossec/logs/malicious_ips.txt"
# Read configuration parameters
try:
with open(sys.argv[1], encoding='utf-8') as alert_file:
alert_json = json.load(alert_file)
except Exception as e:
with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file:
log_file.write(f"Error reading alert file: {e}\n")
sys.exit(1)
hook_url = sys.argv[3] # URL for sending the alert
# Function to get the current API key based on round-robin rotation
def get_next_api_key():
global current_api_key_index
api_key = ABUSEIPDB_API_KEYS[current_api_key_index]
# Move to the next key in the list (round-robin)
current_api_key_index = (current_api_key_index + 1) % len(ABUSEIPDB_API_KEYS)
return api_key
def get_location_from_ip(srcip):
# Define the URL of the geolocation API (ipinfo.io in this case)
url = f"https://ipinfo.io/{srcip}/json"
try:
response = requests.get(url)
response.raise_for_status() # Check for request errors
# Parse the JSON response
data = response.json()
# Extract country and city name
country = data.get('country', 'N/A')
city = data.get('city', 'N/A')
# Return both country and city names
return country, city
except requests.exceptions.RequestException as e:
print(f"Error fetching geolocation for {srcip}: {e}")
return 'N/A', 'N/A'
def check_ip_malicious(srcip):
"""
Check if the IP is malicious using AbuseIPDB's API with round-robin key rotation.
"""
url = f"https://api.abuseipdb.com/api/v2/check"
api_key = get_next_api_key() # Get the next API key using round-robin
headers = {
'Key': api_key,
'Accept': 'application/json'
}
params = {
'ipAddress': srcip,
'maxAgeInDays': 90 # Check only the last 90 days of reports
}
try:
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
data = response.json()
# Check if the IP is flagged as malicious
if data['data']['abuseConfidenceScore'] >= 50: # If score is 50 or higher, consider as malicious
return True
return False
except requests.exceptions.RequestException as e:
print(f"Error checking IP {srcip} with AbuseIPDB: {e}")
return False
def save_malicious_ip(srcip, country, city):
"""
Save malicious IP along with country and city to a file.
"""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
with open(MALICIOUS_IP_FILE, 'a', encoding='utf-8') as file:
file.write(f"{timestamp} - IP: {srcip}, Country: {country}, City: {city}\n")
# Function to get recommendations from ChatGPT based on the source IP and rule description
def get_chatgpt_recommendation(ip, description):
try:
# Send the request to OpenAI's ChatGPT model
response = openai.ChatCompletion.create(
model="gpt-3.5-turbo", # Specify the chat model
messages=[{"role": "system", "content": "You are a cybersecurity assistant providing detailed recommendations."},
{"role": "user", "content": f"Please provide recommendations based on the following rule description:\n\n{description}"}],
max_tokens=150, # Limit the length of the response
temperature=0.7, # Adjust for creativity or variability
)
# Extract and return the assistant's reply
return response['choices'][0]['message']['content'].strip()
except openai.error.OpenAIError as e:
return f"An error occurred while fetching recommendations: {str(e)}"
# Extract data fields safely
alert_level = alert_json.get('rule', {}).get('level', 0) # Assuming level is an integer, default to 0
description = alert_json.get('rule', {}).get('description', "N/A")
agent = alert_json.get('agent', {}).get('name', "N/A")
username = alert_json.get('data', {}).get('dstuser', alert_json.get('data', {}).get('srcuser', "N/A"))
sourceip = alert_json.get('data', {}).get('srcip', alert_json.get('data', {}).get('src_ip', "N/A"))
# Try fetching geolocation and malicious status
try:
country, city = get_location_from_ip(sourceip)
except Exception as e:
print(f"Error fetching geolocation for {sourceip}, falling back to ChatGPT: {e}")
country, city = 'N/A', 'N/A'
try:
is_malicious = check_ip_malicious(sourceip)
except Exception as e:
print(f"Error checking if {sourceip} is malicious, falling back to ChatGPT: {e}")
is_malicious = False
# Get recommendation from ChatGPT
chatgpt_recommendation = get_chatgpt_recommendation(sourceip, description)
# Print the result
print(f"Source IP: {sourceip}")
print(f"Country for IP {sourceip}: {country}")
print(f"City for IP {sourceip}: {city}")
print(f"Is the IP malicious? {'Yes' if is_malicious else 'No'}")
print(f"ChatGPT Recommendation: {chatgpt_recommendation}")
# If the IP is malicious, save it to the file
if is_malicious:
save_malicious_ip(sourceip, country, city)
# If the alert level is lower than 5, skip sending to Telegram
if alert_level < 5:
print(f"Alert level is {alert_level}. Skipping sending to Telegram.")
sys.exit(0)
# Generate request message
msg_text = (
f"*Уровень тревоги*: {alert_level}\n"
f"*Описание*: {description}\n"
f"*Источник*: {agent}\n"
f"*Пользователь*: {username}\n"
f"*Удаленный хост*: {sourceip}\n"
f"*Местоположение*: {city}, {country}\n"
f"*Возможно IP-адрес удаленного хоста является вредоносным?*: {'Да' if is_malicious else 'Нет'}\n"
f"*Рекомендация ChatGPT*: {chatgpt_recommendation}\n"
)
# Generate request data
msg_data = {
"chat_id": CHAT_ID,
"text": msg_text,
}
headers = {'Content-Type': 'application/json', 'Accept-Charset': 'UTF-8'}
# Send the request
try:
print(f"Sending message: {json.dumps(msg_data, indent=2)}")
response = requests.post(hook_url, headers=headers, data=json.dumps(msg_data), params={"parse_mode": "Markdown"})
response.raise_for_status() # Raise an exception for HTTP errors
except Exception as e:
with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file:
log_file.write(f"Error sending alert: {e}\n")
sys.exit(1)
# Log the response for debugging
if response.status_code != 200:
with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file:
log_file.write(f"Error sending message: {response.status_code} - {response.text}\n")
else:
with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file:
log_file.write(f"Message sent successfully: {response.status_code}\n")
sys.exit(0)
Я тестировал скрипт без интеграции ChatGPT, и он работал нормально. Однако если включен ChatGPT, оповещения не отправляются. Когда я использую другой скрипт для ChatGPT, он работает должным образом.
Я работаю над отправкой оповещений из Wazuh в Telegram и интегрировал ChatGPT, чтобы включать рекомендации в оповещения перед их отправкой. До добавления ChatGPT интеграция работала нормально, но теперь оповещения не отправляются. Когда я тестирую функции по отдельности, они работают должным образом, но при объединении оповещения не проходят. Все ключи API верны. Буду признателен за любую помощь или предложения. [code]#!/usr/bin/env python
import sys import json import requests from datetime import datetime import openai # Ensure openai module is imported
# CHAT_ID="xxxx" CHAT_ID = "00000000"
# AbuseIPDB API keys list ABUSEIPDB_API_KEYS = [ "00000000000000000000000000000000000000000000", # Replace with your actual API keys "0000000000000000000000000000000000000000000000000000000000000000000000" ]
# OpenAI API key openai.api_key = "00000000000000000000000000000000000000000000000000000"
# Index to keep track of which API key to use current_api_key_index = 0
# Malicious IP file path MALICIOUS_IP_FILE = "/var/ossec/logs/malicious_ips.txt"
# Read configuration parameters try: with open(sys.argv[1], encoding='utf-8') as alert_file: alert_json = json.load(alert_file) except Exception as e: with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file: log_file.write(f"Error reading alert file: {e}\n") sys.exit(1)
hook_url = sys.argv[3] # URL for sending the alert
# Function to get the current API key based on round-robin rotation def get_next_api_key(): global current_api_key_index api_key = ABUSEIPDB_API_KEYS[current_api_key_index] # Move to the next key in the list (round-robin) current_api_key_index = (current_api_key_index + 1) % len(ABUSEIPDB_API_KEYS) return api_key
def get_location_from_ip(srcip): # Define the URL of the geolocation API (ipinfo.io in this case) url = f"https://ipinfo.io/{srcip}/json"
try: response = requests.get(url) response.raise_for_status() # Check for request errors
# Parse the JSON response data = response.json()
# Extract country and city name country = data.get('country', 'N/A') city = data.get('city', 'N/A')
# Return both country and city names return country, city
except requests.exceptions.RequestException as e: print(f"Error fetching geolocation for {srcip}: {e}") return 'N/A', 'N/A'
def check_ip_malicious(srcip): """ Check if the IP is malicious using AbuseIPDB's API with round-robin key rotation. """ url = f"https://api.abuseipdb.com/api/v2/check" api_key = get_next_api_key() # Get the next API key using round-robin headers = { 'Key': api_key, 'Accept': 'application/json' } params = { 'ipAddress': srcip, 'maxAgeInDays': 90 # Check only the last 90 days of reports }
# Check if the IP is flagged as malicious if data['data']['abuseConfidenceScore'] >= 50: # If score is 50 or higher, consider as malicious return True return False
except requests.exceptions.RequestException as e: print(f"Error checking IP {srcip} with AbuseIPDB: {e}") return False
def save_malicious_ip(srcip, country, city): """ Save malicious IP along with country and city to a file. """ timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S") with open(MALICIOUS_IP_FILE, 'a', encoding='utf-8') as file: file.write(f"{timestamp} - IP: {srcip}, Country: {country}, City: {city}\n")
# Function to get recommendations from ChatGPT based on the source IP and rule description def get_chatgpt_recommendation(ip, description): try: # Send the request to OpenAI's ChatGPT model response = openai.ChatCompletion.create( model="gpt-3.5-turbo", # Specify the chat model messages=[{"role": "system", "content": "You are a cybersecurity assistant providing detailed recommendations."}, {"role": "user", "content": f"Please provide recommendations based on the following rule description:\n\n{description}"}], max_tokens=150, # Limit the length of the response temperature=0.7, # Adjust for creativity or variability )
# Extract and return the assistant's reply return response['choices'][0]['message']['content'].strip()
except openai.error.OpenAIError as e: return f"An error occurred while fetching recommendations: {str(e)}"
# Try fetching geolocation and malicious status try: country, city = get_location_from_ip(sourceip) except Exception as e: print(f"Error fetching geolocation for {sourceip}, falling back to ChatGPT: {e}") country, city = 'N/A', 'N/A'
try: is_malicious = check_ip_malicious(sourceip) except Exception as e: print(f"Error checking if {sourceip} is malicious, falling back to ChatGPT: {e}") is_malicious = False
# Get recommendation from ChatGPT chatgpt_recommendation = get_chatgpt_recommendation(sourceip, description)
# Print the result print(f"Source IP: {sourceip}") print(f"Country for IP {sourceip}: {country}") print(f"City for IP {sourceip}: {city}") print(f"Is the IP malicious? {'Yes' if is_malicious else 'No'}") print(f"ChatGPT Recommendation: {chatgpt_recommendation}")
# If the IP is malicious, save it to the file if is_malicious: save_malicious_ip(sourceip, country, city)
# If the alert level is lower than 5, skip sending to Telegram if alert_level < 5: print(f"Alert level is {alert_level}. Skipping sending to Telegram.") sys.exit(0)
# Send the request try: print(f"Sending message: {json.dumps(msg_data, indent=2)}") response = requests.post(hook_url, headers=headers, data=json.dumps(msg_data), params={"parse_mode": "Markdown"}) response.raise_for_status() # Raise an exception for HTTP errors except Exception as e: with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file: log_file.write(f"Error sending alert: {e}\n") sys.exit(1)
# Log the response for debugging if response.status_code != 200: with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file: log_file.write(f"Error sending message: {response.status_code} - {response.text}\n") else: with open('/var/ossec/logs/integrations.log', 'a', encoding="utf-8") as log_file: log_file.write(f"Message sent successfully: {response.status_code}\n")
sys.exit(0)
[/code] Я тестировал скрипт без интеграции ChatGPT, и он работал нормально. Однако если включен ChatGPT, оповещения не отправляются. Когда я использую другой скрипт для ChatGPT, он работает должным образом.