// main.cpp
#include <iostream>
#include <fstream>
#include <vector>
#include <map>
#include <cstring>
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include <ctime>
#include <algorithm>
#include <memory>
#include <arpa/inet.h> // ntohs ve ntohl için eklenmiştir
#include <tuple>
#include <set>
#include <deque>
#include <unordered_map>
#include <mutex>
#include <thread>
#include <queue>
#include <condition_variable>
#include <sstream> // std::istringstream için
#include <functional> // std::function için
// nlohmann/json.hpp dosyasını doğru şekilde dahil edin
#include "nlohmann/json.hpp" // JSON loglama için
#include <sqlite3.h> // SQLite veritabanı için
// #include <pcap.h> // libpcap kullanılmayacak
using json = nlohmann::json;
// Yapısal tanımlamalar
#pragma pack(push, 1) // Struct üyelerinin hizalanmasını sağlamak için
struct pcap_global_header {
uint32_t magic_number; // Magic number
uint16_t version_major; // Major version number
uint16_t version_minor; // Minor version number
int32_t thiszone; // GMT to local correction
uint32_t sigfigs; // Accuracy of timestamps
uint32_t snaplen; // Max length of captured packets, in octets
uint32_t network; // Data link type
};
struct pcap_packet_header {
uint32_t ts_sec; // Timestamp seconds
uint32_t ts_usec; // Timestamp microseconds
uint32_t incl_len; // Number of octets of packet saved in file
uint32_t orig_len; // Actual length of packet
};
struct ethernet_header {
uint8_t dest_mac[6];
uint8_t source_mac[6];
uint16_t ethertype;
};
struct ip_header {
unsigned char version_ihl;
unsigned char tos;
unsigned short total_length;
unsigned short identification;
unsigned short flags_fragment_offset;
unsigned char ttl;
unsigned char protocol;
unsigned short header_checksum;
uint32_t source_address;
uint32_t destination_address;
};
struct tcp_header {
unsigned short source_port;
unsigned short dest_port;
uint32_t sequence_number;
uint32_t ack_number;
unsigned char data_offset_reserved; // Üst 4 bit: data_offset, Alt 4 bit: reserved
unsigned char flags;
unsigned short window_size;
unsigned short checksum;
unsigned short urgent_pointer;
};
struct udp_header {
unsigned short source_port;
unsigned short dest_port;
unsigned short length;
unsigned short checksum;
};
#pragma pack(pop) // Struct hizalamasını geri almak için
// TCP segment yapısı
struct tcp_segment {
uint32_t seq_num;
std::vector<char> data;
};
// StreamKey yapısı
struct StreamKey {
uint32_t source_ip;
uint32_t dest_ip;
uint16_t source_port;
uint16_t dest_port;
bool operator==(const StreamKey& other) const {
return std::tie(source_ip, dest_ip, source_port, dest_port) ==
std::tie(other.source_ip, other.dest_ip, other.source_port, other.dest_port);
}
};
// Hash fonksiyonu StreamKey için
namespace std {
template <>
struct hash<StreamKey> {
std::size_t operator()(const StreamKey& k) const {
return ((std::hash<uint32_t>()(k.source_ip) ^
(std::hash<uint32_t>()(k.dest_ip) << 1)) >> 1) ^
((std::hash<uint16_t>()(k.source_port) << 1) >> 1) ^
(std::hash<uint16_t>()(k.dest_port) << 1);
}
};
}
// TCP Stream yapısı
struct tcp_stream {
uint32_t next_seq_num = 0;
std::vector<tcp_segment> segments;
std::vector<std::pair<time_t, size_t>> timings;
std::vector<char> buffer; // Yeniden düzenlenen veriyi tutmak için buffer
size_t parse_offset = 0; // Ayrıştırma için sonraki pozisyon
bool is_http = false;
std::string source_ip_str; // Eklenen üye
std::string dest_ip_str; // Eklenen üye
};
// PCAP işlemesi ve protokol ayrıştırma sınıfı
class PacketProcessor {
public:
PacketProcessor();
~PacketProcessor();
// Pcap dosyasını işleme fonksiyonu
void process_pcap_file(const std::string& filename);
// Paketi işleme fonksiyonu (PCAP ve Live Capture ile kullanılabilir)
void process_packet(const std::vector<char>& packet_data, std::ostream& output, time_t timestamp);
private:
// Benzersiz akışları saklamak için unordered_map kullanımı
std::unordered_map<StreamKey, tcp_stream> streams;
std::mutex stream_mutex; // Thread güvenliği için
// AnomalyDetector sınıfının örneği
class AnomalyDetector {
public:
AnomalyDetector();
~AnomalyDetector();
void log_anomaly(const std::string& anomaly_type, uint32_t /*source_ip*/, uint32_t /*dest_ip*/,
uint16_t /*source_port*/, uint16_t /*dest_port*/, size_t /*packet_size*/,
time_t /*timestamp*/, const std::string& /*src_ip_str*/, const std::string& /*dst_ip_str*/);
void process_packet(uint32_t source_ip, uint32_t dest_ip, uint16_t source_port,
uint16_t dest_port, size_t packet_size, time_t timestamp,
const std::string& src_ip_str, const std::string& dst_ip_str);
private:
struct IPStat {
size_t packet_count = 0;
size_t byte_count = 0;
std::deque<std::pair<time_t, size_t>> packet_times; // Paket zamanlarını tutmak için
};
size_t MAX_PACKETS_PER_IP = 1000;
size_t MAX_BYTES_PER_IP = 1000000;
// size_t RATE_THRESHOLD = 1000; // Paket/saniye (Kullanılmıyorsa yorum satırı yapıldı)
std::set<uint16_t> SUSPICIOUS_PORTS = {23, 2323, 23232, 443, 53, 80};
std::map<uint32_t, IPStat> ip_stats;
std::mutex stat_mutex;
// Veritabanı
sqlite3* db = nullptr;
void init_db(sqlite3** db_ptr);
bool is_suspicious_port(uint16_t port) const;
void reset_ip_stats(uint32_t ip);
};
AnomalyDetector anomaly_detector;
// IP adresini string'e çevirme fonksiyonu
std::string ip_to_string(uint32_t ip) const;
// TCP segment ekleme fonksiyonu
void add_segment(tcp_stream& stream, uint32_t seq_num, const std::vector<char>& segment_data);
// TLS record parsing fonksiyonu
bool parse_tls_record(const std::vector<char>& data, size_t& offset, std::vector<char>& record_data, uint8_t& content_type);
// TLS handshake message türleri
enum TLSHandshakeType {
HelloRequest = 0,
ClientHello = 1,
ServerHello = 2,
Certificate = 11,
ServerKeyExchange = 12,
CertificateRequest = 13,
ServerHelloDone = 14,
CertificateVerify = 15,
ClientKeyExchange = 16,
Finished = 20
};
// TLS handshake analizi fonksiyonu
void analyze_tls_packet(const std::vector<char>& buffer, size_t& parse_offset, tcp_stream& stream);
// Sertifika geçerlilik kontrol fonksiyonu
bool is_certificate_valid(X509* cert);
// HTTP paketlerini ayrıştırma ve analiz etme fonksiyonu
void analyze_http_packet(const std::vector<char>& buffer, size_t& parse_offset, tcp_stream& stream);
// UDP paketlerini ayrıştırma fonksiyonu
void parse_udp(const std::vector<char>& packet_data, std::ostream& output);
};
// Constructor
PacketProcessor::PacketProcessor() : anomaly_detector() {
// Constructor içeriği
}
// Destructor
PacketProcessor::~PacketProcessor() {
// Destructor içeriği
}
// IP adresini string'e çevirme fonksiyonu
std::string PacketProcessor::ip_to_string(uint32_t ip) const {
struct in_addr ip_addr;
ip_addr.s_addr = ip;
return std::string(inet_ntoa(ip_addr));
}
// TCP segment ekleme fonksiyonu
void PacketProcessor::add_segment(tcp_stream& stream, uint32_t seq_num, const std::vector<char>& segment_data) {
std::lock_guard<std::mutex> lock(stream_mutex);
if (stream.next_seq_num == 0 || seq_num == stream.next_seq_num) {
// İlk segment veya beklenen segment
if (stream.next_seq_num == 0) {
stream.next_seq_num = seq_num;
}
stream.buffer.insert(stream.buffer.end(), segment_data.begin(), segment_data.end());
stream.next_seq_num += static_cast<uint32_t>(segment_data.size());
// Sıradaki segmentleri kontrol et
auto it = stream.segments.begin();
while (it != stream.segments.end()) {
if (it->seq_num == stream.next_seq_num) {
stream.buffer.insert(stream.buffer.end(), it->data.begin(), it->data.end());
stream.next_seq_num += static_cast<uint32_t>(it->data.size());
it = stream.segments.erase(it);
} else {
++it;
}
}
} else if (seq_num > stream.next_seq_num) {
// Gelecekteki segment, sakla
tcp_segment new_segment{ seq_num, segment_data };
stream.segments.push_back(new_segment);
}
// Eski veya tekrarlanan segmentler göz ardı edilir
}
// TLS record parsing fonksiyonu
bool PacketProcessor::parse_tls_record(const std::vector<char>& data, size_t& offset, std::vector<char>& record_data, uint8_t& content_type) {
if (offset + 5 > data.size()) {
return false;
}
// Content Type
content_type = static_cast<uint8_t>(data[offset]);
// Version (bytes 1 ve 2)
// KULLANILMIYORSA ÇIKARDIK
// uint16_t version = (static_cast<uint8_t>(data[offset + 1]) << 8) | static_cast<uint8_t>(data[offset + 2]);
// Length (bytes 3 ve 4)
uint16_t length = (static_cast<uint8_t>(data[offset + 3]) << 8) | static_cast<uint8_t>(data[offset + 4]);
offset += 5;
if (offset + length > data.size()) {
return false;
}
record_data.assign(data.begin() + offset, data.begin() + offset + length);
offset += length;
return true;
}
// TLS handshake analizi fonksiyonu
void PacketProcessor::analyze_tls_packet(const std::vector<char>& buffer, size_t& parse_offset, tcp_stream& stream) {
std::cout << "analyze_tls_packet çağrıldı. Buffer Boyutu: " << buffer.size() << ", Parse Offset: " << parse_offset << std::endl;
size_t offset = parse_offset;
std::vector<char> record_data;
uint8_t content_type;
bool clientHelloFound = false;
while (parse_tls_record(buffer, offset, record_data, content_type)) {
std::cout << "Content Type: " << static_cast<int>(content_type) << std::endl;
if (content_type == 22) { // Handshake
std::cout << "TLS Handshake Record Detected. Size: " << record_data.size() << " bytes" << std::endl;
if (record_data.size() >= 4) { // handshake_type (1) + handshake_length (3)
TLSHandshakeType handshake_type = static_cast<TLSHandshakeType>(static_cast<uint8_t>(record_data[0]));
size_t current_offset = 4;
if (handshake_type == ClientHello) {
clientHelloFound = true;
std::cout << "Client Hello Message Found." << std::endl;
}
else if (handshake_type == Certificate && clientHelloFound) {
std::cout << "Server Certificate Message Found." << std::endl;
if (current_offset + 3 > record_data.size()) {
std::cerr << "Not enough data for certificate length." << std::endl;
continue;
}
size_t certificates_length = (static_cast<uint8_t>(record_data[current_offset]) << 16) |
(static_cast<uint8_t>(record_data[current_offset + 1]) << 8) |
static_cast<uint8_t>(record_data[current_offset + 2]);
current_offset += 3;
if (current_offset + certificates_length > record_data.size()) {
std::cerr << "Certificate data incomplete." << std::endl;
continue;
}
const unsigned char* cert_data = reinterpret_cast<const unsigned char*>(record_data.data() + current_offset);
const unsigned char* cert_data_end = cert_data + certificates_length;
const unsigned char* p = cert_data;
// Sertifikaları ayrıştır
while (p + 3 <= cert_data_end) { // En az 3 byte gereklidir
size_t cert_len = (p[0] << 16) | (p[1] << 8) | p[2];
p += 3;
if (p + cert_len > cert_data_end) {
std::cerr << "Certificate length exceeds available data." << std::endl;
break;
}
// X509 sertifikasını ayrıştır
X509* cert = d2i_X509(NULL, &p, cert_len);
if (cert) {
char* subject = X509_NAME_oneline(X509_get_subject_name(cert), NULL, 0);
char* issuer = X509_NAME_oneline(X509_get_issuer_name(cert), NULL, 0);
std::cout << "Certificate Subject: " << (subject ? subject : "Not Specified") << std::endl;
std::cout << "Certificate Issuer: " << (issuer ? issuer : "Not Specified") << std::endl;
ASN1_TIME* notBefore = X509_get_notBefore(cert);
ASN1_TIME* notAfter = X509_get_notAfter(cert);
// ASN1_TIME'ı okunabilir formata çevirme
BIO* bio = BIO_new(BIO_s_mem());
ASN1_TIME_print(bio, notBefore);
char notBeforeStr[64] = {0};
BIO_read(bio, notBeforeStr, sizeof(notBeforeStr) - 1);
BIO_free(bio);
bio = BIO_new(BIO_s_mem());
ASN1_TIME_print(bio, notAfter);
char notAfterStr[64] = {0};
BIO_read(bio, notAfterStr, sizeof(notAfterStr) - 1);
BIO_free(bio);
std::cout << "Validity Start: " << notBeforeStr << std::endl;
std::cout << "Validity End: " << notAfterStr << std::endl;
// Sertifika geçerliliğini kontrol et
if (!is_certificate_valid(cert)) {
anomaly_detector.log_anomaly("Sertifika Geçerlilik Hatası", 0, 0, 0, 0, 0, time(NULL), "Unknown", "Unknown");
}
OPENSSL_free(subject);
OPENSSL_free(issuer);
X509_free(cert);
}
else {
std::cerr << "Failed to parse certificate: " << ERR_error_string(ERR_get_error(), NULL) << std::endl;
break;
}
if (p >= cert_data_end) {
break;
}
}
clientHelloFound = false; // Gelecek ClientHello için sıfırla
}
}
time_t now = time(NULL);
stream.timings.emplace_back(now, record_data.size());
if (stream.timings.size() > 1) {
auto& last = stream.timings[stream.timings.size() - 2];
double delay = difftime(now, last.first);
std::cout << "Delay since last packet: " << delay
<< " seconds, Data Size: " << record_data.size()
<< " bytes" << std::endl;
}
}
}
// parse_offset'u güncelle
parse_offset = offset;
}
// Sertifika geçerlilik kontrol fonksiyonu
bool PacketProcessor::is_certificate_valid(X509* cert) {
time_t current_time = time(NULL);
if (X509_cmp_time(X509_get_notBefore(cert), ¤t_time) > 0 ||
X509_cmp_time(X509_get_notAfter(cert), ¤t_time) < 0) {
return false;
}
// Diğer geçerlilik kontrolleri eklenebilir
return true;
}
// HTTP paketlerini ayrıştırma ve analiz etme fonksiyonu
void PacketProcessor::analyze_http_packet(const std::vector<char>& buffer, size_t& parse_offset, tcp_stream& stream) {
std::cout << "analyze_http_packet çağrıldı. Buffer Boyutu: " << buffer.size() << ", Parse Offset: " << parse_offset << std::endl;
// Basit HTTP ayrıştırma (isteğin tamamen burada olduğunu varsayar)
if (parse_offset >= buffer.size()) {
return;
}
std::string data_str(buffer.begin() + parse_offset, buffer.end());
size_t end_of_headers = data_str.find("\r\n\r\n");
if (end_of_headers != std::string::npos) {
std::istringstream stream_data(data_str.substr(0, end_of_headers + 2));
std::string request_line;
std::getline(stream_data, request_line);
if (request_line.find("GET") != std::string::npos) {
size_t uri_start = request_line.find("GET") + 4;
size_t uri_end = request_line.find("HTTP");
if (uri_end > uri_start) {
std::string uri = request_line.substr(uri_start, uri_end - uri_start - 1);
std::cout << "HTTP GET Request URI: " << uri << std::endl;
// Şüpheli URI kontrolü
if (uri.find("malicious") != std::string::npos) {
anomaly_detector.log_anomaly("Şüpheli HTTP GET isteği", 0, 0, 0, 0, 0, time(NULL), "Unknown", "Unknown");
}
}
}
// parse_offset'u güncelle
parse_offset += end_of_headers + 4;
}
}
// UDP paketlerini ayrıştırma fonksiyonu
void PacketProcessor::parse_udp(const std::vector<char>& packet_data, std::ostream& output) {
size_t offset = 0;
// Ethernet başlığını atla (14 byte)
if (packet_data.size() < 14) {
std::cerr << "Insufficient data, cannot process Ethernet header." << std::endl;
return;
}
offset += 14;
if (packet_data.size() < offset + sizeof(ip_header) + sizeof(udp_header)) {
std::cerr << "Insufficient data, cannot process UDP packet." << std::endl;
return;
}
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data() + offset);
offset += (ip->version_ihl & 0x0F) * 4;
const udp_header* udp = reinterpret_cast<const udp_header*>(packet_data.data() + offset);
offset += sizeof(udp_header);
uint16_t source_port = ntohs(udp->source_port);
uint16_t dest_port = ntohs(udp->dest_port);
std::cerr << "UDP Source Port: " << source_port << ", Destination Port: " << dest_port << std::endl;
std::vector<char> udp_data(packet_data.begin() + offset, packet_data.end());
// Güvenli veri yazımı için kontrol ekleyebilirsiniz
std::string udp_data_str(udp_data.begin(), udp_data.end());
output << "UDP Data: " << udp_data_str << std::endl;
}
// process_packet fonksiyonunun tanımı
void PacketProcessor::process_packet(const std::vector<char>& packet_data, std::ostream& output, time_t timestamp) {
size_t offset = 0;
// Ethernet başlığını atla (14 byte)
if (packet_data.size() < 14) {
std::cerr << "Paket boyutu çok küçük, işlenemiyor." << std::endl;
return;
}
offset += 14;
if (packet_data.size() < offset + sizeof(ip_header)) {
std::cerr << "Paket boyutu çok küçük, işlenemiyor." << std::endl;
return;
}
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data() + offset);
unsigned int ip_header_len = (ip->version_ihl & 0x0F) * 4;
offset += ip_header_len;
uint32_t source_ip = ip->source_address;
uint32_t dest_ip = ip->destination_address;
std::string source_ip_str = ip_to_string(source_ip);
std::string dest_ip_str = ip_to_string(dest_ip);
if (ip->protocol == IPPROTO_TCP) {
if (packet_data.size() < offset + sizeof(tcp_header)) {
std::cerr << "Paket TCP başlığını içermiyor." << std::endl;
return;
}
const tcp_header* tcp = reinterpret_cast<const tcp_header*>(packet_data.data() + offset);
unsigned int tcp_header_len = ((tcp->data_offset_reserved >> 4) & 0x0F) * 4;
offset += tcp_header_len;
uint16_t source_port = ntohs(tcp->source_port);
uint16_t dest_port = ntohs(tcp->dest_port);
if (packet_data.size() < offset) {
std::cerr << "Paket TCP yükünü içermiyor." << std::endl;
return;
}
std::vector<char> tcp_payload(packet_data.begin() + offset, packet_data.end());
StreamKey key = {source_ip, dest_ip, source_port, dest_port};
std::lock_guard<std::mutex> lock(stream_mutex);
tcp_stream& stream = streams[key];
stream.source_ip_str = source_ip_str;
stream.dest_ip_str = dest_ip_str;
uint32_t seq_num = ntohl(tcp->sequence_number);
add_segment(stream, seq_num, tcp_payload);
// Anomali tespiti için paketi işleyin
anomaly_detector.process_packet(source_ip, dest_ip, source_port, dest_port, tcp_payload.size(), timestamp, source_ip_str, dest_ip_str);
// Protokol ayrıştırma ve analiz işlemleri
if (!stream.is_http && (source_port == 443 || dest_port == 443)) {
analyze_tls_packet(stream.buffer, stream.parse_offset, stream);
}
else {
analyze_http_packet(stream.buffer, stream.parse_offset, stream);
}
}
else if (ip->protocol == IPPROTO_UDP) {
parse_udp(packet_data, output);
}
else {
std::cerr << "Desteklenmeyen protokol: " << static_cast<int>(ip->protocol) << std::endl;
}
}
// Pcap dosyasını işleme fonksiyonu
void PacketProcessor::process_pcap_file(const std::string& filename) {
std::ifstream file(filename, std::ios::binary);
if (!file) {
std::cerr << "Could not open file: " << filename << std::endl;
return;
}
pcap_global_header global_header;
file.read(reinterpret_cast<char*>(&global_header), sizeof(global_header));
if (file.gcount() != sizeof(global_header)) {
std::cerr << "Incomplete global header." << std::endl;
return;
}
// Check magic number for endianess
bool is_little_endian = false;
if (global_header.magic_number == 0xa1b2c3d4) {
is_little_endian = false;
}
else if (global_header.magic_number == 0xd4c3b2a1) {
is_little_endian = true;
}
else {
std::cerr << "Invalid pcap file or unsupported format." << std::endl;
return;
}
while (file) {
pcap_packet_header packet_header;
file.read(reinterpret_cast<char*>(&packet_header), sizeof(packet_header));
if (file.gcount() != sizeof(packet_header)) {
break; // İnce paket veya dosya sonu
}
// Convert header fields to host byte order if little endian
if (is_little_endian) {
packet_header.ts_sec = ntohl(packet_header.ts_sec);
packet_header.ts_usec = ntohl(packet_header.ts_usec);
packet_header.incl_len = ntohl(packet_header.incl_len);
packet_header.orig_len = ntohl(packet_header.orig_len);
}
std::vector<char> packet_data(packet_header.incl_len);
file.read(packet_data.data(), packet_header.incl_len);
if (file.gcount() != packet_header.incl_len) {
std::cerr << "Incomplete packet data." << std::endl;
break;
}
time_t timestamp = packet_header.ts_sec;
process_packet(packet_data, std::cout, timestamp);
}
}
// ----------------------- AnomalyDetector Üye Fonksiyonlarının Tanımları -----------------------
// Constructor
PacketProcessor::AnomalyDetector::AnomalyDetector() {
init_db(&db);
}
// Destructor
PacketProcessor::AnomalyDetector::~AnomalyDetector() {
if (db) sqlite3_close(db);
}
// log_anomaly fonksiyonu
void PacketProcessor::AnomalyDetector::log_anomaly(const std::string& anomaly_type, uint32_t /*source_ip*/, uint32_t /*dest_ip*/,
uint16_t /*source_port*/, uint16_t /*dest_port*/, size_t /*packet_size*/,
time_t /*timestamp*/, const std::string& /*src_ip_str*/, const std::string& /*dst_ip_str*/) {
std::cerr << "[Anomali Tespit Edildi] " << anomaly_type << std::endl;
// Diğer uyarılar için benzer şekilde düzenleyebilirsiniz
// JSON loglama
json log_entry = {
{"anomaly_type", anomaly_type},
// Diğer alanlar burada dahil edilebilir
};
std::cout << log_entry.dump() << std::endl;
// Veritabanına kaydetme kısmı...
}
void PacketProcessor::AnomalyDetector::process_packet(uint32_t source_ip, uint32_t dest_ip, uint16_t source_port,
uint16_t dest_port, size_t packet_size, time_t timestamp,
const std::string& src_ip_str, const std::string& dst_ip_str) {
std::lock_guard<std::mutex> lock(stat_mutex);
// IP başına paket ve byte sayısını güncelle
IPStat& stat = ip_stats[source_ip];
stat.packet_count += 1;
stat.byte_count += packet_size;
stat.packet_times.emplace_back(timestamp, packet_size);
// Eski paketleri temizle (örneğin 60 saniye öncesi)
while (!stat.packet_times.empty() && difftime(timestamp, stat.packet_times.front().first) > 60) {
stat.packet_count -= 1;
stat.byte_count -= stat.packet_times.front().second;
stat.packet_times.pop_front();
}
// Eşik kontrolü
if (stat.packet_count > MAX_PACKETS_PER_IP) {
log_anomaly("Yüksek paket sayısı", source_ip, dest_ip, source_port, dest_port, packet_size, timestamp, src_ip_str, dst_ip_str);
reset_ip_stats(source_ip);
}
if (stat.byte_count > MAX_BYTES_PER_IP) {
log_anomaly("Yüksek byte sayısı", source_ip, dest_ip, source_port, dest_port, packet_size, timestamp, src_ip_str, dst_ip_str);
reset_ip_stats(source_ip);
}
// Şüpheli port kullanımı
if (is_suspicious_port(source_port) || is_suspicious_port(dest_port)) {
log_anomaly("Şüpheli port kullanımı", source_ip, dest_ip, source_port, dest_port, packet_size, timestamp, src_ip_str, dst_ip_str);
}
}
void PacketProcessor::AnomalyDetector::init_db(sqlite3** db_ptr) {
if (sqlite3_open("anomalies.db", db_ptr)) {
std::cerr << "Cannot open database: " << sqlite3_errmsg(*db_ptr) << std::endl;
*db_ptr = nullptr;
}
else {
const char* create_table_sql = "CREATE TABLE IF NOT EXISTS anomalies ("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"anomaly_type TEXT,"
"source_ip TEXT,"
"dest_ip TEXT,"
"source_port INTEGER,"
"dest_port INTEGER,"
"packet_size INTEGER,"
"timestamp TEXT);";
char* errmsg = nullptr;
if (sqlite3_exec(*db_ptr, create_table_sql, 0, 0, &errmsg) != SQLITE_OK) {
std::cerr << "SQL error: " << errmsg << std::endl;
sqlite3_free(errmsg);
}
}
}
bool PacketProcessor::AnomalyDetector::is_suspicious_port(uint16_t port) const {
return SUSPICIOUS_PORTS.find(port) != SUSPICIOUS_PORTS.end();
}
void PacketProcessor::AnomalyDetector::reset_ip_stats(uint32_t ip) {
ip_stats[ip].packet_count = 0;
ip_stats[ip].byte_count = 0;
while (!ip_stats[ip].packet_times.empty()) ip_stats[ip].packet_times.pop_front();
}
// ----------------------- Main Fonksiyon -----------------------
int main(int argc, char* argv[]) {
// OpenSSL'i başlat
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
// Argüman kontrolü
if (argc < 2) {
std::cerr << "Kullanım: " << argv[0] << " <pcap_dosyası>" << std::endl;
return 1;
}
std::string pcap_file = argv[1];
PacketProcessor packet_processor;
packet_processor.process_pcap_file(pcap_file);
// OpenSSL temizliği (opsiyonel)
EVP_cleanup();
ERR_free_strings();
return 0;
}