All Products
Search
Document Center

Security Center:SDK for malicious file detection

Last Updated:Mar 25, 2024

SDK for malicious file detection is a feature that is developed based on various threat detection engines of Security Center. The feature can detect common viruses such as ransomware and mining programs in offline files and Object Storage Service (OSS) objects to prevent the spread and execution of malicious files. This topic describes how to use SDK for malicious file detection.

Usage notes

  • SDK for malicious file detection is a cloud detection solution. If you use this feature, your files are uploaded to the cloud for detection.

  • A quota of 1 on SDK for malicious file detection can be used to check only a file that is less than or equal to 20 MB in size.

  • Alibaba Cloud accounts that have passed enterprise real-name verification can use the free trial of SDK for malicious file detection. A free trial contains a quota of 10,000 on SDK for malicious file detection. If you purchase Security Center Enterprise, you can specify the quota based on your business requirements. The default queries per second (QPS) for a free trial is different from the default QPS for Security Center Enterprise.

    • QPS of a free trial: 10.

    • QPS of Security Center Enterprise: 20.

  • You can use SDK for malicious file detection based on the following methods:

    • File detection SDK: You can use an SDK to detect malicious files and obtain information about the malicious files from the returned results. You can use SDK for Java or SDK for Python.

    • OSS object detection: You can check objects of OSS buckets in the Security Center console. You can also view the objects on which risks are detected.

  • The speed of malicious file detection is affected by factors such as network conditions, computer performance, and limits on cloud services. SDK for malicious file detection uses queues to process requests during external request spikes. This helps improve processing capabilities in high-concurrency scenarios. When the internal queue is full, the system rejects external requests and does not process external requests until the queue has space available.

    You can increase the queue length to process more concurrent requests. This method affects the detection duration of some samples. The timeout_ms parameter specifies the timeout period of the samples. Unit: milliseconds. To reduce timeout errors, we recommend that you set the timeout_ms parameter to 60,000 milliseconds, which is equivalent to 60 seconds.

Supported virus types

The following table describes the types of viruses that can be detected.

Virus type (virus_type)

Virus name

Backdoor

Reverse shell

DDoS

DDoS trojan

Downloader

Trojan downloader

Engtest

Engine test program

Hacktool

Attacker tool

Trojan

High-risk program

Malbaseware

Tainted basic software

MalScript

Malicious script

Malware

Malicious program

Miner

Mining program

Proxytool

Proxy

RansomWare

Ransomware

RiskWare

Riskware

Rootkit

Rootkit

Stealer

Tool that is used to steal information

Scanner

Scanner

Suspicious

Suspicious program

Virus

Infectious virus

WebShell

Webshell

Worm

Worm

AdWare

Adware

Patcher

Patch

Gametool

Gametool

Prerequisites

If you use a Resource Access Management (RAM) user, make sure that the AliyunYundunSASFullAccess policy is attached to the RAM user. For more information, see Grant permissions to the RAM user.

Enable SDK for malicious file detection

You can apply for a free trial or purchase SDK for malicious file detection.

Free trial

If your Alibaba Cloud account has passed the enterprise real-name verification, you can use a free trial of SDK for malicious file detection and obtain a free quota of 10,000 on SDK for malicious file detection. Each Alibaba Cloud account can use the free trial for only once.

  1. Log on to the Security Center console. In the top navigation bar, select China as the region of the asset that you want to manage.

  2. In the left-side navigation pane, choose Risk Governance > SDK for Malicious File Detection.

  3. On the SDK for Malicious File Detection page, click Try Now.

Payment

If the free trial cannot meet your requirements, you can purchase SDK for malicious file detection.

Important

