# rds-security

Part of **RDS**

<!-- intent-backlink:auto -->

> 💡 **Path Selection**: This skill is one implementation path for [Configure database security settings and access control](../../intent/rds-configure-security/SKILL.md). If you're unsure which path to take, check the routing skill first.

# ApsaraDB RDS Security

## Capabilities Overview

| Sub-capability | Calling Mode | Description |
|--------|----------|------|
| Manage Access Permissions | Synchronous | Configure RAM authorization and manage access permissions for RDS instances. |
| IP Whitelist | Synchronous | Modify and query IP address allowlists for instance access control. |
| SSL Encryption | Synchronous | Modify and query SSL encryption settings for secure connections. |
| VSwitch Details | Synchronous | Query details about vSwitches for network configuration. |
| Describe VSwitch Details | Synchronous | Retrieve information about VSwitches in the network configuration. |
| Manage Security Group Rules | Synchronous | Add and configure security group permissions for RDS instances. |
| Query DDoS Protection Info | Synchronous | Retrieve DDoS protection details and attack counts for RDS instances. |
| Manage VPCs | Synchronous | List and query available Virtual Private Clouds for RDS deployment. |
| Manage Security Group Configuration | Synchronous | Describe and modify the security group configuration of RDS instances. |
| Manage Whitelist Templates | Synchronous | Create, modify, and manage IP whitelist templates and their instance associations. |
| Manage IP Whitelists | Synchronous | Query and modify IP address whitelists for database access control. |
| Manage VPC and vSwitch | Synchronous | Describe available VPCs and vSwitches for network configuration. |
| Manage Security Groups | Synchronous | Add or authorize security group permissions for RDS instances. |
| Manage DDoS Protection | Synchronous | Query DDoS attack count and protection information for instances. |
| Describe VSwitches | Synchronous | Get information about available VSwitches in a VPC. |
| Add Security Group Rule | Synchronous | Create a new security group rule for RDS instances. |
| List VPCs | Synchronous | Retrieve a list of available Virtual Private Clouds. |
| Describe Instance IP Whitelist | Synchronous | Retrieve the IP whitelist configuration for a specific RDS instance. |
| Monitor DDoS Protection | Synchronous | Query DDoS attack counts and protection information for instances. |
| Configure Security Groups | Synchronous | Describe or modify security group configurations for RDS instances. |
| Query Network Infrastructure | Synchronous | Retrieve details about VPCs and vSwitches available for RDS instance deployment. |
| Get Column Encryption Config | Synchronous | Retrieve column-level encryption configuration for database security. |
| Enable TDE | Synchronous | Enable Transparent Data Encryption for RDS instances. |
| Connect to Encrypted RDS Instance | Synchronous | Use EncJDBC to connect to encrypted RDS instances. |
| Modify Column Encryption | Synchronous | Configure column-level encryption settings for enhanced data security. |
| Encrypt/Decrypt Column Data | Synchronous | Use EncDB SDK to encrypt and decrypt column data programmatically. |
| Connect to Always-Confidential Database | Synchronous | Use GoLang_EncMySQL to connect to always-confidential databases. |
| Disk Encryption Status | Synchronous | Query the status and key information of disk encryption. |

## API Calling Pattern

### Authentication
Use bearer token authentication with your Alibaba Cloud API key.

- Header format: `Authorization: Bearer <your_api_key>`
- Environment variable: `DASHSCOPE_API_KEY`

### Service Endpoint
APIs use a single base URL:

- Base URL: `https://rds.aliyuncs.com/`
- Common regions: cn-hangzhou, cn-shanghai, cn-beijing

### Synchronous API Pattern
All security APIs follow a synchronous request-response pattern:
1. Send an HTTP request to the API endpoint with required parameters
2. Include authentication header with your API key
3. Receive immediate JSON response with results or error details
4. Parse the response to extract relevant information

For operations that modify resources (like updating IP whitelists or security groups), the response typically includes a `RequestId` and sometimes a `TaskId` for tracking.

## Parameter Reference

