This article aims to delve into the technical details of Huawei’s HarmonyOS Next system (as of now API 12), and summarize it based on actual development practices. Mainly as a carrier for technology sharing and exchange. Errors and omissions are inevitable. Colleagues are welcome to raise valuable opinions and questions so that we can make progress together. This article is original content, and any reprint must indicate the source and original author.
1. Establishing a safe development environment
(1) Setting steps
To embark on the safe development journey of HarmonyOS Next, you must first establish a suitable development environment. This is just as important as preparing a solid foundation before building your home.
- Development tool installation We need to download and install the HarmonyOS Next official development tool package, such as DevEco Studio. This toolkit is like a general toolbox, which contains various tools we need for development, such as code editors, compilers, debuggers, etc. The installation process is similar to assembling furniture according to instructions. Just follow the step-by-step instructions. However, it should be noted that during the installation process, you must choose a safe download source to avoid downloading tampered installation packages. Just like buying genuine furniture; we should buy from regular channels to prevent buying fakes.
- Configuration of development environment variables After the installation is complete, you need to configure some environment variables so that the system can locate the installed development tools. It’s like finding a fixed storage location for your toolbox in the room and notifying everyone where it is so that it can be accessed at any time. For example, since the development of HarmonyOS Next may involve Java-related technologies, the path to the JDK (Java Development Kit) needs to be set. JDK is like a warehouse that provides us with building materials. Without it, we wouldn’t be able to build the software architecture we need. ### (2) Key points of environmental security configuration
- Regularly update development tools Development tools are like weapons in our hands and must be kept sharp at all times. Regularly updating development tools ensures we have the latest security fixes and feature improvements. Imagine if we fight with a rusty sword (using old versions of development tools with security holes), then the enemy (attacker) can easily break through. Regular updates are like sharpening and upgrading a sword to make it more powerful.
- Limit Unnecessary Network Access In a development environment, some tools can function normally without network access. For these tools, we should limit their network access. 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 official servers for downloading update packages. ## 2. Secure Coding Standards### (1) Standard Project
- Input validation When processing user input, strict validation must be performed. User input is like a mysterious package. We can’t open it directly; we first have to check if the package is safe (the input is legal). For example, if our application requires the user to enter a number, we need to check that the input is actually a number and not other malicious characters. Otherwise, it may cause program malfunction or even be attacked.
- Principle of Least Privilege When applying for permissions in program code, you should follow the principle of least privilege. It’s like in a company where employees are only given the minimum permissions they need to do their jobs. For example, if the application only needs to read the user’s contact information, then it only needs to apply for permission to read contacts, and not apply for other unnecessary permissions, such as sending text messages, making calls, etc. This can reduce the security risks caused by too many permissions. ### (2) Code snippet demonstrating standard encoding method
- Input Validation Code Example Here is a simple ARKTS code snippet that verifies that user input is numeric:
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.");
}
In this example, regular expressions are used to verify whether the user input conforms to the format of the number. If yes, true
The return indicates that the input is valid; otherwise, false
is returned.
- The code example of the principle of least privilege assumes that we are developing an image viewing application that only needs to read the image files in storage. Here is part of the code showing how to apply for 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);
}
}
In this code, we only apply for 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
- Static code analysis tools Static code analysis tools are like strict code reviewers. They directly analyze the source code without running the program. For example, Checkmarx can help us discover potential security vulnerabilities in program code, such as buffer overflow, SQL injection and other risks. It scrutinizes every line of code, just like a reviewer going through an article word for word to find potentially problematic areas.
- Dynamic testing method Dynamic testing is performed while the program is executing. We can simulate various user operations and environmental conditions to observe program behavior. For example, by simulating a large number of users logging into the application at the same time, we can check whether the system will have security issues under high concurrency conditions, such as authentication failure or data leakage. It’s like testing the performance of a weapon on a real battlefield to see if it can function properly in various complex situations. ### (2) Example of vulnerability discovery and repair process Suppose we develop a simple login application and discover a vulnerability during security testing.
- The vulnerability was discovered using a dynamic testing method. When we entered a user name that was too long, we found that the application crashed. It’s like finding out that the walls of your house suddenly collapsed upon receiving a strong impact (tying in a username that’s too long is the equivalent of an anomalous input attack). After analysis, it was found that in part of the code that processes user name input, there is no limit on the input length, causing the program to overflow memory when processing too long strings.
- Bug fix In order to solve this problem, we can add a user name length limit in the input verification 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);
}
By increasing the length limit and stricter character validation, the vulnerability is fixed, just like strengthening a collapsed wall to make the house (the application) stronger and more secure.
Following HarmonyOS Next’s security development practice guide, from establishing a secure development environment and complying with secure coding standards to conducting comprehensive security testing and timely fixing vulnerabilities, is like putting on layers of protective armor for the software we develop. This not only ensures the safe and stable operation of the application, but also enhances users’ trust in our products. During the development process, we should remain vigilant at all times and integrate security awareness into every link, so that we can go further and further on the development path of HarmonyOS Next.