Merhaba kodu derleyip termuxda çalıştırdım ancak kodun çok… · The Chat Archive
Explore / Programming Merhaba kodu derleyip termuxda çalıştırdım ancak kodun çok küçük bir çıktısı görünüyor… Save Share Download ▾ ReportMerhaba kodu derleyip termuxda çalıştırdım ancak kodun çok küçük bir çıktısı görünüyor ve cxxdroididde çalıştırıncada hala pcap hatası alıyorum
(Bir kodda güncelleme yaparsan kodu tam şekilde sun)
Termuxda derlenip çalışan:~ $ clang++ -std=c++17 -Wall -Wextra -o analizator ~/storage/shared/Analizator/src/main.cpp \
-lpcap -lssl -lcrypto -lsqlite3 -lpthread
~ $ ./analizator /storage/emulated/0/Android/PCAPdroid_21_Agu_17_46_35.pcap
UDP Source Port: 23405, Destination Port: 53
UDP Data: �6mtalkgooglecom
UDP Source Port: 37531, Destination Port: 443
UDP Data: G�6�x�J��^K��3se�x�R�~�!g�\�'v*���S���<���
UDP Source Port: 34174, Destination Port: 53
UDP Data: mplay
googleapiscom
UDP Source Port: 53, Destination Port: 23405
UDP Data: �6��mtalkgooglecom�
�
mobile-gtalkl��.9J}��
cxxdroididde aldığım hata:/storage/emulated/0/Analizator/src/main.cpp:31:10: fatal error: 'pcap.h' file not found
#include <pcap.h> // PCAP için
^~~~~~~~
1 error generated.
Ana kod:// main.cpp
#include
#include
#include
#include
#include
#include <openssl/ssl.h>
#include <openssl/err.h>
#include <openssl/x509.h>
#include <openssl/pem.h>
#include
#include
#include
#include <arpa/inet.h> // ntohs ve ntohl için eklenmiştir
#include
#include
#include
#include <unordered_map>
#include
#include
#include
#include <condition_variable>
#include // std::istringstream için
#include // 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> // PCAP için
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 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;
};
Show full message · 782 lines Assistant2024-12-01 20:04 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 1 (2 messages)
Language tr
Conversation date Dec 1, 2024
Added to archive Nov 16, 2026
ID 01m7h42ajhk4q114t6gtsva1mfSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: b582e23a3bdde146799114bc7ccd0818
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
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 data;
};
// StreamKey yapısı
struct StreamKey {
uint32_t source_ip;
uint32_t dest_ip;
uint16_t source_port;
uint16_t dest_port;
code Copy code
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 {
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 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;
code Copy code
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();
code Copy code
// 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
code Copy code
// 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 = 100;
size_t MAX_BYTES_PER_IP = 100000;
// 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& segment_data) {
std::lock_guardstd::mutex lock(stream_mutex);
std::cerr << "Eklenecek Segment Seq Num: " << seq_num << ", Veri Boyutu: " << segment_data.size() << std::endl;
code Copy code
if (stream.next_seq_num == 0) {
// İlk segment
stream.buffer.insert(stream.buffer.end(), segment_data.begin(), segment_data.end());
stream.next_seq_num = seq_num + static_cast<uint32_t>(segment_data.size());
std::cerr << "İlk segment eklendi. Yeni next_seq_num: " << stream.next_seq_num << std::endl;
}
else if (seq_num == stream.next_seq_num) {
// Beklenen segment
stream.buffer.insert(stream.buffer.end(), segment_data.begin(), segment_data.end());
stream.next_seq_num += static_cast<uint32_t>(segment_data.size());
std::cerr << "Segment doğrudan ekleniyor. Yeni next_seq_num: " << stream.next_seq_num << std::endl;
// Buffer'da bekleyen segmentleri kontrol et
auto it = stream.segments.begin();
while (it != stream.segments.end()) {
if (it->seq_num == stream.next_seq_num) {
std::cerr << "Buffered segment ekleniyor. Seq Num: " << it->seq_num << ", Veri Boyutu: " << it->data.size() << std::endl;
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 };
auto it = std::lower_bound(stream.segments.begin(), stream.segments.end(), new_segment,
[](const tcp_segment& a, const tcp_segment& b) {
return a.seq_num < b.seq_num;
});
// Zaten yoksa ekle
if (it == stream.segments.end() || it->seq_num != seq_num) {
stream.segments.insert(it, new_segment);
std::cerr << "Segment gelecekteki segment olarak depolanıyor. Seq Num: " << seq_num << std::endl;
}
}
else {
// Tekrarlanan veya eski segment, göz ardı et
std::cerr << "Segment eski veya tekrarlanan, göz ardı ediliyor. Seq Num: " << seq_num << std::endl;
}
// TLS record parsing fonksiyonu
bool PacketProcessor::parse_tls_record(const std::vector& data, size_t& offset, std::vector& record_data, uint8_t& content_type) {
if (offset + 5 > data.size()) {
return false;
}
code Copy code
// 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& 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;
code Copy code
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& 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;
code Copy code
// 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& packet_data, std::ostream& output) {
if (packet_data.size() < sizeof(ip_header) + sizeof(udp_header)) {
std::cerr << "Insufficient data, cannot process UDP packet." << std::endl;
return;
}
code Copy code
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data());
const udp_header* udp = reinterpret_cast<const udp_header*>(packet_data.data() + (ip->version_ihl & 0x0F) * 4);
std::cerr << "UDP Source Port: " << ntohs(udp->source_port) << ", Destination Port: " << ntohs(udp->dest_port) << std::endl;
std::vector<char> udp_data(packet_data.begin() + ((ip->version_ihl & 0x0F) * 4) + sizeof(udp_header), 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& packet_data, std::ostream& output, time_t timestamp) {
if (packet_data.size() < sizeof(ip_header)) {
std::cerr << "Paket boyutu çok küçük, işlenemiyor." << std::endl;
return;
}
code Copy code
const ip_header* ip = reinterpret_cast<const ip_header*>(packet_data.data());
unsigned int ip_header_len = (ip->version_ihl & 0x0F) * 4;
if (ip_header_len < sizeof(ip_header)) {
std::cerr << "Geçersiz IP başlık uzunluğu: " << ip_header_len << std::endl;
return;
}
if (packet_data.size() < ip_header_len + sizeof(tcp_header)) {
std::cerr << "Paket boyutu TCP/UDP başlığını içermiyor." << std::endl;
return;
}
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) {
const tcp_header* tcp = reinterpret_cast<const tcp_header*>(packet_data.data() + ip_header_len);
unsigned int tcp_header_len = ((tcp->data_offset_reserved >> 4) & 0x0F) * 4;
if (tcp_header_len < sizeof(tcp_header)) {
std::cerr << "Geçersiz TCP başlık uzunluğu: " << tcp_header_len << std::endl;
return;
}
uint16_t source_port = ntohs(tcp->source_port);
uint16_t dest_port = ntohs(tcp->dest_port);
size_t tcp_payload_offset = ip_header_len + tcp_header_len;
if (packet_data.size() < tcp_payload_offset) {
std::cerr << "Paket TCP yükünü içermiyor." << std::endl;
return;
}
std::vector<char> tcp_payload(packet_data.begin() + tcp_payload_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;
}
code Copy code
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
code Copy code
// 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_guardstd::mutex lock(stat_mutex);
code Copy code
// 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();
code Copy code
// 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;
Merhaba!
Anladığım kadarıyla kodunuzu Termux'da başarıyla derleyip çalıştırmışsınız, ancak çıktısı beklediğinizden daha az ve anlaşılmaz görünüyor. Ayrıca, Cxxdroid'de derlemeye çalışırken 'pcap.h' file not found hatası alıyorsunuz.
Cxxdroid'de 'pcap.h' Hatası:
Cxxdroid uygulaması, Android üzerinde çalışan bir C++ geliştirme ortamıdır ancak varsayılan olarak tüm kütüphaneleri içermez. Özellikle, pcap.h gibi ağ paketlerini yakalamak ve işlemek için kullanılan libpcap kütüphanesi Cxxdroid'de bulunmamaktadır. Bu nedenle, aşağıdaki hata ile karşılaşıyorsunuz:
code Copy code
fatal error: 'pcap.h' file not found
#include <pcap.h> // PCAP için
^~~~~~~~
Çözüm:
Ne yazık ki, Cxxdroid'de ek kütüphaneleri yüklemek oldukça sınırlıdır ve genellikle bu tür sistem kütüphanelerini ekleyemezsiniz. Bu durumda, aşağıdaki seçenekleri değerlendirebilirsiniz:
Termux Kullanımı:
Termux, Android üzerinde daha tam teşekküllü bir Linux ortamı sunar ve libpcap gibi kütüphaneleri yükleyebilirsiniz.
Kodunuzu Termux üzerinde geliştirmeye devam edebilir ve apt paket yöneticisi ile gerekli kütüphaneleri yükleyebilirsiniz.
Örneğin, libpcap kütüphanesini yüklemek için:
code Copy code
pkg install libpcap-dev
Masaüstü Bilgisayar veya Sanal Makine:
Eğer mümkünse, kodunuzu bir masaüstü Linux dağıtımında geliştirmeniz daha kolay olacaktır.
Gerekli tüm kütüphaneleri yükleyebilir ve kapsamlı bir geliştirme ortamı kullanabilirsiniz.
Termux'da Çıktının Küçük ve Anlaşılmaz Olması:
Termux'da kodunuzu derleyip çalıştırdığınızda, çıktının beklediğinizden daha az ve anlaşılmaz olduğunu belirtmişsiniz. Örneğin:
code Copy code
UDP Source Port: 23405, Destination Port: 53
UDP Data: �6mtalkgooglecom
...
Bu durumda, kodunuz paketleri okuyor ancak verileri doğru şekilde işleyemiyor olabilir. Bazı nedenler ve çözümler:
Ham Verinin Doğrudan Yazdırılması:
UDP veya TCP paketlerinden alınan veriler genellikle ikili (binary) veridir.
Bu verileri doğrudan std::string veya std::cout ile yazdırmak, konsolda anlaşılmaz karakterlere neden olabilir.
Çözüm: Paket verilerini heksadesimal formatta veya insan tarafından okunabilir bir biçimde yazdırın.
Örneğin, UDP Data yazdırma kısmını şu şekilde güncelleyebilirsiniz:
cpp Copy code
// UDP verisini heksadesimal olarak yazdırma
std::ostringstream oss;
for (unsigned char c : udp_data) {
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(c);
}
output << "UDP Data (Hex): " << oss.str() << std::endl;
DNS veya HTTP Gibi Üst Seviye Protokolleri Ayrıştırma:
Eğer UDP port 53 trafiği (DNS) veya TCP port 80/443 trafiği (HTTP/HTTPS) analiz ediyorsanız, üst seviye protokolleri ayrıştırmak verilerin anlaşılmasını kolaylaştırır.
Çözüm: Paket verilerini DNS, HTTP veya TLS protokollerine göre ayrıştırın ve ilgili alanları yazdırın.
Örneğin, DNS sorgularını ve yanıtlarını ayrıştırmak için ek bir işlev ekleyebilirsiniz.
Endianess ve Byte Ordering:
Farklı mimarilerde byte sıralaması (endianness) sorunları olabilir.
Çözüm: ntohs, ntohl gibi fonksiyonları kullanarak ağ byte sıralamasını host byte sıralamasına çevirin.
Kodunuzun Güncellenmiş Hali:
Aşağıda, çıktıyı daha anlaşılır hale getirmek için bazı değişiklikler yaptım. Özellikle, UDP verilerini heksadesimal olarak yazdırdım ve paket boyutlarını kontrol ettim.
cpp Copy code
// parse_udp fonksiyonu güncellendi
void PacketProcessor::parse_udp(const std::vector<char>& packet_data, std::ostream& output) {
if (packet_data.size() < 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());
unsigned int ip_header_len = (ip->version_ihl & 0x0F) * 4;
if (packet_data.size() < ip_header_len + sizeof(udp_header)) {
std::cerr << "Insufficient data, cannot process UDP packet." << std::endl;
return;
}
const udp_header* udp = reinterpret_cast<const udp_header*>(packet_data.data() + ip_header_len);
uint16_t source_port = ntohs(udp->source_port);
uint16_t dest_port = ntohs(udp->dest_port);
output << "UDP Source Port: " << source_port << ", Destination Port: " << dest_port << std::endl;
size_t udp_payload_offset = ip_header_len + sizeof(udp_header);
if (packet_data.size() < udp_payload_offset) {
std::cerr << "No UDP payload." << std::endl;
return;
}
std::vector<char> udp_data(packet_data.begin() + udp_payload_offset, packet_data.end());
// UDP verisini heksadesimal olarak yazdırma
std::ostringstream oss;
for (unsigned char c : udp_data) {
oss << std::hex << std::setw(2) << std::setfill('0') << static_cast<int>(c);
}
output << "UDP Data (Hex): " << oss.str() << std::endl;
}
Benzer şekilde, TCP paketleri için de çıktıyı daha anlaşılır hale getirebiliriz.
Ek Olarak:
Protokol Ayrıştırma: Eğer belirli bir protokolü (örneğin DNS veya HTTP) ayrıştırmak istiyorsanız, ilgili protokolün paket yapısını kodunuza ekleyebilir ve verileri daha ayrıntılı yazdırabilirsiniz.
Hata Ayıklama Mesajları: Kodunuzda çok sayıda std::cerr kullanımı mevcut. Bunları gerektiğinde aktifleştirip pasifleştirecek şekilde düzenleyebilirsiniz.
Thread Güvenliği ve Mutex Kullanımı: Kodunuzda çoklu iş parçacığı (thread) ve mutex kullanımı mevcut. Eğer kod tek iş parçacığında çalışıyorsa, bu kısımları sadeleştirebilirsiniz.
Sonuç:
Cxxdroid'de pcap.h Hatası: Maalesef Cxxdroid'de pcap.h ve ilgili kütüphaneleri eklemek mümkün olmadığı için, kodunuzu Termux veya masaüstü bir ortamda geliştirmeye devam etmeniz daha uygun olacaktır.
Termux'da Çıktının Anlaşılır Olması: Kodunuzu yukarıdaki öneriler doğrultusunda güncelleyerek, çıktının daha anlaşılır ve veri odaklı olmasını sağlayabilirsiniz.
Tam Kodun Sunulması: Kodunuzun tamamını eklediğiniz için teşekkür ederim. Bu şekilde sorunu daha iyi analiz edebildik.
Eğer başka sorularınız veya ihtiyaçlarınız olursa lütfen yazın, birlikte çözmeye çalışalım!
Copy first response
Not yet included in a published release.