If the free quota is not exhausted, the remaining free quota is added to the purchased quota after you purchase the feature.

  1. Log on to the Security Center console. In the top navigation bar, select China as the region of the asset that you want to manage.

  2. In the left-side navigation pane, choose Risk Governance > SDK for Malicious File Detection.

  3. On the SDK for Malicious File Detection page, click Buy Now. On the page that appears, select Yes for Malicious File Detection SDK, and configure the Quota for Malicious File Detection SDK parameter based on the number of total files that you want to check.

    If you purchased a paid edition of Security Center, you can specify the quota on SDK for malicious file detection. If you did not purchase a paid edition of Security Center, select a paid edition of Security Center based on your business requirements.

    • If you do not require the other features of Security Center, select Value-added Plan Edition.

    • If you want to use the other features of Security Center, such as vulnerability fixing and container threat detection, select the required edition of Security Center. For more information about the features that are supported by each edition, see Functions and features.

  4. Read and select Terms of Service, click Buy Now, and then complete the payment.

After you enable SDK for malicious file detection, you can view the remaining quota on SDK for malicious file detection on the SDK for Malicious File Detection page.

image.png

Call SDK for malicious file detection

Preparations

  • The environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET are configured.

    You can define the environment variables ALIBABA_CLOUD_ACCESS_KEY_ID and ALIBABA_CLOUD_ACCESS_KEY_SECRET to configure the default credentials. When you call an API operation, the system reads the AccessKey pair from the default credentials and uses the AccessKey pair to complete authentication. For more information, see Configure credentials.

  • You must select an access method and obtain an SDK based on the following table.

    Access method

    Version

    Procedure

    Java

    Java Development Kit (JDK) 1.8 or later

    You can obtain SDK for Java by using one of the following methods:

    • Use Maven to obtain SDK for Java: Open the pom.xml file of your Maven project and add the aliyun-sas-filedetect dependency. We recommend that you use this method if you have access to the Internet.

      <dependency>
         <groupId>com.aliyun</groupId>
         <artifactId>filedetect</artifactId>
         <version>1.0.0</version>
      </dependency>
    • Import and install SDK for Java offline if you do not have access to the Internet: Visit the Code library for Java over the Internet and download the SDK for Java, and add the SDK for Java to your project.

    Python

    Python 3.6 or later

    You can obtain SDK for Python by using one of the following methods:

    • Use pip to install SDK for Python. We recommend that you use this method if you have access to the Internet.

      pip install -U alibabacloud_filedetect
    • Install SDK for Python offline if you do not have access to the Internet: Visit the Code library for Python and download SDK for Python over the Internet. Upload SDK for Python to the project environment, decompress the SDK package, and run the following installation command:

      pip install alibabacloud_sas_filedetect-1.0.0-py3-none-any.whl

Sample code

Important

If you use SDK for Python, change the value of the path parameter in the following example.

package com.aliyun.filedetect.sample;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

import com.aliyun.filedetect.*;

public class Sample {

    /**
     * Synchronous file detection operation. 
     * @param detector The detector object. 
     * @param path The path to the file that you want to check. 
     * @param timeout_ms The timeout period. Unit: milliseconds. 
     * @param wait_if_queuefull Specify the operation that is performed when the queue is full. The value false indicates that the system directly returns an error, and the value true indicates the system waits until the queue has space available. 
     * @throws InterruptedException
     */
    public static DetectResult detectFileSync(OpenAPIDetector detector, String path, int timeout_ms, boolean wait_if_queuefull) throws InterruptedException {
        if (null == detector || null == path) return null;
        DetectResult result = null;
        while(true) {
            result = detector.detectSync(path, timeout_ms);
            if (null == result) break;
            if (result.error_code != ERR_CODE.ERR_DETECT_QUEUE_FULL) break;
            if (!wait_if_queuefull) break;
            detector.waitQueueAvailable(-1);
        }
        return result;
    }

