DEV Community

SameX
SameX

Posted on

Insights into the Security Development Practices of HarmonyOS Next

This article aims to deeply explore the technical details of the Huawei HarmonyOS Next system (up to API 12 as of now), and is summarized based on actual development practices. It mainly serves as a vehicle for technical sharing and communication. Mistakes and omissions are inevitable. Colleagues are welcome to put forward valuable opinions and questions so that we can make progress together. This article is original content, and any form of reprint must indicate the source and the original author.

1. Setup of the Security Development Environment

(1) Setup Steps

To embark on the journey of security development for HarmonyOS Next, the first step is to set up a suitable development environment. This is as crucial as preparing a solid foundation before building a house.

  1. Installation of Development Tools We need to download and install the official development toolkit of HarmonyOS Next, such as DevEco Studio. This toolkit is like a universal toolbox that contains various tools required for our development, such as a code editor, compiler, and debugger. The installation process is similar to assembling furniture according to the instructions. Just follow the prompts step by step. However, it should be noted that during the installation process, it is essential to choose a secure download source to avoid downloading tampered installation packages. It's just like buying genuine furniture; we should purchase from formal channels to prevent buying counterfeits.
  2. Configuration of Development Environment Variables After the installation is completed, some environment variables also need to be configured so that the system can locate the installed development tools. This is like finding a fixed storage location for the toolbox in the room and informing everyone where it is so that it can be accessed at any time. For example, setting the path of the JDK (Java Development Kit) is necessary because the development of HarmonyOS Next may involve Java-related technologies. The JDK is like a warehouse that provides us with building materials. Without it, we cannot build the desired software edifice. ### (2) Key Points for Environment Security Configuration
  3. Regularly Update Development Tools Development tools are like the weapons in our hands, and they should always be kept sharp. Regularly updating development tools can ensure that we have the latest security fixes and functional improvements. Imagine if we were to fight with a rusty sword (using an old version of development tools with security vulnerabilities), it would be easy for the enemy (attackers) to break through. Regular updates are like sharpening and upgrading the sword to make it more powerful.
  4. Restrict Unnecessary Network Access In the development environment, some tools may work properly without network access. For these tools, we should restrict their network access rights. This is like installing anti-theft nets on the doors and windows of a house to prevent thieves (malicious network attacks) from entering through these unnecessary channels. For example, we can set rules in the firewall to only allow development tools to access necessary network resources, such as the official server for downloading update packages. ## 2. Security Coding Standards ### (1) Standard Items
  5. Input Validation When handling user input, strict validation must be carried out. User input is like a mysterious package. We cannot open it directly; we must first check whether the package is safe (whether the input is legal). For example, if our application requires the user to input a number, we need to check whether the input content is truly a number rather than other malicious characters. Otherwise, it may cause the program to malfunction or even be attacked.
  6. Principle of Least Privilege When applying for permissions in the code, the principle of least privilege should be followed. This is like in a company, where employees are only granted the minimum permissions required to complete their work. For example, if an application only needs to read the user's contact information, then only the permission to read contacts should be applied for, and other unnecessary permissions, such as sending text messages or making phone calls, should not be applied for. This can reduce the security risks brought about by excessive permissions. ### (2) Code Snippets Demonstrating Standard Coding Methods
  7. Input Validation Code Example The following is a simple ARKTS code snippet used to validate whether the user input is a number:
function validateInput(input: string): boolean {
    const numberRegex: RegExp = /^\d+$/;
    return numberRegex.test(input);
}
let userInput: string = "123";
if (validateInput(userInput)) {
    console.log("Input is valid and is a number.");
} else {
    console.log("Input is invalid. Please enter a number.");
}
Enter fullscreen mode Exit fullscreen mode

In this example, a regular expression is used to verify whether the user input conforms to the format of a number. If it does, true is returned to indicate that the input is valid; otherwise, false is returned.

  1. Code Example for the Principle of Least Privilege Suppose we are developing a picture viewing application that only needs to read picture files in the storage. The following is part of the code showing how to apply for the minimum permissions:
import featureAbility from '@ohos.ability.featureAbility';
async function requestMinimalPermission(): Promise<void> {
    try {
        const permissions: Array<string> = ["ohos.permission.READ_USER_STORAGE"];
        const requestResult: number = await featureAbility.requestPermissionsFromUser(permissions);
        if (requestResult === 0) {
            console.log("Permission application successful. Pictures in user storage can be read.");
        } else {
            console.log("Permission application failed. Please check the settings.");
        }
    } catch (err) {
        console.error("Error in permission application:", err);
    }
}
Enter fullscreen mode Exit fullscreen mode

In this code, we only apply for the permission to read user storage and do not apply for other irrelevant permissions, ensuring the minimum use of permissions.

3. Security Testing and Vulnerability Fixing

(1) Security Testing Tools and Methods

  1. Static Code Analysis Tools Static code analysis tools are like strict code reviewers. They analyze the source code directly without running the program. For example, Checkmarx can help us discover potential security vulnerabilities in the code, such as buffer overflow, SQL injection, and other risks. It will carefully examine each line of the code, just like a reviewer checking an article word by word to find possible problem areas.
  2. Dynamic Testing Methods Dynamic testing is carried out while the program is running. We can simulate various user operations and environmental conditions and observe the behavior of the program. For example, by simulating a large number of users logging into the application simultaneously, we can check whether the system will have security issues under high-concurrency conditions, such as authentication failure or data leakage. This is like testing the performance of a weapon on a real battlefield to see whether it can function properly under various complex situations. ### (2) Example Illustrating the Process of Vulnerability Discovery and Fixing Suppose we have developed a simple login application, and during security testing, a vulnerability is discovered.
  3. Vulnerability Discovery Using the dynamic testing method, when we input an overly long username, we find that the application program crashes. This is like finding that a wall of a house suddenly collapses when subjected to a strong impact (inputting an overly long username is equivalent to an abnormal input attack). After analysis, it is found that in the part of the code that processes the username input, there is no limit on the input length, resulting in a memory overflow when the program processes overly long strings.
  4. Vulnerability Fixing To address this issue, we can add a limit on the length of the username in the input validation code. The modified code is as follows:
function validateUsername(username: string): boolean {
    if (username.length > 20) {
        console.log("Username is too long. Please re-enter.");
        return false;
    }
    const validCharsRegex: RegExp = /^[a-zA-Z0-9_]+$/;
    return validCharsRegex.test(username);
}
Enter fullscreen mode Exit fullscreen mode

By adding the length limit and stricter character validation, the vulnerability is fixed, just like reinforcing the collapsed wall and making the house (the application program) stronger and more secure.
Following the security development practice guidelines of HarmonyOS Next, from setting up a secure development environment, adhering to security coding standards, to conducting comprehensive security testing and timely vulnerability fixing, is like putting layer after layer of protective armor on the software we develop. This not only ensures the secure and stable operation of the application but also enhances users' trust in our products. During the development process, we should always be vigilant and integrate security awareness into every aspect so that we can walk more steadily and farther on the path of HarmonyOS Next development.

Top comments (0)