### IP Whitelist Management

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| Action | String | true | | | The operation that you want to perform. Set the value to ModifySecurityIps. |
| DBInstanceId | String | true | | | The ID of the instance. |
| SecurityIps | String | true | | Maximum 1,000 entries per instance; valid formats: IP address (e.g., 10.23.XX.XX) or CIDR block (e.g., 10.23.XX.XX/24, where 24 is between 1-32) | The IP addresses and CIDR blocks that you want to include in the IP address allowlist. If the IP address allowlist contains more than one IP address or CIDR block, separate these IP addresses and CIDR blocks with commas (,). Each IP address or CIDR block in the IP address allowlist must be unique. |
| DBInstanceIPArrayName | String | false | Default | Maximum 200 IP address allowlists per instance | The name of the IP address allowlist that you want to modify. Default value: Default. |
| DBInstanceIPArrayAttribute | String | false | | | The attribute of the IP address allowlist. By default, this parameter is empty. |
| SecurityIPType | String | false | | Fixed value: IPv4 | The type of IP address in the IP address allowlist. |
| WhitelistNetworkType | String | false | MIX | Valid values: Classic, VPC, MIX | The network type of the IP address allowlist. |
| ModifyMode | String | false | Cover | Valid values: Cover, Append, Delete | The method that is used to modify the IP address allowlist. |
| FreshWhiteListReadins | String | false | | Applies only to ApsaraDB RDS for PostgreSQL instances; multiple instances separated by commas (,); required only if attached to read-only instances | The read-only instances to which you want to synchronize the IP address allowlist. |

### SSL Encryption Settings

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| Action | String | true | | | The operation that you want to perform. Set the value to ModifyDBInstanceSSL. |
| DBInstanceId | String | true | | | The ID of the instance. |
| ConnectionString | String | true | | | The internal or public endpoint for which the server certificate needs to be created or updated. |
| SSLEnabled | Integer | false | | one of: 0, 1 | Specifies whether to enable or disable SSL encryption. Valid values: 1 (enables SSL encryption), 0 (disables SSL encryption). |
| CAType | String | false | aliyun | one of: aliyun, custom | The type of the server certificate. This parameter is supported only when the instance runs PostgreSQL with standard SSDs or ESSDs. If SSLEnabled is set to 1, the default value is aliyun. |
| ServerCert | String | false | | | The content of the server certificate. This parameter is supported only when the instance runs PostgreSQL with standard SSDs or ESSDs. Required if CAType is set to custom. |
| ServerKey | String | false | | | The private key of the server certificate. This parameter is supported only when the instance runs PostgreSQL with standard SSDs or ESSDs. Required if CAType is set to custom. |
| ClientCAEnabled | Integer | false | | one of: 0, 1 | Specifies whether to enable the public key of the CA that issues client certificates. Supported only for PostgreSQL instances with standard or ESSDs. |
| ClientCACert | String | false | | | The public key of the CA that issues client certificates. Required if ClientCAEnabled is set to 1. |
| ClientCrlEnabled | Integer | false | | one of: 0, 1 | Specifies whether to enable a certificate revocation list (CRL) that contains revoked client certificates. Available only when ClientCAEnabled is enabled. |
| ClientCertRevocationList | String | false | | | The CRL that contains revoked client certificates. Required if ClientCrlEnabled is set to 1. |
| ACL | String | false | | one of: cert, perfer, verify-ca, verify-full (only for PostgreSQL 12+) | The method used to verify the identities of clients. Supported only when ClientCAEnabled is enabled. |
| ReplicationACL | String | false | | one of: cert, perfer, verify-ca, verify-full (only for PostgreSQL 12+) | The method used to verify replication permission. Supported only when ClientCAEnabled is enabled. |

### Security Group Rules

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| DBInstanceId | String | true | | | The ID of the instance. You can call the DescribeDBInstances operation to query the IDs of instances. |
| PortRange | String | true | | range 1-65535, format: start_port/end_port | The range of destination ports over which TCP and UDP traffic is allowed in the security group rule. Valid values: 1 to 65535. Separate the start port number and the end port number with a forward slash (/). Example: 1/200. |
| IpProtocol | String | false | | one of: TCP, UDP | The type of the transport layer protocol. Valid values: TCP, UDP. |
| SourceCidrIp | String | false | | | The range of source IP addresses. CIDR blocks and IPv4 addresses are supported. |
| Description | String | false | | | The description of the security group rule. |

### DDoS Protection Monitoring

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| RegionId | String | false | | | The ID of the region in which the RDS Custom instance resides. |
| InstanceType | String | false | | must be 'ecs' | The type of the asset that is assigned a public IP address. Fixed value: ecs. |
| DdosRegionId | String | false | | | The region ID of the asset. |

### Column Encryption Configuration

