File Attacks
A file attack is an attack where threat actors use certain file types, usually *.DOCX, *.XLSX, or *.PDF, designed to entice users to open the document or follow a malicious link in a document. If the file is embedded with malicious code, the code will be executed when the document is opened.
Macro-enabled files (.xlsm, .docm) are particularly dangerous as they can execute arbitrary code when opened, potentially installing keyloggers or other malware.
Attack Example: Malicious Email Campaign
Threat actors often send convincing emails with malicious attachments that disarm the victim’s response to any script/macro warnings:
Phishing Email Template
Malicious Excel Macro Example
<! DOCTYPE html >
< html >
< head >
< title > Work Email </ title >
</ head >
< body >
< article class = "message-pane" >
< header class = "message-info" >
< section class = "from-to" >
< h1 > [email protected] </ h1 >
< h2 > Urgent accounts error! </ h2 >
< p > To: < em > [email protected] </ em ></ p >
</ section >
</ header >
< section class = "message-content" >
< header >
< p > I'm not sure where we got it wrong. But I need you to look at
this spreadsheet urgently. Don't worry about the warnings,
I wrote a macro to help me with the sums </ p >
< a href = "urgent_finance_review.xlsm" > urgent_finance_review.xlsm </ a >
</ header >
</ section >
</ article >
</ body >
</ html >
Common File Attack Vectors
File Types and Attack Methods
Microsoft Office Documents
.docm / .xlsm - Macro-enabled documents
.doc / .xls - Legacy formats with macro support
Embedded VBA scripts execute on open
PDF Documents
Embedded JavaScript
Form exploits
Malicious links
Archive Files
.zip / .rar containing executables
Double extension tricks (e.g., document.pdf.exe)
Image Files
Embedded scripts in SVG files
Steganography-hidden payloads
Metadata exploits
Side-Channel Attacks
A side-channel attack does not target a program or its code directly. Rather, it attempts to gather information or influence the program execution of a system by measuring or exploiting indirect effects of the system or its hardware.
Side-channel attacks break cryptography by exploiting information inadvertently leaked by a system when performing cryptographic operations.
Types of Side-Channel Leaks
Timing : Measure execution time differences
Power consumption : Analyze power usage patterns
Electromagnetic emission : Monitor EM radiation
Acoustic : Listen to hardware sounds
Cache behavior : Exploit CPU cache timing
This example demonstrates a side-channel attack that exploits the comparison of response times for correct and incorrect usernames to inform a brute force attack.
Attack Methodology
Baseline Analysis
Compare average login time for a known valid username versus random usernames to detect timing differences. python TimeBasedLoginAnalysis.py -u admin -S
Username Enumeration
Test a list of potential usernames by comparing their response times against the baseline. python TimeBasedLoginUserEnum.py -u admin -t 32 -s 100 -f users.txt
Targeted Attack
Use verified usernames with known passwords from data breaches to perform targeted dictionary attacks.
Timing Attack Implementation
Time-Based Username Enumeration
Vulnerable Login Code
import requests
import statistics
from concurrent.futures import ThreadPoolExecutor
def trylogin ( username , results ):
"""Attempt login and measure response time"""
session = requests.Session()
try :
r = session.post(
"http://127.0.0.1:5000/index.html" ,
data = { "username" : username, "password" : "randomPassword" },
)
# Convert to milliseconds
results[username].append(r.elapsed.total_seconds() * 1000 )
return r.elapsed.total_seconds() * 1000
except Exception as e:
print ( f "[error] { e } " )
return 0
def average_response_time ( username , threads = 4 , samples = 100 ):
"""Calculate average response time for username"""
results = {username: []}
with ThreadPoolExecutor( max_workers = min (threads, samples)) as tp:
for k in range (samples):
tp.submit(trylogin, username, results)
if len (results[username]) != 0 :
return sum (results[username]) / len (results[username])
else :
return None
# Compare valid vs invalid username timing
avg_real_user = average_response_time( "admin" , threads = 4 , samples = 100 )
avg_random_user = average_response_time( "xyzabc" , threads = 4 , samples = 100 )
diff = abs (avg_real_user - avg_random_user)
print ( f "Timing difference: { diff :.2f} ms" )
if diff > 5 : # If difference is > 5ms
print ( "[!] Application vulnerable to timing attacks" )
Detecting Timing Vulnerabilities
The script performs 100 login attempts for each username and compares average response times:
Valid username : Typically shows consistent, longer response times (e.g., 45ms average)
Invalid username : Shows shorter response times (e.g., 12ms average)
Difference > 5ms : Indicates exploitable timing leak
Countermeasures
File Attack Prevention
File Upload Validation
Content-Type Validation
from flask import Flask, request
import os
from werkzeug.utils import secure_filename
ALLOWED_EXTENSIONS = { 'txt' , 'pdf' , 'png' , 'jpg' , 'jpeg' , 'gif' }
MAX_FILE_SIZE = 5 * 1024 * 1024 # 5MB
def allowed_file ( filename ):
return '.' in filename and \
filename.rsplit( '.' , 1 )[ 1 ].lower() in ALLOWED_EXTENSIONS
@app.route ( '/upload' , methods = [ 'POST' ])
def upload_file ():
if 'file' not in request.files:
return 'No file part' , 400
file = request.files[ 'file' ]
# Check file size
file .seek( 0 , os. SEEK_END )
file_length = file .tell()
if file_length > MAX_FILE_SIZE :
return 'File too large' , 400
file .seek( 0 )
# Validate extension
if file and allowed_file( file .filename):
filename = secure_filename( file .filename)
# Additional: Scan with antivirus
# Additional: Validate file content matches extension
file .save(os.path.join(app.config[ 'UPLOAD_FOLDER' ], filename))
return 'File uploaded successfully'
return 'Invalid file type' , 400
Side-Channel Attack Prevention
Isochronous Authentication
Constant-Time Comparison
Flask-Limiter Rate Limiting
from datetime import datetime, timedelta
from time import sleep
import random
@app.route ( '/' , methods = [ 'POST' ])
def authenticate_user ():
start_time = datetime.now()
end_time = start_time + timedelta( milliseconds = 500 )
username = request.form[ 'username' ]
password = request.form[ 'password' ]
# Perform authentication
is_authenticated = check_credentials(username, password)
# Add random micro delays
sleep(random.uniform( 0.001 , 0.005 ))
# Wait until exactly 500ms has elapsed
while datetime.now() < end_time:
pass
if is_authenticated:
return render_template( "/success.html" , value = username)
else :
return render_template( "/index.html" ), 401
Defense-in-Depth Strategy
Input Validation
Whitelist allowed file types
Validate file content matches extension
Scan uploads with antivirus
Limit file sizes
Execution Prevention
Disable macros by default
Sandbox file processing
Use Content Security Policy
Application control policies
Timing Attack Mitigation
Implement isochronous functions (constant execution time)
Add random micro delays
Use constant-time comparison for secrets
Implement strict rate limiting
User Education
Train users to recognize phishing
Warn about macro-enabled files
Establish verification procedures
Implement reporting mechanisms
Additional Security Measures
Side-channel attacks are difficult to detect in action, often do not leave any trace, and may not alter a system while running. Code review with specific attack scenarios in mind is essential.
Best Practices
Code Review : Specifically look for timing-dependent operations in security-critical code
Randomize Operations : Add noise through random micro delays in cryptographic processes
Constant-Time Functions : Ensure operations run for exactly the same duration regardless of input
Rate Limiting : Implement aggressive rate limiting on authentication endpoints
Whitelist Firewalls : Block unnecessary outbound connections
Application Control : Restrict which applications can execute files
References