    /**
     * Asynchronous file detection operation. 
     * @param detector The detector object. 
     * @param path The path to the file that you want to detect. 
     * @param timeout_ms The timeout period. Unit: milliseconds. 
     * @param wait_if_queuefull Specify the operation that is performed when the queue is full. The value false indicates that the system directly returns an error, and the value true indicates the system waits until the queue has space available. 
     * @param callback The callback function. 
     * @throws InterruptedException
     */
    public static int detectFile(OpenAPIDetector detector, String path, int timeout_ms, boolean wait_if_queuefull, IDetectResultCallback callback) throws InterruptedException {
        if (null == detector || null == path || null == callback) return ERR_CODE.ERR_INIT.value();
        int result = ERR_CODE.ERR_INIT.value();
        if (wait_if_queuefull) {
            final IDetectResultCallback real_callback = callback;
            callback = new IDetectResultCallback() {
                public void onScanResult(int seq, String file_path, DetectResult callback_res) {
                    if (callback_res.error_code == ERR_CODE.ERR_DETECT_QUEUE_FULL) return;
                    real_callback.onScanResult(seq, file_path, callback_res);
                }
            };
        }
        while(true) {
            result = detector.detect(path, timeout_ms, callback);
            if (result != ERR_CODE.ERR_DETECT_QUEUE_FULL.value()) break;
            if (!wait_if_queuefull) break;
            detector.waitQueueAvailable(-1);
        }
        return result;
    }

    /**
     * Format the detection result. 
     * @param result The detection result. 
     * @return The formatted string. 
     */
    public static String formatDetectResult(DetectResult result) {
        if (result.isSucc()) {
            DetectResult.DetectResultInfo info = result.getDetectResultInfo();
            String msg = String.format("[DETECT RESULT] [SUCCEED] md5: %s, time: %d, result: %s, score: %d"
                    , info.md5, info.time, info.result.name(), info.score);
            DetectResult.VirusInfo vinfo = info.getVirusInfo();
            if (vinfo != null) {
                msg += String.format(", virus_type: %s, ext_info: %s", vinfo.virus_type, vinfo.ext_info);
            }
            return msg;
        }
        DetectResult.ErrorInfo info = result.getErrorInfo();
        return String.format("[DETECT RESULT] [FAIL] md5: %s, time: %d, error_code: %s, error_message: %s"
                , info.md5, info.time, info.error_code.name(), info.error_string);
    }

    /**
     * Synchronous detection of directories or files. 
     * @param path The path. You can specify a file or a directory. Use recursive traversal when you specify a directory. 
     * @param is_sync_scan Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
     * @throws InterruptedException
     */
    public static void detectDirOrFileSync(OpenAPIDetector detector, String path, int timeout_ms, Map<String, DetectResult> result_map) throws InterruptedException {
        File file = new File(path);
        String abs_path = file.getAbsolutePath();
        if (file.isDirectory()) {
            String[] ss = file.list();
            if (ss == null) return;
            for (String s : ss) {
                String subpath = abs_path + File.separator + s;
                detectDirOrFileSync(detector, subpath, timeout_ms, result_map);
            }
            return;
        }

        System.out.println(String.format("[detectFileSync] [BEGIN] queueSize: %d, path: %s, timeout: %d", detector.getQueueSize(), abs_path, timeout_ms));
        DetectResult res = detectFileSync(detector, abs_path, timeout_ms, true);
        System.err.println(String.format("                 [ END ] %s", formatDetectResult(res)));
        result_map.put(abs_path, res);
    }

    /**
     * Asynchronous detection of directories or files. 
     * @param path The path. You can specify a file or a directory. Use recursive traversal when you specify a directory. 
     * @param is_sync_scan Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
     * @throws InterruptedException
     */
    public static void detectDirOrFile(OpenAPIDetector detector, String path, int timeout_ms, IDetectResultCallback callback) throws InterruptedException {
        File file = new File(path);
        String abs_path = file.getAbsolutePath();
        if (file.isDirectory()) {
            String[] ss = file.list();
            if (ss == null) return;
            for (String s : ss) {
                String subpath = abs_path + File.separator + s;
                detectDirOrFile(detector, subpath, timeout_ms, callback);
            }
            return;
        }


        int seq = detectFile(detector, abs_path, timeout_ms, true, callback);
        System.out.println(String.format("[detectFile] [BEGIN] seq: %d, queueSize: %d, path: %s, timeout: %d", seq, detector.getQueueSize(), abs_path, timeout_ms));
    }

