
Alibabacloud Ddoscoo Intercept Query
- 97 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Queries Alibaba Cloud DDoS Pro (ddoscoo) block reasons via SLS full logs and the Aliyun CLI to explain why a request was intercepted.
About
Investigates DDoS Pro intercept events by discovering instances, querying SLS logs by Request ID, and analyzing CC, precise access control, region blocking, and IP blacklist rules. A developer uses it when users report being blocked by DDoS Pro and needs a structured analysis and remediation report.
- Traces a blocked Request ID through SLS full logs to the exact protection rule
- Requires Aliyun CLI >= 3.3.3 with AI-mode enabled around the workflow
Alibabacloud Ddoscoo Intercept Query by the numbers
- 97 all-time installs (skills.sh)
- Ranked #1,023 of 2,203 Security skills by installs in the Skillselion catalog
- Data as of Aug 5, 2026 (Skillselion catalog sync)
npx skills add https://github.com/aliyun/alibabacloud-aiops-skills --skill alibabacloud-ddoscoo-intercept-queryAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 97 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Queries Alibaba Cloud DDoS Pro (ddoscoo) block reasons via SLS full logs and the Aliyun CLI to explain why a request was intercepted.
Files
DDoS Pro (Anti-DDoS Pro) Intercept Query
Scenario Description
Query and analyze DDoS Pro (ddoscoo) block/intercept events using SLS full logs and ddoscoo CLI commands. When a user reports being blocked by DDoS Pro or encounters a block page, this skill discovers DDoS instances, checks full log configuration, queries SLS logs by Request ID, retrieves rule details, and outputs a structured analysis report with recommendations.
Architecture: DDoS Pro Instance → Full Log (SLS) → Log Query → Rule Analysis → Report
Installation
Pre-check: Aliyun CLI >= 3.3.3 required
Run aliyun version to verify >= 3.3.3. If not installed or version too low,see references/cli-installation-guide.md for installation instructions.
Pre-check: Aliyun CLI plugin update required
[MUST] run aliyun configure set --auto-plugin-install true to enable automatic plugin installation.[MUST] run aliyun plugin update to ensure that any existing plugins are always up-to-date.Pre-check: AI-Mode Lifecycle
At the start of the Core Workflow (before any CLI invocation):
[MUST] Enable AI-Mode — AI-mode is required for Agent Skill execution.
Run the following commands before any CLI invocation:
```bash
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query"
```
[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason (workflow success, failure, error, user cancellation, or session end), always disable AI-mode first. AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
```bash
aliyun configure ai-mode disable
```
Pre-check: SLS CLI plugin required
[MUST] Install the SLS CLI plugin before any log query operations:
```bash
aliyun component install sls
```
Verify the plugin is available:
```bash
aliyun sls --help
```
If aliyun component install is not available, use the legacy command:```bash
aliyun plugin install --names aliyun-cli-sls
```
Environment Variables
No additional environment variables required. Authentication is handled via the Aliyun CLI credential chain.
Authentication
Pre-check: Alibaba Cloud Credentials Required
>
Security Rules:
- NEVER read, echo, or print AK/SK values (e.g., echo $ALIBABA_CLOUD_ACCESS_KEY_ID is FORBIDDEN)- NEVER ask the user to input AK/SK directly in the conversation or command line
- NEVER use aliyun configure set with literal credential values- ONLY use aliyun configure list to check credential status>
```bash
aliyun configure list
```
Check the output for a valid profile (AK, STS, or OAuth identity).
>
If no valid profile exists, STOP here.
1. Obtain credentials from Alibaba Cloud Console
2. Configure credentials outside of this session (via aliyun configure in terminal or environment variables in shell profile)3. Return and re-run after aliyun configure list shows a valid profile>
Note on 401 Unauthorized errors: A401 The security token has expirederror means the STS temporary credential has expired — this is not a RAM permission issue. Ask the user to refresh credentials outside this session viaaliyun configure, then retry.
RAM Policy
See references/ram-policies.md for the full list of required permissions.
[MUST] Permission Failure Handling: When any command or API call fails due to permission errors at any point during execution, follow this process:
1. Read references/ram-policies.md to get the full list of permissions required by this SKILL2. Use ram-permission-diagnose skill to guide the user through requesting the necessary permissions3. Pause and wait until the user confirms that the required permissions have been granted
Parameter Confirmation
IMPORTANT: Parameter Confirmation — Before executing any command or API call,
ALL user-customizable parameters (e.g., RegionId, instance names, CIDR blocks,
passwords, domain names, resource specifications, etc.) MUST be confirmed with the
user. Do NOT assume or use default values without explicit user approval.
| Parameter Name | Required/Optional | Description | Default Value |
|---|---|---|---|
| Request ID | Required | The traceid from DDoS Pro's block response page | None |
| Domain | Optional | The website domain configured in DDoS Pro (auto-discovered if not provided) | Auto-discover |
| DDoS Instance ID | Optional | DDoS Pro instance ID (auto-discovered if not provided) | Auto-discover |
| SLS Project | Optional | SLS Project name (auto-discovered if not provided) | Auto-discover |
| SLS Logstore | Optional | SLS Logstore name (auto-discovered if not provided) | Auto-discover |
| RegionId | Optional | DDoS Pro region: cn-hangzhou (China Mainland) or ap-southeast-1 (International) | cn-hangzhou |
Core Workflow
[MUST] Required API Call Sequence — The following API calls MUST be executed in order for every invocation of this skill. Do NOT skip any step, even if you believe the result is known in advance:
1. Step 2a →ddoscoo DescribeInstances(both regions) + if domain unknown:DescribeWebAccessLogDispatchStatusfor domain discovery only
2. Step 2b →ddoscoo DescribeSlsOpenStatus+DescribeLogStoreExistStatus+DescribeSlsLogstoreInfo
3. Step 2c →ddoscoo DescribeWebAccessLogStatusonly (domain must be known from user or Step 2a;DescribeWebAccessLogDispatchStatusis NOT permitted here)
4. Step 3 → sls GetLogs (query block log by Request ID)5. Step 5 → Output analysis report
[MUST] User-Agent Header — EveryaliyunCLI command in this skill MUST include--header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryto identify the caller.
[MUST] 敏感数据脱敏 — 全局规则,贯穿所有输出 — 以下规则适用于整个工作流的所有输出,包括最终报告、中间分析、日志引用、补充说明的任何段落,不得在任何位置还原已脱敏的数据:
- Client IP:仅保留第一段,其余用 * 替代。适用于所有输出格式(JSON 字段、纯文本段落均须脱敏):- 纯文本段落:140.205.11.30→140.*.*.*;"来自 IP 140.205.11.30 的请求" → "来自 IP 140...* 的请求"
- JSON 字段引用:"real_client_ip": "140.205.11.30"→"real_client_ip": "140.*.*.*"
- Cookie / Authorization / Token:整个值替换为 [MASKED],包括在引用原始日志字段时- Query Parameters:所有参数值替换为***。示例:?token=abc&name=test→?token=***&name=***
- User-Agent 字符串:截取前 32 个字符
Step 1: Information Collection
Confirm the Request ID (traceid) with the user. Guide them to obtain it from: 1. The block page displayed in the browser (shows Request ID directly) 2. The HTML body of DDoS Pro's block (intercept) response (contains traceid)
Optionally collect the domain name if the user knows which website was blocked.
Step 2: Discover DDoS Pro Instances and Verify Full Log Service
Step 2a: Discover DDoS Pro Instances and Protected Domains
# Query DDoS Pro instances (API endpoint region: cn-hangzhou for China, ap-southeast-1 for International)
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region ap-southeast-1 --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query[MUST] Instance Discovery Validation — After calling describe-instances, inspect the response:- If Instances is a non-empty array → record the instance(s) and proceed to Step 2b.- IfInstancesis empty ([]) for one region → retry with the other region before proceeding.
- If both regions return empty → stop and inform the user: "No DDoS Pro instances were found under this account. Please verify your credentials and region."
- Do NOT proceed to Step 2b or beyond if `describe-instances` returns no results. An empty instance list means subsequent SLS and log queries will also fail — continuing will produce an empty or incorrect report.
[MUST] Domain Discovery — Step 2c requires a known domain name to call describe-web-access-log-status. If the user did NOT provide the domain in their message, discover it HERE in Step 2a before proceeding:```bash
# Discover all protected domains (domain discovery only — do NOT use the log status from this response)
aliyun ddoscoo describe-web-access-log-dispatch-status --page-number 1 --page-size 10 --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
```
Extract the domain name(s) from the response and record them. This API is used only for domain name discovery, not for checking log status. The actual log status check happens in Step 2c using describe-web-access-log-status.[MUST] International Region API Error Recovery: If anyap-southeast-1API call returnsInvalidRosettaRegionId,400 Bad Request, or similar region-level errors:
1. Do NOT abandon the workflow — continue with available data
2. For SLS-related operations: International DDoS Pro SLS projects are typically hosted incn-hangzhou(notap-southeast-1), with project names likeddosdip-project-<uid>-ap-southeast-1. Always trycn-hangzhouas the SLS region.
3. For rule query APIs (e.g.,describe-web-precise-access-rule,describe-l7-global-rule): Ifap-southeast-1fails, retry the same API call usingcn-hangzhouendpoint
4. [MUST] Never skip a user-requested query step due to region API errors — always attempt recovery via the alternative region before reporting failure
Step 2b: Check SLS and Full Log Status
First check if SLS is opened and log store exists:
aliyun ddoscoo describe-sls-open-status --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
aliyun ddoscoo describe-log-store-exist-status --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryThen get the SLS logstore info (project, logstore, capacity, TTL):
aliyun ddoscoo describe-sls-logstore-info --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query[IMPORTANT] Fallback for SLS Info Retrieval: Ifdescribe-sls-logstore-inforeturns an error (e.g.,400 InvalidRosettaRegionIdinap-southeast-1), use the following fallback methods in order:
>
Fallback 1 — Get SLS info from domain log status (requires knowing a domain):
```bash
aliyun ddoscoo describe-web-access-log-status --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
```
ExtractSlsProjectandSlsLogstorefrom the response.
>
Fallback 2 — List all SLS projects and find the ddoscoo one:
```bash
aliyun sls list-project --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
```
Look for project names containingddoscooorddosdip. Note: International DDoS Pro SLS projects may also be hosted incn-hangzhou.
Step 2c: Check Domain Full Log Status
⛔ FORBIDDEN: `describe-web-access-log-dispatch-status` is NOT used in this step.
Domain discovery was completed in Step 2a. This step has exactly ONE permitted API call.
By this point the domain name MUST be known (provided by the user, or discovered in Step 2a). Call:
aliyun ddoscoo describe-web-access-log-status --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query- 若返回
SlsConfigStatus=true,说明已开启,直接进入 Step 3。 - 若未开启,告知用户并征得同意后开启:
aliyun ddoscoo enable-web-access-log-config --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryConstraint: This skill only supports enabling full log (enable-web-access-log-config). Disabling is not permitted via this skill. Never calldisable-web-access-log-config.
[IMPORTANT] Error Handling for Enable: If enable-web-access-log-config returns an error:-DomainDoNotBelongToYou— Domain is not configured in this DDoS Pro instance. Verify the domain belongs to this instance, or try the other region (cn-hangzhou↔ap-southeast-1).
- 403 Forbidden / RAM permission error — See references/ram-policies.md.>
[IMPORTANT] Historical Logs: Enabling full log only records future requests. If the block event occurred before enabling, no SLS log will exist for that Request ID. Inform the user: "Full log has been enabled, but the historical block event cannot be queried via SLS. Please reproduce the block and retry with the new Request ID."
Step 3: Query SLS Logs
[MUST] Use the SLS CLI plugin (aliyun sls get-logs) for all log queries.Use the SLS project/logstore obtained from Step 2 to query block logs:
# Query SLS logs via plugin-mode call
TO_TIME=$(python3 -c "import time; print(int(time.time()))")
FROM_TIME=$((TO_TIME - 86400))
aliyun sls get-logs \
--project <project-name> \
--logstore <logstore-name> \
--from $FROM_TIME \
--to $TO_TIME \
--query "<request-id>" \
--reverse true \
--lines 100 \
--region <sls-region> \
--header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryIf no results found in the last 24 hours, progressively expand the time range:
- Last 3 days:
FROM_TIME=$((TO_TIME - 86400 * 3)) - Last 7 days:
FROM_TIME=$((TO_TIME - 86400 * 7)) - Last 30 days:
FROM_TIME=$((TO_TIME - 86400 * 30)) - Maximum (based on TTL):
FROM_TIME=$((TO_TIME - 86400 * <ttl_days>))
Fallback method — If the SLS plugin command above fails (e.g., plugin not installed), use the Python script:
```bash
python3 scripts/get_ddos_logs.py \
--project <project-name> \
--logstore <logstore-name> \
--request-id <request-id> \
--region <sls-region>
```
Note: DDoS Pro full log SLS region mapping:
- China Mainland instances (
cn-hangzhou): SLS project is incn-hangzhou - International instances (
ap-southeast-1): SLS project is also typically in `cn-hangzhou` (notap-southeast-1), with project names likeddosdip-project-<uid>-ap-southeast-1
[MUST] Do NOT guess SLS project names. Always use the exact project/logstore values obtained from Step 2b (describe-sls-logstore-infoor its fallback). If both APIs failed, usealiyun sls list-project --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryto discover projects containingddoscooorddosdip.
Step 4: Query Rule Details
After obtaining the SLS log, extract key fields to determine the block type and query the specific rule configuration.
Step 4a: Identify Block Type from Log Fields
The two most important log fields for identifying the block type are:
- `cc_phase` — Identifies which protection module triggered the block
- `last_owner` — Format is
<rule_name>|<source>, wheresourceismanual(user-created) orclover(auto-generated)
`cc_phase` → Block Type → Query API Mapping:
cc_phase value | Block Type | Rule Detail Query Command |
|---|---|---|
gfcc / cc | CC Protection (频率控制自定义规则) | describe-web-cc-rules-v2 |
gfacl / acl | Precise Access Control (精确访问控制) | describe-web-precise-access-rule |
gfai / ai | AI Smart Protection (AI智能防护) | describe-web-cc-protect-switch |
gfglobal / global / gf_rule | Global Defense Policy (全局防护策略) | describe-l7-global-rule |
gfbwip / blacklist | IP Blacklist (IP黑名单) | describe-web-rules (BlackList field) |
gfareaban / region / geo | Region Blocking (区域封禁) | describe-web-area-block-configs |
Other useful log fields:
| Log Field | Description |
|---|---|
cc_action | Action taken: block, captcha, close, watch |
cc_rule_id | Specific rule ID that triggered |
cc_blocks | Whether the request was blocked (1 = yes) |
final_action | Final action taken on the request |
final_plugin | Block plugin identifier |
traceid | Request trace ID (same as Request ID in block page) |
matched_host | The domain that matched the request |
host | The Host header from the request |
real_client_ip | Client's real IP address |
last_owner | `<rule_name>\ |
isp_line | DDoS Pro 接入线路(如:电信、联通、移动、香港、海外等)。注意:此字段反映的是 DDoS Pro 的接入线路,不等同于客户端的物理位置。报告中应表述为"请求经由 {isp_line} 线路接入",不可将其直接等同于客户端所在地区 |
Step 4b: Query Strategy Switch Status (策略预检)
[MUST] Before querying specific rules, first check which protection modules are enabled:
aliyun ddoscoo describe-web-cc-protect-switch --domains.1 '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryThis returns all switch states. Key fields:
| Field | Description | Values |
|---|---|---|
CcEnable | CC protection master switch | 0 (off) / 1 (on) |
CcCustomRuleEnable | Custom CC rules switch | 0 / 1 |
PreciseRuleEnable | Precise Access Control (ACL) switch | 0 / 1 |
CcGlobalSwitch | Global defense switch | close / open |
AiRuleEnable | AI smart protection switch | 0 / 1 |
AiMode | AI mode | watch / defense |
AiTemplate | AI level | level30 / level60 / level90 |
BlackWhiteListEnable | IP blacklist/whitelist switch | 0 / 1 |
RegionBlockEnable | Region blocking switch | 0 / 1 |
Step 4c: Query Specific Rule Details
Based on cc_phase, call the corresponding API to fetch the rule configuration.
If `cc_phase` = `cc` → CC Protection Rules:
# Query all CC rules for the domain; use --owner manual for user rules, clover for auto rules
aliyun ddoscoo describe-web-cc-rules-v2 --domain '<domain>' --offset 0 --page-size 30 --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryThen find the specific rule by matching last_owner's rule name (the part before |) against the rule's name field in the response.
If `cc_phase` = `gfacl` → Precise Access Control (ACL) Rules:
aliyun ddoscoo describe-web-precise-access-rule --domains.1 '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryThen find the specific rule by matching last_owner's rule name against the rule's Name field in the response.
If `cc_phase` = `ai` → AI Smart Protection:
# AI protection has no individual rules; check mode and level from switch status
aliyun ddoscoo describe-web-cc-protect-switch --domains.1 '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryReport the AiMode (watch/defense), AiTemplate (level30/60/90), and AiRuleEnable status.
If `cc_phase` = `global` or `gf_rule` → Global Defense Policy:
# Get global rule list with RuleId, Action, Enabled, Description
aliyun ddoscoo describe-l7-global-rule --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryIf `cc_phase` = `blacklist` → IP Blacklist/Whitelist:
# Get blacklist and whitelist IPs from domain web rules
aliyun ddoscoo describe-web-rules --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryExtract BlackList and WhiteList arrays from the response.
If `cc_phase` = `region` or `geo` → Region Blocking:
aliyun ddoscoo describe-web-area-block-configs --domains.1 '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryCheck which regions have Block = 1.
[IMPORTANT] Domain Not Found: If the domain query returns DomainNotExist, the domain may have been removed from DDoS Pro after the block event. Report this to the user — the log is still valid but rule details cannot be retrieved.See references/domain-security-policy.md for the complete domain security policy management reference including rule creation, modification, deletion, and field reference tables.
Step 5: Output Analysis Report
[MUST] Sensitive Data Masking — Apply the global masking rules defined in Core Workflow to all fields in this report, including any supplementary paragraphs. Never restore masked data in any section.
## DDoS Pro Intercept Analysis Report
### Request Information
- Request ID: {request_traceid}
- Block Time: {time}
- Client IP: {masked_real_client_ip, e.g. 192.***.***.***}
- ISP Line: {isp_line}(DDoS Pro 接入线路,非客户端实际位置)
- Domain: {matched_host}
- Request URL: {host}{request_path}?{masked_query_params}
### Block Details
- Rule ID: {final_rule_id 或 cc_rule_id;若日志中两个字段均不存在,输出 "N/A - 日志中未记录规则 ID",不可省略此行}
- Block Type: {final_plugin / cc_phase}
- Action: {final_action or cc_action}
### Recommendations
{Based on block type, refer to references/common-block-reasons.md}Troubleshooting
No Logs Found
1. Re-check SLS and log store status (Step 2b) 2. Check domain full log switch:
aliyun ddoscoo describe-web-access-log-status --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query3. Enable if disabled (check-then-act):
aliyun ddoscoo enable-web-access-log-config --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query4. Check all domain log dispatch status:
aliyun ddoscoo describe-web-access-log-dispatch-status --page-number 1 --page-size 50 --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryRequest ID Not Found
1. Verify Request ID format (typically 30+ hex characters) 2. Script auto-expands search up to 90 days 3. Try both regions (cn-hangzhou and ap-southeast-1) 4. Check log retention (TTL) via describe-sls-logstore-info
Multi-Instance Scenarios
DDoS Pro instances may span both regions. Query logs across all discovered SLS projects until the Request ID is found.
Rule Operation Constraints
See references/rule-operations.md for detailed instructions.
When user requests to disable a rule: 1. Check current status first (idempotent check-then-act) 2. Only disable operations are permitted; never delete rules 3. Confirm with user before executing
Disable CC Rule:
aliyun ddoscoo disable-web-cc-rule --domain '<domain>' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryDisable Precise Access Control:
aliyun ddoscoo modify-web-precise-access-switch --domain '<domain>' --config '{"PreciseRuleEnable": 0}' --region <region-id> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Verification Method
See references/verification-method.md for detailed verification steps.
Expected Outcome: Intercept analysis report generated with complete request information, rule details, and actionable recommendations.
Verification: After querying with a known Request ID, the output should contain all fields in the report template.
Cleanup
This skill is read-only by default and does not create persistent resources. No cleanup required unless:
- Full log was enabled for a domain during execution (inform user; this skill only enables, never disables)
- CC rules were disabled (can be re-enabled via
enable-web-cc-rule)
Best Practices
1. Always query both regions (cn-hangzhou and ap-southeast-1) for instance discovery 2. [MUST] Use aliyun sls get-logs (plugin mode, kebab-case) for SLS log queries 3. Do NOT guess SLS project/logstore names — always obtain them from describe-sls-logstore-info or describe-web-access-log-status 4. Check domain full log status before querying to avoid empty results 5. [MUST] Mask sensitive data in output reports: Client IP → first_octet.*.*.*, query parameters → ***, cookies/tokens → [MASKED] 6. Use idempotent check-then-act pattern before any write operations 7. Never delete rules — only disable/enable operations are permitted
Reference Links
| Reference | Description |
|---|---|
| references/ram-policies.md | RAM permission requirements |
| references/common-block-reasons.md | Common block reasons and recommendations |
| references/rule-config-details.md | Rule configuration field descriptions |
| references/rule-operations.md | Rule operation policy and constraints |
| references/domain-security-policy.md | Domain security policy management (query, create, modify, delete rules) |
| references/related-commands.md | All CLI commands used in this skill |
| references/verification-method.md | Success verification steps |
| references/cli-installation-guide.md | Aliyun CLI installation and upgrade guide |
Acceptance Criteria: alibabacloud-ddoscoo-intercept-query
Scenario: DDoS Pro (Anti-DDoS Pro) Intercept Query Purpose: Skill testing acceptance criteria
---
Correct CLI Command Patterns
1. Product — verify product name exists
✅ CORRECT
aliyun ddoscoo describe-instances ...
aliyun sls get-logs ...❌ INCORRECT
# Wrong product name (should be ddoscoo):
# aliyun ddos describe-instances ...
# Wrong case:
# aliyun DDosCoo describe-instances ...
# Traditional API format (PascalCase), not plugin mode:
# Must use kebab-case like describe-instances, NOT PascalCase like DescribeInstances2. Command — verify action exists under the product (plugin mode)
✅ CORRECT
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou
aliyun ddoscoo describe-web-access-log-status --domain 'example.com' --region cn-hangzhou
aliyun ddoscoo describe-web-cc-rules-v2 --domain 'example.com' --region cn-hangzhou
aliyun ddoscoo describe-web-precise-access-rule --domains 'example.com' --region cn-hangzhou❌ INCORRECT
# Traditional API format (PascalCase), not plugin mode:
# Must use kebab-case like describe-instances, NOT PascalCase
# Must use kebab-case like describe-web-access-log-status, NOT PascalCase
# Must use kebab-case like describe-web-cc-rules-v2, NOT PascalCase3. Parameters — verify each parameter name exists for the command
✅ CORRECT
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou
aliyun ddoscoo disable-web-cc-rule --domain 'example.com' --region cn-hangzhou❌ INCORRECT
# Wrong parameter format (PascalCase vs kebab-case):
# Must use --page-number, NOT --PageNumber
# Must use --domain, NOT --Domain4. AI-Mode Lifecycle + User-Agent Header
✅ CORRECT
# At skill start: enable AI-Mode and set User-Agent
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query"
# Every aliyun command must also include --header with full skill name
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
aliyun sls get-logs --project <p> --logstore <l> --from <ts> --to <ts> --query <q> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
# At skill exit (every exit point): disable AI-Mode
aliyun configure ai-mode disable❌ INCORRECT
# Missing --header on any command
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou
# Missing skill name suffix in User-Agent
aliyun ddoscoo describe-instances ... --header User-Agent=AlibabaCloud-Agent-Skills
# Not disabling AI-mode at exit
# (AI-mode must be disabled before final response)5. Security — never expose credentials
✅ CORRECT
aliyun configure list # Only check status❌ INCORRECT
echo $ALIBABA_CLOUD_ACCESS_KEY_ID # FORBIDDEN: printing AK
aliyun configure set --access-key-id xxx # FORBIDDEN: literal credential values---
Correct Script Patterns
1. SLS Log Query Script
✅ CORRECT
python3 scripts/get_ddos_logs.py \
--project ddoscoo-project-xxx \
--logstore ddoscoo-logstore \
--request-id 2f6fc15517769105850466500e008c \
--region cn-hangzhou❌ INCORRECT
python3 get_ddos_logs.py ... # Script not in scripts/ directory
python3 scripts/get_ddos_logs.py --request_id # Wrong parameter format (underscore vs hyphen)---
Workflow Patterns
1. Idempotent Check-Then-Act
✅ CORRECT
1. Query current state (describe-web-cc-rules-v2 / describe-web-precise-access-rule)
2. If already in target state -> skip, inform user
3. If not -> confirm with user -> execute change❌ INCORRECT
1. Directly execute change without checking current state
2. Execute change without user confirmation2. Full Log Enable Flow
✅ CORRECT
1. Check SLS status (describe-sls-open-status)
2. Check log store exists (describe-log-store-exist-status)
3. Check domain log status (describe-web-access-log-status)
4. If enabled -> proceed to query
5. If not -> inform user -> get consent -> enable (enable-web-access-log-config)❌ INCORRECT
1. Skip status check, directly enable
2. Disable full log (disable-web-access-log-config) — FORBIDDEN via this skillAliyun CLI Installation & Configuration Guide
Complete guide for installing and configuring Aliyun CLI.
Aliyun CLI 3.3.3+: Supports installing and using all published Alibaba Cloud product plugins. Make sure to upgrade to 3.3.3 or later for full plugin ecosystem coverage.
Installation
macOS
Using Homebrew (Recommended)
brew install aliyun-cli
# Upgrade to latest
brew upgrade aliyun-cli
# Verify version (>= 3.3.3)
aliyun versionUsing Binary
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-macosx-latest-amd64.tgz
# Extract
tar -xzf aliyun-cli-macosx-latest-amd64.tgz
# Move to PATH
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionLinux
Debian/Ubuntu
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionCentOS/RHEL
# Download
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-amd64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-amd64.tgz
sudo mv aliyun /usr/local/bin/
# Verify
aliyun versionARM64 Architecture
# Download ARM64 version
wget https://aliyuncli.alicdn.com/aliyun-cli-linux-latest-arm64.tgz
# Extract and install
tar -xzf aliyun-cli-linux-latest-arm64.tgz
sudo mv aliyun /usr/local/bin/Windows
Using Binary 1. Download from: https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip 2. Extract the ZIP file 3. Add the directory to your PATH environment variable 4. Open new Command Prompt or PowerShell 5. Verify: aliyun version
Using PowerShell
# Download
Invoke-WebRequest -Uri "https://aliyuncli.alicdn.com/aliyun-cli-windows-latest-amd64.zip" -OutFile "aliyun-cli.zip"
# Extract
Expand-Archive -Path aliyun-cli.zip -DestinationPath C:\aliyun-cli
# Add to PATH (requires admin privileges)
$env:Path += ";C:\aliyun-cli"
[Environment]::SetEnvironmentVariable("Path", $env:Path, [System.EnvironmentVariableTarget]::Machine)
# Verify
aliyun versionConfiguration
Quick Start
aliyun configure set \
--mode AK \
--access-key-id <your-access-key-id> \
--access-key-secret <your-access-key-secret> \
--region cn-hangzhouAll aliyun configure commands support non-interactive flags, which is the recommended approach — it works in scripts, CI/CD pipelines, and agent-driven automation without hanging on stdin prompts.
Where to Get Access Keys
1. Log in to Aliyun Console: https://ram.console.aliyun.com/ 2. Navigate to: AccessKey Management 3. Create a new AccessKey pair 4. Save the secret immediately — it's only shown once
Configuration Modes
Aliyun CLI supports 6 authentication modes. All examples below use non-interactive flags.
1. AK Mode (Access Key)
Most common mode for personal accounts and scripts.
aliyun configure set \
--mode AK \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--region cn-hangzhouConfiguration is stored in ~/.aliyun/config.json:
{
"current": "default",
"profiles": [
{
"name": "default",
"mode": "AK",
"access_key_id": "LTAI5tXXXXXXXX",
"access_key_secret": "8dXXXXXXXXXXXXXXXXXXXXXXXX",
"region_id": "cn-hangzhou",
"output_format": "json",
"language": "en"
}
]
}2. StsToken Mode (Temporary Credentials)
For short-lived access (tokens expire in 1-12 hours).
aliyun configure set \
--mode StsToken \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--sts-token v1.0:XXXXXXXXXXXXXXXX \
--region cn-hangzhouUse cases: CI/CD pipelines, temporary access for external contractors, cross-account access.
3. RamRoleArn Mode (Assume RAM Role)
Assume a RAM role for elevated or cross-account access.
aliyun configure set \
--mode RamRoleArn \
--access-key-id LTAI5tXXXXXXXX \
--access-key-secret 8dXXXXXXXXXXXXXXXXXXXXXXXX \
--ram-role-arn acs:ram::123456789012:role/AdminRole \
--role-session-name my-session \
--region cn-hangzhouUse cases: cross-account resource access, temporary elevated privileges, role-based access control.
4. EcsRamRole Mode (ECS Instance RAM Role)
Use the RAM role attached to an ECS instance — no credentials needed.
aliyun configure set \
--mode EcsRamRole \
--ram-role-name MyEcsRole \
--region cn-hangzhouRequirements: must be running on an ECS instance with a RAM role attached.
Use cases: scripts and automation running on ECS instances.
5. RsaKeyPair Mode (RSA Key Pair)
Use RSA key pair for authentication (generate key pair in Aliyun Console first).
aliyun configure set \
--mode RsaKeyPair \
--private-key /path/to/private-key.pem \
--key-pair-name my-key-pair \
--region cn-hangzhou6. RamRoleArnWithEcs Mode (ECS + RAM Role)
Combine ECS instance role with RAM role assumption for cross-account access from ECS.
aliyun configure set \
--mode RamRoleArnWithEcs \
--ram-role-name MyEcsRole \
--ram-role-arn acs:ram::123456789012:role/TargetRole \
--role-session-name my-session \
--region cn-hangzhouEnvironment Variables
Highest priority - overrides config file
Access Key Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouSTS Token Mode
export ALIBABA_CLOUD_ACCESS_KEY_ID=your_access_key_id
export ALIBABA_CLOUD_ACCESS_KEY_SECRET=your_access_key_secret
export ALIBABA_CLOUD_SECURITY_TOKEN=your_sts_token
export ALIBABA_CLOUD_REGION_ID=cn-hangzhouECS RAM Role Mode
export ALIBABA_CLOUD_ECS_METADATA=role_nameUse Case:
- CI/CD pipelines
- Docker containers
- Temporary credential override
Managing Multiple Profiles
Create Named Profiles
aliyun configure set --profile projectA \
--mode AK \
--access-key-id LTAI5tAAAAAAAA \
--access-key-secret 8dAAAAAAAAAAAAAAAAAAAAAAAA \
--region cn-hangzhou
aliyun configure set --profile projectB \
--mode AK \
--access-key-id LTAI5tBBBBBBBB \
--access-key-secret 8dBBBBBBBBBBBBBBBBBBBBBBBB \
--region cn-shanghaiUse Specific Profile
aliyun ecs describe-instances --profile projectA
export ALIBABA_CLOUD_PROFILE=projectA
aliyun ecs describe-instances # Uses projectAList and Switch Profiles
aliyun configure list # List all profiles
aliyun configure set --current projectA # Switch default profileCredential Priority
Credentials are loaded in this order (first found wins):
1. Command-line flag: --profile <name> 2. Environment variable: ALIBABA_CLOUD_PROFILE 3. Environment credentials: ALIBABA_CLOUD_ACCESS_KEY_ID, etc. 4. Configuration file: ~/.aliyun/config.json (current profile) 5. ECS Instance RAM Role: If running on ECS with attached role
Verification
Test Authentication
# Basic test - list regions
aliyun ecs describe-regions
# Expected output: JSON array of regionsIf successful, you'll see:
{
"Regions": {
"Region": [
{
"RegionId": "cn-hangzhou",
"RegionEndpoint": "ecs.cn-hangzhou.aliyuncs.com",
"LocalName": "华东 1(杭州)"
},
...
]
},
"RequestId": "..."
}If failed, you'll see error messages:
InvalidAccessKeyId.NotFound- Wrong Access Key IDSignatureDoesNotMatch- Wrong Access Key SecretInvalidSecurityToken.Expired- STS token expired (for StsToken mode)Forbidden.RAM- Insufficient permissions
Debug Configuration
# Show current configuration
aliyun configure get
# Test with debug logging
aliyun ecs describe-regions --log-level=debug
# Check credential provider
aliyun configure get modeSecurity Best Practices
1. Use RAM Users (Not Root Account)
❌ Don't: Use Aliyun root account credentials ✅ Do: Create RAM users with specific permissions
# Create RAM user in console
# Attach only necessary policies
# Use RAM user's access keys2. Principle of Least Privilege
Grant only the minimum permissions needed:
# Example: Read-only ECS access
# Attach policy: AliyunECSReadOnlyAccess3. Rotate Access Keys Regularly
# Create new access key in RAM Console, then update configuration
aliyun configure set --access-key-id NEW_KEY --access-key-secret NEW_SECRET
# Delete old access key from console4. Use STS Tokens for Temporary Access
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token XXXX --region cn-hangzhou5. Use ECS RAM Roles When Possible
aliyun configure set --mode EcsRamRole --ram-role-name MyRole --region cn-hangzhou6. Never Commit Credentials
# Add to .gitignore
echo "~/.aliyun/config.json" >> .gitignore
# Use environment variables in CI/CD instead7. Secure Config File
# Restrict permissions
chmod 600 ~/.aliyun/config.jsonTroubleshooting
Issue: Command Not Found
# Check installation
which aliyun
# Check PATH
echo $PATH
# Reinstall or add to PATHIssue: Authentication Failed
# Verify configuration
aliyun configure get
# Test with debug
aliyun ecs describe-regions --log-level=debug
# Check credentials in console
# Verify access key is activeIssue: Permission Denied
# Error: Forbidden.RAM
# Check RAM user permissions
# Attach necessary policies in RAM console
# Example: AliyunECSFullAccess for ECS operationsIssue: STS Token Expired
# Error: InvalidSecurityToken.Expired
# Reconfigure with new token
aliyun configure set --mode StsToken \
--access-key-id XXXX --access-key-secret XXXX \
--sts-token NEW_TOKEN --region cn-hangzhouIssue: Wrong Region
# Some resources may not exist in the specified region
# Check available regions
aliyun ecs describe-regions
# Update default region
aliyun configure set region cn-shanghaiAdvanced Configuration
Custom Endpoint
# Use custom or private endpoint
export ALIBABA_CLOUD_ECS_ENDPOINT=ecs-vpc.cn-hangzhou.aliyuncs.comProxy Settings
# HTTP proxy
export HTTP_PROXY=http://proxy.example.com:8080
export HTTPS_PROXY=http://proxy.example.com:8080
# No proxy for specific domains
export NO_PROXY=localhost,127.0.0.1,.aliyuncs.comTimeout Settings
# Connection timeout (default: 10s)
export ALIBABA_CLOUD_CONNECT_TIMEOUT=30
# Read timeout (default: 10s)
export ALIBABA_CLOUD_READ_TIMEOUT=30Next Steps
After installation and configuration:
1. Install plugins for services you need (v3.3.3+ supports all published product plugins):
aliyun plugin install --names ecs vpc rds
# List all available plugins
aliyun plugin list-remote2. Explore commands:
aliyun ecs --help
aliyun fc --help3. Read documentation:
- Command Syntax Guide
- Global Flags Reference
- Common Scenarios
References
- Official Documentation: https://help.aliyun.com/zh/cli/
- RAM Console: https://ram.console.aliyun.com/
- Access Key Management: https://ram.console.aliyun.com/manage/ak
- Plugin Repository: https://github.com/aliyun/aliyun-cli
Common DDoS Pro Block Reasons and Recommendations
Block Reason Reference Table
| Rule Type | Common Causes | Recommendations |
|---|---|---|
| CC Protection (频率控制) | Request frequency exceeded CC threshold | Check if request pattern is normal; adjust CC rule threshold or switch to observation mode |
| Precise Access Control (精确访问控制) | URL/headers/parameters matched ACL rules | Verify if the request matches business expectations; check rule matching conditions |
| Region Blocking (区域封禁) | Source region/country is restricted | Verify if the access region should be allowed; adjust region blocking config |
| IP Blacklist (IP黑名单) | Client IP is on the auto CC blacklist | Check if IP was blocked by mistake; remove from blacklist if legitimate |
| AI Smart Protection (AI智能防护) | AI model identified request as malicious | Verify if request behavior is normal; adjust AI protection mode |
| Global Defense Policy (全局防护策略) | Triggered global L7 defense rules | Check global rule configuration; adjust if causing false positives |
DDoS Pro SLS Full Log Key Fields
| Field | Description |
|---|---|
request_traceid | Request trace ID (used for intercept query) |
cc_action | CC protection action: close (pass), captcha (challenge), block (deny) |
cc_rule_id | CC rule ID that triggered the action |
cc_phase | CC protection phase |
final_action | Final action taken on the request |
final_plugin | Plugin/module that triggered the block |
final_rule_id | Rule ID that caused the final action |
matched_host | Matched domain name |
real_client_ip | Real client IP address |
host | Request Host header |
request_uri | Request URI path |
request_method | HTTP method (GET, POST, etc.) |
status | HTTP response status code |
upstream_status | Origin server response status code |
http_user_agent | Client User-Agent header |
time | Log timestamp |
Domain Naming in DDoS Pro
DDoS Pro website forwarding rules are domain-based. The domain configured in DDoS Pro forwarding rules is directly used as the identifier (e.g., www.example.com).
域名安全策略管理
目录
域名预检
若提供了域名信息,则提前获取域名配置信息。若未提供域名,使用 AskUserQuestion 收集域名。
aliyun ddoscoo describe-domain-resource --domain '<域名>' --region cn-hangzhou #获取国内高防实例的域名配置信息
aliyun ddoscoo describe-domain-resource --domain '<域名>' --region ap-southeast-1 #获取国际高防实例的域名配置信息策略预检
# 获取策略开关状态
aliyun ddoscoo describe-web-cc-protect-switch --domains.1 '<域名>' --region '<REGION>'
# 获取CC防护策略,其中manual代表手动策略|clover代表智能策略
aliyun ddoscoo describe-web-cc-rules-v2 --domain '<域名>' --offset 0 --page-size 30 --region '<REGION>'
# 获取ACL防护策略
aliyun ddoscoo describe-web-precise-access-rule --domains.1 '<域名>' --region '<REGION>'
# 获取全局防护策略的规则列表(含RuleId、Action、Enabled、Description)
aliyun ddoscoo describe-l7-global-rule --domain '<域名>' --region '<REGION>'
# 获取黑白名单IP列表
aliyun ddoscoo describe-web-rules --domain '<域名>' --region '<REGION>' | python3 -c "import sys,json;d=json.load(sys.stdin)['WebRules'][0];print('BlackList:',d.get('BlackList',[]));print('WhiteList:',d.get('WhiteList',[]))"
# 获取区域封禁配置(返回每个Region的Block状态 0/1)
aliyun ddoscoo describe-web-area-block-configs --domains.1 '<域名>' --region '<REGION>'describe-web-cc-protect-switch 返回字段说明:
| 字段 | 说明 | 取值 |
|---|---|---|
AiMode | 智能防护模式 | watch(预警)、defense(防护) |
AiRuleEnable | 智能防护开关 | 0(关闭)、1(开启) |
AiTemplate | 智能防护等级 | level30(宽松)、level60(正常)、level90(严格) |
BlackWhiteListEnable | 黑白名单开关 | 0(关闭)、1(开启) |
CcCustomRuleEnable | 自定义CC规则开关 | 0(关闭)、1(开启) |
CcEnable | CC防护总开关 | 0(关闭)、1(开启) |
CcGlobalSwitch | CC全局防护开关 | close(关闭)、open(开启) |
PreciseRuleEnable | 精确访问控制(ACL)开关 | 0(关闭)、1(开启) |
RegionBlockEnable | 区域封禁开关 | 0(关闭)、1(开启) |
说明: 其中 CcEnable、CcCustomRuleEnable、CcGlobalSwitch、PreciseRuleEnable 属于 CC 防护大类,由同一个开关接口控制。CcTemplate 和 Domain 可忽略。
CC防护
创建或编辑CC防护的自定义规则
单次最多支持10条策略下发,即RuleList内最多可包含10个完整的策略。
aliyun ddoscoo config-web-cc-rule-v2 --domain '<域名>' --rule-list '[{"action":"<block|challenge|watch>","name":"<规则名称>","ratelimit":{"interval":<统计时长>,"ttl":<处置时长>,"threshold":<阈值次数>,"target":"<统计源>","subkey":"<字段名称>"},"statistics":{"mode":"<count|distinct>","field":"<ip|header|uri>"},"condition":[{"field":"<匹配字段>","match_method":"<匹配方法>","content":"<匹配内容>","header_name":"<字段名称>"}],"status_code":{"enabled":<true|false>,"code":<状态码>,"use_ratio":<true|false>,"count_threshold":<数量阈值>}}]' --expires '<有效期秒数>' --region '<REGION>'参数填写指南
| 参数路径 | 参数名 | 是否必填 | 可选值/说明 |
|---|---|---|---|
--domain | 域名 | 必填 | 已配置转发规则的网站域名 |
action | 匹配动作 | 必填 | block(封禁)、challenge(挑战)、watch(观察) |
name | 规则名称 | 必填 | 自定义规则名称字符串,仅支持数字、字母、下划线 |
ratelimit.interval | 统计时长 | 必填 | 整数,单位:秒 |
ratelimit.ttl | 处置时长 | 必填 | 整数,单位:秒 |
ratelimit.threshold | 阈值次数 | 必填 | 整数,触发阈值(请求次数) |
ratelimit.target | 统计源 | 必填 | ip、header、session、cookie-name、query-parameter |
ratelimit.subkey | 字段名称 | 条件必填 | target 为 header/cookie-name/query-parameter 时必填 |
statistics | 去重统计 | 可选 | 整个对象可选,默认为不去重统计 |
statistics.mode | 去重模式 | 条件必填 | count(不去重)、distinct(去重统计) |
statistics.field | 统计源 | 条件必填 | ip、header、uri |
condition | 匹配条件 | 必填 | 数组类型,可包含多个条件,条件间为且关系 |
condition[].field | 匹配字段 | 必填 | 见匹配字段与匹配方法参考表 |
condition[].match_method | 匹配方法 | 必填 | 见匹配字段与匹配方法参考表 |
condition[].content | 匹配内容 | 必填 | 具体匹配值 |
condition[].header_name | 字段名称 | 条件必填 | field 为 header/cookie-name/query-parameter 时必填 |
status_code | 状态码统计 | 可选 | 整个对象可选,默认不启用 |
status_code.enabled | 是否开启 | 条件必填 | true、false |
status_code.code | 状态码 | 条件必填 | 整数,范围 100~599 |
status_code.use_ratio | 是否使用比率 | 条件必填 | true(按比率)、false(按数量) |
status_code.ratio_threshold | 比率阈值 | 可选 | 整数,范围 1~100 |
status_code.count_threshold | 数量阈值 | 可选 | 整数,范围 2~50000 |
--expires | 有效期 | 可选 | 整数,单位:秒;0 表示永久生效(默认) |
删除CC防护规则
单次最多支持10条策略下发,即RuleNames列表内最多可包含10个规则名称。
aliyun ddoscoo delete-web-cc-rule-v2 --domain '<域名>' --rule-names '["<规则名称1>","<规则名称2>"]' --region '<REGION>'关闭/开启CC防护
aliyun ddoscoo modify-web-cc-global-switch --domain '<域名>' --cc-global-switch '<close|open>' --region '<REGION>'精确访问控制(ACL)
创建或编辑ACL防护规则
单次最多支持10条策略下发,即Rules内最多可包含10个完整的策略。
aliyun ddoscoo modify-web-precise-access-rule --domain '<域名>' --rules '[{"action":"<accept|block|challenge|watch>","name":"<规则名称>","condition":[{"field":"<匹配字段>","match_method":"<匹配方法>","content":"<匹配内容>","header_name":"<字段名称>"}]}]' --expires '<有效期秒数>' --region '<REGION>'参数填写指南
| 参数路径 | 参数名 | 是否必填 | 可选值/说明 |
|---|---|---|---|
--domain | 域名 | 必填 | 已配置转发规则的网站域名 |
action | 匹配动作 | 必填 | accept(放行)、block(封禁)、challenge(挑战)、watch(观察) |
name | 规则名称 | 必填 | 自定义规则名称字符串 |
condition | 匹配条件 | 必填 | 数组类型,可包含多个条件,条件间为且关系 |
condition[].field | 匹配字段 | 必填 | 见匹配字段与匹配方法参考表 |
condition[].match_method | 匹配方法 | 必填 | 见匹配字段与匹配方法参考表 |
condition[].content | 匹配内容 | 必填 | 具体匹配值 |
condition[].header_name | 字段名称 | 条件必填 | field 为 header/cookie-name/query-parameter 时必填 |
--expires | 有效期 | 可选 | 整数,单位:秒;仅 action 为 block 时生效;不传表示永久生效 |
与CC防护的差异: ACL的action多了accept(放行),没有频率限制相关参数(ratelimit、statistics、status_code),是纯条件匹配型规则。
删除ACL防护规则
aliyun ddoscoo delete-web-precise-access-rule --domain '<域名>' --rule-names.1 '<规则名称1>' --rule-names.2 '<规则名称2>' --region '<REGION>'关闭/开启ACL防护
aliyun ddoscoo modify-web-precise-access-switch --domain '<域名>' --config '{"PreciseRuleEnable":<0|1>}' --region '<REGION>'AI智能防护
关闭/开启AI智能防护
aliyun ddoscoo modify-web-ai-protect-switch --domain '<域名>' --config '{"AiRuleEnable":<0|1>}' --region '<REGION>'设置AI智能防护模式和等级
aliyun ddoscoo modify-web-ai-protect-mode --domain '<域名>' --config '{"AiTemplate":"<level30|level60|level90>","AiMode":"<watch|defense>"}' --region '<REGION>'参数填写指南
| 参数路径 | 参数名 | 是否必填 | 可选值/说明 |
|---|---|---|---|
--domain | 域名 | 必填 | 已配置转发规则的网站域名 |
AiRuleEnable | 智能防护开关 | 必填 | 0(关闭)、1(开启) |
AiTemplate | 防护等级 | 必填 | level30(宽松)、level60(正常)、level90(严格) |
AiMode | 防护模式 | 必填 | watch(预警)、defense(防护) |
说明: 开关和模式/等级是两个独立接口。开关通过modify-web-ai-protect-switch控制,模式和等级通过modify-web-ai-protect-mode同时设置。查询当前状态通过策略预检中的describe-web-cc-protect-switch返回的AiRuleEnable、AiMode、AiTemplate字段获取。
全局防护策略
设置全局防护策略的开关和等级
aliyun ddoscoo config-domain-security-profile --domain '<域名>' --config '{"global_rule_enable":<0|1>,"global_rule_mode":"<weak|default|hard>"}' --region '<REGION>'参数填写指南
| 参数路径 | 参数名 | 是否必填 | 可选值/说明 |
|---|---|---|---|
--domain | 域名 | 必填 | 已配置转发规则的网站域名 |
global_rule_enable | 全局防护开关 | 可选 | 0(关闭)、1(开启) |
global_rule_mode | 防护等级 | 可选 | weak(宽松)、default(正常)、hard(严格) |
说明: Config中只需包含要修改的字段,未包含的字段保持不变。查询全局防护开关状态通过策略预检中的describe-web-cc-protect-switch返回的CcGlobalSwitch字段获取。全局防护等级无独立查询接口。
修改全局防护策略的规则动作和开关
单次最多支持10条策略下发,即RuleAttr内最多可包含10个完整的策略。
aliyun ddoscoo config-l7-global-rule --domain '<域名>' --rule-attr '[{"RuleId":"<规则ID>","Action":"<block|watch|challenge>","Enabled":<0|1>}]' --region '<REGION>'参数填写指南
| 参数路径 | 参数名 | 是否必填 | 可选值/说明 |
|---|---|---|---|
--domain | 域名 | 必填 | 已配置转发规则的网站域名 |
RuleId | 规则ID | 必填 | 从describe-l7-global-rule返回的规则ID |
Action | 规则动作 | 必填 | block(拦截)、watch(观察)、challenge(挑战) |
Enabled | 规则开关 | 必填 | 0(关闭)、1(开启) |
IP黑白名单
配置黑白名单IP
支持IP和IP/掩码格式,黑名单和白名单各最多2000个。白名单不支持配置/0网段到/8网段。该接口为全量覆盖,需传入完整的黑白名单列表。
aliyun ddoscoo config-web-ip-set --domain '<域名>' --black-list.1 '<IP或IP/掩码>' --black-list.2 '<IP或IP/掩码>' --white-list.1 '<IP或IP/掩码>' --white-list.2 '<IP或IP/掩码>' --region '<REGION>'注意: 该接口为全量覆盖模式,每次调用需传入完整的黑白名单列表。如需新增IP,应先通过策略预检中的describe-web-rules获取当前列表,追加后再调用本接口。关闭/开启黑白名单
aliyun ddoscoo modify-web-ip-set-switch --domain '<域名>' --config '{"bwlist_enable":<0|1>}' --region '<REGION>'区域封禁
设置封禁地域
该接口为全量覆盖模式,需传入完整的封禁地域列表。不传Regions参数表示清空所有封禁地域。
aliyun ddoscoo modify-web-area-block --domain '<域名>' --regions.1 '<地域代码1>' --regions.2 '<地域代码2>' --region '<REGION>'注意: 该接口为全量覆盖模式,每次调用需传入完整的封禁地域列表。如需新增地域,应先通过策略预检中的describe-web-area-block-configs获取当前已封禁列表(Block为1的Region),追加后再调用本接口。常用地域代码说明
| 地域代码格式 | 说明 | 示例 |
|---|---|---|
CN-ALL | 中国大陆全部 | CN-ALL |
CN-xxxxxx | 中国大陆省份 | CN-110000(北京)、CN-310000(上海)、CN-330000(浙江) |
OVERSEAS-ALL | 海外全部 | OVERSEAS-ALL |
OVERSEAS-xx | 海外国家(ISO 3166-1 alpha-2) | OVERSEAS-US(美国)、OVERSEAS-JP(日本) |
关闭/开启区域封禁
aliyun ddoscoo modify-web-area-block-switch --domain '<域名>' --config '{"RegionblockEnable":<0|1>}' --region '<REGION>'匹配字段与匹配方法参考表
CC防护和精确访问控制(ACL)共用以下匹配字段和匹配方法。
匹配字段与匹配方法对应关系
| field | 描述 | 可用 match_method |
|---|---|---|
ip | 访问请求的来源 IP | belong、nbelong、ipinlist、ipninlist |
uri | 访问请求的 URI 地址 | contain、ncontain、equal、nequal、lless、lequal、lgreat、prefix、inlist、ninlist |
referer | 访问请求的来源网址 | contain、ncontain、equal、nequal、lless、lequal、lgreat、nexist、inlist、ninlist |
user-agent | 客户端浏览器标识等信息 | contain、ncontain、equal、nequal、lless、lequal、lgreat、inlist、ninlist |
params | URL 地址中的参数部分 | contain、ncontain、equal、nequal、lless、lequal、lgreat、inlist、ninlist |
cookie | 访问请求中的 Cookie 信息 | contain、ncontain、equal、nequal、lless、lequal、lgreat、nexist、inlist、ninlist |
content-type | 响应 HTTP 内容类型 | contain、ncontain、equal、nequal、lless、lequal、lgreat、inlist、ninlist |
x-forwarded-for | 客户端真实 IP(XFF) | contain、ncontain、equal、nequal、lless、lequal、lgreat、nexist、inlist、ninlist |
content-length | 访问请求包含的字节数 | vless、vequal、vgreat |
post-body | 访问请求的内容信息 | contain、ncontain、equal、nequal、inlist、ninlist |
http-method | 访问请求方法 | equal、nequal、inlist、ninlist |
header | 自定义 HTTP 头部字段 | contain、ncontain、equal、nequal、lless、lequal、lgreat、nexist、inlist、ninlist |
scheme | 访问请求协议 | equal、nequal |
protocol | HTTP 版本 | equal、nequal、inlist、ninlist |
http2-fingerprint | HTTP2.0 指纹 | equal、nequal、inlist、ninlist |
ja3-fingerprint | JA3 指纹 | equal、nequal、inlist、ninlist |
ja4-fingerprint | JA4 指纹 | equal、nequal、inlist、ninlist |
area | 请求大洲/国家 | areainlist |
uri-path | 请求 URI-Path | contain、ncontain、equal、nequal、lless、lequal、lgreat、prefix、inlist、ninlist |
cookie-name | 自定义 Cookie | contain、ncontain、equal、nequal、lless、lequal、lgreat、prefix、inlist、ninlist |
query-parameter | 自定义请求参数 | contain、ncontain、equal、nequal、lless、lequal、lgreat、prefix、inlist、ninlist |
server-port | 请求 Server-Port | vless、vequal、vgreat |
match_method 逻辑符说明
| match_method | 说明 |
|---|---|
belong | 属于 |
nbelong | 不属于 |
ipinlist | IP 在列表中 |
ipninlist | IP 不在列表中 |
contain | 包含 |
ncontain | 不包含 |
equal | 等于 |
nequal | 不等于 |
lless | 长度小于 |
lequal | 长度等于 |
lgreat | 长度大于 |
prefix | 前缀匹配 |
inlist | 等于多值之一 |
ninlist | 不等于多值之一 |
nexist | 不存在 |
vless | 值小于 |
vequal | 值等于 |
vgreat | 值大于 |
areainlist | 区域封禁选择 |
RAM Policy Requirements
This skill requires the following RAM permissions to operate correctly.
Minimum Required Permissions
DDoS Pro (ddoscoo) Permissions
| Action | Resource | Description |
|---|---|---|
yundun-ddoscoo:DescribeInstances | * | Query DDoS Pro instance list |
yundun-ddoscoo:DescribeInstanceIds | * | Query DDoS Pro instance IDs |
yundun-ddoscoo:DescribeSlsOpenStatus | * | Check SLS open status |
yundun-ddoscoo:DescribeLogStoreExistStatus | * | Check if log store exists |
yundun-ddoscoo:DescribeSlsLogstoreInfo | * | Get SLS logstore info (project, logstore, capacity, TTL) |
yundun-ddoscoo:DescribeWebAccessLogStatus | * | Check domain full log status |
yundun-ddoscoo:DescribeWebAccessLogDispatchStatus | * | Check all domains full log dispatch status |
yundun-ddoscoo:DescribeWebRules | * | Query website forwarding rules |
yundun-ddoscoo:DescribeWebCcRulesV2 | * | Query CC protection rules |
yundun-ddoscoo:DescribeWebPreciseAccessRule | * | Query precise access control rules |
yundun-ddoscoo:DescribeWebAreaBlockConfigs | * | Query region blocking configs |
yundun-ddoscoo:DescribeAutoCcBlacklist | * | Query auto CC blacklist |
yundun-ddoscoo:DescribeL7GlobalRule | * | Query global defense policy |
SLS Permissions
| Action | Resource | Description |
|---|---|---|
log:GetLogStoreLogs | acs:log:*:*:project/<ddos-sls-project>/logstore/<ddos-logstore> | Query DDoS Pro full logs from SLS |
Optional Permissions (Log Service Management)
These permissions are only needed when enabling full log for a domain:
| Action | Resource | Description |
|---|---|---|
yundun-ddoscoo:EnableWebAccessLogConfig | * | Enable full log for a domain (enable only, disable is not permitted) |
Optional Permissions (Rule Operations)
These permissions are only needed when the user requests to disable a rule:
| Action | Resource | Description |
|---|---|---|
yundun-ddoscoo:DisableWebCcRule | * | Disable CC custom rule for a domain |
yundun-ddoscoo:ModifyWebPreciseAccessSwitch | * | Toggle precise access control switch |
Sample RAM Policy (JSON)
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"yundun-ddoscoo:DescribeInstances",
"yundun-ddoscoo:DescribeInstanceIds",
"yundun-ddoscoo:DescribeSlsOpenStatus",
"yundun-ddoscoo:DescribeLogStoreExistStatus",
"yundun-ddoscoo:DescribeSlsLogstoreInfo",
"yundun-ddoscoo:DescribeWebAccessLogStatus",
"yundun-ddoscoo:DescribeWebAccessLogDispatchStatus",
"yundun-ddoscoo:DescribeWebRules",
"yundun-ddoscoo:DescribeWebCcRulesV2",
"yundun-ddoscoo:DescribeWebPreciseAccessRule",
"yundun-ddoscoo:DescribeWebAreaBlockConfigs",
"yundun-ddoscoo:DescribeAutoCcBlacklist",
"yundun-ddoscoo:DescribeL7GlobalRule"
],
"Resource": "*"
},
{
"Effect": "Allow",
"Action": [
"log:GetLogStoreLogs"
],
"Resource": "acs:log:*:*:project/*/logstore/*"
}
]
}Notes
- DDoS Pro resources use
*because instance IDs and domains are dynamically discovered during execution. - SLS resource can be narrowed to specific projects/logstores if known in advance.
- Rule disable permissions are intentionally excluded from the base policy. Only grant when rule disable operations are needed.
- This skill never calls delete APIs for rules — deletion is explicitly prohibited.
Related CLI Commands
All CLI commands used in this skill. Commands use plugin mode format (lowercase + hyphens). Every command includes --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query.
DDoS Pro (ddoscoo) Commands
| Command | Description | Used In |
|---|---|---|
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query DDoS Pro instance list | Step 2a |
aliyun ddoscoo describe-sls-open-status --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Check SLS open status | Step 2b |
aliyun ddoscoo describe-log-store-exist-status --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Check if log store exists | Step 2b |
aliyun ddoscoo describe-sls-logstore-info --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Get SLS logstore info (project, logstore, capacity, TTL) | Step 2b |
aliyun ddoscoo describe-web-access-log-status --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Check domain full log status | Step 2b / 2c |
aliyun ddoscoo describe-web-access-log-dispatch-status --page-number 1 --page-size 10 --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Check all domains full log dispatch status | Step 2c |
aliyun ddoscoo enable-web-access-log-config --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Enable full log for a domain (enable only) | Step 2c |
aliyun ddoscoo describe-web-cc-protect-switch --domains.1 <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query all protection switch states | Step 4b |
aliyun ddoscoo describe-web-cc-rules-v2 --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query CC protection rules | Step 4c |
aliyun ddoscoo describe-web-precise-access-rule --domains.1 <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query precise access control rules | Step 4c |
aliyun ddoscoo describe-web-area-block-configs --domains.1 <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query region blocking configs | Step 4c |
aliyun ddoscoo describe-l7-global-rule --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query global defense policy | Step 4c |
aliyun ddoscoo describe-web-rules --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query website forwarding rules (IP blacklist/whitelist) | Step 4c |
aliyun ddoscoo disable-web-cc-rule --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Disable CC custom rule | Rule Operations |
aliyun ddoscoo enable-web-cc-rule --domain <d> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Enable CC custom rule | Rule Operations |
aliyun ddoscoo modify-web-precise-access-switch --domain <d> --config <json> --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Toggle precise access control switch | Rule Operations |
SLS Commands
| Command | Description | Used In |
|---|---|---|
aliyun sls get-logs --project <p> --logstore <l> --from <ts> --to <ts> --query <q> --lines 100 --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | Query SLS logs by keyword (plugin-mode) | Step 3 |
aliyun sls list-project --region <r> --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query | List all SLS projects (fallback to discover ddoscoo project) | Step 2b |
Utility Commands
| Command | Description | Used In |
|---|---|---|
aliyun version | Check CLI version (>= 3.3.3 required) | Pre-check |
aliyun configure list | Check credential configuration | Authentication |
aliyun configure set --auto-plugin-install true | Enable auto plugin install | Pre-check |
aliyun plugin update | Update CLI plugins | Pre-check |
DDoS Pro Rule Configuration Details
Rule Types Overview
| Rule Type | CLI Query Command | Description |
|---|---|---|
| CC Protection Rules | describe-web-cc-rules-v2 | Custom frequency control (rate limiting) rules |
| Precise Access Control | describe-web-precise-access-rule | Custom ACL rules with condition matching |
| Region Blocking | describe-web-area-block-configs | Geographic region blocking |
| IP Blacklist | describe-auto-cc-blacklist | Auto CC blacklist IPs |
| IP Whitelist | describe-auto-cc-whitelist | Auto CC whitelist IPs |
| Global Defense Policy | describe-l7-global-rule | Global L7 defense rules |
| AI Smart Protection | modify-web-ai-protect-mode | AI-based protection mode |
CC Protection Rule Fields
| Parameter | Type | Description |
|---|---|---|
Name | string | Rule name |
Domain | string | Associated domain |
Act | string | Action: block, captcha, close (observation) |
Count | int | Request count threshold |
Interval | int | Time window (seconds) |
Mode | string | Matching mode |
Ttl | int | Blacklist duration (seconds) |
Uri | string | URI pattern to match |
Precise Access Control Rule Fields
| Parameter | Type | Description |
|---|---|---|
Name | string | Rule name |
Domain | string | Associated domain |
Action | string | Action: block, captcha, allow |
Conditions | array | List of matching conditions |
Expires | int | Rule expiration time (0 = permanent) |
Condition Structure
| Field | Description |
|---|---|
Field | Match field (e.g., URI, IP, Referer, User-Agent, Header, Cookie, etc.) |
MatchMethod | Match method (e.g., contain, not-contain, prefix, regex, etc.) |
Content | Match content/value |
Region Blocking Config Fields
| Parameter | Type | Description |
|---|---|---|
Domain | string | Associated domain |
RegionList | array | List of blocked regions |
SLS Log Field Mapping to Rule Type
| Log Field Pattern | Likely Rule Type |
|---|---|
cc_action = block/captcha, cc_rule_id present | CC Protection Rule |
final_plugin contains "precise" or "acl" | Precise Access Control |
final_plugin contains "region" or "geo" | Region Blocking |
final_plugin contains "blacklist" or "ip" | IP Blacklist |
final_plugin contains "ai" | AI Smart Protection |
DDoS Pro Rule Operation Policy
Warning: Rule Disabling Policy (Important!)
When the user requests to disable a rule, the following constraints must be followed:
1. Only Perform Disable Operations
Only call disable/switch APIs to turn off the rule. Never delete rules.
2. Never Delete Rules
Even if the disable operation fails, you must not call any delete API (e.g., delete-web-cc-rule, delete-web-cc-rule-v2, delete-web-precise-access-rule).
3. Never Modify Rule Content
Do not modify rule matching conditions, thresholds, or other configurations.
4. Failure Handling
- If the disable operation fails, inform the user of the failure reason
- Do not attempt to delete the rule or use other workarounds
- Wait for the user's new instructions before performing any other operations
5. Idempotent Check-Then-Act (Required)
Before executing any write operation, always query the current state first and skip the operation if the resource is already in the target state.
6. Pre-Operation Confirmation
Confirm operation: Disable rule {rule_name} (Domain: {domain})
- Operation type: Disable
- Will not delete the rule
- Will not modify rule content
- Can be re-enabled at any time
Continue? Reply "yes" to confirm---
Disable Commands by Rule Type
CC Protection Rule
Check current status:
aliyun ddoscoo describe-web-cc-rules-v2 --domain '<domain>' --region <region-id>Disable CC custom rule:
aliyun ddoscoo disable-web-cc-rule --domain '<domain>' --region <region-id>Re-enable CC custom rule:
aliyun ddoscoo enable-web-cc-rule --domain '<domain>' --region <region-id>Precise Access Control
Check current status:
aliyun ddoscoo describe-web-precise-access-rule --domains '<domain>' --region <region-id>Toggle precise access control switch:
aliyun ddoscoo modify-web-precise-access-switch --domain '<domain>' --config '{"PreciseRuleEnable": 0}' --region <region-id>Re-enable precise access control:
aliyun ddoscoo modify-web-precise-access-switch --domain '<domain>' --config '{"PreciseRuleEnable": 1}' --region <region-id>Region Blocking
Check current status:
aliyun ddoscoo describe-web-area-block-configs --domains '<domain>' --region <region-id>Toggle region blocking switch:
aliyun ddoscoo modify-web-area-block-switch --domain '<domain>' --config '{"RegionBlockSwitch": 0}' --region <region-id>Forbidden Operations
aliyun ddoscoo delete-web-cc-rule ... # FORBIDDEN
aliyun ddoscoo delete-web-cc-rule-v2 ... # FORBIDDEN
aliyun ddoscoo delete-web-precise-access-rule ... # FORBIDDEN---
Operation Flowchart
User requests to disable/enable a rule
|
Identify rule type (CC / Precise ACL / Region Block / etc.)
|
Query current rule status (check-then-act)
|
+---------------------+
| Already in target |
| state? |
+------+--------------+
Yes | No
| |
Inform user Confirm operation with user
(no action (disable only, no deletion)
needed) |
Execute disable command
|
+-------------+
| Success? |
+------+------+
Yes | No
| |
| Report failure reason
| Wait for user instructions
| (Do NOT attempt to delete)
v
Operation completeSuccess Verification Method
Scenario Goal Verification
Expected Outcome: Given a Request ID from a DDoS Pro block/intercept event, the skill produces a complete analysis report identifying the blocking rule, its configuration, and actionable recommendations.
Verification Steps
1. Instance Discovery Verification
Command:
aliyun ddoscoo describe-instances --page-number 1 --page-size 50 --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Indicator: Response contains Instances array with at least one valid DDoS Pro instance.
2. SLS and Log Store Status Verification
Command:
aliyun ddoscoo describe-sls-open-status --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-query
aliyun ddoscoo describe-log-store-exist-status --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Indicator: SLS is opened and log store exists.
3. SLS Logstore Info Verification
Command:
aliyun ddoscoo describe-sls-logstore-info --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Indicator: Response contains valid LogStore, ProjectName (or equivalent fields) with storage capacity and TTL info.
4. Domain Full Log Status Verification
Command:
aliyun ddoscoo describe-web-access-log-status --domain '<domain>' --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Indicator: Full log is enabled for the target domain.
5. Log Query Verification
Command:
python3 scripts/get_ddos_logs.py \
--project <project-name> \
--logstore <logstore-name> \
--request-id <known-request-id> \
--region <sls-region>Success Indicator: Returns at least one log record containing request_traceid, block-related fields (cc_action, final_action, final_plugin, final_rule_id).
6. Rule Detail Verification
CC Rules:
aliyun ddoscoo describe-web-cc-rules-v2 --domain '<domain>' --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-queryPrecise Access Control:
aliyun ddoscoo describe-web-precise-access-rule --domains.1 '<domain>' --region cn-hangzhou --header User-Agent=AlibabaCloud-Agent-Skills/alibabacloud-ddoscoo-intercept-querySuccess Indicator: Response contains rule details (Name, Action/Act, Conditions).
7. End-to-End Verification
Process: Run the complete workflow with a known Request ID.
Success Indicator: Output report contains all required fields:
- Request ID, Block Time, Client IP (masked)
- Rule ID / Rule Type, Block Action
- Recommendations based on block type
#!/usr/bin/env python3
"""
DDoS Pro (ddoscoo) SLS Full Log Query Script
Generates timestamps and calls aliyun sls get-logs to query DDoS Pro intercept/block logs
"""
import subprocess
import sys
import json
import time
import argparse
import re
# Note: User-Agent is managed globally via AI-Mode (aliyun configure ai-mode set-user-agent).
# No per-command --header is needed.
# ---------------------------------------------------------------------------
# Sensitive data masking helpers
# ---------------------------------------------------------------------------
# Fields that require masking in log output
_SENSITIVE_LOG_FIELDS = {
'real_client_ip', 'remote_addr', 'client_ip', 'src_ip',
'http_user_agent', 'user_agent',
'cookie', 'http_cookie', 'set_cookie',
'authorization', 'token', 'secret',
}
def _mask_ip(ip_str):
"""Mask an IP address, preserving only the first octet (IPv4) or prefix (IPv6).
Examples:
'192.168.1.100' -> '192.***.***.***'
'2001:db8::1' -> '2001:****:****:****'
"""
if not ip_str or not isinstance(ip_str, str):
return ip_str
ip_str = ip_str.strip()
if ':' in ip_str and '.' not in ip_str: # IPv6
parts = ip_str.split(':')
if len(parts) >= 2:
return parts[0] + ':****:****:****'
return ip_str
# IPv4 (may also contain port like 1.2.3.4:8080)
host = ip_str.split(':')[0] if ':' in ip_str else ip_str
octets = host.split('.')
if len(octets) == 4:
return f"{octets[0]}.***.***.***"
return ip_str
def _mask_uri(uri_str):
"""Mask query parameters in a URI while preserving the path.
Examples:
'/api/v1/user?token=abc123&name=test' -> '/api/v1/user?token=***&name=***'
'/static/page' -> '/static/page'
"""
if not uri_str or not isinstance(uri_str, str):
return uri_str
if '?' not in uri_str:
return uri_str
path, query = uri_str.split('?', 1)
masked_params = []
for param in query.split('&'):
if '=' in param:
key, _ = param.split('=', 1)
masked_params.append(f"{key}=***")
else:
masked_params.append(param)
return f"{path}?{'&'.join(masked_params)}"
def _mask_user_agent(ua_str):
"""Truncate User-Agent to first 32 chars to reduce PII exposure."""
if not ua_str or not isinstance(ua_str, str):
return ua_str
if len(ua_str) <= 32:
return ua_str
return ua_str[:32] + '...'
def _mask_field_value(field_key, value):
"""Apply appropriate masking based on the field key."""
field_lower = field_key.lower()
if field_lower in ('real_client_ip', 'remote_addr', 'client_ip', 'src_ip'):
return _mask_ip(str(value))
if field_lower in ('request_uri', 'uri', 'querystring', 'query_string'):
return _mask_uri(str(value))
if field_lower in ('http_user_agent', 'user_agent'):
return _mask_user_agent(str(value))
if field_lower in ('cookie', 'http_cookie', 'set_cookie',
'authorization', 'token', 'secret'):
return '******'
return value
def _is_sensitive_field(field_key):
"""Check if a field contains potentially sensitive data."""
fl = field_key.lower()
return (fl in _SENSITIVE_LOG_FIELDS or
'cookie' in fl or 'token' in fl or 'secret' in fl or
'password' in fl or 'auth' in fl or 'credential' in fl)
def get_current_timestamp():
"""Get current Unix timestamp (seconds)"""
return int(time.time())
def query_sls_logs(project, logstore, request_id, region, ttl=90, profile=None):
"""
Query SLS logs with automatic time range expansion
Args:
project: SLS Project name
logstore: SLS Logstore name
request_id: Request ID to query
region: SLS region
ttl: Log retention period (days), default 90
profile: Aliyun CLI profile name (optional)
Returns:
Query results (list of dicts)
"""
to_time = get_current_timestamp()
max_from_time = to_time - ttl * 86400 # Maximum lookback time
# Initial time range: last 24 hours
from_time = to_time - 86400
# Progressively expand time range
time_ranges = [
(to_time - 86400, "last 24 hours"),
(to_time - 86400 * 3, "last 3 days"),
(to_time - 86400 * 7, "last 7 days"),
(to_time - 86400 * 30, "last 30 days"),
(max_from_time, f"last {ttl} days (maximum range)"),
]
for from_ts, range_desc in time_ranges:
# Ensure not exceeding maximum lookback time
if from_ts < max_from_time:
from_ts = max_from_time
range_desc = f"last {ttl} days (maximum range)"
print(f"\nQuerying logs for {range_desc}...")
print(f"Time range: {from_ts} ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(from_ts))}) -> {to_time} ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(to_time))})")
# Build aliyun sls command (plugin-mode: kebab-case get-logs per SA-2.11)
cmd = [
"aliyun", "sls", "get-logs",
"--project", project,
"--logstore", logstore,
"--from", str(from_ts),
"--to", str(to_time),
"--query", request_id,
"--reverse", "true",
"--lines", "100",
"--region", region,
]
if profile:
cmd.extend(["--profile", profile])
try:
result = subprocess.run(cmd, capture_output=True, text=True, timeout=60)
if result.returncode == 0:
try:
logs = json.loads(result.stdout)
if logs and len(logs) > 0:
print(f"Found {len(logs)} log record(s)")
return logs
else:
print(f"No logs found in this time range")
except json.JSONDecodeError:
print(f"Failed to parse response")
print(f"Raw output: {result.stdout[:200]}")
else:
print(f"Query failed: {result.stderr[:200]}")
except subprocess.TimeoutExpired:
print(f"Query timed out")
except Exception as e:
print(f"Query error: {e}")
# Stop querying if maximum range is reached
if from_ts <= max_from_time:
break
print(f"\nRequest ID not found in any time range: {request_id}")
return []
def parse_log_entry(log):
"""Parse a single log entry and extract key information (with masking)"""
key_fields = {
'traceid': 'Request ID',
'request_traceid': 'Request ID',
'final_rule_id': 'Rule ID',
'final_plugin': 'Block Plugin',
'final_action': 'Action',
'cc_action': 'CC Action',
'cc_rule_id': 'CC Rule ID',
'cc_phase': 'CC Phase',
'cc_blocks': 'CC Blocks',
'last_owner': 'Last Owner',
'status': 'HTTP Status',
'upstream_status': 'Upstream Status',
'real_client_ip': 'Client IP',
'matched_host': 'Matched Host',
'host': 'Domain',
'request_uri': 'Request URI',
'request_method': 'Request Method',
'http_user_agent': 'User-Agent',
'time': 'Time',
}
parsed = {}
for key, label in key_fields.items():
if key in log:
parsed[label] = _mask_field_value(key, log[key])
return parsed
def determine_block_type(log):
"""Determine the block type from DDoS Pro log fields.
Returns a tuple of (block_type_label, phase_key) where phase_key
is one of: 'cc', 'gfacl', 'ai', 'global', 'blacklist', 'region', or 'unknown'.
"""
cc_phase = log.get('cc_phase', '')
cc_action = log.get('cc_action', '')
final_plugin = log.get('final_plugin', '')
# cc_phase mapping — actual DDoS Pro values all have 'gf' prefix
_PHASE_MAP = {
# CC protection (频率控制)
'cc': ('CC Protection (频率控制自定义规则)', 'cc'),
'gfcc': ('CC Protection (频率控制自定义规则)', 'cc'),
# Precise Access Control (精确访问控制 / ACL)
'gfacl': ('Precise Access Control (精确访问控制)', 'gfacl'),
'acl': ('Precise Access Control (精确访问控制)', 'gfacl'),
# AI Smart Protection (AI智能防护)
'ai': ('AI Smart Protection (AI智能防护)', 'ai'),
'gfai': ('AI Smart Protection (AI智能防护)', 'ai'),
# Global Defense Policy (全局防护策略)
'global': ('Global Defense Policy (全局防护策略)', 'global'),
'gfglobal': ('Global Defense Policy (全局防护策略)', 'global'),
'gf_rule': ('Global Defense Policy (全局防护策略)', 'global'),
# IP Blacklist (IP黑名单)
'blacklist': ('IP Blacklist (IP黑名单)', 'blacklist'),
'gfbwip': ('IP Blacklist (IP黑名单)', 'blacklist'),
# Region Blocking (区域封禁)
'region': ('Region Blocking (区域封禁)', 'region'),
'geo': ('Region Blocking (区域封禁)', 'region'),
'gfareaban': ('Region Blocking (区域封禁)', 'region'),
}
# Primary: exact match on cc_phase
if cc_phase in _PHASE_MAP:
return _PHASE_MAP[cc_phase]
# Fallback: match on cc_action / final_plugin
if cc_action in ('block', 'captcha') or log.get('cc_rule_id'):
return ('CC Protection (频率控制)', 'cc')
if 'precise' in final_plugin or 'acl' in final_plugin:
return ('Precise Access Control (精确访问控制)', 'gfacl')
if 'region' in final_plugin or 'geo' in final_plugin:
return ('Region Blocking (区域封禁)', 'region')
if 'blacklist' in final_plugin or 'ip' in final_plugin:
return ('IP Blacklist (IP黑名单)', 'blacklist')
if 'ai' in final_plugin:
return ('AI Smart Protection (AI智能防护)', 'ai')
if final_plugin:
return (f'Other ({final_plugin})', 'unknown')
return ('Unknown', 'unknown')
def _get_rule_query_commands(log, phase_key, region='cn-hangzhou'):
"""Generate CLI commands for querying ALL policy types for the domain.
The matched policy type (based on phase_key) is marked with [MATCHED].
Returns a list of (description, command, is_matched) tuples.
"""
domain = log.get('matched_host') or log.get('host', '<domain>')
last_owner = log.get('last_owner', '')
rule_name = last_owner.split('|')[0] if '|' in last_owner else last_owner
owner = 'manual'
if '|' in last_owner:
owner = last_owner.split('|')[1]
# All policy query commands: (phase_key, description, command)
all_policies = [
('_switch',
"All protection switch status (策略预检)",
f"aliyun ddoscoo describe-web-cc-protect-switch --domains.1 '{domain}' --region {region}"),
('cc',
f"CC protection rules (频率控制) [Owner={owner}]",
f"aliyun ddoscoo describe-web-cc-rules-v2 --domain '{domain}' --offset 0 --page-size 30 --owner {owner} --region {region}"),
('gfacl',
"Precise Access Control rules (精确访问控制/ACL)",
f"aliyun ddoscoo describe-web-precise-access-rule --domains.1 '{domain}' --region {region}"),
('ai',
"AI Smart Protection status (AI智能防护)",
f"aliyun ddoscoo describe-web-cc-protect-switch --domains.1 '{domain}' --region {region}"),
('global',
"Global Defense Policy rules (全局防护策略)",
f"aliyun ddoscoo describe-l7-global-rule --domain '{domain}' --region {region}"),
('blacklist',
"IP Blacklist/Whitelist (IP黑白名单)",
f"aliyun ddoscoo describe-web-rules --domain '{domain}' --region {region}"),
('region',
"Region Blocking config (区域封禁)",
f"aliyun ddoscoo describe-web-area-block-configs --domains.1 '{domain}' --region {region}"),
]
commands = []
for policy_key, desc, cmd in all_policies:
is_matched = (policy_key == phase_key)
if is_matched and rule_name:
desc = f"{desc} → rule '{rule_name}'"
commands.append((desc, cmd, is_matched))
return commands
def print_log_analysis(logs, region='cn-hangzhou'):
"""Print log analysis results for DDoS Pro intercept events"""
if not logs:
return
print("\n" + "="*60)
print("DDoS Pro Intercept Analysis Report")
print("="*60)
for idx, log in enumerate(logs, 1):
parsed = parse_log_entry(log)
print(f"\n[Log Record {idx}]")
print("-"*60)
# Request information
print("\nRequest Information:")
for key in ['Request ID', 'Time', 'Client IP', 'Request Method',
'Domain', 'Matched Host', 'Request URI', 'User-Agent']:
if key in parsed:
print(f" {key}: {parsed[key]}")
# Block details
print("\nBlock Details:")
block_type_label, phase_key = determine_block_type(log)
print(f" Block Type: {block_type_label}")
# Parse last_owner for rule name and source
last_owner = log.get('last_owner', '')
if last_owner and '|' in last_owner:
rule_name, rule_source = last_owner.split('|', 1)
source_label = 'User-created' if rule_source == 'manual' else 'Auto-generated'
print(f" Matched Rule Name: {rule_name} ({source_label})")
for key in ['Rule ID', 'CC Rule ID', 'Block Plugin', 'Action',
'CC Action', 'CC Phase', 'HTTP Status', 'Upstream Status']:
if key in parsed:
print(f" {key}: {parsed[key]}")
# Raw log (optional, for single record)
if len(logs) == 1:
# Exclude already-displayed fields
_displayed = {
'request_traceid', 'final_rule_id', 'final_plugin', 'final_action',
'cc_action', 'cc_rule_id', 'cc_phase',
'status', 'upstream_status', 'real_client_ip', 'matched_host',
'host', 'request_uri', 'request_method',
'http_user_agent', 'time',
'__source__', '__time__', '__topic__',
}
print("\nFull Log Fields:")
for key, value in sorted(log.items()):
if key not in _displayed:
if _is_sensitive_field(key):
display_value = _mask_field_value(key, value)
else:
display_value = value if len(str(value)) < 50 else str(value)[:50] + "..."
print(f" {key}: {display_value}")
# Recommended rule query commands (based on first log record)
first_log = logs[0]
_, first_phase_key = determine_block_type(first_log)
rule_commands = _get_rule_query_commands(first_log, first_phase_key, region=region)
if rule_commands:
print("\nAll Policy Query Commands:")
print("-"*60)
for desc, cmd, is_matched in rule_commands:
marker = " [MATCHED]" if is_matched else ""
print(f"\n # {desc}{marker}")
print(f" {cmd}")
print("\n" + "="*60)
# ---------------------------------------------------------------------------
# Allowed Alibaba Cloud region IDs (non-exhaustive but covers all public regions)
_VALID_REGIONS = {
# China mainland
'cn-hangzhou', 'cn-shanghai', 'cn-beijing', 'cn-shenzhen', 'cn-zhangjiakou',
'cn-huhehaote', 'cn-wulanchabu', 'cn-chengdu', 'cn-qingdao', 'cn-guangzhou',
'cn-nanjing', 'cn-fuzhou', 'cn-heyuan',
# International
'ap-southeast-1', 'ap-southeast-2', 'ap-southeast-3', 'ap-southeast-5',
'ap-southeast-6', 'ap-southeast-7', 'ap-south-1', 'ap-northeast-1',
'ap-northeast-2', 'us-east-1', 'us-west-1', 'eu-west-1', 'eu-central-1',
'me-east-1', 'me-central-1',
# China Finance / Gov
'cn-hangzhou-finance', 'cn-shanghai-finance-1', 'cn-shenzhen-finance-1',
'cn-beijing-finance-1', 'cn-north-2-gov-1',
}
# Pattern: alphanumeric, hyphens, underscores (SLS project / logstore names)
_SLS_NAME_RE = re.compile(r'^[a-zA-Z0-9][a-zA-Z0-9_-]{0,127}$')
# Pattern: request trace ID — hex, alphanumeric, hyphens (e.g. UUIDs, trace IDs)
_REQUEST_ID_RE = re.compile(r'^[a-zA-Z0-9-]{1,128}$')
# Pattern: DDoS Pro instance ID (e.g. ddoscoo-cn-xxx)
_INSTANCE_ID_RE = re.compile(r'^[a-zA-Z0-9_-]{1,128}$')
def _validate_sls_name(value, label):
"""Validate SLS project / logstore name format."""
if not _SLS_NAME_RE.match(value):
raise argparse.ArgumentTypeError(
f"Invalid {label}: '{value}'. "
f"Must start with alphanumeric and contain only [a-zA-Z0-9_-], max 128 chars."
)
return value
def _validate_request_id(value):
"""Validate request ID format (alphanumeric + hyphens)."""
if not _REQUEST_ID_RE.match(value):
raise argparse.ArgumentTypeError(
f"Invalid request ID: '{value}'. "
f"Must contain only [a-zA-Z0-9-], max 128 chars."
)
return value
def _validate_region(value):
"""Validate region is a known Alibaba Cloud region ID."""
if value not in _VALID_REGIONS:
raise argparse.ArgumentTypeError(
f"Invalid region: '{value}'. "
f"Must be a valid Alibaba Cloud region ID (e.g. cn-hangzhou, ap-southeast-1)."
)
return value
def _validate_instance_id(value):
"""Validate DDoS Pro instance ID format."""
if not _INSTANCE_ID_RE.match(value):
raise argparse.ArgumentTypeError(
f"Invalid instance ID: '{value}'. "
f"Must contain only [a-zA-Z0-9_-], max 128 chars."
)
return value
def _validate_ttl(value):
"""Validate TTL is a positive integer within a reasonable range."""
try:
ivalue = int(value)
except (ValueError, TypeError):
raise argparse.ArgumentTypeError(f"Invalid TTL: '{value}'. Must be a positive integer.")
if ivalue < 1 or ivalue > 3650:
raise argparse.ArgumentTypeError(
f"TTL out of range: {ivalue}. Must be between 1 and 3650 days."
)
return ivalue
def main():
parser = argparse.ArgumentParser(description='Query DDoS Pro SLS full logs for intercept/block events')
parser.add_argument('--project', required=True,
type=lambda v: _validate_sls_name(v, 'project'),
help='SLS Project name')
parser.add_argument('--logstore', required=True,
type=lambda v: _validate_sls_name(v, 'logstore'),
help='SLS Logstore name')
parser.add_argument('--request-id', required=True,
type=_validate_request_id,
help='Request ID (traceid) to query')
parser.add_argument('--region', default='cn-hangzhou',
type=_validate_region,
help='SLS region (default: cn-hangzhou)')
parser.add_argument('--ttl', type=_validate_ttl, default=90,
help='Log retention period in days (default: 90, max: 3650)')
parser.add_argument('--json', action='store_true', help='Output raw logs in JSON format')
parser.add_argument('--instance-id',
type=_validate_instance_id,
help='DDoS Pro instance ID (for reference)')
parser.add_argument('--profile',
help='Aliyun CLI profile name (e.g. default, china, intl)')
args = parser.parse_args()
print("="*60)
print("DDoS Pro SLS Full Log Query")
print("="*60)
print(f"Project: {args.project}")
print(f"Logstore: {args.logstore}")
print(f"Request ID: {args.request_id}")
print(f"Region: {args.region}")
print(f"Current timestamp: {get_current_timestamp()} ({time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(get_current_timestamp()))})")
# Query logs
if args.profile:
print(f"Profile: {args.profile}")
# Query logs
logs = query_sls_logs(args.project, args.logstore, args.request_id, args.region, args.ttl, profile=args.profile)
if logs:
if args.json:
# JSON format output — mask sensitive fields before emitting
sanitized_logs = []
for log in logs:
sanitized = {}
for k, v in log.items():
if _is_sensitive_field(k):
sanitized[k] = _mask_field_value(k, v)
elif k.lower() in ('request_uri', 'uri', 'querystring', 'query_string'):
sanitized[k] = _mask_uri(str(v))
else:
sanitized[k] = v
sanitized_logs.append(sanitized)
print("\n" + json.dumps(sanitized_logs, indent=2, ensure_ascii=False))
else:
# Analysis format output
print_log_analysis(logs, region=args.region)
return 0
else:
print("\nSuggestions:")
print(" 1. Verify the Request ID is correct")
print(" 2. Confirm that full log is enabled for the domain")
print(" 3. Wait 3-5 minutes and retry (log sync delay)")
return 1
if __name__ == '__main__':
sys.exit(main())