|
| 1 | +# CWE-476: NULL Pointer Dereference |
| 2 | + |
| 3 | +Avoiding NULL Pointer Dereference is crucial for preventing runtime errors, and ensuring that your code executes successfully. |
| 4 | + |
| 5 | +* Ensure that you have a valid object before callings its instance methods. |
| 6 | +* Verify that the object is not None before accessing or modifying its fields. |
| 7 | +* Confirm the object is an array or similar data structure before taking its length. |
| 8 | +* Check the object is an array before accessing or modifying its elements. |
| 9 | +* Raise only exceptions that properly inherit from the BaseException class, never raise "None". |
| 10 | + |
| 11 | +If the data originates from a lesser trusted source, verifying that objects are not None becomes a mandatory security measure to prevent potential vulnerabilities such as unauthorized access or unexpected behavior. However, when dealing with data from trusted and well-controlled sources, the primary concern shifts from a security one, to more of a stability issue as per [CWE-390](https://github.com/ossf/wg-best-practices-os-developers/blob/main/docs/Secure-Coding-Guide-for-Python/CWE-703/CWE-390/README.md). |
| 12 | + |
| 13 | +## Non-Compliant Code Example - Verify that the object is not None before accessing or modifying its fields |
| 14 | + |
| 15 | +`Noncompliant01.py` defines a function `is_valid_name()` that checks if a certain name is properly defined (contains exactly two words, both capitalized): |
| 16 | + |
| 17 | +*[noncompliant01.py](noncompliant01.py):* |
| 18 | + |
| 19 | +```py |
| 20 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 21 | +# SPDX-License-Identifier: MIT |
| 22 | +""" Non-compliant Code Example """ |
| 23 | + |
| 24 | + |
| 25 | +def is_valid_name(s: str) -> bool: |
| 26 | + """ Check if the input is a name with 2 capitalised Strings """ |
| 27 | + names = s.split() |
| 28 | + if len(names) != 2: |
| 29 | + return False |
| 30 | + return s.istitle() |
| 31 | + |
| 32 | + |
| 33 | +##################### |
| 34 | +# Attempting to exploit above code example |
| 35 | +##################### |
| 36 | +name = is_valid_name(None) |
| 37 | + |
| 38 | + |
| 39 | +print(name) |
| 40 | + |
| 41 | +``` |
| 42 | + |
| 43 | +The `is_valid_name()` function could get called with a null argument, which raises an `AttributeError` due to the `NoneType` object not having any `split` attribute. |
| 44 | + |
| 45 | +## Compliant Code Example - Verify that the object is not None before accessing or modifying its fields |
| 46 | + |
| 47 | +The `compliant01.py` code includes the same implementation as the previous `noncompliant01.py` but now checks if the string is `None`. |
| 48 | + |
| 49 | +The type hint `Optional [str]` can be added to the method signature to show that it could be called with `None` (where `Optional[X]` is equivalent to `X` | `None` or `Union[X, None]`). |
| 50 | + |
| 51 | +*[compliant01.py](compliant01.py):* |
| 52 | + |
| 53 | +```py |
| 54 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 55 | +# SPDX-License-Identifier: MIT |
| 56 | +""" Compliant Code Example """ |
| 57 | + |
| 58 | +from typing import Optional |
| 59 | + |
| 60 | + |
| 61 | +def is_valid_name(s: Optional[str]) -> bool: |
| 62 | + """ Check if the input is a name with 2 capitalised Strings """ |
| 63 | + if s is None: |
| 64 | + return False |
| 65 | + names = s.split() |
| 66 | + if len(names) != 2: |
| 67 | + return False |
| 68 | + return s.istitle() |
| 69 | + |
| 70 | + |
| 71 | +##################### |
| 72 | +# Attempting to exploit above code example |
| 73 | +##################### |
| 74 | +name = is_valid_name(None) |
| 75 | + |
| 76 | + |
| 77 | +print(name) |
| 78 | + |
| 79 | +``` |
| 80 | + |
| 81 | +## Non-Compliant Code Example - Confirm the object is an array or similar data structure before taking its length |
| 82 | + |
| 83 | +`Noncompliant02.py` demonstrates the process of checking the number of students in a given classroom. In certain scenarios, such as a small school without a certain grade, the number of students in a classroom may legitimately be represented as `None`. |
| 84 | + |
| 85 | +*[noncompliant02.py](noncompliant02.py):* |
| 86 | + |
| 87 | +```py |
| 88 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 89 | +# SPDX-License-Identifier: MIT |
| 90 | +"""Non-compliant Code Example""" |
| 91 | + |
| 92 | + |
| 93 | +def print_number_of_students(classroom: list[str]): |
| 94 | + """Print the number of students in a classroom""" |
| 95 | + print(f"The classroom has {len(classroom)} students.") |
| 96 | + |
| 97 | + |
| 98 | +##################### |
| 99 | +# Attempting to exploit above code example |
| 100 | +##################### |
| 101 | +print_number_of_students(None) |
| 102 | + |
| 103 | +``` |
| 104 | + |
| 105 | +The code example attempts to directly call `len()` on a non-array value, in this case on `None`, which will raise a `TypeError`. Such unchecked dereferencing of a `None` value could result in an application crash or denial of service, impacting system availability. |
| 106 | + |
| 107 | +## Compliant Code Example - Confirm the object is an array or similar data structure before taking its length |
| 108 | + |
| 109 | +The `compliant02.py` solution safely checks whether the classroom object is an array (or list) before calling the `len()` thereby preventing a potential `TypeError` and avoiding loss of availability. |
| 110 | + |
| 111 | +*[compliant02.py](compliant02.py):* |
| 112 | + |
| 113 | +```py |
| 114 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 115 | +# SPDX-License-Identifier: MIT |
| 116 | +"""Compliant Code Example""" |
| 117 | + |
| 118 | + |
| 119 | +def print_number_of_students(classroom: list[str]): |
| 120 | + """Print the number of students in a classroom""" |
| 121 | + if isinstance(classroom, list): |
| 122 | + print(f"The classroom has {len(classroom)} students.") |
| 123 | + else: |
| 124 | + print("Given object is not a classroom.") |
| 125 | + |
| 126 | + |
| 127 | +##################### |
| 128 | +# Attempting to exploit above code example |
| 129 | +##################### |
| 130 | +print_number_of_students(None) |
| 131 | + |
| 132 | +``` |
| 133 | + |
| 134 | +## Non-Compliant Code Example - Raise only exceptions that properly inherit from the BaseException class, never raise "None" |
| 135 | + |
| 136 | +`Noncompliant03.py` demonstrates an incorrect example of checking for whether the variable passed is a list. If the variable is not a list, then the code example attempts to raise `None`. |
| 137 | + |
| 138 | +*[noncompliant03.py](noncompliant03.py):* |
| 139 | + |
| 140 | +```py |
| 141 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 142 | +# SPDX-License-Identifier: MIT |
| 143 | +"""Non-compliant Code Example""" |
| 144 | + |
| 145 | + |
| 146 | +def print_number_of_students(classroom: list[str]): |
| 147 | + """Print the number of students in a classroom""" |
| 148 | + if not isinstance(classroom, list): |
| 149 | + raise None |
| 150 | + print(f"The classroom has {len(classroom)} students.") |
| 151 | + |
| 152 | + |
| 153 | +##################### |
| 154 | +# Attempting to exploit above code example |
| 155 | +##################### |
| 156 | +print_number_of_students(["student 1", "student 2", "student 3"]) |
| 157 | +print_number_of_students(None) |
| 158 | + |
| 159 | +``` |
| 160 | + |
| 161 | +This code example returns: `TypeError: exceptions must derive from BaseException`. This is problematic because rasing `None` does not provide any useful error information or traceback, leading to less informative error handling and potentially causing the program to crash unexpectedly without clear diagnostic details. |
| 162 | + |
| 163 | +## Compliant Code Example - Raise only exceptions that properly inherit from the BaseException class, never raise "None" |
| 164 | + |
| 165 | +The `compliant03.py` solution raises a `ValueError` rather than `None`, ensuring clear error reporting. |
| 166 | + |
| 167 | +*[compliant03.py](compliant03.py):* |
| 168 | + |
| 169 | +```py |
| 170 | +# SPDX-FileCopyrightText: OpenSSF project contributors |
| 171 | +# SPDX-License-Identifier: MIT |
| 172 | +"""Compliant Code Example""" |
| 173 | + |
| 174 | + |
| 175 | +def print_number_of_students(classroom: list[str]): |
| 176 | + """Print the number of students in a classroom""" |
| 177 | + if not isinstance(classroom, list): |
| 178 | + raise ValueError("classroom is not a list") |
| 179 | + # TODO: also check each entry |
| 180 | + print(f"The classroom has {len(classroom)} students.") |
| 181 | + |
| 182 | + |
| 183 | +##################### |
| 184 | +# Attempting to exploit above code example |
| 185 | +##################### |
| 186 | +print_number_of_students(["student 1", "student 2", "student 3"]) |
| 187 | +print_number_of_students(None) |
| 188 | + |
| 189 | +``` |
| 190 | + |
| 191 | +## Automated Detection |
| 192 | + |
| 193 | +|Tool|Version|Checker|Description| |
| 194 | +|:----|:----|:----|:----| |
| 195 | +|[mypy](https://mypy-lang.org/)|0.960 on python 3.10.4||Item "None" of "Optional[str]" has no attribute "split"| |
| 196 | +|[pylint](https://pylint.pycqa.org/)|3.3.4|[E0702-raising bad-type](https://pylint.readthedocs.io/en/latest/user_guide/messages/error/raising-bad-type.html)|Raising NoneType while only classes or instances are allowed| |
| 197 | +|[pyright](https://github.com/microsoft/pyright)|1.1.402||noncompliant01.py:17:22 - error: Argument of type "None" cannot be assigned to parameter "s" of type "str" in function "is_valid_name" None" is not assignable to "str" (reportArgumentType) noncompliant03.py:21:19 - error: Invalid exception class or object "None" does not derive from BaseException (reportGeneralTypeIssues) 2 errors, 0 warnings, 0 informations| |
| 198 | +|[pylance](https://marketplace.visualstudio.com/items?itemName=ms-python.vscode-pylance)|2025.6.2||Argument of type "None" cannot be assigned to parameter "s" of type "str" in function "is_valid_name"| |
| 199 | + |
| 200 | +## Related Guidelines |
| 201 | + |
| 202 | +||| |
| 203 | +|:---|:---| |
| 204 | +|[SEI CERT C Coding Standard](https://wiki.sei.cmu.edu/confluence/display/c/SEI+CERT+C+Coding+Standard)|[EXP34-C. Do not dereference null pointers](https://wiki.sei.cmu.edu/confluence/display/c/EXP34-C.+Do+not+dereference+null+pointers)| |
| 205 | +|[SEI CERT Oracle Coding Standard for Java](https://wiki.sei.cmu.edu/confluence/display/java/SEI+CERT+Oracle+Coding+Standard+for+Java)|[ERR00-J. Do not suppress or ignore checked exceptions](https://wiki.sei.cmu.edu/confluence/display/java/ERR00-J.+Do+not+suppress+or+ignore+checked+exceptions)| |
| 206 | +|[ISO/IEC TR 24772:2010](http://www.aitcnet.org/isai/)|Null Pointer Dereference [XYH]| |
| 207 | +|[MITRE CWE Pillar](http://cwe.mitre.org/)|[CWE-703, Improper Check or Handling of Exceptional Conditions](https://cwe.mitre.org/data/definitions/703.html)| |
| 208 | +|[MITRE CWE Base](http://cwe.mitre.org/)|[CWE-476, NULL Pointer Dereference](http://cwe.mitre.org/data/definitions/476.html)| |
| 209 | + |
| 210 | +## Bibliography |
| 211 | + |
| 212 | +||| |
| 213 | +|:---|:---| |
| 214 | +|[[Python 3.10.4 docs](https://docs.python.org/3/library/string.html#formatstrings)]|[The None Object](https://docs.python.org/3/c-api/none.html)| |
0 commit comments