    /**
     * Start the detection on files or directories. 
     * @param path The path. You can specify a file or a directory. Use recursive traversal when you specify a directory. 
     * @param is_sync_scan Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
     * @throws InterruptedException
     */
    public static void scan(final OpenAPIDetector detector, String path, int detect_timeout_ms, boolean is_sync) throws InterruptedException {
        System.out.println(String.format("[SCAN] [START] path: %s, detect_timeout_ms: %d, is_sync: %b", path, detect_timeout_ms, is_sync));
        long start_time = System.currentTimeMillis();
        final Map<String, DetectResult> result_map = new HashMap<>();
        if (is_sync) {
            detectDirOrFileSync(detector, path, detect_timeout_ms, result_map);
        } else {
            detectDirOrFile(detector, path, detect_timeout_ms, new IDetectResultCallback() {
                public void onScanResult(int seq, String file_path, DetectResult callback_res) {
                    System.err.println(String.format("[detectFile] [ END ] seq: %d, queueSize: %d, %s", seq, detector.getQueueSize(), formatDetectResult(callback_res)));
                    result_map.put(file_path, callback_res);
                }
            });
            // Wait until the task is complete. 
            detector.waitQueueEmpty(-1);
        }
        long used_time = System.currentTimeMillis() - start_time;
        System.out.println(String.format("[SCAN] [ END ] used_time: %d, files: %d", used_time, result_map.size()));

        int fail_count = 0;
        int white_count = 0;
        int black_count = 0;
        for (Map.Entry<String, DetectResult> entry : result_map.entrySet()) {
            DetectResult res = entry.getValue();
            if (res.isSucc()) {
                if (res.getDetectResultInfo().result == DetectResult.RESULT.RES_BLACK) {
                    black_count ++;
                } else {
                    white_count ++;
                }
            } else {
                fail_count ++;
            }
        }
        System.out.println(String.format("             fail_count: %d, white_count: %d, black_count: %d"
                , fail_count, white_count, black_count));
    }

    public static void main(String[] args_) throws Exception {
        // Obtain the detector instance. 
        OpenAPIDetector detector = OpenAPIDetector.getInstance();

        // Initialize the SDK. 
        ERR_CODE init_ret = detector.init(System.getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"), System.getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET"));

        boolean is_sync_scan=false; // Specify whether to perform an asynchronous detection or a synchronous detection. An asynchronous detection provides better performance. The value false indicates an asynchronous detection, and the value true indicates a synchronous detection. 
        int timeout_ms = 120000;  // The detection time of a sample. Unit: milliseconds. 
        String path = "test2.php"; // The file or directory that you want to scan. 

        // Start the scan and wait until the scan is complete. 
        scan(detector, path, timeout_ms, is_sync_scan);

        // Deinitialize the SDK.
        System.out.println("Over.");
        detector.uninit();
    }
}
# -*- coding: utf-8 -*-
import os
import sys
from typing import List
import threading
import time
import traceback

from alibabacloud_filedetect.OpenAPIDetector import OpenAPIDetector
from alibabacloud_filedetect.IDetectResultCallback import IDetectResultCallback
from alibabacloud_filedetect.ERR_CODE import ERR_CODE
from alibabacloud_filedetect.DetectResult import DetectResult

