Logger System 0.1.3
High-performance C++20 thread-safe logging system with asynchronous capabilities
Loading...
Searching...
No Matches
security_demo.cpp
Go to the documentation of this file.
1// BSD 3-Clause License
2// Copyright (c) 2024, 🍀☀🌕🌥 🌊
3// See the LICENSE file in the project root for full license information.
4
20// #include <kcenon/logger/security/log_sanitizer.h> // TODO: Not implemented yet
21// #include <kcenon/logger/structured/structured_logger.h> // TODO: Not implemented yet
23// #include <kcenon/logger/routing/log_router.h> // TODO: Not implemented yet
26#include <kcenon/common/interfaces/logger_interface.h>
27
28#include <iostream>
29#include <thread>
30#include <chrono>
31#include <regex>
32
33using namespace kcenon::logger;
35namespace ci = kcenon::common::interfaces;
36using namespace std::chrono_literals;
37
38// Custom security filter that blocks sensitive logs
40public:
41 bool should_log(const log_entry& entry) const override {
42 const std::string message = entry.message.to_string();
43
44 // Block logs containing passwords
45 if (message.find("password") != std::string::npos) {
46 std::cout << "[SECURITY] Blocked log containing password" << std::endl;
47 return false;
48 }
49 return true;
50 }
51
52 std::string get_name() const override {
53 return "security_filter";
54 }
55};
56
58 std::cout << "\n=== Log Sanitization Demo ===" << std::endl;
59
60 auto sanitizer = std::make_shared<log_sanitizer>();
61
62 // Test various sensitive data patterns
63 std::vector<std::string> test_messages = {
64 "Credit card payment: 4532-1234-5678-9012",
65 "User SSN: 123-45-6789",
66 "Contact email: john.doe@example.com",
67 "Server IP: 192.168.1.100",
68 "API_KEY=example_test_key_1234567890",
69 "Login with password=SuperSecret123!",
70 "Multiple cards: 5555-4444-3333-2222 and 4111111111111111",
71 "Mixed data: email admin@test.com from 10.0.0.1 with key=abcd1234efgh5678"
72 };
73
74 std::cout << "\nOriginal vs Sanitized messages:" << std::endl;
75 std::cout << std::string(80, '-') << std::endl;
76
77 for (const auto& msg : test_messages) {
78 std::string sanitized = sanitizer->sanitize(msg);
79 std::cout << "Original: " << msg << std::endl;
80 std::cout << "Sanitized: " << sanitized << std::endl;
81 std::cout << std::endl;
82 }
83}
84
86 std::cout << "\n=== Security Logging Demo ===" << std::endl;
87
88 auto logger = std::make_shared<logger_module::logger>();
89 auto sanitizer = std::make_shared<log_sanitizer>();
90
91 // Add security filter
92 auto sec_filter = std::make_unique<security_filter>();
93 logger->set_filter(std::move(sec_filter));
94
95 // Simulate security events
96 std::cout << "\nLogging security events (sensitive data will be sanitized):" << std::endl;
97
98 // This will be blocked by the security filter
99 logger->log(ci::log_level::warning,
100 std::string("User login attempt with password=admin123"));
101
102 // These will be logged but sanitized
103 logger->log(ci::log_level::warning,
104 sanitizer->sanitize("Suspicious activity from IP 192.168.1.100"));
105
106 logger->log(ci::log_level::warning,
107 sanitizer->sanitize("Failed login for email user@example.com"));
108
109 logger->log(ci::log_level::error,
110 sanitizer->sanitize("Data breach detected: SSN 123-45-6789 exposed"));
111
112 logger->log(ci::log_level::critical,
113 sanitizer->sanitize("API key compromised: key=EXAMPLE_KEY_12345"));
114}
115
117 std::cout << "\n=== Encryption Demo ===" << std::endl;
118
119 auto logger = std::make_shared<logger_module::logger>();
120
121 // Add encrypted file writer
122 logger->add_writer(std::make_unique<file_writer>("security_encrypted.log"));
123
124 logger->log(ci::log_level::info,
125 std::string("This message will be written to an encrypted log file"));
126
127 logger->log(ci::log_level::warning,
128 std::string("Sensitive operations are logged securely"));
129
130 std::cout << "Messages written to encrypted log file: security_encrypted.log" << std::endl;
131}
132
134 std::cout << "\n=== Audit Trail Demo ===" << std::endl;
135
136 auto logger = std::make_shared<logger_module::logger>();
137
138 // Create audit logger (separate from main logger)
139 auto audit_writer = std::make_unique<file_writer>("audit_trail.log");
140 logger->add_writer("audit", std::move(audit_writer));
141
142 // Configure routing for audit trail
143 auto& router = logger->get_router();
144 // Note: Router configuration would be done here if needed
145
146 // Simulate various events
147 logger->log(ci::log_level::info, std::string("Normal operation"));
148 logger->log(ci::log_level::warning, std::string("High CPU usage"));
149 logger->log(ci::log_level::critical, std::string("Security breach detected"));
150 logger->log(ci::log_level::critical, std::string("Unauthorized access attempt"));
151 logger->log(ci::log_level::error, std::string("Database connection failed"));
152
153 std::cout << "Audit events written to: audit_trail.log" << std::endl;
154}
155
157 std::cout << "\n=== Compliance Logging Demo ===" << std::endl;
158
159 auto base_logger = std::make_shared<logger_module::logger>();
160 auto structured = std::make_shared<structured_logger>(base_logger);
161 auto sanitizer = std::make_shared<log_sanitizer>();
162
163 // GDPR-compliant user data access log
164 structured->info(sanitizer->sanitize("User data access"))
165 .field("user_id", "USR-12345")
166 .field("accessed_by", "ADMIN-001")
167 .field("data_type", "personal_information")
168 .field("purpose", "support_request")
169 .field("timestamp", std::chrono::system_clock::now())
170 .field("ip_address", sanitizer->sanitize("192.168.1.50"))
171 .commit();
172
173 // PCI compliance - payment processing
174 structured->info(sanitizer->sanitize("Payment processed"))
175 .field("transaction_id", "TXN-98765")
176 .field("amount", 150.00)
177 .field("currency", "USD")
178 .field("card_last_four", "9012") // Only last 4 digits
179 .field("status", "success")
180 .commit();
181
182 // HIPAA compliance - healthcare data access
183 structured->warning(sanitizer->sanitize("Medical record accessed"))
184 .field("patient_id", "PAT-55555") // Anonymized ID
185 .field("accessed_by", "DOC-777")
186 .field("record_type", "lab_results")
187 .field("compliance", "HIPAA")
188 .commit();
189}
190
192 std::cout << "\n=== Intrusion Detection Demo ===" << std::endl;
193
194 auto logger = std::make_shared<logger_module::logger>();
195 auto structured = std::make_shared<structured_logger>(logger);
196 auto sanitizer = std::make_shared<log_sanitizer>();
197
198 // Simulate suspicious activities
199 structured->warning(sanitizer->sanitize("Multiple failed login attempts"))
200 .field("source_ip", sanitizer->sanitize("10.0.0.100"))
201 .field("target_user", "admin")
202 .field("attempts", 5)
203 .field("time_window", "60s")
204 .commit();
205
206 structured->critical(sanitizer->sanitize("Potential SQL injection detected"))
207 .field("endpoint", "/api/users")
208 .field("payload", sanitizer->sanitize("'; DROP TABLE users; --"))
209 .field("blocked", true)
210 .commit();
211
212 structured->error(sanitizer->sanitize("Unauthorized API access"))
213 .field("api_key", sanitizer->sanitize("api_key=example_api_key_abcdefgh123456"))
214 .field("endpoint", "/api/v1/sensitive-data")
215 .field("blocked", true)
216 .commit();
217
218 structured->critical(sanitizer->sanitize("Port scan detected"))
219 .field("source_ip", sanitizer->sanitize("203.0.113.0"))
220 .field("ports_scanned", 1000)
221 .field("duration", "120s")
222 .field("action", "ip_blocked")
223 .commit();
224}
225
227 std::cout << "\n=== Security Metrics Demo ===" << std::endl;
228
229 auto logger = std::make_shared<logger_module::logger>();
230 logger->enable_metrics_collection(true);
231
232 // Get security-related metrics
233 auto metrics_result = logger->get_current_metrics();
234
235 std::cout << "\nSecurity Logging Metrics:" << std::endl;
236 if (metrics_result) {
237 auto& metrics = metrics_result.value();
238 std::cout << "Total logs: " << metrics.messages_enqueued.load() << std::endl;
239 std::cout << "Messages per second: " << metrics.get_messages_per_second() << std::endl;
240 std::cout << "Average enqueue time: " << metrics.get_avg_enqueue_time_ns() << " ns" << std::endl;
241
242 // Calculate security event rate (simplified for demo)
243 auto duration = 1;
244
245 if (duration > 0) {
246 double message_rate = metrics.get_messages_per_second();
247 std::cout << "\nMessage rate: " << message_rate << " msgs/sec" << std::endl;
248
249 if (message_rate > 1000.0) {
250 logger->log(ci::log_level::critical,
251 std::string("High message rate detected!"));
252 }
253 }
254 } else {
255 std::cout << "Failed to get metrics" << std::endl;
256 }
257}
258
259int main() {
260 try {
261 std::cout << "=== Security Features Demo ===" << std::endl;
262 std::cout << "Demonstrating logger security capabilities\n" << std::endl;
263
264 // Create and configure logger
265 auto logger = std::make_shared<logger_module::logger>();
266 logger->set_level(ci::log_level::debug);
267 logger->start();
268
269 // Add console output for demo
270 logger->add_writer(std::make_unique<console_writer>());
271
272 // Run demonstrations
274 std::this_thread::sleep_for(100ms);
275
277 std::this_thread::sleep_for(100ms);
278
280 std::this_thread::sleep_for(100ms);
281
283 std::this_thread::sleep_for(100ms);
284
286 std::this_thread::sleep_for(100ms);
287
289 std::this_thread::sleep_for(100ms);
290
292
293 // Cleanup
294 logger->stop();
295 logger->flush();
296
297 std::cout << "\n=== Security Demo Complete ===" << std::endl;
298 std::cout << "Check the following files for results:" << std::endl;
299 std::cout << "- security_encrypted.log (encrypted messages)" << std::endl;
300 std::cout << "- audit_trail.log (critical security events)" << std::endl;
301
302 } catch (const std::exception& e) {
303 std::cerr << "Error: " << e.what() << std::endl;
304 return 1;
305 }
306
307 return 0;
308}
std::string to_string() const
Convert to std::string.
std::string get_name() const override
Get the name of this filter.
bool should_log(const log_entry &entry) const override
Check if a log entry should be processed.
Console writer for logging to stdout/stderr.
File writer for logging to files with optional buffering.
Interface for log filters used by filtered_logger.
High-performance, thread-safe logging system with asynchronous capabilities.
void demonstrate_compliance_logging()
void demonstrate_intrusion_detection()
void demonstrate_encryption()
void demonstrate_log_sanitization()
void demonstrate_security_logging()
void demonstrate_security_metrics()
void demonstrate_audit_trail()
int main()
Represents a single log entry with all associated metadata.
Definition log_entry.h:155
small_string_256 message
The actual log message.
Definition log_entry.h:169