All Products
Search
Document Center

Elastic Compute Service:Protect Alibaba Cloud accounts and prevent credential leakage

Last Updated:Jun 25, 2026

Enable MFA, use RAM roles instead of AccessKeys, and rotate credentials regularly to prevent unauthorized access.

Security risks

The main security threats to an Alibaba Cloud account include brute-force attacks on passwords and leakage of long-term credentials, such as AccessKeys and STS tokens. If an attacker obtains these credentials, they can impersonate a legitimate user to log on, manage resources, or access sensitive data. This can cause:

  • Unauthorized resource usage, resulting in direct financial losses.

  • Infrastructure damage or service interruptions affecting business availability.

  • Sensitive data leakage or encryption, leading to information disclosure and ransomware risks.

  • Installation of malicious programs or backdoors, posing long-term threats to system security and data integrity.

Best practices

Protect account passwords and enable MFA

  • Set complex passwords: Weak passwords are a primary cause of account breaches. Avoid weak passwords to prevent brute-force attacks.

  • Change passwords regularly: Change your password every 90 days to reduce leakage risk from long-term use.

  • Enable MFA: Attach or detach a virtual MFA device for your Alibaba Cloud account and RAM users. MFA adds a dynamic verification code, such as a mobile token or a hardware-protected key, as an extra layer beyond password authentication to prevent unauthorized access.

Use ECS RAM roles instead of AccessKeys

If an application on an ECS instance needs to call Alibaba Cloud APIs, such as for ECS scaling, use a RAM role instead of an AccessKey.

Create a RAM user and attach a role

The account must have the sts:AssumeRole permission to attach a role to an instance.

Console

  1. Create and authorize a Resource Access Management (RAM) user.

  2. Attach a RAM role to an ECS instance.

    Attach a role during instance creation

    When you create an instance on the instance purchase page, select Instance RAM Role in Advanced Options.

    Select Security Hardening Mode for Metadata Access Mode to prevent STS token leakage caused by instance vulnerabilities or configuration errors. See Access instance metadata using the enforced mode.

    Attach a role to an existing instance

    1. Go to the ECS console - Instances page and select the target region.

    2. Click the instance ID to go to the instance details page.

    3. In the Other Information section, click Attach/Detach RAM Role.

    4. Select the RAM role and click OK.

    Important

    An ECS instance can have only one RAM role. If your application requires multiple permissions, grant all of them to that single role.

    For example, if an instance already has the AliyunECSDiskEncryptDefaultRole role and also needs network interface management permissions, add the AliyunECSNetworkInterfaceManagementAccess policy to the role in the RAM console.

API

Use API operations to attach and detach roles:

Use a RAM role to access Alibaba Cloud services from an application

An application on an ECS instance can obtain a temporary STS token from the instance metadata service and use it to call Alibaba Cloud APIs.

Sample code

from alibabacloud_credentials.client import Client as CredClient
from alibabacloud_credentials.models import Config as CredConfig
from alibabacloud_tea_openapi.models import Config
from alibabacloud_ecs20140526.client import Client as EcsClient
from alibabacloud_ecs20140526 import models as ecs_models
from alibabacloud_tea_util.models import RuntimeOptions

# Step 1: Obtain an STS token
def get_sts_token():
    config = CredConfig(
        type="ecs_ram_role",
        enable_imds_v1=False
    )
    cred_client = CredClient(config)
    credential = cred_client.get_credential()
    return {
        "AccessKeyId": credential.get_access_key_id(),
        "AccessKeySecret": credential.get_access_key_secret(),
        "SecurityToken": credential.get_security_token()
    }

# Step 2: Initialize the ECS client
def create_ecs_client(sts_token):
    config = Config(
        access_key_id=sts_token["AccessKeyId"],
        access_key_secret=sts_token["AccessKeySecret"],
        security_token=sts_token["SecurityToken"],
        endpoint="ecs.cn-hangzhou.aliyuncs.com"
    )
    return EcsClient(config)