class Sample(object):

    def __init__(self):
        pass


    """
    Synchronous file detection operation. 
    @param detector The detector object. 
    @param path The path to the file that you want to detect. 
    @param timeout_ms The timeout period. Unit: milliseconds. 
    @param wait_if_queuefull Specify the operation that is performed when the queue is full. The value false indicates that the system directly returns an error, and the value true indicates the system waits until the queue has space available. 
    """
    def detectFileSync(self, detector, path, timeout_ms, wait_if_queuefull):
        if detector is None or path is None:
            return None
        result = None
        while True:
            result = detector.detectSync(path, timeout_ms)
            if result is None:
                break
            if result.error_code != ERR_CODE.ERR_DETECT_QUEUE_FULL:
                break
            if wait_if_queuefull is False:
                break
            detector.waitQueueAvailable(-1)

        return result


    """
    Asynchronous file detection operation. 
    @param detector The detector object. 
    @param path The path to the file that you want to detect. 
    @param timeout_ms The timeout period. Unit: milliseconds. 
    @param wait_if_queuefull Specify the operation that is performed when the queue is full. The value false indicates that the system directly returns an error, and the value true indicates the system waits until the queue has space available. 
    @param callback The callback function. 
    """
    def detectFile(self, detector, path, timeout_ms, wait_if_queuefull, callback):
        if detector is None or path is None or callback is None:
            return ERR_CODE.ERR_INIT.value
        result = ERR_CODE.ERR_INIT.value
        if wait_if_queuefull:
            real_callback = callback
            class AsyncTaskCallback(IDetectResultCallback):
                def onScanResult(self, seq, file_path, callback_res):
                    if callback_res.error_code == ERR_CODE.ERR_DETECT_QUEUE_FULL:
                        return
                    real_callback.onScanResult(seq, file_path, callback_res)
            callback = AsyncTaskCallback()
        while True:
            result = detector.detect(path, timeout_ms, callback)
            if result != ERR_CODE.ERR_DETECT_QUEUE_FULL.value:
                break
            if wait_if_queuefull is False:
                break
            detector.waitQueueAvailable(-1)

        return result


    """
    Format the detection result. 
    @param result The detection result. 
    @return The formatted string. 
    """
    @staticmethod
    def formatDetectResult(result):
        if result.isSucc():
            info = result.getDetectResultInfo()
            msg = "[DETECT RESULT] [SUCCEED] md5: {}, time: {}, result: {}, score: {}".format(info.md5,
                info.time, info.result, info.score)
            vinfo = info.getVirusInfo()
            if vinfo is not None:
                msg += ", virus_type: {}, ext_info: {}".format(vinfo.virus_type, vinfo.ext_info)
            return msg

        info = result.getErrorInfo()
        msg = "[DETECT RESULT] [FAIL] md5: {}, time: {}, error_code: {}, error_message: {}".format(info.md5,
            info.time, info.error_code, info.error_string)
        return msg



    """
    Synchronous detection of directories or files. 
    @param path The path. You can specify files or directories. Use recursive traversal when you specify a directory. 
    @param is_sync Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
    """
    def detectDirOrFileSync(self, detector, path, timeout_ms, result_map):
        abs_path = os.path.abspath(path)
        if os.path.isdir(abs_path):
            sub_files = os.listdir(abs_path)
            if len(sub_files) == 0:
                return
            for sub_file in sub_files:
                sub_path = os.path.join(abs_path, sub_file)
                self.detectDirOrFileSync(detector, sub_path, timeout_ms, result_map)
            return

        elif os.path.isfile(abs_path):
            print("[detectFileSync] [BEGIN] queueSize: {}, path: {}, timeout: {}".format(
                detector.getQueueSize(), abs_path, timeout_ms))
            res = self.detectFileSync(detector, abs_path, timeout_ms, True)
            print("                 [ END ] {}".format(self.formatDetectResult(res)))
            result_map[abs_path] = res

        return


    """
    Asynchronous detection of directories or files. 
    @param path The path. You can specify files or directories. Use recursive traversal when you specify a directory. 
    @param is_sync Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
    """
    def detectDirOrFile(self, detector, path, timeout_ms, callback):
        abs_path = os.path.abspath(path)
        if os.path.isdir(abs_path):
            sub_files = os.listdir(abs_path)
            if len(sub_files) == 0:
                return
            for sub_file in sub_files:
                sub_path = os.path.join(abs_path, sub_file)
                self.detectDirOrFile(detector, sub_path, timeout_ms, callback)
            return

        elif os.path.isfile(abs_path):
            seq = self.detectFile(detector, abs_path, timeout_ms, True, callback)
            print("[detectFile] [BEGIN] seq: {}, queueSize: {}, path: {}, timeout: {}".format(
                seq, detector.getQueueSize(), abs_path, timeout_ms))

        return


    """
    Start the detection on files or directories. 
    @param path The path. You can specify files or directories. Use recursive traversal when you specify a directory. 
    @param is_sync Specify whether to use the synchronous detection operation. We recommend that you use the asynchronous detection operation. The value true indicates that the synchronous detection operation is used, and the value false indicates that the asynchronous detection operation is used. 
    """
    def scan(self, detector, path, detect_timeout_ms, is_sync):
        try:
            print("[SCAN] [START] path: {}, detect_timeout_ms: {}, is_sync: {}".format(path, detect_timeout_ms, is_sync))
            start_time = time.time()
            result_map = {}
            if is_sync:
                self.detectDirOrFileSync(detector, path, detect_timeout_ms, result_map)
            else:
                class AsyncTaskCallback(IDetectResultCallback):
                    def onScanResult(self, seq, file_path, callback_res):
                        print("[detectFile] [ END ] seq: {}, queueSize: {}, {}".format(seq,
                            detector.getQueueSize(), Sample.formatDetectResult(callback_res)))
                        result_map[file_path] = callback_res
                self.detectDirOrFile(detector, path, detect_timeout_ms, AsyncTaskCallback())

                # Wait until the task is complete. 
                detector.waitQueueEmpty(-1)

            used_time_ms = (time.time() - start_time) * 1000
            print("[SCAN] [ END ] used_time: {}, files: {}".format(used_time_ms, len(result_map)))

            failed_count = 0
            white_count = 0
            black_count = 0
            for file_path, res in result_map.items():
                if res.isSucc():
                    if res.getDetectResultInfo().result == DetectResult.RESULT.RES_BLACK:
                        black_count += 1
                    else:
                        white_count += 1
                else:
                    failed_count += 1

            print("               fail_count: {}, white_count: {}, black_count: {}".format(
                failed_count, white_count, black_count))

        except Exception as e:
            print(traceback.format_exc(), file=sys.stderr)


    def main(self):
        # Obtain the detector instance. 
        detector = OpenAPIDetector.get_instance()
        
        # Obtain the AccessKey ID and AccessKey secret in environment variables.
        access_key_id = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_ID')
        access_key_secret = os.getenv('ALIBABA_CLOUD_ACCESS_KEY_SECRET')

        # Initialize the SDK. 
        init_ret = detector.init(access_key_id, access_key_secret)
        print("INIT RET: {}".format(init_ret))

        # Specify the custom parameters for scan. 
        is_sync_scan = False # Specify whether the detection is an asynchronous detection or a synchronous detection. An asynchronous detection provides better performance. The value false indicates an asynchronous detection. 
        timeout_ms = 120000 # The detection time of a sample. Unit: milliseconds. 
        path = "./test" # The files or directories that you want to scan. 

        # Start the scan and wait until the scan is complete. 
        self.scan(detector, path, timeout_ms, is_sync_scan)

        # Deinitialize the SDK.
        print("Over.")
        detector.uninit()


