0% found this document useful (0 votes)
12 views8 pages

Secure File Management Techniques

Uploaded by

Pugal Ragu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views8 pages

Secure File Management Techniques

Uploaded by

Pugal Ragu
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

16/06/2025, 17:36 data protection based scenerios

1. Encrypt a File Before Cloud Upload


Encrypts a file using AES. The encrypted file can then be safely uploaded to the cloud.

In [1]: from [Link] import Cipher, algorithms, modes


from [Link] import padding
import os

def encrypt_file(input_file, output_file, key):


iv = [Link](16) # Make a random 16-byte IV for this encryption
cipher = Cipher([Link](key), [Link](iv)) # Set up AES in CBC mod
encryptor = [Link]()
padder = padding.PKCS7(128).padder() # Prepare to pad the data

with open(input_file, 'rb') as f_in, open(output_file, 'wb') as f_out:


f_out.write(iv) # Save the IV at the start of the output file
data = f_in.read() # Read all the input file
padded = [Link](data) + [Link]() # Add padding to the d
encrypted = [Link](padded) + [Link]() # Encrypt t
f_out.write(encrypted) # Write the encrypted data to the output file

key = [Link](32) # Make a random 32-byte key (good for AES-256)


encrypt_file('[Link]', 'mybackup_encrypted.aes', key) # Encrypt the file

2. Find Aadhaar or PAN Numbers in a Text File


Looks for Aadhaar or PAN numbers in a text file using simple patterns.

In [4]: import re

def check_ids(file_path):
aadhaar = r'\b\d{4}\s\d{4}\s\d{4}\b' # Pattern for Aadhaar (xxxx xxxx xxxx)
pan = r'\b[A-Z]{5}[0-9]{4}[A-Z]\b' # Pattern for PAN (ABCDE1234F)
with open(file_path, 'r') as f:
text = [Link]() # Read the file as text
aadhaar_found = [Link](aadhaar, text) # Find all Aadhaar numbers
pan_found = [Link](pan, text) # Find all PAN numbers
print("Aadhaar:", aadhaar_found)
print("PAN:", pan_found)

check_ids('[Link]')

Aadhaar: ['8143 0769 3721']


PAN: []

3. Backup Logs with Timestamp


Makes a copy of a log file and adds the date and time to its name.

In [25]: import os
import shutil
from datetime import datetime
import hashlib

[Link] protection based [Link] 1/8


16/06/2025, 17:36 data protection based scenerios

import logging

def backup_logs(log_file_path: str, backup_dir: str) -> str:


# This function makes a backup copy of a log file, adds a timestamp to the n
# checks that the copy is correct, and sets the file to read-only.

try:
# Check if the log file exists
if not [Link](log_file_path):
raise FileNotFoundError(f"Log file not found: {log_file_path}")

# Make the backup folder if it doesn't exist


if not [Link](backup_dir):
[Link](backup_dir, exist_ok=True)
[Link](backup_dir, 0o755) # Set folder permissions

# Make a new backup file name with the current date and time
timestamp = [Link]().strftime("%Y%m%d-%H%M%S")
base_name = [Link](log_file_path)
backup_name = f"{base_name}.{timestamp}.bak"
backup_path = [Link](backup_dir, backup_name)

# Get the checksum (fingerprint) of the original file


file_hash = hashlib.sha256()
with open(log_file_path, 'rb') as src_file:
while chunk := src_file.read(8192):
file_hash.update(chunk)
original_checksum = file_hash.hexdigest()

# Copy the log file to the backup folder


shutil.copy2(log_file_path, backup_path)

# Get the checksum of the backup file


file_hash = hashlib.sha256()
with open(backup_path, 'rb') as backup_file:
while chunk := backup_file.read(8192):
file_hash.update(chunk)
backup_checksum = file_hash.hexdigest()

# Make sure the backup is exactly the same as the original


if original_checksum != backup_checksum:
raise IOError("Backup checksum verification failed")

# Make the backup file read-only


[Link](backup_path, 0o440)

[Link](f"Successfully backed up {log_file_path} to {backup_path}")


return backup_path