| Parameter | Type | Required | Default | Constraints | Description |
|------|------|------|--------|------|------|
| DBInstanceId | String | true | | | The DB instance ID. |
| MEK | String | true | | 32-character hexadecimal string (16 bytes) | The master encryption key (MEK) that you generate and manage. Valid value: a 32-character hexadecimal string (16 bytes). |
| ENC_ALGO | String | false | SM4_128_GCM | One of: AES_128_GCM, AES_128_CTR, AES_128_CBC, AES_128_ECB (not recommended), SM4_128_GCM (default), SM4_128_CTR, SM4_128_CBC, SM4_128_ECB (not recommended) | The encryption algorithm. Default: SM4_128_GCM. |

## Code Examples

### Query IP Address Whitelists - Python - all

```python
import requests

url = 'https://rds.aliyuncs.com/'
params = {
    'Action': 'DescribeDBInstanceIPArrayList',
    'DBInstanceId': 'rm-uf6wjk5xxxxxxx',
    'Version': '2014-08-15'
}
headers = {
    'Authorization': 'Bearer <your-access-token>'
}

response = requests.get(url, params=params, headers=headers)
print(response.json())
```

### Modify IP Address Allowlist - Bash - all

```bash
curl -X GET 'https://rds.aliyuncs.com/?Action=DescribeDBInstanceIPArrayList&DBInstanceId=rm-uf6wjk5xxxxxxx&<Common request parameters>' \
-H 'Authorization: Bearer <your-access-token>'
```

### Connect to Encrypted RDS Instance with EncJDBC - Java - all

```java
// Replace the placeholders with your instance connection details.
String hostname = "hostname";
String port     = "port";
String dbname   = "db";
String username = "user";
String password = "password";

// Use a strong, randomly generated MEK in production.
String mek     = "00112233445566778899aabbccddeeff";
String encAlgo = "SM4_128_CBC";

Properties props = new Properties();
props.setProperty("user", username);
props.setProperty("password", password);
props.setProperty("MEK", mek);
props.setProperty("ENC_ALGO", encAlgo);

String dbUrl = String.format("jdbc:mysql:encdb://%s:%s/%s", hostname, port, dbname);
Class.forName("com.aliyun.encdb.mysql.jdbc.EncDriver");
Connection connection = DriverManager.getConnection(dbUrl, props);

int[]    intData = {1, 2, 3, 4, 5, 6};
String[] strData = {"abc", "bcd", "1", "def", "efg", "fgi"};

// Create the table.
connection.createStatement().executeUpdate("drop table if exists test");
connection.createStatement().executeUpdate("create table test (a int, b text)");

// Insert rows using PreparedStatement.
// EncJDBC automatically encrypts values targeting encrypted columns.
for (int i = 0; i < 6; i++) {
    PreparedStatement pstmt = connection.prepareStatement("insert into test values (?,?)");
    pstmt.setInt(1, intData[i]);
    pstmt.setString(2, strData[i]);
    pstmt.executeUpdate();
}

// Query rows. EncJDBC automatically decrypts results before returning them.
ResultSet rs = connection.createStatement().executeQuery("select * from test");
while (rs.next()) {
    for (int i = 0; i < rs.getMetaData().getColumnCount(); i++) {
        System.out.print(rs.getString(i + 1));
        System.out.print("\t");
    }
    System.out.print("\n");
}
```

### Connect to Always-Confidential Database with GoLang - Go - all

```go
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/aliyun/alibabacloud-encdb-mysql-go-client"
)

func main() {
    // Replace the placeholders with your actual connection information.
    db, err := sql.Open("encmysql", "<username>:<password>@tcp(<hostname>:<port>)/<dbname>?MEK=00112233445566778899aabbccddeeff&ENC_ALGO=SM4_128_CBC")
    if err != nil {
        panic(err)
    }

    _, err = db.Exec("DROP TABLE IF EXISTS test")
    if err != nil {
        panic(err)
    }
    _, err = db.Exec(`CREATE TABLE test(a int, b text, c float)`)
    if err != nil {
        panic(err)
    }
    _, err = db.Exec(`INSERT INTO test SET a = 0, b = 'test', c = 0.0`)
    if err != nil {
        panic(err)
    }

    rows, err := db.Query("SELECT * FROM test")
    rows.Next()
    var a int
    var b string
    var c float32

    err = rows.Scan(&a, &b, &c)
    fmt.Printf("read data: %d %s %f\n", a, b, c)
}
```