if __name__ == "__main__":
    sample = Sample()
    sample.main()

Returned results

After you call the SDK, the detection results are not synchronized to the Security Center console. You can view the results only in the returned results of the SDK call. You can view the remaining quota on SDK for malicious file detection in the Security Center console. The SDK for Malicious File Detection page displays detection statistics. For example, the Total Files parameter on the At-risk File Overview tab specifies the total number of scanned files.

struct DetectResult {
    std::string md5; // The MD5 hash value of the sample.
    long time = 0; // The time that is required to process this request. Unit: milliseconds.

    ERR_CODE error_code;    // The error code.
    std::string error_string;     // The extended error message.

    enum RESULT {
        RES_WHITE = 0,       // The number of secure files.
        RES_BLACK = 1,       // The number of suspicious files.
        RES_PENDING = 3           // The number of files that are being detected.
     };
    RESULT result;          // The detection result.

    int score;                // The detection score. Valid values: 0 to 100.
    std::string virus_type;    // The virus type. Examples: WebShell, MalScript, and Hacktool.
    std::string ext_info;    // The extended information. The value of this parameter is a JSON string.
};

The following error codes may be returned:

enum ERR_CODE {
    ERR_INIT = -100,            // Initialization is required or repeated.
    ERR_FILE_NOT_FOUND = -99,  // The file is not found.
    ERR_DETECT_QUEUE_FULL = -98, // The detection queue is full.
    ERR_CALL_API = -97, // An error occurred while calling the operation.
    ERR_TIMEOUT = -96, // The operation timed out.