# Step 3: Build the request to create an instance
def build_create_instance_request():
    return ecs_models.RunInstancesRequest(
        region_id="cn-hangzhou",
        image_id="aliyun_3_x64_20G_scc_alibase_20220225.vhd",
        instance_type="ecs.e-c1m2.xlarge",
        security_group_id="sg-bp1esyhwfbqeyudt****",
        v_switch_id="vsw-bp1nzprm8h7mmnl8t****",
        instance_name="sdk-test",
        instance_charge_type="PostPaid",
        key_pair_name="sdk-key-pair",
        system_disk_category="cloud_essd"
    )

# Step 4: Call the API to create the instance
def create_instance(client, request):
    runtime = RuntimeOptions()
    try:
        response = client.run_instances_with_options(request, runtime)
        print("Instance created successfully. Instance ID:", response.body.instance_id_sets.instance_id_set[0])
    except Exception as e:
        print("Failed to create instance. Error message:", e)

# Main function
if __name__ == "__main__":
    sts_token = get_sts_token()  # Obtain an STS token
    ecs_client = create_ecs_client(sts_token)  # Initialize the ECS client
    request = build_create_instance_request()  # Build the request to create an instance
    create_instance(ecs_client, request)  # Call the API to create the instance

Protect AccessKeys and reduce leakage risk

If you must use an AccessKey, strengthen its security management throughout its lifecycle — creation, storage, distribution, and use.

  • Creation: Follow the principle of "one AccessKey per person, one AccessKey per application." Do not share an AccessKey among multiple users or programs. This lets you quickly identify the responsible party, limit the impact, and rotate the key if leaked.

  • Permission management: Follow the principle of least privilege and grant only necessary permissions. Use RAM users and assign permissions based on responsibilities. Avoid using the Alibaba Cloud account AccessKey. See Avoid using your Alibaba Cloud account and grant different permissions to RAM users with different responsibilities.

  • Secure storage: Store AccessKeys on trusted devices, such as:

    • A file readable only by root or a specific user.

    • A database or Key Management Service (KMS) with access control.

    • Do not store AccessKeys in notes, code repositories, chat records, or personal signatures.

  • Secure distribution: Send the encrypted AccessKey file through one channel (such as email) and the decryption password through a separate channel (such as a text message).

  • Secure use: Do not hard-code AccessKeys in your code. Store the AccessKey in a separate configuration file, encrypt it, and save it on a trusted server. After distribution, decrypt the file and set permissions so only the owner can read it.

  • Network access control: Configure a network access control policy for the AccessKey in the RAM console.

  • Regular rotation and cleanup

  • Monitor for AccessKey leakage: Use the AccessKey leakage detection feature in Security Center to check whether an AccessKey has been leaked. This feature supports alert notifications. If a leak occurs, Alibaba Cloud provides restrictive protection for the AccessKey to prevent escalation.

Compliance

Check whether an ECS instance uses an AccessKey

Query AccessKey logs to find the services, IP addresses, and resources associated with an AccessKey.

Prerequisite: You have created an ActionTrail trail and delivered logs to an SLS Logstore.

  • Query AccessKey calls initiated from a VPC Endpoint:

    * | SELECT "event.eventid","event.sourceipaddress", "event.userIdentity.accessKeyId",  "event.vpcId" WHERE "event.userIdentity.accessKeyId" LIKE 'LTA%' and "event.vpcId" LIKE 'vpc%'

    Example result:

    image.png

    Use the vpcId and sourceipaddress to identify the ECS instance that initiated the call. Then, investigate which programs use the accessKeyId to call the OpenAPI.

  • Query AccessKey calls initiated from an Internet Endpoint:

    * | SELECT "event.eventid","event.sourceipaddress", "event.userIdentity.accessKeyId" WHERE "event.userIdentity.accessKeyId" LIKE 'LTA%' and "event.vpcId" IS NULL

    Example result:

    image.png

    Determine whether the sourceipaddress is a public IP address of an ECS instance. Retrieve the EIPs and public IP addresses under your account, then check whether the sourceipaddress belongs to you. If an EIP or public IP address is directly attached to an ECS instance, you can locate the instance and modify its configuration.

Replace the AccessKey with an instance RAM role

See Use ECS RAM roles instead of AccessKeys and Solutions for AccessKey leakage.