code
stringlengths
14
2.05k
label
int64
0
1
programming_language
stringclasses
7 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
98
description
stringlengths
36
379
url
stringlengths
36
48
label_name
stringclasses
2 values
def test_file_hash(self): self.assertEqual( self.document.get_file_hash(), "7d8c4778b182e4f3bd442408c64a6e22a4b0ed85" ) self.assertEqual( self.pdf_document.get_file_hash(), "7d8c4778b182e4f3bd442408c64a6e22a4b0ed85", ) self.assertEqual( ...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def _set_file_hash(self): with self.open_file() as f: self.file_hash = hash_filelike(f)
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def _set_file_hash(self): with self.open_file() as f: self.file_hash = hash_filelike(f)
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def get_file_hash(self): if self.file_hash == "": self._set_file_hash() self.save(update_fields=["file_hash"]) return self.file_hash
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def get_file_hash(self): if self.file_hash == "": self._set_file_hash() self.save(update_fields=["file_hash"]) return self.file_hash
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def _set_image_file_metadata(self): self.file.open() # Set new image file size self.file_size = self.file.size # Set new image file hash self._set_file_hash() self.file.seek(0)
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def _set_image_file_metadata(self): self.file.open() # Set new image file size self.file_size = self.file.size # Set new image file hash self._set_file_hash() self.file.seek(0)
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_file_hash(self): self.assertEqual( self.image.get_file_hash(), "4dd0211870e130b7e1690d2ec53c499a54a48fef" )
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_file_hash(self): self.assertEqual( self.image.get_file_hash(), "4dd0211870e130b7e1690d2ec53c499a54a48fef" )
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_hashes_large_file(self): class FakeLargeFile: """ A class that pretends to be a huge file (~1.3GB) """ def __init__(self): self.iterations = 20000 def read(self, bytes): self.iterations -= 1 ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_hashes_large_file(self): class FakeLargeFile: """ A class that pretends to be a huge file (~1.3GB) """ def __init__(self): self.iterations = 20000 def read(self, bytes): self.iterations -= 1 ...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_hashes_io(self): self.assertEqual( hash_filelike(BytesIO(b"test")), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" ) self.assertEqual( hash_filelike(StringIO("test")), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" )
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_hashes_io(self): self.assertEqual( hash_filelike(BytesIO(b"test")), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" ) self.assertEqual( hash_filelike(StringIO("test")), "a94a8fe5ccb19ba61c4c0873d391e987982fbbd3" )
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def __init__(self): self.iterations = 20000
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def __init__(self): self.iterations = 20000
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_hashes_django_uploaded_file(self): """ Check Django's file shims can be hashed as-is. `SimpleUploadedFile` inherits the base `UploadedFile`, but is easiest to test against """ self.assertEqual( hash_filelike(SimpleUploadedFile("example.txt", b"test")), ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_hashes_django_uploaded_file(self): """ Check Django's file shims can be hashed as-is. `SimpleUploadedFile` inherits the base `UploadedFile`, but is easiest to test against """ self.assertEqual( hash_filelike(SimpleUploadedFile("example.txt", b"test")), ...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_hashes_file(self): with self.test_file.open(mode="r") as f: self.assertEqual( hash_filelike(f), "9e58400061ca660ef7b5c94338a5205627c77eda" )
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_hashes_file(self): with self.test_file.open(mode="r") as f: self.assertEqual( hash_filelike(f), "9e58400061ca660ef7b5c94338a5205627c77eda" )
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_hashes_file_bytes(self): with self.test_file.open(mode="rb") as f: self.assertEqual( hash_filelike(f), "9e58400061ca660ef7b5c94338a5205627c77eda" )
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_hashes_file_bytes(self): with self.test_file.open(mode="rb") as f: self.assertEqual( hash_filelike(f), "9e58400061ca660ef7b5c94338a5205627c77eda" )
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def read(self, bytes): self.iterations -= 1 if not self.iterations: return b"" return b"A" * bytes
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def read(self, bytes): self.iterations -= 1 if not self.iterations: return b"" return b"A" * bytes
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def hash_filelike(filelike): """ Compute the hash of a file-like object, without loading it all into memory. """ file_pos = 0 if hasattr(filelike, "tell"): file_pos = filelike.tell() try: # Reset file handler to the start of the file so we hash it all filelike.seek(0) ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def hash_filelike(filelike): """ Compute the hash of a file-like object, without loading it all into memory. """ file_pos = 0 if hasattr(filelike, "tell"): file_pos = filelike.tell() try: # Reset file handler to the start of the file so we hash it all filelike.seek(0) ...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Willow supports). Overridden from ImageField to use Willow instead of Pillow as the image library in order to enable SVG support. """ f = FileF...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def to_python(self, data): """ Check that the file-upload field data contains a valid image (GIF, JPG, PNG, etc. -- whatever Willow supports). Overridden from ImageField to use Willow instead of Pillow as the image library in order to enable SVG support. """ f = FileF...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_add_temporary_uploaded_file(self): """ Test that uploading large files (spooled to the filesystem) work as expected """ test_image_file = get_test_image_file() uploaded_file = TemporaryUploadedFile( "test.png", "image/png", test_image_file.size, "utf-8" ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def test_add_temporary_uploaded_file(self): """ Test that uploading large files (spooled to the filesystem) work as expected """ test_image_file = get_test_image_file() uploaded_file = TemporaryUploadedFile( "test.png", "image/png", test_image_file.size, "utf-8" ...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.
https://cwe.mitre.org/data/definitions/770.html
safe
def test_split_backslash(self): stmts = sqlparse.parse(r"select '\\'; select '\''; select '\\\'';") self.assertEqual(len(stmts), 3)
1
Python
CWE-1333
Inefficient Regular Expression Complexity
The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles.
https://cwe.mitre.org/data/definitions/1333.html
safe
def test_split_backslash(): stmts = sqlparse.parse("select '\'; select '\'';") assert len(stmts) == 2
1
Python
CWE-1333
Inefficient Regular Expression Complexity
The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles.
https://cwe.mitre.org/data/definitions/1333.html
safe
def safe_extract(tar, path=".", members=None, *, numeric_owner=False): for member in tar.getmembers(): member_path = os.path.join(path, member.name) if not __is_within_directory(path, member_path): raise Exception("Attempted Path Traversal in Tar File") tar.extractall(path, members, ...
1
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the...
https://cwe.mitre.org/data/definitions/22.html
safe
def __is_within_directory(directory, target): abs_directory = os.path.abspath(directory) abs_target = os.path.abspath(target) prefix = os.path.commonprefix([abs_directory, abs_target]) return prefix == abs_directory
1
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the product does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the...
https://cwe.mitre.org/data/definitions/22.html
safe
def connect(self) -> dict: """ Set up the connection required by the handler. Returns: HandlerStatusResponse """ headers = { 'Content-Type': 'application/json', } data = '{' + f'"userName": "{self.connection_data["username"]}","passwo...
1
Python
CWE-311
Missing Encryption of Sensitive Data
The product does not encrypt sensitive or critical information before storage or transmission.
https://cwe.mitre.org/data/definitions/311.html
safe
def on_file(file): nonlocal file_object data["file"] = clear_filename(file.file_name.decode()) file_object = file.file_object
1
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
def on_file(file): nonlocal file_object data["file"] = clear_filename(file.file_name.decode()) file_object = file.file_object
1
Python
NVD-CWE-noinfo
null
null
null
safe
def select(self, query: ast.Select) -> pd.DataFrame: conditions = extract_comparison_conditions(query.where) urls = [] for op, arg1, arg2 in conditions: if op == 'or': raise NotImplementedError(f'OR is not supported') if arg1 == 'url': ...
1
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
def select(self, query: ast.Select) -> pd.DataFrame: conditions = extract_comparison_conditions(query.where) urls = [] for op, arg1, arg2 in conditions: if op == 'or': raise NotImplementedError(f'OR is not supported') if arg1 == 'url': ...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def is_private_url(url: str): """ Raises exception if url is private :param url: url to check """ hostname = urlparse(url).hostname if not hostname: # Unable find hostname in url return True ip = socket.gethostbyname(hostname) return ipaddress.ip_address(ip).is_private
1
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
def is_private_url(url: str): """ Raises exception if url is private :param url: url to check """ hostname = urlparse(url).hostname if not hostname: # Unable find hostname in url return True ip = socket.gethostbyname(hostname) return ipaddress.ip_address(ip).is_private
1
Python
NVD-CWE-noinfo
null
null
null
safe
def clear_filename(filename: str): """ Removes path symbols from filename which could be used for path injection :param s: :return: """ if not filename: return filename badchars = '\\/:*?\"<>|' for c in badchars: filename = filename.replace(c, '') return filename
1
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
def clear_filename(filename: str): """ Removes path symbols from filename which could be used for path injection :param s: :return: """ if not filename: return filename badchars = '\\/:*?\"<>|' for c in badchars: filename = filename.replace(c, '') return filename
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_basic_init_function(get_contract): code = """ val: public(uint256) @external def __init__(a: uint256): self.val = a """ c = get_contract(code, *[123]) assert c.val() == 123 # Make sure the init code does not access calldata assembly = vyper.compile_code(code, ["asm"])["asm"].spl...
1
Python
CWE-670
Always-Incorrect Control Flow Implementation
The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.
https://cwe.mitre.org/data/definitions/670.html
safe
def test_checkable_raw_call(get_contract, assert_tx_failed): target_source = """ baz: int128 @external def fail1(should_raise: bool): if should_raise: raise "fail" # test both paths for raw_call - # they are different depending if callee has or doesn't have returntype # (fail2 fails because of staticca...
1
Python
CWE-670
Always-Incorrect Control Flow Implementation
The code contains a control flow path that does not reflect the algorithm that the path is intended to implement, leading to incorrect behavior any time this path is navigated.
https://cwe.mitre.org/data/definitions/670.html
safe
def test_overflow(): code = """ x: uint256[2] """ storage_layout_override = {"x": {"slot": 2**256 - 1, "type": "uint256[2]"}} with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var x, out of bounds: {2**256}\n" ): compile_code( code, output_for...
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def test_overflow(): code = """ x: uint256[2] """ storage_layout_override = {"x": {"slot": 2**256 - 1, "type": "uint256[2]"}} with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var x, out of bounds: {2**256}\n" ): compile_code( code, output_for...
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def test_overflow(): code = """ x: uint256[2] """ storage_layout_override = {"x": {"slot": 2**256 - 1, "type": "uint256[2]"}} with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var x, out of bounds: {2**256}\n" ): compile_code( code, output_for...
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def test_allocator_overflow(get_contract): code = """ x: uint256 y: uint256[max_value(uint256)] """ with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var y, tried to allocate slots 1 through {2**256}\n", ): get_contract(code)
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def test_allocator_overflow(get_contract): code = """ x: uint256 y: uint256[max_value(uint256)] """ with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var y, tried to allocate slots 1 through {2**256}\n", ): get_contract(code)
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def test_allocator_overflow(get_contract): code = """ x: uint256 y: uint256[max_value(uint256)] """ with pytest.raises( StorageLayoutException, match=f"Invalid storage slot for var y, tried to allocate slots 1 through {2**256}\n", ): get_contract(code)
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict: ret = {} offset = 0 for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}): varinfo = node.target._metadata["varinfo"] type_ = varinfo.typ varinfo.set_position(CodeOffset(offset)) ...
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict: ret = {} offset = 0 for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}): varinfo = node.target._metadata["varinfo"] type_ = varinfo.typ varinfo.set_position(CodeOffset(offset)) ...
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def set_code_offsets(vyper_module: vy_ast.Module) -> Dict: ret = {} offset = 0 for node in vyper_module.get_children(vy_ast.VariableDecl, filters={"is_immutable": True}): varinfo = node.target._metadata["varinfo"] type_ = varinfo.typ varinfo.set_position(CodeOffset(offset)) ...
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def allocate_slot(self, n, var_name): ret = self._slot if self._slot + n >= 2**256: raise StorageLayoutException( f"Invalid storage slot for var {var_name}, tried to allocate" f" slots {self._slot} through {self._slot + n}" ) self._slot...
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def allocate_slot(self, n, var_name): ret = self._slot if self._slot + n >= 2**256: raise StorageLayoutException( f"Invalid storage slot for var {var_name}, tried to allocate" f" slots {self._slot} through {self._slot + n}" ) self._slot...
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def allocate_slot(self, n, var_name): ret = self._slot if self._slot + n >= 2**256: raise StorageLayoutException( f"Invalid storage slot for var {var_name}, tried to allocate" f" slots {self._slot} through {self._slot + n}" ) self._slot...
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def __init__(self, starting_slot: int = 0): self._slot = starting_slot
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def __init__(self, starting_slot: int = 0): self._slot = starting_slot
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def __init__(self, starting_slot: int = 0): self._slot = starting_slot
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def __init__(self, value_type: VyperType, length: int): if not 0 < length < 2**256: raise InvalidType("Array length is invalid") if length >= 2**64: warnings.warn("Use of large arrays can be unsafe!") super().__init__(UINT256_T, value_type) self.length = len...
1
Python
CWE-789
Memory Allocation with Excessive Size Value
The product allocates memory based on an untrusted, large size value, but it does not ensure that the size is within expected limits, allowing arbitrary amounts of memory to be allocated.
https://cwe.mitre.org/data/definitions/789.html
safe
def __init__(self, value_type: VyperType, length: int): if not 0 < length < 2**256: raise InvalidType("Array length is invalid") if length >= 2**64: warnings.warn("Use of large arrays can be unsafe!") super().__init__(UINT256_T, value_type) self.length = len...
1
Python
CWE-193
Off-by-one Error
A product calculates or uses an incorrect maximum or minimum value that is 1 more, or 1 less, than the correct value.
https://cwe.mitre.org/data/definitions/193.html
safe
def __init__(self, value_type: VyperType, length: int): if not 0 < length < 2**256: raise InvalidType("Array length is invalid") if length >= 2**64: warnings.warn("Use of large arrays can be unsafe!") super().__init__(UINT256_T, value_type) self.length = len...
1
Python
CWE-682
Incorrect Calculation
The product performs a calculation that generates incorrect or unintended results that are later used in security-critical decisions or resource management.
https://cwe.mitre.org/data/definitions/682.html
safe
def test_dynarray_length_no_clobber(get_contract, assert_tx_failed, code): # check that length is not clobbered before dynarray data copy happens c = get_contract(code) assert_tx_failed(lambda: c.should_revert())
1
Python
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def append_dyn_array(darray_node, elem_node): assert isinstance(darray_node.typ, DArrayT) assert darray_node.typ.count > 0, "jerk boy u r out" ret = ["seq"] with darray_node.cache_when_complex("darray") as (b1, darray_node): len_ = get_dyn_array_count(darray_node) with len_.cache_when_...
1
Python
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def make_byte_array_copier(dst, src): assert isinstance(src.typ, _BytestringT) assert isinstance(dst.typ, _BytestringT) _check_assign_bytes(dst, src) # TODO: remove this branch, copy_bytes and get_bytearray_length should handle if src.value == "~empty": # set length word to 0. retu...
1
Python
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def pop_dyn_array(darray_node, return_popped_item): assert isinstance(darray_node.typ, DArrayT) assert darray_node.encoding == Encoding.VYPER ret = ["seq"] with darray_node.cache_when_complex("darray") as (b1, darray_node): old_len = clamp("gt", get_dyn_array_count(darray_node), 0) new_l...
1
Python
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def test_for_range_oob_check(get_contract, assert_tx_failed, typ): code = f""" @external def test(): x: {typ} = max_value({typ}) for i in range(x, x+2): pass """ c = get_contract(code) assert_tx_failed(lambda: c.test())
1
Python
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def test_for_range_edge(get_contract, typ): code = f""" @external def test(): found: bool = False x: {typ} = max_value({typ}) for i in range(x, x + 1): if i == max_value({typ}): found = True assert found found = False x = max_value({typ}) - 1 for i in range(x, x + 2...
1
Python
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def _parse_For_range(self): # TODO make sure type always gets annotated if "type" in self.stmt.target._metadata: iter_typ = self.stmt.target._metadata["type"] else: iter_typ = INT256_T # Get arg0 arg0 = self.stmt.iter.args[0] num_of_args = len...
1
Python
CWE-190
Integer Overflow or Wraparound
The product performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def fuzz(kwarg1, kwarg2, default1, default2): code = f""" @internal def foo(a: {typ1} = {repr(default1)}, b: {typ2} = {repr(default2)}) -> ({typ1}, {typ2}): return a, b @external def test0() -> ({typ1}, {typ2}): return self.foo() @external def test1() -> ({typ1}, {typ2}): return self.foo({repr...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_internal_call_kwargs(get_contract, typ1, strategy1, typ2, strategy2): # GHSA-ph9x-4vc9-m39g @given(kwarg1=strategy1, default1=strategy1, kwarg2=strategy2, default2=strategy2) @settings(deadline=None, max_examples=5) # len(cases) * len(cases) * 5 * 5 def fuzz(kwarg1, kwarg2, default1, default2...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def lookup_internal_function(self, method_name, args_ir, ast_source): # TODO is this the right module for me? """ Using a list of args, find the internal method to use, and the kwargs which need to be filled in by the compiler """ sig = self.sigs["self"].get(method_n...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def build_IR(self, expr, args, kwargs, context): input_buf = context.new_internal_variable(get_type_for_exact_size(128)) output_buf = MemoryPositions.FREE_VAR_SPACE return IRnode.from_list( [ "seq", # clear output memory first, ecrecover can return...
1
Python
CWE-252
Unchecked Return Value
The product does not check the return value from a method or function, which can prevent it from detecting unexpected states and conditions.
https://cwe.mitre.org/data/definitions/252.html
safe
def validate_identifier(attr, ast_node=None): if not re.match("^[_a-zA-Z][a-zA-Z0-9_]*$", attr): raise StructureException(f"'{attr}' contains invalid character(s)", ast_node) if attr.lower() in RESERVED_KEYWORDS: raise StructureException(f"'{attr}' is a reserved keyword", ast_node)
1
Python
CWE-667
Improper Locking
The product does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.
https://cwe.mitre.org/data/definitions/667.html
safe
def __init__(self, message="Error Message not found.", *items): """ Exception initializer. Arguments --------- message : str Error message to display with the exception. *items : VyperNode | Tuple[str, VyperNode], optional Vyper ast node(s), o...
1
Python
CWE-667
Improper Locking
The product does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.
https://cwe.mitre.org/data/definitions/667.html
safe
def test_concat_buffer3(get_contract): # GHSA-2q8v-3gqq-4f8p code = """ s: String[1] s2: String[33] s3: String[34] @external def __init__(): self.s = "a" self.s2 = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa" # 33*'a' @internal def bar() -> uint256: self.s3 = concat(self.s, self.s2) return 1 @external...
1
Python
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
safe
def test_concat_buffer2(get_contract): # GHSA-2q8v-3gqq-4f8p code = """ i: immutable(int256) @external def __init__(): i = -1 s: String[2] = concat("a", "b") @external def foo() -> int256: return i """ c = get_contract(code) assert c.foo() == -1
1
Python
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
safe
def test_concat_buffer(get_contract): # GHSA-2q8v-3gqq-4f8p code = """ @internal def bar() -> uint256: sss: String[2] = concat("a", "b") return 1 @external def foo() -> int256: a: int256 = -1 b: uint256 = self.bar() return a """ c = get_contract(code) assert c.foo() == -1
1
Python
CWE-120
Buffer Copy without Checking Size of Input ('Classic Buffer Overflow')
The product copies an input buffer to an output buffer without verifying that the size of the input buffer is less than the size of the output buffer, leading to a buffer overflow.
https://cwe.mitre.org/data/definitions/120.html
safe
def on_part_end(self) -> None: if self._current_part.file is None: self.items.append( ( self._current_part.field_name, _user_safe_decode(self._current_part.data, self._charset), ) ) else: self...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_part_begin(self) -> None: self._current_part = MultipartPart()
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_part_data(self, data: bytes, start: int, end: int) -> None: message_bytes = data[start:end] if self._current_part.file is None: self._current_part.data += message_bytes else: self._file_parts_to_write.append((self._current_part, message_bytes))
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_header_field(self, data: bytes, start: int, end: int) -> None: self._current_partial_header_name += data[start:end]
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_header_value(self, data: bytes, start: int, end: int) -> None: self._current_partial_header_value += data[start:end]
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def __init__( self, headers: Headers, stream: typing.AsyncGenerator[bytes, None], *, max_files: typing.Union[int, float] = 1000, max_fields: typing.Union[int, float] = 1000, ) -> None: assert ( multipart is not None ), "The `python-mult...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_end(self) -> None: pass
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
async def parse(self) -> FormData: # Parse the Content-Type header to get the multipart boundary. _, params = parse_options_header(self.headers["Content-Type"]) charset = params.get(b"charset", "utf-8") if type(charset) == bytes: charset = charset.decode("latin-1") ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def on_headers_finished(self) -> None: disposition, options = parse_options_header( self._current_part.content_disposition ) try: self._current_part.field_name = _user_safe_decode( options[b"name"], self._charset ) except KeyError: ...
1
Python
CWE-400
Uncontrolled Resource Consumption
The product does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
safe
def _configure_templating(cls, app): tempdir = app.config["PYLOAD_API"].get_cachedir() cache_path = os.path.join(tempdir, "jinja") os.makedirs(cache_path, exist_ok=True) app.create_jinja_environment() # NOTE: enable autoescape for all file extensions (included .js) ...
0
Python
CWE-319
Cleartext Transmission of Sensitive Information
The product transmits sensitive or security-critical data in cleartext in a communication channel that can be sniffed by unauthorized actors.
https://cwe.mitre.org/data/definitions/319.html
vulnerable
def _configure_handlers(cls, app): """ Register error handlers. """ for exc, fn in cls.FLASK_ERROR_HANDLERS: app.register_error_handler(exc, fn)
0
Python
CWE-1021
Improper Restriction of Rendered UI Layers or Frames
The web application does not restrict or incorrectly restricts frame objects or UI layers that belong to another application or domain, which can lead to user confusion about which interface the user is interacting with.
https://cwe.mitre.org/data/definitions/1021.html
vulnerable
def get_events(self, uuid): """ Lists occured events, may be affected to changes in future. :param uuid: :return: list of `Events` """ events = self.pyload.event_manager.get_events(uuid) new_events = [] def conv_dest(d): return (Destinati...
0
Python
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
def is_authenticated(session=flask.session): return session.get("name") and session.get( "authenticated" ) # NOTE: why checks name?
0
Python
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
def cast(self, typ, value): """ cast value to given format. """ if typ == "int": return int(value) elif typ == "float": return float(value) elif typ == "str": return "" if value is None else str(value) elif typ == "bytes"...
0
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def init_handle(self): """ sets common options to curl handle. """ self.c.setopt(pycurl.FOLLOWLOCATION, 1) self.c.setopt(pycurl.MAXREDIRS, 10) self.c.setopt(pycurl.CONNECTTIMEOUT, 30) self.c.setopt(pycurl.NOSIGNAL, 1) self.c.setopt(pycurl.NOPROGRESS, 1...
0
Python
CWE-295
Improper Certificate Validation
The product does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
def info(): api = flask.current_app.config["PYLOAD_API"] conf = api.get_config_dict() extra = os.uname() if hasattr(os, "uname") else tuple() context = { "python": sys.version, "os": " ".join((os.name, sys.platform) + extra), "version": api.get_server_version(), "folder"...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def login(): user = flask.request.form["username"] password = flask.request.form["password"] api = flask.current_app.config["PYLOAD_API"] user_info = api.check_auth(user, password) if not user_info: log.error(f"Login failed for user '{user}'") return jsonify(False) s = set_ses...
0
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
def login(): api = flask.current_app.config["PYLOAD_API"] next = get_redirect_url(fallback=flask.url_for("app.dashboard")) if flask.request.method == "POST": user = flask.request.form["username"] password = flask.request.form["password"] user_info = api.check_auth(user, password) ...
0
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
def _configure_session(cls, app): tempdir = app.config["PYLOAD_API"].get_cachedir() cache_path = os.path.join(tempdir, "flask") os.makedirs(cache_path, exist_ok=True) app.config["SESSION_FILE_DIR"] = cache_path app.config["SESSION_TYPE"] = "filesystem" app.config["SE...
0
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
def get_throttles(self): throttles = super().get_throttles() if self.action == "reset_password": throttles.append(PasswordResetRequestThrottle()) return throttles
0
Python
CWE-285
Improper Authorization
The product does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
vulnerable
def clean_identity(self): v = self.cleaned_data["identity"] if len(v) > 254: raise forms.ValidationError("Address is too long.") if User.objects.filter(email=v).exists(): raise forms.ValidationError( "An account with this email address already exists....
0
Python
CWE-203
Observable Discrepancy
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
https://cwe.mitre.org/data/definitions/203.html
vulnerable
def test_it_checks_for_existing_users(self): alice = User(username="alice", email="alice@example.org") alice.save() form = {"identity": "alice@example.org", "tz": ""} r = self.client.post("/accounts/signup/", form) self.assertContains(r, "already exists")
0
Python
CWE-203
Observable Discrepancy
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
https://cwe.mitre.org/data/definitions/203.html
vulnerable