Cyber Security Hackathon Training
Cyber Security Hackathon Training
1
CYBER SECURITY TECHNICAL
DOCUMENT
VERSION 1.0
2
Index
1 SQL Injection 04 - 09
3 OSINT 15 - 19
5 Reverse Engineering 23 - 26
6 PHP Deserialization 27 - 30
7 Phishing 31 - 34
8 Memory Forensics 35 - 39
9 Disk Forensics 40 - 44
10 Quishing 45 - 47
11 JWT Token 48 - 52
12 CSRF Token 53 - 56
13 Network Analysis 57 - 60
14 PCAP Analysis 61 - 65
15 Magic Bytes 66 - 68
3
SQL Injection
1. What is SQL Injection?
SQL Injection (SQLi) is a code injection technique that exploits vulnerabilities in a web
application’s software by manipulating SQL queries. Attackers can retrieve or modify the
database contents and, in some cases, even execute administrative operations.
4
3. Common SQL Injection Payloads
5
' UNION SELECT username, password FROM users -- (Dump data from a table)
6
character-by-character)
a. Bypassing Authentication
' OR '1'='1':-
Bypasses login forms by manipulating the WHERE clause of the SQL query.
b. Union Attack
7
' UNION SELECT @@version --
➔ Stored Procedures: Encapsulate SQL queries, making it harder to inject malicious code.
8
➔ Input Validation & Escaping: Validate all user inputs and escape special characters to
prevent their execution in SQL.
➔ Least Privilege Principle: Restrict database permissions for users interacting with the
web application.
➔ Web Application Firewalls (WAFs): Detect and block SQL injection attempts.
➢ Manual Testing: Use payloads such as 1' OR '1'='1' -- in form inputs and observe results.
8. Resources
9
Broken Access Control
Broken Access Control occurs when a web application fails to enforce proper permissions,
allowing users to access data or functionalities they shouldn’t. Attackers can exploit this to gain
unauthorized access to sensitive resources.
Occurs when internal objects (such as files, records, or database keys) are exposed and can be
directly accessed by users via modified URLs or request parameters.
10
Example: /user/1234 changed to /user/1235 to access another user's data.
When the application fails to verify if a user has the appropriate permissions to execute a
particular function.
c. Forceful Browsing
d. Privilege Escalation
Users with limited access can gain higher privileges (e.g., from a regular user to an admin) due
to improper checks.
Example: User modifies their role parameter from user to admin in an HTTP
request.
3. Exploitation Techniques
11
a. Horizontal Privilege Escalation
● Accessing Other Users' Data: An attacker changes a URL parameter to access another
user’s private data.
● Unauthorized Administrative Access: A regular user manually navigates to an admin
page to access protected features.
● Modifying User Roles: Altering hidden parameters to escalate privileges or gain
additional functionality.
a. Deny by Default
● All access should be denied by default, and explicit permissions should be granted only
to specific roles or users.
12
b. Role-Based Access Control (RBAC)
● Implement RBAC to ensure users have only the permissions necessary for their role.
● Ensure proper checks are performed at both the UI and API levels for critical actions and
sensitive data.
e. Session Management
● Tie sessions to specific users and roles. Prevent session hijacking by enforcing
re-authentication for sensitive actions.
● Automated Tools:
○ OWASP ZAP: Can identify insecure object references and missing function-level
access controls.
○ Burp Suite: Security testing tool with a wide range of access control exploitation
features.
13
7. Common Tools for Exploiting Broken Access Control
● Postman: Test APIs and modify request parameters to check for access control flaws.
● Burp Suite: Automated scanner and manual testing tool to manipulate requests.
● OWASP ZAP: An open-source web application security scanner that helps test access
control vulnerabilities.
8. Prevention Checklist
● Verify access control checks are in place at both client and server levels.
9. Resources
14
Osint
1. What is OSINT?
OSINT stands for Open-Source Intelligence. It refers to the process of collecting and analyzing
publicly available data to gather actionable intelligence. This data can be accessed through
various sources, such as websites, social media, public records, forums, and other online
databases.
2. OSINT Process
15
➔ Processing: Filter and organize raw data.
➔ Analysis: Derive meaningful insights from the collected data.
➔ Reporting: Present findings in a concise, actionable format.
3. Types of OSINT
● Passive OSINT: Gathering data without direct interaction with the target (e.g., searching
websites, public records).
● Active OSINT: Involves interaction with the target, such as sending emails or filling out
forms to elicit a response.
16
● Search Engine Dorking: Using advanced search operators to uncover hidden or sensitive
information on search engines.
● Whois Lookup: Identifying domain ownership, IP address allocations, and DNS
information.
● Geolocation: Tracking locations from images, videos, and social media check-ins.
(e.g., site:example.com).
17
(e.g., filetype:pdf).
(e.g., inurl:admin).
(e.g., related:example.com).
➔ Legal Compliance: Ensure data collection follows the laws and regulations of the
country, including privacy laws (GDPR, CCPA).
➔ Avoid Hacking: OSINT focuses on open, publicly available data. Engaging in activities
such as password cracking or server intrusion is illegal.
➔ Respect Privacy: Avoid using OSINT to infringe on individuals' personal rights or stalk
them.
18
➔ Threat actor communications on forums.
➔ Censys: Search engine for discovering devices, certificates, and websites on the internet.
➔ OSINTCurio.us: A blog and community offering in-depth OSINT analysis and research.
19
Reverse Image Search
1. What is Reverse Image Search?
Reverse image search is a technique that allows users to search the internet using an image as
the query instead of text. It enables users to find similar images, track the original source of an
image, and identify modifications or usage across the web.
● Finding Image Sources: Identify where an image originated or who created it.
● Checking Image Authenticity: Verify if an image has been altered or is being misused.
● Discovering Similar Images: Locate variations or similar images for design inspiration.
20
● Identifying People or Places: Find out more about people or locations depicted in the
image.
● TinEye: A dedicated reverse image search engine that tracks image usage across the
web.
● Bing Visual Search: Microsoft's reverse image search tool that provides visual search
results.
● Yandex Images: Russian search engine with a powerful reverse image search feature.
● Pinterest Lens: Allows users to find visually similar images and related pins on Pinterest.
● CamFind: Mobile app that lets users take a picture and find similar images or products.
21
○ Open the Pinterest app or website.
○ Click on the camera icon to upload an image or take a photo.
○ Discover similar images and related pins.
22
Reverse Engineering
1. What is Reverse Engineering?
● Static Analysis: Examining the code or structure of a system without executing it. This
includes reading source code, analyzing binaries, or reviewing documentation.
● Dynamic Analysis: Executing the system and observing its behavior in real-time, which
may involve debugging and monitoring system calls or memory usage.
23
● Hardware Reverse Engineering: Disassembling physical devices to analyze their
components, circuitry, and functions.
● Disassembly: Converting machine code back into assembly language for analysis.
● Decompilation: Translating compiled code back into high-level source code.
● Debugging: Using debugging tools to step through code execution to understand the
program flow and detect anomalies.
● Network Analysis: Capturing and analyzing network traffic to understand communication
protocols and data exchange.
● Protocol Analysis: Examining the protocols used for communication between devices or
software to identify vulnerabilities or compatibility issues.
● Ghidra: A free and open-source software reverse engineering suite developed by the
NSA.
● IDA Pro: A powerful disassembler and debugger widely used for static and dynamic
analysis (commercial tool).
● Radare2: An open-source framework for analyzing binaries and performing reverse
engineering tasks.
● OllyDbg: A 32-bit assembler level analyzing debugger for Windows applications.
● x64dbg: An open-source debugger for Windows that supports both 32-bit and 64-bit
applications.
● Cutter: A Qt and C++ GUI powered by Radare2, providing a user-friendly interface for
reverse engineering.
● Wireshark: A network protocol analyzer that captures and inspects network packets.
● apktool: A tool for reverse engineering Android APK files to decode resources to their
original form.
24
6. Reverse Engineering Process
1. Define Objectives: Clearly outline the goals of the reverse engineering effort (e.g.,
understanding functionality, discovering vulnerabilities).
2. Data Collection: Gather relevant software, documentation, or hardware for analysis.
3. Static Analysis: Review the code structure, identify key components, and look for
potential vulnerabilities or interesting features.
4. Dynamic Analysis: Execute the system in a controlled environment, observing its
behavior and interactions.
5. Documentation: Keep detailed records of findings, including diagrams, code snippets,
and analysis results.
6. Reporting: Compile findings into a comprehensive report that addresses the initial
objectives.
7. Ethical Considerations
● Legal Compliance: Ensure that reverse engineering practices comply with copyright and
intellectual property laws.
● Respect Privacy: Avoid using reverse engineering to compromise personal or
confidential information.
● Intent: Use reverse engineering for ethical purposes, such as improving security or
interoperability, rather than malicious activities.
8. Applications in Cybersecurity
25
● Security Audits: Assessing existing systems for vulnerabilities by replicating attack
scenarios.
● Books:
○ "Practical Reverse Engineering" by Bruce Dang et al.
○ "Reversing: Secrets of Reverse Engineering" by Eldad Eilam.
● Online Courses:
○ Cybrary's reverse engineering courses.
○ Udemy's reverse engineering courses.
● Communities and Forums:
○ Reverse Engineering Stack Exchange.
○ Reddit’s r/ReverseEngineering.
26
PHP Deserialization
1. What is PHP Deserialization?
PHP Deserialization is the process of converting a serialized string back into its original PHP
object or data structure. Serialization converts data into a format suitable for storage or
transmission, while deserialization restores the data to its original form.
Deserialization: Converts the serialized string back to the original data structure.
$unserialized = unserialize($serialized);
print_r($unserialized);
// Output: Array ( [name] => Alice [age] => 25 )
27
3. PHP Deserialization Vulnerability Example
O:8:"Exploit":0:{}
● This could create an object of the Exploit class, allowing the attacker to manipulate
the application if the class has exploitable methods (e.g., __wakeup() or
__destruct()).
● Remote Code Execution (RCE): Attacker can inject code that is executed when a
vulnerable class method is called.
● Object Injection: Creating unauthorized objects that affect application logic.
● Denial of Service (DoS): Large or malicious data structures may cause the server to
crash.
● Authentication Bypass: Exploiting improperly serialized user sessions or objects.
28
● Disable PHP Object Serialization: Avoid using serialize() and unserialize()
when possible.
Crafting Payloads: Attackers create payloads containing serialized objects with malicious logic.
Example:
O:8:"Exploit":1:{s:4:"code";s:20:"system('ls /');";}
● Use Public Exploit Tools: Tools like PHPGGC (PHP Generic Gadget Chains) can generate
payloads to exploit vulnerable deserialization.
PHPGGC is a tool that generates gadget chains for PHP object injection:
29
● PHP Manual: PHP serialize() and unserialize()
● PHPGGC Tool: PHPGGC
30
Phishing
1. What is Phishing?
Phishing is a form of cyber attack that involves tricking individuals into providing sensitive
information, such as usernames, passwords, credit card numbers, or other personal data.
Attackers impersonate legitimate entities through various communication channels, often
leading victims to fraudulent websites or malicious attachments.
● Email Phishing: The most common form, where attackers send emails that appear to be
from trusted sources, often including links to fake websites.
31
● Whaling: A type of spear phishing that targets high-profile individuals, such as executives
or senior management, often with significant financial gain as the goal.
● Vishing (Voice Phishing): Phishing conducted through voice calls, where attackers
impersonate legitimate entities to extract sensitive information.
● Smishing (SMS Phishing): Phishing attacks carried out via SMS or text messages, often
containing malicious links.
● Urgency Tactics: Messages that create a sense of urgency, prompting immediate action
(e.g., "Your account will be suspended unless you verify it now!").
● Spoofed URLs: Links that appear legitimate but lead to malicious sites. Attackers often
use similar domain names to trick users (e.g., using "paypal-secure.com" instead of
"paypal.com").
● Malicious Attachments: Emails containing attachments that, when opened, can install
malware on the victim's device.
● Fake Login Pages: Fraudulent websites designed to look like legitimate login pages,
capturing user credentials when they attempt to sign in.
32
● Generic Greetings: Emails that start with "Dear Customer" instead of using the
recipient's name.
● Spelling and Grammar Errors: Poorly written emails with typos or awkward phrasing.
● Verify Sender's Email Address: Check if the email address matches the legitimate
organization's address.
● Hover Over Links: Place the cursor over links (without clicking) to see the actual URL
destination.
● Look for HTTPS: Legitimate websites will have HTTPS in the URL; however, this alone is
not a guarantee of safety.
● Analyze the Content: Consider the tone and urgency of the email. If it feels off, verify it
through official channels.
● Education and Training: Conduct regular training sessions for employees on recognizing
and responding to phishing attempts.
● Implement Email Filters: Use email security solutions to filter out suspected phishing
emails.
● Enable Two-Factor Authentication (2FA): Adding an extra layer of security can help
protect accounts even if credentials are compromised.
● Regular Software Updates: Keep software, including security tools, up to date to protect
against vulnerabilities.
33
● Anti-Phishing Solutions: Software solutions like Mimecast, Proofpoint, or Microsoft
Defender for Office 365 provide protection against phishing attacks.
● Browser Extensions: Tools like Web of Trust (WOT) or Netcraft can help identify
malicious websites.
● Email Security Solutions: Use email gateways with phishing detection capabilities to
filter out suspicious messages.
● Change Passwords Immediately: Update passwords for affected accounts and any
other accounts using similar credentials.
● Monitor Financial Accounts: Check for unauthorized transactions and report any
suspicious activity to your bank.
● Report the Attack: Inform your organization's IT department and report the phishing
attempt to the relevant authorities (e.g., FTC in the US).
● Enable Identity Theft Protection: Consider using identity theft protection services if
sensitive information has been compromised.
34
Memory Forensics
1. What is Memory Forensics?
Memory forensics is the process of analyzing volatile memory (RAM) to extract valuable
information about the state of a system at a given point in time. It is a crucial aspect of digital
forensics, enabling investigators to uncover evidence related to malware infections, system
intrusions, and other malicious activities that may not be captured in disk-based analysis.
● Malware Analysis: Identify and analyze malicious processes and code running in
memory.
● User Activity Monitoring: Determine what applications were running and what actions
users performed prior to an incident.
35
● Data Recovery: Recover sensitive information, such as passwords or encryption keys,
that may reside in memory.
● Volatile Memory: Memory that is lost when a system is powered off. It includes RAM
and cache memory.
● Memory Image: A complete capture of the system's RAM, used for analysis.
36
4. Common Memory Forensics Tools
● Rekall: Another open-source memory analysis tool with a user-friendly interface, suitable
for examining RAM captures.
● FTK Imager: A forensic imaging tool that can capture memory dumps as well as disk
images.
● WinDbg: A Microsoft debugger that can be used to analyze Windows memory dumps.
● LiME (Linux Memory Extractor): A tool used to acquire memory images from Linux
systems.
● DumpIt: A simple tool that can create memory images of Windows systems.
1. Capture Memory Image: Use tools like FTK Imager, DumpIt, or LiME to create a complete
memory dump from the target system.
2. Load Memory Image: Import the captured memory image into a forensic analysis tool
like Volatility or Rekall.
37
3. Analyze the Memory:
○ Identify Running Processes: List active processes and their memory usage.
○ Extract Artifacts: Look for valuable artifacts such as user credentials, encryption
keys, and documents.
○ Analyze File System Structures: Investigate file handles and DLLs loaded into
memory.
4. Document Findings: Keep detailed notes on the analysis process and findings, including
evidence of malicious activity.
● Processes and Threads: Information about running processes and their states.
● Loaded Modules: Information about DLLs and kernel modules loaded in memory.
● User Data: Cached user passwords, browser sessions, and other sensitive information.
● Kernel Objects: Insights into system-level activity, including drivers and system calls.
● Data Volatility: Memory is ephemeral, meaning evidence can be lost if not captured
quickly.
38
● Encryption: Encrypted data in memory can complicate analysis.
● Memory Forensics Techniques: The need for expertise in memory structures and
operating system internals.
● Large Volumes of Data: Memory images can be large and complex, requiring efficient
filtering and analysis.
● Preserve Evidence: Ensure the integrity of the memory image by using write-blocking
techniques during capture.
● Use Trusted Tools: Rely on well-known and widely accepted forensic tools to avoid
introducing errors.
● Maintain Chain of Custody: Document every step taken during the analysis process to
uphold legal standards.
● Regular Training: Keep skills updated with the latest techniques and tools in memory
forensics.
● Books:
○ Practical Memory Forensics by Andrew Case, Jamie Levy, and AAron Walters.
○ The Art of Memory Forensics by Michael Hale Ligh, Andrew Case, Jamie Levy, and
AAron Walters.
● Online Courses: Platforms like Cybrary, Udemy, and SANS offer courses on digital
forensics and memory analysis.
● Communities and Forums: Engage with online communities like the SANS Institute or
various cybersecurity forums for knowledge sharing.
39
Disk Forensics
1. What is Disk Forensics?
Disk forensics is the process of analyzing computer hard drives and other storage media to
recover, preserve, and analyze data in a way that is legally admissible. It is a crucial aspect of
digital forensics, often used in investigations involving cybercrime, data breaches, and data
recovery.
● Data Recovery: Retrieve lost or deleted files from damaged or corrupted storage media.
● Evidence Preservation: Maintain the integrity of digital evidence for legal proceedings.
40
● Incident Response: Investigate security incidents to determine the extent of a breach or
compromise.
● Storage Media: Devices such as hard drives, SSDs, USB drives, and memory cards.
● Disk Image: A sector-by-sector copy of a storage device, used for analysis without
altering the original data.
● File System: The method and data structure that an operating system uses to manage
files on a disk.
● Logical vs. Physical Analysis: Logical analysis focuses on file structures and content,
while physical analysis looks at raw data and disk sectors.
● EnCase: A comprehensive forensic tool for disk imaging, analysis, and reporting.
● FTK (Forensic Toolkit): A forensic software that provides disk imaging and data recovery
capabilities, along with analysis tools.
● Autopsy: An open-source digital forensics platform that supports disk analysis and
recovery.
● Sleuth Kit: A collection of command-line tools for disk forensic analysis, often used with
Autopsy.
● dd and dcfldd: Command-line tools for creating disk images in a forensic manner.
41
● X1 Social Discovery: Focused on the collection and analysis of social media data, with
some disk forensic capabilities.
1. Evidence Collection:
○ Create a forensic disk image using tools like FTK Imager or dd.
2. Data Preservation:
○ Store the original media securely and keep a documented chain of custody.
○ Verify the integrity of the disk image using checksums (e.g., MD5, SHA-1).
3. Data Analysis:
○ File System Analysis: Examine file systems (FAT, NTFS, EXT) for file structures,
timestamps, and metadata.
○ Keyword Searches: Search for specific terms, patterns, or file types relevant to
the investigation.
○ Recover Deleted Files: Identify and restore deleted files from unallocated space
or slack space.
4. Documentation:
○ Maintain detailed notes on the analysis process, findings, and any tools or
techniques used.
○ Prepare a forensic report summarizing the analysis and findings for legal
proceedings.
● File Metadata: Information about files, such as creation, modification, and access
timestamps.
● System Logs: Logs from the operating system that may provide insights into user
actions and system events.
42
● User Data: Documents, images, emails, and other files created or accessed by users.
● Temporary Files: Files created by applications that may contain remnants of user
activity.
43
● Books:
○ Digital Forensics and Cyber Crime by T. A. J. O. T. S. (A. M. J.) and M. E. M. T. (R.
J. M.)
○ File System Forensic Analysis by Brian Carrier.
● Online Courses: Platforms like Udemy, Coursera, and SANS offer courses on digital
forensics and incident response.
● Communities and Forums: Join forums like the Digital Forensics Community and attend
conferences such as DEF CON and Black Hat for networking and knowledge sharing.
44
Quishing
1. What is Quishing?
Quishing is a form of cyber attack that combines traditional phishing techniques with QR codes.
Attackers use QR codes to direct victims to malicious websites, download malware, or provide
sensitive information, often under the guise of legitimate services or promotions.
45
4. Risks Associated with Quishing
● Verify Sources: Only scan QR codes from trusted sources or known contacts.
● Preview URLs: Use a QR code scanner that previews the URL before redirecting you,
allowing you to verify its legitimacy.
● Avoid Providing Sensitive Information: Never enter personal data or credentials on
unfamiliar websites accessed via QR codes.
● Educate Yourself and Others: Raise awareness about quishing and teach others how to
recognize and avoid such attacks.
46
● URL Scanning Tools: Use services like VirusTotal to scan URLs before visiting them.
● Regular Security Training: Conduct training sessions for employees and users to identify
and respond to potential quishing attempts.
● QR Code Readers: Apps that can scan QR codes and preview the destination URL before
opening it.
● URL Shortener Checkers: Tools that help verify the legitimacy of shortened URLs linked
to QR codes.
● Cybersecurity Blogs: Follow reputable cybersecurity blogs and news sites for the latest
information on quishing and related threats.
● Online Courses: Platforms like Coursera and Udemy offer courses on cybersecurity
awareness, including phishing and quishing.
● Community Forums: Participate in cybersecurity forums and discussions to stay
informed about emerging threats and defenses.
47
JWT Token
1. What is a JWT?
JWT (JSON Web Token) is an open standard (RFC 7519) for securely transmitting information
between parties as a JSON object. It is compact, URL-safe, and can be used for authentication
and information exchange. JWTs are commonly used in web applications for stateless
authentication and authorization.
2. Structure of a JWT
● Header: Contains metadata about the token, including the type (JWT) and the signing
algorithm used (e.g., HS256).
● Payload: Contains the claims or the data being transmitted. This can include standard
claims (like iss, exp, sub, aud) and custom claims defined by the application.
48
● Signature: Used to verify the authenticity of the token. It is created by combining the
encoded header and payload and signing it with a secret key using the specified
algorithm.
eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9. // Header
eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.
// Payload
SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c // Signature
Claims are pieces of information about the user or context. They can be classified into three
types:
● Registered Claims: Predefined claims that are recommended but not mandatory.
Examples include:
○ iss: Issuer of the token.
○ sub: Subject of the token (usually the user ID).
○ aud: Audience for which the token is intended.
○ exp: Expiration time (in Unix time).
○ iat: Issued at time (in Unix time).
49
● Public Claims: Custom claims defined by the application that can be used to convey
information.
● Private Claims: Claims created to share information between parties that agree on using
them.
4. Signing Algorithms
● HMAC (Symmetric Key): Both the issuer and the consumer share a secret key (e.g.,
HS256).
● RSA or ECDSA (Asymmetric Key): The issuer uses a private key to sign the token, while
the consumer uses a public key to verify it (e.g., RS256).
● Authentication: After successful login, the server generates a JWT and sends it to the
client, which stores it (typically in local storage or cookies) for future requests.
● Authorization: JWTs can convey user permissions or roles, allowing servers to check
access levels for protected resources.
● Information Exchange: JWTs can carry information between parties securely and can be
verified to ensure data integrity.
● Compact: The tokens are small and can be sent via URLs, POST requests, or in HTTP
headers.
50
● Self-contained: JWTs contain all the necessary information about the user, reducing the
need to query the database multiple times.
● Cross-domain: JWTs can be used across different domains without issues related to
CORS.
● Token Revocation: Once a JWT is issued, it cannot be easily revoked unless additional
mechanisms are implemented (e.g., maintaining a blacklist).
● Token Size: Although compact, large payloads can lead to performance issues when
transmitted.
● Complexity: Implementing JWT correctly requires careful attention to security practices.
9. JWT Libraries
● JavaScript: jsonwebtoken
● Python: PyJWT
● Java: jjwt
● .NET: System.IdentityModel.Tokens.Jwt
● PHP: firebase/php-jwt
51
10. Resources for Learning More About JWT
52
CSRF Token
1. What is a CSRF Token?
A CSRF Token (Cross-Site Request Forgery Token) is a security mechanism used to prevent
CSRF attacks, where unauthorized commands are transmitted from a user that the web
application trusts. CSRF tokens are unique, unpredictable values generated by the server and
included in requests made by the client.
● An attacker tricks a user into performing unwanted actions on a web application where
they are authenticated (e.g., submitting a form).
● For example, the user might be logged into their bank account, and the attacker sends a
malicious link or form that, when executed, transfers funds without the user’s
knowledge.
53
3. How CSRF Tokens Work
● Token Generation: When a user accesses a form on a web page, the server generates a
unique CSRF token and embeds it in the form.
● Token Submission: When the form is submitted, the CSRF token is sent along with the
request.
● Token Validation: The server checks the received CSRF token against the one stored in
the user session. If they match, the request is processed; if not, the request is rejected.
1. Token Generation:
○ Generate a unique token for each user session or each request.
○ Store the token in the user’s session or database.
2. Embedding the Token:
Send the CSRF token in headers for AJAX requests, often using JavaScript:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('input[name="csrf_token"]').val()
}
});
4. Token Verification:
On form submission or AJAX request, verify that the token received matches the one stored on
the server:
if request.form['csrf_token'] != session['csrf_token']:
abort(403) # Forbidden
54
5. Best Practices for CSRF Tokens
● Unique per Session: Generate a unique token for each session or request, not just for a
user’s session.
● Secure Storage: Store the token securely, ideally in the user session or in a database.
● Token Length and Complexity: Ensure tokens are sufficiently long and complex to resist
brute-force attacks.
● Same-Site Cookies: Use the SameSite attribute for cookies to prevent them from being
sent in cross-origin requests.
● Review Forms: Ensure that all state-changing forms include CSRF tokens.
● Manual Testing: Attempt to submit forms without CSRF tokens to see if the application
properly rejects the requests.
While CSRF tokens are the most common defense mechanism, other strategies include:
● Same-Site Cookie Attribute: Set the SameSite attribute on cookies to prevent them
from being sent with cross-origin requests.
● Double Submit Cookies: Send the CSRF token in both a cookie and as a request
parameter and validate both.
55
● User Interaction Verification: Implement additional confirmation steps for sensitive
actions (e.g., re-entering a password).
56
Network Analysis
1. What is Network Analysis?
Network Analysis involves the process of inspecting, monitoring, and evaluating a computer
network's performance, security, and efficiency. It aims to optimize network functionality,
identify potential issues, and enhance security measures.
● Traffic Analysis: Analyze data packets to understand usage patterns and detect
anomalies.
● Network Topology: The layout of devices, connections, and data flows within the
network (e.g., star, ring, mesh).
● Data Packets: Units of data transmitted across a network, containing headers and
payloads.
57
4. Network Analysis Tools
● Wireshark: A powerful network protocol analyzer that captures and inspects data
packets in real-time.
● Tcpdump: A command-line packet analyzer used to capture and analyze TCP/IP packets.
● Nmap: A network scanning tool used for network discovery and security auditing.
● NetFlow Analyzer: Monitors and analyzes network traffic patterns using NetFlow data.
● Packet Sniffing: Capturing data packets flowing through the network to analyze traffic.
● Traffic Flow Analysis: Monitoring bandwidth usage and identifying peak usage times.
● Vulnerability Scanning: Scanning the network for security weaknesses using tools like
Nessus or OpenVAS.
● Protocol Analysis: Examining the protocols in use and their configurations to ensure
compliance and performance.
1. Define Objectives: Establish the goals of the analysis (e.g., performance monitoring,
security assessment).
2. Collect Data: Use network analysis tools to gather traffic data, logs, and performance
metrics.
3. Analyze Data: Examine the collected data for patterns, anomalies, and potential issues.
4. Identify Issues: Diagnose problems such as bottlenecks, high latency, or unauthorized
access.
58
5. Recommend Improvements: Suggest actions based on findings to enhance network
performance and security.
● Bandwidth Utilization: Measure of how much bandwidth is being used compared to its
capacity.
● Latency: The time taken for data to travel from the source to the destination.
● Packet Loss: The percentage of packets that do not reach their destination, which can
indicate network congestion or faults.
● Throughput: The actual amount of data transmitted successfully over a specific time
period.
● Update Tools and Techniques: Keep network analysis tools and methodologies up to
date to address evolving threats.
● Segment the Network: Use segmentation to isolate critical systems and reduce the
attack surface.
● Implement Security Measures: Employ firewalls, intrusion detection systems (IDS), and
proper access controls to protect the network.
● High Data Volumes: Managing and analyzing large amounts of network data can be
overwhelming.
59
● Encrypted Traffic: Analyzing encrypted traffic (e.g., HTTPS) can complicate visibility into
the data being transmitted.
● Dynamic Networks: Networks that frequently change can make consistent monitoring
difficult.
● Books: Look for titles on network security, performance analysis, and troubleshooting.
● Online Courses: Platforms like Coursera, Udemy, or LinkedIn Learning offer courses on
networking and analysis.
● Blogs and Forums: Participate in networking forums and follow cybersecurity blogs for
the latest trends and insights.
60
PCAP Analysis
1. What is PCAP?
PCAP (Packet Capture) refers to the process of capturing and analyzing network traffic. A PCAP
file contains raw network packets, including headers and payload data, which can be inspected
to understand network behavior, diagnose issues, or investigate security incidents.
61
● Performance Monitoring: Monitor bandwidth usage, latency, and network congestion.
● Wireshark: The most popular packet analyzer with a graphical interface for live and
offline PCAP analysis.
● Tcpdump: A command-line packet sniffer that captures packets and can save them as
PCAP files.
● TShark: The command-line version of Wireshark, suitable for scripting and automation.
● NetworkMiner: A tool focused on extracting artifacts from PCAP files (e.g., files,
credentials).
● Suricata: An intrusion detection and prevention system (IDS/IPS) that can analyze PCAP
files for suspicious activity.
● Headers: Information about the captured packet, including timestamp, source and
destination addresses, and protocols.
● Payload: The actual data transferred within the packet (e.g., HTTP requests, DNS
queries).
62
2. Filter Traffic:
● Use display filters to isolate relevant packets (e.g., filter HTTP traffic in Wireshark):
http
ip.addr == 192.168.1.1
tcp or udp
○ Analyze Latency: Look for delays in TCP handshakes or high ping times.
○Examine Bandwidth Usage: Identify which hosts or services consume the most
bandwidth.
4. Detect Anomalies and Threats:
○ Reconstruct HTTP files or streams (in Wireshark, right-click and choose "Follow
TCP Stream").
○ Extract files from captured traffic using NetworkMiner or Wireshark export tools.
6. Generate Reports:
○ Export summaries, statistics, or filtered traffic from Wireshark for further analysis
or reporting.
63
6. Common Protocols to Inspect in PCAP Analysis
Filter by IP address:
ip.addr == 10.0.0.1
Filter by Port:
tcp.port == 80
http.request
64
9. Best Practices for PCAP Analysis
● Use Filters Wisely: Narrow down large datasets using display and capture filters.
● Correlate with Logs: Use network and system logs to validate findings from PCAP files.
● Automate with Scripts: Use tools like TShark or Python scripts for repetitive tasks.
● Monitor Encrypted Traffic: Understand the limitations of encrypted traffic and focus on
metadata (e.g., IPs, ports).
65
Magic Bytes
Magic bytes (or magic numbers) are unique sequences of bytes used at the beginning of a file
to identify the file type or format. These bytes act as a signature or fingerprint that allows
software to recognize the content of a file, even if the file extension is incorrect or missing.
● File Type Identification: Determine the correct file type, irrespective of its extension.
● File Integrity Verification: Check if files have been tampered with or corrupted.
● Malware Analysis: Identify disguised malicious files (e.g., a malicious script with a .jpg
extension).
● Forensics and Reverse Engineering: Analyze unknown files and validate their content.
66
4. How to Identify Magic Bytes
file Command: Identify the file type based on its magic bytes
file <filename>
67
● Forensics: Validate file types during forensic investigations.
● Intrusion Detection: Identify suspicious files uploaded to a server, even if the file
extensions have been changed.
● Reverse Engineering: Analyze binaries by examining their headers and magic bytes.
● Attackers may modify a file’s magic bytes to bypass security filters. For example,
changing the bytes of a malicious .exe to match that of an image file.
● Mismatch Detection: Use both file extensions and magic bytes to verify a file’s integrity.
● File Type Forgery: Be cautious of files where the extension does not match the magic
bytes.
● False Identification: Some files may have similar starting bytes, leading to incorrect
identification.
● Corrupted Files: Missing or altered magic bytes can make it hard to determine the
original file type.
● Hex Editors: Tools like HxD or 010 Editor allow you to explore file headers.
● The file Command Documentation: Learn more about the Linux file command.
● Online Magic Number Databases: Repositories that list common magic bytes for quick
reference.
68
—-------------------------------------------------------------EOF—------------------------------------------------------
69