
Alibabacloud Dsc Audit
- 142 installs
- 208 repo stars
- Updated August 4, 2026
- aliyun/alibabacloud-aiops-skills
Run Data Security Center audits to assess data classification, sensitive exposure, encryption posture, and compliance gaps before or after production release.
About
Security skill for Alibaba Cloud Data Security Center audits: evaluate data assets for sensitivity, encryption, access risk, and regulatory alignment, prioritize findings, and plan remediation before shipping or during compliance reviews.
- Triggers DSC compliance scans
- Interprets sensitive data findings
- Maps risks to remediation actions
- Tracks encryption and masking gaps
- Supports audit evidence collection
Alibabacloud Dsc Audit by the numbers
- 142 all-time installs (skills.sh)
- Ranked #909 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-dsc-auditAdd your badge
Show developers this skill is listed on Skillselion. Paste this into your README.
| Installs | 142 |
|---|---|
| repo stars | ★ 208 |
| Last updated | August 4, 2026 |
| Repository | aliyun/alibabacloud-aiops-skills ↗ |
What it does
Run Data Security Center audits to assess data classification, sensitive exposure, encryption posture, and compliance gaps before or after production release.
Files
Alibaba Cloud Data Security Center Risk Event Query and Handling
This skill uses Alibaba Cloud Python Common SDK (generic invocation) to query security risk events from the Data Security Center and handle them.
Architecture
User → Python Common SDK → Data Security Center (Sddp) API
├── DescribeRiskRules (Query risk events)
└── PreHandleAuditRisk (Handle risk events)Installation
pip3 install -r scripts/requirements.txtOr install packages individually:
pip3 install alibabacloud_tea_openapi==0.4.3 alibabacloud_credentials==1.0.8 alibabacloud_tea_util==0.3.14 alibabacloud_openapi_util==0.2.4[MUST] CLI User-Agent — Every aliyun CLI command invocation must include: --user-agent AlibabaCloud-Agent-Skills/alibabacloud-dsc-audit
Pre-check: Aliyun CLI >= 3.3.3 required
Run aliyun version to verify >= 3.3.3. If not installed or version too low,run curl -fsSL https://aliyuncli.alicdn.com/setup.sh | bash to update,or 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.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:
aliyun configure ai-mode enable
aliyun configure ai-mode set-user-agent --user-agent "AlibabaCloud-Agent-Skills/alibabacloud-dsc-audit"[MUST] Disable AI-Mode at EVERY exit point — Before delivering the final response for ANY reason, always disable AI-mode first. This applies to ALL exit paths: workflow success, workflow failure, error/exception, user cancellation, session end, or any other scenario where no further CLI commands will be executed. AI-mode is only used for Agent Skill invocation scenarios and MUST NOT remain enabled after the skill stops running.
aliyun configure ai-mode disableAuthentication
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 profileRAM Permissions
Before using this skill, ensure the current user has the required RAM permissions. For detailed permission lists and policy configurations, refer to references/ram-policies.md
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 | Required/Optional | Description | Default |
|---|---|---|---|
CurrentPage | Optional | Current page number | 1 |
PageSize | Optional | Records per page | 10 |
HandleStatus | Optional | Processing status, PROCESSED means handled, UNPROCESSED means not handled | UNPROCESSED |
RiskId | Required for handling | Risk event ID | - |
HandleDetail | Required for handling | Handling details description | - |
Core Workflow
Step 1: Query Unprocessed Security Risk Events
Use the scripts/query_risk.py script to query unprocessed security risk events. This is a paginated API that returns the first 20 records by default.
python3 scripts/query_risk.pyExample output:
Found 31 unprocessed security risk events
================================================================================
Risk ID: 75110196
Rule Name: jiangyu_test_mysqldump
Risk Level: High Risk
Product Type: RDS
Alert Count: 20
Asset Count: 2
Rule Category: Database Dump Attack
--------------------------------------------------------------------------------Query Result Field Descriptions
The query results return the following key fields. Risk Event ID (RiskId) is a required parameter for handling:
| Field | Description |
|---|---|
| RiskId | Risk event ID, required for handling |
| RuleName | Rule name |
| WarnLevelName | Risk level (High Risk/Medium Risk/Low Risk) |
| ProductCode | Product type (RDS/OSS, etc.) |
| AlarmCount | Alert count |
| InstanceCount | Number of affected assets |
| FirstAlarmTime | First discovery time |
| LastAlarmTime | Last discovery time |
Step 2: Handle Security Risk Events
Use the scripts/handle_risk.py script to handle specified risk events.
python3 scripts/handle_risk.py <RiskID> <HandleDetail>Example:
python3 scripts/handle_risk.py 75110196 "Confirmed as false positive, closing this alert"Example output:
Handling risk event...
Risk ID: 75110196
Handle Detail: Confirmed as false positive, closing this alert
--------------------------------------------------
✅ Handling successful!
RequestId: C34D813F-A234-5D66-842D-504D84D5C680Handling Parameter Descriptions
| Parameter | Description |
|---|---|
RiskId | Risk event ID, obtained from DescribeRiskRules API |
HandleType | Handling type, fixed as Manual (manual handling) |
HandleMethod | Handling method, fixed as 0 |
HandleDetail | Handling details, requires user to input specific handling description |
Success Verification
Verify Query Operation
1. After executing the query code, check if the returned statusCode is 200 2. Check if the returned body contains the Items list 3. Verify that TotalCount matches the actual number of returned records
Verify Handling Operation
1. After executing the handling code, check if the returned statusCode is 200 2. Call DescribeRiskRules again to query the RiskId and confirm the status has changed
Cleanup
This skill is primarily used for query and handling operations, does not involve resource creation, and requires no cleanup.
API and Command Reference
| Product | API Action | Script | Description |
|---|---|---|---|
| Sddp | DescribeRiskRules | scripts/query_risk.py | Query security risk events |
| Sddp | PreHandleAuditRisk | scripts/handle_risk.py | Handle security risk events |
Script Usage
| Script | Usage | Description |
|---|---|---|
query_risk.py | python3 scripts/query_risk.py | Execute directly, no parameters required |
handle_risk.py | python3 scripts/handle_risk.py <RiskID> <HandleDetail> | Requires Risk ID and handling description |
For detailed API information, refer to references/related-apis.md
Best Practices
1. Paginated Query: When using paginated APIs, increment the CurrentPage parameter until all records are retrieved 2. Record RiskId: The RiskId in query results is a required parameter for handling operations, make sure to record it 3. Handle Description: Provide a clear HandleDetail description when handling for subsequent auditing 4. Error Handling: Implement retry mechanisms for temporary errors like Throttling 5. Credential Security: Use CredentialClient to manage credentials, do not hardcode AK/SK
Reference Links
| Reference Document | Description |
|---|---|
| references/related-apis.md | API detailed documentation |
| references/ram-policies.md | RAM permission configuration |
| references/cli-installation-guide.md | CLI installation guide |
| references/acceptance-criteria.md | Acceptance criteria |
| Generic Invocation Documentation | Alibaba Cloud Python SDK generic invocation documentation |
Important Notes
Warning: This skill only uses the Data Security Center'sDescribeRiskRulesandPreHandleAuditRiskAPIs.
If these two APIs cannot be found, report an error. Do NOT call other OpenAPIs without authorization.
Do not use Alibaba Cloud CLI tools to call APIs.
Acceptance Criteria: alibabacloud-dsc-audit
Scenario: Data Security Center Security Risk Event Query and Handling Purpose: Skill test acceptance criteria
---
Correct Common SDK Code Patterns
1. Import Pattern
✅ CORRECT
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient # Required for RPC style❌ INCORRECT
# Error: Using legacy SDK
from aliyunsdkcore.client import AcsClient
from aliyunsdksddp.request.v20190103 import DescribeRiskRulesRequest
# Error: Missing OpenApiUtilClient (required for RPC style)
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
# Missing OpenApiUtilClient2. Authentication Pattern
✅ CORRECT
# Use CredentialClient, do not hardcode AK/SK
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'sddp.cn-zhangjiakou.aliyuncs.com'
client = OpenApiClient(config)❌ INCORRECT
# Error: Hardcoded AK/SK
config = open_api_models.Config(
access_key_id='LTAI5tXXXXXXXX',
access_key_secret='8dXXXXXXXXXXXXXXXXXXXXXXXX'
)
# Error: Using string instead of CredentialClient
config = open_api_models.Config(credential='my-credential')3. API Parameter Configuration (RPC Style)
✅ CORRECT
params = open_api_models.Params(
action='DescribeRiskRules',
version='2019-01-03',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='RPC',
pathname='/', # Fixed as '/' for RPC style
req_body_type='json',
body_type='json'
)❌ INCORRECT
# Error: RPC style using custom pathname
params = open_api_models.Params(
action='DescribeRiskRules',
version='2019-01-03',
style='RPC',
pathname='/risk/rules', # RPC style should be '/'
)
# Error: Using ROA style
params = open_api_models.Params(
action='DescribeRiskRules',
version='2019-01-03',
style='ROA', # Should be RPC
)4. Request Building (RPC Style)
✅ CORRECT
# RPC style uses query parameters, must use OpenApiUtilClient.query()
queries = {
'CurrentPage': 1,
'PageSize': 10,
'HandleStatus': 'UNPROCESSED'
}
request = open_api_models.OpenApiRequest(
query=OpenApiUtilClient.query(queries)
)❌ INCORRECT
# Error: RPC style using body parameters
request = open_api_models.OpenApiRequest(
body={'CurrentPage': 1, 'PageSize': 10}
)
# Error: Not using OpenApiUtilClient.query()
request = open_api_models.OpenApiRequest(
query={'CurrentPage': 1, 'PageSize': 10}
)5. Complex Parameter Handling (Flat Mode)
✅ CORRECT
# Use flat mode for complex objects
queries = {
'RiskId': 75110196,
'HandleInfoList.1.HandleType': 'Manual',
'HandleInfoList.1.HandleContent': json.dumps({
'HandleMethod': 0,
'HandleDetail': 'Handling description'
})
}❌ INCORRECT
# Error: Directly passing nested objects
queries = {
'RiskId': 75110196,
'HandleInfoList': [
{
'HandleType': 'Manual',
'HandleContent': {
'HandleMethod': 0,
'HandleDetail': 'Handling description'
}
}
]
}6. API Call
✅ CORRECT
runtime = util_models.RuntimeOptions()
response = client.call_api(params, request, runtime)
# Check response
status_code = response.get('statusCode')
body = response.get('body')
if status_code == 200:
items = body.get('Items', [])❌ INCORRECT
# Error: Missing runtime options
response = client.call_api(params, request)
# Error: Not checking status code
body = response.get('body')
items = body['Items'] # May throw KeyError---
Service Configuration Validation
✅ CORRECT
| Configuration | Correct Value |
|---|---|
| Product Code | Sddp |
| Endpoint | sddp.cn-zhangjiakou.aliyuncs.com |
| API Version | 2019-01-03 |
| API Style | RPC |
❌ INCORRECT
| Error Case | Description |
|---|---|
| Wrong endpoint | Using sddp.aliyuncs.com instead of sddp.cn-zhangjiakou.aliyuncs.com |
| Wrong version | Using incorrect version number |
| Wrong style | Using ROA instead of RPC |
---
API Restriction Validation
✅ CORRECT
This skill only uses the following two APIs:
DescribeRiskRules- Query security risk eventsPreHandleAuditRisk- Handle security risk events
❌ INCORRECT
Calling other unauthorized APIs:
DescribeDataAssetsDescribeRules- Any other Data Security Center APIs
---
Pagination Query Validation
✅ CORRECT
def fetch_all_risk_rules():
all_items = []
current_page = 1
while True:
response = describe_risk_rules(current_page)
body = response.get('body', {})
items = body.get('Items', [])
all_items.extend(items)
total_count = body.get('TotalCount', 0)
if current_page * page_size >= total_count:
break
current_page += 1
return all_items❌ INCORRECT
# Error: Only fetching first page, ignoring subsequent pages
def fetch_risk_rules():
response = describe_risk_rules(current_page=1)
return response.get('body', {}).get('Items', [])---
Required Field Validation
Query Results Must Include RiskId
✅ CORRECT
for item in items:
risk_id = item.get('RiskId') # Must display
print(f"Risk ID: {risk_id}") # Required for handling❌ INCORRECT
# Error: Not displaying RiskId
for item in items:
print(f"Rule Name: {item.get('RuleName')}")
# Missing RiskId, user cannot perform handling operationsAliyun 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": "China (Hangzhou)"
},
...
]
},
"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
Data Security Center RAM Permission Configuration
Required Permissions List
Using this skill requires the following RAM permissions:
| API | RAM Permission | Description |
|---|---|---|
| DescribeRiskRules | yundun-sddp:DescribeRiskRules | Query security risk events |
| PreHandleAuditRisk | yundun-sddp:PreHandleAuditRisk | Handle security risk events |
Custom Policy Examples
Minimum Privilege Policy (Recommended)
Grant only the minimum permissions required for this skill:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"yundun-sddp:DescribeRiskRules",
"yundun-sddp:PreHandleAuditRisk"
],
"Resource": "*"
}
]
}Read-Only Query Policy
Allow only querying risk events, no handling:
{
"Version": "1",
"Statement": [
{
"Effect": "Allow",
"Action": [
"yundun-sddp:DescribeRiskRules"
],
"Resource": "*"
}
]
}Configuration Steps
1. Log in to RAM Console 2. Navigate to Permission Management > Permission Policies 3. Click Create Permission Policy 4. Select Script Edit mode 5. Paste the policy content above 6. Name the policy (e.g., DSCAuditPolicy) 7. Attach the policy to the RAM user or role that needs to use this skill
Permission Verification
Run the following command to verify the current user has the required permissions:
# Test query permission using aliyun CLI
aliyun sddp DescribeRiskRules --region cn-zhangjiakou --CurrentPage 1 --PageSize 1If results are returned instead of a permission error, the query permission is granted.
Important Notes
1. Principle of Least Privilege: Grant only the permissions actually needed for this skill 2. Permission Separation: Query and handling permissions can be granted separately to different roles 3. Audit Trail: RAM operations are recorded in ActionTrail for security auditing 4. Regular Review: Periodically check permission configurations and remove permissions that are no longer needed
Data Security Center API Reference
Service Configuration
| Configuration | Value |
|---|---|
| Product Code | Sddp |
| Endpoint | sddp.cn-zhangjiakou.aliyuncs.com |
| API Version | 2019-01-03 |
| API Style | RPC |
API List
| API Name | Description | Method |
|---|---|---|
| DescribeRiskRules | Query security risk events | POST |
| PreHandleAuditRisk | Handle security risk events | POST |
---
DescribeRiskRules - Query Security Risk Events
API Description
Paginated query of security risk event list from the Data Security Center. Increment the CurrentPage parameter to retrieve all risk events.
Request Parameters
| Parameter | Type | Required | Description | Default |
|---|---|---|---|---|
| CurrentPage | Integer | No | Current page number | 1 |
| PageSize | Integer | No | Records per page | 10 |
| HandleStatus | String | No | Processing status | UNPROCESSED |
HandleStatus Enum Values
| Value | Description |
|---|---|
| UNPROCESSED | Not processed |
| PROCESSED | Processed |
Request Example
{
"CurrentPage": 1,
"PageSize": 10,
"HandleStatus": "UNPROCESSED"
}Response Parameters
| Parameter | Type | Description |
|---|---|---|
| TotalCount | Integer | Total number of risk events |
| PageSize | Integer | Records per page |
| CurrentPage | Integer | Current page number |
| Items | Array | Risk event list |
Items Array Element Structure
| Field | Type | Description |
|---|---|---|
| RiskId | Long | Risk event ID, must use this ID for handling |
| RuleName | String | Rule name |
| RuleId | Long | Rule ID |
| WarnLevel | Integer | Risk level value |
| WarnLevelName | String | Risk level name (High Risk/Medium Risk/Low Risk) |
| ProductCode | String | Product type (RDS/OSS, etc.) |
| AlarmCount | Integer | Alert count |
| InstanceCount | Integer | Number of affected assets |
| ClientIpCount | Integer | Number of client IPs |
| FirstAlarmTime | Long | First discovery time (timestamp) |
| LastAlarmTime | Long | Last discovery time (timestamp) |
| HandleStatus | String | Processing status |
| RuleCategoryName | String | Rule category name |
Response Example
{
"code": 200,
"data": {
"TotalCount": 1,
"PageSize": 10,
"CurrentPage": 1,
"Items": [
{
"RiskId": 75110196,
"ClientIpCount": 2,
"FirstAlarmTime": 1772075549000,
"ProductCode": "RDS",
"RuleId": 9953728,
"RuleCategoryId": 11,
"TotalInstanceCount": 2,
"LastAlarmTime": 1773387801000,
"AlarmSource": "DSC",
"AlertFrequency": "1/day",
"InstanceCount": 2,
"WarnLevel": 3,
"SupportAi": false,
"HandleMarkTime": 0,
"HandleStatus": "UNPROCESSED",
"TotalUserNameCount": 4,
"RuleCategoryName": "Database Dump Attack",
"TotalAlarmCount": 18,
"TotalClientIpCount": 2,
"UserNameCount": 4,
"WarnLevelName": "High Risk",
"RuleName": "jiangyu_test_mysqldump",
"AlarmCount": 18
}
]
},
"requestId": "95755da3-6dcf-4978-a693-0dcf270da272",
"success": true
}---
PreHandleAuditRisk - Handle Security Risk Events
API Description
Perform handling operations on specified security risk events.
Request Parameters
| Parameter | Type | Required | Description |
|---|---|---|---|
| RiskId | Long | Yes | Risk event ID, obtained from DescribeRiskRules API |
| HandleInfoList | Array | Yes | Handling method list |
HandleInfoList Structure
| Field | Type | Required | Description |
|---|---|---|---|
| HandleType | String | Yes | Handling type, fixed as Manual (manual handling) |
| HandleContent | Object | Yes | Handling content |
HandleContent Structure
| Field | Type | Required | Description |
|---|---|---|---|
| HandleMethod | Integer | Yes | Handling method, fixed as 0 |
| HandleDetail | String | Yes | Handling details, requires user to input specific description |
Request Example (Original Format)
{
"RiskId": 75110196,
"HandleInfoList": [
{
"HandleType": "Manual",
"HandleContent": {
"HandleMethod": 0,
"HandleDetail": "Confirmed as false positive, closing this alert"
}
}
]
}Request Example (Flat Mode - SDK Usage)
In RPC-style APIs, complex objects need to be converted to flat mode:
{
"RiskId": 75110196,
"HandleInfoList.1.HandleType": "Manual",
"HandleInfoList.1.HandleContent": "{\"HandleMethod\": 0, \"HandleDetail\": \"Confirmed as false positive, closing this alert\"}"
}Response Parameters
| Parameter | Type | Description |
|---|---|---|
| RequestId | String | Request ID |
| Success | Boolean | Whether the operation was successful |
Response Example
{
"RequestId": "a1b2c3d4-e5f6-7890-abcd-ef1234567890",
"Success": true
}---
Error Codes
| Error Code | Description | Solution |
|---|---|---|
| InvalidParameter | Invalid parameter | Check parameter format and constraints |
| MissingParameter | Missing required parameter | Add required parameters |
| Forbidden | Access denied | Check RAM permissions |
| Throttling | Request rate exceeded | Implement retry with backoff |
| ServiceUnavailable | Service temporarily unavailable | Retry after delay |
| InternalError | Internal service error | Contact technical support with RequestId |
# -*- coding: utf-8 -*-
import json
import re
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
# Constants
RISK_ID_MIN = 1
RISK_ID_MAX = 2 ** 63 - 1 # Alibaba Cloud IDs are typically 64-bit integers
HANDLE_DETAIL_MAX_LENGTH = 500
# Allowed characters: Chinese, English, numbers, common punctuation
HANDLE_DETAIL_PATTERN = re.compile(r'^[\u4e00-\u9fa5a-zA-Z0-9\s,。、;:""''!?()\-_,.;:!?()\[\]]+$')
# Timeout configuration (milliseconds)
CONNECT_TIMEOUT_MS = 10000 # Connection timeout 10 seconds
READ_TIMEOUT_MS = 30000 # Read timeout 30 seconds
def create_runtime_options():
"""Create RuntimeOptions with timeout configuration"""
runtime = util_models.RuntimeOptions()
runtime.connect_timeout = CONNECT_TIMEOUT_MS
runtime.read_timeout = READ_TIMEOUT_MS
return runtime
def validate_risk_id(risk_id_str):
"""
Validate risk_id parameter
- Must be a valid positive integer format
- Must be within valid range
Returns: (is_valid, risk_id_int_or_error_msg)
"""
# Format validation: must be numeric only
if not risk_id_str or not risk_id_str.strip().isdigit():
return False, "risk_id must be a positive integer"
try:
risk_id = int(risk_id_str.strip())
except ValueError:
return False, "risk_id conversion failed, please enter a valid integer"
# Range validation
if risk_id < RISK_ID_MIN or risk_id > RISK_ID_MAX:
return False, f"risk_id is out of valid range ({RISK_ID_MIN} - {RISK_ID_MAX})"
return True, risk_id
def validate_handle_detail(handle_detail):
"""
Validate handle_detail parameter
- Length limit
- Special character filtering (prevent command injection)
Returns: (is_valid, sanitized_detail_or_error_msg)
"""
if not handle_detail or not handle_detail.strip():
return False, "handle_detail cannot be empty"
detail = handle_detail.strip()
# Length validation
if len(detail) > HANDLE_DETAIL_MAX_LENGTH:
return False, f"handle_detail length cannot exceed {HANDLE_DETAIL_MAX_LENGTH} characters"
# Special character validation (prevent command injection)
if not HANDLE_DETAIL_PATTERN.match(detail):
return False, "handle_detail contains invalid characters, only Chinese, English, numbers and common punctuation are allowed"
return True, detail
def create_client():
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'sddp.cn-zhangjiakou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills/alibabacloud-dsc-audit'
return OpenApiClient(config)
def describe_risk_rules(current_page=1, page_size=20):
"""Query unprocessed security risk events"""
client = create_client()
params = open_api_models.Params(
action='DescribeRiskRules',
version='2019-01-03',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='RPC',
pathname='/',
req_body_type='json',
body_type='json'
)
queries = {
'CurrentPage': current_page,
'PageSize': page_size,
'HandleStatus': 'UNPROCESSED'
}
request = open_api_models.OpenApiRequest(query=OpenApiUtilClient.query(queries))
runtime = create_runtime_options()
return client.call_api(params, request, runtime)
def find_risk_in_unprocessed(risk_id):
"""Find specified RiskId in unprocessed risk events list, supports pagination"""
current_page = 1
page_size = 50
while True:
response = describe_risk_rules(current_page, page_size)
status_code = response.get('statusCode')
body = response.get('body', {})
if status_code != 200:
return False
items = body.get('Items', [])
total_count = body.get('TotalCount', 0)
# Search for target RiskId in current page
for item in items:
if item.get('RiskId') == risk_id:
return True
# Check if there are more pages
if current_page * page_size >= total_count:
break
current_page += 1
return False
def handle_audit_risk(risk_id, handle_detail):
"""Handle security risk event"""
client = create_client()
params = open_api_models.Params(
action='PreHandleAuditRisk',
version='2019-01-03',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='RPC',
pathname='/',
req_body_type='json',
body_type='json'
)
# Use flat mode for complex objects
queries = {
'RiskId': risk_id,
'HandleInfoList.1.HandleType': 'Manual',
'HandleInfoList.1.HandleContent': json.dumps({
'HandleMethod': 0,
'HandleDetail': handle_detail
})
}
request = open_api_models.OpenApiRequest(query=OpenApiUtilClient.query(queries))
runtime = create_runtime_options()
return client.call_api(params, request, runtime)
if __name__ == '__main__':
import sys
if len(sys.argv) < 3:
print("Usage: python3 handle_risk.py <RiskID> <HandleDetail>")
print("Example: python3 handle_risk.py 66718695 'Confirmed as false positive, closing alert'")
sys.exit(1)
# Input validation
is_valid, result = validate_risk_id(sys.argv[1])
if not is_valid:
print(f"❌ Parameter error: {result}")
sys.exit(1)
risk_id = result
is_valid, result = validate_handle_detail(sys.argv[2])
if not is_valid:
print(f"❌ Parameter error: {result}")
sys.exit(1)
handle_detail = result
# Pre-handling validation: check if risk event exists in unprocessed list
print(f"Validating risk event...")
if not find_risk_in_unprocessed(risk_id):
print(f"❌ No handleable risk event found: RiskId={risk_id}")
sys.exit(1)
print(f"✓ Risk event confirmed to exist in unprocessed list")
print(f"Handling risk event...")
print(f"Risk ID: {risk_id}")
print(f"Handle Detail: {handle_detail}")
print("-" * 50)
response = handle_audit_risk(risk_id, handle_detail)
status_code = response.get('statusCode')
body = response.get('body', {})
if status_code == 200:
print("✅ Handling successful!")
print(f"RequestId: {body.get('RequestId')}")
else:
print(f"❌ Handling failed: {json.dumps(body, indent=2, ensure_ascii=False)}")
# -*- coding: utf-8 -*-
import json
from alibabacloud_tea_openapi.client import Client as OpenApiClient
from alibabacloud_credentials.client import Client as CredentialClient
from alibabacloud_tea_openapi import models as open_api_models
from alibabacloud_tea_util import models as util_models
from alibabacloud_openapi_util.client import Client as OpenApiUtilClient
# Timeout configuration (milliseconds)
CONNECT_TIMEOUT_MS = 10000 # Connection timeout 10 seconds
READ_TIMEOUT_MS = 30000 # Read timeout 30 seconds
def create_runtime_options():
"""Create RuntimeOptions with timeout configuration"""
runtime = util_models.RuntimeOptions()
runtime.connect_timeout = CONNECT_TIMEOUT_MS
runtime.read_timeout = READ_TIMEOUT_MS
return runtime
def create_client():
credential = CredentialClient()
config = open_api_models.Config(credential=credential)
config.endpoint = 'sddp.cn-zhangjiakou.aliyuncs.com'
config.user_agent = 'AlibabaCloud-Agent-Skills/alibabacloud-dsc-audit'
return OpenApiClient(config)
def describe_risk_rules(current_page=1, page_size=20, handle_status='UNPROCESSED'):
client = create_client()
params = open_api_models.Params(
action='DescribeRiskRules',
version='2019-01-03',
protocol='HTTPS',
method='POST',
auth_type='AK',
style='RPC',
pathname='/',
req_body_type='json',
body_type='json'
)
queries = {
'CurrentPage': current_page,
'PageSize': page_size,
'HandleStatus': handle_status
}
request = open_api_models.OpenApiRequest(query=OpenApiUtilClient.query(queries))
runtime = create_runtime_options()
return client.call_api(params, request, runtime)
if __name__ == '__main__':
response = describe_risk_rules()
status_code = response.get('statusCode')
body = response.get('body', {})
if status_code == 200:
total_count = body.get('TotalCount', 0)
items = body.get('Items', [])
print(f"Found {total_count} unprocessed security risk events")
print("=" * 80)
if items:
for item in items:
print(f"Risk ID: {item.get('RiskId')}")
print(f"Rule Name: {item.get('RuleName')}")
print(f"Risk Level: {item.get('WarnLevelName')}")
print(f"Product Type: {item.get('ProductCode')}")
print(f"Alert Count: {item.get('AlarmCount')}")
print(f"Asset Count: {item.get('InstanceCount')}")
print(f"Rule Category: {item.get('RuleCategoryName')}")
print("-" * 80)
else:
print("No unprocessed security risk events found")
else:
print(f"Query failed: {json.dumps(body, indent=2, ensure_ascii=False)}")
# Alibaba Cloud Python Common SDK dependencies
# Required for generic API invocation to Data Security Center (Sddp)
alibabacloud_tea_openapi==0.4.3
alibabacloud_credentials==1.0.8
alibabacloud_tea_util==0.3.14
alibabacloud_openapi_util==0.2.4