Amazon Staff-Level Information Security Analyst Interview Preparation Guide
Amazon's interview process for Staff-level Information Security Analysts combines structured technical and behavioral evaluation across multiple interview types. The process typically includes initial recruiter screening, technical phone interviews assessing core security skills, onsite technical rounds covering cloud security architecture, detection engineering, and system design, supplemented by behavioral rounds evaluating Amazon Leadership Principles alignment and strategic thinking. The full loop tests deep expertise in security operations, decision-making under ambiguity, mentorship capability, and ability to drive security initiatives at organizational scale.
Interview Rounds
Recruiter Screening
What to Expect
Initial conversation with Amazon recruiter to assess background, career trajectory, and motivation for the Staff-level position. Discussion covers your progression in security roles, key accomplishments, specific interest in the Security Analyst position, and logistics (availability, relocation, work authorization). Recruiter may explore your knowledge of Amazon's security culture and why you're drawn to the role. This is a screening call to verify that your experience matches Staff-level expectations and assess cultural fit before investing in technical rounds.
Tips & Advice
Prepare a concise 2-3 minute narrative of your security career emphasizing progression to Staff level. Highlight 2-3 standout accomplishments showing depth, scope, and impact (e.g., 'Led a major incident investigation involving 50+ affected systems and coordinated response across 3 teams'). Articulate specific interest in the role—mention aspects like SOC modernization, cloud security at scale, detection engineering, or leading security initiatives. Research Amazon's security mission and mention what resonates with you. Prepare 1-2 thoughtful questions about the role or team. Keep answers concise; this is a lightweight screen, not a technical assessment.
Focus Topics
Motivation for Amazon Security Role
Explain genuine interest in this specific role and what aspects of Amazon's security mission, scale, or technical challenges appeal to you
Practice Interview
Study Questions
Career Progression to Staff-Level Security Role
Clearly articulate your journey from earlier security positions to Staff-level expertise, highlighting expanding scope of responsibility, technical depth, and growth in scope of influence
Practice Interview
Study Questions
Technical Phone Screen
What to Expect
First technical assessment with an Amazon security engineer or analyst. Expect 3-4 targeted technical questions, primarily scenario-based and focused on your incident response methodology, threat analysis, and SIEM expertise. Typical questions: 'Walk me through investigating a suspicious spike in failed login attempts,' 'How would you respond to a phishing report with a suspicious attachment?' or 'Describe your process for analyzing a security alert.' This round evaluates your ability to think systematically about security problems, apply structured investigation methodology, and communicate technical reasoning clearly without ambiguity.
Tips & Advice
For any incident response question, use the STAR method adapted for security investigations: (1) Detection—how did you identify the issue (monitoring alert, manual review, scan)? (2) Initial Assessment—severity rating, affected systems, blast radius estimate. (3) Containment—immediate actions to stop spread or prevent further impact. (4) Investigation & Root Cause—methodology and tools used to determine root cause (SIEM queries, log analysis, forensics). (5) Remediation—steps to fix vulnerability and prevent recurrence. (6) Post-Incident—new detection rules, process improvements, team training. Quantify impact when possible (e.g., 'investigation took 2 hours, affected 340 user accounts'). Think out loud and explain your reasoning at each step rather than jumping to conclusions. Demonstrate knowledge of practical tools: SIEM query syntax (Splunk SPL or similar), network analysis tools (Wireshark, tcpdump), threat intelligence sources. Reference the MITRE ATT&CK framework when discussing techniques. Show you understand both technical execution and business context of security decisions.
Focus Topics
Threat Analysis & Vulnerability Assessment
Methodology for identifying security vulnerabilities, analyzing threats, prioritizing remediation based on risk and business impact, and communicating findings to stakeholders
Practice Interview
Study Questions
Network Security & Packet Analysis
Understanding of network protocols (TCP/IP, DNS, HTTP), ability to analyze packet captures with tools like Wireshark, recognition of network-level attack signatures and indicators of compromise
Practice Interview
Study Questions
SIEM Tools, Log Analysis & Detection Engineering
Practical hands-on knowledge of SIEM platforms (Splunk, QRadar, Sentinel, or equivalent); ability to write queries to search for threat indicators, extract relevant data, correlate events, and identify patterns
Practice Interview
Study Questions
Incident Response & Investigation Methodology (NIST Framework)
Structured approach to incident response: detection and analysis, containment, eradication, recovery, and post-incident activities; ability to assess severity and prioritize investigation steps
Practice Interview
Study Questions
Technical Deep Dive - Cloud Security & AWS Architecture
What to Expect
Onsite technical round focused on AWS security architecture, cloud-native threat landscape, and detection in cloud environments. Expect scenario-based technical questions: 'How would you investigate a suspected compromise of an EC2 instance?' 'Design monitoring for a multi-account AWS environment,' 'Walk me through detecting lateral movement in AWS using IAM logs.' Questions assess understanding of AWS security services (IAM, CloudTrail, VPC Flow Logs, GuardDuty, Secrets Manager, KMS), shared responsibility model, and cloud-specific attack patterns. Interviewers evaluate your ability to think architecturally about cloud security and translate cloud security concepts into operational detection and response procedures.
Tips & Advice
Develop deep expertise in AWS security services: IAM roles, policies, and permission boundaries; VPC architecture, security groups, Network ACLs, and VPC Flow Logs; CloudTrail for API audit logging; GuardDuty for threat detection; Secrets Manager and KMS for encryption and secrets management; CloudWatch for monitoring. Understand the shared responsibility model deeply—AWS secures infrastructure, you secure your workloads. Prepare 2-3 detailed examples of real cloud security incidents you've investigated or detected, walking through your investigation methodology. For Staff level, discuss how you'd design monitoring at scale across multiple AWS accounts and regions. Discuss cloud-specific attack patterns: misconfigured S3 buckets, EC2 credential exposure, lateral movement via IAM permissions, data exfiltration through CloudFront or cross-account access. Be prepared to write or discuss CloudTrail query examples and explain how you'd use CloudTrail events to detect compromise. Explain trade-offs: real-time monitoring vs. batch analysis, centralized vs. distributed detection, cost vs. detection coverage.
Focus Topics
Compliance & Governance in AWS (SOC 2, PCI DSS, HIPAA, GDPR compliance on AWS)
Understanding of AWS compliance programs and certifications; mapping compliance requirements to technical controls; design of audit trails and evidence collection for compliance; compliance automation
Practice Interview
Study Questions
Data Protection in Cloud (Encryption, DLP, Data Classification)
Implementation of encryption at rest (KMS) and in transit (TLS); data classification strategies; data loss prevention controls; understanding when and where to apply encryption
Practice Interview
Study Questions
Cloud-Specific Threats & Detection Patterns
Recognition of cloud-native attack vectors (credential exposure, lateral movement via IAM, misconfiguration exploitation, data exfiltration); how to detect these patterns in AWS logs and telemetry
Practice Interview
Study Questions
Cloud Network Security & IAM Architecture
Design and implementation of IAM least-privilege policies, VPC isolation patterns, security group rule sets, and network access controls; understanding identity and access management at scale in cloud
Practice Interview
Study Questions
AWS Security Services (CloudTrail, GuardDuty, VPC Flow Logs, IAM)
Deep proficiency with AWS native security tools and services; understanding of what each service logs, how to query logs, and how to interpret findings in context of threat investigation
Practice Interview
Study Questions
Detection Engineering & SIEM Architecture
What to Expect
Onsite technical round focused on designing and optimizing detection systems and SIEM infrastructure. Expect questions like: 'Design a SIEM pipeline for detecting insider threat activity,' 'How would you build detection rules to identify lateral movement in Windows environments?' 'Design log aggregation architecture for a large organization spanning cloud and on-premises.' Questions may include whiteboarding or detailed discussion of detection architecture, alert tuning strategies, and scaling detection operations. Evaluators assess your ability to think architecturally about detection engineering, mentor others on detection design, and balance detection coverage with false positive management.
Tips & Advice
Develop a clear detection engineering methodology: (1) Threat Understanding—use MITRE ATT&CK to define threat or technique you're detecting; (2) Observable Identification—what security events or log entries would indicate this technique? (3) Detection Logic—write detection rule in SIEM query language or pseudocode; (4) False Positive Tuning—discuss how you'd refine rules to reduce false positives; (5) Validation—how do you test the detection? (6) Documentation and Tuning—post-deployment improvements. For Staff level, discuss how you'd scale detection program—coordinate detection rules across multiple tools, collaborate with other teams, mentor junior analysts on detection design. Prepare specific examples of detections you've built with quantified success metrics (e.g., 'I designed a detection for T1021 lateral movement that caught 3 real incidents in the first month with zero false positives'). Demonstrate understanding of SIEM query optimization—efficiency, scalability, and performance tuning. Discuss trade-offs: detection coverage vs. false positives, real-time alerting vs. batch investigations, centralized vs. distributed detection strategies.
Focus Topics
Threat Hunting & Proactive Threat Detection
Methodology for proactive threat hunting: developing investigation hypotheses, searching logs for evidence, validating hunts, and converting hunts into permanent detections
Practice Interview
Study Questions
Incident Detection & Response Automation
Design automated response playbooks and orchestration for security alerts; determining when to automate vs. requiring human judgment; integration of detection and response systems
Practice Interview
Study Questions
False Positive Tuning & Alert Management
Strategies for reducing false positives at scale: whitelisting legitimate activity, tuning alert thresholds, understanding business context, managing alert fatigue in SOC operations
Practice Interview
Study Questions
Detection Engineering Methodology & MITRE ATT&CK Framework
Systematic approach to developing security detections: threat/technique definition using MITRE ATT&CK, observable identification, detection logic development, false positive tuning, validation, and ongoing optimization
Practice Interview
Study Questions
SIEM Query Language & Rule Development (Splunk SPL, KQL, or equivalent)
Proficiency in writing, optimizing, and maintaining queries in SIEM tools; understanding of query performance, field extraction, correlation rules, and statistical detection methods
Practice Interview
Study Questions
System Design & Security Architecture
What to Expect
Onsite round focused on designing secure systems and security architecture from first principles. Examples: 'Design a security monitoring architecture for a large organization spanning multiple cloud providers and on-premises infrastructure,' 'Design a threat intelligence ingestion and distribution pipeline,' 'Design a secure software deployment and supply chain security architecture,' or 'Design a data protection and DLP architecture.' You'll be asked to identify threats, propose layered controls across identity, network, data, and monitoring, discuss trade-offs (security vs. usability vs. cost), and justify technology choices. Evaluators assess strategic thinking, defense-in-depth understanding, ability to work with constraints (cost, complexity), and capacity to architect security at organizational scale.
Tips & Advice
Approach system design with structured methodology: (1) Understand Requirements—what needs protection? What's the scale? (2) Define Assumptions—fill in missing details logically and document them; (3) Identify Assets & Threats—what are critical assets? Use threat modeling (STRIDE) to identify attack vectors; (4) Propose Layered Controls—(A) Identity: IAM, MFA, SAML/OIDC, least privilege; (B) Network: segmentation, VPC isolation, firewalls, allowlist-based access; (C) Data: encryption at rest/transit, DLP, data classification; (D) Monitoring: logging, SIEM, alerting, forensics; (5) Discuss Trade-offs—explicitly address security vs. usability, cost vs. coverage, centralized vs. distributed approaches; (6) Scalability & Evolution—how does the architecture grow? How is it maintained? For Staff level, don't over-engineer; show judgment about where to focus effort. Reference real AWS services and security practices. Draw clear diagrams. For Staff level, discuss how you'd evangelize the architecture to stakeholders, mentor teams on implementation, and measure effectiveness through metrics. Avoid overly complex solutions; show pragmatism and understanding of when to say 'we accept this risk' or 'we monitor this manually until it becomes a priority.'
Focus Topics
Scalability, Cost Optimization & Technology Trade-offs
Design security solutions that scale efficiently with organizational growth; understand cost implications of architecture choices; balance technology options (buy vs. build, open source vs. commercial)
Practice Interview
Study Questions
Compliance Architecture & Policy Implementation
Map compliance requirements (SOC 2, PCI DSS, HIPAA, GDPR) to technical controls; design audit trails and evidence collection mechanisms; develop and communicate security policies and procedures
Practice Interview
Study Questions
Monitoring, Logging & Observability at Scale
Design centralized logging infrastructure; aggregate security events across distributed systems; implement security observability; understand data retention, cost implications, and compliance requirements
Practice Interview
Study Questions
Threat Modeling & Risk Assessment
Systematic threat identification using frameworks like STRIDE; vulnerability analysis; risk quantification; communicating risk to business stakeholders in terms they understand
Practice Interview
Study Questions
Security Architecture Design & Defense-in-Depth
Comprehensive security architecture spanning identity (IAM, MFA), network (segmentation, VPC isolation, firewalls), application, data (encryption, classification), and monitoring; understanding layered controls and trade-offs
Practice Interview
Study Questions
Behavioral & Leadership Round 1
What to Expect
Interview focused on behavioral competencies, decision-making, and alignment with Amazon's Leadership Principles. Expect 5-6 questions using the STAR method (Situation, Task, Action, Result). Examples: 'Tell me about a time you led a major security initiative or project,' 'Describe a significant conflict or disagreement with a colleague and how you resolved it,' 'Give an example of when you failed—what did you learn?' 'Tell me about a time you had to make a decision with incomplete information,' 'Describe when you drove change in your organization,' 'Tell me about a time you had to prioritize between competing security needs.' Evaluators assess your ability to collaborate, take ownership, communicate effectively, handle ambiguity, influence without authority, and learn from failures.
Tips & Advice
Develop a 'story bank' with 5-7 detailed stories covering: (1) Leading a security project or initiative from conception to completion; (2) Handling conflict or disagreement with colleagues; (3) Significant failure and lessons learned; (4) Operating with incomplete information and making a decision; (5) Influencing others or driving organizational change; (6) Mentoring team members or developing others; (7) Taking ownership of a difficult problem. Use STAR format rigorously: Situation (1-2 sentences of context—be specific about company, team size, context), Task (your specific responsibility—use 'I' ownership language), Action (specific steps you took—avoid 'we' statements; focus on your contribution), Result (quantified impact when possible—metrics, time saved, quality improvements). For Staff level, emphasize: how you drove strategy or influenced direction, evidence of mentoring team members, examples of scaling capabilities or improving processes, instances where you raised standards or changed how the team operates. Quantify impact: 'reduced MTTR from 4 hours to 45 minutes,' 'trained 12 junior analysts on threat hunting,' 'redesigned detection rules increasing alert quality by 60%,' 'led incident response for 3 major breaches.' Avoid generic answers; make stories specific and memorable with concrete details.
Focus Topics
Learning from Failure & Resilience
Examples of significant setbacks, failures, or difficult situations; how you processed the experience, what you learned, and how you applied lessons to future situations
Practice Interview
Study Questions
Mentorship & Team Capability Development
Stories of mentoring junior analysts, developing team capabilities, sharing knowledge, raising team's technical depth or operational maturity
Practice Interview
Study Questions
Collaboration & Cross-Functional Teamwork
Examples of working effectively with other teams (engineering, incident response, compliance, product teams); resolving disagreements; building consensus; achieving shared goals
Practice Interview
Study Questions
Ownership & Initiative Leadership
Stories demonstrating taking full ownership of security projects, initiatives, or improvements; driving them from conception through completion; delivering results despite obstacles
Practice Interview
Study Questions
Behavioral & Leadership Round 2
What to Expect
Second behavioral round focused deeply on Amazon Leadership Principles and cultural fit. Questions target specific principles: 'Deliver Results'—setting ambitious goals and executing despite constraints; 'Bias for Action'—making decisions with incomplete information and moving fast; 'Earn Trust'—admitting mistakes and being honest; 'Think Big'—long-term thinking and strategic vision; 'Customer Obsession'—understanding how security serves Amazon's customers and business. Expect 4-5 questions using STAR format. This round also assesses your understanding of Amazon's security culture, attitude toward automation and data-driven decisions, and perspective on managing security at scale.
Tips & Advice
Research Amazon's Leadership Principles in detail and prepare specific examples for each. Practice articulating how you embody 'Deliver Results': setting metrics, achieving ambitious goals, shipping on schedule. 'Bias for Action': making decisions with incomplete information, experimenting, failing fast and learning. 'Earn Trust': being honest about mistakes, taking accountability, building credibility through integrity. 'Think Big': long-term thinking, innovation, not just firefighting. 'Customer Obsession': translating to 'customer' meaning both Amazon's services and internal security customers (developers, infrastructure teams). Prepare stories around: (1) Delivering results against ambitious security goals; (2) Making a decision without perfect information and the outcome; (3) Failing, admitting it, and learning; (4) Long-term security improvement or vision you've driven; (5) Automation and process improvement you've led; (6) How you measure security effectiveness with data/metrics; (7) Operating with multiple competing priorities and how you prioritize. For Staff level, tell stories showing strategic impact and influence. Discuss how you approach security operations as a scalable system, not just incident response. Mention automation, efficiency improvements, data-driven decision-making, and long-term security posture improvements.
Focus Topics
Long-Term Strategic Thinking & Security Vision
Stories of proposing and implementing long-term security improvements, staying ahead of emerging threats, contributing to security culture evolution in your organization, thinking in terms of years not just incidents
Practice Interview
Study Questions
Data-Driven Decision Making & Metrics
Examples of using data and metrics to make security decisions, prioritize threats, measure program effectiveness, communicate impact to leadership using business language
Practice Interview
Study Questions
Scaling Security Operations & Automation
Examples of automating manual security processes, scaling security operations to larger organizations or more complex environments, increasing team efficiency and sustainability
Practice Interview
Study Questions
Amazon Leadership Principles Alignment (Deliver Results, Bias for Action, Earn Trust, Think Big)
Demonstrate deep alignment with Amazon's core values through specific examples: delivering results with metrics, making decisions despite uncertainty, admitting mistakes, thinking strategically about long-term security posture
Practice Interview
Study Questions
Hiring Manager / Bar Raiser Round
What to Expect
Final onsite round with hiring manager or senior security leader serving as 'bar raiser.' This round serves dual purposes: final assessment of your fit for Staff-level role and opportunity for you to assess cultural fit. Expect 3-4 in-depth questions diving deeper into your security expertise and strategic thinking. Typical questions: 'Describe how you'd set up Security Operations for a large organization,' 'Walk me through how you'd approach a critical security incident,' 'What's your vision for the future of security in organizations like Amazon?' 'How would you measure success in a security operations program?' 'Tell me about your philosophy on security culture and team development.' This round evaluates: readiness for Staff-level impact, ability to influence security strategy, perspective on balancing security with operational needs, and whether you'll raise the bar for team quality.
Tips & Advice
This is your final chance to demonstrate Staff-level readiness. Prepare 2-3 well-developed examples of your proudest security accomplishments where you drove significant impact. Be conversational and authentic; this round assesses whether you'll be a great team member and raise team standards. Show you've thought deeply about the role and what success looks like. Discuss how you'd approach Amazon's specific security challenges: operating at massive scale, managing security across hundreds of services, automation and efficiency, compliance across multiple jurisdictions, detecting sophisticated threats, building a high-performing security team. Prepare thoughtful questions about the team, recent security priorities, how security influences product decisions, and your potential impact. Demonstrate that you're ready to mentor and elevate others, not just execute tasks yourself. For Staff-level, emphasize: setting vision for security program, mentoring team members, driving strategy, measuring effectiveness, building security culture. Show that you understand the difference between Staff-level impact (influencing direction, multiplying through others) and individual contributor impact.
Focus Topics
Technical Leadership & Mentorship Philosophy
Your approach to developing team members, sharing knowledge, raising security capabilities across organization, building high-performing teams, and developing future leaders
Practice Interview
Study Questions
Influencing Without Authority & Stakeholder Management
Examples of driving security improvements or policy changes by influencing engineers, product teams, and leadership without direct authority; building consensus and gaining buy-in
Practice Interview
Study Questions
Emerging Threats & Future Security Challenges
Discussion of current and emerging threats relevant to Amazon's business; how you stay current with threat intelligence and industry trends; how you'd prepare organization for future challenges
Practice Interview
Study Questions
Security Program Design & Strategic Vision
Your vision for a mature security operations program at organizational scale: how you'd establish priorities, build team capabilities, measure success, evolve program over time based on emerging threats and business needs
Practice Interview
Study Questions
Major Incident Response & Crisis Leadership
Deep discussion of approach to large-scale security incident: how you prioritize, communicate across stakeholders, manage uncertainty, make tough calls under pressure, lead team to resolution
Practice Interview
Study Questions
Frequently Asked Information Security Analyst Interview Questions
Sample Answer
from dateutil import parser as dparser
from dateutil.tz import tzutc
import csv, io, re
SYSLOG_RE = re.compile(r'^(?P<ts>\w{3}\s+\d{1,2}\s+\d{2}:\d{2}:\d{2})\s+(?P<host>\S+)\s+(?P<rest>.+)$')
def _to_utc_iso(ts_str):
# Try dateutil first (handles many formats and timezones)
try:
dt = dparser.parse(ts_str, fuzzy=True)
dt_utc = dt.astimezone(tzutc())
return dt_utc.isoformat()
except Exception:
return None
def parse_log_line(line: str) -> dict:
line = line.strip()
if not line:
return None
# Try CSV (Windows Event Log export)
try:
reader = csv.reader(io.StringIO(line))
row = next(reader)
# common exported CSVs: Timestamp, Computer, EventID, TaskCategory, Level, User, Source, Message, ...
# we'll map best-effort
candidates = {i: v for i, v in enumerate(row)}
ts = candidates.get(0) or candidates.get(1)
hostname = candidates.get(1) or candidates.get(0)
username = None
source_ip = None
raw_message = candidates.get(7) if len(row) > 7 else " | ".join(row[2:])
# try to extract username/ip from other columns or message
for v in row:
if '@' in v or v.lower().startswith('domain\\') or v.lower().startswith('nt authority'):
username = username or v
m = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', v)
if m:
source_ip = source_ip or m.group(0)
ts_iso = _to_utc_iso(ts) if ts else None
if ts_iso or raw_message:
return {
"timestamp": ts_iso,
"hostname": hostname or None,
"event_type": candidates.get(2) or None,
"username": username,
"source_ip": source_ip,
"raw_message": raw_message or None
}
except Exception:
pass # CSV parse failed; try syslog
# Try syslog
m = SYSLOG_RE.match(line)
if m:
ts_raw = m.group('ts')
host = m.group('host')
rest = m.group('rest')
ts_iso = _to_utc_iso(ts_raw)
# attempt to extract username and IP from message
user = None
ip = None
um = re.search(r'user[=\s:"\']?([\w\\@.\-]+)', rest, re.I)
if um: user = um.group(1)
im = re.search(r'\b(?:\d{1,3}\.){3}\d{1,3}\b', rest)
if im: ip = im.group(0)
return {
"timestamp": ts_iso,
"hostname": host,
"event_type": None,
"username": user,
"source_ip": ip,
"raw_message": rest
}
# completely unparsable
return NoneSample Answer
Sample Answer
Sample Answer
Sample Answer
title: Detect PowerShell Invocations with Base64 Encoded Commands
id: d1a4f2a2-9b6e-4c3b-8f4e-1234567890ab
description: Detects PowerShell processes launched with base64-encoded commands (flags -EncodedCommand or -enc), commonly used to obfuscate and execute malicious payloads.
status: experimental
author: InfoSec Analyst
date: 2026-03-02
logsource:
product: windows
service: security
category: process_creation
detection:
selection_process:
Image|endswith:
- '\powershell.exe'
- '\pwsh.exe'
selection_cmd:
CommandLine|re: '(\-encodedcommand|\-enc)\s+[A-Za-z0-9\+/=]{20,}'
detection_condition: selection_process and selection_cmd
falsepositives:
- Legitimate automation or management tooling that uses encoded commands (scripts, config management, scheduled tasks).
- Inline base64 used by admins for short encoded data (rare).
level: high
tags:
- attack.execution
- attack.t1059.001
- attack.t1059
- attack.persistence
fields:
- CommandLine
- ParentImage
- Image
- UserSample Answer
Sample Answer
Sample Answer
Sample Answer
ETCDCTL_API=3 etcdctl snapshot save /forensics/etcd-snap.db \
--endpoints=<etcd-endpoint> --cacert=/etc/etcd/ca.crt ...crictl inspect --output go-template --template '{{.status.imageRef}}' <containerid>
ctr --namespace k8s.io snapshot save /forensics/container-<id>.tar <containerd-io-ref>Sample Answer
from scapy.all import PcapReader, TCP
import csv, math, multiprocessing, gzip
def session_key(pkt):
a,b = pkt[IP].src, pkt[IP].dst
s,d = pkt[TCP].sport, pkt[TCP].dport
return tuple(sorted([(a,s),(b,d)])) # canonical 4-tuple
def shannon_entropy(data_bytes):
if not data_bytes: return 0.0
counts = {}
for b in data_bytes: counts[b] = counts.get(b,0)+1
import math
L = len(data_bytes)
return -sum((c/L)*math.log2(c/L) for c in counts.values())
def process_pcap(path, out_csv):
sessions = {} # key -> {packets: [(ts,seq,payload)], start, end}
with PcapReader(path) as pcap:
for pkt in pcap:
if TCP not in pkt: continue
k = session_key(pkt)
ts = float(pkt.time)
seq = int(pkt[TCP].seq)
payload = bytes(pkt[TCP].payload)
meta = sessions.setdefault(k, {"pkts":[],"start":ts,"end":ts})
meta["pkts"].append((ts, seq, payload))
meta["start"] = min(meta["start"], ts)
meta["end"] = max(meta["end"], ts)
# reassemble per-session and compute metrics
with open(out_csv, 'w', newline='') as f:
w = csv.writer(f)
w.writerow(["session","start","end","duration","num_pkts","bytes","entropy","avg_iat"])
for k, m in sessions.items():
pkts = sorted(m["pkts"], key=lambda x: x[1]) # sort by seq for reassembly
data = b"".join(p for _,__,p in pkts)
entropy = shannon_entropy(data)
times = [t for t,_,_ in sorted(m["pkts"], key=lambda x: x[0])]
iats = [(times[i+1]-times[i]) for i in range(len(times)-1)] if len(times)>1 else [0]
avg_iat = sum(iats)/len(iats) if iats else 0
w.writerow([str(k), m["start"], m["end"], m["end"]-m["start"],
len(pkts), len(data), round(entropy,4), round(avg_iat,6)])Want to create your own tailored preparation guide using our deep research?
Get Started for FreeInterview-Ready Courses
Visual-first, interactive, structured learning paths
Browse Information Security Analyst jobs
AI-enriched listings across hundreds of company career pages
Explore Jobs