Merhaba,
CxxDroid IDE'sinde çalıştırdığınızda programınıza komut satırı argümanları verilemiyor. Bu nedenle argc < 2 koşulu sağlanıyor ve program kullanım mesajını yazdırıp çıkıyor.
Bu sorunu çözmek için, programınızı komut satırı argümanı yerine doğrudan analiz etmek istediğiniz pcap dosyasını kullanacak şekilde düzenleyebilirsiniz. Yani, main fonksiyonunuzdaki argüman kontrolünü kaldırıp doğrudan dosya yolunu belirtebilirsiniz.
Aşağıdaki adımları izleyerek kodunuzu düzenleyebilirsiniz:
-
main Fonksiyonunu Değiştirin:
Mevcut main fonksiyonunuzu aşağıdaki gibi değiştirin:
int main() {
// OpenSSL'i başlat
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
// Analiz etmek istediğiniz pcap dosyasının yolunu burada belirtin
std::string pcap_file = "storage/shared/Download/PCAPdroid/PCAPdroid_19_Kas_17_14_35.pcap";
PacketProcessor packet_processor;
packet_processor.process_pcap_file(pcap_file);
// OpenSSL temizliği (opsiyonel)
EVP_cleanup();
ERR_free_strings();
return 0;
}
-
Dosya Yolunu Kontrol Edin:
Dosya yolunun doğru olduğundan emin olun. CxxDroid'de dosya sistemine erişim sınırlı olabilir. Eğer programa dosya yolu erişimi vermekte sorun yaşıyorsanız, pcap dosyasını programınızın çalıştığı dizine veya izin verilen bir dizine kopyalayarak yolu buna göre güncelleyebilirsiniz:
std::string pcap_file = "PCAPdroid_19_Kas_17_14_35.pcap";
Ve pcap dosyanızı CxxDroid'in proje dizinine kopyalayın.
-
Argüman Kontrolünü Kaldırın:
Argüman kontrolünü kaldırdığımız için, artık argc ve argv kullanılmayacak. Bu nedenle main fonksiyonunuzun imzasını int main() olarak değiştirdik.
-
Programınızı Çalıştırın:
Kodunuzu kaydettikten sonra CxxDroid'de programınızı çalıştırın. Artık programınız belirtilen pcap dosyasını analiz edecektir.
Notlar:
- Eğer dosya yolu veya dosya erişimi ile ilgili sorunlar yaşarsanız, CxxDroid'in hangi dizinlere erişebildiğini kontrol edin ve dosyanızı uygun bir yere koyun.
- OpenSSL ve diğer kütüphanelerin CxxDroid'de düzgün çalıştığından emin olun. Gerekli kütüphanelerin kurulumu veya yapılandırılması gerekebilir.
- CxxDroid'de bazı kitaplıklar ve fonksiyonlar tam desteklenmeyebilir. Özellikle
sqlite3.h veya openssl ile ilgili derleme sorunları yaşarsanız, bu kısımları yorum satırı yaparak veya kaldırarak deneme yapabilirsiniz.
Düzenlenmiş Kodu Tekrar Paylaşıyorum:
#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 {
uint8_t version_ihl;
uint8_t tos;
uint16_t total_length;
uint16_t identification;
uint16_t flags_fragment_offset;
uint8_t ttl;
uint8_t protocol;
uint16_t header_checksum;
uint32_t source_address;
uint32_t destination_address;
};
struct tcp_header {
uint16_t source_port;
uint16_t dest_port;
uint32_t sequence_number;
uint32_t ack_number;
uint8_t data_offset_reserved;
uint8_t flags;
uint16_t window_size;
uint16_t checksum;
uint16_t urgent_pointer;
};
struct udp_header {
uint16_t source_port;
uint16_t dest_port;
uint16_t length;
uint16_t 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, uint32_t linktype);
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, uint32_t linktype);
};
// 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));
}
// Byte sıralamasını tersine çeviren fonksiyonlar
uint32_t swap_uint32(uint32_t val) {
return ((val & 0x000000FFU) << 24) |
((val & 0x0000FF00U) << 8) |
((val & 0x00FF0000U) >> 8) |
((val & 0xFF000000U) >> 24);
}
uint16_t swap_uint16(uint16_t val) {
return (val << 8) | (val >> 8);
}
// 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]);
// 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, uint32_t linktype) {
size_t offset = 0;
// Bağlantı katmanı tipine göre işlem
if (linktype == 1) { // DLT_EN10MB, Ethernet
// 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;
} else if (linktype == 101) { // DLT_RAW, RAW IP
// Ethernet başlığı yok, doğrudan IP başlığına geç
offset += 0;
} else if (linktype == 0) { // DLT_NULL veya diğerleri
// Loopback veya NULL başlığı (genellikle 4 bayt)
if (packet_data.size() < 4) {
std::cerr << "Paket boyutu çok küçük, işlenemiyor." << std::endl;
return;
}
offset += 4;
} else {
std::cerr << "Desteklenmeyen link-layer tipi: " << linktype << std::endl;
return;
}
if (packet_data.size() < offset + sizeof(ip_header)) {
std::cerr << "Insufficient data, cannot process IP header." << std::endl;
return;
}
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data() + offset);
// Endian dönüşümleri
uint16_t total_length = ntohs(ip->total_length);
uint16_t identification = ntohs(ip->identification);
uint16_t flags_fragment_offset = ntohs(ip->flags_fragment_offset);
uint16_t header_checksum = ntohs(ip->header_checksum);
uint32_t source_ip = ntohl(ip->source_address);
uint32_t dest_ip = ntohl(ip->destination_address);
unsigned int ip_header_len = (ip->version_ihl & 0x0F) * 4;
offset += ip_header_len;
if (packet_data.size() < offset + sizeof(udp_header)) {
std::cerr << "Insufficient data, cannot process UDP header." << std::endl;
return;
}
const udp_header* udp = reinterpret_cast<const udp_header*>(packet_data.data() + offset);
// Endian dönüşümleri
uint16_t source_port = ntohs(udp->source_port);
uint16_t dest_port = ntohs(udp->dest_port);
uint16_t length = ntohs(udp->length);
uint16_t checksum = ntohs(udp->checksum);
offset += sizeof(udp_header);
std::cerr << "UDP Source Port: " << source_port << ", Destination Port: " << dest_port << std::endl;
if (packet_data.size() < offset) {
std::cerr << "No UDP payload available." << std::endl;
return;
}
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, uint32_t linktype) {
size_t offset = 0;
// Bağlantı katmanı tipine göre paket başlangıcını ayarla
if (linktype == 1) { // DLT_EN10MB, Ethernet
// 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;
} else if (linktype == 101) { // DLT_RAW, RAW IP
// Ethernet başlığı yok, doğrudan IP başlığına geç
offset += 0;
} else if (linktype == 0) { // DLT_NULL veya diğerleri
// Loopback veya NULL başlığı (genellikle 4 bayt)
if (packet_data.size() < 4) {
std::cerr << "Paket boyutu çok küçük, işlenemiyor." << std::endl;
return;
}
offset += 4;
} else {
std::cerr << "Desteklenmeyen link-layer tipi: " << linktype << std::endl;
return;
}
if (packet_data.size() < offset + sizeof(ip_header)) {
std::cerr << "Paket boyutu çok küçük, IP başlığı işlenemiyor." << std::endl;
return;
}
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data() + offset);
// Version ve IHL (Internet Header Length)
unsigned int ip_header_len = (ip->version_ihl & 0x0F) * 4;
// Protokol numarası
uint8_t protocol = ip->protocol;
// Endian dönüşümleri
uint16_t total_length = ntohs(ip->total_length);
uint16_t identification = ntohs(ip->identification);
uint16_t flags_fragment_offset = ntohs(ip->flags_fragment_offset);
uint16_t header_checksum = ntohs(ip->header_checksum);
uint32_t source_ip = ntohl(ip->source_address);
uint32_t dest_ip = ntohl(ip->destination_address);
// Debugging için protokol numarasını yazdıralım
std::cout << "Processing packet with IP Protocol: " << static_cast<int>(protocol) << std::endl;
// Offset'i güncelle
offset += ip_header_len;
std::string source_ip_str = ip_to_string(source_ip);
std::string dest_ip_str = ip_to_string(dest_ip);
if (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;
// Endian dönüşümleri
uint16_t source_port = ntohs(tcp->source_port);
uint16_t dest_port = ntohs(tcp->dest_port);
uint32_t seq_num = ntohl(tcp->sequence_number);
uint32_t ack_num = ntohl(tcp->ack_number);
uint16_t window_size = ntohs(tcp->window_size);
uint16_t checksum = ntohs(tcp->checksum);
uint16_t urgent_pointer = ntohs(tcp->urgent_pointer);
// TCP header bilgilerini yazdırma
std::cout << "TCP Packet - Source Port: " << source_port << ", Destination Port: " << dest_port << std::endl;
std::cout << "Sequence Number: " << seq_num << ", Acknowledgment Number: " << ack_num << std::endl;
offset += tcp_header_len;
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;
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, stream.source_ip_str, stream.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 (protocol == IPPROTO_UDP) {
parse_udp(packet_data, output, linktype);
}
else {
std::cerr << "Desteklenmeyen protokol: " << static_cast<int>(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 << "Dosya açılamadı: " << 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 << "Eksik global header." << std::endl;
return;
}
// Endianess kontrolü ve gerekiyorsa dönüşüm
bool is_swapped = false;
if (global_header.magic_number == 0xa1b2c3d4) {
is_swapped = false; // Big endian
}
else if (global_header.magic_number == 0xd4c3b2a1) {
is_swapped = true; // Little endian
// Tüm header alanlarını dönüştürmemiz gerekiyor
global_header.version_major = swap_uint16(global_header.version_major);
global_header.version_minor = swap_uint16(global_header.version_minor);
global_header.thiszone = static_cast<int32_t>(swap_uint32(static_cast<uint32_t>(global_header.thiszone)));
global_header.sigfigs = swap_uint32(global_header.sigfigs);
global_header.snaplen = swap_uint32(global_header.snaplen);
global_header.network = swap_uint32(global_header.network);
}
else {
std::cerr << "Geçersiz pcap dosyası veya desteklenmeyen format." << std::endl;
return;
}
uint32_t linktype = global_header.network;
std::cout << "Link-layer type: " << linktype << std::endl;
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
}
// Endianess dönüşümü
if (is_swapped) {
packet_header.ts_sec = swap_uint32(packet_header.ts_sec);
packet_header.ts_usec = swap_uint32(packet_header.ts_usec);
packet_header.incl_len = swap_uint32(packet_header.incl_len);
packet_header.orig_len = swap_uint32(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() != static_cast<std::streamsize>(packet_header.incl_len)) {
std::cerr << "Eksik paket verisi." << std::endl;
break;
}
time_t timestamp = packet_header.ts_sec;
process_packet(packet_data, std::cout, timestamp, linktype);
}
}
// ----------------------- 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 << "Veritabanı açılamadı: " << 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 hatası: " << 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() {
// OpenSSL'i başlat
SSL_library_init();
OpenSSL_add_all_algorithms();
SSL_load_error_strings();
// Analiz etmek istediğiniz pcap dosyasının yolunu burada belirtin
std::string pcap_file = "storage/shared/Download/PCAPdroid/PCAPdroid_19_Kas_17_14_35.pcap";
PacketProcessor packet_processor;
packet_processor.process_pcap_file(pcap_file);
// OpenSSL temizliği (opsiyonel)
EVP_cleanup();
ERR_free_strings();
return 0;
}
Umarım bu düzenleme ile sorununuz çözülür. İyi çalışmalar!