    ERR_SUCC = 0              // The operation is successful.
};

A higher detection score indicates a higher risk. The following table describes the mapping between detection scores and risk levels.

Score range

Risk level

0~60

Secure

61~70

At-risk

71~80

Suspicious

81~100

Malicious

OSS file detection

Perform a detection on objects in buckets

Before you perform a detection, make sure that the remaining quota for the current Alibaba Cloud account is sufficient. If the remaining quota is insufficient, you can perform the following operations to purchase additional quota: Go to the SDK for Malicious File Detection page, click the At-risk File Overview tab, and then click Upgrade Configuration.

  1. Log on to the Security Center console. In the top navigation bar, select China as the region of the asset that you want to manage.

  2. In the left-side navigation pane, choose Risk Governance > SDK for Malicious File Detection.

  3. Click the OSS File Check tab, select a detection method, and then start detection.

    If your bucket is not displayed in the list on the OSS File Check page, you can click Synchronize Buckets to obtain the latest list of buckets.

    Detection method

    Description

    Procedure

    Manual full detection

    Check all objects in one or more buckets.

    1. On the OSS File Check tab, click Check in the Actions column of a bucket or select multiple buckets and click Batch Check.

    2. In the Check dialog box, configure the File Check Type and Scan Path parameters and click OK.

    Manual incremental detection

    Check only newly added objects in a bucket that has been checked.

    1. On the OSS File Check tab, find the required bucket and click Incremental Check in the Actions column.

    2. In the Incremental Check dialog box, configure the File Check Type and Scan Path parameters and click OK.

    Auto detection

    Enable periodic automatic detection for specified buckets based on configured scan policies. Take note of the following items before you configure a scan policy:

    • A bucket can be specified only in one policy.

    • Automatic detection is enabled only for newly added objects in OSS. Repeated detection is not performed on the same file.

    1. On the OSS File Check tab, click Log Audit Settings.

    2. In the Log Audit Settings panel, click Create Policy.

      If an existing policy meets your business requirements, you can click Edit in the Actions column of the policy. In the Edit Policy panel, select the bucket for which you want to enable automatic detection and click OK.

    3. In the Create Policy panel, configure parameters such as the Policy Name, Schedule, File Check Time, File Check Type, and Effective Bucket parameters, and click OK.

View detection results

  • View the overall information about at-risk OSS objects

    In the statistics section of the At-risk File Overview tab, you can view the following information: the total number of OSS objects that are detected, the number of objects at different risk levels, including high, medium, and low, and the remaining quota.

  • View the details of at-risk files

    In the list of at-risk files, find the file whose details you want to view and click Details in the Actions column. In the details panel, view the information such as Documentation details and Description of events.

    Important

    A file on which risks are detected may be embedded with viruses such as malicious scripts and DDoS trojans. We recommend that you handle the file at the earliest opportunity based on the suggestions provided in the Description of events section.

  • View the statistics on OSS object detection

    In the statistics section of the OSS File Check tab, you can view the following information: the number of buckets in which malicious objects are detected, the number of objects at different risk levels, including high, medium, and low, the number of undetected buckets, and the total number of buckets.

  • View the detection results of a bucket

    On the OSS File Check tab, find the bucket whose detection results you want to view and click Details in the Actions column. On the File Check Details page, you can view the information about the bucket in Basic information and At-risk File Details sections.

Export detection results

  • Export the list of all at-risk files

    On the At-risk File Overview tab, click the image..png icon. After the file is exported, click Download in the dialog box that appears.

  • Export the list of all at-risk files by bucket

    On the OSS File Check tab, click the image..png icon. After the file is exported, click Download in the dialog box that appears.

References

You can call one of the following API operations to use SDK for malicious file detection: