-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path12-logging-security.py
More file actions
1831 lines (1468 loc) · 69.2 KB
/
12-logging-security.py
File metadata and controls
1831 lines (1468 loc) · 69.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""Question: Implement secure logging practices to protect sensitive information and maintain security.
Create a comprehensive logging security system that demonstrates:
1. Secure log configuration and handling
2. Data sanitization and PII protection
3. Log injection prevention
4. Secure log storage and rotation
5. Audit logging and monitoring
Requirements:
1. Create a secure logger with data sanitization
2. Implement PII detection and masking
3. Create audit logging for security events
4. Implement secure log rotation and storage
5. Demonstrate log injection prevention
Example usage:
secure_logger = SecureLogger()
secure_logger.log_user_action("user123", "login", {"ip": "192.168.1.1"})
"""
# LEARNING CHALLENGE
#
# Before looking at any solution below, please try to solve this yourself first!
#
# Tips for success:
# - Read the question carefully
# - Think about what classes and methods you need
# - Start with a simple implementation
# - Test your code step by step
# - Don't worry if it's not perfect - learning is a process!
#
# Remember: The best way to learn programming is by doing, not by reading solutions!
#
# Take your time, experiment, and enjoy the learning process!
# Try to implement your solution here:
# (Write your code below this line)
# HINT SECTION (Only look if you're really stuck!)
#
# Think about:
# - What sensitive data needs to be protected in logs?
# - How can you detect and sanitize PII (emails, SSNs, credit cards)?
# - What are log injection attacks and how to prevent them?
# - How to implement secure log rotation and storage?
#
# Remember: Start simple and build up complexity gradually!
# ===============================================================================
# STEP-BY-STEP SOLUTION
# ===============================================================================
#
# CLASSROOM-STYLE WALKTHROUGH
#
# Let's solve this problem step by step, just like in a programming class!
# Each step builds upon the previous one, so you can follow along and understand
# the complete thought process.
#
# ===============================================================================
# Step 1: Import modules and create basic data sanitization
# ===============================================================================
# Explanation:
# Secure logging starts with sanitizing sensitive data. We need to identify
# and mask PII (Personally Identifiable Information) before logging.
import logging
import re
import hashlib
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
import os
class DataSanitizer:
"""Sanitizes sensitive data before logging."""
def __init__(self):
# Common PII patterns
self.patterns = {
'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
'ssn': re.compile(r'\b\d{3}-?\d{2}-?\d{4}\b'),
'credit_card': re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),
'phone': re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),
'ip_address': re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
}
def sanitize_text(self, text: str) -> str:
"""Sanitize text by masking PII."""
if not isinstance(text, str):
text = str(text)
# Mask email addresses
text = self.patterns['email'].sub(lambda m: self._mask_email(m.group()), text)
# Mask SSN
text = self.patterns['ssn'].sub('***-**-****', text)
# Mask credit card numbers
text = self.patterns['credit_card'].sub('****-****-****-****', text)
# Mask phone numbers
text = self.patterns['phone'].sub('***-***-****', text)
return text
def _mask_email(self, email: str) -> str:
"""Mask email while preserving domain for debugging."""
parts = email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
masked_username = username[0] + '*' * (len(username) - 1)
return f"{masked_username}@{domain}"
return "***@***.***"
# What we accomplished in this step:
# - Created basic data sanitization for common PII patterns
# - Implemented email masking that preserves domain for debugging
# - Set up foundation for secure logging
# Step 2: Add log injection prevention
# ===============================================================================
# Explanation:
# Log injection attacks occur when attackers inject malicious content into logs.
# We need to sanitize control characters and escape sequences.
import logging
import re
import hashlib
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
import os
class DataSanitizer:
"""Sanitizes sensitive data before logging."""
def __init__(self):
# Common PII patterns
self.patterns = {
'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
'ssn': re.compile(r'\b\d{3}-?\d{2}-?\d{4}\b'),
'credit_card': re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),
'phone': re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),
'ip_address': re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
}
def sanitize_text(self, text: str) -> str:
"""Sanitize text by masking PII."""
if not isinstance(text, str):
text = str(text)
# Mask email addresses
text = self.patterns['email'].sub(lambda m: self._mask_email(m.group()), text)
# Mask SSN
text = self.patterns['ssn'].sub('***-**-****', text)
# Mask credit card numbers
text = self.patterns['credit_card'].sub('****-****-****-****', text)
# Mask phone numbers
text = self.patterns['phone'].sub('***-***-****', text)
return text
def _mask_email(self, email: str) -> str:
"""Mask email while preserving domain for debugging."""
parts = email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
masked_username = username[0] + '*' * (len(username) - 1)
return f"{masked_username}@{domain}"
return "***@***.***"
class LogInjectionPreventer:
"""Prevents log injection attacks by sanitizing control characters."""
def __init__(self):
# Dangerous control characters and escape sequences
self.dangerous_chars = {
'\n': '\\n', # Newline
'\r': '\\r', # Carriage return
'\t': '\\t', # Tab
'\b': '\\b', # Backspace
'\f': '\\f', # Form feed
'\v': '\\v', # Vertical tab
'\0': '\\0', # Null character
}
# ANSI escape sequences (for terminal control)
self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
def sanitize_for_logging(self, text: str) -> str:
"""Sanitize text to prevent log injection attacks."""
if not isinstance(text, str):
text = str(text)
# Remove ANSI escape sequences
text = self.ansi_escape.sub('', text)
# Replace dangerous control characters
for char, replacement in self.dangerous_chars.items():
text = text.replace(char, replacement)
# Remove other non-printable characters
text = ''.join(char for char in text if ord(char) >= 32 or char in ['\t'])
# Limit length to prevent log flooding
if len(text) > 1000:
text = text[:997] + "..."
return text
def validate_log_entry(self, entry: str) -> bool:
"""Validate that log entry is safe."""
# Check for suspicious patterns
suspicious_patterns = [
r'(?i)(script|javascript|vbscript)', # Script injection
r'(?i)(<|>|<|>)', # HTML/XML injection
r'(?i)(union|select|insert|delete)', # SQL injection patterns
r'(?i)(eval|exec|system)', # Code execution
]
for pattern in suspicious_patterns:
if re.search(pattern, entry):
return False
return True
# What we accomplished in this step:
# - Added log injection prevention with control character sanitization
# - Implemented ANSI escape sequence removal
# - Added validation for suspicious patterns
# - Limited log entry length to prevent flooding
# Step 3: Create the secure logger with data sanitization
# ===============================================================================
# Explanation:
# Now we combine data sanitization and injection prevention into a secure logger
# that handles all logging operations safely.
import logging
import re
import hashlib
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
import os
class DataSanitizer:
"""Sanitizes sensitive data before logging."""
def __init__(self):
# Common PII patterns
self.patterns = {
'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
'ssn': re.compile(r'\b\d{3}-?\d{2}-?\d{4}\b'),
'credit_card': re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),
'phone': re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),
'ip_address': re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
}
def sanitize_text(self, text: str) -> str:
"""Sanitize text by masking PII."""
if not isinstance(text, str):
text = str(text)
# Mask email addresses
text = self.patterns['email'].sub(lambda m: self._mask_email(m.group()), text)
# Mask SSN
text = self.patterns['ssn'].sub('***-**-****', text)
# Mask credit card numbers
text = self.patterns['credit_card'].sub('****-****-****-****', text)
# Mask phone numbers
text = self.patterns['phone'].sub('***-***-****', text)
return text
def _mask_email(self, email: str) -> str:
"""Mask email while preserving domain for debugging."""
parts = email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
masked_username = username[0] + '*' * (len(username) - 1)
return f"{masked_username}@{domain}"
return "***@***.***"
class LogInjectionPreventer:
"""Prevents log injection attacks by sanitizing control characters."""
def __init__(self):
# Dangerous control characters and escape sequences
self.dangerous_chars = {
'\n': '\\n', # Newline
'\r': '\\r', # Carriage return
'\t': '\\t', # Tab
'\b': '\\b', # Backspace
'\f': '\\f', # Form feed
'\v': '\\v', # Vertical tab
'\0': '\\0', # Null character
}
# ANSI escape sequences (for terminal control)
self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
def sanitize_for_logging(self, text: str) -> str:
"""Sanitize text to prevent log injection attacks."""
if not isinstance(text, str):
text = str(text)
# Remove ANSI escape sequences
text = self.ansi_escape.sub('', text)
# Replace dangerous control characters
for char, replacement in self.dangerous_chars.items():
text = text.replace(char, replacement)
# Remove other non-printable characters
text = ''.join(char for char in text if ord(char) >= 32 or char in ['\t'])
# Limit length to prevent log flooding
if len(text) > 1000:
text = text[:997] + "..."
return text
def validate_log_entry(self, entry: str) -> bool:
"""Validate that log entry is safe."""
# Check for suspicious patterns
suspicious_patterns = [
r'(?i)(script|javascript|vbscript)', # Script injection
r'(?i)(<|>|<|>)', # HTML/XML injection
r'(?i)(union|select|insert|delete)', # SQL injection patterns
r'(?i)(eval|exec|system)', # Code execution
]
for pattern in suspicious_patterns:
if re.search(pattern, entry):
return False
return True
class SecureLogger:
"""Secure logger with data sanitization and injection prevention."""
def __init__(self, name: str = "secure_app", log_file: str = "secure_app.log"):
self.sanitizer = DataSanitizer()
self.injection_preventer = LogInjectionPreventer()
# Configure secure logging
self.logger = logging.getLogger(name)
self.logger.setLevel(logging.INFO)
# Create secure formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# File handler with secure permissions
if not self.logger.handlers:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
self.logger.addHandler(file_handler)
# Set secure file permissions (owner read/write only)
try:
os.chmod(log_file, 0o600)
except OSError:
pass # May fail on some systems
def _sanitize_message(self, message: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Sanitize message and data before logging."""
# Sanitize the main message
clean_message = self.sanitizer.sanitize_text(message)
clean_message = self.injection_preventer.sanitize_for_logging(clean_message)
# Sanitize additional data if provided
if data:
clean_data = {}
for key, value in data.items():
clean_key = self.injection_preventer.sanitize_for_logging(str(key))
clean_value = self.sanitizer.sanitize_text(str(value))
clean_value = self.injection_preventer.sanitize_for_logging(clean_value)
clean_data[clean_key] = clean_value
clean_message += f" | Data: {json.dumps(clean_data, separators=(',', ':'))}"
# Final validation
if not self.injection_preventer.validate_log_entry(clean_message):
return "SUSPICIOUS_CONTENT_BLOCKED"
return clean_message
def info(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log info message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.info(clean_message)
def warning(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log warning message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.warning(clean_message)
def error(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log error message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.error(clean_message)
def log_user_action(self, user_id: str, action: str, metadata: Optional[Dict[str, Any]] = None):
"""Log user action with sanitization."""
# Hash user ID for privacy
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
message = f"User action: {action} by user_{user_hash}"
self.info(message, metadata)
# What we accomplished in this step:
# - Created secure logger that combines sanitization and injection prevention
# - Added secure file permissions for log files
# - Implemented user action logging with privacy protection
# - Added comprehensive message sanitization pipeline
# Step 4: Add audit logging for security events
# ===============================================================================
# Explanation:
# Audit logging tracks security-critical events for compliance and monitoring.
# We need to log authentication, authorization, and security violations.
import logging
import re
import hashlib
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
import os
class DataSanitizer:
"""Sanitizes sensitive data before logging."""
def __init__(self):
# Common PII patterns
self.patterns = {
'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
'ssn': re.compile(r'\b\d{3}-?\d{2}-?\d{4}\b'),
'credit_card': re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),
'phone': re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),
'ip_address': re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
}
def sanitize_text(self, text: str) -> str:
"""Sanitize text by masking PII."""
if not isinstance(text, str):
text = str(text)
# Mask email addresses
text = self.patterns['email'].sub(lambda m: self._mask_email(m.group()), text)
# Mask SSN
text = self.patterns['ssn'].sub('***-**-****', text)
# Mask credit card numbers
text = self.patterns['credit_card'].sub('****-****-****-****', text)
# Mask phone numbers
text = self.patterns['phone'].sub('***-***-****', text)
return text
def _mask_email(self, email: str) -> str:
"""Mask email while preserving domain for debugging."""
parts = email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
masked_username = username[0] + '*' * (len(username) - 1)
return f"{masked_username}@{domain}"
return "***@***.***"
class LogInjectionPreventer:
"""Prevents log injection attacks by sanitizing control characters."""
def __init__(self):
# Dangerous control characters and escape sequences
self.dangerous_chars = {
'\n': '\\n', # Newline
'\r': '\\r', # Carriage return
'\t': '\\t', # Tab
'\b': '\\b', # Backspace
'\f': '\\f', # Form feed
'\v': '\\v', # Vertical tab
'\0': '\\0', # Null character
}
# ANSI escape sequences (for terminal control)
self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
def sanitize_for_logging(self, text: str) -> str:
"""Sanitize text to prevent log injection attacks."""
if not isinstance(text, str):
text = str(text)
# Remove ANSI escape sequences
text = self.ansi_escape.sub('', text)
# Replace dangerous control characters
for char, replacement in self.dangerous_chars.items():
text = text.replace(char, replacement)
# Remove other non-printable characters
text = ''.join(char for char in text if ord(char) >= 32 or char in ['\t'])
# Limit length to prevent log flooding
if len(text) > 1000:
text = text[:997] + "..."
return text
def validate_log_entry(self, entry: str) -> bool:
"""Validate that log entry is safe."""
# Check for suspicious patterns
suspicious_patterns = [
r'(?i)(script|javascript|vbscript)', # Script injection
r'(?i)(<|>|<|>)', # HTML/XML injection
r'(?i)(union|select|insert|delete)', # SQL injection patterns
r'(?i)(eval|exec|system)', # Code execution
]
for pattern in suspicious_patterns:
if re.search(pattern, entry):
return False
return True
class SecureLogger:
"""Secure logger with data sanitization and injection prevention."""
def __init__(self, name: str = "secure_app", log_file: str = "secure_app.log"):
self.sanitizer = DataSanitizer()
self.injection_preventer = LogInjectionPreventer()
# Configure secure logging
self.logger = logging.getLogger(name)
self.logger.setLevel(logging.INFO)
# Create secure formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# File handler with secure permissions
if not self.logger.handlers:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
self.logger.addHandler(file_handler)
# Set secure file permissions (owner read/write only)
try:
os.chmod(log_file, 0o600)
except OSError:
pass # May fail on some systems
def _sanitize_message(self, message: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Sanitize message and data before logging."""
# Sanitize the main message
clean_message = self.sanitizer.sanitize_text(message)
clean_message = self.injection_preventer.sanitize_for_logging(clean_message)
# Sanitize additional data if provided
if data:
clean_data = {}
for key, value in data.items():
clean_key = self.injection_preventer.sanitize_for_logging(str(key))
clean_value = self.sanitizer.sanitize_text(str(value))
clean_value = self.injection_preventer.sanitize_for_logging(clean_value)
clean_data[clean_key] = clean_value
clean_message += f" | Data: {json.dumps(clean_data, separators=(',', ':'))}"
# Final validation
if not self.injection_preventer.validate_log_entry(clean_message):
return "SUSPICIOUS_CONTENT_BLOCKED"
return clean_message
def info(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log info message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.info(clean_message)
def warning(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log warning message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.warning(clean_message)
def error(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log error message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.error(clean_message)
def log_user_action(self, user_id: str, action: str, metadata: Optional[Dict[str, Any]] = None):
"""Log user action with sanitization."""
# Hash user ID for privacy
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
message = f"User action: {action} by user_{user_hash}"
self.info(message, metadata)
class AuditLogger(SecureLogger):
"""Specialized logger for security audit events."""
def __init__(self, audit_file: str = "security_audit.log"):
super().__init__(name="security_audit", log_file=audit_file)
# Configure separate audit logger with higher security
self.audit_logger = logging.getLogger("audit")
self.audit_logger.setLevel(logging.INFO)
# Create audit-specific formatter with more details
audit_formatter = logging.Formatter(
'%(asctime)s - AUDIT - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S UTC'
)
# Separate audit file handler
if not self.audit_logger.handlers:
audit_handler = logging.FileHandler(audit_file)
audit_handler.setFormatter(audit_formatter)
audit_handler.setLevel(logging.INFO)
self.audit_logger.addHandler(audit_handler)
# Set even more restrictive permissions for audit logs
try:
os.chmod(audit_file, 0o400) # Read-only for owner
except OSError:
pass
def log_authentication_event(self, user_id: str, event_type: str,
success: bool, ip_address: str,
user_agent: Optional[str] = None):
"""Log authentication events."""
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
status = "SUCCESS" if success else "FAILURE"
# Sanitize IP address (keep for security monitoring)
clean_ip = self.injection_preventer.sanitize_for_logging(ip_address)
# Sanitize user agent
clean_user_agent = ""
if user_agent:
clean_user_agent = self.injection_preventer.sanitize_for_logging(user_agent)[:200]
audit_data = {
"event_type": "authentication",
"auth_event": event_type,
"user_hash": user_hash,
"status": status,
"source_ip": clean_ip,
"user_agent": clean_user_agent,
"timestamp": datetime.utcnow().isoformat()
}
message = f"AUTH_{status}: {event_type} for user_{user_hash} from {clean_ip}"
self.audit_logger.info(f"{message} | {json.dumps(audit_data, separators=(',', ':'))}")
def log_authorization_event(self, user_id: str, resource: str,
action: str, granted: bool, reason: str = ""):
"""Log authorization events."""
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
status = "GRANTED" if granted else "DENIED"
# Sanitize inputs
clean_resource = self.injection_preventer.sanitize_for_logging(resource)
clean_action = self.injection_preventer.sanitize_for_logging(action)
clean_reason = self.injection_preventer.sanitize_for_logging(reason)
audit_data = {
"event_type": "authorization",
"user_hash": user_hash,
"resource": clean_resource,
"action": clean_action,
"status": status,
"reason": clean_reason,
"timestamp": datetime.utcnow().isoformat()
}
message = f"AUTHZ_{status}: {clean_action} on {clean_resource} for user_{user_hash}"
self.audit_logger.info(f"{message} | {json.dumps(audit_data, separators=(',', ':'))}")
def log_security_violation(self, violation_type: str, details: Dict[str, Any],
severity: str = "HIGH"):
"""Log security violations and suspicious activities."""
# Sanitize all details
clean_details = {}
for key, value in details.items():
clean_key = self.injection_preventer.sanitize_for_logging(str(key))
clean_value = self.sanitizer.sanitize_text(str(value))
clean_value = self.injection_preventer.sanitize_for_logging(clean_value)
clean_details[clean_key] = clean_value
audit_data = {
"event_type": "security_violation",
"violation_type": violation_type,
"severity": severity,
"details": clean_details,
"timestamp": datetime.utcnow().isoformat()
}
message = f"SECURITY_VIOLATION: {violation_type} - Severity: {severity}"
self.audit_logger.error(f"{message} | {json.dumps(audit_data, separators=(',', ':'))}")
def log_data_access(self, user_id: str, data_type: str, operation: str,
record_count: int = 1):
"""Log sensitive data access events."""
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
# Sanitize inputs
clean_data_type = self.injection_preventer.sanitize_for_logging(data_type)
clean_operation = self.injection_preventer.sanitize_for_logging(operation)
audit_data = {
"event_type": "data_access",
"user_hash": user_hash,
"data_type": clean_data_type,
"operation": clean_operation,
"record_count": record_count,
"timestamp": datetime.utcnow().isoformat()
}
message = f"DATA_ACCESS: {clean_operation} on {clean_data_type} by user_{user_hash} ({record_count} records)"
self.audit_logger.info(f"{message} | {json.dumps(audit_data, separators=(',', ':'))}")
# What we accomplished in this step:
# - Created specialized audit logger for security events
# - Added authentication and authorization event logging
# - Implemented security violation tracking
# - Added data access logging for compliance
# - Enhanced audit log security with restrictive permissions
# Step 5: Add secure log rotation and storage
# ===============================================================================
# Explanation:
# Secure log rotation prevents log files from growing too large and ensures
# old logs are properly archived with maintained security.
import logging
import re
import hashlib
import json
from typing import Dict, Any, List, Optional
from datetime import datetime
import os
from logging.handlers import RotatingFileHandler, TimedRotatingFileHandler
class DataSanitizer:
"""Sanitizes sensitive data before logging."""
def __init__(self):
# Common PII patterns
self.patterns = {
'email': re.compile(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'),
'ssn': re.compile(r'\b\d{3}-?\d{2}-?\d{4}\b'),
'credit_card': re.compile(r'\b\d{4}[-\s]?\d{4}[-\s]?\d{4}[-\s]?\d{4}\b'),
'phone': re.compile(r'\b\d{3}[-.]?\d{3}[-.]?\d{4}\b'),
'ip_address': re.compile(r'\b\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}\b')
}
def sanitize_text(self, text: str) -> str:
"""Sanitize text by masking PII."""
if not isinstance(text, str):
text = str(text)
# Mask email addresses
text = self.patterns['email'].sub(lambda m: self._mask_email(m.group()), text)
# Mask SSN
text = self.patterns['ssn'].sub('***-**-****', text)
# Mask credit card numbers
text = self.patterns['credit_card'].sub('****-****-****-****', text)
# Mask phone numbers
text = self.patterns['phone'].sub('***-***-****', text)
return text
def _mask_email(self, email: str) -> str:
"""Mask email while preserving domain for debugging."""
parts = email.split('@')
if len(parts) == 2:
username = parts[0]
domain = parts[1]
masked_username = username[0] + '*' * (len(username) - 1)
return f"{masked_username}@{domain}"
return "***@***.***"
class LogInjectionPreventer:
"""Prevents log injection attacks by sanitizing control characters."""
def __init__(self):
# Dangerous control characters and escape sequences
self.dangerous_chars = {
'\n': '\\n', # Newline
'\r': '\\r', # Carriage return
'\t': '\\t', # Tab
'\b': '\\b', # Backspace
'\f': '\\f', # Form feed
'\v': '\\v', # Vertical tab
'\0': '\\0', # Null character
}
# ANSI escape sequences (for terminal control)
self.ansi_escape = re.compile(r'\x1B(?:[@-Z\\-_]|\[[0-?]*[ -/]*[@-~])')
def sanitize_for_logging(self, text: str) -> str:
"""Sanitize text to prevent log injection attacks."""
if not isinstance(text, str):
text = str(text)
# Remove ANSI escape sequences
text = self.ansi_escape.sub('', text)
# Replace dangerous control characters
for char, replacement in self.dangerous_chars.items():
text = text.replace(char, replacement)
# Remove other non-printable characters
text = ''.join(char for char in text if ord(char) >= 32 or char in ['\t'])
# Limit length to prevent log flooding
if len(text) > 1000:
text = text[:997] + "..."
return text
def validate_log_entry(self, entry: str) -> bool:
"""Validate that log entry is safe."""
# Check for suspicious patterns
suspicious_patterns = [
r'(?i)(script|javascript|vbscript)', # Script injection
r'(?i)(<|>|<|>)', # HTML/XML injection
r'(?i)(union|select|insert|delete)', # SQL injection patterns
r'(?i)(eval|exec|system)', # Code execution
]
for pattern in suspicious_patterns:
if re.search(pattern, entry):
return False
return True
class SecureRotatingFileHandler(RotatingFileHandler):
"""Secure rotating file handler that maintains file permissions."""
def __init__(self, filename, mode='a', maxBytes=0, backupCount=0,
encoding=None, delay=False, secure_permissions=0o600):
super().__init__(filename, mode, maxBytes, backupCount, encoding, delay)
self.secure_permissions = secure_permissions
def doRollover(self):
"""Override rollover to maintain secure permissions."""
super().doRollover()
# Set secure permissions on all log files
try:
# Set permissions on current log file
os.chmod(self.baseFilename, self.secure_permissions)
# Set permissions on backup files
for i in range(1, self.backupCount + 1):
backup_name = f"{self.baseFilename}.{i}"
if os.path.exists(backup_name):
os.chmod(backup_name, self.secure_permissions)
except OSError:
pass # May fail on some systems
class SecureLogger:
"""Secure logger with data sanitization and injection prevention."""
def __init__(self, name: str = "secure_app", log_file: str = "secure_app.log"):
self.sanitizer = DataSanitizer()
self.injection_preventer = LogInjectionPreventer()
# Configure secure logging
self.logger = logging.getLogger(name)
self.logger.setLevel(logging.INFO)
# Create secure formatter
formatter = logging.Formatter(
'%(asctime)s - %(name)s - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S'
)
# File handler with secure permissions
if not self.logger.handlers:
file_handler = logging.FileHandler(log_file)
file_handler.setFormatter(formatter)
file_handler.setLevel(logging.INFO)
self.logger.addHandler(file_handler)
# Set secure file permissions (owner read/write only)
try:
os.chmod(log_file, 0o600)
except OSError:
pass # May fail on some systems
def _sanitize_message(self, message: str, data: Optional[Dict[str, Any]] = None) -> str:
"""Sanitize message and data before logging."""
# Sanitize the main message
clean_message = self.sanitizer.sanitize_text(message)
clean_message = self.injection_preventer.sanitize_for_logging(clean_message)
# Sanitize additional data if provided
if data:
clean_data = {}
for key, value in data.items():
clean_key = self.injection_preventer.sanitize_for_logging(str(key))
clean_value = self.sanitizer.sanitize_text(str(value))
clean_value = self.injection_preventer.sanitize_for_logging(clean_value)
clean_data[clean_key] = clean_value
clean_message += f" | Data: {json.dumps(clean_data, separators=(',', ':'))}"
# Final validation
if not self.injection_preventer.validate_log_entry(clean_message):
return "SUSPICIOUS_CONTENT_BLOCKED"
return clean_message
def info(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log info message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.info(clean_message)
def warning(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log warning message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.warning(clean_message)
def error(self, message: str, data: Optional[Dict[str, Any]] = None):
"""Log error message with sanitization."""
clean_message = self._sanitize_message(message, data)
self.logger.error(clean_message)
def log_user_action(self, user_id: str, action: str, metadata: Optional[Dict[str, Any]] = None):
"""Log user action with sanitization."""
# Hash user ID for privacy
user_hash = hashlib.sha256(user_id.encode()).hexdigest()[:8]
message = f"User action: {action} by user_{user_hash}"
self.info(message, metadata)
class AuditLogger(SecureLogger):
"""Specialized logger for security audit events."""
def __init__(self, audit_file: str = "security_audit.log"):
super().__init__(name="security_audit", log_file=audit_file)
# Configure separate audit logger with higher security
self.audit_logger = logging.getLogger("audit")
self.audit_logger.setLevel(logging.INFO)
# Create audit-specific formatter with more details
audit_formatter = logging.Formatter(
'%(asctime)s - AUDIT - %(levelname)s - %(message)s',
datefmt='%Y-%m-%d %H:%M:%S UTC'
)
# Separate audit file handler
if not self.audit_logger.handlers:
audit_handler = logging.FileHandler(audit_file)
audit_handler.setFormatter(audit_formatter)
audit_handler.setLevel(logging.INFO)
self.audit_logger.addHandler(audit_handler)