except Exception as e:
[Link](f"Backup failed: {str(e)}")
# Delete the backup file if something went wrong
if 'backup_path' in locals() and [Link](backup_path):
[Link](backup_path)
return ""

# Example usage
if __name__ == "__main__":
[Link](level=[Link])
result = backup_logs(

[Link] protection based [Link] 2/8


16/06/2025, 17:36 data protection based scenerios

r'C:\Users\pugaz\Downloads\backup\sample_log.log', # Path to your log f


'./backups' # Folder to store backups
)
if result:
print(f"Backup successful: {result}")
else:
print("Backup failed. Check logs for details.")

INFO:root:Successfully backed up C:\Users\pugaz\Downloads\backup\sample_log.log t


o ./backups\sample_log.[Link]
Backup successful: ./backups\sample_log.[Link]

4. Scan Git Repository for Secrets


This script checks every file in a folder (and its subfolders) for patterns that look like
secrets, such as AWS keys or private keys. It prints out the file name and the pattern if a
possible secret is found.

In [39]: import os
import re
import glob

def scan_for_secrets(repo_folder):
# Patterns for secrets: AWS Access Key, Stripe Key, Private Key
secret_patterns = [
r'AKIA[0-9A-Z]{16}', # AWS Access Key ID
r'sk_live_[0-9a-zA-Z]{24}', # Stripe Live Secret Key
r'-----BEGIN PRIVATE KEY-----' # Private Key block
]

# Get all files in the repo_folder and its subfolders


files = [Link]([Link](repo_folder, '**', '*'), recursive=True)

for file in files:


