Oh no! Where's the JavaScript?
Your Web browser does not have JavaScript enabled or does not support JavaScript. Please enable JavaScript on your Web browser to properly view this Web site, or upgrade to a Web browser that does support JavaScript.
Articles

ai based cyber security automation sample program

Here’s an AI-based cybersecurity automation program showcasing intrusion detection and threat classification. It automates the detection of suspicious activity in log files using a machine learning model for anomaly detection.

 


AI-Powered Intrusion Detection Automation

Use Case:

  1. Monitor log files (e.g., web server logs or firewall logs) in real-time.
  2. Use AI to classify log entries as normal or suspicious.
  3. Alert the admin via email if suspicious activity is detected.

Code Example

import os
import smtplib
from email.mime.text import MIMEText
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler
import joblib # For loading pre-trained ML models
import pandas as pd

# Load pre-trained AI model (e.g., Isolation Forest or similar)
model = joblib.load("anomaly_detection_model.pkl") # Replace with your model file

# Email configuration
SMTP_SERVER = "smtp.example.com"
EMAIL_FROM = "your_email@example.com"
EMAIL_PASSWORD = "your_password"
EMAIL_TO = "admin@example.com"

def process_log_entry(log_entry):
 """Convert a log entry into a suitable format for the AI model."""
 # Assuming log_entry is a comma-separated string: "timestamp,ip,status,request"
 # Extract features like IP, status code, request type, etc.
 parts = log_entry.split(",")
 return pd.DataFrame([{
 "ip": parts[1], # Example: Convert IP to numeric representation
 "status_code": int(parts[2]),
 "request_type": parts[3],
 }])

def classify_log(log_entry):
 """Classify a log entry as normal or suspicious."""
 data = process_log_entry(log_entry)
 prediction = model.predict(data) # Returns 0 for normal, 1 for suspicious
 return prediction[0] == 1

def send_alert(log_entry):
 """Send an email alert for suspicious activity."""
 subject = "Suspicious Activity Detected"
 body = f"A suspicious log entry was detected:nn{log_entry}"
 msg = MIMEText(body)
 msg["Subject"] = subject
 msg["From"] = EMAIL_FROM
 msg["To"] = EMAIL_TO

 with smtplib.SMTP_SSL(SMTP_SERVER, 465) as server:
 server.login(EMAIL_FROM, EMAIL_PASSWORD)
 server.sendmail(EMAIL_FROM, EMAIL_TO, msg.as_string())
 print("Alert email sent!")

class LogMonitorHandler(FileSystemEventHandler):
 """Handles new log entries in the watched folder."""
 def on_modified(self, event):
 if event.is_directory:
 return
 if event.src_path.endswith(".log"):
 print(f"Log file updated: {event.src_path}")
 with open(event.src_path, "r") as file:
 logs = file.readlines()
 for log_entry in logs[-10:]: # Process the last 10 entries
 if classify_log(log_entry.strip()):
 print(f"Suspicious log detected: {log_entry.strip()}")
 send_alert(log_entry.strip())

def start_monitoring(log_folder):
 """Start monitoring a folder for new log entries."""
 observer = Observer()
 event_handler = LogMonitorHandler()
 observer.schedule(event_handler, log_folder, recursive=False)
 observer.start()
 print(f"Monitoring logs in: {log_folder}")
 try:
 while True:
 pass
 except KeyboardInterrupt:
 observer.stop()
 observer.join()

# Main
if __name__ == "__main__":
 # Replace with the path of the folder containing log files
 LOG_FOLDER = "/path/to/logs"
 start_monitoring(LOG_FOLDER)

How It Works

  1. Log Monitoring:

    • Watches a folder containing log files in real-time using the
      watchdog
      library.
    • Detects changes (e.g., new entries) in
      .log
      files.
  2. AI-Based Threat Detection:

    • Extracts features from each log entry (e.g., IP address, status code, request type).
    • Classifies the log entry as "normal" or "suspicious" using a pre-trained anomaly detection model.
  3. Alert Automation:

    • Sends an email alert to the administrator for every suspicious log entry.

Dependencies

Install the required libraries:

pip install watchdog pandas scikit-learn joblib

Customizations

  • Pre-trained Model: Use a model like Isolation Forest, Autoencoders, or a supervised classifier (e.g., Random Forest). Train the model on your log dataset.
  • Log Formats: Adapt the
    process_log_entry
    function to parse your specific log file format.
  • Alerting Mechanisms: Extend the email alert system to integrate with Slack, SMS, or other alerting services.

Example Log Entry

For this example, the log file might look like:

2025-01-26,192.168.1.10,404,GET /admin
2025-01-26,10.0.0.5,200,POST /login

The

process_log_entry
function should transform this into a format suitable for your AI model.


 

caa January 26 2025 26 reads 0 comments Print

0 comments

Leave a Comment

Please Login to Post a Comment.
  • No Comments have been Posted.

Sign In
Not a member yet? Click here to register.
Forgot Password?
Users Online Now
Guests Online 2
Members Online 0

Total Members: 14
Newest Member: Frank_nKansas