I am part of a OpenSSF group writing documentation on secure coding in Python and we are scratching our heads on if this is a compliant solution for CWE-369:
# SPDX-FileCopyrightText: OpenSSF project contributors
# SPDX-License-Identifier: MIT
""" Compliant Code Example """
from decimal import Decimal, ROUND_HALF_UP, Overflow
def divide(first_number: int, second_number: int):
'''Function to divide 2 numbers'''
if second_number == 0:
raise ZeroDivisionError("TODO: implement zero division error handling here")
# This operation may cause an overflow due to a large exponent
try:
result = Decimal(first_number / second_number)
except Overflow as e:
raise Overflow("TODO: implement overflow error handling here") from e
rounded_result = Decimal(result).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
# Rounding result to 2 decimal place
return rounded_result
#####################
# Trying to exploit above code example
#####################
for number in (10, 41, 200, -10, 0):
# Dividing 100 by each number 10, 41, 200, -10, and 0 separately.
print("-" * 20 + f"divide by {number}" + "-" * 20 + "\n")
print(f"100 / {number} = ", end="")
print(divide(100, number))
I have decided to go with this approach as Decimal ensures the accuracy of the math, and it also prevents float overflow from occurring.
Would this be a suitable compliant solution?
Overall OpenSSF project on secure coding I work on: