1e41f4b71Sopenharmony_ci# C&C++ Secure Coding Guide 2e41f4b71Sopenharmony_ci 3e41f4b71Sopenharmony_ciThis document provides some secure coding suggestions based on the C\&C++ language to guide development. 4e41f4b71Sopenharmony_ci 5e41f4b71Sopenharmony_ci# Functions 6e41f4b71Sopenharmony_ci 7e41f4b71Sopenharmony_ci## Check the validity of all values received from external sources 8e41f4b71Sopenharmony_ci 9e41f4b71Sopenharmony_ci**\[Description]** 10e41f4b71Sopenharmony_ci 11e41f4b71Sopenharmony_ciExternal sources are networks, user input, command lines, files (including program configuration files), environment variables, user-mode data (for kernel programs), inter-process communications (including pipes, messages, shared memory, sockets, RPCs, and communications between different boards in a device), API parameters, and global variables. 12e41f4b71Sopenharmony_ci 13e41f4b71Sopenharmony_ciData from outside programs is often considered untrusted and needs to be properly checked for validity before being used. If data from an external source is not checked before use, unexpected security risks may occur. 14e41f4b71Sopenharmony_ci 15e41f4b71Sopenharmony_ciNote: Do not use assertions to check external input data. Assertions should be used to prevent incorrect program assumptions but cannot be used to check for runtime errors in a released version. 16e41f4b71Sopenharmony_ci 17e41f4b71Sopenharmony_ciData from outside programs must be checked before being used. Typical scenarios include: 18e41f4b71Sopenharmony_ci 19e41f4b71Sopenharmony_ci- **Used as an array index** 20e41f4b71Sopenharmony_ci 21e41f4b71Sopenharmony_ci If untrusted data is used as an array index, the array upper bound may be exceeded, causing invalid memory access. 22e41f4b71Sopenharmony_ci 23e41f4b71Sopenharmony_ci- **Used as a memory offset address** 24e41f4b71Sopenharmony_ci 25e41f4b71Sopenharmony_ci Using untrusted data as the pointer offset for memory access may result in invalid memory access and cause further damages, for example, any address read/write. 26e41f4b71Sopenharmony_ci 27e41f4b71Sopenharmony_ci- **Used as a memory allocation size parameter** 28e41f4b71Sopenharmony_ci 29e41f4b71Sopenharmony_ci Zero-byte allocation may cause invalid memory access; an unrestricted memory allocation size leads to excessive resource consumption. 30e41f4b71Sopenharmony_ci 31e41f4b71Sopenharmony_ci- **Used a loop condition** 32e41f4b71Sopenharmony_ci 33e41f4b71Sopenharmony_ci If untrusted data is used as a loop condition, problems such as buffer overflow, out-of-bounds read/write, and infinite loop may occur. 34e41f4b71Sopenharmony_ci 35e41f4b71Sopenharmony_ci- **Used as a divisor** 36e41f4b71Sopenharmony_ci 37e41f4b71Sopenharmony_ci Divide-by-zero errors may occur. 38e41f4b71Sopenharmony_ci 39e41f4b71Sopenharmony_ci- **Used as a command line parameter** 40e41f4b71Sopenharmony_ci 41e41f4b71Sopenharmony_ci Command injection vulnerabilities may occur. 42e41f4b71Sopenharmony_ci 43e41f4b71Sopenharmony_ci- **Used as the parameter of a database query statement** 44e41f4b71Sopenharmony_ci 45e41f4b71Sopenharmony_ci SQL injection vulnerabilities may occur. 46e41f4b71Sopenharmony_ci 47e41f4b71Sopenharmony_ci- **Used as an input/output format string** 48e41f4b71Sopenharmony_ci 49e41f4b71Sopenharmony_ci Format string vulnerabilities may occur. 50e41f4b71Sopenharmony_ci 51e41f4b71Sopenharmony_ci- **Used as a memory copy length** 52e41f4b71Sopenharmony_ci 53e41f4b71Sopenharmony_ci Buffer overflows may occur. 54e41f4b71Sopenharmony_ci 55e41f4b71Sopenharmony_ci- **Used a file path** 56e41f4b71Sopenharmony_ci 57e41f4b71Sopenharmony_ci Direct access to an untrusted file path may result in directory traversal attacks. As a result, the system is controlled by the attacker who can perform file operations without permissions. 58e41f4b71Sopenharmony_ci 59e41f4b71Sopenharmony_ciInput validation includes but is not limited to: 60e41f4b71Sopenharmony_ci 61e41f4b71Sopenharmony_ci- API parameter validity check 62e41f4b71Sopenharmony_ci- Data length check 63e41f4b71Sopenharmony_ci- Data range check 64e41f4b71Sopenharmony_ci- Data type and format check 65e41f4b71Sopenharmony_ci- Check on inputs that can only contain permitted characters (in the trustlist), especially special characters in certain cases. 66e41f4b71Sopenharmony_ci 67e41f4b71Sopenharmony_ci**External Data Validation Principles** 68e41f4b71Sopenharmony_ci 69e41f4b71Sopenharmony_ci1. Trust boundary 70e41f4b71Sopenharmony_ci 71e41f4b71Sopenharmony_ci External data is untrusted. Therefore, if data is transmitted and processed across different trust boundaries during system operation, validity check must be performed on data from modules outside the trust boundaries to prevent attacks from spreading. 72e41f4b71Sopenharmony_ci 73e41f4b71Sopenharmony_ci (a) Different so (or dll) modules 74e41f4b71Sopenharmony_ci 75e41f4b71Sopenharmony_ci As an independent third-party module, the so or dll module is used to export common API functions for other modules to call. The so/dll module is unable to determine whether the caller passes on valid arguments. Therefore, the common function of the so/dll module needs to check the validity of the arguments provided by the caller. The so/dll module should be designed in low coupling and high reusability. Although the so/dll module is designed to be used only in this software in certain cases, different so/dll modules should still be regarded as different trust boundaries. 76e41f4b71Sopenharmony_ci 77e41f4b71Sopenharmony_ci (b) Different processes 78e41f4b71Sopenharmony_ci 79e41f4b71Sopenharmony_ci To prevent privilege escalation through processes with high permissions, the IPC communications between processes (including IPC communications between boards and network communications between hosts) should be regarded as communications across different trust boundaries. 80e41f4b71Sopenharmony_ci 81e41f4b71Sopenharmony_ci (c) Application layer processes and operating system kernel 82e41f4b71Sopenharmony_ci The operating system kernel has higher permissions than the application layer. The interface provided by the kernel for the application layer should process the data from the application layer as untrusted data. 83e41f4b71Sopenharmony_ci 84e41f4b71Sopenharmony_ci (d) Internal and external environments of TEE 85e41f4b71Sopenharmony_ci To prevent attacks from spreading to the TEE, the interfaces provided by the TEE and SGX for external systems should process external data as untrusted data. 86e41f4b71Sopenharmony_ci 87e41f4b71Sopenharmony_ci2. External data validation 88e41f4b71Sopenharmony_ci 89e41f4b71Sopenharmony_ci The external data received by a module must be validated before being used. After data validation is completed, the data stored in the module does not need to be verified again by other internal subfunctions in the module. 90e41f4b71Sopenharmony_ci 91e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 92e41f4b71Sopenharmony_ci 93e41f4b71Sopenharmony_ciThe **Foo()** function processes external data. Because the buffer does not necessarily end with '\\0', the **nameLen** value returned by **strlen** may exceed **len**. As a result, out-of-bounds read occurs. 94e41f4b71Sopenharmony_ci 95e41f4b71Sopenharmony_ci```cpp 96e41f4b71Sopenharmony_civoid Foo(const unsigned char* buffer, size_t len) 97e41f4b71Sopenharmony_ci{ 98e41f4b71Sopenharmony_ci // "buffer" may be a null pointer and may not end with '\0'. 99e41f4b71Sopenharmony_ci const char* s = reinterpret_cast<const char*>(buffer); 100e41f4b71Sopenharmony_ci size_t nameLen = strlen(s); 101e41f4b71Sopenharmony_ci std::string name(s, nameLen); 102e41f4b71Sopenharmony_ci Foo2(name); 103e41f4b71Sopenharmony_ci ... 104e41f4b71Sopenharmony_ci} 105e41f4b71Sopenharmony_ci``` 106e41f4b71Sopenharmony_ci 107e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 108e41f4b71Sopenharmony_ci 109e41f4b71Sopenharmony_ciExternal data is checked for validity. In this example, **strnlen** is used to calculate the string length to reduce the risk of out-of-bounds read. 110e41f4b71Sopenharmony_ci 111e41f4b71Sopenharmony_ci```cpp 112e41f4b71Sopenharmony_civoid Foo(const unsigned char* buffer, size_t len) 113e41f4b71Sopenharmony_ci{ 114e41f4b71Sopenharmony_ci // Parameter validity check must be performed. 115e41f4b71Sopenharmony_ci if (buffer == nullptr || len == 0 || len >= MAX_BUFFER_LEN) { 116e41f4b71Sopenharmony_ci ... // Error handling 117e41f4b71Sopenharmony_ci } 118e41f4b71Sopenharmony_ci 119e41f4b71Sopenharmony_ci const char* s = reinterpret_cast<const char*>(buffer); 120e41f4b71Sopenharmony_ci size_t nameLen = strnlen(s, len); // strnlen is used to mitigate the risk of out-of-bounds read. 121e41f4b71Sopenharmony_ci if (nameLen == len) { 122e41f4b71Sopenharmony_ci ... // Error handling 123e41f4b71Sopenharmony_ci } 124e41f4b71Sopenharmony_ci std::string name(s, nameLen); 125e41f4b71Sopenharmony_ci ... 126e41f4b71Sopenharmony_ci Foo2(name); 127e41f4b71Sopenharmony_ci ... 128e41f4b71Sopenharmony_ci} 129e41f4b71Sopenharmony_ci``` 130e41f4b71Sopenharmony_ci 131e41f4b71Sopenharmony_ci```cpp 132e41f4b71Sopenharmony_cinamespace ModuleA { 133e41f4b71Sopenharmony_ci// Foo2() is an internal function of the module. Parameter validity is ensured by the caller as agreed. 134e41f4b71Sopenharmony_cistatic void Foo2(const std::string& name) 135e41f4b71Sopenharmony_ci{ 136e41f4b71Sopenharmony_ci ... 137e41f4b71Sopenharmony_ci Bar(name.c_str()); // Call the function in MODULE_B. 138e41f4b71Sopenharmony_ci} 139e41f4b71Sopenharmony_ci 140e41f4b71Sopenharmony_ci// Foo() is an external interface of the module. Parameter validity check must be performed. 141e41f4b71Sopenharmony_civoid Foo(const unsigned char* buffer, size_t len) 142e41f4b71Sopenharmony_ci{ 143e41f4b71Sopenharmony_ci // Check the null pointer and valid parameter range. 144e41f4b71Sopenharmony_ci if (buffer == nullptr || len <= sizeof(int)) { 145e41f4b71Sopenharmony_ci // Error handling 146e41f4b71Sopenharmony_ci ... 147e41f4b71Sopenharmony_ci } 148e41f4b71Sopenharmony_ci 149e41f4b71Sopenharmony_ci int nameLen = *(reinterpret_cast<const int*>(buffer)); // Obtain the length of the name character string from the packet. 150e41f4b71Sopenharmony_ci // nameLen is untrusted data and its validity must be checked. 151e41f4b71Sopenharmony_ci if (nameLen <= 0 || static_cast<size_t>(nameLen) > len - sizeof(int)) { 152e41f4b71Sopenharmony_ci // Error handling 153e41f4b71Sopenharmony_ci ... 154e41f4b71Sopenharmony_ci } 155e41f4b71Sopenharmony_ci 156e41f4b71Sopenharmony_ci std::string name(reinterpret_cast<const char*>(buffer), nameLen); 157e41f4b71Sopenharmony_ci Foo2(name); // Call the internal functions of the module. 158e41f4b71Sopenharmony_ci ... 159e41f4b71Sopenharmony_ci} 160e41f4b71Sopenharmony_ci} 161e41f4b71Sopenharmony_ci``` 162e41f4b71Sopenharmony_ci 163e41f4b71Sopenharmony_ciThe following code is the code in `MODULE_B` written using the C language: 164e41f4b71Sopenharmony_ci 165e41f4b71Sopenharmony_ci```cpp 166e41f4b71Sopenharmony_ci// Bar is a common function of MODULE_B. 167e41f4b71Sopenharmony_ci// If name is not nullptr, the string must be a valid string, which is longer than 0 bytes and null terminated. 168e41f4b71Sopenharmony_civoid Bar(const char* name) 169e41f4b71Sopenharmony_ci{ 170e41f4b71Sopenharmony_ci // Parameter validity check must be performed. 171e41f4b71Sopenharmony_ci if (name == nullptr || name[0] == '\0') { 172e41f4b71Sopenharmony_ci // Error handling 173e41f4b71Sopenharmony_ci ... 174e41f4b71Sopenharmony_ci } 175e41f4b71Sopenharmony_ci size_t nameLen = strlen(name); // strnlen does not need to be used. 176e41f4b71Sopenharmony_ci ... 177e41f4b71Sopenharmony_ci} 178e41f4b71Sopenharmony_ci``` 179e41f4b71Sopenharmony_ci 180e41f4b71Sopenharmony_ciFor module A, the buffer is an external untrusted input, which must be strictly verified. Validity check is performed while the name is parsed from the buffer. The name is valid in module A, and validity check is not required when the name is transferred to internal subfunctions as a parameter. (If the name content needs to be parsed, it must be verified.) If the name in module A needs to be transferred to other modules across the trusted plane (in this example, the common function of module B is directly called, or by means of file, pipe, or network transfer), the name is untrusted data for module B and therefore validity check must be performed. 181e41f4b71Sopenharmony_ci 182e41f4b71Sopenharmony_ci# Classes 183e41f4b71Sopenharmony_ci 184e41f4b71Sopenharmony_ci## Class member variables must be explicitly initialized 185e41f4b71Sopenharmony_ci 186e41f4b71Sopenharmony_ci**\[Description]** 187e41f4b71Sopenharmony_ci 188e41f4b71Sopenharmony_ciIf a class member variable is not explicitly initialized, the object will have an indeterminate value. If the class member variable has a default constructor, it does not need to be explicitly initialized. 189e41f4b71Sopenharmony_ci 190e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 191e41f4b71Sopenharmony_ci 192e41f4b71Sopenharmony_ci```cpp 193e41f4b71Sopenharmony_ciclass Message { 194e41f4b71Sopenharmony_cipublic: 195e41f4b71Sopenharmony_ci void Process() 196e41f4b71Sopenharmony_ci { 197e41f4b71Sopenharmony_ci ... 198e41f4b71Sopenharmony_ci } 199e41f4b71Sopenharmony_ci 200e41f4b71Sopenharmony_ciprivate: 201e41f4b71Sopenharmony_ci uint32_t msgId; // Noncompliant: The member variable is not initialized. 202e41f4b71Sopenharmony_ci size_t msgLength; // Noncompliant: The member variable is not initialized. 203e41f4b71Sopenharmony_ci unsigned char* msgBuffer; // Noncompliant: The member variable is not initialized. 204e41f4b71Sopenharmony_ci std::string someIdentifier; // Only this member variable is initialized by the default constructor. 205e41f4b71Sopenharmony_ci}; 206e41f4b71Sopenharmony_ci 207e41f4b71Sopenharmony_ciMessage message; // The message member variable is not completely initialized. 208e41f4b71Sopenharmony_cimessage.Process(); // Potential risks exist in subsequent use. 209e41f4b71Sopenharmony_ci``` 210e41f4b71Sopenharmony_ci 211e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 212e41f4b71Sopenharmony_ci 213e41f4b71Sopenharmony_ciOne practice is to explicitly initialize the class member variable in declarations. 214e41f4b71Sopenharmony_ci 215e41f4b71Sopenharmony_ci```cpp 216e41f4b71Sopenharmony_ciclass Message { 217e41f4b71Sopenharmony_cipublic: 218e41f4b71Sopenharmony_ci void Process() 219e41f4b71Sopenharmony_ci { 220e41f4b71Sopenharmony_ci ... 221e41f4b71Sopenharmony_ci } 222e41f4b71Sopenharmony_ci 223e41f4b71Sopenharmony_ciprivate: 224e41f4b71Sopenharmony_ci uint32_t msgId{0}; 225e41f4b71Sopenharmony_ci size_t msgLength{0}; 226e41f4b71Sopenharmony_ci unsigned char* msgBuffer{nullptr}; 227e41f4b71Sopenharmony_ci std::string someIdentifier; // The default constructor is used, and explicit initialization is not required. 228e41f4b71Sopenharmony_ci}; 229e41f4b71Sopenharmony_ci``` 230e41f4b71Sopenharmony_ci 231e41f4b71Sopenharmony_ciAnother option is to initialize the list using a constructor. 232e41f4b71Sopenharmony_ci 233e41f4b71Sopenharmony_ci```cpp 234e41f4b71Sopenharmony_ciclass Message { 235e41f4b71Sopenharmony_cipublic: 236e41f4b71Sopenharmony_ci Message() : msgId(0), msgLength(0), msgBuffer(nullptr) {} 237e41f4b71Sopenharmony_ci void Process() 238e41f4b71Sopenharmony_ci { 239e41f4b71Sopenharmony_ci ... 240e41f4b71Sopenharmony_ci } 241e41f4b71Sopenharmony_ci 242e41f4b71Sopenharmony_ciprivate: 243e41f4b71Sopenharmony_ci uint32_t msgId; 244e41f4b71Sopenharmony_ci size_t msgLength; 245e41f4b71Sopenharmony_ci unsigned char* msgBuffer; 246e41f4b71Sopenharmony_ci std::string someIdentifier; // The default constructor is used, and explicit initialization is not required. 247e41f4b71Sopenharmony_ci}; 248e41f4b71Sopenharmony_ci``` 249e41f4b71Sopenharmony_ci 250e41f4b71Sopenharmony_ci## Clearly define the special member functions to be implemented 251e41f4b71Sopenharmony_ci 252e41f4b71Sopenharmony_ci**\[Description]** 253e41f4b71Sopenharmony_ci 254e41f4b71Sopenharmony_ci**Rule of three** 255e41f4b71Sopenharmony_ci 256e41f4b71Sopenharmony_ciIf a class requires a user-defined destructor, a user-defined copy constructor, or a user-defined copy assignment operator, it almost certainly requires all three. 257e41f4b71Sopenharmony_ci 258e41f4b71Sopenharmony_ci```cpp 259e41f4b71Sopenharmony_ciclass Foo { 260e41f4b71Sopenharmony_cipublic: 261e41f4b71Sopenharmony_ci Foo(const char* buffer, size_t size) { Init(buffer, size); } 262e41f4b71Sopenharmony_ci Foo(const Foo& other) { Init(other.buf, other.size); } 263e41f4b71Sopenharmony_ci 264e41f4b71Sopenharmony_ci Foo& operator=(const Foo& other) 265e41f4b71Sopenharmony_ci { 266e41f4b71Sopenharmony_ci Foo tmp(other); 267e41f4b71Sopenharmony_ci Swap(tmp); 268e41f4b71Sopenharmony_ci return *this; 269e41f4b71Sopenharmony_ci } 270e41f4b71Sopenharmony_ci 271e41f4b71Sopenharmony_ci ~Foo() { delete[] buf; } 272e41f4b71Sopenharmony_ci 273e41f4b71Sopenharmony_ci void Swap(Foo& other) noexcept 274e41f4b71Sopenharmony_ci { 275e41f4b71Sopenharmony_ci using std::swap; 276e41f4b71Sopenharmony_ci swap(buf, other.buf); 277e41f4b71Sopenharmony_ci swap(size, other.size); 278e41f4b71Sopenharmony_ci } 279e41f4b71Sopenharmony_ci 280e41f4b71Sopenharmony_ciprivate: 281e41f4b71Sopenharmony_ci void Init(const char* buffer, size_t size) 282e41f4b71Sopenharmony_ci { 283e41f4b71Sopenharmony_ci this->buf = new char[size]; 284e41f4b71Sopenharmony_ci memcpy(this->buf, buffer, size); 285e41f4b71Sopenharmony_ci this->size = size; 286e41f4b71Sopenharmony_ci } 287e41f4b71Sopenharmony_ci 288e41f4b71Sopenharmony_ci char* buf; 289e41f4b71Sopenharmony_ci size_t size; 290e41f4b71Sopenharmony_ci}; 291e41f4b71Sopenharmony_ci``` 292e41f4b71Sopenharmony_ci 293e41f4b71Sopenharmony_ciThe implicitly-defined special member functions are typically incorrect if the class manages a resource whose handle is an object of non-class type (such as the raw pointer or POSIX file descriptor), whose destructor does nothing and copy constructor/assignment operator performs a "shallow copy". 294e41f4b71Sopenharmony_ci 295e41f4b71Sopenharmony_ciClasses that manage non-copyable resources through copyable handles may have to declare copy assignment and copy constructor private and not provide their definitions or define them as deleted. 296e41f4b71Sopenharmony_ci 297e41f4b71Sopenharmony_ci**Rule of five** 298e41f4b71Sopenharmony_ci 299e41f4b71Sopenharmony_ciThe presence of a user-defined destructor, copy-constructor, or copy-assignment operator can prevent implicit definition of the move constructor and the move assignment operator. Therefore, any class for which move semantics are desirable has to declare all five special member functions. 300e41f4b71Sopenharmony_ci 301e41f4b71Sopenharmony_ci```cpp 302e41f4b71Sopenharmony_ciclass Foo { 303e41f4b71Sopenharmony_cipublic: 304e41f4b71Sopenharmony_ci Foo(const char* buffer, size_t size) { Init(buffer, size); } 305e41f4b71Sopenharmony_ci Foo(const Foo& other) { Init(other.buf, other.size); } 306e41f4b71Sopenharmony_ci 307e41f4b71Sopenharmony_ci Foo& operator=(const Foo& other) 308e41f4b71Sopenharmony_ci { 309e41f4b71Sopenharmony_ci Foo tmp(other); 310e41f4b71Sopenharmony_ci Swap(tmp); 311e41f4b71Sopenharmony_ci return *this; 312e41f4b71Sopenharmony_ci } 313e41f4b71Sopenharmony_ci 314e41f4b71Sopenharmony_ci Foo(Foo&& other) noexcept : buf(std::move(other.buf)), size(std::move(other.size)) 315e41f4b71Sopenharmony_ci { 316e41f4b71Sopenharmony_ci other.buf = nullptr; 317e41f4b71Sopenharmony_ci other.size = 0; 318e41f4b71Sopenharmony_ci } 319e41f4b71Sopenharmony_ci 320e41f4b71Sopenharmony_ci Foo& operator=(Foo&& other) noexcept 321e41f4b71Sopenharmony_ci { 322e41f4b71Sopenharmony_ci Foo tmp(std::move(other)); 323e41f4b71Sopenharmony_ci Swap(tmp); 324e41f4b71Sopenharmony_ci return *this; 325e41f4b71Sopenharmony_ci } 326e41f4b71Sopenharmony_ci 327e41f4b71Sopenharmony_ci ~Foo() { delete[] buf; } 328e41f4b71Sopenharmony_ci 329e41f4b71Sopenharmony_ci void Swap(Foo& other) noexcept 330e41f4b71Sopenharmony_ci { 331e41f4b71Sopenharmony_ci using std::swap; 332e41f4b71Sopenharmony_ci swap(buf, other.buf); 333e41f4b71Sopenharmony_ci swap(size, other.size); 334e41f4b71Sopenharmony_ci } 335e41f4b71Sopenharmony_ci 336e41f4b71Sopenharmony_ciprivate: 337e41f4b71Sopenharmony_ci void Init(const char* buffer, size_t size) 338e41f4b71Sopenharmony_ci { 339e41f4b71Sopenharmony_ci this->buf = new char[size]; 340e41f4b71Sopenharmony_ci memcpy(this->buf, buffer, size); 341e41f4b71Sopenharmony_ci this->size = size; 342e41f4b71Sopenharmony_ci } 343e41f4b71Sopenharmony_ci 344e41f4b71Sopenharmony_ci char* buf; 345e41f4b71Sopenharmony_ci size_t size; 346e41f4b71Sopenharmony_ci}; 347e41f4b71Sopenharmony_ci``` 348e41f4b71Sopenharmony_ci 349e41f4b71Sopenharmony_ciHowever, failure to provide the move constructor and move assignment operator is usually not an error, but a missed optimization opportunity. 350e41f4b71Sopenharmony_ci 351e41f4b71Sopenharmony_ci**Rule of zero** 352e41f4b71Sopenharmony_ci 353e41f4b71Sopenharmony_ciIf a class does not need to deal exclusively with resource ownership, the class should not have custom destructors, copy/move constructors, or copy/move assignment operators. 354e41f4b71Sopenharmony_ci 355e41f4b71Sopenharmony_ci```cpp 356e41f4b71Sopenharmony_ciclass Foo { 357e41f4b71Sopenharmony_cipublic: 358e41f4b71Sopenharmony_ci Foo(const std::string& text) : text(text) {} 359e41f4b71Sopenharmony_ci 360e41f4b71Sopenharmony_ciprivate: 361e41f4b71Sopenharmony_ci std::string text; 362e41f4b71Sopenharmony_ci}; 363e41f4b71Sopenharmony_ci``` 364e41f4b71Sopenharmony_ci 365e41f4b71Sopenharmony_ciAs long as a copy constructor, copy assignment operator, or destructor is declared for a class, the compiler will not implicitly generate move constructors or move assignment operators. As a result, the move operation of this class becomes a copy operation at a higher cost. As long as a move constructor or move assignment operator is declared for a class, the compiler will define the implicitly generated copy constructor or copy assignment operator as deleted. As a result, the class can only be moved but cannot be copied. Therefore, if any of the functions is declared, all the other functions should be declared to avoid unexpected results. 366e41f4b71Sopenharmony_ci 367e41f4b71Sopenharmony_ciLikewise, if a base class needs to define the virtual destructor as public, all related special member functions need to be implicitly defined: 368e41f4b71Sopenharmony_ci 369e41f4b71Sopenharmony_ci```cpp 370e41f4b71Sopenharmony_ciclass Base { 371e41f4b71Sopenharmony_cipublic: 372e41f4b71Sopenharmony_ci ... 373e41f4b71Sopenharmony_ci Base(const Base&) = default; 374e41f4b71Sopenharmony_ci Base& operator=(const Base&) = default; 375e41f4b71Sopenharmony_ci Base(Base&&) = default; 376e41f4b71Sopenharmony_ci Base& operator=(Base&&) = default; 377e41f4b71Sopenharmony_ci virtual ~Base() = default; 378e41f4b71Sopenharmony_ci ... 379e41f4b71Sopenharmony_ci}; 380e41f4b71Sopenharmony_ci``` 381e41f4b71Sopenharmony_ci 382e41f4b71Sopenharmony_ciHowever, if a copy constructor/copy assignment operator is declared for a base class, slicing may occur. Therefore, the copy constructor/copy assignment operator in the base class is often explicitly defined as deleted, and other special member functions are also explicitly defined as deleted: 383e41f4b71Sopenharmony_ci 384e41f4b71Sopenharmony_ci```cpp 385e41f4b71Sopenharmony_ciclass Base { 386e41f4b71Sopenharmony_cipublic: 387e41f4b71Sopenharmony_ci ... 388e41f4b71Sopenharmony_ci Base(const Base&) = delete; 389e41f4b71Sopenharmony_ci Base& operator=(const Base&) = delete; 390e41f4b71Sopenharmony_ci Base(Base&&) = delete; 391e41f4b71Sopenharmony_ci Base& operator=(Base&&) = delete; 392e41f4b71Sopenharmony_ci virtual ~Base() = default; 393e41f4b71Sopenharmony_ci ... 394e41f4b71Sopenharmony_ci}; 395e41f4b71Sopenharmony_ci``` 396e41f4b71Sopenharmony_ci 397e41f4b71Sopenharmony_ci## The copy constructor, copy assignment operator, move constructor, and move assignment operator in the base class must be defined as non-public or deleted 398e41f4b71Sopenharmony_ci 399e41f4b71Sopenharmony_ci**\[Description]** 400e41f4b71Sopenharmony_ci 401e41f4b71Sopenharmony_ciSlicing occurs if a derived class object is directly assigned to a base class object. In this case, only the base class part is copied or moved, which undermines polymorphism. 402e41f4b71Sopenharmony_ci 403e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 404e41f4b71Sopenharmony_ci 405e41f4b71Sopenharmony_ciIn the following code, the copy constructor and copy assignment operator of the base class are declared as default. Slicing occurs if a derived class object is assigned to the base class object. The copy constructor and copy assignment operator can be declared as deleted so that the compiler can check such assignment behavior. 406e41f4b71Sopenharmony_ci 407e41f4b71Sopenharmony_ci```cpp 408e41f4b71Sopenharmony_ciclass Base { 409e41f4b71Sopenharmony_cipublic: 410e41f4b71Sopenharmony_ci Base() = default; 411e41f4b71Sopenharmony_ci Base(const Base&) = default; 412e41f4b71Sopenharmony_ci Base& operator=(const Base&) = default; 413e41f4b71Sopenharmony_ci ... 414e41f4b71Sopenharmony_ci virtual void Fun() { std::cout << "Base" << std::endl; } 415e41f4b71Sopenharmony_ci}; 416e41f4b71Sopenharmony_ci 417e41f4b71Sopenharmony_ciclass Derived : public Base { 418e41f4b71Sopenharmony_ci ... 419e41f4b71Sopenharmony_ci void Fun() override { std::cout << "Derived" << std::endl; } 420e41f4b71Sopenharmony_ci}; 421e41f4b71Sopenharmony_ci 422e41f4b71Sopenharmony_civoid Foo(const Base& base) 423e41f4b71Sopenharmony_ci{ 424e41f4b71Sopenharmony_ci Base other = base; // Noncompliant: Slicing occurs. 425e41f4b71Sopenharmony_ci other.Fun(); // The Fun() function of the base class is called. 426e41f4b71Sopenharmony_ci} 427e41f4b71Sopenharmony_ciDerived d; 428e41f4b71Sopenharmony_ciFoo(d); 429e41f4b71Sopenharmony_ci``` 430e41f4b71Sopenharmony_ci 431e41f4b71Sopenharmony_ci## The resources of the source object must be correctly reset in move constructors and move assignment operators 432e41f4b71Sopenharmony_ci 433e41f4b71Sopenharmony_ci**\[Description]** 434e41f4b71Sopenharmony_ci 435e41f4b71Sopenharmony_ciThe move constructor and move assignment operator move the ownership of a resource from one object to another. Once the resource is moved, the resource of the source object should be reset correctly. This can prevent the source object from freeing the moved resources in destructors. 436e41f4b71Sopenharmony_ci 437e41f4b71Sopenharmony_ciSome non-resource data can be retained in the moved object, but the moved object must be in a state that can be properly destructed. Therefore, after an object is moved, do not reply on the value of the moved object unless the object is explicitly specified. lvalue reference may lead to unexpected behavior. 438e41f4b71Sopenharmony_ci 439e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 440e41f4b71Sopenharmony_ci 441e41f4b71Sopenharmony_ci```cpp 442e41f4b71Sopenharmony_ciclass Foo { 443e41f4b71Sopenharmony_cipublic: 444e41f4b71Sopenharmony_ci ... 445e41f4b71Sopenharmony_ci Foo(Foo&& foo) noexcept : data(foo.data) 446e41f4b71Sopenharmony_ci { 447e41f4b71Sopenharmony_ci } 448e41f4b71Sopenharmony_ci 449e41f4b71Sopenharmony_ci Foo& operator=(Foo&& foo) 450e41f4b71Sopenharmony_ci { 451e41f4b71Sopenharmony_ci data = foo.data; 452e41f4b71Sopenharmony_ci return *this; 453e41f4b71Sopenharmony_ci } 454e41f4b71Sopenharmony_ci 455e41f4b71Sopenharmony_ci ~Foo() 456e41f4b71Sopenharmony_ci { 457e41f4b71Sopenharmony_ci delete[] data; 458e41f4b71Sopenharmony_ci } 459e41f4b71Sopenharmony_ci 460e41f4b71Sopenharmony_ciprivate: 461e41f4b71Sopenharmony_ci char* data = nullptr; 462e41f4b71Sopenharmony_ci}; 463e41f4b71Sopenharmony_ci``` 464e41f4b71Sopenharmony_ci 465e41f4b71Sopenharmony_ciThe move constructor and move assignment operator of the **Foo()** function do not correctly reset the resources of the source object. When the source object is destructed, the resources will be released. As a result, the resources taken over by the newly created object become invalid. 466e41f4b71Sopenharmony_ci 467e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 468e41f4b71Sopenharmony_ci 469e41f4b71Sopenharmony_ci```cpp 470e41f4b71Sopenharmony_ciclass Foo { 471e41f4b71Sopenharmony_cipublic: 472e41f4b71Sopenharmony_ci ... 473e41f4b71Sopenharmony_ci Foo(Foo&& foo) noexcept : data(foo.data) 474e41f4b71Sopenharmony_ci { 475e41f4b71Sopenharmony_ci foo.data = nullptr; 476e41f4b71Sopenharmony_ci } 477e41f4b71Sopenharmony_ci 478e41f4b71Sopenharmony_ci Foo& operator=(Foo&& foo) 479e41f4b71Sopenharmony_ci { 480e41f4b71Sopenharmony_ci if (this == &foo) { 481e41f4b71Sopenharmony_ci return *this; 482e41f4b71Sopenharmony_ci } 483e41f4b71Sopenharmony_ci delete[] data; 484e41f4b71Sopenharmony_ci data = foo.data; 485e41f4b71Sopenharmony_ci foo.data = nullptr; 486e41f4b71Sopenharmony_ci return *this; 487e41f4b71Sopenharmony_ci } 488e41f4b71Sopenharmony_ci 489e41f4b71Sopenharmony_ci ~Foo() 490e41f4b71Sopenharmony_ci { 491e41f4b71Sopenharmony_ci delete[] data; 492e41f4b71Sopenharmony_ci } 493e41f4b71Sopenharmony_ci 494e41f4b71Sopenharmony_ciprivate: 495e41f4b71Sopenharmony_ci char* data = nullptr; 496e41f4b71Sopenharmony_ci}; 497e41f4b71Sopenharmony_ci``` 498e41f4b71Sopenharmony_ci 499e41f4b71Sopenharmony_ci In some standard libraries, the implementation of std::string may implement the short string optimization (SSO). The content of the character string to be moved may not be altered during the implementation of move semantics. As a result, the output of the following code may not be the expected b but ab, causing compatibility issues. 500e41f4b71Sopenharmony_ci 501e41f4b71Sopenharmony_ci```cpp 502e41f4b71Sopenharmony_cistd::string str{"a"}; 503e41f4b71Sopenharmony_cistd::string other = std::move(str); 504e41f4b71Sopenharmony_ci 505e41f4b71Sopenharmony_cistr.append(1, 'b'); 506e41f4b71Sopenharmony_cistd::cout << str << std::endl; 507e41f4b71Sopenharmony_ci``` 508e41f4b71Sopenharmony_ci 509e41f4b71Sopenharmony_ci## The base class destructor must be declared as virtual when a derived class is released through a base class pointer 510e41f4b71Sopenharmony_ci 511e41f4b71Sopenharmony_ci**\[Description]** 512e41f4b71Sopenharmony_ci 513e41f4b71Sopenharmony_ciThe destructor of the derived class can be called through polymorphism only when the base class destructor is declared as virtual. If the base class destructor is not declared as virtual, only the base class destructor (instead of the derived class destructor) is called when the derived class is released through a base class pointer, causing memory leaks. 514e41f4b71Sopenharmony_ci 515e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 516e41f4b71Sopenharmony_ci 517e41f4b71Sopenharmony_ciMemory leaks occur because the base class destructor is not declared as virtual. 518e41f4b71Sopenharmony_ci 519e41f4b71Sopenharmony_ci```cpp 520e41f4b71Sopenharmony_ciclass Base { 521e41f4b71Sopenharmony_cipublic: 522e41f4b71Sopenharmony_ci Base() = default; 523e41f4b71Sopenharmony_ci ~Base() { std::cout << "~Base" << std::endl; } 524e41f4b71Sopenharmony_ci virtual std::string GetVersion() = 0; 525e41f4b71Sopenharmony_ci}; 526e41f4b71Sopenharmony_ciclass Derived : public Base { 527e41f4b71Sopenharmony_cipublic: 528e41f4b71Sopenharmony_ci Derived() 529e41f4b71Sopenharmony_ci { 530e41f4b71Sopenharmony_ci const size_t numberCount = 100; 531e41f4b71Sopenharmony_ci numbers = new int[numberCount]; 532e41f4b71Sopenharmony_ci } 533e41f4b71Sopenharmony_ci 534e41f4b71Sopenharmony_ci ~Derived() 535e41f4b71Sopenharmony_ci { 536e41f4b71Sopenharmony_ci delete[] numbers; 537e41f4b71Sopenharmony_ci std::cout << "~Derived" << std::endl; 538e41f4b71Sopenharmony_ci } 539e41f4b71Sopenharmony_ci 540e41f4b71Sopenharmony_ci std::string GetVersion() 541e41f4b71Sopenharmony_ci { 542e41f4b71Sopenharmony_ci return std::string("hello!"); 543e41f4b71Sopenharmony_ci } 544e41f4b71Sopenharmony_ci 545e41f4b71Sopenharmony_ciprivate: 546e41f4b71Sopenharmony_ci int* numbers; 547e41f4b71Sopenharmony_ci}; 548e41f4b71Sopenharmony_civoid Foo() 549e41f4b71Sopenharmony_ci{ 550e41f4b71Sopenharmony_ci Base* base = new Derived(); 551e41f4b71Sopenharmony_ci delete base; // The base class destructor is called, causing resource leaks. 552e41f4b71Sopenharmony_ci} 553e41f4b71Sopenharmony_ci``` 554e41f4b71Sopenharmony_ci 555e41f4b71Sopenharmony_ci## Avoid slicing during object assignment and initialization 556e41f4b71Sopenharmony_ci 557e41f4b71Sopenharmony_ci**\[Description]** 558e41f4b71Sopenharmony_ci 559e41f4b71Sopenharmony_ciSlicing occurs when a derived class object is assigned to a base class object, damaging polymorphism. 560e41f4b71Sopenharmony_ci 561e41f4b71Sopenharmony_ciIf the object needs to be sliced, it is recommended that an explicit operation be defined for slicing, thereby avoiding misunderstanding and improving maintainability. 562e41f4b71Sopenharmony_ci 563e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 564e41f4b71Sopenharmony_ci 565e41f4b71Sopenharmony_ci```cpp 566e41f4b71Sopenharmony_ciclass Base { 567e41f4b71Sopenharmony_ci virtual void Fun(); 568e41f4b71Sopenharmony_ci}; 569e41f4b71Sopenharmony_ci 570e41f4b71Sopenharmony_ciclass Derived : public Base { 571e41f4b71Sopenharmony_ci ... 572e41f4b71Sopenharmony_ci}; 573e41f4b71Sopenharmony_civoid Foo(const Base& base) 574e41f4b71Sopenharmony_ci{ 575e41f4b71Sopenharmony_ci Base other = base; // Noncompliant: Slicing occurs. 576e41f4b71Sopenharmony_ci other.Fun(); // The Fun() function of the base class is called. 577e41f4b71Sopenharmony_ci} 578e41f4b71Sopenharmony_ciDerived d; 579e41f4b71Sopenharmony_ciBase b{d}; // Noncompliant: Only base is constructed. 580e41f4b71Sopenharmony_cib = d; // Noncompliant: Assigned only to base. 581e41f4b71Sopenharmony_ci 582e41f4b71Sopenharmony_ciFoo(d); 583e41f4b71Sopenharmony_ci``` 584e41f4b71Sopenharmony_ci 585e41f4b71Sopenharmony_ci# Expressions and Statements 586e41f4b71Sopenharmony_ci 587e41f4b71Sopenharmony_ci## Ensure that objects have been initialized before being used 588e41f4b71Sopenharmony_ci 589e41f4b71Sopenharmony_ci**\[Description]** 590e41f4b71Sopenharmony_ci 591e41f4b71Sopenharmony_ciInitialization is the process of setting the expected value for an object by means of explicit initialization, default constructor initialization, and value assignment. Reading an uninitialized value may result in undefined behaviour. Therefore, ensure that objects have been initialized before being used. 592e41f4b71Sopenharmony_ci 593e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 594e41f4b71Sopenharmony_ci 595e41f4b71Sopenharmony_ci```cpp 596e41f4b71Sopenharmony_civoid Bar(int data); 597e41f4b71Sopenharmony_ci... 598e41f4b71Sopenharmony_civoid Foo() 599e41f4b71Sopenharmony_ci{ 600e41f4b71Sopenharmony_ci int data; 601e41f4b71Sopenharmony_ci Bar(data); // Noncompliant: Not initialized before being used 602e41f4b71Sopenharmony_ci ... 603e41f4b71Sopenharmony_ci} 604e41f4b71Sopenharmony_ci``` 605e41f4b71Sopenharmony_ci 606e41f4b71Sopenharmony_ciIf there are different branches, ensure that all branches are initialized before being used as values. 607e41f4b71Sopenharmony_ci 608e41f4b71Sopenharmony_ci```cpp 609e41f4b71Sopenharmony_civoid Bar(int data); 610e41f4b71Sopenharmony_ci... 611e41f4b71Sopenharmony_civoid Foo(int condition) 612e41f4b71Sopenharmony_ci{ 613e41f4b71Sopenharmony_ci int data; 614e41f4b71Sopenharmony_ci if (condition > 0) { 615e41f4b71Sopenharmony_ci data = CUSTOMIZED_SIZE; 616e41f4b71Sopenharmony_ci } 617e41f4b71Sopenharmony_ci Bar(data); // Noncompliant: Values not initialized for some branches 618e41f4b71Sopenharmony_ci ... 619e41f4b71Sopenharmony_ci} 620e41f4b71Sopenharmony_ci``` 621e41f4b71Sopenharmony_ci 622e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 623e41f4b71Sopenharmony_ci 624e41f4b71Sopenharmony_ci```cpp 625e41f4b71Sopenharmony_civoid Bar(int data); 626e41f4b71Sopenharmony_ci... 627e41f4b71Sopenharmony_civoid Foo() 628e41f4b71Sopenharmony_ci{ 629e41f4b71Sopenharmony_ci int data{0}; // Compliant: Explicit initialization 630e41f4b71Sopenharmony_ci Bar(data); 631e41f4b71Sopenharmony_ci ... 632e41f4b71Sopenharmony_ci} 633e41f4b71Sopenharmony_civoid InitData(int& data); 634e41f4b71Sopenharmony_ci... 635e41f4b71Sopenharmony_civoid Foo() 636e41f4b71Sopenharmony_ci{ 637e41f4b71Sopenharmony_ci int data; 638e41f4b71Sopenharmony_ci InitData(data); // Compliant: Initialization using functions 639e41f4b71Sopenharmony_ci ... 640e41f4b71Sopenharmony_ci} 641e41f4b71Sopenharmony_cistd::string data; // Compliant: Default constructor initialization 642e41f4b71Sopenharmony_ci... 643e41f4b71Sopenharmony_ci``` 644e41f4b71Sopenharmony_ci 645e41f4b71Sopenharmony_ci## Avoid using reinterpret\_cast 646e41f4b71Sopenharmony_ci 647e41f4b71Sopenharmony_ci**\[Description]** 648e41f4b71Sopenharmony_ci 649e41f4b71Sopenharmony_ci`reinterpret_cast` is used to convert irrelevant types. `reinterpret_cast` tries to cast one type to another type, which destroys the type of security and reliability. It is an unsafe conversion. It is advised to use reinterpret\_cast as little as possible. 650e41f4b71Sopenharmony_ci 651e41f4b71Sopenharmony_ci## Avoid using const\_cast 652e41f4b71Sopenharmony_ci 653e41f4b71Sopenharmony_ci**\[Description]** 654e41f4b71Sopenharmony_ci 655e41f4b71Sopenharmony_ci`const_cast` is used to remove the `const` and `volatile` attributes of an object. 656e41f4b71Sopenharmony_ci 657e41f4b71Sopenharmony_ciUsing a pointer or reference converted by **const\_cast** to modify a **const** or **volatile** object will result in undefined behavior. 658e41f4b71Sopenharmony_ci 659e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 660e41f4b71Sopenharmony_ci 661e41f4b71Sopenharmony_ci```cpp 662e41f4b71Sopenharmony_ciconst int i = 1024; 663e41f4b71Sopenharmony_ciint* p = const_cast<int*>(&i); 664e41f4b71Sopenharmony_ci*p = 2048; // Undefined behavior 665e41f4b71Sopenharmony_ciclass Foo { 666e41f4b71Sopenharmony_cipublic: 667e41f4b71Sopenharmony_ci void SetValue(int v) { value = v; } 668e41f4b71Sopenharmony_ci 669e41f4b71Sopenharmony_ciprivate: 670e41f4b71Sopenharmony_ci int value{0}; 671e41f4b71Sopenharmony_ci}; 672e41f4b71Sopenharmony_ci 673e41f4b71Sopenharmony_ciint main() 674e41f4b71Sopenharmony_ci{ 675e41f4b71Sopenharmony_ci const Foo foo; 676e41f4b71Sopenharmony_ci Foo* p = const_cast<Foo*>(&foo); 677e41f4b71Sopenharmony_ci p->SetValue(2); // Undefined behavior 678e41f4b71Sopenharmony_ci return 0; 679e41f4b71Sopenharmony_ci} 680e41f4b71Sopenharmony_ci``` 681e41f4b71Sopenharmony_ci 682e41f4b71Sopenharmony_ci## Ensure no overflows in signed integer operations 683e41f4b71Sopenharmony_ci 684e41f4b71Sopenharmony_ci**\[Description]** 685e41f4b71Sopenharmony_ci 686e41f4b71Sopenharmony_ciIn the C++ standard, signed integer overflow is undefined behavior. Therefore, signed integer overflows are handled differently in implementations. For example, after defining a signed integer type as a modulus, the compiler may not detect integer overflows. 687e41f4b71Sopenharmony_ci 688e41f4b71Sopenharmony_ciUsing overflowed values may cause out-of-bounds read/write risks in the buffer. For security purposes, ensure that operations do not cause overflows when signed integers in external data are used in the following scenarios: 689e41f4b71Sopenharmony_ci 690e41f4b71Sopenharmony_ci- Integer operand of pointer operation (pointer offset value) 691e41f4b71Sopenharmony_ci- Array index 692e41f4b71Sopenharmony_ci- Length of the variable-length array (and the length operation expression) 693e41f4b71Sopenharmony_ci- Memory copy length 694e41f4b71Sopenharmony_ci- Parameter of the memory allocation function 695e41f4b71Sopenharmony_ci- Loop judgment condition 696e41f4b71Sopenharmony_ci 697e41f4b71Sopenharmony_ciInteger promotion needs to be considered when the operation is performed for the integer types whose precision is less than **int**. Programmers also need to master integer conversion rules, including implicit conversion rules, to design secure arithmetic operations. 698e41f4b71Sopenharmony_ci 699e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 700e41f4b71Sopenharmony_ci 701e41f4b71Sopenharmony_ciIn the following code example, the integers involved in the subtraction operation are external data and are not validated before being used. As a result, integer overflow may occur, which further results in buffer overflow due to memory copy operations. 702e41f4b71Sopenharmony_ci 703e41f4b71Sopenharmony_ci```cpp 704e41f4b71Sopenharmony_ciunsigned char* content = ... // Pointer to the packet header 705e41f4b71Sopenharmony_cisize_t contentSize = ... // Total length of the buffer 706e41f4b71Sopenharmony_ciint totalLen = ... // Total length of the packet 707e41f4b71Sopenharmony_ciint skipLen = ... // Data length that needs to be ignored from the parsed message 708e41f4b71Sopenharmony_ci 709e41f4b71Sopenharmony_cistd::vector<unsigned char> dest; 710e41f4b71Sopenharmony_ci 711e41f4b71Sopenharmony_ci// Using totalLen - skipLen to calculate the length of the remaining data is likely to cause integer overflows. 712e41f4b71Sopenharmony_cistd::copy_n(&content[skipLen], totalLen - skipLen, std::back_inserter(dest)); 713e41f4b71Sopenharmony_ci... 714e41f4b71Sopenharmony_ci``` 715e41f4b71Sopenharmony_ci 716e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 717e41f4b71Sopenharmony_ci 718e41f4b71Sopenharmony_ciIn the following code example, code is refactored to use the variable of the `size_t` type to indicate the data length and check whether the external data length is valid. 719e41f4b71Sopenharmony_ci 720e41f4b71Sopenharmony_ci```cpp 721e41f4b71Sopenharmony_ciunsigned char* content = ... // Pointer to the packet header 722e41f4b71Sopenharmony_cisize_t contentSize = ... // Total length of the buffer 723e41f4b71Sopenharmony_cisize_t totalLen = ... // Total length of the packet 724e41f4b71Sopenharmony_cisize_t skipLen = ... // Data length that needs to be ignored from the parsed message 725e41f4b71Sopenharmony_ci 726e41f4b71Sopenharmony_ciif (skipLen >= totalLen || totalLen > contentSize) { 727e41f4b71Sopenharmony_ci ... // Error handling 728e41f4b71Sopenharmony_ci} 729e41f4b71Sopenharmony_ci 730e41f4b71Sopenharmony_cistd::vector<unsigned char> dest; 731e41f4b71Sopenharmony_cistd::copy_n(&content[skipLen], totalLen - skipLen, std::back_inserter(dest)); 732e41f4b71Sopenharmony_ci... 733e41f4b71Sopenharmony_ci``` 734e41f4b71Sopenharmony_ci 735e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 736e41f4b71Sopenharmony_ci 737e41f4b71Sopenharmony_ciIn the following code example, the value range of external data is validated. However, the second type is `int`, and `std::numeric_limits<unsigned long>::max()` is incorrectly used as a validation condition. As a result, integer overflow occurs. 738e41f4b71Sopenharmony_ci 739e41f4b71Sopenharmony_ci```cpp 740e41f4b71Sopenharmony_ciint second = ... // External data 741e41f4b71Sopenharmony_ci 742e41f4b71Sopenharmony_ci //The value range of unsigned long is incorrectly used for upper limit validation. 743e41f4b71Sopenharmony_ciif (second < 0 || second > (std::numeric_limits<unsigned long>::max() / 1000)) { 744e41f4b71Sopenharmony_ci return -1; 745e41f4b71Sopenharmony_ci} 746e41f4b71Sopenharmony_ciint millisecond = second * 1000; // Integer overflow may occur. 747e41f4b71Sopenharmony_ci... 748e41f4b71Sopenharmony_ci``` 749e41f4b71Sopenharmony_ci 750e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 751e41f4b71Sopenharmony_ci 752e41f4b71Sopenharmony_ciOne option is to change the second type to `unsigned long`. This solution is applicable to the scenario where the new variable type is more fit for service logic. 753e41f4b71Sopenharmony_ci 754e41f4b71Sopenharmony_ci```cpp 755e41f4b71Sopenharmony_ciunsigned long second = ... // Refactor the type to unsigned long. 756e41f4b71Sopenharmony_ci 757e41f4b71Sopenharmony_ciif (second > (std::numeric_limits<unsigned long>::max() / 1000)) { 758e41f4b71Sopenharmony_ci return -1; 759e41f4b71Sopenharmony_ci} 760e41f4b71Sopenharmony_ciint millisecond = second * 1000; 761e41f4b71Sopenharmony_ci... 762e41f4b71Sopenharmony_ci``` 763e41f4b71Sopenharmony_ci 764e41f4b71Sopenharmony_ciAnother method is to change the upper limit to `std::numeric_limits<int>::max()`. 765e41f4b71Sopenharmony_ci 766e41f4b71Sopenharmony_ci```cpp 767e41f4b71Sopenharmony_ciint second = ... // External data 768e41f4b71Sopenharmony_ci 769e41f4b71Sopenharmony_ciif (second < 0 || second > (std::numeric_limits<int>::max() / 1000)) { 770e41f4b71Sopenharmony_ci return -1; 771e41f4b71Sopenharmony_ci} 772e41f4b71Sopenharmony_ciint millisecond = second * 1000; 773e41f4b71Sopenharmony_ci``` 774e41f4b71Sopenharmony_ci 775e41f4b71Sopenharmony_ci**\[Impact]** 776e41f4b71Sopenharmony_ci 777e41f4b71Sopenharmony_ciInteger overflows may cause buffer overflows and arbitrary code execution. 778e41f4b71Sopenharmony_ci 779e41f4b71Sopenharmony_ci## Ensure that unsigned integer operations do not wrap 780e41f4b71Sopenharmony_ci 781e41f4b71Sopenharmony_ci**\[Description]** 782e41f4b71Sopenharmony_ci 783e41f4b71Sopenharmony_ciInteger wrap may occur in the arithmetic operation results of unsigned integers, which may cause risks such as out-of-bounds read/write in the buffer. For security purposes, ensure that operations do not cause wrapping when unsigned integers in external data are used in the following scenarios: 784e41f4b71Sopenharmony_ci 785e41f4b71Sopenharmony_ci- Pointer offset value (integer operands in pointer arithmetic operations) 786e41f4b71Sopenharmony_ci- Array index value 787e41f4b71Sopenharmony_ci- Memory copy length 788e41f4b71Sopenharmony_ci- Parameter of the memory allocation function 789e41f4b71Sopenharmony_ci- Loop judgment condition 790e41f4b71Sopenharmony_ci 791e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 792e41f4b71Sopenharmony_ci 793e41f4b71Sopenharmony_ciIn the following code example, the program checks whether the total length of the next sub-packet and the processed packet exceeds the maximum packet length. The addition operation in the check condition may cause integer wrapping, causing potential validation bypassing issues. 794e41f4b71Sopenharmony_ci 795e41f4b71Sopenharmony_ci```cpp 796e41f4b71Sopenharmony_cisize_t totalLen = ... // Total length of the packet 797e41f4b71Sopenharmony_cisize_t readLen = 0; // Record the length of the processed packet. 798e41f4b71Sopenharmony_ci... 799e41f4b71Sopenharmony_cisize_t pktLen = ParsePktLen(); // Length of the next sub-packet parsed from the network packet 800e41f4b71Sopenharmony_ciif (readLen + pktLen > totalLen) { // Integer wrapping may occur. 801e41f4b71Sopenharmony_ci ... // Error handling 802e41f4b71Sopenharmony_ci} 803e41f4b71Sopenharmony_ci... 804e41f4b71Sopenharmony_cireadLen += pktLen; 805e41f4b71Sopenharmony_ci... 806e41f4b71Sopenharmony_ci``` 807e41f4b71Sopenharmony_ci 808e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 809e41f4b71Sopenharmony_ci 810e41f4b71Sopenharmony_ciThe readLen variable is the length of the processed packet and is definitely less than totalLen. Therefore, the use of the subtraction operation instead of the addition operation will not bypass the condition check. 811e41f4b71Sopenharmony_ci 812e41f4b71Sopenharmony_ci```cpp 813e41f4b71Sopenharmony_cisize_t totalLen = ... // Total length of the packet 814e41f4b71Sopenharmony_cisize_t readLen = 0; // Record the length of the processed packet. 815e41f4b71Sopenharmony_ci... 816e41f4b71Sopenharmony_cisize_t pktLen = ParsePktLen(); // From the network packet 817e41f4b71Sopenharmony_ciif (pktLen > totalLen - readLen) { 818e41f4b71Sopenharmony_ci ... // Error handling 819e41f4b71Sopenharmony_ci} 820e41f4b71Sopenharmony_ci... 821e41f4b71Sopenharmony_cireadLen += pktLen; 822e41f4b71Sopenharmony_ci... 823e41f4b71Sopenharmony_ci``` 824e41f4b71Sopenharmony_ci 825e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 826e41f4b71Sopenharmony_ci 827e41f4b71Sopenharmony_ciIn the following code example, integer wrapping may occur in the operation of len validation, resulting in condition check bypassing. 828e41f4b71Sopenharmony_ci 829e41f4b71Sopenharmony_ci```cpp 830e41f4b71Sopenharmony_cisize_t len =... // From the user-mode input 831e41f4b71Sopenharmony_ci 832e41f4b71Sopenharmony_ciif (SCTP_SIZE_MAX - len < sizeof(SctpAuthBytes)) { // Integer wrapping may occur in subtraction. 833e41f4b71Sopenharmony_ci ... // Error handling 834e41f4b71Sopenharmony_ci} 835e41f4b71Sopenharmony_ci... = kmalloc(sizeof(SctpAuthBytes) + len, gfp); // Integer wrapping may occur. 836e41f4b71Sopenharmony_ci... 837e41f4b71Sopenharmony_ci``` 838e41f4b71Sopenharmony_ci 839e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 840e41f4b71Sopenharmony_ci 841e41f4b71Sopenharmony_ciIn the following code example, the subtraction operation is relocated (ensure that the value of the subtraction expression is not reversed during compilation) to avoid integer wrapping. 842e41f4b71Sopenharmony_ci 843e41f4b71Sopenharmony_ci```cpp 844e41f4b71Sopenharmony_cisize_t len =... // From the user-mode input 845e41f4b71Sopenharmony_ci 846e41f4b71Sopenharmony_ciif (len > SCTP_SIZE_MAX - sizeof(SctpAuthBytes)) { // Ensure no integer wrapping for the subtraction expression value during compilation. 847e41f4b71Sopenharmony_ci ... // Error handling 848e41f4b71Sopenharmony_ci} 849e41f4b71Sopenharmony_ci... = kmalloc(sizeof(SctpAuthBytes) + len, gfp); 850e41f4b71Sopenharmony_ci... 851e41f4b71Sopenharmony_ci``` 852e41f4b71Sopenharmony_ci 853e41f4b71Sopenharmony_ci**\[Exception]** 854e41f4b71Sopenharmony_ci 855e41f4b71Sopenharmony_ciUnsigned integers can exhibit modulo behavior (wrapping) when necessary for the proper execution of the program. It is recommended that the variable declaration and each operation on that integer be clearly commented as supporting modulo behavior. 856e41f4b71Sopenharmony_ci 857e41f4b71Sopenharmony_ci**\[Impact]** 858e41f4b71Sopenharmony_ci 859e41f4b71Sopenharmony_ciInteger wrapping is likely to cause buffer overflows and arbitrary code execution. 860e41f4b71Sopenharmony_ci 861e41f4b71Sopenharmony_ci## Ensure that division and remainder operations do not cause divide-by-zero errors 862e41f4b71Sopenharmony_ci 863e41f4b71Sopenharmony_ci**\[Description]** 864e41f4b71Sopenharmony_ci 865e41f4b71Sopenharmony_ciDivision remainder operations performed on integers with the divisor of zero are undefined behavior. Ensure that the divisor is not 0 in division and remainder operations. 866e41f4b71Sopenharmony_ci 867e41f4b71Sopenharmony_ciThe ISO/IEEE 754-1985 standard for binary floating-point arithmetic specifies the behavior and results of floating-point number division by zero. However, the presence of undefined behavior depends on whether the hardware and software environments comply with this standard. Therefore, before dividing a floating point number by zero, ensure that the hardware and software environments comply with the binary floating-point arithmetic. Otherwise, undefined behavior still exists. 868e41f4b71Sopenharmony_ci 869e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 870e41f4b71Sopenharmony_ci 871e41f4b71Sopenharmony_ci```c 872e41f4b71Sopenharmony_cisize_t a = ReadSize(); // From external data 873e41f4b71Sopenharmony_cisize_t b = 1000 / a; // Noncompliant: a may be 0 874e41f4b71Sopenharmony_cisize_t c = 1000 % a; // Noncompliant: a may be 0 875e41f4b71Sopenharmony_ci... 876e41f4b71Sopenharmony_ci``` 877e41f4b71Sopenharmony_ci 878e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 879e41f4b71Sopenharmony_ci 880e41f4b71Sopenharmony_ciIn the following code example, a=0 validation is added to prevent divide-by-zero errors. 881e41f4b71Sopenharmony_ci 882e41f4b71Sopenharmony_ci```c 883e41f4b71Sopenharmony_cisize_t a = ReadSize(); // From external data 884e41f4b71Sopenharmony_ciif (a == 0) { 885e41f4b71Sopenharmony_ci ... // Error handling 886e41f4b71Sopenharmony_ci} 887e41f4b71Sopenharmony_cisize_t b = 1000 / a; // Compliant: Ensure that a is not 0. 888e41f4b71Sopenharmony_cisize_t c = 1000 % a; // Compliant: Ensure that a is not 0. 889e41f4b71Sopenharmony_ci... 890e41f4b71Sopenharmony_ci``` 891e41f4b71Sopenharmony_ci 892e41f4b71Sopenharmony_ci**\[Impact]** 893e41f4b71Sopenharmony_ci 894e41f4b71Sopenharmony_ciDivide-by-zero errors are likely to cause DoS. 895e41f4b71Sopenharmony_ci 896e41f4b71Sopenharmony_ci## Bitwise operations can be performed only on unsigned integers 897e41f4b71Sopenharmony_ci 898e41f4b71Sopenharmony_ci**\[Description]** 899e41f4b71Sopenharmony_ci 900e41f4b71Sopenharmony_ciUndefined behavior may occur during bitwise operations on signed integers. To avoid undefined behavior, ensure that bitwise operations are performed only on unsigned integers. In addition, the unsigned integer type with less precision than **int** is promoted when a bitwise operation is performed on the unsigned integer. Then the bitwise operation is performed on the promoted integer. Therefore, beware of the bitwise operations on such unsigned integers to avoid unexpected results. The bitwise operators are as follows: 901e41f4b71Sopenharmony_ci 902e41f4b71Sopenharmony_ci- `~` (Complement operator) 903e41f4b71Sopenharmony_ci- `&` (AND) 904e41f4b71Sopenharmony_ci- `|` (OR) 905e41f4b71Sopenharmony_ci- `^` (XOR) 906e41f4b71Sopenharmony_ci- `>>` (Right shift operator) 907e41f4b71Sopenharmony_ci- `<<` (Left shift operator) 908e41f4b71Sopenharmony_ci- `&=` 909e41f4b71Sopenharmony_ci- `^=` 910e41f4b71Sopenharmony_ci- `|=` 911e41f4b71Sopenharmony_ci- `>>=` 912e41f4b71Sopenharmony_ci- `<<=` 913e41f4b71Sopenharmony_ci 914e41f4b71Sopenharmony_ciC++20 defines bitwise shift operations on signed integers, and such operations can be performed in compliance with C++20. 915e41f4b71Sopenharmony_ci 916e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 917e41f4b71Sopenharmony_ci 918e41f4b71Sopenharmony_ciIn versions earlier than C++20, the right shift operation `data >> 24` can be implemented as arithmetic (signed) shift or logic (unsigned) shift. If the value in `value << data` is a negative number or the result of the left shift operation is out of the representable range of the promoted integer type, undefined behavior occurs. 919e41f4b71Sopenharmony_ci 920e41f4b71Sopenharmony_ci```cpp 921e41f4b71Sopenharmony_ciint32_t data = ReadByte(); 922e41f4b71Sopenharmony_ciint32_t value = data >> 24; // The result of the right shift operation on a signed integer is implementation-defined. 923e41f4b71Sopenharmony_ci 924e41f4b71Sopenharmony_ci... // Check the valid data range. 925e41f4b71Sopenharmony_ci 926e41f4b71Sopenharmony_ciint32_t mask = value << data; // The left shift operation on a signed integer may cause undefined behavior. 927e41f4b71Sopenharmony_ci``` 928e41f4b71Sopenharmony_ci 929e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 930e41f4b71Sopenharmony_ci 931e41f4b71Sopenharmony_ci```cpp 932e41f4b71Sopenharmony_ciuint32_t data = static_cast<uint32_t>(ReadByte()); 933e41f4b71Sopenharmony_ciuint32_t value = data >> 24; // Bitwise operations are performed only on unsigned integers. 934e41f4b71Sopenharmony_ci 935e41f4b71Sopenharmony_ci... // Check the valid data range. 936e41f4b71Sopenharmony_ci 937e41f4b71Sopenharmony_ciuint32_t mask = value << data; 938e41f4b71Sopenharmony_ci``` 939e41f4b71Sopenharmony_ci 940e41f4b71Sopenharmony_ciIf bitwise operations are performed on unsigned integers with less precision than `int`, the operation results may be unexpected due to integer promotions. In this case, you need to immediately convert the operation results to the expected types to avoid unexpected results. 941e41f4b71Sopenharmony_ci 942e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 943e41f4b71Sopenharmony_ci 944e41f4b71Sopenharmony_ci```cpp 945e41f4b71Sopenharmony_ciuint8_t mask = 1; 946e41f4b71Sopenharmony_ciuint8_t value = (~mask) >> 4; // Noncompliant: The result of the ~ operation contains high-order data, which may not meet the expectation. 947e41f4b71Sopenharmony_ci``` 948e41f4b71Sopenharmony_ci 949e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 950e41f4b71Sopenharmony_ci 951e41f4b71Sopenharmony_ci```cpp 952e41f4b71Sopenharmony_ciuint8_t mask = 1; 953e41f4b71Sopenharmony_ciuint8_t value = (static_cast<uint8_t>(~mask)) >> 4; // Compliant: The result is converted to the expected type immediately after the ~ operation. 954e41f4b71Sopenharmony_ci``` 955e41f4b71Sopenharmony_ci 956e41f4b71Sopenharmony_ci**\[Exception]** 957e41f4b71Sopenharmony_ci 958e41f4b71Sopenharmony_ci- A signed integer constant or enumerated value used as a bit flag can be used as an operand for the \& and \| operators. 959e41f4b71Sopenharmony_ci 960e41f4b71Sopenharmony_ci```cpp 961e41f4b71Sopenharmony_ciint fd = open(fileName, O_CREAT | O_EXCL, S_IRWXU | S_IRUSR); 962e41f4b71Sopenharmony_ci``` 963e41f4b71Sopenharmony_ci 964e41f4b71Sopenharmony_ci- If a signed positive integer is known at compile time, it can be used as the right operand of a shift operator. 965e41f4b71Sopenharmony_ci 966e41f4b71Sopenharmony_ci```cpp 967e41f4b71Sopenharmony_ciconstexpr int SHIFT_BITS = 3; 968e41f4b71Sopenharmony_ci... 969e41f4b71Sopenharmony_ciuint32_t id = ...; 970e41f4b71Sopenharmony_ciuint32_t type = id >> SHIFT_BITS; 971e41f4b71Sopenharmony_ci``` 972e41f4b71Sopenharmony_ci 973e41f4b71Sopenharmony_ci# Resource Management 974e41f4b71Sopenharmony_ci 975e41f4b71Sopenharmony_ci## Ensure validation of external data that is used as an array index or memory operation length 976e41f4b71Sopenharmony_ci 977e41f4b71Sopenharmony_ci**\[Description]** 978e41f4b71Sopenharmony_ci 979e41f4b71Sopenharmony_ciWhen external data is used as an array index for memory access, the data size must be strictly validated to ensure that the array index is within the valid scope. Otherwise, serious errors may occur. Buffer overflows will occur if data is copied to the memory space insufficient for storing the data. To prevent such errors, limit the size of data to be copied based on the target capacity or ensure that the target capacity is sufficient to store the data to be copied. 980e41f4b71Sopenharmony_ci 981e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 982e41f4b71Sopenharmony_ci 983e41f4b71Sopenharmony_ciIn the following code example, the **SetDevId()** function has an off-by-one error. When index equals `DEV_NUM`, an element is written out of bounds. 984e41f4b71Sopenharmony_ci 985e41f4b71Sopenharmony_ci```cpp 986e41f4b71Sopenharmony_cistruct Dev { 987e41f4b71Sopenharmony_ci int id; 988e41f4b71Sopenharmony_ci char name[MAX_NAME_LEN]; 989e41f4b71Sopenharmony_ci}; 990e41f4b71Sopenharmony_ci 991e41f4b71Sopenharmony_cistatic Dev devs[DEV_NUM]; 992e41f4b71Sopenharmony_ci 993e41f4b71Sopenharmony_ciint SetDevId(size_t index, int id) 994e41f4b71Sopenharmony_ci{ 995e41f4b71Sopenharmony_ci if (index > DEV_NUM) { // Off-by-one error 996e41f4b71Sopenharmony_ci ... // Error handling 997e41f4b71Sopenharmony_ci } 998e41f4b71Sopenharmony_ci 999e41f4b71Sopenharmony_ci devs[index].id = id; 1000e41f4b71Sopenharmony_ci return 0; 1001e41f4b71Sopenharmony_ci} 1002e41f4b71Sopenharmony_ci``` 1003e41f4b71Sopenharmony_ci 1004e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1005e41f4b71Sopenharmony_ci 1006e41f4b71Sopenharmony_ciIn the following code example, the index validation condition is modified to avoid the off-by-one error. 1007e41f4b71Sopenharmony_ci 1008e41f4b71Sopenharmony_ci```cpp 1009e41f4b71Sopenharmony_cistruct Dev { 1010e41f4b71Sopenharmony_ci int id; 1011e41f4b71Sopenharmony_ci char name[MAX_NAME_LEN]; 1012e41f4b71Sopenharmony_ci}; 1013e41f4b71Sopenharmony_ci 1014e41f4b71Sopenharmony_cistatic Dev devs[DEV_NUM]; 1015e41f4b71Sopenharmony_ci 1016e41f4b71Sopenharmony_ciint SetDevId(size_t index, int id) 1017e41f4b71Sopenharmony_ci{ 1018e41f4b71Sopenharmony_ci if (index >= DEV_NUM) { 1019e41f4b71Sopenharmony_ci ... // Error handling 1020e41f4b71Sopenharmony_ci } 1021e41f4b71Sopenharmony_ci devs[index].id = id; 1022e41f4b71Sopenharmony_ci return 0; 1023e41f4b71Sopenharmony_ci} 1024e41f4b71Sopenharmony_ci``` 1025e41f4b71Sopenharmony_ci 1026e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1027e41f4b71Sopenharmony_ci 1028e41f4b71Sopenharmony_ciExternal input data may not be directly used as the memory copy length, but may be indirectly involved in memory copy operations. In the following code, **inputTable.count** is from external packets. It is used as the upper limit of the **for** loop body and indirectly involved in memory copy operations, instead of being directly used as the memory copy length. Buffer overflows may occur because the length is not validated. 1029e41f4b71Sopenharmony_ci 1030e41f4b71Sopenharmony_ci```cpp 1031e41f4b71Sopenharmony_cistruct ValueTable { 1032e41f4b71Sopenharmony_ci size_t count; 1033e41f4b71Sopenharmony_ci int val[MAX_NUMBERS]; 1034e41f4b71Sopenharmony_ci}; 1035e41f4b71Sopenharmony_ci 1036e41f4b71Sopenharmony_civoid ValueTableDup(const ValueTable& inputTable) 1037e41f4b71Sopenharmony_ci{ 1038e41f4b71Sopenharmony_ci ValueTable outputTable = {0, {0}}; 1039e41f4b71Sopenharmony_ci ... 1040e41f4b71Sopenharmony_ci for (size_t i = 0; i < inputTable.count; i++) { 1041e41f4b71Sopenharmony_ci outputTable.val[i] = inputTable.val[i]; 1042e41f4b71Sopenharmony_ci } 1043e41f4b71Sopenharmony_ci ... 1044e41f4b71Sopenharmony_ci} 1045e41f4b71Sopenharmony_ci``` 1046e41f4b71Sopenharmony_ci 1047e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1048e41f4b71Sopenharmony_ci 1049e41f4b71Sopenharmony_ciIn the following code example, **inputTable.count** is validated. 1050e41f4b71Sopenharmony_ci 1051e41f4b71Sopenharmony_ci```cpp 1052e41f4b71Sopenharmony_cistruct ValueTable { 1053e41f4b71Sopenharmony_ci size_t count; 1054e41f4b71Sopenharmony_ci int val[MAX_NUMBERS]; 1055e41f4b71Sopenharmony_ci}; 1056e41f4b71Sopenharmony_ci 1057e41f4b71Sopenharmony_civoid ValueTableDup(const ValueTable& inputTable) 1058e41f4b71Sopenharmony_ci{ 1059e41f4b71Sopenharmony_ci ValueTable outputTable = {0, {0}}; 1060e41f4b71Sopenharmony_ci ... 1061e41f4b71Sopenharmony_ci // Based on application scenarios, validate the cyclic length inputTable.count of external packets 1062e41f4b71Sopenharmony_ci // and the array size outputTable.val to prevent buffer overflows. 1063e41f4b71Sopenharmony_ci if (inputTable->count > 1064e41f4b71Sopenharmony_ci sizeof(outputTable.val) / sizeof(outputTable.val[0])) { 1065e41f4b71Sopenharmony_ci ... // Error handling 1066e41f4b71Sopenharmony_ci } 1067e41f4b71Sopenharmony_ci for (size_t i = 0; i < inputTable.count; i++) { 1068e41f4b71Sopenharmony_ci outputTable.val[i] = inputTable.val[i]; 1069e41f4b71Sopenharmony_ci } 1070e41f4b71Sopenharmony_ci ... 1071e41f4b71Sopenharmony_ci} 1072e41f4b71Sopenharmony_ci``` 1073e41f4b71Sopenharmony_ci 1074e41f4b71Sopenharmony_ci**\[Impact]** 1075e41f4b71Sopenharmony_ci 1076e41f4b71Sopenharmony_ciIf the length of the copied data is externally controllable, buffer overflows may occur during data copy operations, which may cause arbitrary code execution vulnerabilities. 1077e41f4b71Sopenharmony_ci 1078e41f4b71Sopenharmony_ci## Verify the requested memory size before requesting memory 1079e41f4b71Sopenharmony_ci 1080e41f4b71Sopenharmony_ci**\[Description]** 1081e41f4b71Sopenharmony_ci 1082e41f4b71Sopenharmony_ciWhen the requested memory size is an external input, it must be verified to prevent the request for zero-length memory or excessive and illegal memory requests. This is because memory resources are limited and can be exhausted. If the requested memory is too large (memory requested at a time is too large, or requested multiple times in a loop), resources may be used up unexpectedly. Unexpected buffer allocation may result from incorrect parameter values, improper range checks, integer overflows, or truncation. If memory requests are controlled by attackers, security issues such as buffer overflows may occur. 1083e41f4b71Sopenharmony_ci 1084e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1085e41f4b71Sopenharmony_ci 1086e41f4b71Sopenharmony_ciIn the following code example, the memory space specified by **size** is dynamically allocated. However, **size** is not validated. 1087e41f4b71Sopenharmony_ci 1088e41f4b71Sopenharmony_ci```c 1089e41f4b71Sopenharmony_ci// size is not validated before being passed into to the DoSomething() function. 1090e41f4b71Sopenharmony_ciint DoSomething(size_t size) 1091e41f4b71Sopenharmony_ci{ 1092e41f4b71Sopenharmony_ci ... 1093e41f4b71Sopenharmony_ci char* buffer = new char[size]; // size is not validated before being used in this function. 1094e41f4b71Sopenharmony_ci ... 1095e41f4b71Sopenharmony_ci delete[] buffer; 1096e41f4b71Sopenharmony_ci} 1097e41f4b71Sopenharmony_ci``` 1098e41f4b71Sopenharmony_ci 1099e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1100e41f4b71Sopenharmony_ci 1101e41f4b71Sopenharmony_ciIn the following code example, before the memory space specified by **size** is dynamically allocated, the validity check required by the program is performed. 1102e41f4b71Sopenharmony_ci 1103e41f4b71Sopenharmony_ci```c 1104e41f4b71Sopenharmony_ci// size is not validated before being passed into to the DoSomething() function. 1105e41f4b71Sopenharmony_ciint DoSomething(size_t size) 1106e41f4b71Sopenharmony_ci{ 1107e41f4b71Sopenharmony_ci // In this function, size is validated before being used. FOO_MAX_LEN is defined as the maximum memory space expected. 1108e41f4b71Sopenharmony_ci if (size == 0 || size > FOO_MAX_LEN) { 1109e41f4b71Sopenharmony_ci ... // Error handling 1110e41f4b71Sopenharmony_ci } 1111e41f4b71Sopenharmony_ci char* buffer = new char[size]; 1112e41f4b71Sopenharmony_ci ... 1113e41f4b71Sopenharmony_ci delete[] buffer; 1114e41f4b71Sopenharmony_ci} 1115e41f4b71Sopenharmony_ci``` 1116e41f4b71Sopenharmony_ci 1117e41f4b71Sopenharmony_ci**\[Impact]** 1118e41f4b71Sopenharmony_ci 1119e41f4b71Sopenharmony_ciIf the size of the requested memory is externally controllable, resources may be exhausted, resulting in DoS. 1120e41f4b71Sopenharmony_ci 1121e41f4b71Sopenharmony_ci## An array should not be passed as a pointer separately when it is passed into a function as a parameter 1122e41f4b71Sopenharmony_ci 1123e41f4b71Sopenharmony_ci**\[Description]** 1124e41f4b71Sopenharmony_ci 1125e41f4b71Sopenharmony_ciWhen the function parameter type is array (not array reference) or pointer, the array that is being passed into a function is degraded to a pointer. As a result, the array length information is lost, causing potential out-of-bounds read/write issues. If a function receives only fixed-length arrays as parameters, define the parameter type as an array reference or `std::array`. If the function receives a pointer without a length, then the length should also be passed into the function as a parameter. 1126e41f4b71Sopenharmony_ci 1127e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1128e41f4b71Sopenharmony_ci 1129e41f4b71Sopenharmony_ci```cpp 1130e41f4b71Sopenharmony_ciconstexpr int MAX_LEN = 1024; 1131e41f4b71Sopenharmony_ciconstexpr int SIZE = 10; 1132e41f4b71Sopenharmony_ci 1133e41f4b71Sopenharmony_civoid UseArr(int arr[]) 1134e41f4b71Sopenharmony_ci{ 1135e41f4b71Sopenharmony_ci for (int i = 0; i < MAX_LEN; i++) { 1136e41f4b71Sopenharmony_ci std::cout << arr[i] << std::endl; 1137e41f4b71Sopenharmony_ci } 1138e41f4b71Sopenharmony_ci} 1139e41f4b71Sopenharmony_ci 1140e41f4b71Sopenharmony_civoid Test() 1141e41f4b71Sopenharmony_ci{ 1142e41f4b71Sopenharmony_ci int arr[SIZE] = {0}; 1143e41f4b71Sopenharmony_ci UseArr(arr); 1144e41f4b71Sopenharmony_ci} 1145e41f4b71Sopenharmony_ci``` 1146e41f4b71Sopenharmony_ci 1147e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1148e41f4b71Sopenharmony_ci 1149e41f4b71Sopenharmony_ciIt is easier to use the combination of the pointer and length as a type. The following is a simple encapsulation example: 1150e41f4b71Sopenharmony_ci 1151e41f4b71Sopenharmony_ci```cpp 1152e41f4b71Sopenharmony_citemplate <typename T> 1153e41f4b71Sopenharmony_ciclass Slice { 1154e41f4b71Sopenharmony_cipublic: 1155e41f4b71Sopenharmony_ci template <size_t N> 1156e41f4b71Sopenharmony_ci Slice(T (&arr)[N]) : data(arr), len(N) {} 1157e41f4b71Sopenharmony_ci 1158e41f4b71Sopenharmony_ci template <size_t N> 1159e41f4b71Sopenharmony_ci Slice(std::array<T, N> arr) : data(arr.data()), len(N) {} 1160e41f4b71Sopenharmony_ci 1161e41f4b71Sopenharmony_ci Slice(T* arr, size_t n) : data(arr), len(n) {} 1162e41f4b71Sopenharmony_ci ... 1163e41f4b71Sopenharmony_ci 1164e41f4b71Sopenharmony_ciprivate: 1165e41f4b71Sopenharmony_ci T* data; 1166e41f4b71Sopenharmony_ci size_t len; 1167e41f4b71Sopenharmony_ci}; 1168e41f4b71Sopenharmony_ci 1169e41f4b71Sopenharmony_civoid UseArr(Slice<int> arr) 1170e41f4b71Sopenharmony_ci{ 1171e41f4b71Sopenharmony_ci for (int i = 0; i < arr.size(); i++) { 1172e41f4b71Sopenharmony_ci std::cout << arr[i] << std::endl; 1173e41f4b71Sopenharmony_ci } 1174e41f4b71Sopenharmony_ci} 1175e41f4b71Sopenharmony_ci 1176e41f4b71Sopenharmony_ciconstexpr int SIZE = 10; 1177e41f4b71Sopenharmony_ci 1178e41f4b71Sopenharmony_civoid Test() 1179e41f4b71Sopenharmony_ci{ 1180e41f4b71Sopenharmony_ci int arr[SIZE] = {0}; 1181e41f4b71Sopenharmony_ci Slice<int> s{arr}; 1182e41f4b71Sopenharmony_ci UseArr(s); 1183e41f4b71Sopenharmony_ci} 1184e41f4b71Sopenharmony_ci``` 1185e41f4b71Sopenharmony_ci 1186e41f4b71Sopenharmony_ciIf project conditions permit, it is advised to use a mature library for parameter passing, such as the `std::span` type in C++20. 1187e41f4b71Sopenharmony_ci 1188e41f4b71Sopenharmony_ciIf these utility classes are not used, you can pass the pointer and length as two parameters. 1189e41f4b71Sopenharmony_ci 1190e41f4b71Sopenharmony_ci```cpp 1191e41f4b71Sopenharmony_civoid UseArr(int arr[], size_t len) 1192e41f4b71Sopenharmony_ci{ 1193e41f4b71Sopenharmony_ci for (int i = 0; i < len; i++) { 1194e41f4b71Sopenharmony_ci std::cout << arr[i] << std::endl; 1195e41f4b71Sopenharmony_ci } 1196e41f4b71Sopenharmony_ci} 1197e41f4b71Sopenharmony_ci 1198e41f4b71Sopenharmony_ciconstexpr int SIZE = 10; 1199e41f4b71Sopenharmony_ci 1200e41f4b71Sopenharmony_civoid Test() 1201e41f4b71Sopenharmony_ci{ 1202e41f4b71Sopenharmony_ci int arr[SIZE] = {0}; 1203e41f4b71Sopenharmony_ci UseArr(arr, sizeof(arr)); 1204e41f4b71Sopenharmony_ci} 1205e41f4b71Sopenharmony_ci``` 1206e41f4b71Sopenharmony_ci 1207e41f4b71Sopenharmony_ci## When a lambda escapes the current scope, do not capture local variables by reference 1208e41f4b71Sopenharmony_ci 1209e41f4b71Sopenharmony_ci**\[Description]** 1210e41f4b71Sopenharmony_ci 1211e41f4b71Sopenharmony_ciIf a lambda is not limited to local use (for example, when it is transferred to the outside of a function or to another thread), do not capture local variables by reference. Capturing by reference in a lambda means storing a reference to a local object. If the life cycle of the lambda is longer than that of local variables, memory may be insecure. 1212e41f4b71Sopenharmony_ci 1213e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1214e41f4b71Sopenharmony_ci 1215e41f4b71Sopenharmony_ci```cpp 1216e41f4b71Sopenharmony_civoid Foo() 1217e41f4b71Sopenharmony_ci{ 1218e41f4b71Sopenharmony_ci int local = 0; 1219e41f4b71Sopenharmony_ci // The local is captured by reference. The local no longer exists after the function is executed. Therefore, the Process() behavior is undefined. 1220e41f4b71Sopenharmony_ci threadPool.QueueWork([&] { Process(local); }); 1221e41f4b71Sopenharmony_ci} 1222e41f4b71Sopenharmony_ci``` 1223e41f4b71Sopenharmony_ci 1224e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1225e41f4b71Sopenharmony_ci 1226e41f4b71Sopenharmony_ci```cpp 1227e41f4b71Sopenharmony_civoid Foo() 1228e41f4b71Sopenharmony_ci{ 1229e41f4b71Sopenharmony_ci int local = 0; 1230e41f4b71Sopenharmony_ci // Capture the local by value. The local is always valid when Process() is called. 1231e41f4b71Sopenharmony_ci threadPool.QueueWork([local] { Process(local); }); 1232e41f4b71Sopenharmony_ci} 1233e41f4b71Sopenharmony_ci``` 1234e41f4b71Sopenharmony_ci 1235e41f4b71Sopenharmony_ci## Assign a new value to the variable pointing to a resource handle or descriptor immediately after the resource is freed 1236e41f4b71Sopenharmony_ci 1237e41f4b71Sopenharmony_ci**\[Description]** 1238e41f4b71Sopenharmony_ci 1239e41f4b71Sopenharmony_ciVariables pointing to resource handles or descriptors include pointers, file descriptors, socket descriptors, and other variables pointing to resources. Take a pointer as an example. If a pointer that has successfully obtained a memory segment is not immediately set to **nullptr** after the memory segment is freed and no new object is allocated, the pointer is a dangling pointer. Operations on a dangling pointer may lead to double-free and access-freed-memory vulnerabilities. An effective way to mitigate these vulnerabilities is to immediately set freed pointers to new values, such as **nullptr**. For a global resource handle or descriptor, a new value must be set immediately after the resource is freed, so as to prevent the invalid value from being used. For a resource handle or descriptor that is used only in a single function, ensure that the invalid value is not used again after the resource is freed. 1240e41f4b71Sopenharmony_ci 1241e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1242e41f4b71Sopenharmony_ci 1243e41f4b71Sopenharmony_ciIn the following code example, the message is processed based on the message type. After the message is processed, the memory to which the **body** points is freed, but the pointer is not set to **nullptr**. If other functions process the message structure again, double-free and access-freed-memory errors may occur. 1244e41f4b71Sopenharmony_ci 1245e41f4b71Sopenharmony_ci```c 1246e41f4b71Sopenharmony_ciint Fun() 1247e41f4b71Sopenharmony_ci{ 1248e41f4b71Sopenharmony_ci SomeStruct *msg = nullptr; 1249e41f4b71Sopenharmony_ci 1250e41f4b71Sopenharmony_ci ... // Use new to allocate the memory space for msg and msg->body and initialize msg. 1251e41f4b71Sopenharmony_ci 1252e41f4b71Sopenharmony_ci if (msg->type == MESSAGE_A) { 1253e41f4b71Sopenharmony_ci ... 1254e41f4b71Sopenharmony_ci delete msg->body; // Noncompliant: The pointer is not set to bnullptrb after memory is freed. 1255e41f4b71Sopenharmony_ci } 1256e41f4b71Sopenharmony_ci 1257e41f4b71Sopenharmony_ci ... 1258e41f4b71Sopenharmony_ci 1259e41f4b71Sopenharmony_ci // msg is saved to the global queue, and the freed body member may be used. 1260e41f4b71Sopenharmony_ci if (!InsertMsgToQueue(msg)) { 1261e41f4b71Sopenharmony_ci delete msg->body; // The memory to which the body points may be freed again. 1262e41f4b71Sopenharmony_ci delete msg; 1263e41f4b71Sopenharmony_ci return -1; 1264e41f4b71Sopenharmony_ci } 1265e41f4b71Sopenharmony_ci return 0; 1266e41f4b71Sopenharmony_ci} 1267e41f4b71Sopenharmony_ci``` 1268e41f4b71Sopenharmony_ci 1269e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1270e41f4b71Sopenharmony_ci 1271e41f4b71Sopenharmony_ciIn the following code example, the released pointer is immediately set to **nullptr** to avoid double-free errors. 1272e41f4b71Sopenharmony_ci 1273e41f4b71Sopenharmony_ci```c 1274e41f4b71Sopenharmony_ciint Fun() 1275e41f4b71Sopenharmony_ci{ 1276e41f4b71Sopenharmony_ci SomeStruct *msg = nullptr; 1277e41f4b71Sopenharmony_ci 1278e41f4b71Sopenharmony_ci ... // Use new to allocate the memory space for msg and msg->body and initialize msg. 1279e41f4b71Sopenharmony_ci 1280e41f4b71Sopenharmony_ci if (msg->type == MESSAGE_A) { 1281e41f4b71Sopenharmony_ci ... 1282e41f4b71Sopenharmony_ci delete msg->body; 1283e41f4b71Sopenharmony_ci msg->body = nullptr; 1284e41f4b71Sopenharmony_ci } 1285e41f4b71Sopenharmony_ci 1286e41f4b71Sopenharmony_ci ... 1287e41f4b71Sopenharmony_ci 1288e41f4b71Sopenharmony_ci // msg saved to the global queue 1289e41f4b71Sopenharmony_ci if (!InsertMsgToQueue(msg)) { 1290e41f4b71Sopenharmony_ci delete msg->body; // No need to assign nullptr because the pointer leaves the scope soon 1291e41f4b71Sopenharmony_ci delete msg; // No need to assign nullptr because the pointer leaves the scope soon 1292e41f4b71Sopenharmony_ci return -1; 1293e41f4b71Sopenharmony_ci } 1294e41f4b71Sopenharmony_ci return 0; 1295e41f4b71Sopenharmony_ci} 1296e41f4b71Sopenharmony_ci``` 1297e41f4b71Sopenharmony_ci 1298e41f4b71Sopenharmony_ciThe default memory freeing function does not perform any action on NULL pointers. 1299e41f4b71Sopenharmony_ci 1300e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1301e41f4b71Sopenharmony_ci 1302e41f4b71Sopenharmony_ciIn the following code example, no new value is assigned to the file descriptor after it is closed. 1303e41f4b71Sopenharmony_ci 1304e41f4b71Sopenharmony_ci```c 1305e41f4b71Sopenharmony_ciSOCKET s = INVALID_SOCKET; 1306e41f4b71Sopenharmony_ciint fd = -1; 1307e41f4b71Sopenharmony_ci... 1308e41f4b71Sopenharmony_ciclosesocket(s); 1309e41f4b71Sopenharmony_ci... 1310e41f4b71Sopenharmony_ciclose(fd); 1311e41f4b71Sopenharmony_ci... 1312e41f4b71Sopenharmony_ci``` 1313e41f4b71Sopenharmony_ci 1314e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1315e41f4b71Sopenharmony_ci 1316e41f4b71Sopenharmony_ciIn the following code example, a new value is assigned to the corresponding variable immediately after the resource is freed. 1317e41f4b71Sopenharmony_ci 1318e41f4b71Sopenharmony_ci```c 1319e41f4b71Sopenharmony_ciSOCKET s = INVALID_SOCKET; 1320e41f4b71Sopenharmony_ciint fd = -1; 1321e41f4b71Sopenharmony_ci... 1322e41f4b71Sopenharmony_ciclosesocket(s); 1323e41f4b71Sopenharmony_cis = INVALID_SOCKET; 1324e41f4b71Sopenharmony_ci... 1325e41f4b71Sopenharmony_ciclose(fd); 1326e41f4b71Sopenharmony_cifd = -1; 1327e41f4b71Sopenharmony_ci... 1328e41f4b71Sopenharmony_ci``` 1329e41f4b71Sopenharmony_ci 1330e41f4b71Sopenharmony_ci**\[Impact]** 1331e41f4b71Sopenharmony_ci 1332e41f4b71Sopenharmony_ciThe practices of using the freed memory, freeing the freed memory again, or using the freed resources may cause DoS or arbitrary code execution. 1333e41f4b71Sopenharmony_ci 1334e41f4b71Sopenharmony_ci## new and delete operators must be used in pairs, and new\[] and delete\[] operators must also be used in pairs. 1335e41f4b71Sopenharmony_ci 1336e41f4b71Sopenharmony_ci**\[Description]** 1337e41f4b71Sopenharmony_ci 1338e41f4b71Sopenharmony_ciThe object created using the new operator can be destroyed only using the delete operator. The object array created using the new\[] operator can be destroyed only using the delete\[] operator. 1339e41f4b71Sopenharmony_ci 1340e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1341e41f4b71Sopenharmony_ci 1342e41f4b71Sopenharmony_ci```cpp 1343e41f4b71Sopenharmony_ciclass C { 1344e41f4b71Sopenharmony_cipublic: 1345e41f4b71Sopenharmony_ci C(size_t len) : arr(new int[len]) {} 1346e41f4b71Sopenharmony_ci ~C() 1347e41f4b71Sopenharmony_ci { 1348e41f4b71Sopenharmony_ci delete arr; // delete[] arr; should be used. 1349e41f4b71Sopenharmony_ci } 1350e41f4b71Sopenharmony_ci 1351e41f4b71Sopenharmony_ciprivate: 1352e41f4b71Sopenharmony_ci int* arr; 1353e41f4b71Sopenharmony_ci}; 1354e41f4b71Sopenharmony_ci``` 1355e41f4b71Sopenharmony_ci 1356e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1357e41f4b71Sopenharmony_ci 1358e41f4b71Sopenharmony_ci```cpp 1359e41f4b71Sopenharmony_ciclass C { 1360e41f4b71Sopenharmony_cipublic: 1361e41f4b71Sopenharmony_ci C(size_t len) : arr(new int[len]) {} 1362e41f4b71Sopenharmony_ci ~C() { delete[] arr; } 1363e41f4b71Sopenharmony_ci 1364e41f4b71Sopenharmony_ciprivate: 1365e41f4b71Sopenharmony_ci int* arr; 1366e41f4b71Sopenharmony_ci}; 1367e41f4b71Sopenharmony_ci``` 1368e41f4b71Sopenharmony_ci 1369e41f4b71Sopenharmony_ci## The custom operators new and delete must be defined in pairs, and the behavior specified in the operators must be the same as that of the operators to be replaced 1370e41f4b71Sopenharmony_ci 1371e41f4b71Sopenharmony_ci**\[Description]** 1372e41f4b71Sopenharmony_ci 1373e41f4b71Sopenharmony_ciThe custom operators new and delete as well as new\[] and delete\[] must be defined in pairs. The behavior specified in the new/delete operators must be the same as that of the operators to be replaced. 1374e41f4b71Sopenharmony_ci 1375e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1376e41f4b71Sopenharmony_ci 1377e41f4b71Sopenharmony_ci```cpp 1378e41f4b71Sopenharmony_ci// If the custom operator new is defined, the corresponding operator delete must be defined. 1379e41f4b71Sopenharmony_cistruct S { 1380e41f4b71Sopenharmony_ci static void* operator new(size_t sz) 1381e41f4b71Sopenharmony_ci { 1382e41f4b71Sopenharmony_ci ... // Custom operation 1383e41f4b71Sopenharmony_ci return ::operator new(sz); 1384e41f4b71Sopenharmony_ci } 1385e41f4b71Sopenharmony_ci}; 1386e41f4b71Sopenharmony_ci``` 1387e41f4b71Sopenharmony_ci 1388e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1389e41f4b71Sopenharmony_ci 1390e41f4b71Sopenharmony_ci```cpp 1391e41f4b71Sopenharmony_cistruct S { 1392e41f4b71Sopenharmony_ci static void* operator new(size_t sz) 1393e41f4b71Sopenharmony_ci { 1394e41f4b71Sopenharmony_ci ... // Custom operation 1395e41f4b71Sopenharmony_ci return ::operator new(sz); 1396e41f4b71Sopenharmony_ci } 1397e41f4b71Sopenharmony_ci static void operator delete(void* ptr, size_t sz) 1398e41f4b71Sopenharmony_ci { 1399e41f4b71Sopenharmony_ci ... // Custom operation 1400e41f4b71Sopenharmony_ci ::operator delete(ptr); 1401e41f4b71Sopenharmony_ci } 1402e41f4b71Sopenharmony_ci}; 1403e41f4b71Sopenharmony_ci``` 1404e41f4b71Sopenharmony_ci 1405e41f4b71Sopenharmony_ciThe default operator new throws an exception `std::bad_alloc` when memory allocation fails, whereas the operator new that uses the `std::nothrow` parameter returns **nullptr** in the case of a memory allocation failure. The behavior specified the custom operators new and delete must be the same as that of built-in operators. 1406e41f4b71Sopenharmony_ci 1407e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1408e41f4b71Sopenharmony_ci 1409e41f4b71Sopenharmony_ci```cpp 1410e41f4b71Sopenharmony_ci// Function declared in the header file of the memory management module 1411e41f4b71Sopenharmony_ciextern void* AllocMemory(size_t size); // nullptr is returned in the case of a memory allocation failure. 1412e41f4b71Sopenharmony_civoid* operator new(size_t size) 1413e41f4b71Sopenharmony_ci{ 1414e41f4b71Sopenharmony_ci return AllocMemory(size); 1415e41f4b71Sopenharmony_ci} 1416e41f4b71Sopenharmony_ci``` 1417e41f4b71Sopenharmony_ci 1418e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1419e41f4b71Sopenharmony_ci 1420e41f4b71Sopenharmony_ci```cpp 1421e41f4b71Sopenharmony_ci// Function declared in the header file of the memory management module 1422e41f4b71Sopenharmony_ciextern void* AllocMemory(size_t size); // nullptr is returned in the case of a memory allocation failure. 1423e41f4b71Sopenharmony_civoid* operator new(size_t size) 1424e41f4b71Sopenharmony_ci{ 1425e41f4b71Sopenharmony_ci void* ret = AllocMemory(size); 1426e41f4b71Sopenharmony_ci if (ret != nullptr) { 1427e41f4b71Sopenharmony_ci return ret; 1428e41f4b71Sopenharmony_ci } 1429e41f4b71Sopenharmony_ci throw std::bad_alloc(); // An exception is thrown in the case of an allocation failure. 1430e41f4b71Sopenharmony_ci} 1431e41f4b71Sopenharmony_ci 1432e41f4b71Sopenharmony_civoid* operator new(size_t size, const std::nothrow_t& tag) 1433e41f4b71Sopenharmony_ci{ 1434e41f4b71Sopenharmony_ci return AllocMemory(size); 1435e41f4b71Sopenharmony_ci} 1436e41f4b71Sopenharmony_ci``` 1437e41f4b71Sopenharmony_ci 1438e41f4b71Sopenharmony_ci# Error Handling 1439e41f4b71Sopenharmony_ci 1440e41f4b71Sopenharmony_ci## Throw an object itself instead of the pointer to the object when throwing an exception 1441e41f4b71Sopenharmony_ci 1442e41f4b71Sopenharmony_ci**\[Description]** 1443e41f4b71Sopenharmony_ci 1444e41f4b71Sopenharmony_ciThe recommended exception throwing method in C++ is to throw the object itself instead of the pointer to the object. 1445e41f4b71Sopenharmony_ci 1446e41f4b71Sopenharmony_ciWhen the throw statement is used to throw an exception, a temporary object, called an exception object, is constructed. The life cycle of the exception object is clearly defined in the C++ standard: The exception object is constructed when it is thrown. It is destructed when a catch statement of the exception object does not end with `throw` (that is, it is not thrown again) or when the `std::exception_ptr` object that captures the exception is destructed. 1447e41f4b71Sopenharmony_ci 1448e41f4b71Sopenharmony_ciIf a pointer is thrown, the responsibility for recycling the thrown object is unclear. Whether you are obligated to perform the `delete` operation on the pointer where the exception is caught depends on how the object is allocated (for example, static variables, or allocation using `new`) and whether the object is shared. However, the pointer type itself does not indicate the life cycle or ownership of the object, and therefore it is impossible to determine whether the `delete` operation should be performed on the object. If the `delete` operation is not performed on the object that should be deleted, memory leaks occur. If the `delete` operation is performed on the object that should not be deleted, memory will be freed twice. 1449e41f4b71Sopenharmony_ci 1450e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1451e41f4b71Sopenharmony_ci 1452e41f4b71Sopenharmony_ciDo not throw pointers. 1453e41f4b71Sopenharmony_ci 1454e41f4b71Sopenharmony_ci```cpp 1455e41f4b71Sopenharmony_cistatic SomeException exc1("reason 1"); 1456e41f4b71Sopenharmony_ci 1457e41f4b71Sopenharmony_citry { 1458e41f4b71Sopenharmony_ci if (SomeFunction()) { 1459e41f4b71Sopenharmony_ci throw &exc1; // Noncompliant: This is the pointer to the static object, which should not be deleted. 1460e41f4b71Sopenharmony_ci } else { 1461e41f4b71Sopenharmony_ci throw new SomeException("reason 2"); // Noncompliant: The dynamically allocated object should be deleted. 1462e41f4b71Sopenharmony_ci } 1463e41f4b71Sopenharmony_ci} catch (const SomeException* e) { 1464e41f4b71Sopenharmony_ci delete e; // Noncompliant: It is uncertain whether the delete operation is required. 1465e41f4b71Sopenharmony_ci} 1466e41f4b71Sopenharmony_ci``` 1467e41f4b71Sopenharmony_ci 1468e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1469e41f4b71Sopenharmony_ci 1470e41f4b71Sopenharmony_ciAlways throw the exception object itself. 1471e41f4b71Sopenharmony_ci 1472e41f4b71Sopenharmony_ci```cpp 1473e41f4b71Sopenharmony_citry { 1474e41f4b71Sopenharmony_ci if (SomeFunction()) { 1475e41f4b71Sopenharmony_ci throw SomeException("reason 1"); 1476e41f4b71Sopenharmony_ci } else { 1477e41f4b71Sopenharmony_ci throw SomeException("reason 2"); 1478e41f4b71Sopenharmony_ci } 1479e41f4b71Sopenharmony_ci} catch (const SomeException& e) { 1480e41f4b71Sopenharmony_ci ... // Compliant. It can be determined that the delete operation is not required. 1481e41f4b71Sopenharmony_ci} 1482e41f4b71Sopenharmony_ci``` 1483e41f4b71Sopenharmony_ci 1484e41f4b71Sopenharmony_ci## Never throw exceptions from destructors 1485e41f4b71Sopenharmony_ci 1486e41f4b71Sopenharmony_ci**\[Description]** 1487e41f4b71Sopenharmony_ci 1488e41f4b71Sopenharmony_ciBy default, destructors have the `noexcept` attribute. If they throw exceptions, `std::terminate` will be present. Since C++ 11, destructors can be marked as `noexcept(false)`. However, if a destructor is called during stack unwinding (for example, another exception is thrown, causing local variables on the stack to be destructed), `std::terminate` occurs. The destructors are mostly used to deallocate local variables regardless of whether the return value is normal or whether an exception is thrown. Therefore, it is generally not good to throw exceptions from destructors. 1489e41f4b71Sopenharmony_ci 1490e41f4b71Sopenharmony_ci# Standard Library 1491e41f4b71Sopenharmony_ci 1492e41f4b71Sopenharmony_ci## Do not create a std::string from a null pointer 1493e41f4b71Sopenharmony_ci 1494e41f4b71Sopenharmony_ci**\[Description]** 1495e41f4b71Sopenharmony_ci 1496e41f4b71Sopenharmony_ciThe null pointer is dereferenced when it is passed to the std::string constructor, causing undefined behavior. 1497e41f4b71Sopenharmony_ci 1498e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1499e41f4b71Sopenharmony_ci 1500e41f4b71Sopenharmony_ci```cpp 1501e41f4b71Sopenharmony_civoid Foo() 1502e41f4b71Sopenharmony_ci{ 1503e41f4b71Sopenharmony_ci const char* path = std::getenv("PATH"); 1504e41f4b71Sopenharmony_ci std::string str(path); // Error: No check on whether the return value of getenv is nullptr 1505e41f4b71Sopenharmony_ci std::cout << str << std::endl; 1506e41f4b71Sopenharmony_ci} 1507e41f4b71Sopenharmony_ci``` 1508e41f4b71Sopenharmony_ci 1509e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1510e41f4b71Sopenharmony_ci 1511e41f4b71Sopenharmony_ci```cpp 1512e41f4b71Sopenharmony_civoid Foo() 1513e41f4b71Sopenharmony_ci{ 1514e41f4b71Sopenharmony_ci const char* path = std::getenv("PATH"); 1515e41f4b71Sopenharmony_ci if (path == nullptr) { 1516e41f4b71Sopenharmony_ci ... // Error reporting 1517e41f4b71Sopenharmony_ci return; 1518e41f4b71Sopenharmony_ci } 1519e41f4b71Sopenharmony_ci std::string str(path); 1520e41f4b71Sopenharmony_ci ... 1521e41f4b71Sopenharmony_ci std::cout << str << std::endl; 1522e41f4b71Sopenharmony_ci} 1523e41f4b71Sopenharmony_civoid Foo() 1524e41f4b71Sopenharmony_ci{ 1525e41f4b71Sopenharmony_ci const char* path = std::getenv("PATH"); 1526e41f4b71Sopenharmony_ci std::string str(path == nullptr ? path : ""); 1527e41f4b71Sopenharmony_ci ... // Check on the null string 1528e41f4b71Sopenharmony_ci std::cout << str << std::endl; // Check on the null string if necessary 1529e41f4b71Sopenharmony_ci} 1530e41f4b71Sopenharmony_ci``` 1531e41f4b71Sopenharmony_ci 1532e41f4b71Sopenharmony_ci## Do not save the pointers returned by the **c\_str()** and **data()** member functions of std::string 1533e41f4b71Sopenharmony_ci 1534e41f4b71Sopenharmony_ci**\[Description]** 1535e41f4b71Sopenharmony_ci 1536e41f4b71Sopenharmony_ciTo ensure the validity of the reference values returned by the **c\_str()** and **data()** member functions of the std::string object, do not save the **c\_str()** and **data()** results of std::string. Instead, call them directly when needed (the call overhead is optimized through compiler inlining). Otherwise, when the std::string object is modified by calling its modify method, or when the std::string object is out of the scope, the stored pointer becomes invalid. Using an invalid pointer will result in undefined behavior. 1537e41f4b71Sopenharmony_ci 1538e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1539e41f4b71Sopenharmony_ci 1540e41f4b71Sopenharmony_ci```cpp 1541e41f4b71Sopenharmony_civoid Bar(const char* data) 1542e41f4b71Sopenharmony_ci{ 1543e41f4b71Sopenharmony_ci ... 1544e41f4b71Sopenharmony_ci} 1545e41f4b71Sopenharmony_ci 1546e41f4b71Sopenharmony_civoid Foo1() 1547e41f4b71Sopenharmony_ci{ 1548e41f4b71Sopenharmony_ci std::string name{"demo"}; 1549e41f4b71Sopenharmony_ci const char* text = name.c_str(); // After the expression ends, the life cycle of name is still in use and the pointer is valid. 1550e41f4b71Sopenharmony_ci 1551e41f4b71Sopenharmony_ci // If a non-const member function (such as operator[] and begin()) of std::string is called and the name is therefore modified, 1552e41f4b71Sopenharmony_ci // the text content may become unavailable or may not be the original character string. 1553e41f4b71Sopenharmony_ci name = "test"; 1554e41f4b71Sopenharmony_ci name[1] = '2'; 1555e41f4b71Sopenharmony_ci ... 1556e41f4b71Sopenharmony_ci Bar(text); // The text no longer points to the valid memory space. 1557e41f4b71Sopenharmony_ci} 1558e41f4b71Sopenharmony_ci 1559e41f4b71Sopenharmony_civoid Foo2() 1560e41f4b71Sopenharmony_ci{ 1561e41f4b71Sopenharmony_ci std::string name{"demo"}; 1562e41f4b71Sopenharmony_ci std::string test{"test"}; 1563e41f4b71Sopenharmony_ci const char* text = (name + test).c_str(); // After the expression ends, the temporary object generated by the + operator is destroyed. 1564e41f4b71Sopenharmony_ci ... 1565e41f4b71Sopenharmony_ci Bar(text); // The text no longer points to the valid memory space. 1566e41f4b71Sopenharmony_ci} 1567e41f4b71Sopenharmony_ci 1568e41f4b71Sopenharmony_civoid Foo3(std::string& s) 1569e41f4b71Sopenharmony_ci{ 1570e41f4b71Sopenharmony_ci const char* data = s.data(); 1571e41f4b71Sopenharmony_ci ... 1572e41f4b71Sopenharmony_ci s.replace(0, 3, "***"); 1573e41f4b71Sopenharmony_ci ... 1574e41f4b71Sopenharmony_ci Bar(data); // The data no longer points to the valid memory space. 1575e41f4b71Sopenharmony_ci} 1576e41f4b71Sopenharmony_ci``` 1577e41f4b71Sopenharmony_ci 1578e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1579e41f4b71Sopenharmony_ci 1580e41f4b71Sopenharmony_ci```cpp 1581e41f4b71Sopenharmony_civoid Foo1() 1582e41f4b71Sopenharmony_ci{ 1583e41f4b71Sopenharmony_ci std::string name{"demo"}; 1584e41f4b71Sopenharmony_ci 1585e41f4b71Sopenharmony_ci name = "test"; 1586e41f4b71Sopenharmony_ci name[1] = '2'; 1587e41f4b71Sopenharmony_ci ... 1588e41f4b71Sopenharmony_ci Bar(name.c_str()); 1589e41f4b71Sopenharmony_ci} 1590e41f4b71Sopenharmony_ci 1591e41f4b71Sopenharmony_civoid Foo2() 1592e41f4b71Sopenharmony_ci{ 1593e41f4b71Sopenharmony_ci std::string name{"demo"}; 1594e41f4b71Sopenharmony_ci std::string test{"test"}; 1595e41f4b71Sopenharmony_ci name += test; 1596e41f4b71Sopenharmony_ci ... 1597e41f4b71Sopenharmony_ci Bar(name.c_str()); 1598e41f4b71Sopenharmony_ci} 1599e41f4b71Sopenharmony_ci 1600e41f4b71Sopenharmony_civoid Foo3(std::string& s) 1601e41f4b71Sopenharmony_ci{ 1602e41f4b71Sopenharmony_ci ... 1603e41f4b71Sopenharmony_ci s.replace(0, 3, "***"); 1604e41f4b71Sopenharmony_ci ... 1605e41f4b71Sopenharmony_ci Bar(s.data()); 1606e41f4b71Sopenharmony_ci} 1607e41f4b71Sopenharmony_ci``` 1608e41f4b71Sopenharmony_ci 1609e41f4b71Sopenharmony_ci**\[Exception]** 1610e41f4b71Sopenharmony_ci 1611e41f4b71Sopenharmony_ciIn rare cases where high performance coding is required, you can temporarily save the pointer returned by the c\_str() method of std::string to match the existing functions which support only the input parameters of the `const char*` type. However, you should ensure that the life cycle of the std::string object is longer than that of the saved pointer, and that the std::string object is not modified within the life cycle of the saved pointer. 1612e41f4b71Sopenharmony_ci 1613e41f4b71Sopenharmony_ci## Ensure that the buffer for strings has sufficient space for character data and terminators, and that the string is null-terminated 1614e41f4b71Sopenharmony_ci 1615e41f4b71Sopenharmony_ci**\[Description]** 1616e41f4b71Sopenharmony_ci 1617e41f4b71Sopenharmony_ciA C-style character string is a continuous sequence of characters, which is terminated by the first null character and contains the null character. 1618e41f4b71Sopenharmony_ci 1619e41f4b71Sopenharmony_ciWhen copying or storing a C-style string, ensure that the buffer has sufficient space to hold the character sequence including the null terminator, and that the string is null terminated. Otherwise, buffer overflows may occur. 1620e41f4b71Sopenharmony_ci 1621e41f4b71Sopenharmony_ci- Preferentially use std::string to indicate a string because it is easier to operate and more likely to be correctly used. This can prevent overflows and null-terminator missing due to improper use of C-style strings. 1622e41f4b71Sopenharmony_ci- When using the C-style strings provided by the C/C++ standard library for function operations, ensure that the input string is null terminated, that the string is not read or written beyond the string buffer, and that the string after the storage operation is null terminated. 1623e41f4b71Sopenharmony_ci 1624e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1625e41f4b71Sopenharmony_ci 1626e41f4b71Sopenharmony_ci```cpp 1627e41f4b71Sopenharmony_cichar buf[BUFFER_SIZE]; 1628e41f4b71Sopenharmony_cistd::cin >> buf; 1629e41f4b71Sopenharmony_civoid Foo(std::istream& in) 1630e41f4b71Sopenharmony_ci{ 1631e41f4b71Sopenharmony_ci char buffer[BUFFER_SIZE]; 1632e41f4b71Sopenharmony_ci if (!in.read(buffer, sizeof(buffer))) { // Note: in.read() does not ensure null termination. 1633e41f4b71Sopenharmony_ci ... // Error handling 1634e41f4b71Sopenharmony_ci return; 1635e41f4b71Sopenharmony_ci } 1636e41f4b71Sopenharmony_ci 1637e41f4b71Sopenharmony_ci std::string str(buffer); // Noncompliant: The string is not null terminated. 1638e41f4b71Sopenharmony_ci ... 1639e41f4b71Sopenharmony_ci} 1640e41f4b71Sopenharmony_civoid Foo(std::istream& in) 1641e41f4b71Sopenharmony_ci{ 1642e41f4b71Sopenharmony_ci std::string s; 1643e41f4b71Sopenharmony_ci in >> s; // Noncompliant: The length of the data to be read is not restricted, which may cause resource consumption or attacks. 1644e41f4b71Sopenharmony_ci ... 1645e41f4b71Sopenharmony_ci} 1646e41f4b71Sopenharmony_ci``` 1647e41f4b71Sopenharmony_ci 1648e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1649e41f4b71Sopenharmony_ci 1650e41f4b71Sopenharmony_ci```cpp 1651e41f4b71Sopenharmony_cichar buf[BUFFER_SIZE] = {0}; 1652e41f4b71Sopenharmony_cistd::cin.width(sizeof(buf) - 1); // The buffer length must be N–1 to reserve space for a null terminator. 1653e41f4b71Sopenharmony_cistd::cin >> buf; 1654e41f4b71Sopenharmony_civoid Foo(std::istream& in) 1655e41f4b71Sopenharmony_ci{ 1656e41f4b71Sopenharmony_ci char buffer[BUFFER_SIZE]; 1657e41f4b71Sopenharmony_ci 1658e41f4b71Sopenharmony_ci if (!in.read(buffer, sizeof(buffer)) { // Note: in.read() does not ensure null termination. 1659e41f4b71Sopenharmony_ci ... // Error handling 1660e41f4b71Sopenharmony_ci return; 1661e41f4b71Sopenharmony_ci } 1662e41f4b71Sopenharmony_ci 1663e41f4b71Sopenharmony_ci std::string str(buffer, in.gcount()); // Ensure that the std::string constructor reads only characters of a specified length. 1664e41f4b71Sopenharmony_ci ... 1665e41f4b71Sopenharmony_ci} 1666e41f4b71Sopenharmony_civoid Foo(std::istream& in) 1667e41f4b71Sopenharmony_ci{ 1668e41f4b71Sopenharmony_ci std::string s; 1669e41f4b71Sopenharmony_ci in.width(MAX_NEED_SIZE); 1670e41f4b71Sopenharmony_ci in >> s; // Compliant: The maximum length of the data to be read is restricted. 1671e41f4b71Sopenharmony_ci ... 1672e41f4b71Sopenharmony_ci} 1673e41f4b71Sopenharmony_ci``` 1674e41f4b71Sopenharmony_ci 1675e41f4b71Sopenharmony_ci**\[Impact]** 1676e41f4b71Sopenharmony_ci 1677e41f4b71Sopenharmony_ciSetting no limits to the integer values in external data is likely to cause DoS, buffer overflows, information leaks, or arbitrary code execution. 1678e41f4b71Sopenharmony_ci 1679e41f4b71Sopenharmony_ci## Do not use std::string to store sensitive information 1680e41f4b71Sopenharmony_ci 1681e41f4b71Sopenharmony_ci**\[Description]** 1682e41f4b71Sopenharmony_ci 1683e41f4b71Sopenharmony_ciThe std::string class is a string management class defined in C++. If sensitive information (such as passwords) is operated using std::string, it may be scattered in memory during program running and cannot be cleared. 1684e41f4b71Sopenharmony_ci 1685e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1686e41f4b71Sopenharmony_ci 1687e41f4b71Sopenharmony_ciIn the following code example, the **Foo()** function obtains the password, saves it to the std::string variable **password**, and then passes it to the **VerifyPassword()** function. In this process, two copies of the password exist in memory. 1688e41f4b71Sopenharmony_ci 1689e41f4b71Sopenharmony_ci```cpp 1690e41f4b71Sopenharmony_cibool VerifyPassword(std::string password) 1691e41f4b71Sopenharmony_ci{ 1692e41f4b71Sopenharmony_ci ... 1693e41f4b71Sopenharmony_ci} 1694e41f4b71Sopenharmony_ci 1695e41f4b71Sopenharmony_civoid Foo() 1696e41f4b71Sopenharmony_ci{ 1697e41f4b71Sopenharmony_ci std::string password = GetPassword(); 1698e41f4b71Sopenharmony_ci VerifyPassword(password); 1699e41f4b71Sopenharmony_ci} 1700e41f4b71Sopenharmony_ci``` 1701e41f4b71Sopenharmony_ci 1702e41f4b71Sopenharmony_ci**\[Impact]** 1703e41f4b71Sopenharmony_ci 1704e41f4b71Sopenharmony_ciSensitive information is not deleted in due time, which may cause information leaks. 1705e41f4b71Sopenharmony_ci 1706e41f4b71Sopenharmony_ci## Ensure that the external data used as container indexes or iterators is within the valid range 1707e41f4b71Sopenharmony_ci 1708e41f4b71Sopenharmony_ci**\[Description]** 1709e41f4b71Sopenharmony_ci 1710e41f4b71Sopenharmony_ciExternal data is untrusted. When it is used as container or array indexes, ensure that its value is within the valid range of the elements that can be accessed by containers or arrays. When external data is used for iterator offset, ensure that the iterator offset value range is \[begin(), end()] of the container associated with the iterator (created from the begin() method of the container object c), that is, greater than or equal to c.begin() and less than or equal to c.end(). 1711e41f4b71Sopenharmony_ci 1712e41f4b71Sopenharmony_ciFor a container (such as std::vector, std::set, or std::map) with the at() method, if the corresponding index is out of range or the key-value does not exist, the method throws an exception. If the index of the corresponding operator\[] is out of range, undefined behavior occurs. If the default key-value fails to be constructed when the corresponding key-value does not exist, undefined behavior also occurs. 1713e41f4b71Sopenharmony_ci 1714e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1715e41f4b71Sopenharmony_ci 1716e41f4b71Sopenharmony_ci```cpp 1717e41f4b71Sopenharmony_ciint main() 1718e41f4b71Sopenharmony_ci{ 1719e41f4b71Sopenharmony_ci // Obtain an integer (index) from external input. 1720e41f4b71Sopenharmony_ci int index; 1721e41f4b71Sopenharmony_ci if (!(std::cin >> index)) { 1722e41f4b71Sopenharmony_ci ... // Error handling 1723e41f4b71Sopenharmony_ci return -1; 1724e41f4b71Sopenharmony_ci } 1725e41f4b71Sopenharmony_ci 1726e41f4b71Sopenharmony_ci std::vector<char> c{'A', 'B', 'C', 'D'}; 1727e41f4b71Sopenharmony_ci 1728e41f4b71Sopenharmony_ci // Noncompliant: The index range is not correctly verified, causing out-of-bounds read: Ensure that the index is within the range of the container element. 1729e41f4b71Sopenharmony_ci std::cout << c[index] << std::endl; 1730e41f4b71Sopenharmony_ci 1731e41f4b71Sopenharmony_ci // Noncompliant: Ensure that the index is within the range of the container or array element. 1732e41f4b71Sopenharmony_ci for (auto pos = std::cbegin(c) + index; pos < std::cend(c); ++pos) { 1733e41f4b71Sopenharmony_ci std::cout << *pos << std::endl; 1734e41f4b71Sopenharmony_ci } 1735e41f4b71Sopenharmony_ci return 0; 1736e41f4b71Sopenharmony_ci} 1737e41f4b71Sopenharmony_civoid Foo(size_t n) 1738e41f4b71Sopenharmony_ci{ 1739e41f4b71Sopenharmony_ci std::vector<int> v{0, 1, 2, 3}; 1740e41f4b71Sopenharmony_ci 1741e41f4b71Sopenharmony_ci // n is the index transferred through an external API, which may cause out-of-bounds access. 1742e41f4b71Sopenharmony_ci for_each_n(v.cbegin(), n, [](int x) { std::cout << x; }); 1743e41f4b71Sopenharmony_ci} 1744e41f4b71Sopenharmony_ci``` 1745e41f4b71Sopenharmony_ci 1746e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1747e41f4b71Sopenharmony_ci 1748e41f4b71Sopenharmony_ci```cpp 1749e41f4b71Sopenharmony_ciint main() 1750e41f4b71Sopenharmony_ci{ 1751e41f4b71Sopenharmony_ci // Obtain an integer (index) from external input. 1752e41f4b71Sopenharmony_ci int index; 1753e41f4b71Sopenharmony_ci if (!(std::cin >> index)) { 1754e41f4b71Sopenharmony_ci ... // Error handling 1755e41f4b71Sopenharmony_ci return -1; 1756e41f4b71Sopenharmony_ci } 1757e41f4b71Sopenharmony_ci 1758e41f4b71Sopenharmony_ci // std::vector is used as an example. Code such as std::cbegin(c) also applies to std::string 1759e41f4b71Sopenharmony_ci // and C array (not applicable to the char* variable and the static character string represented by char*). 1760e41f4b71Sopenharmony_ci std::vector<char> c{'A', 'B', 'C', 'D'}; 1761e41f4b71Sopenharmony_ci 1762e41f4b71Sopenharmony_ci try { 1763e41f4b71Sopenharmony_ci std::cout << c.at(index) << std::endl; // Compliant: When the index is out of range, the at() function throws an exception 1764e41f4b71Sopenharmony_ci } catch (const std::out_of_range& e) { 1765e41f4b71Sopenharmony_ci ... // Out-of-bounds exception handling 1766e41f4b71Sopenharmony_ci } 1767e41f4b71Sopenharmony_ci 1768e41f4b71Sopenharmony_ci // In subsequent code, the valid index must be used for container element index or iterator offset. 1769e41f4b71Sopenharmony_ci // The index range is correctly verified: The index is within the range of the container element. 1770e41f4b71Sopenharmony_ci if (index < 0 || index >= c.size()) { 1771e41f4b71Sopenharmony_ci ... // Error handling 1772e41f4b71Sopenharmony_ci return -1; 1773e41f4b71Sopenharmony_ci } 1774e41f4b71Sopenharmony_ci 1775e41f4b71Sopenharmony_ci std::cout << c[index] << std::endl; // Compliant: The index range has been validated. 1776e41f4b71Sopenharmony_ci 1777e41f4b71Sopenharmony_ci // Compliant: The index has been validated. 1778e41f4b71Sopenharmony_ci for (auto pos = std::cbegin(c) + index; pos < std::cend(c); ++pos) { 1779e41f4b71Sopenharmony_ci std::cout << *pos << std::endl; 1780e41f4b71Sopenharmony_ci } 1781e41f4b71Sopenharmony_ci return 0; 1782e41f4b71Sopenharmony_ci} 1783e41f4b71Sopenharmony_civoid Foo(size_t n) 1784e41f4b71Sopenharmony_ci{ 1785e41f4b71Sopenharmony_ci std::vector<int> v{0, 1, 2, 3}; 1786e41f4b71Sopenharmony_ci 1787e41f4b71Sopenharmony_ci // Ensure that the iteration range [first, first + count) of for_each_n is valid. 1788e41f4b71Sopenharmony_ci if (n > v.size()) { 1789e41f4b71Sopenharmony_ci ... // Error handling 1790e41f4b71Sopenharmony_ci return; 1791e41f4b71Sopenharmony_ci } 1792e41f4b71Sopenharmony_ci for_each_n(v.cbegin(), n, [](int x) { std::cout << x; }); 1793e41f4b71Sopenharmony_ci} 1794e41f4b71Sopenharmony_ci``` 1795e41f4b71Sopenharmony_ci 1796e41f4b71Sopenharmony_ci## Use valid format strings when calling formatted input/output functions 1797e41f4b71Sopenharmony_ci 1798e41f4b71Sopenharmony_ci**\[Description]** 1799e41f4b71Sopenharmony_ci 1800e41f4b71Sopenharmony_ciWhen using C-style formatted input/output functions, ensure that the format strings are valid and strictly match the corresponding parameter types. Otherwise, unexpected behavior occurs. 1801e41f4b71Sopenharmony_ci 1802e41f4b71Sopenharmony_ciIn addition to C-style formatted input/output functions, similar functions in C must also use valid format strings, for example, the **std::format()** function in C++20. 1803e41f4b71Sopenharmony_ci 1804e41f4b71Sopenharmony_ciFor a custom C-style formatted function, you can use the attributes supported by the compiler to automatically check its correctness. For example, the GCC can automatically check custom formatted functions (such as printf, scanf, strftime, and strfmon). For details, see Common Function Attributes in the GCC manual: 1805e41f4b71Sopenharmony_ci 1806e41f4b71Sopenharmony_ci```c 1807e41f4b71Sopenharmony_ciextern int CustomPrintf(void* obj, const char* format, ...) 1808e41f4b71Sopenharmony_ci __attribute__ ((format (printf, 2, 3))); 1809e41f4b71Sopenharmony_ci``` 1810e41f4b71Sopenharmony_ci 1811e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1812e41f4b71Sopenharmony_ci 1813e41f4b71Sopenharmony_ciIn the following code example, an integer is formatted into the macAddr variable, but macAddr is of the unsigned char type, and %x indicates a parameter of the int type. After the function is executed, out-of-bounds write occurs. 1814e41f4b71Sopenharmony_ci 1815e41f4b71Sopenharmony_ci```c 1816e41f4b71Sopenharmony_ciunsigned char macAddr[6]; 1817e41f4b71Sopenharmony_ci... 1818e41f4b71Sopenharmony_ci// The data format in macStr is e2:42:a4:52:1e:33. 1819e41f4b71Sopenharmony_ciint ret = sscanf(macStr, "%x:%x:%x:%x:%x:%x\n", 1820e41f4b71Sopenharmony_ci &macAddr[0], &macAddr[1], 1821e41f4b71Sopenharmony_ci &macAddr[2], &macAddr[3], 1822e41f4b71Sopenharmony_ci &macAddr[4], &macAddr[5]); 1823e41f4b71Sopenharmony_ci... 1824e41f4b71Sopenharmony_ci``` 1825e41f4b71Sopenharmony_ci 1826e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1827e41f4b71Sopenharmony_ci 1828e41f4b71Sopenharmony_ciIn the following code example, %hhx is used to ensure that the format string strictly matches the parameter type. 1829e41f4b71Sopenharmony_ci 1830e41f4b71Sopenharmony_ci```c 1831e41f4b71Sopenharmony_ciunsigned char macAddr[6]; 1832e41f4b71Sopenharmony_ci... 1833e41f4b71Sopenharmony_ci// The data format in macStr is e2:42:a4:52:1e:33. 1834e41f4b71Sopenharmony_ciint ret = sscanf(macStr, "%hhx:%hhx:%hhx:%hhx:%hhx:%hhx\n", 1835e41f4b71Sopenharmony_ci &macAddr[0], &macAddr[1], 1836e41f4b71Sopenharmony_ci &macAddr[2], &macAddr[3], 1837e41f4b71Sopenharmony_ci &macAddr[4], &macAddr[5]); 1838e41f4b71Sopenharmony_ci... 1839e41f4b71Sopenharmony_ci``` 1840e41f4b71Sopenharmony_ci 1841e41f4b71Sopenharmony_ciNote: It is not advised to use C library functions, such as **sscanf()** and **sprintf()**, in C++. You can use std::istringstream, std::ostringstream, and std::stringstream instead. 1842e41f4b71Sopenharmony_ci 1843e41f4b71Sopenharmony_ci**\[Impact]** 1844e41f4b71Sopenharmony_ci 1845e41f4b71Sopenharmony_ciAn incorrect format string may cause memory damage or abnormal program termination. 1846e41f4b71Sopenharmony_ci 1847e41f4b71Sopenharmony_ci## Ensure that the format parameter is not controlled by external data when a formatted input/output function is called 1848e41f4b71Sopenharmony_ci 1849e41f4b71Sopenharmony_ci**\[Description]** 1850e41f4b71Sopenharmony_ci 1851e41f4b71Sopenharmony_ciWhen a formatted function is called, the **format** parameter provided or concatenated by external data will cause a string formatting vulnerability. Take the formatted output function of the C standard library as an example. When the **format** parameter is externally controllable, an attacker can use the %n converter to write an integer to a specified address, use the %x or %d converter to view the stack or register content, or use the %s converter to cause process crashes or other issues. 1852e41f4b71Sopenharmony_ci 1853e41f4b71Sopenharmony_ciCommon formatted functions are as follows: 1854e41f4b71Sopenharmony_ci 1855e41f4b71Sopenharmony_ci- Formatted output functions: **sprintf()**, **vsprintf()**, **snprintf()**, **vsnprintf()**, etc. 1856e41f4b71Sopenharmony_ci- Formatted input functions: **sscanf()**, **vsscanf()**, **fscanf()**, **vscanf()**, etc. 1857e41f4b71Sopenharmony_ci- Formatted error message functions: **err()**, **verr()**, **errx()**, **verrx()**, **warn()**, **vwarn()**, **warnx()**, **vwarnx()**, **error()**, and **error\_at\_line()** 1858e41f4b71Sopenharmony_ci- Formatted log functions: **syslog()** and **vsyslog()** 1859e41f4b71Sopenharmony_ci- **std::format()** provided by C++20 1860e41f4b71Sopenharmony_ci 1861e41f4b71Sopenharmony_ciWhen a formatted function is called, the constant string should be used as the format string. The format string must not be externally controllable: 1862e41f4b71Sopenharmony_ci 1863e41f4b71Sopenharmony_ci```cpp 1864e41f4b71Sopenharmony_ciBox<int> v{MAX_COUNT}; 1865e41f4b71Sopenharmony_cistd::cout << std::format("{:#x}", v); 1866e41f4b71Sopenharmony_ci``` 1867e41f4b71Sopenharmony_ci 1868e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1869e41f4b71Sopenharmony_ci 1870e41f4b71Sopenharmony_ciIn the following code example, the **Log()** function is used to directly log external data, which may cause a format string vulnerability. 1871e41f4b71Sopenharmony_ci 1872e41f4b71Sopenharmony_ci```c 1873e41f4b71Sopenharmony_civoid Foo() 1874e41f4b71Sopenharmony_ci{ 1875e41f4b71Sopenharmony_ci std::string msg = GetMsg(); 1876e41f4b71Sopenharmony_ci ... 1877e41f4b71Sopenharmony_ci syslog(priority, msg.c_str()); // Noncompliant: A format string vulnerability exists. 1878e41f4b71Sopenharmony_ci} 1879e41f4b71Sopenharmony_ci``` 1880e41f4b71Sopenharmony_ci 1881e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1882e41f4b71Sopenharmony_ciThe following practice is recommended: Use the %s converter to log external data to avoid the format string vulnerability. 1883e41f4b71Sopenharmony_ci 1884e41f4b71Sopenharmony_ci```c 1885e41f4b71Sopenharmony_civoid Foo() 1886e41f4b71Sopenharmony_ci{ 1887e41f4b71Sopenharmony_ci std::string msg = GetMsg(); 1888e41f4b71Sopenharmony_ci ... 1889e41f4b71Sopenharmony_ci syslog(priority, "%s", msg.c_str()); // Compliant: No format string vulnerability exists. 1890e41f4b71Sopenharmony_ci} 1891e41f4b71Sopenharmony_ci``` 1892e41f4b71Sopenharmony_ci 1893e41f4b71Sopenharmony_ci**\[Impact]** 1894e41f4b71Sopenharmony_ci 1895e41f4b71Sopenharmony_ciIf the format string is externally controllable, attackers can crash the process, view the stack content, view the memory content, or write data to any memory location, and then execute any code with the permission of the compromised process. 1896e41f4b71Sopenharmony_ci 1897e41f4b71Sopenharmony_ci## Do not use external controllable data as parameters for process startup functions or for the loading functions of dlopen/LoadLibrary and other modules 1898e41f4b71Sopenharmony_ci 1899e41f4b71Sopenharmony_ci**\[Description]** 1900e41f4b71Sopenharmony_ci 1901e41f4b71Sopenharmony_ciProcess startup functions in this requirement include **system()**, **popen()**, **execl()**, **execlp()**, **execle()**, **execv()**, and **execvp()**. Each of these functions such as **system()** and **popen()** will create a process. If external controllable data is used as the parameters of these functions, injection vulnerabilities may occur. When functions such as **execl()** are used to execute new processes, command injection risks also exist if shell is used to start new processes. The use of **execlp()**, **execvp()**, and **execvpe()** functions depends on the program paths searched using the system environment variable PATH. Consider the risks of external environment variables when using these functions, or avoid using these functions. 1902e41f4b71Sopenharmony_ci 1903e41f4b71Sopenharmony_ciTherefore, C standard functions are always preferred to implement the required functions. If you need to use these functions, use the trustlist mechanism to ensure that the parameters of these functions are not affected by any external data. 1904e41f4b71Sopenharmony_ci 1905e41f4b71Sopenharmony_ciThe **dlopen()** and **LoadLibrary()** functions load external modules. If external controllable data is used as parameters of these functions, the modules prepared by attackers may be loaded. If these functions need to be used, take one of the following measures: 1906e41f4b71Sopenharmony_ci 1907e41f4b71Sopenharmony_ci- Use the trustlist mechanism to ensure that the parameters of these functions are not affected by any external data. 1908e41f4b71Sopenharmony_ci- Use the digital signature mechanism to protect the modules to be loaded, ensuring their integrity. 1909e41f4b71Sopenharmony_ci- After the security of the dynamic library loaded locally is ensured by means of permission and access control, the dynamic library is automatically loaded using a specific directory. 1910e41f4b71Sopenharmony_ci- After the security of the local configuration file is ensured by means of permission and access control, the dynamic library specified in the configuration file is automatically loaded. 1911e41f4b71Sopenharmony_ci 1912e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 1913e41f4b71Sopenharmony_ci 1914e41f4b71Sopenharmony_ciIn the following code example, external controllable data is directly used as the parameter of the **LoadLibrary()** function, which may implant Trojan horses into the program. 1915e41f4b71Sopenharmony_ci 1916e41f4b71Sopenharmony_ci```c 1917e41f4b71Sopenharmony_cichar* msg = GetMsgFromRemote(); 1918e41f4b71Sopenharmony_ciLoadLibrary(msg); 1919e41f4b71Sopenharmony_ci``` 1920e41f4b71Sopenharmony_ci 1921e41f4b71Sopenharmony_ciIn the following code example, the external **cmd** command is executed by the **system()** function. Attackers can execute any command: 1922e41f4b71Sopenharmony_ci 1923e41f4b71Sopenharmony_ci```c 1924e41f4b71Sopenharmony_cistd::string cmd = GetCmdFromRemote(); 1925e41f4b71Sopenharmony_cisystem(cmd.c_str()); 1926e41f4b71Sopenharmony_ci``` 1927e41f4b71Sopenharmony_ci 1928e41f4b71Sopenharmony_ciIn the following code example, a part of the **cmd** command executed by the **system()** function is external data. An attacker may enter `some dir;reboot` to cause system reboot: 1929e41f4b71Sopenharmony_ci 1930e41f4b71Sopenharmony_ci```cpp 1931e41f4b71Sopenharmony_cistd::string name = GetDirNameFromRemote(); 1932e41f4b71Sopenharmony_cistd::string cmd{"ls " + name}; 1933e41f4b71Sopenharmony_cisystem(cmd.c_str()); 1934e41f4b71Sopenharmony_ci``` 1935e41f4b71Sopenharmony_ci 1936e41f4b71Sopenharmony_ciWhen using **exec()** functions to prevent command injection, do not use command parsers (such as **/bin/sh**) for the **path** and **file** parameters in the functions. 1937e41f4b71Sopenharmony_ci 1938e41f4b71Sopenharmony_ci```c 1939e41f4b71Sopenharmony_ciint execl(const char* path, const char* arg, ...); 1940e41f4b71Sopenharmony_ciint execlp(const char* file, const char* arg, ...); 1941e41f4b71Sopenharmony_ciint execle(const char* path, const char* arg, ...); 1942e41f4b71Sopenharmony_ciint execv(const char* path, char* const argv[]); 1943e41f4b71Sopenharmony_ciint execvp(const char* file, char* const argv[]); 1944e41f4b71Sopenharmony_ciint execvpe(const char* file, char* const argv[], char* const envp[]); 1945e41f4b71Sopenharmony_ci``` 1946e41f4b71Sopenharmony_ci 1947e41f4b71Sopenharmony_ciFor example, do not use the following methods: 1948e41f4b71Sopenharmony_ci 1949e41f4b71Sopenharmony_ci```c 1950e41f4b71Sopenharmony_cistd::string cmd = GetDirNameFromRemote(); 1951e41f4b71Sopenharmony_ciexecl("/bin/sh", "sh", "-c", cmd.c_str(), nullptr); 1952e41f4b71Sopenharmony_ci``` 1953e41f4b71Sopenharmony_ci 1954e41f4b71Sopenharmony_ciYou can use library functions or write a small amount of code to avoid using the **system()** function to call commands. For example, the `mkdir()` function can implement the function of the `mkdir` command. In the following code, avoid using the `cat` command to copy file content. 1955e41f4b71Sopenharmony_ci 1956e41f4b71Sopenharmony_ci```c 1957e41f4b71Sopenharmony_ciint WriteDataToFile(const char* dstFile, const char* srcFile) 1958e41f4b71Sopenharmony_ci{ 1959e41f4b71Sopenharmony_ci ... // Argument validation 1960e41f4b71Sopenharmony_ci std::ostringstream oss; 1961e41f4b71Sopenharmony_ci oss << "cat " << srcFile << " > " << dstFile; 1962e41f4b71Sopenharmony_ci 1963e41f4b71Sopenharmony_ci std::string cmd{oss.str()}; 1964e41f4b71Sopenharmony_ci system(cmd.c_str()); 1965e41f4b71Sopenharmony_ci ... 1966e41f4b71Sopenharmony_ci} 1967e41f4b71Sopenharmony_ci``` 1968e41f4b71Sopenharmony_ci 1969e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 1970e41f4b71Sopenharmony_ci 1971e41f4b71Sopenharmony_ciSome command functions can be implemented through a small amount of coding. The following code implements the file copy function to avoid calling the `cat` or `cp` command. Note that the following code does not consider the impact of signal interruption for easy description. 1972e41f4b71Sopenharmony_ci 1973e41f4b71Sopenharmony_ci```cpp 1974e41f4b71Sopenharmony_cibool WriteDataToFile(const std::string& dstFilePath, const std::string& srcFilePath) 1975e41f4b71Sopenharmony_ci{ 1976e41f4b71Sopenharmony_ci const int bufferSize = 1024; 1977e41f4b71Sopenharmony_ci std::vector<char> buffer (bufferSize + 1, 0); 1978e41f4b71Sopenharmony_ci 1979e41f4b71Sopenharmony_ci std::ifstream srcFile(srcFilePath, std::ios::binary); 1980e41f4b71Sopenharmony_ci std::ofstream dstFile(dstFilePath, std::ios::binary); 1981e41f4b71Sopenharmony_ci 1982e41f4b71Sopenharmony_ci if (!dstFile || !dstFile) { 1983e41f4b71Sopenharmony_ci ... // Error handling 1984e41f4b71Sopenharmony_ci return false; 1985e41f4b71Sopenharmony_ci } 1986e41f4b71Sopenharmony_ci 1987e41f4b71Sopenharmony_ci while (true) { 1988e41f4b71Sopenharmony_ci // Read the block content from srcFile. 1989e41f4b71Sopenharmony_ci srcFile.read(buffer.data(), bufferSize); 1990e41f4b71Sopenharmony_ci std::streamsize size = srcFile ? bufferSize : srcFile.gcount(); 1991e41f4b71Sopenharmony_ci 1992e41f4b71Sopenharmony_ci // Write the block content to dstFile. 1993e41f4b71Sopenharmony_ci if (size > 0 && !dstFile.write(buffer.data(), size)) { 1994e41f4b71Sopenharmony_ci ... // Error handling 1995e41f4b71Sopenharmony_ci break; 1996e41f4b71Sopenharmony_ci } 1997e41f4b71Sopenharmony_ci 1998e41f4b71Sopenharmony_ci if (!srcFile) { 1999e41f4b71Sopenharmony_ci ... // Error check: An error is recorded before eof() is returned. 2000e41f4b71Sopenharmony_ci break; 2001e41f4b71Sopenharmony_ci } 2002e41f4b71Sopenharmony_ci } 2003e41f4b71Sopenharmony_ci // srcFile and dstFile are automatically closed when they exit the scope. 2004e41f4b71Sopenharmony_ci return true; 2005e41f4b71Sopenharmony_ci} 2006e41f4b71Sopenharmony_ci``` 2007e41f4b71Sopenharmony_ci 2008e41f4b71Sopenharmony_ciAvoid calling the command processor to execute external commands if functionality can be implemented by using library functions (as shown in the preceding example). If a single command needs to be called, use the **exec\*** function for parameterized calling and implement trustlist management on the called command. In addition, avoid using the **execlp()**, **execvp()**, and **execvpe()** functions because these functions depend on the external PATH environment variable. In this case, the externally input **fileName** is only used as a parameter of the **some\_tool** command, posing no command injection risks. 2009e41f4b71Sopenharmony_ci 2010e41f4b71Sopenharmony_ci```cpp 2011e41f4b71Sopenharmony_cipid_t pid; 2012e41f4b71Sopenharmony_cichar* const envp[] = {nullptr}; 2013e41f4b71Sopenharmony_ci... 2014e41f4b71Sopenharmony_cistd::string fileName = GetDirNameFromRemote(); 2015e41f4b71Sopenharmony_ci... 2016e41f4b71Sopenharmony_cipid = fork(); 2017e41f4b71Sopenharmony_ciif (pid < 0) { 2018e41f4b71Sopenharmony_ci ... 2019e41f4b71Sopenharmony_ci} else if (pid == 0) { 2020e41f4b71Sopenharmony_ci // Use some_tool to process the specified file. 2021e41f4b71Sopenharmony_ci execle("/bin/some_tool", "some_tool", fileName.c_str(), nullptr, envp); 2022e41f4b71Sopenharmony_ci _Exit(-1); 2023e41f4b71Sopenharmony_ci} 2024e41f4b71Sopenharmony_ci... 2025e41f4b71Sopenharmony_ciint status; 2026e41f4b71Sopenharmony_ciwaitpid(pid, &status, 0); 2027e41f4b71Sopenharmony_cistd::ofstream ofs(fileName, std::ios::in); 2028e41f4b71Sopenharmony_ci... 2029e41f4b71Sopenharmony_ci``` 2030e41f4b71Sopenharmony_ci 2031e41f4b71Sopenharmony_ciWhen the system command parsers (such as system) must be used to execute commands, the entered command strings must be checked based on an appropriate trustlist to prevent command injection. 2032e41f4b71Sopenharmony_ci 2033e41f4b71Sopenharmony_ci```cpp 2034e41f4b71Sopenharmony_cistd::string cmd = GetCmdFromRemote(); 2035e41f4b71Sopenharmony_ci 2036e41f4b71Sopenharmony_ci// Use the trustlist to check whether the command is valid. Only the "some_tool_a" and "some_tool_b" commands are allowed, and external control is not allowed. 2037e41f4b71Sopenharmony_ciif (!IsValidCmd(cmd.c_str())) { 2038e41f4b71Sopenharmony_ci ... // Error handling 2039e41f4b71Sopenharmony_ci} 2040e41f4b71Sopenharmony_cisystem(cmd.c_str()); 2041e41f4b71Sopenharmony_ci... 2042e41f4b71Sopenharmony_ci``` 2043e41f4b71Sopenharmony_ci 2044e41f4b71Sopenharmony_ci**\[Impact]** 2045e41f4b71Sopenharmony_ci 2046e41f4b71Sopenharmony_ci- If the command string passed to **system()**, **popen()**, or other command handler functions is externally controllable, an attacker may execute any command that exists in the system using the permission of the compromised process. 2047e41f4b71Sopenharmony_ci- If a dynamic library file is externally controllable, attackers can replace the dynamic library file, which may cause arbitrary code execution vulnerabilities in some cases. 2048e41f4b71Sopenharmony_ci 2049e41f4b71Sopenharmony_ci# Other C Coding Specifications 2050e41f4b71Sopenharmony_ci 2051e41f4b71Sopenharmony_ci## Do not apply the sizeof operator to function parameters of array type when taking the size of an array 2052e41f4b71Sopenharmony_ci 2053e41f4b71Sopenharmony_ci**\[Description]** 2054e41f4b71Sopenharmony_ci 2055e41f4b71Sopenharmony_ciThe **sizeof** operator yields the size (in bytes) of its operand, which can be an expression or the parenthesized name of a type, for example, `sizeof(int)` or `sizeof(int *)`. Footnote 103 in section 6.5.3.4 of the C11 standard states that: 2056e41f4b71Sopenharmony_ci 2057e41f4b71Sopenharmony_ci> When applied to a parameter declared to have array or function type, the **sizeof** operator yields the size of the adjusted (pointer) type. 2058e41f4b71Sopenharmony_ci 2059e41f4b71Sopenharmony_ciArguments declared as arrays in the argument list will be adjusted to pointers of corresponding types. For example, although the inArray argument in the `void Func(int inArray[LEN])` function is declared as an array, it is actually adjusted to an int pointer, that is, `void Func(int *inArray)`. As a result, `sizeof(inArray)` is equal to `sizeof(int *)` in this function, leading to unexpected result. For example, in the IA-32 architecture, `sizeof(inArray)` is 4, not the inArray size. 2060e41f4b71Sopenharmony_ci 2061e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2062e41f4b71Sopenharmony_ci 2063e41f4b71Sopenharmony_ciIn the following code example, the **ArrayInit()** function is used to initialize array elements. This function has a parameter declared as `int inArray[]`. When this function is called, a 256-element integer array **data** is passed to it. The **ArrayInit()** function uses `sizeof(inArray) / sizeof(inArray[0])` to determine the number of elements in the input array. However, **inArray** is a function parameter and therefore has a pointer type. As a result, `sizeof(inArray)` is equal to `sizeof(int *)`. The expression `sizeof(inArray) / sizeof(inArray[0])` evaluates to 1, regardless of the length of the array passed to the **ArrayInit()** function, leading to unexpected behavior. 2064e41f4b71Sopenharmony_ci 2065e41f4b71Sopenharmony_ci```c 2066e41f4b71Sopenharmony_ci#define DATA_LEN 256 2067e41f4b71Sopenharmony_civoid ArrayInit(int inArray[]) 2068e41f4b71Sopenharmony_ci{ 2069e41f4b71Sopenharmony_ci // Noncompliant: sizeof(inArray) is used to calculate the array size. 2070e41f4b71Sopenharmony_ci for (size_t i = 0; i < sizeof(inArray) / sizeof(inArray[0]); i++) { 2071e41f4b71Sopenharmony_ci ... 2072e41f4b71Sopenharmony_ci } 2073e41f4b71Sopenharmony_ci} 2074e41f4b71Sopenharmony_ci 2075e41f4b71Sopenharmony_civoid FunctionData(void) 2076e41f4b71Sopenharmony_ci{ 2077e41f4b71Sopenharmony_ci int data[DATA_LEN]; 2078e41f4b71Sopenharmony_ci 2079e41f4b71Sopenharmony_ci ... 2080e41f4b71Sopenharmony_ci ArrayInit(data); // Call ArrayInit() to initialize array data. 2081e41f4b71Sopenharmony_ci ... 2082e41f4b71Sopenharmony_ci} 2083e41f4b71Sopenharmony_ci``` 2084e41f4b71Sopenharmony_ci 2085e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2086e41f4b71Sopenharmony_ci 2087e41f4b71Sopenharmony_ciIn the following code example, the function definition is modified, an array size parameter is added, and the array size is correctly passed to the function. 2088e41f4b71Sopenharmony_ci 2089e41f4b71Sopenharmony_ci```c 2090e41f4b71Sopenharmony_ci#define DATA_LEN 256 2091e41f4b71Sopenharmony_ci// Function description: Argument len is the length of inArray. 2092e41f4b71Sopenharmony_civoid ArrayInit(int inArray[], size_t len) 2093e41f4b71Sopenharmony_ci{ 2094e41f4b71Sopenharmony_ci for (size_t i = 0; i < len; i++) { 2095e41f4b71Sopenharmony_ci ... 2096e41f4b71Sopenharmony_ci } 2097e41f4b71Sopenharmony_ci} 2098e41f4b71Sopenharmony_ci 2099e41f4b71Sopenharmony_civoid FunctionData(void) 2100e41f4b71Sopenharmony_ci{ 2101e41f4b71Sopenharmony_ci int data[DATA_LEN]; 2102e41f4b71Sopenharmony_ci 2103e41f4b71Sopenharmony_ci ArrayInit(data, sizeof(data) / sizeof(data[0])); 2104e41f4b71Sopenharmony_ci ... 2105e41f4b71Sopenharmony_ci} 2106e41f4b71Sopenharmony_ci``` 2107e41f4b71Sopenharmony_ci 2108e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2109e41f4b71Sopenharmony_ci 2110e41f4b71Sopenharmony_ciIn the following code example, `sizeof(inArray)` does not equal `ARRAY_MAX_LEN * sizeof(int)`, because the **sizeof** operator, when applied to a parameter declared to have array type, yields the size of the adjusted (pointer) type even if the parameter declaration specifies a length. In this case, `sizeof(inArray)` is equal to `sizeof(int *)`. 2111e41f4b71Sopenharmony_ci 2112e41f4b71Sopenharmony_ci```c 2113e41f4b71Sopenharmony_ci#define ARRAY_MAX_LEN 256 2114e41f4b71Sopenharmony_ci 2115e41f4b71Sopenharmony_civoid ArrayInit(int inArray[ARRAY_MAX_LEN]) 2116e41f4b71Sopenharmony_ci{ 2117e41f4b71Sopenharmony_ci // Noncompliant: sizeof(inArray), pointer size rather than array size, which is not as expected 2118e41f4b71Sopenharmony_ci for (size_t i = 0; i < sizeof(inArray) / sizeof(inArray[0]); i++) { 2119e41f4b71Sopenharmony_ci ... 2120e41f4b71Sopenharmony_ci } 2121e41f4b71Sopenharmony_ci} 2122e41f4b71Sopenharmony_ci 2123e41f4b71Sopenharmony_ciint main(void) 2124e41f4b71Sopenharmony_ci{ 2125e41f4b71Sopenharmony_ci int masterArray[ARRAY_MAX_LEN]; 2126e41f4b71Sopenharmony_ci 2127e41f4b71Sopenharmony_ci ... 2128e41f4b71Sopenharmony_ci ArrayInit(masterArray); 2129e41f4b71Sopenharmony_ci 2130e41f4b71Sopenharmony_ci return 0; 2131e41f4b71Sopenharmony_ci} 2132e41f4b71Sopenharmony_ci``` 2133e41f4b71Sopenharmony_ci 2134e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2135e41f4b71Sopenharmony_ci 2136e41f4b71Sopenharmony_ciIn the following code example, the specified array length is indicated by the **len** argument. 2137e41f4b71Sopenharmony_ci 2138e41f4b71Sopenharmony_ci```c 2139e41f4b71Sopenharmony_ci#define ARRAY_MAX_LEN 256 2140e41f4b71Sopenharmony_ci 2141e41f4b71Sopenharmony_ci// Function description: Argument len is the length of the argument array. 2142e41f4b71Sopenharmony_civoid ArrayInit(int inArray[], size_t len) 2143e41f4b71Sopenharmony_ci{ 2144e41f4b71Sopenharmony_ci for (size_t i = 0; i < len; i++) { 2145e41f4b71Sopenharmony_ci ... 2146e41f4b71Sopenharmony_ci } 2147e41f4b71Sopenharmony_ci} 2148e41f4b71Sopenharmony_ci 2149e41f4b71Sopenharmony_ciint main(void) 2150e41f4b71Sopenharmony_ci{ 2151e41f4b71Sopenharmony_ci int masterArray[ARRAY_MAX_LEN]; 2152e41f4b71Sopenharmony_ci 2153e41f4b71Sopenharmony_ci ArrayInit(masterArray, ARRAY_MAX_LEN); 2154e41f4b71Sopenharmony_ci ... 2155e41f4b71Sopenharmony_ci 2156e41f4b71Sopenharmony_ci return 0; 2157e41f4b71Sopenharmony_ci} 2158e41f4b71Sopenharmony_ci``` 2159e41f4b71Sopenharmony_ci 2160e41f4b71Sopenharmony_ci## Do not perform the **sizeof** operation on pointer variables to obtain the array size 2161e41f4b71Sopenharmony_ci 2162e41f4b71Sopenharmony_ci**\[Description]** 2163e41f4b71Sopenharmony_ci 2164e41f4b71Sopenharmony_ciPerforming the **sizeof** operation on a pointer that is used as an array leads to an unexpected result. For example, in the variable definition `char *p = array` where array is defined as `char array[LEN]`, the result of the expression `sizeof(p)` is the same as that of `sizeof(char *)`, but not the size of the array. 2165e41f4b71Sopenharmony_ci 2166e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2167e41f4b71Sopenharmony_ci 2168e41f4b71Sopenharmony_ciIn the following code example, **buffer** is a pointer while **path** is an array. The programmer wants to clear the two memory segments. However, the programmer mistakenly writes the memory size as `sizeof(buffer)`, leading to an unexpected result. 2169e41f4b71Sopenharmony_ci 2170e41f4b71Sopenharmony_ci```c 2171e41f4b71Sopenharmony_cichar path[MAX_PATH]; 2172e41f4b71Sopenharmony_cichar *buffer = (char *)malloc(SIZE); 2173e41f4b71Sopenharmony_ci... 2174e41f4b71Sopenharmony_ci 2175e41f4b71Sopenharmony_ci... 2176e41f4b71Sopenharmony_cimemset(path, 0, sizeof(path)); 2177e41f4b71Sopenharmony_ci 2178e41f4b71Sopenharmony_ci// sizeof causes an unexpected result because its result will be the pointer size but not the buffer size. 2179e41f4b71Sopenharmony_cimemset(buffer, 0, sizeof(buffer)); 2180e41f4b71Sopenharmony_ci``` 2181e41f4b71Sopenharmony_ci 2182e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2183e41f4b71Sopenharmony_ci 2184e41f4b71Sopenharmony_ciIn the following code example, `sizeof(buffer)` is changed to the size of the requested buffer: 2185e41f4b71Sopenharmony_ci 2186e41f4b71Sopenharmony_ci```c 2187e41f4b71Sopenharmony_cichar path[MAX_PATH]; 2188e41f4b71Sopenharmony_cichar *buffer = (char *)malloc(SIZE); 2189e41f4b71Sopenharmony_ci... 2190e41f4b71Sopenharmony_ci 2191e41f4b71Sopenharmony_ci... 2192e41f4b71Sopenharmony_cimemset(path, 0, sizeof(path)); 2193e41f4b71Sopenharmony_cimemset(buffer, 0, SIZE); // Use the requested buffer size. 2194e41f4b71Sopenharmony_ci``` 2195e41f4b71Sopenharmony_ci 2196e41f4b71Sopenharmony_ci## Do not directly use external data to concatenate SQL statements 2197e41f4b71Sopenharmony_ci 2198e41f4b71Sopenharmony_ci**\[Description]** 2199e41f4b71Sopenharmony_ci 2200e41f4b71Sopenharmony_ciAn SQL injection vulnerability arises when an SQL query is dynamically altered to form an altogether different query. Execution of this altered query may result in information leaks or data tampering. The root cause of SQL injection is the use of external data to concatenate SQL statements. In C/C++, external data is used to concatenate SQL statements in the following scenarios (but not limited to): 2201e41f4b71Sopenharmony_ci 2202e41f4b71Sopenharmony_ci- Argument for calling **mysql\_query()** and **Execute()** when connecting to MySQL 2203e41f4b71Sopenharmony_ci- Argument for calling **dbsqlexec()** of the db-library driver when connecting to the SQL server 2204e41f4b71Sopenharmony_ci- SQL statement parameter for calling **SQLprepare()** of the ODBC driver when connecting to the database 2205e41f4b71Sopenharmony_ci- Argument for calling **otl\_stream()** and **otl\_column\_desc()** in OTL class library in C++ language 2206e41f4b71Sopenharmony_ci- Input argument for calling **ExecuteWithResSQL()** when connecting to the Oracle database in C++ language 2207e41f4b71Sopenharmony_ci 2208e41f4b71Sopenharmony_ciThe following methods can be used to prevent SQL injection: 2209e41f4b71Sopenharmony_ci 2210e41f4b71Sopenharmony_ci- Use parameterized query (also known as a prepared statement): Parameterized query is a simple and effective way to prevent SQL injection and must be used preferentially. The databases MySQL and Oracle (OCI) support parameterized query. 2211e41f4b71Sopenharmony_ci- Use parameterized query (driven by ODBC): supported by Oracle, SQL server, PostgreSQL, and GaussDB databases. 2212e41f4b71Sopenharmony_ci- Verify external data (trustlist verification is recommended). 2213e41f4b71Sopenharmony_ci- Escape external SQL special characters. 2214e41f4b71Sopenharmony_ci 2215e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2216e41f4b71Sopenharmony_ci 2217e41f4b71Sopenharmony_ciThe following code concatenates user input without checking the input, causing SQL injection risks: 2218e41f4b71Sopenharmony_ci 2219e41f4b71Sopenharmony_ci```c 2220e41f4b71Sopenharmony_cichar name[NAME_MAX]; 2221e41f4b71Sopenharmony_cichar sqlStatements[SQL_CMD_MAX]; 2222e41f4b71Sopenharmony_ciint ret = GetUserInput(name, NAME_MAX); 2223e41f4b71Sopenharmony_ci... 2224e41f4b71Sopenharmony_ciret = sprintf(sqlStatements, 2225e41f4b71Sopenharmony_ci "SELECT childinfo FROM children WHERE name= ‘%s’", 2226e41f4b71Sopenharmony_ci name); 2227e41f4b71Sopenharmony_ci... 2228e41f4b71Sopenharmony_ciret = mysql_query(&myConnection, sqlStatements); 2229e41f4b71Sopenharmony_ci... 2230e41f4b71Sopenharmony_ci``` 2231e41f4b71Sopenharmony_ci 2232e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2233e41f4b71Sopenharmony_ci 2234e41f4b71Sopenharmony_ciUse prepared statements for parameterized query to defend against SQL injection attacks: 2235e41f4b71Sopenharmony_ci 2236e41f4b71Sopenharmony_ci```c 2237e41f4b71Sopenharmony_cichar name[NAME_MAX]; 2238e41f4b71Sopenharmony_ci... 2239e41f4b71Sopenharmony_ciMYSQL_STMT *stmt = mysql_stmt_init(myConnection); 2240e41f4b71Sopenharmony_cichar *query = "SELECT childinfo FROM children WHERE name= ?"; 2241e41f4b71Sopenharmony_ciif (mysql_stmt_prepare(stmt, query, strlen(query))) { 2242e41f4b71Sopenharmony_ci ... 2243e41f4b71Sopenharmony_ci} 2244e41f4b71Sopenharmony_ciint ret = GetUserInput(name, NAME_MAX); 2245e41f4b71Sopenharmony_ci... 2246e41f4b71Sopenharmony_ciMYSQL_BIND params[1]; 2247e41f4b71Sopenharmony_ci(void)memset(params, 0, sizeof(params)); 2248e41f4b71Sopenharmony_ci... 2249e41f4b71Sopenharmony_ciparams[0].bufferType = MYSQL_TYPE_STRING; 2250e41f4b71Sopenharmony_ciparams[0].buffer = (char *)name; 2251e41f4b71Sopenharmony_ciparams[0].bufferLength = strlen(name); 2252e41f4b71Sopenharmony_ciparams[0].isNull = 0; 2253e41f4b71Sopenharmony_ci 2254e41f4b71Sopenharmony_cibool isCompleted = mysql_stmt_bind_param(stmt, params); 2255e41f4b71Sopenharmony_ci... 2256e41f4b71Sopenharmony_ciret = mysql_stmt_execute(stmt); 2257e41f4b71Sopenharmony_ci... 2258e41f4b71Sopenharmony_ci``` 2259e41f4b71Sopenharmony_ci 2260e41f4b71Sopenharmony_ci**\[Impact]** 2261e41f4b71Sopenharmony_ci 2262e41f4b71Sopenharmony_ciIf the string of a concatenated SQL statement is externally controllable, attackers can inject specific strings to deceive programs into executing malicious SQL commands, causing information leakage, permission bypass, and data tampering. 2263e41f4b71Sopenharmony_ci 2264e41f4b71Sopenharmony_ci## Clear sensitive information from memory immediately after using it 2265e41f4b71Sopenharmony_ci 2266e41f4b71Sopenharmony_ci**\[Description]** 2267e41f4b71Sopenharmony_ci 2268e41f4b71Sopenharmony_ciSensitive information (such as passwords and keys) in memory must be cleared immediately after being used to prevent it from being obtained by attackers or accidentally disclosed to low-privilege users. Memory includes but is not limited to: 2269e41f4b71Sopenharmony_ci 2270e41f4b71Sopenharmony_ci- Dynamically allocated memory 2271e41f4b71Sopenharmony_ci- Statically allocated memory 2272e41f4b71Sopenharmony_ci- Automatically allocated (stack) memory 2273e41f4b71Sopenharmony_ci- Memory cache 2274e41f4b71Sopenharmony_ci- Disk cache 2275e41f4b71Sopenharmony_ci 2276e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2277e41f4b71Sopenharmony_ci 2278e41f4b71Sopenharmony_ciGenerally, memory data does not need to be cleared before memory resources are released to prevent extra overheads during running. Therefore, after memory resources are released, the data remains in memory. In this case, sensitive information in the data may be leaked accidentally. To prevent sensitive information leakage, you must clear sensitive information from memory before releasing memory resources. In the following code example, the sensitive information **secret** stored in the referenced dynamic memory is copied to the newly dynamically allocated buffer **newSecret**, and is finally released through **free()**. As data is not cleared before the memory block is released, the memory block may be reallocated to another part of the program, and sensitive information stored in **newSecret** may be accidentally disclosed. 2279e41f4b71Sopenharmony_ci 2280e41f4b71Sopenharmony_ci```c 2281e41f4b71Sopenharmony_cichar *secret = NULL; 2282e41f4b71Sopenharmony_ci/* 2283e41f4b71Sopenharmony_ci * Assume that secret points to sensitive information whose content is less than SIZE_MAX 2284e41f4b71Sopenharmony_ci * and ends with null. 2285e41f4b71Sopenharmony_ci */ 2286e41f4b71Sopenharmony_ci 2287e41f4b71Sopenharmony_cisize_t size = strlen(secret); 2288e41f4b71Sopenharmony_cichar *newSecret = NULL; 2289e41f4b71Sopenharmony_cinewSecret = (char *)malloc(size + 1); 2290e41f4b71Sopenharmony_ciif (newSecret == NULL) { 2291e41f4b71Sopenharmony_ci ... // Error handling 2292e41f4b71Sopenharmony_ci} else { 2293e41f4b71Sopenharmony_ci errno_t ret = strcpy(newSecret, secret); 2294e41f4b71Sopenharmony_ci ... // Process ret 2295e41f4b71Sopenharmony_ci 2296e41f4b71Sopenharmony_ci ... // Process newSecret... 2297e41f4b71Sopenharmony_ci 2298e41f4b71Sopenharmony_ci free(newSecret); 2299e41f4b71Sopenharmony_ci newSecret = NULL; 2300e41f4b71Sopenharmony_ci} 2301e41f4b71Sopenharmony_ci... 2302e41f4b71Sopenharmony_ci``` 2303e41f4b71Sopenharmony_ci 2304e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2305e41f4b71Sopenharmony_ci 2306e41f4b71Sopenharmony_ciIn the following code example, to prevent information leakage, clear the dynamic memory that contains sensitive information (by filling the memory space with '\\0') and then release it. 2307e41f4b71Sopenharmony_ci 2308e41f4b71Sopenharmony_ci```c 2309e41f4b71Sopenharmony_cichar *secret = NULL; 2310e41f4b71Sopenharmony_ci/* 2311e41f4b71Sopenharmony_ci * Assume that secret points to sensitive information whose content is less than SIZE_MAX 2312e41f4b71Sopenharmony_ci * and ends with null. 2313e41f4b71Sopenharmony_ci */ 2314e41f4b71Sopenharmony_cisize_t size = strlen(secret); 2315e41f4b71Sopenharmony_cichar *newSecret = NULL; 2316e41f4b71Sopenharmony_cinewSecret = (char *)malloc(size + 1); 2317e41f4b71Sopenharmony_ciif (newSecret == NULL) { 2318e41f4b71Sopenharmony_ci ... // Error handling 2319e41f4b71Sopenharmony_ci} else { 2320e41f4b71Sopenharmony_ci errno_t ret = strcpy(newSecret, secret); 2321e41f4b71Sopenharmony_ci ... // Process ret 2322e41f4b71Sopenharmony_ci 2323e41f4b71Sopenharmony_ci ... // Process newSecret... 2324e41f4b71Sopenharmony_ci 2325e41f4b71Sopenharmony_ci (void)memset(newSecret, 0, size + 1); 2326e41f4b71Sopenharmony_ci free(newSecret); 2327e41f4b71Sopenharmony_ci newSecret = NULL; 2328e41f4b71Sopenharmony_ci} 2329e41f4b71Sopenharmony_ci... 2330e41f4b71Sopenharmony_ci``` 2331e41f4b71Sopenharmony_ci 2332e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2333e41f4b71Sopenharmony_ci 2334e41f4b71Sopenharmony_ciThe following code is another scenario involving sensitive information clearance. After obtaining the password, the code saves the password to **password** for verification. After the password is used, `memset()` is used to clear the password. 2335e41f4b71Sopenharmony_ci 2336e41f4b71Sopenharmony_ci```c 2337e41f4b71Sopenharmony_ciint Foo(void) 2338e41f4b71Sopenharmony_ci{ 2339e41f4b71Sopenharmony_ci char password[MAX_PWD_LEN]; 2340e41f4b71Sopenharmony_ci if (!GetPassword(password, sizeof(password))) { 2341e41f4b71Sopenharmony_ci ... 2342e41f4b71Sopenharmony_ci } 2343e41f4b71Sopenharmony_ci if (!VerifyPassword(password)) { 2344e41f4b71Sopenharmony_ci ... 2345e41f4b71Sopenharmony_ci } 2346e41f4b71Sopenharmony_ci ... 2347e41f4b71Sopenharmony_ci (void)memset(password, 0, sizeof(password)); 2348e41f4b71Sopenharmony_ci ... 2349e41f4b71Sopenharmony_ci} 2350e41f4b71Sopenharmony_ci``` 2351e41f4b71Sopenharmony_ci 2352e41f4b71Sopenharmony_ci**NOTE**: Ensure that the code for clearing sensitive information is always valid even if the compiler has been optimized. 2353e41f4b71Sopenharmony_ci 2354e41f4b71Sopenharmony_ciFor example, the following code uses an invalid statement in the optimized compiler. 2355e41f4b71Sopenharmony_ci 2356e41f4b71Sopenharmony_ci```c 2357e41f4b71Sopenharmony_ciint SecureLogin(void) 2358e41f4b71Sopenharmony_ci{ 2359e41f4b71Sopenharmony_ci char pwd[PWD_SIZE]; 2360e41f4b71Sopenharmony_ci if (RetrievePassword(pwd, sizeof(pwd))) { 2361e41f4b71Sopenharmony_ci ... // Password check and other processing 2362e41f4b71Sopenharmony_ci } 2363e41f4b71Sopenharmony_ci memset(pwd, 0, sizeof(pwd)); // Compiler optimizations may invalidate this statement. 2364e41f4b71Sopenharmony_ci ... 2365e41f4b71Sopenharmony_ci} 2366e41f4b71Sopenharmony_ci``` 2367e41f4b71Sopenharmony_ci 2368e41f4b71Sopenharmony_ciSome compilers do not execute the code during optimization if they consider the code do not change program execution results. Therefore, the **memset()** function may become invalid after optimization. 2369e41f4b71Sopenharmony_ci 2370e41f4b71Sopenharmony_ciIf the compiler supports the **#pragma** instruction, the instruction can be used to instruct the compiler not to optimize. 2371e41f4b71Sopenharmony_ci 2372e41f4b71Sopenharmony_ci```c 2373e41f4b71Sopenharmony_civoid SecureLogin(void) 2374e41f4b71Sopenharmony_ci{ 2375e41f4b71Sopenharmony_ci char pwd[PWD_SIZE]; 2376e41f4b71Sopenharmony_ci if (RetrievePassword(pwd, sizeof(pwd))) { 2377e41f4b71Sopenharmony_ci ... // Password check and other processing 2378e41f4b71Sopenharmony_ci } 2379e41f4b71Sopenharmony_ci #pragma optimize("", off) 2380e41f4b71Sopenharmony_ci // Clear memory. 2381e41f4b71Sopenharmony_ci ... 2382e41f4b71Sopenharmony_ci #pragma optimize("", on) 2383e41f4b71Sopenharmony_ci ... 2384e41f4b71Sopenharmony_ci} 2385e41f4b71Sopenharmony_ci``` 2386e41f4b71Sopenharmony_ci 2387e41f4b71Sopenharmony_ci**\[Impact]** 2388e41f4b71Sopenharmony_ci 2389e41f4b71Sopenharmony_ciFailure to rapidly clear sensitive information may cause information leakage. 2390e41f4b71Sopenharmony_ci 2391e41f4b71Sopenharmony_ci## Create files with appropriate access permissions explicitly specified 2392e41f4b71Sopenharmony_ci 2393e41f4b71Sopenharmony_ci**\[Description]** 2394e41f4b71Sopenharmony_ci 2395e41f4b71Sopenharmony_ciIf no appropriate access permissions are explicitly specified when a file is created, unauthorized users may access the file, causing information leakage, file data tampering, and malicious code injection into the file. 2396e41f4b71Sopenharmony_ci 2397e41f4b71Sopenharmony_ciAlthough file access permissions depend on the file system, many file creation functions (POSIX **open()** functions, etc.) provide mechanisms to set (or influence) file access permissions. Therefore, when these functions are used to create files, appropriate file access permissions must be explicitly specified to prevent unintended access. 2398e41f4b71Sopenharmony_ci 2399e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2400e41f4b71Sopenharmony_ci 2401e41f4b71Sopenharmony_ciThe POSIX **open()** function is used to create a file but the access permission for the file is not specified, which may cause the file to be created with excessive access permissions. This may lead to vulnerabilities (e.g. CVE-2006-1174). 2402e41f4b71Sopenharmony_ci 2403e41f4b71Sopenharmony_ci```c 2404e41f4b71Sopenharmony_civoid Foo(void) 2405e41f4b71Sopenharmony_ci{ 2406e41f4b71Sopenharmony_ci int fd = -1; 2407e41f4b71Sopenharmony_ci char *filename = NULL; 2408e41f4b71Sopenharmony_ci 2409e41f4b71Sopenharmony_ci ... // Initialize filename. 2410e41f4b71Sopenharmony_ci 2411e41f4b71Sopenharmony_ci fd = open(filename, O_CREAT | O_WRONLY); // Access permission not explicitly specified 2412e41f4b71Sopenharmony_ci if (fd == -1) { 2413e41f4b71Sopenharmony_ci ... // Error handling 2414e41f4b71Sopenharmony_ci } 2415e41f4b71Sopenharmony_ci ... 2416e41f4b71Sopenharmony_ci} 2417e41f4b71Sopenharmony_ci``` 2418e41f4b71Sopenharmony_ci 2419e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2420e41f4b71Sopenharmony_ci 2421e41f4b71Sopenharmony_ciAccess permissions for the newly created file should be explicitly specified in the third argument to **open()**. Access permissions for a file can be set based on actual applications of the file. 2422e41f4b71Sopenharmony_ci 2423e41f4b71Sopenharmony_ci```c 2424e41f4b71Sopenharmony_civoid Foo(void) 2425e41f4b71Sopenharmony_ci{ 2426e41f4b71Sopenharmony_ci int fd = -1; 2427e41f4b71Sopenharmony_ci char *filename = NULL; 2428e41f4b71Sopenharmony_ci 2429e41f4b71Sopenharmony_ci ... // Initialize filename and specify its access permissions. 2430e41f4b71Sopenharmony_ci 2431e41f4b71Sopenharmony_ci // Explicitly specify necessary access permissions for a file. 2432e41f4b71Sopenharmony_ci int fd = open(filename, O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR); 2433e41f4b71Sopenharmony_ci if (fd == -1) { 2434e41f4b71Sopenharmony_ci ... // Error handling 2435e41f4b71Sopenharmony_ci } 2436e41f4b71Sopenharmony_ci ... 2437e41f4b71Sopenharmony_ci} 2438e41f4b71Sopenharmony_ci``` 2439e41f4b71Sopenharmony_ci 2440e41f4b71Sopenharmony_ci**\[Impact]** 2441e41f4b71Sopenharmony_ci 2442e41f4b71Sopenharmony_ciCreating files with weak access permissions may cause unauthorized access to these files. 2443e41f4b71Sopenharmony_ci 2444e41f4b71Sopenharmony_ci## Canonicalize and validate file paths before using them 2445e41f4b71Sopenharmony_ci 2446e41f4b71Sopenharmony_ci**\[Description]** 2447e41f4b71Sopenharmony_ci 2448e41f4b71Sopenharmony_ciFile paths from external data must be validated. Otherwise, system files may be accessed randomly. However, direct validation is not allowed. The file paths must be canonicalized before validation because a file can be described and referenced by paths in various forms. For example, a file path can be an absolute path or a relative path, and the path name, directory name, or file name may contain characters (for example, "." or "..") that make validation difficult and inaccurate. In addition, the file may also be a symbolic link, which further obscures the actual location or identity of the file, making validation difficult and inaccurate. Therefore, file paths must be canonicalized to make it much easier to validate a path, directory, or file name, thereby improving validation accuracy. 2449e41f4b71Sopenharmony_ci 2450e41f4b71Sopenharmony_ciBecause the canonical form may vary with operating systems and file systems, it is best to use a canonical form consistent with the current system features. 2451e41f4b71Sopenharmony_ci 2452e41f4b71Sopenharmony_ciTake an example as follows: 2453e41f4b71Sopenharmony_ci 2454e41f4b71Sopenharmony_ci```c 2455e41f4b71Sopenharmony_ciCanonicalize file paths coming from external data. Without canonicalization, attackers have chances to construct file paths for unauthorized access to files. 2456e41f4b71Sopenharmony_ciFor example, an attacker can construct "../../../etc/passwd" to access any file. 2457e41f4b71Sopenharmony_ci``` 2458e41f4b71Sopenharmony_ci 2459e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2460e41f4b71Sopenharmony_ci 2461e41f4b71Sopenharmony_ciIn this noncompliant code example, **inputFilename** contains a file name that originates from a tainted source, and the file is opened for writing. Before this file name is used for file operations, it should be validated to ensure that it references an expected and valid file. Unfortunately, the file name referenced by **inputFilename** may contain special characters, such as directory characters, which make validation difficult or even impossible. In addition, **inputFilename** may contain a symbolic link to any file path. Even if the file name passes validation, it is invalid. In this scenario, even if the file name is directly validated, the expected result cannot be obtained. The call to **fopen()** may result in unintended access to a file. 2462e41f4b71Sopenharmony_ci 2463e41f4b71Sopenharmony_ci```c 2464e41f4b71Sopenharmony_ci... 2465e41f4b71Sopenharmony_ci 2466e41f4b71Sopenharmony_ciif (!verify_file(inputFilename) { // inputFilename is validated without being canonicalized. 2467e41f4b71Sopenharmony_ci ... // Error handling 2468e41f4b71Sopenharmony_ci} 2469e41f4b71Sopenharmony_ci 2470e41f4b71Sopenharmony_ciif (fopen(inputFilename, "w") == NULL) { 2471e41f4b71Sopenharmony_ci ... // Error handling 2472e41f4b71Sopenharmony_ci} 2473e41f4b71Sopenharmony_ci 2474e41f4b71Sopenharmony_ci... 2475e41f4b71Sopenharmony_ci``` 2476e41f4b71Sopenharmony_ci 2477e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2478e41f4b71Sopenharmony_ci 2479e41f4b71Sopenharmony_ciCanonicalizing file names is difficult because it requires an understanding of the underlying file system. The POSIX **realpath()** function can help convert path names to a canonical form. According to Standard for Information Technology—Portable Operating System Interface (POSIX®), Base Specifications, Issue 7 \[IEEE Std 1003.1:2013]: 2480e41f4b71Sopenharmony_ci 2481e41f4b71Sopenharmony_ci- The **realpath()** function shall derive, from the pathname pointed to by **filename**, an absolute pathname that names the same file, whose resolution does not involve a dot (.), double dots (..), or symbolic links. Further verification, such as ensuring that two consecutive slashes or special files do not appear in the file name, must be performed after canonicalization. For more information about how to perform path name resolution, see section 4.12 "Pathname Resolution" of IEEE Std 1003.1:2013. There are many precautions for using the **realpath()** function. With an understanding of the preceding principles, the following solution can be taken to address the noncompliant code example. 2482e41f4b71Sopenharmony_ci 2483e41f4b71Sopenharmony_ci```c 2484e41f4b71Sopenharmony_cichar *realpathRes = NULL; 2485e41f4b71Sopenharmony_ci 2486e41f4b71Sopenharmony_ci... 2487e41f4b71Sopenharmony_ci 2488e41f4b71Sopenharmony_ci// Canonicalize inputFilename before validation. 2489e41f4b71Sopenharmony_cirealpathRes = realpath(inputFilename, NULL); 2490e41f4b71Sopenharmony_ciif (realpathRes == NULL) { 2491e41f4b71Sopenharmony_ci ... // Canonicalization error handling 2492e41f4b71Sopenharmony_ci} 2493e41f4b71Sopenharmony_ci 2494e41f4b71Sopenharmony_ci// Validate the file path after canonicalizing it 2495e41f4b71Sopenharmony_ciif (!verify_file(realpathRes) { 2496e41f4b71Sopenharmony_ci ... // Validation error handling 2497e41f4b71Sopenharmony_ci} 2498e41f4b71Sopenharmony_ci 2499e41f4b71Sopenharmony_ci// Use 2500e41f4b71Sopenharmony_ciif (fopen(realpathRes, "w") == NULL) { 2501e41f4b71Sopenharmony_ci ... // Operation error handling 2502e41f4b71Sopenharmony_ci} 2503e41f4b71Sopenharmony_ci 2504e41f4b71Sopenharmony_ci... 2505e41f4b71Sopenharmony_ci 2506e41f4b71Sopenharmony_cifree(realpathRes); 2507e41f4b71Sopenharmony_cirealpathRes = NULL; 2508e41f4b71Sopenharmony_ci... 2509e41f4b71Sopenharmony_ci``` 2510e41f4b71Sopenharmony_ci 2511e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2512e41f4b71Sopenharmony_ci 2513e41f4b71Sopenharmony_ciBased on the actual scenario, a second solution can also be used. The description is as follows: If `PATH_MAX` is defined as a constant in **limits.h**, it is also safe to call **realpath()** with a non-null `resolved_path` value. In this example, the **realpath()** function expects `resolved_path` to refer to a character array that is large enough to hold the canonicalized path. If **PATH\_MAX** is defined, allocate a buffer of size `PATH_MAX` to hold the result of **realpath()**. The compliant code example is as follows: 2514e41f4b71Sopenharmony_ci 2515e41f4b71Sopenharmony_ci```c 2516e41f4b71Sopenharmony_cichar *realpathRes = NULL; 2517e41f4b71Sopenharmony_cichar *canonicalFilename = NULL; 2518e41f4b71Sopenharmony_cisize_t pathSize = 0; 2519e41f4b71Sopenharmony_ci 2520e41f4b71Sopenharmony_ci... 2521e41f4b71Sopenharmony_ci 2522e41f4b71Sopenharmony_cipathSize = (size_t)PATH_MAX; 2523e41f4b71Sopenharmony_ci 2524e41f4b71Sopenharmony_ciif (VerifyPathSize(pathSize)) { 2525e41f4b71Sopenharmony_ci canonicalFilename = (char *)malloc(pathSize); 2526e41f4b71Sopenharmony_ci 2527e41f4b71Sopenharmony_ci if (canonicalFilename == NULL) { 2528e41f4b71Sopenharmony_ci ... // Error handling 2529e41f4b71Sopenharmony_ci } 2530e41f4b71Sopenharmony_ci 2531e41f4b71Sopenharmony_ci realpathRes = realpath(inputFilename, canonicalFilename); 2532e41f4b71Sopenharmony_ci} 2533e41f4b71Sopenharmony_ci 2534e41f4b71Sopenharmony_ciif (realpathRes == NULL) { 2535e41f4b71Sopenharmony_ci ... // Error handling 2536e41f4b71Sopenharmony_ci} 2537e41f4b71Sopenharmony_ci 2538e41f4b71Sopenharmony_ciif (VerifyFile(realpathRes)) { 2539e41f4b71Sopenharmony_ci ... // Error handling 2540e41f4b71Sopenharmony_ci} 2541e41f4b71Sopenharmony_ci 2542e41f4b71Sopenharmony_ciif (fopen(realpathRes, "w") == NULL ) { 2543e41f4b71Sopenharmony_ci ... // Error handling 2544e41f4b71Sopenharmony_ci} 2545e41f4b71Sopenharmony_ci 2546e41f4b71Sopenharmony_ci... 2547e41f4b71Sopenharmony_ci 2548e41f4b71Sopenharmony_cifree(canonicalFilename); 2549e41f4b71Sopenharmony_cicanonicalFilename = NULL; 2550e41f4b71Sopenharmony_ci... 2551e41f4b71Sopenharmony_ci``` 2552e41f4b71Sopenharmony_ci 2553e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2554e41f4b71Sopenharmony_ci 2555e41f4b71Sopenharmony_ciThe following code obtains file names from external data, concatenates them into a file path, and directly reads the file content. As a result, attackers can read the content of any file. 2556e41f4b71Sopenharmony_ci 2557e41f4b71Sopenharmony_ci```c 2558e41f4b71Sopenharmony_cichar *filename = GetMsgFromRemote(); 2559e41f4b71Sopenharmony_ci... 2560e41f4b71Sopenharmony_ciint ret = sprintf(untrustPath, "/tmp/%s", filename); 2561e41f4b71Sopenharmony_ci... 2562e41f4b71Sopenharmony_cichar *text = ReadFileContent(untrustPath); 2563e41f4b71Sopenharmony_ci``` 2564e41f4b71Sopenharmony_ci 2565e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2566e41f4b71Sopenharmony_ci 2567e41f4b71Sopenharmony_ciCanonicalize the file path and then check whether the path is valid in the program. 2568e41f4b71Sopenharmony_ci 2569e41f4b71Sopenharmony_ci```c 2570e41f4b71Sopenharmony_cichar *filename = GetMsgFromRemote(); 2571e41f4b71Sopenharmony_ci... 2572e41f4b71Sopenharmony_cisprintf(untrustPath, "/tmp/%s", filename); 2573e41f4b71Sopenharmony_cichar path[PATH_MAX]; 2574e41f4b71Sopenharmony_ciif (realpath(untrustPath, path) == NULL) { 2575e41f4b71Sopenharmony_ci ... // Error handling 2576e41f4b71Sopenharmony_ci} 2577e41f4b71Sopenharmony_ciif (!IsValidPath(path)) { // Check whether the file path is valid. 2578e41f4b71Sopenharmony_ci ... // Error handling 2579e41f4b71Sopenharmony_ci} 2580e41f4b71Sopenharmony_cichar *text = ReadFileContent(path); 2581e41f4b71Sopenharmony_ci``` 2582e41f4b71Sopenharmony_ci 2583e41f4b71Sopenharmony_ci**\[Exception]** 2584e41f4b71Sopenharmony_ci 2585e41f4b71Sopenharmony_ciFile paths can be manually entered on the console where the command line program runs. 2586e41f4b71Sopenharmony_ci 2587e41f4b71Sopenharmony_ci```c 2588e41f4b71Sopenharmony_ciint main(int argc, char **argv) 2589e41f4b71Sopenharmony_ci{ 2590e41f4b71Sopenharmony_ci int fd = -1; 2591e41f4b71Sopenharmony_ci 2592e41f4b71Sopenharmony_ci if (argc == 2) { 2593e41f4b71Sopenharmony_ci fd = open(argv[1], O_RDONLY); 2594e41f4b71Sopenharmony_ci ... 2595e41f4b71Sopenharmony_ci } 2596e41f4b71Sopenharmony_ci 2597e41f4b71Sopenharmony_ci ... 2598e41f4b71Sopenharmony_ci return 0; 2599e41f4b71Sopenharmony_ci} 2600e41f4b71Sopenharmony_ci``` 2601e41f4b71Sopenharmony_ci 2602e41f4b71Sopenharmony_ci**\[Impact]** 2603e41f4b71Sopenharmony_ci 2604e41f4b71Sopenharmony_ciFailure to canonicalize and validate untrusted file paths may cause access to any file. 2605e41f4b71Sopenharmony_ci 2606e41f4b71Sopenharmony_ci## Do not create temporary files in shared directories 2607e41f4b71Sopenharmony_ci 2608e41f4b71Sopenharmony_ci**\[Description]** 2609e41f4b71Sopenharmony_ci 2610e41f4b71Sopenharmony_ciA shared directory refers to a directory that can be accessed by non-privileged users. The temporary files of a program must be exclusively used by the program. If you place the temporary files of the program in the shared directory, other sharing users may obtain additional information about the program, resulting in information leakage. Therefore, do not create temporary files that are used only by a program itself in any shared directory. 2611e41f4b71Sopenharmony_ci 2612e41f4b71Sopenharmony_ciTemporary files are commonly used for auxiliary storage of data that cannot reside in memory or temporary data and also as a means of inter-process communication (by transmitting data through the file system). For example, one process creates a temporary file with a well-known name or a temporary name in a shared directory. The file can then be used to share information among processes. This practice is dangerous because files in a shared directory can be easily hijacked or manipulated by an attacker. Mitigation strategies include the following: 2613e41f4b71Sopenharmony_ci 2614e41f4b71Sopenharmony_ci1. Use other low-level inter-process communication (IPC) mechanisms, such as sockets or shared memory. 2615e41f4b71Sopenharmony_ci2. Use higher-level IPC mechanisms, such as remote procedure call (RPC). 2616e41f4b71Sopenharmony_ci3. Use secure directories that can be accessed only by a program itself (Avoid race conditions in the case of multiple threads or processes.) 2617e41f4b71Sopenharmony_ci 2618e41f4b71Sopenharmony_ciThe following lists several methods for creating temporary files. Product teams can use one or more of these methods as required or customize their own methods. 2619e41f4b71Sopenharmony_ci 2620e41f4b71Sopenharmony_ci1. Files must have appropriate permissions so that they can be accessed only by authorized users. 2621e41f4b71Sopenharmony_ci2. The name of a created file is unique or unpredictable. 2622e41f4b71Sopenharmony_ci3. Files can be created and opened only if the files do not exist (atomic create and open). 2623e41f4b71Sopenharmony_ci4. Open the files with exclusive access to avoid race conditions. 2624e41f4b71Sopenharmony_ci5. Remove files before the program exits. 2625e41f4b71Sopenharmony_ci 2626e41f4b71Sopenharmony_ciIn addition, when two or more users or a group of users have read/write permission to a directory, the potential security risk of the shared directory is far greater than that of the access to temporary files in the directory. 2627e41f4b71Sopenharmony_ci 2628e41f4b71Sopenharmony_ciCreating temporary files in a shared directory is vulnerable. For example, code that works for a locally mounted file system may be vulnerable when shared with a remotely mounted file system. The secure solution is not to create temporary files in shared directories. 2629e41f4b71Sopenharmony_ci 2630e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2631e41f4b71Sopenharmony_ci 2632e41f4b71Sopenharmony_ciThe program creates a temporary file with a hard-coded file name in the shared directory **/tmp** to store temporary data. Because the file name is hard-coded and consequently predictable, an attacker only needs to replace the file with a symbolic link. The target file referenced by the link is then opened and new content can be written. 2633e41f4b71Sopenharmony_ci 2634e41f4b71Sopenharmony_ci```c 2635e41f4b71Sopenharmony_civoid ProcData(const char *filename) 2636e41f4b71Sopenharmony_ci{ 2637e41f4b71Sopenharmony_ci FILE *fp = fopen(filename, "wb+"); 2638e41f4b71Sopenharmony_ci if (fp == NULL) { 2639e41f4b71Sopenharmony_ci ... // Error handling 2640e41f4b71Sopenharmony_ci } 2641e41f4b71Sopenharmony_ci 2642e41f4b71Sopenharmony_ci ... // Write a file. 2643e41f4b71Sopenharmony_ci 2644e41f4b71Sopenharmony_ci fclose(fp); 2645e41f4b71Sopenharmony_ci} 2646e41f4b71Sopenharmony_ci 2647e41f4b71Sopenharmony_ciint main(void) 2648e41f4b71Sopenharmony_ci{ 2649e41f4b71Sopenharmony_ci // Noncompliant: 1. A temporary file is created in shared directories. 2. The temporary file name is hard-coded. 2650e41f4b71Sopenharmony_ci char *pFile = "/tmp/data"; 2651e41f4b71Sopenharmony_ci ... 2652e41f4b71Sopenharmony_ci 2653e41f4b71Sopenharmony_ci ProcData(pFile); 2654e41f4b71Sopenharmony_ci 2655e41f4b71Sopenharmony_ci ... 2656e41f4b71Sopenharmony_ci return 0; 2657e41f4b71Sopenharmony_ci} 2658e41f4b71Sopenharmony_ci``` 2659e41f4b71Sopenharmony_ci 2660e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2661e41f4b71Sopenharmony_ci 2662e41f4b71Sopenharmony_ci```c 2663e41f4b71Sopenharmony_ciDo not create temporary files that are used only by a program itself in this directory. 2664e41f4b71Sopenharmony_ci``` 2665e41f4b71Sopenharmony_ci 2666e41f4b71Sopenharmony_ci**\[Impact]** 2667e41f4b71Sopenharmony_ci 2668e41f4b71Sopenharmony_ciCreating temporary files in an insecure manner may cause unauthorized access to the files and privilege escalation in the local system. 2669e41f4b71Sopenharmony_ci 2670e41f4b71Sopenharmony_ci## Do not access shared objects in signal handlers 2671e41f4b71Sopenharmony_ci 2672e41f4b71Sopenharmony_ci**\[Description]** 2673e41f4b71Sopenharmony_ci 2674e41f4b71Sopenharmony_ciAccessing or modifying shared objects in signal handlers can result in race conditions that can leave data in an uncertain state. This rule is not applicable to the following scenarios (see paragraph 5 in section 5.1.2.3 of the C11 standard): 2675e41f4b71Sopenharmony_ci 2676e41f4b71Sopenharmony_ci- Read/write operations on lock-free atomic object 2677e41f4b71Sopenharmony_ci- Read/write operations on objects of the **volatile sig\_atomic\_t** type. An object of the **volatile sig\_atomic\_t** type can be accessed as an atomic entity even in the presence of asynchronous interrupts, and is asynchronous-safe. 2678e41f4b71Sopenharmony_ci 2679e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2680e41f4b71Sopenharmony_ci 2681e41f4b71Sopenharmony_ciIn the signal handler, the program attempts to use `g_msg` as the shared object and update the shared object when the SIGINT signal is delivered. However, `g_msg` is not a variable of type `volatile sig_atomic_t`, and is not asynchronous-safe. 2682e41f4b71Sopenharmony_ci 2683e41f4b71Sopenharmony_ci```c 2684e41f4b71Sopenharmony_ci#define MAX_MSG_SIZE 32 2685e41f4b71Sopenharmony_cistatic char g_msgBuf[MAX_MSG_SIZE] = {0}; 2686e41f4b71Sopenharmony_cistatic char *g_msg = g_msgBuf; 2687e41f4b71Sopenharmony_ci 2688e41f4b71Sopenharmony_civoid SignalHandler(int signum) 2689e41f4b71Sopenharmony_ci{ 2690e41f4b71Sopenharmony_ci // It is noncompliant to use g_msg because it is not asynchronous-safe. 2691e41f4b71Sopenharmony_ci (void)memset(g_msg,0, MAX_MSG_SIZE); 2692e41f4b71Sopenharmony_ci errno_t ret = strcpy(g_msg, "signal SIGINT received."); 2693e41f4b71Sopenharmony_ci ... // Process ret 2694e41f4b71Sopenharmony_ci} 2695e41f4b71Sopenharmony_ci 2696e41f4b71Sopenharmony_ciint main(void) 2697e41f4b71Sopenharmony_ci{ 2698e41f4b71Sopenharmony_ci errno_t ret = strcpy(g_msg, "No msg yet."); // Initialize message content. 2699e41f4b71Sopenharmony_ci ... // Process ret 2700e41f4b71Sopenharmony_ci 2701e41f4b71Sopenharmony_ci signal(SIGINT, SignalHandler); // Set the SIGINT signal handler. 2702e41f4b71Sopenharmony_ci 2703e41f4b71Sopenharmony_ci ... // Main code loop 2704e41f4b71Sopenharmony_ci 2705e41f4b71Sopenharmony_ci return 0; 2706e41f4b71Sopenharmony_ci} 2707e41f4b71Sopenharmony_ci``` 2708e41f4b71Sopenharmony_ci 2709e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2710e41f4b71Sopenharmony_ci 2711e41f4b71Sopenharmony_ciIn the following code example, only the `volatile sig_atomic_t` type is used as a shared object in signal handlers. 2712e41f4b71Sopenharmony_ci 2713e41f4b71Sopenharmony_ci```c 2714e41f4b71Sopenharmony_ci#define MAX_MSG_SIZE 32 2715e41f4b71Sopenharmony_civolatile sig_atomic_t g_sigFlag = 0; 2716e41f4b71Sopenharmony_ci 2717e41f4b71Sopenharmony_civoid SignalHandler(int signum) 2718e41f4b71Sopenharmony_ci{ 2719e41f4b71Sopenharmony_ci g_sigFlag = 1; // Compliant 2720e41f4b71Sopenharmony_ci} 2721e41f4b71Sopenharmony_ci 2722e41f4b71Sopenharmony_ciint main(void) 2723e41f4b71Sopenharmony_ci{ 2724e41f4b71Sopenharmony_ci signal(SIGINT, SignalHandler); 2725e41f4b71Sopenharmony_ci char msgBuf[MAX_MSG_SIZE]; 2726e41f4b71Sopenharmony_ci errno_t ret = strcpy(msgBuf, "No msg yet."); // Initialize message content. 2727e41f4b71Sopenharmony_ci ... // Process ret 2728e41f4b71Sopenharmony_ci 2729e41f4b71Sopenharmony_ci ... // Main code loop 2730e41f4b71Sopenharmony_ci 2731e41f4b71Sopenharmony_ci if (g_sigFlag == 1) { // Update message content based on g_sigFlag status after exiting the main loop. 2732e41f4b71Sopenharmony_ci ret = strcpy(msgBuf, "signal SIGINT received."); 2733e41f4b71Sopenharmony_ci ... // Process ret 2734e41f4b71Sopenharmony_ci } 2735e41f4b71Sopenharmony_ci 2736e41f4b71Sopenharmony_ci return 0; 2737e41f4b71Sopenharmony_ci} 2738e41f4b71Sopenharmony_ci``` 2739e41f4b71Sopenharmony_ci 2740e41f4b71Sopenharmony_ci**\[Impact]** 2741e41f4b71Sopenharmony_ci 2742e41f4b71Sopenharmony_ciAccessing or modifying shared objects in signal handlers may cause inconsistent status access data. 2743e41f4b71Sopenharmony_ci 2744e41f4b71Sopenharmony_ci## Do not use rand() to generate pseudorandom numbers for security purposes 2745e41f4b71Sopenharmony_ci 2746e41f4b71Sopenharmony_ci**\[Description]** 2747e41f4b71Sopenharmony_ci 2748e41f4b71Sopenharmony_ciThe **rand()** function in the C language standard library generates pseudorandom numbers, which does not ensure the quality of the random sequence produced. In the C11 standard, the range of random numbers generated by the **rand()** function is `[0, RAND_MAX(0x7FFF)]`, which has a relatively short cycle, and the numbers can be predictable. Therefore, do not use the random numbers generated by the **rand()** function for security purposes. Use secure random number generation methods. 2749e41f4b71Sopenharmony_ci 2750e41f4b71Sopenharmony_ciTypical scenarios for security purposes include but are not limited to the following: 2751e41f4b71Sopenharmony_ci 2752e41f4b71Sopenharmony_ci- Generation of session IDs; 2753e41f4b71Sopenharmony_ci- Generation of random numbers in the challenge algorithm; 2754e41f4b71Sopenharmony_ci- Generation of random numbers of verification codes; 2755e41f4b71Sopenharmony_ci- Generation of random numbers for cryptographic algorithm purposes (for example, generating IVs, salt values, and keys). 2756e41f4b71Sopenharmony_ci 2757e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2758e41f4b71Sopenharmony_ci 2759e41f4b71Sopenharmony_ciThe programmer wants the code to generate a unique HTTP session ID that is not predictable. However, the ID is a random number produced by calling the **rand()** function, and is predictable and has limited randomness. 2760e41f4b71Sopenharmony_ci 2761e41f4b71Sopenharmony_ci**\[Impact]** 2762e41f4b71Sopenharmony_ci 2763e41f4b71Sopenharmony_ciUsing the **rand()** function may result in random numbers that are predictable. 2764e41f4b71Sopenharmony_ci 2765e41f4b71Sopenharmony_ci## Do not output the address of an object or function in a released version 2766e41f4b71Sopenharmony_ci 2767e41f4b71Sopenharmony_ci**\[Description]** 2768e41f4b71Sopenharmony_ci 2769e41f4b71Sopenharmony_ciDo not output the address of an object or function in a released version. For example, do not output the address of a variable or function to a client, log, or serial port. 2770e41f4b71Sopenharmony_ci 2771e41f4b71Sopenharmony_ciBefore launching an advanced attack, the attacker usually needs to obtain the memory address (such as the variable address and function address) of the target program and then modify the content of the specified memory for attacks. If the program itself outputs the addresses of objects or functions, the attacker can take this advantage and use these addresses and offsets to calculate the addresses of other objects or functions and launch attacks. In addition, the protection function of address space randomization also fails due to memory address leakage. 2772e41f4b71Sopenharmony_ci 2773e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2774e41f4b71Sopenharmony_ci 2775e41f4b71Sopenharmony_ciIn the following code example, the address to which the pointer points is logged in the %p format. 2776e41f4b71Sopenharmony_ci 2777e41f4b71Sopenharmony_ci```c 2778e41f4b71Sopenharmony_ciint Encode(unsigned char *in, size_t inSize, unsigned char *out, size_t maxSize) 2779e41f4b71Sopenharmony_ci{ 2780e41f4b71Sopenharmony_ci ... 2781e41f4b71Sopenharmony_ci Log("in=%p, in size=%zu, out=%p, max size=%zu\n", in, inSize, out, maxSize); 2782e41f4b71Sopenharmony_ci ... 2783e41f4b71Sopenharmony_ci} 2784e41f4b71Sopenharmony_ci``` 2785e41f4b71Sopenharmony_ci 2786e41f4b71Sopenharmony_ciNote: This example uses only the %p format for logging pointers. In scenarios where pointers are converted to integers and then logged, the same risk exists. 2787e41f4b71Sopenharmony_ci 2788e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2789e41f4b71Sopenharmony_ci 2790e41f4b71Sopenharmony_ciIn the following code example, the code for logging the address is deleted. 2791e41f4b71Sopenharmony_ci 2792e41f4b71Sopenharmony_ci```c 2793e41f4b71Sopenharmony_ciint Encode(unsigned char *in, size_t inSize, unsigned char *out, size_t maxSize) 2794e41f4b71Sopenharmony_ci{ 2795e41f4b71Sopenharmony_ci ... 2796e41f4b71Sopenharmony_ci Log("in size=%zu, max size=%zu\n", inSize, maxSize); 2797e41f4b71Sopenharmony_ci ... 2798e41f4b71Sopenharmony_ci} 2799e41f4b71Sopenharmony_ci``` 2800e41f4b71Sopenharmony_ci 2801e41f4b71Sopenharmony_ci**\[Exception]** 2802e41f4b71Sopenharmony_ci 2803e41f4b71Sopenharmony_ciWhen the program crashes and exits, the memory address and other information can be output in the crash exception information. 2804e41f4b71Sopenharmony_ci 2805e41f4b71Sopenharmony_ci**\[Impact]** 2806e41f4b71Sopenharmony_ci 2807e41f4b71Sopenharmony_ciMemory address leakage creates vulnerabilities to adversaries, probably leading to an address space randomization protection failure. 2808e41f4b71Sopenharmony_ci 2809e41f4b71Sopenharmony_ci## Do not include public IP addresses in code 2810e41f4b71Sopenharmony_ci 2811e41f4b71Sopenharmony_ci**\[Description]** 2812e41f4b71Sopenharmony_ci 2813e41f4b71Sopenharmony_ciIf the public IP addresses that are invisible and unknown to users are included in code or scripts, customers may doubt code security. 2814e41f4b71Sopenharmony_ci 2815e41f4b71Sopenharmony_ciPublic network addresses (including public IP addresses, public URLs/domain names, and email addresses) contained in the released software (including software packages and patch packages) must meet the following requirements: 1\. Do not contain any public network address that is invisible on UIs or not disclosed in product documentation. 2\. Do not write disclosed public IP addresses in code or scripts. They can be stored in configuration files or databases. 2816e41f4b71Sopenharmony_ci 2817e41f4b71Sopenharmony_ciThe public IP addresses built in open-source or third-party software must meet the first requirement at least. 2818e41f4b71Sopenharmony_ci 2819e41f4b71Sopenharmony_ci**\[Exception]** 2820e41f4b71Sopenharmony_ci 2821e41f4b71Sopenharmony_ciThis requirement is not mandatory when public network addresses must be specified as required by standard protocols. For example, an assembled public network URL must be specified for the namespace of functions based on the SOAP protocol. W3.org addresses on HTTP pages are also exceptions. 2822e41f4b71Sopenharmony_ci 2823e41f4b71Sopenharmony_ci# Secure Kernel Coding 2824e41f4b71Sopenharmony_ci 2825e41f4b71Sopenharmony_ci## Ensure that the mapping start address and space size in kernel mmap are validated 2826e41f4b71Sopenharmony_ci 2827e41f4b71Sopenharmony_ci**\[Description]** 2828e41f4b71Sopenharmony_ci 2829e41f4b71Sopenharmony_ciIn the mmap interface of the kernel, the **remap\_pfn\_range()** function is often used to map the physical memory of a device to a user process space. If the parameters (such as the mapping start address) are controlled by the user mode and no validation is performed, the user mode can read and write any kernel address through the mapping. An attacker can even construct arguments to run arbitrary code in the kernel. 2830e41f4b71Sopenharmony_ci 2831e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2832e41f4b71Sopenharmony_ci 2833e41f4b71Sopenharmony_ciWhen **remap\_pfn\_range()** is used for memory mapping in the following code, the user-controllable mapping start address and space size are not validated. As a result, the kernel may crash or any code may be executed. 2834e41f4b71Sopenharmony_ci 2835e41f4b71Sopenharmony_ci```c 2836e41f4b71Sopenharmony_cistatic int incorrect_mmap(struct file *file, struct vm_area_struct *vma) 2837e41f4b71Sopenharmony_ci{ 2838e41f4b71Sopenharmony_ci unsigned long size; 2839e41f4b71Sopenharmony_ci size = vma->vm_end - vma->vm_start; 2840e41f4b71Sopenharmony_ci vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); 2841e41f4b71Sopenharmony_ci // Error: The mapping start address and space size are not validated. 2842e41f4b71Sopenharmony_ci if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, size, vma->vm_page_prot)) { 2843e41f4b71Sopenharmony_ci err_log("%s, remap_pfn_range fail", __func__); 2844e41f4b71Sopenharmony_ci return EFAULT; 2845e41f4b71Sopenharmony_ci } else { 2846e41f4b71Sopenharmony_ci vma->vm_flags &= ~VM_IO; 2847e41f4b71Sopenharmony_ci } 2848e41f4b71Sopenharmony_ci 2849e41f4b71Sopenharmony_ci return EOK; 2850e41f4b71Sopenharmony_ci} 2851e41f4b71Sopenharmony_ci``` 2852e41f4b71Sopenharmony_ci 2853e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2854e41f4b71Sopenharmony_ci 2855e41f4b71Sopenharmony_ciAdd the validity check on parameters such as the mapping start address. 2856e41f4b71Sopenharmony_ci 2857e41f4b71Sopenharmony_ci```c 2858e41f4b71Sopenharmony_cistatic int correct_mmap(struct file *file, struct vm_area_struct *vma) 2859e41f4b71Sopenharmony_ci{ 2860e41f4b71Sopenharmony_ci unsigned long size; 2861e41f4b71Sopenharmony_ci size = vma->vm_end - vma->vm_start; 2862e41f4b71Sopenharmony_ci // Modification: Add a function to check whether the mapping start address and space size are valid. 2863e41f4b71Sopenharmony_ci if (!valid_mmap_phys_addr_range(vma->vm_pgoff, size)) { 2864e41f4b71Sopenharmony_ci return EINVAL; 2865e41f4b71Sopenharmony_ci } 2866e41f4b71Sopenharmony_ci 2867e41f4b71Sopenharmony_ci vma->vm_page_prot = pgprot_noncached(vma->vm_page_prot); 2868e41f4b71Sopenharmony_ci if (remap_pfn_range(vma, vma->vm_start, vma->vm_pgoff, size, vma->vm_page_prot)) { 2869e41f4b71Sopenharmony_ci err_log( "%s, remap_pfn_range fail ", __func__); 2870e41f4b71Sopenharmony_ci return EFAULT; 2871e41f4b71Sopenharmony_ci } else { 2872e41f4b71Sopenharmony_ci vma->vm_flags &= ~VM_IO; 2873e41f4b71Sopenharmony_ci } 2874e41f4b71Sopenharmony_ci 2875e41f4b71Sopenharmony_ci return EOK; 2876e41f4b71Sopenharmony_ci} 2877e41f4b71Sopenharmony_ci``` 2878e41f4b71Sopenharmony_ci 2879e41f4b71Sopenharmony_ci## Kernel programs must use kernel-specific functions to read and write user-mode buffers 2880e41f4b71Sopenharmony_ci 2881e41f4b71Sopenharmony_ci**\[Description]** 2882e41f4b71Sopenharmony_ci 2883e41f4b71Sopenharmony_ciDuring data exchange between the user mode and kernel mode, if no check (such as address range check and null pointer check) is performed in the kernel and the user mode input pointer is directly referenced, the kernel may crash and any address may be read or written when an invalid pointer is input in the user mode. Therefore, do not use unsafe functions such as **memcpy()** and **sprintf()**. Instead, use the dedicated functions provided by the kernel, such as **copy\_from\_user()**, **copy\_to\_user()**, **put\_user()**, and **get\_user()**, to read and write the user-mode buffer. Input validation is added to these functions. 2884e41f4b71Sopenharmony_ci 2885e41f4b71Sopenharmony_ciThe forbidden functions are **memcpy()**, **bcopy()**, **memmove()**, **strcpy()**, **strncpy()**, **strcat()**, **strncat()**, **sprintf()**, **vsprintf()**, **snprintf()**, **vsnprintf()**, **sscanf()** and **vsscanf()**. 2886e41f4b71Sopenharmony_ci 2887e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2888e41f4b71Sopenharmony_ci 2889e41f4b71Sopenharmony_ciThe kernel mode directly uses the buf pointer input by the user mode as the argument of **snprintf()**. When **buf** is **NULL**, the kernel may crash. 2890e41f4b71Sopenharmony_ci 2891e41f4b71Sopenharmony_ci```c 2892e41f4b71Sopenharmony_cissize_t incorrect_show(struct file *file, char__user *buf, size_t size, loff_t *data) 2893e41f4b71Sopenharmony_ci{ 2894e41f4b71Sopenharmony_ci // Error: The user-mode pointer is directly referenced. If the value of buf is NULL, a null pointer causes kernel crashes. 2895e41f4b71Sopenharmony_ci return snprintf(buf, size, "%ld\n", debug_level); 2896e41f4b71Sopenharmony_ci} 2897e41f4b71Sopenharmony_ci``` 2898e41f4b71Sopenharmony_ci 2899e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2900e41f4b71Sopenharmony_ci 2901e41f4b71Sopenharmony_ciUse the **copy\_to\_user()** function instead of **snprintf()**. 2902e41f4b71Sopenharmony_ci 2903e41f4b71Sopenharmony_ci```c 2904e41f4b71Sopenharmony_cissize_t correct_show(struct file *file, char __user *buf, size_t size, loff_t *data) 2905e41f4b71Sopenharmony_ci{ 2906e41f4b71Sopenharmony_ci int ret = 0; 2907e41f4b71Sopenharmony_ci char level_str[MAX_STR_LEN] = {0}; 2908e41f4b71Sopenharmony_ci snprintf(level_str, MAX_STR_LEN, "%ld \n", debug_level); 2909e41f4b71Sopenharmony_ci if(strlen(level_str) >= size) { 2910e41f4b71Sopenharmony_ci return EFAULT; 2911e41f4b71Sopenharmony_ci } 2912e41f4b71Sopenharmony_ci 2913e41f4b71Sopenharmony_ci // Modification: Use the dedicated function copy_to_user() to write data to the user-mode buf and prevent buffer overflow. 2914e41f4b71Sopenharmony_ci ret = copy_to_user(buf, level_str, strlen(level_str)+1); 2915e41f4b71Sopenharmony_ci return ret; 2916e41f4b71Sopenharmony_ci} 2917e41f4b71Sopenharmony_ci``` 2918e41f4b71Sopenharmony_ci 2919e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2920e41f4b71Sopenharmony_ci 2921e41f4b71Sopenharmony_ciThe pointer **user\_buf** transferred in user mode is used as the data source to perform the **memcpy()** operation in kernel mode. When **user\_buf** is **NULL**, the kernel may crash. 2922e41f4b71Sopenharmony_ci 2923e41f4b71Sopenharmony_ci```c 2924e41f4b71Sopenharmony_cisize_t incorrect_write(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) 2925e41f4b71Sopenharmony_ci{ 2926e41f4b71Sopenharmony_ci ... 2927e41f4b71Sopenharmony_ci char buf [128] = {0}; 2928e41f4b71Sopenharmony_ci int buf_size = 0; 2929e41f4b71Sopenharmony_ci buf_size = min(count, (sizeof(buf)-1)); 2930e41f4b71Sopenharmony_ci // Error: The user-mode pointer is directly referenced. If user_buf is NULL, the kernel may crash. 2931e41f4b71Sopenharmony_ci (void)memcpy(buf, user_buf, buf_size); 2932e41f4b71Sopenharmony_ci ... 2933e41f4b71Sopenharmony_ci} 2934e41f4b71Sopenharmony_ci``` 2935e41f4b71Sopenharmony_ci 2936e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2937e41f4b71Sopenharmony_ci 2938e41f4b71Sopenharmony_ciReplace **memcpy()** with **copy\_from\_user()**. 2939e41f4b71Sopenharmony_ci 2940e41f4b71Sopenharmony_ci```c 2941e41f4b71Sopenharmony_cissize_t correct_write(struct file *file, const char __user *user_buf, size_t count, loff_t *ppos) 2942e41f4b71Sopenharmony_ci{ 2943e41f4b71Sopenharmony_ci ... 2944e41f4b71Sopenharmony_ci char buf[128] = {0}; 2945e41f4b71Sopenharmony_ci int buf_size = 0; 2946e41f4b71Sopenharmony_ci 2947e41f4b71Sopenharmony_ci buf_size = min(count, (sizeof(buf)-1)); 2948e41f4b71Sopenharmony_ci // Modification: Use the dedicated function copy_from_user() to write data to the kernel-mode buf and prevent buffer overflows. 2949e41f4b71Sopenharmony_ci if (copy_from_user(buf, user_buf, buf_size)) { 2950e41f4b71Sopenharmony_ci return EFAULT; 2951e41f4b71Sopenharmony_ci } 2952e41f4b71Sopenharmony_ci 2953e41f4b71Sopenharmony_ci ... 2954e41f4b71Sopenharmony_ci} 2955e41f4b71Sopenharmony_ci``` 2956e41f4b71Sopenharmony_ci 2957e41f4b71Sopenharmony_ci## Verify the copy length of **copy\_from\_user()** to prevent buffer overflows 2958e41f4b71Sopenharmony_ci 2959e41f4b71Sopenharmony_ci**\[Description]** 2960e41f4b71Sopenharmony_ci 2961e41f4b71Sopenharmony_ciThe **copy\_from\_user()** function is used in kernel mode to copy data from the user mode. If the length of the copied data is not validated or is improperly validated, the kernel buffer overflows, causing kernel panic or privilege escalation. 2962e41f4b71Sopenharmony_ci 2963e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 2964e41f4b71Sopenharmony_ci 2965e41f4b71Sopenharmony_ciThe copy length is not validated. 2966e41f4b71Sopenharmony_ci 2967e41f4b71Sopenharmony_ci```c 2968e41f4b71Sopenharmony_cistatic long gser_ioctl(struct file *fp, unsigned cmd, unsigned long arg) 2969e41f4b71Sopenharmony_ci{ 2970e41f4b71Sopenharmony_ci char smd_write_buf[GSERIAL_BUF_LEN]; 2971e41f4b71Sopenharmony_ci switch (cmd) 2972e41f4b71Sopenharmony_ci { 2973e41f4b71Sopenharmony_ci case GSERIAL_SMD_WRITE: 2974e41f4b71Sopenharmony_ci if (copy_from_user(&smd_write_arg, argp, sizeof(smd_write_arg))) {...} 2975e41f4b71Sopenharmony_ci // Error: The value of smd_write_arg.size is entered by the user and is not validated. 2976e41f4b71Sopenharmony_ci copy_from_user(smd_write_buf, smd_write_arg.buf, smd_write_arg.size); 2977e41f4b71Sopenharmony_ci ... 2978e41f4b71Sopenharmony_ci } 2979e41f4b71Sopenharmony_ci} 2980e41f4b71Sopenharmony_ci``` 2981e41f4b71Sopenharmony_ci 2982e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 2983e41f4b71Sopenharmony_ci 2984e41f4b71Sopenharmony_ciLength validation is added. 2985e41f4b71Sopenharmony_ci 2986e41f4b71Sopenharmony_ci```c 2987e41f4b71Sopenharmony_cistatic long gser_ioctl(struct file *fp, unsigned cmd, unsigned long arg) 2988e41f4b71Sopenharmony_ci{ 2989e41f4b71Sopenharmony_ci char smd_write_buf[GSERIAL_BUF_LEN]; 2990e41f4b71Sopenharmony_ci switch (cmd) 2991e41f4b71Sopenharmony_ci { 2992e41f4b71Sopenharmony_ci case GSERIAL_SMD_WRITE: 2993e41f4b71Sopenharmony_ci if (copy_from_user(&smd_write_arg, argp, sizeof(smd_write_arg))){...} 2994e41f4b71Sopenharmony_ci // Modification: Add validation. 2995e41f4b71Sopenharmony_ci if (smd_write_arg.size >= GSERIAL_BUF_LEN) {......} 2996e41f4b71Sopenharmony_ci copy_from_user(smd_write_buf, smd_write_arg.buf, smd_write_arg.size); 2997e41f4b71Sopenharmony_ci ... 2998e41f4b71Sopenharmony_ci } 2999e41f4b71Sopenharmony_ci} 3000e41f4b71Sopenharmony_ci``` 3001e41f4b71Sopenharmony_ci 3002e41f4b71Sopenharmony_ci## Initialize the data copied by **copy\_to\_user()** to prevent information leakage 3003e41f4b71Sopenharmony_ci 3004e41f4b71Sopenharmony_ci**\[Description]** 3005e41f4b71Sopenharmony_ci 3006e41f4b71Sopenharmony_ci**Note:** When **copy\_to\_user()** is used in kernel mode to copy data to the user mode, sensitive information (such as the pointer on the stack) may be leaked if the data is not completely initialized (for example, the structure member is not assigned a value, or the memory fragmentation is caused by byte alignment). Attackers can bypass security mechanisms such as Kaslr. 3007e41f4b71Sopenharmony_ci 3008e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 3009e41f4b71Sopenharmony_ci 3010e41f4b71Sopenharmony_ciThe data structure members are not completely initialized. 3011e41f4b71Sopenharmony_ci 3012e41f4b71Sopenharmony_ci```c 3013e41f4b71Sopenharmony_cistatic long rmnet_ctrl_ioctl(struct file *fp, unsigned cmd, unsigned long arg) 3014e41f4b71Sopenharmony_ci{ 3015e41f4b71Sopenharmony_ci struct ep_info info; 3016e41f4b71Sopenharmony_ci switch (cmd) { 3017e41f4b71Sopenharmony_ci case FRMNET_CTRL_EP_LOOKUP: 3018e41f4b71Sopenharmony_ci info.ph_ep_info.ep_type = DATA_EP_TYPE_HSUSB; 3019e41f4b71Sopenharmony_ci info.ipa_ep_pair.cons_pipe_num = port->ipa_cons_idx; 3020e41f4b71Sopenharmony_ci info.ipa_ep_pair.prod_pipe_num = port->ipa_prod_idx; 3021e41f4b71Sopenharmony_ci // Error: The info structure has four members, not all of which are assigned with values. 3022e41f4b71Sopenharmony_ci ret = copy_to_user((void __user *)arg, &info, sizeof(info)); 3023e41f4b71Sopenharmony_ci ... 3024e41f4b71Sopenharmony_ci } 3025e41f4b71Sopenharmony_ci} 3026e41f4b71Sopenharmony_ci``` 3027e41f4b71Sopenharmony_ci 3028e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 3029e41f4b71Sopenharmony_ci 3030e41f4b71Sopenharmony_ciInitialize all data. 3031e41f4b71Sopenharmony_ci 3032e41f4b71Sopenharmony_ci```c 3033e41f4b71Sopenharmony_cistatic long rmnet_ctrl_ioctl(struct file *fp, unsigned cmd, unsigned long arg) 3034e41f4b71Sopenharmony_ci{ 3035e41f4b71Sopenharmony_ci struct ep_info info; 3036e41f4b71Sopenharmony_ci // Modification: Use memset to initialize the buffer to ensure that no memory fragmentation exists due to byte alignment or no value assignment. 3037e41f4b71Sopenharmony_ci (void)memset(&info, '0', sizeof(ep_info)); 3038e41f4b71Sopenharmony_ci switch (cmd) { 3039e41f4b71Sopenharmony_ci case FRMNET_CTRL_EP_LOOKUP: 3040e41f4b71Sopenharmony_ci info.ph_ep_info.ep_type = DATA_EP_TYPE_HSUSB; 3041e41f4b71Sopenharmony_ci info.ipa_ep_pair.cons_pipe_num = port->ipa_cons_idx; 3042e41f4b71Sopenharmony_ci info.ipa_ep_pair.prod_pipe_num = port->ipa_prod_idx; 3043e41f4b71Sopenharmony_ci ret = copy_to_user((void __user *)arg, &info, sizeof(info)); 3044e41f4b71Sopenharmony_ci ... 3045e41f4b71Sopenharmony_ci } 3046e41f4b71Sopenharmony_ci} 3047e41f4b71Sopenharmony_ci``` 3048e41f4b71Sopenharmony_ci 3049e41f4b71Sopenharmony_ci## Do not use the BUG\_ON macro in exception handling to avoid kernel panic 3050e41f4b71Sopenharmony_ci 3051e41f4b71Sopenharmony_ci**\[Description]** 3052e41f4b71Sopenharmony_ci 3053e41f4b71Sopenharmony_ciThe BUG\_ON macro calls the **panic()** function of the kernel to print error information and suspend the system. In normal logic processing (for example, the **cmd** parameter of the **ioctl** interface cannot be identified), the system should not crash. Do not use the BUG\_ON macro in such exception handling scenarios. The WARN\_ON macro is recommended. 3054e41f4b71Sopenharmony_ci 3055e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 3056e41f4b71Sopenharmony_ci 3057e41f4b71Sopenharmony_ciThe BUG\_ON macro is used in the normal process. 3058e41f4b71Sopenharmony_ci 3059e41f4b71Sopenharmony_ci```c 3060e41f4b71Sopenharmony_ci/ * Determine whether the timer on the Q6 side is busy. 1: busy; 0: not busy */ 3061e41f4b71Sopenharmony_cistatic unsigned int is_modem_set_timer_busy(special_timer *smem_ptr) 3062e41f4b71Sopenharmony_ci{ 3063e41f4b71Sopenharmony_ci int i = 0; 3064e41f4b71Sopenharmony_ci if (smem_ptr == NULL) { 3065e41f4b71Sopenharmony_ci printk(KERN_EMERG"%s:smem_ptr NULL!\n", __FUNCTION__); 3066e41f4b71Sopenharmony_ci // Error: The system BUG_ON macro calls panic() after printing the call stack, which causes kernel DoS and should not be used in normal processes. 3067e41f4b71Sopenharmony_ci BUG_ON(1); 3068e41f4b71Sopenharmony_ci return 1; 3069e41f4b71Sopenharmony_ci } 3070e41f4b71Sopenharmony_ci 3071e41f4b71Sopenharmony_ci ... 3072e41f4b71Sopenharmony_ci} 3073e41f4b71Sopenharmony_ci``` 3074e41f4b71Sopenharmony_ci 3075e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 3076e41f4b71Sopenharmony_ci 3077e41f4b71Sopenharmony_ciRemove the BUG\_ON macro. 3078e41f4b71Sopenharmony_ci 3079e41f4b71Sopenharmony_ci```c 3080e41f4b71Sopenharmony_ci/ * Determine whether the timer on the Q6 side is busy. 1: busy; 0: not busy */ 3081e41f4b71Sopenharmony_cistatic unsigned int is_modem_set_timer_busy(special_timer *smem_ptr) 3082e41f4b71Sopenharmony_ci{ 3083e41f4b71Sopenharmony_ci int i = 0; 3084e41f4b71Sopenharmony_ci if (smem_ptr == NULL) { 3085e41f4b71Sopenharmony_ci printk(KERN_EMERG"%s:smem_ptr NULL!\n", __FUNCTION__); 3086e41f4b71Sopenharmony_ci // Modification: Remove the BUG_ON call or use WARN_ON. 3087e41f4b71Sopenharmony_ci return 1; 3088e41f4b71Sopenharmony_ci } 3089e41f4b71Sopenharmony_ci 3090e41f4b71Sopenharmony_ci ... 3091e41f4b71Sopenharmony_ci} 3092e41f4b71Sopenharmony_ci``` 3093e41f4b71Sopenharmony_ci 3094e41f4b71Sopenharmony_ci## Do not use functions that may cause the process hibernation in the interrupt handler or in the context code of the process that holds the spin lock 3095e41f4b71Sopenharmony_ci 3096e41f4b71Sopenharmony_ci**\[Description]** 3097e41f4b71Sopenharmony_ci 3098e41f4b71Sopenharmony_ciProcesses as the scheduling unit. In the interrupt context, only the interrupt with a higher priority can be interrupted. The system cannot schedule processes during interrupt processing. If the interrupt handler is in hibernation state, the kernel cannot be woken up, paralyzing the kernel. 3099e41f4b71Sopenharmony_ci 3100e41f4b71Sopenharmony_ciSpin locks disable preemption. If the spin lock enters the hibernation state after being locked, other processes will stop running because they cannot obtain the CPU (single-core CPU). In this case, the system does not respond and is suspended. 3101e41f4b71Sopenharmony_ci 3102e41f4b71Sopenharmony_ciTherefore, functions that may cause hibernation (such as **vmalloc()** and **msleep()**), block (such as **copy\_from\_user()**, **copy\_to\_user()**), or consume a large amount of time (such as **printk()**) should not be used in the interrupt processing program or the context code of the process that holds the spin lock. 3103e41f4b71Sopenharmony_ci 3104e41f4b71Sopenharmony_ci## Use the kernel stack properly to prevent kernel stack overflows 3105e41f4b71Sopenharmony_ci 3106e41f4b71Sopenharmony_ci**\[Description]** 3107e41f4b71Sopenharmony_ci 3108e41f4b71Sopenharmony_ciThe kernel stack size is fixed (8 KB for a 32-bit system and 16 KB for a 64-bit system). Improper use of the kernel stack may cause stack overflows and system suspension. Therefore, the following requirements must be met: 3109e41f4b71Sopenharmony_ci 3110e41f4b71Sopenharmony_ci- The memory space requested on the stack cannot exceed the size of the kernel stack. 3111e41f4b71Sopenharmony_ci- Pay attention to the number of function nestings. 3112e41f4b71Sopenharmony_ci- Do not define excessive variables. 3113e41f4b71Sopenharmony_ci 3114e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 3115e41f4b71Sopenharmony_ci 3116e41f4b71Sopenharmony_ciThe variables defined in the following code are too large, causing stack overflows. 3117e41f4b71Sopenharmony_ci 3118e41f4b71Sopenharmony_ci```c 3119e41f4b71Sopenharmony_ci... 3120e41f4b71Sopenharmony_cistruct result 3121e41f4b71Sopenharmony_ci{ 3122e41f4b71Sopenharmony_ci char name[4]; 3123e41f4b71Sopenharmony_ci unsigned int a; 3124e41f4b71Sopenharmony_ci unsigned int b; 3125e41f4b71Sopenharmony_ci unsigned int c; 3126e41f4b71Sopenharmony_ci unsigned int d; 3127e41f4b71Sopenharmony_ci}; // The size of the result structure is 20 bytes. 3128e41f4b71Sopenharmony_ci 3129e41f4b71Sopenharmony_ciint foo() 3130e41f4b71Sopenharmony_ci{ 3131e41f4b71Sopenharmony_ci struct result temp[512]; 3132e41f4b71Sopenharmony_ci // Error: The temp array contains 512 elements. The total size is 10 KB, which is far greater than the kernel stack size. 3133e41f4b71Sopenharmony_ci (void)memset(temp, 0, sizeof(result) * 512); 3134e41f4b71Sopenharmony_ci ... // use temp do something 3135e41f4b71Sopenharmony_ci return 0; 3136e41f4b71Sopenharmony_ci} 3137e41f4b71Sopenharmony_ci 3138e41f4b71Sopenharmony_ci... 3139e41f4b71Sopenharmony_ci``` 3140e41f4b71Sopenharmony_ci 3141e41f4b71Sopenharmony_ciThe **temp** array has 512 elements, and the total size is 10 KB, which is far greater than the kernel size (8 KB). The stack overflows obviously. 3142e41f4b71Sopenharmony_ci 3143e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 3144e41f4b71Sopenharmony_ci 3145e41f4b71Sopenharmony_ciUse **kmalloc()** instead. 3146e41f4b71Sopenharmony_ci 3147e41f4b71Sopenharmony_ci```c 3148e41f4b71Sopenharmony_ci... 3149e41f4b71Sopenharmony_cistruct result 3150e41f4b71Sopenharmony_ci{ 3151e41f4b71Sopenharmony_ci char name[4]; 3152e41f4b71Sopenharmony_ci unsigned int a; 3153e41f4b71Sopenharmony_ci unsigned int b; 3154e41f4b71Sopenharmony_ci unsigned int c; 3155e41f4b71Sopenharmony_ci unsigned int d; 3156e41f4b71Sopenharmony_ci}; // The size of the result structure is 20 bytes. 3157e41f4b71Sopenharmony_ci 3158e41f4b71Sopenharmony_ciint foo() 3159e41f4b71Sopenharmony_ci{ 3160e41f4b71Sopenharmony_ci struct result *temp = NULL; 3161e41f4b71Sopenharmony_ci temp = (result *)kmalloc(sizeof(result) * 512, GFP_KERNEL); // Modification: Use kmalloc() to apply for memory. 3162e41f4b71Sopenharmony_ci ... // check temp is not NULL 3163e41f4b71Sopenharmony_ci (void)memset(temp, 0, sizeof(result) * 512); 3164e41f4b71Sopenharmony_ci ... // use temp do something 3165e41f4b71Sopenharmony_ci ... // free temp 3166e41f4b71Sopenharmony_ci return 0; 3167e41f4b71Sopenharmony_ci} 3168e41f4b71Sopenharmony_ci... 3169e41f4b71Sopenharmony_ci``` 3170e41f4b71Sopenharmony_ci 3171e41f4b71Sopenharmony_ci## Restore address validation after the operation is complete 3172e41f4b71Sopenharmony_ci 3173e41f4b71Sopenharmony_ci**\[Description]** 3174e41f4b71Sopenharmony_ci 3175e41f4b71Sopenharmony_ciThe SMEP security mechanism prevents the kernel from executing the code in the user space (PXN is the SMEP of the ARM version). System calls (such as **open()** and **write()**) are originally provided for user space programs to access. By default, these functions validate the input address. If it is not a user space address, an error is reported. Therefore, disable address validation before using these system calls in a kernel program. **set\_fs()**/**get\_fs()** is used to address this problem. For details, see the following code: 3176e41f4b71Sopenharmony_ci 3177e41f4b71Sopenharmony_ci```c 3178e41f4b71Sopenharmony_ci... 3179e41f4b71Sopenharmony_cimmegment_t old_fs; 3180e41f4b71Sopenharmony_ciprintk("Hello, I'm the module that intends to write message to file.\n"); 3181e41f4b71Sopenharmony_ciif (file == NULL) { 3182e41f4b71Sopenharmony_ci file = filp_open(MY_FILE, O_RDWR | O_APPEND | O_CREAT, 0664); 3183e41f4b71Sopenharmony_ci} 3184e41f4b71Sopenharmony_ci 3185e41f4b71Sopenharmony_ciif (IS_ERR(file)) { 3186e41f4b71Sopenharmony_ci printk("Error occurred while opening file %s, exiting ...\n", MY_FILE); 3187e41f4b71Sopenharmony_ci return 0; 3188e41f4b71Sopenharmony_ci} 3189e41f4b71Sopenharmony_ci 3190e41f4b71Sopenharmony_cisprintf(buf, "%s", "The Message."); 3191e41f4b71Sopenharmony_ciold_fs = get_fs(); // get_fs() is used to obtain the upper limit of the user space address. 3192e41f4b71Sopenharmony_ci // #define get_fs() (current->addr_limit 3193e41f4b71Sopenharmony_ciset_fs(KERNEL_DS); // set_fs is used to increase the upper limit of the address space to KERNEL_DS so that the kernel code can call system functions. 3194e41f4b71Sopenharmony_cifile->f_op->write(file, (char *)buf, sizeof(buf), &file->f_pos); // The kernel code can call the write() function. 3195e41f4b71Sopenharmony_ciset_fs(old_fs); // Restore the address limit of the user space in time after use. 3196e41f4b71Sopenharmony_ci... 3197e41f4b71Sopenharmony_ci``` 3198e41f4b71Sopenharmony_ci 3199e41f4b71Sopenharmony_ciAccording to the preceding code, it is vital to restore address validation immediately after the operation is complete. Otherwise, the SMEP/PXN security mechanism will fail, making it easy to exploit many vulnerabilities. 3200e41f4b71Sopenharmony_ci 3201e41f4b71Sopenharmony_ci**\[Noncompliant Code Example]** 3202e41f4b71Sopenharmony_ci 3203e41f4b71Sopenharmony_ciThe program error processing branch does not use **set\_fs()** to restore address validation. 3204e41f4b71Sopenharmony_ci 3205e41f4b71Sopenharmony_ci```c 3206e41f4b71Sopenharmony_ci... 3207e41f4b71Sopenharmony_cioldfs = get_fs(); 3208e41f4b71Sopenharmony_ciset_fs(KERNEL_DS); 3209e41f4b71Sopenharmony_ci/* Create a done file in the timestamp directory. */ 3210e41f4b71Sopenharmony_cifd = sys_open(path, O_CREAT | O_WRONLY, FILE_LIMIT); 3211e41f4b71Sopenharmony_ciif (fd < 0) { 3212e41f4b71Sopenharmony_ci BB_PRINT_ERR("sys_mkdir[%s] error, fd is[%d]\n", path, fd); 3213e41f4b71Sopenharmony_ci return; // Error: Address validation is not restored in the error processing program branch. 3214e41f4b71Sopenharmony_ci} 3215e41f4b71Sopenharmony_ci 3216e41f4b71Sopenharmony_cisys_close(fd); 3217e41f4b71Sopenharmony_ciset_fs(oldfs); 3218e41f4b71Sopenharmony_ci... 3219e41f4b71Sopenharmony_ci``` 3220e41f4b71Sopenharmony_ci 3221e41f4b71Sopenharmony_ci**\[Compliant Code Example]** 3222e41f4b71Sopenharmony_ci 3223e41f4b71Sopenharmony_ciAddress validation is restored in the error processing program. 3224e41f4b71Sopenharmony_ci 3225e41f4b71Sopenharmony_ci```c 3226e41f4b71Sopenharmony_ci... 3227e41f4b71Sopenharmony_cioldfs = get_fs(); 3228e41f4b71Sopenharmony_ciset_fs(KERNEL_DS); 3229e41f4b71Sopenharmony_ci 3230e41f4b71Sopenharmony_ci/* Create a done file in the timestamp directory. */ 3231e41f4b71Sopenharmony_cifd = sys_open(path, O_CREAT | O_WRONLY, FILE_LIMIT); 3232e41f4b71Sopenharmony_ciif (fd < 0) { 3233e41f4b71Sopenharmony_ci BB_PRINT_ERR("sys_mkdir[%s] error, fd is[%d] \n", path, fd); 3234e41f4b71Sopenharmony_ci set_fs(oldfs); // Modification: Restore address validation in the error processing program branch. 3235e41f4b71Sopenharmony_ci return; 3236e41f4b71Sopenharmony_ci} 3237e41f4b71Sopenharmony_ci 3238e41f4b71Sopenharmony_cisys_close(fd); 3239e41f4b71Sopenharmony_ciset_fs(oldfs); 3240e41f4b71Sopenharmony_ci... 3241e41f4b71Sopenharmony_ci```