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