This skill provides read-only analysis of Huawei Cloud WAF (Web Application Firewall) security event logs. It queries attack event data through hcloud CLI, performs multi-dimensional aggregation and analysis, and generates actionable protection rule recommendations based on observed attack patterns.
Key Capabilities:
Query and filter security events by attack type, source IP, target domain/URL, time range, and geography
Aggregate statistics by attack category, source IP frequency, geographic distribution, and time trends
Recommend specific WAF protection rules (precise access control, CC protection, IP blacklist/whitelist, geo-blocking) based on analyzed attack characteristics
These modify production resources; the user decides when and whether to run them
Auto-execute any write operation based on analysis findings
❌ NEVER
Even if the recommendation seems obvious, do NOT run it
What the agent MUST do:
Perform read-only queries and analysis
Generate a structured report with prioritized recommendations
For each recommendation, output the exact, copy-paste ready hcloud command that the user can execute themselves
Clearly label each command with its purpose and expected effect
What the agent MUST NOT do:
Execute any command that creates, modifies, or deletes WAF resources
Ask the user "should I execute this for you?" — just present the command and let the user decide
Proceed to execute recommendations after presenting them — stop after the report is delivered
Prerequisites
Requirement
Description
hcloud CLI
v7.2+ installed and configured with AK/SK, region, and project ID
Project ID
Valid project ID (configured via hcloud configure set --cli-project-id=<id>)
IAM Permissions
See references/iam-policies.md for least-privilege policy
Network
Accessible network path to Huawei Cloud API endpoints
⚠️ Windows PowerShell Compatibility — STRICTLY ENFORCED
This skill runs on Windows PowerShell. The agent MUST NOT use Linux/Unix shell commands. Use PowerShell-native equivalents at all times.
❌ Linux command (NEVER use)
✅ PowerShell equivalent
Example
head -N
Select-Object -First N
... | Select-Object -First 30
tail -N
Select-Object -Last N
... | Select-Object -Last 30
grep "pattern"
Select-String "pattern"
... | Select-String "error"
wc -l
(... ).Count or (Measure-Object -Line).Lines
$items.Count
sort
Sort-Object
... | Sort-Object Count -Descending
uniq
Get-Unique or Group-Object
... | Group-Object
awk '{print $1}'
ForEach-Object { $_.field }
$items | ForEach-Object { $_.sip }
cut -d: -f1
Split-Path, -split, or Substring
($_ -split ':')[0]
sed 's/a/b/'
-replace operator
'text' -replace 'a','b'
cat file
Get-Content file
Get-Content "$env:TEMP\data.json" -Raw
echo "text"
Write-Host "text"
Write-Host "Processing..."
export VAR=value
$env:VAR="value"
$env:HTTP_PROXY="http://127.0.0.1:3128"
sleep N
Start-Sleep -Seconds N
Start-Sleep -Seconds 2
Additional rules:
Always use Out-File -Encoding utf8 instead of > file for redirecting output (avoids encoding issues)
Use double quotes " around variable expansions inside strings: "Total: $($items.Count)"
Pipe hcloud JSON output to ConvertFrom-Json for structured analysis: hcloud WAF ListEvent ... \| ConvertFrom-Json
Workflow
Step 1: Clarify Analysis Scope
Ask the user for the following parameters (defaults provided):
Parameter
Default
Options
Time range
today
today, yesterday, 3days, 1week, 1month
Domain filter
All domains
Specific domain name or leave empty
Attack type filter
All types
sqli, xss, cc, botm, cmdi, robot, etc.
Analysis focus
General overview
Attack type stats, IP analysis, target analysis, time trends, rule recommendation
Data volume
First page (100)
See options below
Data Volume Options:
Option
Description
When to use
first_page (default)
Query first 100 events only, fastest
Quick glance at recent activity
sample_pages
Query N pages of events; N must be explicitly specified by the user — agent has NO default
Balanced speed vs coverage
all_pages
Paginate through ALL results up to 10,000
Comprehensive analysis, may take several minutes
by_attack_type
First query to discover attack types, then query top N types separately (each gets its own first page)
Best attack-type diversity, avoids single-type bias
⚠️ IMPORTANT — Data Volume Selection (STRICTLY ENFORCED):
The agent MUST ask the user which data volume option to use. Do NOT silently default to any option.
If user chooses sample_pages, the agent MUST ask the user how many pages (N) to fetch. There is NO default value for N. The agent must NOT assume or default to any number (e.g., 5). Ask explicitly: "你想采样多少页?(每页100条事件)"
If total events > 100 and user chose first_page, warn them that the sample may not represent the full picture.
Step 2: Query Security Events
Step 2a: Get Total Count First
Always start with a single lightweight query to determine total event count:
Step 3 — Merge all per-type files into one combined dataset:
powershell
# Clean up old attack type files to avoid mixing with previous runs
Remove-Item "$env:TEMP\waf_events_attack_*.json" -ErrorAction SilentlyContinue
$allItems = @()
foreach ($file in Get-ChildItem "$env:TEMP\waf_events_attack_*.json") {
$raw = Get-Content $file.FullName -Raw
$data = $raw | ConvertFrom-Json
if ($data.items) { $allItems += $data.items }
}
$merged = @{ total = "multi-type-sample"; items = $allItems } | ConvertTo-Json -Depth 10
$merged | Out-File -Encoding utf8 "$env:TEMP\waf_events_all.json"
Write-Host "Combined dataset: $($allItems.Count) events across multiple attack types"
Common Query Examples
bash
# Filter by source IP
hcloud WAF ListEvent --recent={time_range} --sip={source_ip} --pagesize=100
# ⚠️ WARNING: --domain conflicts with KooCLI system parameter and will prompt interactively
# DO NOT use --domain in automated scripts; see workaround below
# hcloud WAF ListEvent --recent={time_range} --domain={domain} --pagesize=100
# Sort by different dimensions
hcloud WAF ListEvent --recent={time_range} --sort_key=sort_ip --pagesize=100
hcloud WAF ListEvent --recent={time_range} --sort_key=attack --pagesize=100
⚠️ --domain Parameter Conflict: The --domain parameter name conflicts with KooCLI's system parameter. Using it directly triggers an interactive prompt asking to choose between system/API parameter, which hangs non-interactive environments (e.g., Bash tool, automation scripts).
Solution — Use --cli-jsonInput to bypass the conflict:
Note:project_id can be obtained from hcloud configure list or from previous API responses. hcloud outputs a warning message before JSON when using --cli-jsonInput, so use file redirect and skip to the first { character when parsing.
Important:
Maximum 10,000 records per query; narrow time range if exceeded
--pagesize parameter: Valid range is [0, total_data]. Default to 100 if user doesn't specify. Use user's value when provided. If API returns error WAF.00011011: pageOrPageSize.illegal, inform the user that their pagesize value is too large and ask them to enter a smaller value within the valid range
Paginate through results if total count > pagesize (use multiple queries with --page=1, --page=2, etc.)
Use --from and --to (millisecond timestamps) for custom time ranges (max 30 days)
Always save multi-page results to a merged file before analysis to avoid PowerShell variable scope issues
Step 3: Multi-Dimensional Analysis
⚠️ PowerShell Variable Scope Warning: Each Bash tool invocation runs in an isolated session — variables do NOT persist across calls. You MUST either:
Load and analyze data in the same command block, OR
Save query results to a file first, then reload from file in subsequent analysis commands
Group by sip (source IP) field, sorted by frequency:
Identify top attacking IPs (>5 hits in analysis period)
Cross-reference with ip_countries and ip_regions for geographic distribution
Flag IPs from unexpected countries
3c. Target Asset Analysis
Group by host (domain) and url fields:
Identify most-targeted domains
Identify most-targeted URL paths
Correlate attack types with specific URLs
3d. Time Trend Analysis
The time field in API responses is a Unix millisecond timestamp (e.g., 1789696805000). It MUST be converted using [DateTimeOffset]::FromUnixTimeMilliseconds():
powershell
# CORRECT - Convert Unix millisecond timestamp to local time
$items | ForEach-Object {
[DateTimeOffset]::FromUnixTimeMilliseconds([long]$_.time).LocalDateTime.ToString("yyyy-MM-dd HH")
} | Group-Object | Sort-Object Name | Select-Object Count, Name
# WRONG - FromFileTimeUtc expects Windows FILETIME (epoch 1601-01-01),
# passing a Unix timestamp will produce dates around year 1601
[DateTime]::FromFileTimeUtc($_.time)
Calculate block rate vs pass rate to assess protection effectiveness
Identify rules that are in "log only" mode and should be escalated to "block"
Step 4: View Detailed Events (if needed)
For deeper investigation of specific events:
bash
hcloud WAF ShowEvent --eventid={event_id}
The detail view includes: full request headers, payload content, matched rule ID, and action taken.
⚠️ Timeout Warning:ShowEvent may fail with [USE_ERROR]调用API超时 if:
The event is old and data retrieval is slow
The API endpoint is under heavy load
Troubleshooting steps:
Increase read timeout: hcloud configure set --cli-read-timeout=60
Try a more recent event ID (older events may have been archived)
If timeout persists, the detailed event data can often be found in the original ListEvent response's response_body, headers, and other fields — use that as a fallback
Step 5: Generate Protection Rule Recommendations
Based on the analysis results, recommend specific WAF protection rules with executable hcloud commands. See references/rule-recommendation-guide.md for detailed mapping logic and full command reference.
Geo access control rule (block specific countries)
CreateGeoipRule
Repeated attacks from known malicious IPs
IP blacklist rule
CreateWhiteblackipRule
BOT/scanner user-agent patterns
Precise access control rule (User-Agent matching)
CreateCustomRule
Attacks on admin/api paths
Precise access control rule (URL path restriction)
CreateCustomRule
Multiple attack types from same IP subnet
IP group blacklist rule
CreateWhiteblackipRule
Malicious crawler/scanner traffic (robot)
JS anti-crawler rule (User-Agent matching)
CreateAnticrawlerRule
IDC datacenter malicious IP (iprank)
IP reputation rule (threat intelligence)
CreateIpReputationRule
Web content tampering (antitamper)
Anti-tamper rule (URL protection)
CreateAntiTamperRule
Persistent attacker blocking (followed_action)
Punishment rule (auto-block after threshold)
CreatePunishmentRule
Sensitive data in responses
Anti-leakage rule (filter phone/id_card/email)
CreateAntileakageRule
Webshell upload/access (webshell)
Enable webshell detection module
UpdatePolicy --options.webshell=true
Directory traversal (ptr) / Other vuln (vuln)
Enable basic protection + custom rule for payload
UpdatePolicy --options.webattack=true
High-frequency scan (antiscan_high_freq_scan)
CC protection or modulex scan protection
CreateCcRule / UpdatePolicy
After determining the recommendation, output the corresponding hcloud command as a code block for the user to copy and execute themselves. Do NOT execute the command. Use the policy_id extracted from the event data (the policyid field). See below for command templates per pattern:
Note:{project_id} is the same one configured in hcloud CLI (via hcloud configure set --cli-project-id=<id>). Check current value with hcloud configure list.
Note: Useful for temporary rule disabling during troubleshooting
KooCLI Parameter Pitfalls
Pitfall
❌ Wrong
✅ Correct
Nested params
--action=block
--action.category=block
Header field name
--conditions.1.field=UA
--conditions.1.index=User-Agent
Immediate effect
--status=1
--time=false
mode conflict
--mode=1 (direct)
--cli-jsonInput=file.json
Array index
--conditions.0.xxx
--conditions.1.xxx (starts from 1)
Singular/plural
ListWhiteblackipRules
ListWhiteblackipRule
Case sensitivity
ShowWhiteblackipRule
ShowWhiteBlackIpRule (capital B)
Step 6: Present Analysis Report
Output a structured report containing:
Summary — Total events, time range, top findings
Attack Type Breakdown — Counts and percentages
Top Attacking IPs — With geographic info
Most Targeted Assets — Domains and URLs
Time Distribution — Peak periods
Recommended Rules — Prioritized list with copy-paste ready hcloud commands (DO NOT execute them)
Report Delivery Format:
markdown
## 🛡️ Protection Recommendations
### Priority 1: [Rule Name]
**Purpose**: [What this rule does]
**Expected Effect**: [Impact on security posture]
**Command to execute** (copy and run in your terminal):
```bash
hcloud WAF CreateXxxRule --policy_id={policy_id} ...
Verification command (after you execute the above):
bash
hcloud WAF ListXxxRule --policy_id={policy_id}
text
**Important**: After presenting the report with all recommended commands, **STOP**. Do not ask "should I execute these?" or attempt to run them. The user will decide when and whether to execute the commands.
## Core Commands
| Command | Purpose |
|---------|---------|
| `hcloud WAF ListEvent` | Query attack event list with multi-dimensional filtering, sorting, and pagination |
| `hcloud WAF ShowEvent` | View detailed information of a single attack event |
| `hcloud WAF ListAttackActionTypes --from=<ms_timestamp> --to=<ms_timestamp>` | Aggregate event counts by protection action type (block/log/pass/etc.) within the specified time range |
### ListEvent Key Parameters
| Parameter | Type | Description |
|-----------|------|-------------|
| `--recent` | string | Quick time range: `today`, `yesterday`, `3days`, `1week`, `1month` |
| `--from` / `--to` | integer | Custom time range (millisecond timestamps), max 30 days |
| `--attacks.N` | array | Filter by attack type: `sqli`, `xss`, `cc`, `botm`, `cmdi`, `rfi`, `rce`, `lfi`, `ptr`, `webshell`, `vuln`, `robot`, `iprank`, `antitamper`, `anticrawler`, `followed_action`, `antileakage`, `antiscan_high_freq_scan`, `custom_whiteblackip`, `custom_geoip`, `custom_custom`, `advanced_bot`, etc. Run `ListAttackActionTypes` for full list |
| `--actions.N` | array | Filter by action: `block`, `pass`, `log`, `captcha`, `cache`, `mask`, `js_challenge`, `advanced_captcha`, `abort_response`, `desensitize` |
| `--sip` | string | Filter by source IP (supports fuzzy match with `--query_mode=include`) |
| `--sips.N` | array | Filter by multiple source IPs |
| `--domain` | string | Filter by domain (fuzzy match) |
| `--url` | string | Filter by URL (supports fuzzy match with `--query_mode=include`) |
| `--urls.N` | array | Filter by URL list |
| `--query_mode` | string | Query mode: `equal` (exact match) or `include` (fuzzy match, default). Affects `--sip` and `--url` only |
| `--ip_countries.N` | array | Filter by client IP country |
| `--ip_regions.N` | array | Filter by client IP province (China only) |
| `--rules.N` | array | Filter by matched rule ID |
| `--sort_key` | string | Sort field: `attack_time`, `sort_ip`, `host`, `geo_str`, `component`, `rule`, `attack` |
| `--sort_direction` | string | `desc` (default) or `asc` |
| `--page` / `--pagesize` | integer | Pagination controls |
| `--payload` | string | Search by malicious payload content |
| `--nattacks.N` | array | Exclude attack type (opposite of `--attacks.N`) |
| `--enterprise_project_id` | string | Enterprise project filter |
## Parameter Confirmation
| Parameter | Required | Description | Example |
|-----------|----------|-------------|---------|
| `{time_range}` | No | Analysis time window (default: `today`) | `1week` |
| `{domain}` | No | Target domain filter | `example.com` |
| `{attack_type}` | No | Attack type filter | `sqli` |
| `{source_ip}` | No | Source IP filter | `203.0.113.1` |
## Reference Documents
- `references/iam-policies.md` — Least-privilege IAM policies for WAF log querying
- `references/cli-installation-guide.md` — hcloud CLI installation and configuration
- `references/verification-method.md` — How to verify the skill is working correctly
- `references/dataflow-diagram.md` — Mermaid data flow diagram
- `references/acceptance-criteria.md` — Acceptance criteria for analysis output quality
- `references/rule-recommendation-guide.md` — Detailed attack-to-rule mapping logic
## KooCLI Command Format Standard
```bash
hcloud <Service> <Operation> [--key=value ...]
Feature
Description
Example
Service name
Exact KooCLI service name, uppercase
WAF
Operation name
PascalCase
ListEvent, ShowEvent
Simple parameter
--key=value
--sip=203.0.113.1
Indexed parameter
--key.N=value
--attacks.1=sqli --attacks.2=xss
Region
Use default configured region; do NOT specify --cli-region