### Query VSwitch Details - Bash - all

```bash
curl -X GET 'https://rds.aliyuncs.com/?Action=DescribeVSwitches&ResourceOwnerId=0&RegionId=cn-hangzhou&VpcId=vpc-bp1opxu1zkhn**********&ZoneId=cn-hangzhou-h&PageNumber=1&PageSize=30&Common request parameters'
```

### Modify Security Group Configuration - Python - all

```python
import json
import requests

# Set up the API endpoint and headers
url = "https://rds.aliyuncs.com/" 
headers = {
    "Content-Type": "application/json",
    "Authorization": "Bearer YOUR_API_KEY"
}

# Define the request body
payload = {
    "Action": "ModifySecurityGroupConfiguration",
    "Version": "2014-08-15",
    "DBInstanceId": "rm-bp15i4hn07r******",
    "SecurityGroupId": "sg-****"
}

# Send the request
response = requests.post(url, headers=headers, data=json.dumps(payload))

# Print the response
print(response.json())
```

### Query DDoS Protection Information - Python - all

```python
import requests

url = "https://rds.aliyuncs.com/api/v1/DescribeRCInstanceIpAddress"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}
params = {
    "TemplateId": 412,
    "RegionId": "cn-hangzhou",
    "ResourceGroupId": "rg-acfmy*****"
}

response = requests.get(url, headers=headers, params=params)
print(response.json())
```

### Query Column Encryption Configuration - Python - all

```python
import requests
import json

# Set your API endpoint and credentials
url = "https://rds.aliyuncs.com/api/v1/DescribeDBInstanceCLS"
headers = {
    "Authorization": "Bearer YOUR_API_KEY",
    "Content-Type": "application/json"
}

# Request parameters
params = {
    "DBInstanceId": "rm-t4n8t18o******6d5"
}

# Make the API call
response = requests.get(url, headers=headers, params=params)

# Parse response
if response.status_code == 200:
    data = response.json()
    print(json.dumps(data, indent=2))
else:
    print(f"Error: {response.status_code} - {response.text}")
```

## Response Format

```json
{
    "Items": {
        "DBInstanceIPArray": [
            {
                "DBInstanceIPArrayName": "rds_default",
                "DBInstanceIPArrayAttribute": "",
                "WhitelistNetworkType": "VPC",
                "SecurityIPList": "192.168.1.0/24",
                "SecurityIPType": "IPv4"
            }
        ]
    },
    "RequestId": "E2B6AF71-DC32-4055-B477-43B348798D10"
}
```

**Key Fields**:
- `Items.DBInstanceIPArray[].DBInstanceIPArrayName` — Name of the IP address whitelist
- `Items.DBInstanceIPArray[].SecurityIPList` — List of IP addresses or CIDR blocks in the whitelist
- `Items.DBInstanceIPArray[].WhitelistNetworkType` — Network type of the whitelist (Classic, VPC, or MIX)
- `Items.DBInstanceIPArray[].SecurityIPType` — IP address type (IPv4)
- `RequestId` — Unique identifier for the API request

## Error Handling

