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( self.extensionless_document.get_file_hash(), "7d8c4778b182e4f3bd442408c64a6e22a4b0ed85", )
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 if not self.iterations: return b"" return b"A" * bytes self.assertEqual( hash_filelike(FakeLargeFile()), "187cc1db32624dccace20d042f6d631f1a483020", )
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 if not self.iterations: return b"" return b"A" * bytes self.assertEqual( hash_filelike(FakeLargeFile()), "187cc1db32624dccace20d042f6d631f1a483020", )
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")), "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_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")), "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 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) except (AttributeError, UnsupportedOperation): pass hasher = sha1() while True: data = filelike.read(HASH_READ_SIZE) if not data: break # Use `force_bytes` to account for files opened as text hasher.update(force_bytes(data)) if hasattr(filelike, "seek"): # Reset the file handler to where it was before filelike.seek(file_pos) return hasher.hexdigest()
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) except (AttributeError, UnsupportedOperation): pass hasher = sha1() while True: data = filelike.read(HASH_READ_SIZE) if not data: break # Use `force_bytes` to account for files opened as text hasher.update(force_bytes(data)) if hasattr(filelike, "seek"): # Reset the file handler to where it was before filelike.seek(file_pos) return hasher.hexdigest()
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 = FileField.to_python(self, data) if f is None: return None # Get the file content ready for Willow if hasattr(data, "temporary_file_path"): # Django's `TemporaryUploadedFile` is enough of a file to satisfy Willow # Willow doesn't support opening images by path https://github.com/wagtail/Willow/issues/108 file = data else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # Annotate the python representation of the FileField with the image # property so subclasses can reuse it for their own validation f.image = willow.Image.open(file) f.content_type = image_format_name_to_content_type(f.image.format_name) except Exception as exc: # Willow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) if f is not None: self.check_image_file_size(f) self.check_image_file_format(f) self.check_image_pixel_size(f) return 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 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 = FileField.to_python(self, data) if f is None: return None # Get the file content ready for Willow if hasattr(data, "temporary_file_path"): # Django's `TemporaryUploadedFile` is enough of a file to satisfy Willow # Willow doesn't support opening images by path https://github.com/wagtail/Willow/issues/108 file = data else: if hasattr(data, "read"): file = BytesIO(data.read()) else: file = BytesIO(data["content"]) try: # Annotate the python representation of the FileField with the image # property so subclasses can reuse it for their own validation f.image = willow.Image.open(file) f.content_type = image_format_name_to_content_type(f.image.format_name) except Exception as exc: # Willow doesn't recognize it as an image. raise ValidationError( self.error_messages["invalid_image"], code="invalid_image", ) from exc if hasattr(f, "seek") and callable(f.seek): f.seek(0) if f is not None: self.check_image_file_size(f) self.check_image_file_format(f) self.check_image_pixel_size(f) return 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 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" ) uploaded_file.write(test_image_file.file.getvalue()) uploaded_file.seek(0) response = self.post( { "title": "Test image", "file": uploaded_file, } ) # Should redirect back to index self.assertRedirects(response, reverse("wagtailimages:index")) # Check that the image was created images = Image.objects.filter(title="Test image") self.assertEqual(images.count(), 1) # Test that size was populated correctly image = images.first() self.assertEqual(image.width, 640) self.assertEqual(image.height, 480) # Test that the file_size/hash fields were set self.assertTrue(image.file_size) self.assertTrue(image.file_hash) # Test that it was placed in the root collection root_collection = Collection.get_first_root_node() self.assertEqual(image.collection, root_collection)
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" ) uploaded_file.write(test_image_file.file.getvalue()) uploaded_file.seek(0) response = self.post( { "title": "Test image", "file": uploaded_file, } ) # Should redirect back to index self.assertRedirects(response, reverse("wagtailimages:index")) # Check that the image was created images = Image.objects.filter(title="Test image") self.assertEqual(images.count(), 1) # Test that size was populated correctly image = images.first() self.assertEqual(image.width, 640) self.assertEqual(image.height, 480) # Test that the file_size/hash fields were set self.assertTrue(image.file_size) self.assertTrue(image.file_hash) # Test that it was placed in the root collection root_collection = Collection.get_first_root_node() self.assertEqual(image.collection, root_collection)
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, numeric_owner)
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 restricted directory.
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 restricted directory.
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"]}","password": "{self.connection_data["password"]}"' + '}' response = requests.post(self.base_url + '/apiv2/login', headers=headers, data=data) return { 'Authorization': '_dremio' + response.json()['token'], 'Content-Type': 'application/json', }
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': url = arg2 if op == '=': urls = [str(url)] elif op == 'in': if type(url) == str: urls = [str(url)] else: urls = url else: raise NotImplementedError( f'url can be url = "someurl", you can also crawl multiple sites, as follows:' f' url IN ("url1", "url2", ..)' ) else: pass if len(urls) == 0: raise NotImplementedError( f'You must specify what url you want to crawl, for example: SELECT * FROM crawl WHERE url IN ("someurl", ..)') if query.limit is None: raise NotImplementedError(f'You must specify a LIMIT which defines the number of pages to crawl') limit = query.limit.value if limit < 0: limit = 0 config = Config() is_cloud = config.get("cloud", False) if is_cloud: urls = [ url for url in urls if not is_private_url(url) ] result = get_all_websites(urls, limit, html=False) if len(result) > limit: result = result[:limit] # filter targets result = project_dataframe(result, query.targets, self.get_columns()) return result
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': url = arg2 if op == '=': urls = [str(url)] elif op == 'in': if type(url) == str: urls = [str(url)] else: urls = url else: raise NotImplementedError( f'url can be url = "someurl", you can also crawl multiple sites, as follows:' f' url IN ("url1", "url2", ..)' ) else: pass if len(urls) == 0: raise NotImplementedError( f'You must specify what url you want to crawl, for example: SELECT * FROM crawl WHERE url IN ("someurl", ..)') if query.limit is None: raise NotImplementedError(f'You must specify a LIMIT which defines the number of pages to crawl') limit = query.limit.value if limit < 0: limit = 0 config = Config() is_cloud = config.get("cloud", False) if is_cloud: urls = [ url for url in urls if not is_private_url(url) ] result = get_all_websites(urls, limit, html=False) if len(result) > limit: result = result[:limit] # filter targets result = project_dataframe(result, query.targets, self.get_columns()) return result
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"].split(" ") ir_return_idx_start = assembly.index("{") ir_return_idx_end = assembly.index("}") assert "CALLDATALOAD" in assembly assert "CALLDATACOPY" not in assembly[:ir_return_idx_start] + assembly[ir_return_idx_end:] assert "CALLDATALOAD" not in assembly[:ir_return_idx_start] + assembly[ir_return_idx_end:]
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 staticcall) @external def fail2(should_raise: bool) -> int128: if should_raise: self.baz = self.baz + 1 return self.baz """ caller_source = """ @external @view def foo(_addr: address, should_raise: bool) -> uint256: success: bool = True response: Bytes[32] = b"" success, response = raw_call( _addr, _abi_encode(should_raise, method_id=method_id("fail1(bool)")), max_outsize=32, is_static_call=True, revert_on_failure=False, ) assert success == (not should_raise) return 1 @external @view def bar(_addr: address, should_raise: bool) -> uint256: success: bool = True response: Bytes[32] = b"" success, response = raw_call( _addr, _abi_encode(should_raise, method_id=method_id("fail2(bool)")), max_outsize=32, is_static_call=True, revert_on_failure=False, ) assert success == (not should_raise) return 2 # test max_outsize not set case @external @nonpayable def baz(_addr: address, should_raise: bool) -> uint256: success: bool = True success = raw_call( _addr, _abi_encode(should_raise, method_id=method_id("fail1(bool)")), revert_on_failure=False, ) assert success == (not should_raise) return 3 """ target = get_contract(target_source) caller = get_contract(caller_source) assert caller.foo(target.address, True) == 1 assert caller.foo(target.address, False) == 1 assert caller.bar(target.address, True) == 2 assert caller.bar(target.address, False) == 2 assert caller.baz(target.address, True) == 3 assert caller.baz(target.address, False) == 3
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_formats=["layout"], storage_layout_override=storage_layout_override )
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_formats=["layout"], storage_layout_override=storage_layout_override )
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_formats=["layout"], storage_layout_override=storage_layout_override )
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)) len_ = ceil32(type_.size_in_bytes) # this could have better typing but leave it untyped until # we understand the use case better ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_} offset += len_ return ret
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)) len_ = ceil32(type_.size_in_bytes) # this could have better typing but leave it untyped until # we understand the use case better ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_} offset += len_ return ret
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)) len_ = ceil32(type_.size_in_bytes) # this could have better typing but leave it untyped until # we understand the use case better ret[node.target.id] = {"type": str(type_), "offset": offset, "length": len_} offset += len_ return ret
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 += n return ret
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 += n return ret
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 += n return ret
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 = length
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 = length
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 = length
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_complex("old_darray_len") as (b2, len_): assertion = ["assert", ["lt", len_, darray_node.typ.count]] ret.append(IRnode.from_list(assertion, error_msg=f"{darray_node.typ} bounds check")) # NOTE: typechecks elem_node # NOTE skip array bounds check bc we already asserted len two lines up ret.append( make_setter(get_element_ptr(darray_node, len_, array_bounds_check=False), elem_node) ) # store new length ret.append(STORE(darray_node, ["add", len_, 1])) return IRnode.from_list(b1.resolve(b2.resolve(ret)))
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. return STORE(dst, 0) with src.cache_when_complex("src") as (b1, src): with get_bytearray_length(src).cache_when_complex("len") as (b2, len_): max_bytes = src.typ.maxlen ret = ["seq"] dst_ = bytes_data_ptr(dst) src_ = bytes_data_ptr(src) ret.append(copy_bytes(dst_, src_, len_, max_bytes)) # store length ret.append(STORE(dst, len_)) return b1.resolve(b2.resolve(ret))
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_len = IRnode.from_list(["sub", old_len, 1], typ=UINT256_T) with new_len.cache_when_complex("new_len") as (b2, new_len): # store new length ret.append(STORE(darray_node, new_len)) # NOTE skip array bounds check bc we already asserted len two lines up if return_popped_item: popped_item = get_element_ptr(darray_node, new_len, array_bounds_check=False) ret.append(popped_item) typ = popped_item.typ location = popped_item.location else: typ, location = None, None return IRnode.from_list(b1.resolve(b2.resolve(ret)), typ=typ, location=location)
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): if i == max_value({typ}): found = True assert found """ c = get_contract(code) 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 _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(self.stmt.iter.args) # Type 1 for, e.g. for i in range(10): ... if num_of_args == 1: arg0_val = self._get_range_const_value(arg0) start = IRnode.from_list(0, typ=iter_typ) rounds = arg0_val # Type 2 for, e.g. for i in range(100, 110): ... elif self._check_valid_range_constant(self.stmt.iter.args[1]).is_literal: arg0_val = self._get_range_const_value(arg0) arg1_val = self._get_range_const_value(self.stmt.iter.args[1]) start = IRnode.from_list(arg0_val, typ=iter_typ) rounds = IRnode.from_list(arg1_val - arg0_val, typ=iter_typ) # Type 3 for, e.g. for i in range(x, x + 10): ... else: arg1 = self.stmt.iter.args[1] rounds = self._get_range_const_value(arg1.right) start = Expr.parse_value_expr(arg0, self.context) _, hi = start.typ.int_bounds start = clamp("le", start, hi + 1 - rounds) r = rounds if isinstance(rounds, int) else rounds.value if r < 1: return varname = self.stmt.target.id i = IRnode.from_list(self.context.fresh_varname("range_ix"), typ=UINT256_T) iptr = self.context.new_variable(varname, iter_typ) self.context.forvars[varname] = True loop_body = ["seq"] # store the current value of i so it is accessible to userland loop_body.append(["mstore", iptr, i]) loop_body.append(parse_body(self.stmt.body, self.context)) ir_node = IRnode.from_list(["repeat", i, start, rounds, rounds, loop_body]) del self.context.forvars[varname] return ir_node
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(kwarg1)}) @external def test2() -> ({typ1}, {typ2}): return self.foo({repr(kwarg1)}, {repr(kwarg2)}) @external def test3(x1: {typ1}) -> ({typ1}, {typ2}): return self.foo(x1) @external def test4(x1: {typ1}, x2: {typ2}) -> ({typ1}, {typ2}): return self.foo(x1, x2) """ c = get_contract(code) assert c.test0() == [default1, default2] assert c.test1() == [kwarg1, default2] assert c.test2() == [kwarg1, kwarg2] assert c.test3(kwarg1) == [kwarg1, default2] assert c.test4(kwarg1, kwarg2) == [kwarg1, kwarg2]
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): 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(kwarg1)}) @external def test2() -> ({typ1}, {typ2}): return self.foo({repr(kwarg1)}, {repr(kwarg2)}) @external def test3(x1: {typ1}) -> ({typ1}, {typ2}): return self.foo(x1) @external def test4(x1: {typ1}, x2: {typ2}) -> ({typ1}, {typ2}): return self.foo(x1, x2) """ c = get_contract(code) assert c.test0() == [default1, default2] assert c.test1() == [kwarg1, default2] assert c.test2() == [kwarg1, kwarg2] assert c.test3(kwarg1) == [kwarg1, default2] assert c.test4(kwarg1, kwarg2) == [kwarg1, kwarg2] fuzz()
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_name, None) def _check(cond, s="Unreachable"): if not cond: raise CompilerPanic(s) # these should have been caught during type checking; sanity check _check(sig is not None) _check(sig.internal) _check(len(sig.base_args) <= len(args_ir) <= len(sig.args)) # more sanity check, that the types match # _check(all(l.typ == r.typ for (l, r) in zip(args_ir, sig.args)) num_provided_kwargs = len(args_ir) - len(sig.base_args) kw_vals = list(sig.default_values.values())[num_provided_kwargs:] return sig, kw_vals
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 0 bytes ["mstore", output_buf, 0], ["mstore", input_buf, args[0]], ["mstore", input_buf + 32, args[1]], ["mstore", input_buf + 64, args[2]], ["mstore", input_buf + 96, args[3]], ["staticcall", "gas", 1, input_buf, 128, output_buf, 32], ["mload", output_buf], ], typ=AddressT(), )
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), or tuple of (description, node) indicating where the exception occured. Source annotations are generated in the order the nodes are given. A single tuple of (lineno, col_offset) is also understood to support the old API, but new exceptions should not use this approach. """ self.message = message self.lineno = None self.col_offset = None if len(items) == 1 and isinstance(items[0], tuple) and isinstance(items[0][0], int): # support older exceptions that don't annotate - remove this in the future! self.lineno, self.col_offset = items[0][:2] else: # strip out None sources so that None can be passed as a valid # annotation (in case it is only available optionally) self.annotations = [k for k in items if k is not None]
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 def foo() -> int256: i: int256 = -1 b: uint256 = self.bar() 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_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._file_parts_to_finish.append(self._current_part) # The file can be added to the items right now even though it's not # finished yet, because it will be finished in the `parse()` method, before # self.items is used in the return value. self.items.append((self._current_part.field_name, self._current_part.file))
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-multipart` library must be installed to use form parsing." self.headers = headers self.stream = stream self.max_files = max_files self.max_fields = max_fields self.items: typing.List[typing.Tuple[str, typing.Union[str, UploadFile]]] = [] self._current_files = 0 self._current_fields = 0 self._current_partial_header_name: bytes = b"" self._current_partial_header_value: bytes = b"" self._current_part = MultipartPart() self._charset = "" self._file_parts_to_write: typing.List[typing.Tuple[MultipartPart, bytes]] = [] self._file_parts_to_finish: typing.List[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_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") self._charset = charset try: boundary = params[b"boundary"] except KeyError: raise MultiPartException("Missing boundary in multipart.") # Callbacks dictionary. callbacks = { "on_part_begin": self.on_part_begin, "on_part_data": self.on_part_data, "on_part_end": self.on_part_end, "on_header_field": self.on_header_field, "on_header_value": self.on_header_value, "on_header_end": self.on_header_end, "on_headers_finished": self.on_headers_finished, "on_end": self.on_end, } # Create the parser. parser = multipart.MultipartParser(boundary, callbacks) # Feed the parser with data from the request. async for chunk in self.stream: parser.write(chunk) # Write file data, it needs to use await with the UploadFile methods that # call the corresponding file methods *in a threadpool*, otherwise, if # they were called directly in the callback methods above (regular, # non-async functions), that would block the event loop in the main thread. for part, data in self._file_parts_to_write: assert part.file # for type checkers await part.file.write(data) for part in self._file_parts_to_finish: assert part.file # for type checkers await part.file.seek(0) self._file_parts_to_write.clear() self._file_parts_to_finish.clear() parser.finalize() return FormData(self.items)
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: raise MultiPartException( 'The Content-Disposition header field "name" must be ' "provided." ) if b"filename" in options: self._current_files += 1 if self._current_files > self.max_files: raise MultiPartException( f"Too many files. Maximum number of files is {self.max_files}." ) filename = _user_safe_decode(options[b"filename"], self._charset) tempfile = SpooledTemporaryFile(max_size=self.max_file_size) self._current_part.file = UploadFile( file=tempfile, # type: ignore[arg-type] size=0, filename=filename, headers=Headers(raw=self._current_part.item_headers), ) else: self._current_fields += 1 if self._current_fields > self.max_fields: raise MultiPartException( f"Too many fields. Maximum number of fields is {self.max_fields}." ) self._current_part.file = None
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) # maybe this will break .txt rendering, but we don't render this kind of files actually # that does not change 'default_for_string=False' (by default) app.jinja_env.autoescape = jinja2.select_autoescape(default=True) app.jinja_env.bytecode_cache = jinja2.FileSystemBytecodeCache(cache_path) for fn in cls.JINJA_TEMPLATE_FILTERS: app.add_template_filter(fn) for fn in cls.JINJA_TEMPLATE_GLOBALS: app.add_template_global(fn) for fn in cls.JINJA_CONTEXT_PROCESSORS: app.context_processor(fn)
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 (Destination.QUEUE if d == "queue" else Destination.COLLECTOR).value for e in events: event = EventInfo() event.eventname = e[0] if e[0] in ("update", "remove", "insert"): event.id = e[3] event.type = ( ElementType.PACKAGE if e[2] == "pack" else ElementType.FILE ).value event.destination = conv_dest(e[1]) elif e[0] == "order": if e[1]: event.id = e[1] event.type = ( ElementType.PACKAGE if e[2] == "pack" else ElementType.FILE ) event.destination = conv_dest(e[3]) elif e[0] == "reload": event.destination = conv_dest(e[1]) new_events.append(event) return new_events
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": return b"" if value is None else bytes(value) elif typ == "bool": value = "" if value is None else str(value) return value.lower() in ("1", "true", "on", "yes", "y") elif typ == "time": value = "" if value is None else str(value) if not value: value = "0:00" if ":" not in value: value += ":00" return value elif typ in ("file", "folder"): return "" if value in (None, "") else os.path.realpath(os.path.expanduser(os.fsdecode(value))) else: return value
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) if hasattr(pycurl, "AUTOREFERER"): self.c.setopt(pycurl.AUTOREFERER, 1) self.c.setopt(pycurl.SSL_VERIFYPEER, 0) self.c.setopt(pycurl.LOW_SPEED_TIME, 60) self.c.setopt(pycurl.LOW_SPEED_LIMIT, 5) if hasattr(pycurl, "USE_SSL"): self.c.setopt(pycurl.USE_SSL, pycurl.USESSL_TRY) # self.c.setopt(pycurl.VERBOSE, 1) # self.c.setopt(pycurl.HTTP_VERSION, pycurl.CURL_HTTP_VERSION_1_1) self.c.setopt( pycurl.USERAGENT, b"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.113 Safari/537.36", ) if pycurl.version_info()[7]: self.c.setopt(pycurl.ENCODING, b"gzip, deflate") self.c.setopt( pycurl.HTTPHEADER, [ b"Accept: */*", b"Accept-Language: en-US,en", b"Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7", b"Connection: keep-alive", b"Keep-Alive: 300", b"Expect:", ], )
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": PKGDIR, "config": api.get_userdir(), "download": conf["general"]["storage_folder"]["value"], "freespace": format.size(api.free_space()), "webif": conf["webui"]["port"]["value"], "language": conf["general"]["language"]["value"], } return render_template("info.html", **context)
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_session(user_info) log.info(f"User '{user}' successfully logged in") flask.flash("Logged in successfully") return jsonify(s)
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) if not user_info: log.error(f"Login failed for user '{user}'") return render_template("login.html", next=next, errors=True) set_session(user_info) log.info(f"User '{user}' successfully logged in") flask.flash("Logged in successfully") if is_authenticated(): return flask.redirect(next) if api.get_config_value("webui", "autologin"): allusers = api.get_all_userdata() if len(allusers) == 1: # TODO: check if localhost user_info = list(allusers.values())[0] set_session(user_info) # NOTE: Double-check authentication here because if session[name] is empty, # next login_required redirects here again and all loop out. if is_authenticated(): return flask.redirect(next) return render_template("login.html", next=next)
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["SESSION_COOKIE_NAME"] = "pyload_session" app.config["SESSION_COOKIE_SAMESITE"] = "None" app.config["SESSION_COOKIE_SECURE"] = app.config["PYLOAD_API"].get_config_value("webui", "use_ssl") app.config["SESSION_PERMANENT"] = False session_lifetime = max(app.config["PYLOAD_API"].get_config_value("webui", "session_lifetime"), 1) * 60 app.config["PERMANENT_SESSION_LIFETIME"] = session_lifetime
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." ) return v
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="[email protected]") alice.save() form = {"identity": "[email protected]", "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