Security Monitoring, SIEM, and Detection Engineering Questions
Building and operating the detection stack: the SOC and detection-engineering practice that answers 'can we see an attack happening.' Covers SIEM platform selection and architecture, use-case and detection-rule query development (for example Splunk SPL, KQL, or Sigma), alert triage and tuning to reduce false positives, detection engineering and closing coverage gaps, mapping detections to the MITRE ATT&CK framework and scoring detection coverage, log analysis and anomaly and baseline development, network and endpoint telemetry sourcing, malware and compromise-indicator recognition, and security operations center (SOC) alert escalation workflows. Distinct from the reactive work of containing, remediating, and communicating during a confirmed incident (incident response and postmortem topics own that ground; this topic stops at 'the alert fired and here is the detection logic', not 'here is how we contained and recovered from it'). Distinct from generic system-reliability monitoring and observability (SLOs, error budgets, uptime dashboards), a separate discipline even when the underlying ingestion mechanics look similar; the anomaly or signal here must be framed as adversarial or security-relevant. Distinct from hardening a software delivery pipeline against supply-chain compromise (SBOM generation, artifact signing, dependency and build-permission controls); this topic only touches the delivery pipeline from the detection side, spotting a compromised build or tainted artifact via telemetry, not the preventive-controls side. Distinct from designing security control architecture and governance (security architecture and cloud security architecture topics own the design-time question of what controls should exist); this topic is the run-time operation of the detection stack once those controls are in place.
Write a Sigma rule (YAML-style) that detects suspicious usage of certutil or powershell when invoked with command-line patterns indicating encoding or decoding of content (for example '-EncodedCommand' or 'certutil -decode'). Target Windows ProcessCreate events and include reasonable fields (process_name, command_line, parent_process). Keep the rule generic and explain rationale for key fields.
Sample Answer
Direct answer
Certutil and PowerShell both ship as trusted, signed native Windows binaries, which is exactly why attackers abuse them for encoding/decoding staged payloads (a living-off-the-land technique, MITRE ATT&CK T1027 Obfuscated Files or Information, and T1140 Deobfuscate/Decode Files or Information): the activity blends in with legitimate administrative tool usage rather than requiring the attacker to bring in a separate, more easily-flagged decoder utility.
Structured elaboration
title: Suspicious Certutil or PowerShell Encode/Decode Usage
id: 9e1f2a3b-4c5d-4e6f-8a9b-0c1d2e3f4a5b
status: experimental
description: Detects certutil or PowerShell invoked with command-line patterns
indicating encoding or decoding of content, a common living-off-the-land
technique for staging or deobfuscating a payload without downloading a
separate decoder tool.
logsource:
category: process_creation
product: windows
detection:
selection_certutil:
Image|endswith: '\certutil.exe'
CommandLine|contains:
- '-decode'
- '-encode'
- '/decode'
- '/encode'
selection_powershell:
Image|endswith: '\powershell.exe'
CommandLine|contains:
- '-EncodedCommand'
- 'FromBase64String'
- 'ToBase64String'
filter_known_admin_tooling:
ParentImage|endswith: '\sccm_agent.exe'
condition: (selection_certutil or selection_powershell) and not filter_known_admin_tooling
level: medium
fields:
- Image
- CommandLine
- ParentImage
- User
tags:
- attack.defense_evasion
- attack.t1140
- attack.t1027
Rationale for key fields: Image narrows each selector to the exact binary (certutil.exe or powershell.exe) rather than matching on process NAME alone (which an attacker could rename a different binary to spoof, hence the more specific full-path/endswith match); CommandLine carries the actual evidence of encode/decode intent, since neither binary's mere presence is suspicious on its own, both are legitimate, common administrative tools; ParentImage supports both the false-positive filter and, more broadly, helps an analyst judge whether the invocation chain looks like normal tooling (a management agent) or something else (a document application spawning certutil.exe, for instance, which would be a much stronger standalone signal even without matching this specific rule).
Kept the rule GENERIC, per the question's own instruction, rather than narrowly targeting one specific known malicious command line: the two selectors cover the certutil and PowerShell encode/decode SURFACE broadly (multiple flag spellings, multiple relevant cmdlets/methods) rather than a single exact string, since a rule keyed to one specific observed command line is trivially evaded by the next minor variation an attacker tries.
Worked example
Parsed and converted to SPL using pySigma with the Splunk backend, executed locally:
Output (actual output):
(Image="*\\certutil.exe" CommandLine IN ("*-decode*", "*-encode*", "*/decode*", "*/encode*")) OR (Image="*\\powershell.exe" CommandLine IN ("*-EncodedCommand*", "*FromBase64String*", "*ToBase64String*")) NOT ParentImage="*\\sccm_agent.exe" | table Image,CommandLine,ParentImage,User
The backend doubles each backslash in the Image/ParentImage path literals because SPL treats a single backslash as a string-escape character inside quoted values, so this is correct SPL syntax, not a formatting artifact. This confirms the rule parses as valid Sigma and translates into a runnable SPL search combining both selectors with the false-positive filter applied to either branch, matching the intended (A or B) and not C logic.
Trade-offs and pitfalls
- Certutil's
-decode/-encodeis a genuinely dual-use capability: legitimate IT operations occasionally use certutil for exactly this purpose (base64-encoding/decoding a certificate or small file as part of a manual troubleshooting step), so this rule is deliberately shipped atlevel: mediumrather than high, reflecting a real, non-trivial false-positive rate that should be expected and tuned against actual fired-alert data, following the same evidence-driven approach used for any noisy rule. - Common mistake: matching only the flag spelling an analyst happened to observe in one incident (for example only
-decode) and missing the sibling spellings (/decode,-encode,/encode); Windows utilities frequently accept both dash- and slash-prefixed flags, and a rule that only covers one form is trivially evaded by an attacker (or, just as often, missed against entirely benign administrative usage that happens to use the other form). - This rule catches the INVOCATION pattern only: a fuller detection pipeline would pair this with a follow-up step that actually decodes and re-scans Base64 content flagged by this rule, since the encode/decode ACT is the signal here, not an assessment of what was encoded or decoded.
- MITRE mapping precision: T1140 (Deobfuscate/Decode Files or Information) is the more precise tag for the DECODE direction specifically; T1027 (Obfuscated Files or Information) is the broader parent concept covering obfuscation generally. Tagging both, as this rule does, is defensible since the rule covers both encode and decode invocations, but a rule scoped to decode-only activity specifically would be more precisely tagged with T1140 alone.
In Python 3.x write a defensive script that reads a CSV export of Windows Security events (columns: Timestamp, EventID, Account, SourceIP, LogonType). Implement logic to flag SourceIP addresses that have 5 or more failed logon attempts (EventID 4625) followed by a successful logon (EventID 4624) from the same IP within 10 minutes. Output flagged records as JSON.
Sample Answer
Direct answer
Flagging a source IP with 5+ failed logons followed by a success within 10 minutes, from a CSV export rather than a live stream, means sorting the rows by timestamp first (a CSV export offers no ordering guarantee), wrapped in defensive handling so one malformed row does not abort processing the rest of the file.
Structured elaboration
Defensive parsing: validate the CSV has the expected columns before processing any rows; parse each row's timestamp defensively, skipping (not crashing on) a row with an unparseable timestamp, since a real CSV export can contain corrupted or partial rows.
Windowed correlation, identical logic to the streaming case, applied to a bounded batch: sort all valid rows by timestamp, then walk them in order maintaining a per-source-IP deque of recent failures (Event ID 4625), evicting anything older than the 10-minute window, and checking the accumulated failure count against the threshold whenever a success (Event ID 4624) arrives for that same IP.
JSON output: each flagged record includes the source IP, the successful account and timestamp, the failure count, and the distinct accounts attempted, giving an analyst immediately actionable detail (not just a bare "flagged: true") without requiring a follow-up query.
Worked example
import csv, io, json
from collections import defaultdict, deque
from datetime import datetime, timedelta
WINDOW = timedelta(minutes=10)
THRESHOLD = 5
REQUIRED_COLUMNS = {"Timestamp", "EventID", "Account", "SourceIP", "LogonType"}
def flag_from_csv(csv_text: str) -> list:
reader = csv.DictReader(io.StringIO(csv_text))
if not REQUIRED_COLUMNS.issubset(set(reader.fieldnames or [])):
raise ValueError(f"CSV missing required columns: {REQUIRED_COLUMNS - set(reader.fieldnames or [])}")
fails_by_ip = defaultdict(deque)
flagged = []
rows = []
for row in reader:
try:
ts = datetime.strptime(row["Timestamp"], "%Y-%m-%d %H:%M:%S")
except (ValueError, KeyError):
continue # skip malformed rows rather than crashing the whole run
rows.append((ts, row))
rows.sort(key=lambda r: r[0])
for ts, row in rows:
ip = row.get("SourceIP", "").strip()
event_id = row.get("EventID", "").strip()
account = row.get("Account", "").strip()
if not ip or not event_id:
continue
dq = fails_by_ip[ip]
if event_id == "4625":
dq.append((ts, account))
while dq and ts - dq[0][0] > WINDOW:
dq.popleft()
elif event_id == "4624":
while dq and ts - dq[0][0] > WINDOW:
dq.popleft()
if len(dq) >= THRESHOLD:
flagged.append({
"source_ip": ip, "success_account": account,
"success_time": ts.strftime("%Y-%m-%d %H:%M:%S"),
"failed_attempt_count": len(dq),
"failed_accounts_tried": sorted({a for _, a in dq}),
})
dq.clear()
return flagged
sample_csv = '''Timestamp,EventID,Account,SourceIP,LogonType
2026-07-30 09:00:00,4625,admin,203.0.113.9,3
2026-07-30 09:01:00,4625,administrator,203.0.113.9,3
2026-07-30 09:02:00,4625,root,203.0.113.9,3
2026-07-30 09:03:00,4625,svc-app,203.0.113.9,3
2026-07-30 09:04:00,4625,test,203.0.113.9,3
2026-07-30 09:05:00,4624,svc-app,203.0.113.9,3
2026-07-30 09:10:00,4625,alice,192.168.1.5,2
2026-07-30 09:11:00,4625,alice,192.168.1.5,2
2026-07-30 09:12:00,4624,alice,192.168.1.5,2
2026-07-30 09:20:00,4625,bob,198.51.100.4,3
2026-07-30 09:35:00,4624,bob,198.51.100.4,3
BAD-ROW-MALFORMED,4624,x,1.2.3.4,3
'''
print(json.dumps(flag_from_csv(sample_csv), indent=2))
Output (actually executed with python3):
[
{
"source_ip": "203.0.113.9",
"success_account": "svc-app",
"success_time": "2026-07-30 09:05:00",
"failed_attempt_count": 5,
"failed_accounts_tried": [
"admin", "administrator", "root", "svc-app", "test"
]
}
]
Only the genuine 5-failures-then-success pattern for 203.0.113.9 was flagged. The malformed row (BAD-ROW-MALFORMED,...) did not crash the run, it was silently skipped by the timestamp-parsing guard. 192.168.1.5's 2-failure pattern stayed below the threshold and was correctly excluded. 198.51.100.4's failure-then-success pair, real events 15 minutes apart, fell OUTSIDE the 10-minute window and was correctly excluded as well.
Complexity
- Time: O(nlogn) dominated by the sort step (CSV rows have no ordering guarantee), followed by an O(n) amortized pass with bounded per-IP eviction.
- Space: O(k×w), proportional to the number of distinct source IPs and their recent-failure count within the window, plus O(n) to hold the full parsed row list before sorting, an acceptable trade-off for a bounded, batch-oriented CSV export rather than an unbounded live stream.
Edge cases
- Malformed timestamp row: silently skipped, confirmed directly in the executed output (the run completed and produced correct results despite the bad row).
- Below-threshold failure count: correctly excluded, confirmed directly (
192.168.1.5). - Failure-then-success pair outside the time window: correctly excluded, confirmed directly (
198.51.100.4). - Missing
SourceIPorEventIDvalue on an otherwise well-formed row: skipped via the explicit empty-string guard, rather than silently mis-keying into a shared""bucket that could conflate unrelated events.
Trade-offs and pitfalls
- Common mistake: assuming a CSV export arrives in chronological order and skipping the sort step; unlike a live stream, a CSV export is a static file with no ordering guarantee, and processing it out of order would break the windowed-eviction logic's correctness entirely.
- Common mistake: raising an exception on the first malformed row and aborting the entire file; a defensive script explicitly means tolerating a genuinely malformed subset of rows (a truncated export, a corrupted field) while still processing everything that IS well-formed, which is exactly what this implementation's
try/except ... continuepattern achieves. - Column-presence validation up front is cheap insurance: checking
REQUIRED_COLUMNSbefore processing any rows fails fast with a clear error message if the CSV export's schema has changed (a column renamed or removed upstream), rather than silently producing an empty or wrong result that looks like "no findings" when the real problem is a broken input format.
Explain how encrypted network channels (TLS/HTTPS/SSH) impact detection of C2 and exfiltration. Describe three metadata-based signals (for example JA3/TLS fingerprinting, SNI anomalies, session timing and volume patterns) that can help detect encrypted malicious communication without decrypting payloads, and discuss limitations.
Sample Answer
Direct answer
Three metadata-based signals carry most of the practical value for spotting encrypted command-and-control (C2) or malicious communication without decrypting payload: TLS client/server fingerprinting (JA3/JA3S), Server Name Indication (SNI) anomalies, and session timing/volume patterns, each visible on the wire regardless of encryption, each individually limited, and materially stronger when combined.
Structured elaboration
1. JA3/TLS fingerprinting: fingerprints the specific, ordered combination of parameters a TLS client (JA3) or server (JA3S) offers during the handshake, producing a stable identifier for the CLIENT LIBRARY/CONFIGURATION in use, not the connection's content; malware families using distinctive or non-standard TLS libraries often produce a fingerprint different from common legitimate software, making this a useful, payload-free signal for flagging traffic consistent with known-malicious tooling.
2. SNI anomalies: the Server Name Indication field, sent unencrypted even within a TLS handshake, reveals the requested hostname; a domain-generation-algorithm-style high-entropy SNI value, an SNI that does not match the certificate presented, or an unexpectedly absent SNI are all payload-free signals worth investigating.
3. Session timing and volume patterns: regular, low-jitter connection timing and unusual data-volume patterns relative to a host's own baseline are both visible from connection metadata alone, without needing to see what was actually transmitted.
Worked example
The JA3 mechanism itself, concretely: a JA3 fingerprint is the MD5 hash of a comma-joined string built from five ClientHello fields (TLS version, cipher list, extension list, elliptic curves, EC point formats), each individually hyphen-joined in the order the client actually sent them.
import hashlib
def compute_ja3(version, ciphers, extensions, elliptic_curves, ec_point_formats):
# JA3 = md5(SSLVersion,Cipher,SSLExtension,EllipticCurve,EllipticCurvePointFormat)
ja3_string = ",".join([
str(version),
"-".join(str(c) for c in ciphers),
"-".join(str(e) for e in extensions),
"-".join(str(c) for c in elliptic_curves),
"-".join(str(p) for p in ec_point_formats),
])
digest = hashlib.md5(ja3_string.encode()).hexdigest()
return ja3_string, digest
# A ClientHello fingerprint typical of a common legitimate browser TLS stack
legit_string, legit_hash = compute_ja3(
version=771,
ciphers=[4865, 4866, 4867, 49195, 49199, 49196, 49200, 52393, 52392, 49171, 49172, 156, 157, 47, 53],
extensions=[0, 23, 65281, 10, 11, 35, 16, 5, 51, 43, 13, 45, 28, 21],
elliptic_curves=[29, 23, 24],
ec_point_formats=[0],
)
# A ClientHello fingerprint typical of a minimal/custom TLS client (e.g. some C2 frameworks
# use a small, non-standard cipher/extension list rather than a full browser stack)
malware_string, malware_hash = compute_ja3(
version=771,
ciphers=[4865, 4867, 49195, 156],
extensions=[0, 10, 11, 35],
elliptic_curves=[29, 23],
ec_point_formats=[0],
)
print("Legitimate-browser-style ClientHello:")
print(f" JA3 string: {legit_string}")
print(f" JA3 hash: {legit_hash}")
print()
print("Minimal/non-standard ClientHello (illustrative of a non-browser TLS stack):")
print(f" JA3 string: {malware_string}")
print(f" JA3 hash: {malware_hash}")
print()
print(f"Hashes differ: {legit_hash != malware_hash}")
Output (actually executed with python3):
Legitimate-browser-style ClientHello:
JA3 string: 771,4865-4866-4867-49195-49199-49196-49200-52393-52392-49171-49172-156-157-47-53,0-23-65281-10-11-35-16-5-51-43-13-45-28-21,29-23-24,0
JA3 hash: 0513b40cc2beae370c325436a478b15b
Minimal/non-standard ClientHello (illustrative of a non-browser TLS stack):
JA3 string: 771,4865-4867-49195-156,0-10-11-35,29-23,0
JA3 hash: ad08e700e230c3700d5736e59c77aada
Hashes differ: True
This demonstrates concretely why JA3 works as a signal at all: the hash is sensitive to the ORDER and SET of parameters offered, not the destination or content, so a client library that offers a smaller, non-standard set of ciphers/extensions (as some minimal or custom TLS implementations do, in contrast to a full browser stack's much longer, standardized list) produces a visibly different, stable hash. None of the three signals alone reliably distinguishes malicious from benign traffic on its own, though: a rare JA3 fingerprint could belong to a legitimate but uncommon piece of software; an unusual SNI could be a genuinely new but legitimate service; regular timing could be a legitimate health-check. A connection that combines all three, an uncommon JA3 fingerprint, an SNI resolving to a domain with no established reputation, AND a regular, low-jitter connection interval, produces a materially stronger combined signal than any one alone, applied here specifically to the encrypted-C2 problem.
Trade-offs and pitfalls
- Limitations, stated directly since the question asks for them: none of these three signals can see WHAT was actually communicated, only characteristics ABOUT how it was communicated; a sophisticated attacker aware of JA3-based detection can deliberately mimic a common legitimate client's fingerprint, and legitimate infrastructure can occasionally produce superficially similar patterns (a rare software configuration, a genuinely new but benign service, a legitimately periodic health-check), meaning all three signals function as probabilistic corroboration rather than proof.
- This is a deliberately concise, fast three-signal summary rather than the deepest possible treatment: the underlying JA3 computation mechanism, a fuller signal set including certificate metadata, and formal validation methodology would each need more depth for a rigorous detection-design conversation; the value here is speed, suited to a quick explanation or an initial framing of the problem.
- Common mistake: treating any single one of these three signals as sufficient grounds for an automated blocking action; given the limitations above, these signals are best used for enrichment and analyst-facing scoring rather than direct, automated response.
With very limited endpoint telemetry (process creation events and summarized netflow only), propose statistical heuristics and feature engineering to detect abuse of LOLBins. Suggest concrete features (for example: process-parent novelty score, command-line entropy proxy, atypical destination score, time-of-day deviation) and describe how you would combine them into a scoring model or anomaly detector.
Sample Answer
Direct answer
With only process-creation events and summarized (non-packet-level) netflow, LOLBin abuse detection has to lean entirely on BEHAVIORAL statistics computed from what little structure those two sources provide, rather than any content inspection, since there is no command-line-argument detail, file-content, or per-packet visibility available; the practical approach is a small set of cheaply-computed numeric features per process-creation event, combined into a single weighted or learned score rather than any one feature acting as a hard rule, since each individual feature alone is only weakly discriminating at this telemetry depth.
Structured elaboration
Process-parent novelty score: for each observed (parent process, child process) pair, maintain a per-host or per-fleet historical frequency count, and score a NEW event by how rarely (or never) that specific parent-child pairing has been observed before, for example score = -log(observed_frequency + epsilon), so a pairing seen thousands of times scores near zero and a never-before-seen pairing scores high; this directly targets the classic LOLBin abuse pattern of a legitimate binary (certutil.exe, mshta.exe, regsvr32.exe) being launched by an UNUSUAL parent (a browser, an Office application, a scripting host) rather than its normal parent (a shell or scheduled task).
Command-line entropy proxy: since full command-line content may not be captured at this telemetry depth, approximate obfuscation signal from whatever IS available, process name length and character-class mix (if partial command-line or image-path data exists), or, if command-line truly is unavailable, a proxy built from process-creation RATE and pattern instead (a burst of LOLBin-family process creations in a short window is itself an entropy-like signal of scripted/automated invocation rather than manual interactive use); where at least a truncated command-line is available, Shannon entropy over the character distribution is a cheap, standard obfuscation proxy (H = -sum(p_i * log2(p_i)) over character frequencies), with a high value pointing toward base64/hex-encoded payloads.
Atypical destination score: pair each process-creation event with the summarized netflow occurring in a short window AFTER it (the process launched, then made a connection), and score the destination by novelty against that HOST's own historical destination set (has this host ever connected to this destination/ASN before) rather than a global allowlist/denylist, since a global list misses host-specific abuse while a per-host novelty baseline catches "this LOLBin just talked to somewhere this host has never gone."
Time-of-day deviation: score each event's timestamp against the HOST's (or the responsible user account's) own historical activity-time distribution, not a fleet-wide baseline, since normal working hours vary by role and geography; a LOLBin invocation at 3am on a workstation with no history of any activity at that hour is a stronger signal than the same invocation timing on a server that runs scheduled maintenance nightly.
Combining into a scoring model: given how weak any single feature is at this telemetry depth, a WEIGHTED linear combination or a simple logistic-regression-style scoring function (score = w1*parent_novelty + w2*entropy_proxy + w3*destination_novelty + w4*time_deviation) calibrated against a labeled or semi-labeled sample of known-benign and known-suspicious LOLBin invocations is more robust than any single hard threshold on one feature; the weights themselves can start as analyst-assigned priors (parent novelty weighted highest, since it is the most directly diagnostic of the four at this telemetry depth) and be refined once enough labeled feedback accumulates to fit them properly.
Trade-offs and pitfalls
- Common mistake: treating any ONE of these four features as sufficient grounds for an alert; at this reduced telemetry depth, each feature individually has a meaningfully high false-positive rate (an unusual but entirely legitimate one-off administrative task can trigger parent novelty, time-of-day deviation, or both), and the combined score exists specifically to require CORROBORATION across independent signals before an alert fires.
- Common mistake: baselining destination or time-of-day novelty against a GLOBAL population instead of per-host or per-account history; this either misses attacks on unusually-active hosts or floods quiet hosts with false positives for entirely ordinary variation.
- Command-line entropy is the weakest of the four features WITHOUT full command-line capture: if only a truncated or partial command-line is available, the entropy proxy degrades significantly, and the design should be explicit that this feature's reliability depends directly on how much command-line detail the endpoint agent actually captures, not treated as equally strong to the other three regardless of capture depth.
- This entire approach is a deliberate telemetry-constrained fallback, not a substitute for richer visibility: if full command-line capture, DLL/module-load events, or packet-level netflow become available later, several of these proxy features (especially the entropy proxy) should be replaced with the direct signal rather than kept as permanent design choices; the scoring-model structure (weighted combination requiring corroboration) is the durable part, the specific proxy features are not.
Write a YARA rule suitable for scanning a webroot to detect simple PHP web shells that often include both the functions 'base64_decode' and 'eval', while minimizing false positives against legitimate code that uses one of those functions innocuously. Explain your rationale briefly in comments in the rule.
Sample Answer
Direct answer
A YARA rule requiring BOTH base64_decode and eval to appear together, plus a PHP open tag, catches the minimal webshell pattern the question names while avoiding the two most common false-positive sources, legitimate code using base64 decoding alone (for example, decoding an uploaded file) and legitimate code using eval alone; requiring all three conditions together is what keeps the rule precise rather than firing on either innocuous use in isolation.
Structured elaboration
rule Suspicious_PHP_Webshell_Base64_Eval
{
meta:
description = "Flags PHP files combining base64_decode and eval, a common minimal webshell pattern, while requiring BOTH functions together to reduce false positives against legitimate code using only one innocuously."
author = "security-monitoring-and-detection topic"
date = "2026-07-30"
strings:
$b64 = "base64_decode" ascii
$eval = "eval(" ascii
$php_open = "<?php" ascii
condition:
$php_open and $b64 and $eval
}
Rationale, in comments as the question requests: $php_open scopes the rule to files that are actually PHP (a <?php opening tag), preventing a match on non-PHP prose or documentation that happens to mention both function names without being executable code at all; $b64 and $eval are each simple, low-overhead string matches (deliberately not regex, since a bare substring check is faster to scan across a large webroot); the condition requires all three together with a plain and, the entire minimization strategy the question asks for, since dropping any one of the three conditions reopens exactly the false-positive path that condition exists to close.
Worked example
Compiled and matched with yara-python against four constructed samples, executed locally:
import yara
rule_source = r'''
rule Suspicious_PHP_Webshell_Base64_Eval
{
strings:
$b64 = "base64_decode" ascii
$eval = "eval(" ascii
$php_open = "<?php" ascii
condition:
$php_open and $b64 and $eval
}
'''
rules = yara.compile(source=rule_source)
webshell_sample = b'<?php eval(base64_decode($_POST["cmd"])); ?>'
print("Webshell sample:", [m.rule for m in rules.match(data=webshell_sample)])
benign_b64_only = b'<?php $data = base64_decode($_POST["image_data"]); file_put_contents("upload.png", $data); ?>'
print("Benign base64-only sample:", [m.rule for m in rules.match(data=benign_b64_only)])
benign_eval_only = b'<?php eval("echo " . $safe_expression . ";"); ?>'
print("Benign eval-only sample:", [m.rule for m in rules.match(data=benign_eval_only)])
doc_text = b'This article discusses base64_decode and eval() as a common webshell pattern, but is not itself PHP.'
print("Documentation-text sample:", [m.rule for m in rules.match(data=doc_text)])
Output (actually executed with yara-python 4.5.4):
Webshell sample: ['Suspicious_PHP_Webshell_Base64_Eval']
Benign base64-only sample: []
Benign eval-only sample: []
Documentation-text sample: []
All four results confirm the rule's own design goal precisely: it fires ONLY on the genuine webshell pattern, and correctly stays silent on both single-function benign uses AND on prose that merely mentions both function names as text without being executable PHP at all, the last case specifically demonstrating why the $php_open condition matters beyond just the two function-name checks.
Trade-offs and pitfalls
- Common mistake: matching on
base64_decodeOReval(rather than AND) under the assumption that either alone is suspicious enough; the executed benign-sample results above show directly why this would be far too noisy against real, legitimate PHP code, both functions have entirely ordinary, non-malicious uses in isolation. - This rule is trivially evadable by a moderately sophisticated attacker, worth stating honestly rather than overselling the rule's coverage: string-splitting (
'base64'.'_decode'), using an alternate decoding function (str_rot13, a custom XOR routine), or invokingevalindirectly through a variable function call ($func = 'eval'; $func($x);, though technicallyevalis a language construct not a true callable in PHP, illustrating the kind of subtlety a real evasion attempt would need to work around) would all defeat this specific string-matching rule; it is a useful, cheap first layer against unsophisticated or commodity webshells, not a comprehensive webshell-detection solution on its own. - Common mistake: scanning without the
<?phprequirement under the theory that "more matches is safer"; the documentation-text negative control above demonstrates directly why this backfires, dropping the PHP-open-tag condition would make the rule fire on any text file merely discussing these functions, a real, avoidable source of noise in a webroot that might legitimately contain documentation or comments. - Broader IOC list, beyond this specific YARA rule: a fuller webshell-detection posture layers this rule alongside OTHER indicators (unusual file-modification timestamps in the webroot, files with executable extensions in upload-only directories, web-server access-log patterns consistent with webshell interaction), since no single YARA rule, however well-tuned, substitutes for a broader detection strategy against this technique family.
Unlock Full Question Bank
Get access to all 12 Security Monitoring, SIEM, and Detection Engineering interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.