| Error Code (Code) | Description (Description) | Recommended Action (Recommended Action) |
|---------------|--------------------|-----------------------------|
| 400 | InvalidWhitelistNetType.Malformed: The error message returned because the value of the WhitelistNetworkType parameter is invalid. Enter a valid value. | Verify that WhitelistNetworkType is set to one of: Classic, VPC, or MIX |
| 400 | InvalidIPArrayAttribute.Format: The error message returned because the value of the DBInstanceIPArrayAttribute parameter is in an invalid format. Enter a value in the valid format and try again. If the IP address allowlist contains multiple IP addresses or CIDR blocks, make sure that the IP addresses and CIDR blocks are unique and are separated by commas (,). The entries in the IP address allowlist must be in one of the following formats: IP addresses, such as 10.23.12.24. CIDR blocks, such as 10.23.12.0/24. In this case, 24 indicates that the prefix of each IP address is 24-bit long. You can replace 24 with a value within the range of 1 to 32. | Ensure IP addresses and CIDR blocks follow the correct format and are unique |
| 400 | InvalidSecurityIPList.Duplicate: The error message returned because the specified IP addresses or CIDR blocks are invalid. The specified IP addresses or CIDR blocks are duplicate. | Remove duplicate IP addresses or CIDR blocks from your request |
| 400 | SecurityIPList.Format: The error message returned because the specified IP addresses or CIDR blocks are invalid. | Verify that all IP addresses and CIDR blocks follow the correct format |
| 400 | InvalidServerCertOrPrivateKey: The error message returned because the specified server certificate or private key is invalid. | Check that your server certificate and private key are valid and properly formatted |
| 400 | InvalidClientCACert: The error message returned because the value of the ClientCACert parameter is invalid. | Verify that your client CA certificate is valid |
| 400 | InvalidClientCrl: The error message returned because the specified CRL is invalid. | Ensure your certificate revocation list is properly formatted |
| 400 | InvalidCAType.NotFound: The error message returned because the specified type of the server certificate is invalid. | Confirm that CAType is set to either 'aliyun' or 'custom' |
| 400 | InvalidACL.NotFound: The error message returned because the value of the ACL parameter is invalid. | Verify that ACL is set to one of: cert, perfer, verify-ca, or verify-full |
| 400 | InvalidSSLStatus: The error message returned because the value of the SSLEnabled parameter is invalid. | Ensure SSLEnabled is set to either 0 (disabled) or 1 (enabled) |
| 403 | InvalidClientCrl.Permission: The error message returned because you are not authorized to perform this operation. You must configure a client CA certificate before you perform this operation. | Configure a client CA certificate before enabling CRL |
| 403 | InvalidACL.Permission: The error message returned because the client CA certificate is not specified. | Specify a client CA certificate before configuring ACL |

## Environment Requirements

- SDK package: Install the appropriate SDK for your language (e.g., `pip install aliyun-python-sdk-rds` for Python)
- Environment variable setup: `export DASHSCOPE_API_KEY=your_api_key`
- For EncJDBC: JDK 1.8 or later, Maven 3.9.2
- For GoLang_EncMySQL: Go 1.18 or later

## FAQ

Q: How do I configure IP whitelisting for my RDS instance?
A: Use the ModifySecurityIps API to add, update, or delete IP addresses in your instance's whitelist. You can specify individual IPs or CIDR blocks, and choose between different modification modes (Cover, Append, Delete).

Q: What's the difference between standard and enhanced whitelist mode?
A: Standard whitelist mode (MIX) applies IP rules to all network types, while enhanced whitelist mode allows separate configuration for Classic and VPC network types. Enhanced mode provides more granular control over network access.

Q: How can I enable SSL encryption for my RDS instance?
A: Use the ModifyDBInstanceSSL API with SSLEnabled set to 1. For PostgreSQL instances, you can also configure client certificate validation and certificate revocation lists for additional security.

Q: What should I do if I get a "SecurityIPList.Format" error?
A: This error indicates invalid IP addresses or CIDR blocks in your request. Verify that all entries follow the correct format (e.g., 192.168.1.1 for IPs or 192.168.1.0/24 for CIDR blocks) and that there are no duplicates.

Q: How do I connect to an always-confidential database?
A: Use specialized client drivers like EncJDBC for Java or GoLang_EncMySQL for Go applications. These drivers handle encryption/decryption automatically using your Master Encryption Key (MEK) without requiring changes to your application logic.

## Pricing & Billing

### Billing Model
API calls are billed on a per-request basis. Each successful API invocation counts as one request regardless of the response size or complexity.

### Price Reference

| Model/Specification | Input Price | Output Price | Other Fees |
|-----------|---------|---------|---------|
| IP Whitelist Management | 0.0001 / | 0.0001 / |
| SSL Encryption Settings | 0.001 / | 0.001 / |
| VSwitch Details | 0.001 / | 0.001 / |
| Security Group Rules | 0.002 / | |
| DDoS Protection Monitoring | 0.002 / | |
| Column Encryption Configuration | 0.002 / | 0.002 / |
| Always-Confidential Database | 0.0001 / | 0.0001 / |

### Free Tier
Most security APIs include a monthly free tier:
- IP Whitelist Management: 1000 free calls per month
- SSL Encryption Settings: 1000 free calls per month
- VSwitch Details: 100 free calls per month
- Always-Confidential Database: 1000 free requests per month

### Usage Limits
- Rate limits: Most APIs have a limit of 100 QPS (queries per second) per account
- IP Whitelist: Maximum 1,000 IP addresses/CIDR blocks per instance and 200 whitelists per instance
- Security Groups: Maximum 10 security groups per instance