if [Link](file):
found = False # Flag to track if a secret is found in this file
try:
with open(file, 'r', errors='ignore') as f:
text = [Link]()
for pattern in secret_patterns:
if [Link](pattern, text):
print(f"Potential secret found in: {file} (Pattern:
found = True
if not found:
print(f"No secrets found in: {file}")
except Exception as e:
# Skips files that can't be read as text (like images or binarie
continue

# Example usage:
scan_for_secrets(r'C:\Users\pugaz\Downloads\backup')

[Link] protection based [Link] 3/8


16/06/2025, 17:36 data protection based scenerios

No secrets found in: C:\Users\pugaz\Downloads\backup\backup_test.txt


No secrets found in: C:\Users\pugaz\Downloads\backup\confidential_share.txt
No secrets found in: C:\Users\pugaz\Downloads\backup\crm_api_data.json
No secrets found in: C:\Users\pugaz\Downloads\backup\customer_data.csv
No secrets found in: C:\Users\pugaz\Downloads\backup\metadata_image.jpg
No secrets found in: C:\Users\pugaz\Downloads\backup\salary_data_2025.xlsx
No secrets found in: C:\Users\pugaz\Downloads\backup\sample_log.log
Potential secret found in: C:\Users\pugaz\Downloads\backup\[Link] (Pattern: A
KIA[0-9A-Z]{16})
No secrets found in: C:\Users\pugaz\Downloads\backup\test_document.docx
No secrets found in: C:\Users\pugaz\Downloads\backup\token_file.txt

Secure File Deletion for Retired Servers


This script securely deletes a file by overwriting its contents with random data before
removing it from the disk. This helps prevent recovery of sensitive information, which is
important for data security and compliance.

In [31]: import os

def secure_delete(file_path, passes=3):


# This function overwrites a file with random data several times, then delet

if [Link](file_path):
size = [Link](file_path) # Find out how big the file is
with open(file_path, 'r+b') as f:
for i in range(passes):
[Link](0) # Go to the start of the file
[Link]([Link](size)) # Write random bytes over the whole f
[Link]() # Make sure data is written
[Link]([Link]()) # Force data to disk
[Link](file_path) # Delete the file
print(f"File '{file_path}' securely deleted with {passes} overwrite pass
else:
print(f"File '{file_path}' not found or is not a regular file.")

# Example usage:
secure_delete('sensitive_data.txt')
import re

def scan_backup_for_malware(backup_file, malware_signatures):


# This function checks a file for known malware patterns before you restore

try:
with open(backup_file, 'r', errors='ignore') as f:
contents = [Link]() # Read the whole file as text
found = False
for signature in malware_signatures:
if [Link](signature, contents): # Look for each malware patt
print(f"Warning: Malware pattern found ({signature}) in '{ba
found = True
if not found:
print(f"No known malware signatures detected in '{backup_file}'.
except Exception as e:
print(f"Could not scan file '{backup_file}': {e}")

# Some example malware patterns to look for


malware_signatures = [

[Link] protection based [Link] 4/8


16/06/2025, 17:36 data protection based scenerios

r'virus_signature', # just a fake marker for demo


r'evil_function\(', # looks like a bad function call
r'base64_decode\(', # often used to hide malware
r'(?:trojan|worm|ransomware)',# common malware keywords
r'cmd\.exe', # Windows command prompt
r'powershell -enc', # encoded PowerShell command
]

# Example usage:
scan_backup_for_malware(r'C:\Users\pugaz\Downloads\backup\sample_log.log', malwa

File 'sensitive_data.txt' securely deleted with 3 overwrite passes.

Validate Backup Before Restoration: Scan


Restored Backups for Known Malware Patterns
This script scans a restored backup file for known malware patterns (signatures) before
restoration. This helps prevent reintroducing malware into your environment. Signature-
based detection is a widely used and effective method for identifying known threats in
files and backups.

In [40]: import re

def scan_backup_for_malware(backup_file, malware_signatures):


"""
Scans a backup file for known malware patterns before restoration.
Args:
backup_file (str): Path to the restored backup file.
malware_signatures (list): List of regex patterns (signatures) for known
"""
try:
with open(backup_file, 'r', errors='ignore') as f:
contents = [Link]()
found = False
for signature in malware_signatures:
if [Link](signature, contents):
print(f"Warning: Malware pattern found ({signature}) in '{ba
found = True
if not found:
print(f"No known malware signatures detected in '{backup_file}'.
except Exception as e:
print(f"Could not scan file '{backup_file}': {e}")

# Example: Use simple signatures for demonstration


malware_signatures = [
r'virus_signature', # simple text marker
r'evil_function\(', # suspicious function call
r'base64_decode\(', # common in malware obfuscation
r'(?:trojan|worm|ransomware)',# common malware keywords
r'cmd\.exe', # suspicious Windows command
r'powershell -enc', # encoded PowerShell command
]

# Usage example:
scan_backup_for_malware(r'C:\Users\pugaz\Downloads\backup\sample_log.log', malwa

[Link] protection based [Link] 5/8


16/06/2025, 17:36 data protection based scenerios

No known malware signatures detected in 'C:\Users\pugaz\Downloads\backup\sample_l


[Link]'. Safe to proceed.

Alert on Unauthorized Cloud App Use


This script scans HTTP log files for access to unauthorized or banned cloud applications
(shadow IT), such as Dropbox or WeTransfer, and prints an alert for each detection.

In [42]: import re

def alert_shadow_it(log_file, banned_domains):


patterns = [[Link](rf'\b{[Link](domain)}\b', [Link]) for domai
try:
with open(log_file, 'r', errors='ignore') as f:
for line_num, line in enumerate(f, 1):
for domain, pattern in zip(banned_domains, patterns):
if [Link](line):
print(f"ALERT: Unauthorized cloud app '{domain}' used (l
except FileNotFoundError:
print(f"Log file '{log_file}' not found.")
except Exception as e:
print(f"Error reading log file: {e}")

banned_domains = [
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]',
'[Link]'
]

# Run the detection


alert_shadow_it('[Link]', banned_domains)

ALERT: Unauthorized cloud app '[Link]' used (line 2): [Link] - - [16/J
un/2025:10:01:00 +0000] "GET /download HTTP/1.1" 200 2048 "[Link]
e" "Mozilla/5.0"
ALERT: Unauthorized cloud app '[Link]' used (line 4): [Link] - - [1
6/Jun/2025:10:03:00 +0000] "GET /files HTTP/1.1" 200 4096 "[Link]
share" "Mozilla/5.0"

Local File Versioning System


This script implements a simple local file versioning system in Python. Every time you
save a file, it creates a new version in a separate directory with a timestamp, preventing
accidental overwrites and preserving your file history.

In [43]: import os
import shutil
from datetime import datetime

def save_new_version(file_path, version_dir='versions'):


"""
Saves a new version of the specified file in a version directory.

[Link] protection based [Link] 6/8


16/06/2025, 17:36 data protection based scenerios

The versioned file is named with a timestamp to prevent overwrites.

Args:
file_path (str): Path to the file to be versioned.
version_dir (str): Directory where versions are stored.
"""
if not [Link](file_path):
print(f"File '{file_path}' does not exist.")
return

# Create version directory if it doesn't exist


if not [Link](version_dir):
[Link](version_dir)

# Generate a versioned filename with timestamp


base_name = [Link](file_path)
timestamp = [Link]().strftime('%Y%m%d_%H%M%S')
versioned_name = f"{base_name}.v{timestamp}"
versioned_path = [Link](version_dir, versioned_name)

# Copy the file as a new version


shutil.copy2(file_path, versioned_path)
print(f"New version saved: {versioned_path}")

# Example usage:
save_new_version('[Link]') # Replace '[Link]' with your file name

New version saved: versions\[Link].v20250616_171828

Train Employees to Detect DLP Violations


Simulate and evaluate DLP (Data Loss Prevention) rule effectiveness using sample files.
This exercise helps employees recognize risky content and understand how DLP tools
work.

In [47]: with open(r'C:\Users\pugaz\Downloads\backup\confidential_share.txt', 'r', encodi


content = [Link]()
print(content)

This is a confidential file shared for temporary access only.

--------------------
Employee Name: John Doe
Credit Card: 4111 1111 1111 1111
SSN: 123-45-6789
Confidential: Project Phoenix

In [44]: import re

def simulate_dlp_scan(file_path, rules):


with open(file_path, 'r', errors='ignore') as f:
content = [Link]()
for rule_name, pattern in [Link]():
if [Link](pattern, content):
print(f"DLP Violation Detected: {rule_name} in {file_path}")

# Define sample DLP rules


dlp_rules = {

[Link] protection based [Link] 7/8


16/06/2025, 17:36 data protection based scenerios

"Credit Card": r"\b(?:\d[ -]*?){13,16}\b",


"SSN": r"\b\d{3}-\d{2}-\d{4}\b",
"Confidential Project": r"Project Phoenix"
}

# Simulate scanning a file


simulate_dlp_scan(r'C:\Users\pugaz\Downloads\backup\confidential_share.txt', dlp

DLP Violation Detected: Credit Card in C:\Users\pugaz\Downloads\backup\confidenti


al_share.txt
DLP Violation Detected: SSN in C:\Users\pugaz\Downloads\backup\confidential_shar
[Link]
DLP Violation Detected: Confidential Project in C:\Users\pugaz\Downloads\backup\c
onfidential_share.txt

Automated SaaS CRM Backup


This guide describes how to automate backups of your CRM SaaS data using a simulated
API response stored in a JSON file. The process saves timestamped backup copies locally,
preventing accidental overwrites and enabling historical data restoration.

In [48]: import os
import shutil
import json
from datetime import datetime

def backup_crm_data(api_data_file, backup_dir='crm_backups'):


"""
Reads CRM API data from a JSON file and saves a timestamped backup copy.
Args:
api_data_file (str): Path to the CRM API data JSON file.
backup_dir (str): Directory to store backup files.
"""
# Ensure backup directory exists
[Link](backup_dir, exist_ok=True)

# Read API data (simulate API call)


with open(api_data_file, 'r', encoding='utf-8') as f:
data = [Link](f)

# Create a timestamped filename


timestamp = [Link]().strftime('%Y%m%d_%H%M%S')
backup_file = [Link](backup_dir, f'crm_backup_{timestamp}.json')

# Save backup
with open(backup_file, 'w', encoding='utf-8') as f:
[Link](data, f, indent=2)
print(f"CRM backup saved: {backup_file}")

# Example usage:
backup_crm_data(r'C:\Users\pugaz\Downloads\backup\crm_api_data.json')

CRM backup saved: crm_backups\crm_backup_20250616_172745.json

[Link] protection based [Link] 8/8

You might also like