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_create_custom_connector_template( self, db: Session, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ) -> None: template = CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) template.save(db=db) # assert we can retrieve a connector template by key and # that the values are the same as what we persisted custom_connector: Optional[ CustomConnectorTemplate ] = CustomConnectorTemplate.get_by_key_or_id( db=db, data={"key": "planet_express"} ) assert custom_connector assert custom_connector.name == "Planet Express" assert custom_connector.config == planet_express_config assert custom_connector.dataset == planet_express_dataset assert custom_connector.icon == planet_express_icon assert custom_connector.functions == planet_express_functions
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_create_custom_connector_template( self, db: Session, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ) -> None: template = CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) template.save(db=db) # assert we can retrieve a connector template by key and # that the values are the same as what we persisted custom_connector: Optional[ CustomConnectorTemplate ] = CustomConnectorTemplate.get_by_key_or_id( db=db, data={"key": "planet_express"} ) assert custom_connector assert custom_connector.name == "Planet Express" assert custom_connector.config == planet_express_config assert custom_connector.dataset == planet_express_dataset assert custom_connector.icon == planet_express_icon assert custom_connector.functions == planet_express_functions
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() # verify that the template in the registry is the same as the one in the database assert connector_templates == { "planet_express": ConnectorTemplate( config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, human_readable="Planet Express", ) } # assert the request override was registered SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() # verify that the template in the registry is the same as the one in the database assert connector_templates == { "planet_express": ConnectorTemplate( config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, human_readable="Planet Express", ) } # assert the request override was registered SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_no_templates(self): CONFIG.security.allow_custom_connector_functions = True connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {}
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_no_templates(self): CONFIG.security.allow_custom_connector_functions = True connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {}
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_save_template( self, mock_create_or_update: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): db = MagicMock() CustomConnectorTemplateLoader.save_template( db, ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } ) ), ) # verify that a connector template can updated with no issue CustomConnectorTemplateLoader.save_template( db, ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } ) ), ) assert mock_create_or_update.call_count == 2
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_save_template( self, mock_create_or_update: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): db = MagicMock() CustomConnectorTemplateLoader.save_template( db, ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } ) ), ) # verify that a connector template can updated with no issue CustomConnectorTemplateLoader.save_template( db, ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": planet_express_functions, "icon.svg": planet_express_icon, } ) ), ) assert mock_create_or_update.call_count == 2
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_function_loader(self): """Verify that all override implementations can be loaded by RestrictedPython""" overrides_path = "src/fides/api/service/saas_request/override_implementations" for filename in os.listdir(overrides_path): if filename.endswith(".py") and filename != "__init__.py": file_path = os.path.join(overrides_path, filename) with open(file_path, "r") as file: register_custom_functions(file.read())
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_function_loader(self): """Verify that all override implementations can be loaded by RestrictedPython""" overrides_path = "src/fides/api/service/saas_request/override_implementations" for filename in os.listdir(overrides_path): if filename.endswith(".py") and filename != "__init__.py": file_path = os.path.join(overrides_path, filename) with open(file_path, "r") as file: register_custom_functions(file.read())
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_loaders_have_separate_instances( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database file_connector_templates = FileConnectorTemplateLoader.get_connector_templates() custom_connector_templates = ( CustomConnectorTemplateLoader.get_connector_templates() ) assert file_connector_templates != custom_connector_templates
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_loaders_have_separate_instances( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database file_connector_templates = FileConnectorTemplateLoader.get_connector_templates() custom_connector_templates = ( CustomConnectorTemplateLoader.get_connector_templates() ) assert file_connector_templates != custom_connector_templates
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_disallowed_modules( self, planet_express_config, planet_express_dataset, planet_express_icon, ): CONFIG.security.allow_custom_connector_functions = True with pytest.raises(SyntaxError) as exc: CustomConnectorTemplateLoader.save_template( MagicMock(), ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": "import os", "icon.svg": planet_express_icon, } ) ), ) assert "Import of 'os' module is not allowed." == str(exc.value)
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_disallowed_modules( self, planet_express_config, planet_express_dataset, planet_express_icon, ): CONFIG.security.allow_custom_connector_functions = True with pytest.raises(SyntaxError) as exc: CustomConnectorTemplateLoader.save_template( MagicMock(), ZipFile( create_zip_file( { "config.yml": planet_express_config, "dataset.yml": planet_express_dataset, "functions.py": "import os", "icon.svg": planet_express_icon, } ) ), ) assert "Import of 'os' module is not allowed." == str(exc.value)
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def replaceable_planet_express_zip( self, replaceable_planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ) -> BytesIO: return create_zip_file( { "config.yml": replaceable_planet_express_config, "dataset.yml": planet_express_dataset, "icon.svg": planet_express_icon, "functions.py": planet_express_functions, } )
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def replaceable_planet_express_zip( self, replaceable_planet_express_config, planet_express_dataset, planet_express_functions, planet_express_icon, ) -> BytesIO: return create_zip_file( { "config.yml": replaceable_planet_express_config, "dataset.yml": planet_express_dataset, "icon.svg": planet_express_icon, "functions.py": planet_express_functions, } )
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_invalid_template( self, mock_all: MagicMock, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config="planet_express_config", dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # verify the custom functions aren't loaded if the template is invalid connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {} with pytest.raises(NoSuchSaaSRequestOverrideException): SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was not registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" not in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_invalid_template( self, mock_all: MagicMock, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = True mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config="planet_express_config", dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # verify the custom functions aren't loaded if the template is invalid connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {} with pytest.raises(NoSuchSaaSRequestOverrideException): SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was not registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" not in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_custom_connector_functions_disabled_custom_functions( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, ): """ A connector template with no custom functions should still be loaded even if allow_custom_connector_functions is set to false """ CONFIG.security.allow_custom_connector_functions = False # save custom connector template to the database mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=None, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == { "planet_express": ConnectorTemplate( config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, human_readable="Planet Express", ) }
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_custom_connector_functions_disabled_custom_functions( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, ): """ A connector template with no custom functions should still be loaded even if allow_custom_connector_functions is set to false """ CONFIG.security.allow_custom_connector_functions = False # save custom connector template to the database mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=None, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == { "planet_express": ConnectorTemplate( config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, human_readable="Planet Express", ) }
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_invalid_functions( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, ): CONFIG.security.allow_custom_connector_functions = True # save custom connector template to the database mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions="planet_express_functions", ) ] # verify nothing is loaded if the custom functions fail to load connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {}
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_invalid_functions( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, ): CONFIG.security.allow_custom_connector_functions = True # save custom connector template to the database mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions="planet_express_functions", ) ] # verify nothing is loaded if the custom functions fail to load connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {}
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_custom_connector_template_loader_custom_connector_functions_disabled( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = False mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {} with pytest.raises(NoSuchSaaSRequestOverrideException): SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was not registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" not in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-693
Protection Mechanism Failure
The product does not use or incorrectly uses a protection mechanism that provides sufficient defense against directed attacks against the product.
https://cwe.mitre.org/data/definitions/693.html
vulnerable
def test_custom_connector_template_loader_custom_connector_functions_disabled( self, mock_all: MagicMock, planet_express_config, planet_express_dataset, planet_express_icon, planet_express_functions, ): CONFIG.security.allow_custom_connector_functions = False mock_all.return_value = [ CustomConnectorTemplate( key="planet_express", name="Planet Express", config=planet_express_config, dataset=planet_express_dataset, icon=planet_express_icon, functions=planet_express_functions, ) ] # load custom connector templates from the database connector_templates = CustomConnectorTemplateLoader.get_connector_templates() assert connector_templates == {} with pytest.raises(NoSuchSaaSRequestOverrideException): SaaSRequestOverrideFactory.get_override( "planet_express_user_access", SaaSRequestType.READ ) # assert the strategy was not registered authentication_strategies = AuthenticationStrategy.get_strategies() assert "planet_express" not in [ strategy.name for strategy in authentication_strategies ]
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The product constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def __init__( self, privacy_request: PrivacyRequest, dsr_data: Dict[str, Any], ): """ Manages populating HTML templates from the given data and adding the generated pages to a zip file in a way that the pages can be navigated between. """ # zip file variables self.baos = BytesIO() # we close this in the finally block of generate() # pylint: disable=consider-using-with self.out = zipfile.ZipFile(self.baos, "w") # Jinja template environment initialization def pretty_print(value: str, indent: int = 4) -> str: return json.dumps(value, indent=indent, default=storage_json_encoder) jinja2.filters.FILTERS["pretty_print"] = pretty_print self.template_loader = Environment(loader=FileSystemLoader(DSR_DIRECTORY)) # to pass in custom colors in the future self.template_data: Dict[str, Any] = { "text_color": TEXT_COLOR, "header_color": HEADER_COLOR, "border_color": BORDER_COLOR, } self.main_links: Dict[str, Any] = {} # used to track the generated pages # report data to populate the templates self.request_data = _map_privacy_request(privacy_request) self.dsr_data = dsr_data
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def _populate_template( self, template_path: str, heading: Optional[str] = None, description: Optional[str] = None, data: Optional[Dict[str, Any]] = None, ) -> str: """Generates a file from the template and data""" report_data = { "heading": heading, "description": description, "data": data, "request": self.request_data, } report_data.update(self.template_data) template = self.template_loader.get_template(template_path) return template.render(report_data)
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def safer_getattr(object, name, default=None, getattr=getattr): """Getattr implementation which prevents using format on string objects. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ """ if isinstance(object, str) and name == 'format': raise NotImplementedError( 'Using format() on a %s is not safe.' % object.__class__.__name__) if name.startswith('_'): raise AttributeError( '"{name}" is an invalid attribute name because it ' 'starts with "_"'.format(name=name) ) return getattr(object, name, default)
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 test_string_in_utility_builtins(): from RestrictedPython.Utilities import utility_builtins assert utility_builtins['string'] is string
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 test_Guards__safer_getattr__1(): """It prevents using the format method of a string. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ """ glb = { '__builtins__': safe_builtins, } with pytest.raises(NotImplementedError) as err: restricted_exec(STRING_DOT_FORMAT_DENIED, glb) assert 'Using format() on a str is not safe.' == str(err.value)
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 test_Guards__safer_getattr__2(): """It prevents using the format method of a unicode. format() is considered harmful: http://lucumr.pocoo.org/2016/12/29/careful-with-str-format/ """ glb = { '__builtins__': safe_builtins, } with pytest.raises(NotImplementedError) as err: restricted_exec(UNICODE_DOT_FORMAT_DENIED, glb) assert 'Using format() on a str is not safe.' == str(err.value)
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 test_conn_upgrade(parser) -> None: text = ( b"GET /test HTTP/1.1\r\n" b"connection: upgrade\r\n" b"upgrade: websocket\r\n\r\n" ) messages, upgrade, tail = parser.feed_data(text) msg = messages[0][0] assert not msg.should_close assert msg.upgrade assert upgrade
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def set_k304(self) -> bool: ck = gencookie("k304", self.uparam["k304"], self.args.R, False, 86400 * 299) self.out_headerlist.append(("Set-Cookie", ck)) self.redirect("", "?h#cc") return True
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
fn invalid_feature_names_error() { // Errors for more restricted feature syntax. let p = project() .file( "Cargo.toml", r#" [package] name = "foo" version = "0.1.0" [features] "foo/bar" = [] "#, ) .file("src/lib.rs", "") .build(); p.cargo("check") .with_status(101) .with_stderr( "\ error: failed to parse manifest at `[CWD]/Cargo.toml` Caused by: feature named `foo/bar` is not allowed to contain slashes ", ) .run(); }
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def run_command(cmd, log_output=False): """ Return (exitcode, output) of executing the provided `cmd` in a shell. `cmd` can be provided as a string or as a list of arguments. If `log_output` is True, the stdout and stderr of the process will be captured and streamed to the `logger`. """ if isinstance(cmd, list): cmd = " ".join(cmd) if not log_output: exitcode, output = subprocess.getstatusoutput(cmd) return exitcode, output process = subprocess.Popen( cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, universal_newlines=True, ) while _stream_process(process): sleep(1) exitcode = process.poll() return exitcode, ""
0
Python
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
vulnerable
def _redirect_safe(self, url, default=None): """Redirect if url is on our PATH Full-domain redirects are allowed if they pass our CORS origin checks. Otherwise use default (self.base_url if unspecified). """ if default is None: default = self.base_url # protect chrome users from mishandling unescaped backslashes. # \ is not valid in urls, but some browsers treat it as / # instead of %5C, causing `\\` to behave as `//` url = url.replace("\\", "%5C") parsed = urlparse(url) if parsed.netloc or not (parsed.path + "/").startswith(self.base_url): # require that next_url be absolute path within our path allow = False # OR pass our cross-origin check if parsed.netloc: # if full URL, run our cross-origin check: origin = f"{parsed.scheme}://{parsed.netloc}" origin = origin.lower() if self.allow_origin: allow = self.allow_origin == origin elif self.allow_origin_pat: allow = bool(re.match(self.allow_origin_pat, origin)) if not allow: # not allowed, use default self.log.warning("Not allowing login redirect to %r" % url) url = default self.redirect(url)
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def write_error(self, status_code: int, **kwargs: Any) -> None: """APIHandler errors are JSON, not human pages""" self.set_header("Content-Type", "application/json") message = responses.get(status_code, "Unknown HTTP Error") reply: dict[str, Any] = { "message": message, } exc_info = kwargs.get("exc_info") if exc_info: e = exc_info[1] if isinstance(e, HTTPError): reply["message"] = e.log_message or message reply["reason"] = e.reason else: reply["message"] = "Unhandled error" reply["reason"] = None reply["traceback"] = "".join(traceback.format_exception(*exc_info)) self.log.warning("wrote error: %r", reply["message"], exc_info=True) self.finish(json.dumps(reply))
0
Python
CWE-209
Generation of Error Message Containing Sensitive Information
The product generates an error message that includes sensitive information about its environment, users, or associated data.
https://cwe.mitre.org/data/definitions/209.html
vulnerable
async def post(self, kernel_id, action): """Interrupt or restart a kernel.""" km = self.kernel_manager if action == "interrupt": await ensure_async(km.interrupt_kernel(kernel_id)) # type:ignore[func-returns-value] self.set_status(204) if action == "restart": try: await km.restart_kernel(kernel_id) except Exception as e: message = "Exception restarting kernel" self.log.error(message, exc_info=True) traceback = format_tb(e.__traceback__) self.write(json.dumps({"message": message, "traceback": traceback})) self.set_status(500) else: model = await ensure_async(km.kernel_model(kernel_id)) self.write(json.dumps(model, default=json_default)) self.finish()
0
Python
CWE-209
Generation of Error Message Containing Sensitive Information
The product generates an error message that includes sensitive information about its environment, users, or associated data.
https://cwe.mitre.org/data/definitions/209.html
vulnerable
def _create_token(cls, user_id: Optional[str], issued_on: float) -> str: """Creates a new CSRF token. Args: user_id: str|None. The user_id for which the token is generated. issued_on: float. The timestamp at which the token was issued. Returns: str. The generated CSRF token. """ cls.init_csrf_secret() # The token has 4 parts: hash of the actor user id, hash of the page # name, hash of the time issued and plain text of the time issued. if user_id is None: user_id = cls._USER_ID_DEFAULT # Round time to seconds. issued_on_str = str(int(issued_on)) digester = hmac.new( key=CSRF_SECRET.value.encode('utf-8'), digestmod='md5' ) digester.update(user_id.encode('utf-8')) digester.update(b':') digester.update(issued_on_str.encode('utf-8')) digest = digester.digest() # The b64encode returns bytes, so we first need to decode the returned # bytes to string. token = '%s/%s' % ( issued_on_str, base64.urlsafe_b64encode(digest).decode('utf-8')) return token
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 is_csrf_token_valid(cls, user_id: Optional[str], token: str) -> bool: """Validates a given CSRF token. Args: user_id: str|None. The user_id to validate the CSRF token against. token: str. The CSRF token to validate. Returns: bool. Whether the given CSRF token is valid. """ try: parts = token.split('/') if len(parts) != 2: return False issued_on = int(parts[0]) age = cls._get_current_time() - issued_on if age > cls._CSRF_TOKEN_AGE_SECS: return False authentic_token = cls._create_token(user_id, issued_on) if authentic_token == token: return True return False except Exception: return False
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_create_and_validate_token(self) -> None: uid = 'user_id' token = base.CsrfTokenManager.create_csrf_token(uid) self.assertTrue(base.CsrfTokenManager.is_csrf_token_valid( uid, token)) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid('bad_user', token)) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid(uid, 'new_token')) self.assertFalse( base.CsrfTokenManager.is_csrf_token_valid(uid, 'new/token'))
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 _secure_path(path_tuple): if _has_insecure_pathelement(path_tuple): # belt-and-suspenders security; this should never be true # unless someone screws up the traversal_path code # (request.subpath is computed via traversal_path too) return None if any([_contains_slash(item) for item in path_tuple]): return None encoded = '/'.join(path_tuple) # will be unicode return encoded
0
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
vulnerable
def _contains_slash(item): for sep in _seps: if sep in item: return True
0
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
vulnerable
def get_all_progress(self, recency=_progress_period_secs * 2): """ Get progress information for all ongoing operations :param recency: (int) seconds back :return list of progress codes """ query = """ SELECT code, array_agg(state) FROM web_progress WHERE create_date > timezone('utc', now()) - INTERVAL '{recency} SECOND' AND recur_depth = 0 {user_id} GROUP BY code """.format( recency=recency or 0, user_id=not self.is_progress_admin() and "AND create_uid = {user_id}" .format( user_id=self.env.user.id, ) or '') # superuser has right to see (and cancel) progress of everybody self.env.cr.execute(query) result = self.env.cr.fetchall() ret = [{ 'code': r[0], } for r in result if r[0] and 'cancel' not in r[1] and 'done' not in r[1]] return ret
0
Python
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The product constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
vulnerable
def handle_one_response(self): """ Invoke the application to produce one response. This is called by :meth:`handle_one_request` after all the state for the request has been established. It is responsible for error handling. """ self.time_start = time.time() self.status = None self.headers_sent = False self.result = None self.response_use_chunked = False self.connection_upgraded = False self.response_length = 0 try: try: self.run_application() finally: try: self.wsgi_input._discard() except socket.error: # Don't let exceptions during discarding # input override any exception that may have been # raised by the application, such as our own _InvalidClientInput. # In the general case, these aren't even worth logging (see the comment # just below) pass except _InvalidClientInput: self._send_error_response_if_possible(400) except socket.error as ex: if ex.args[0] in self.ignored_socket_errors: # See description of self.ignored_socket_errors. self.close_connection = True else: self.handle_error(*sys.exc_info()) except: # pylint:disable=bare-except self.handle_error(*sys.exc_info()) finally: self.time_finish = time.time() self.log_request()
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _handle_client_error(self, ex): # Called for invalid client input # Returns the appropriate error response. if not isinstance(ex, ValueError): # XXX: Why not self._log_error to send it through the loop's # handle_error method? traceback.print_exc() if isinstance(ex, _InvalidClientRequest): # No formatting needed, that's already been handled. In fact, because the # formatted message contains user input, it might have a % in it, and attempting # to format that with no arguments would be an error. self.log_error(ex.formatted_message) else: self.log_error('Invalid request: %s', str(ex) or ex.__class__.__name__) return ('400', _BAD_REQUEST_RESPONSE)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _chunked_read(self, length=None, use_readline=False): # pylint:disable=too-many-branches rfile = self.rfile self._send_100_continue() if length == 0: return b"" if use_readline: reader = self.rfile.readline else: reader = self.rfile.read response = [] while self.chunk_length != 0: maxreadlen = self.chunk_length - self.position if length is not None and length < maxreadlen: maxreadlen = length if maxreadlen > 0: data = reader(maxreadlen) if not data: self.chunk_length = 0 self._chunked_input_error = True raise IOError("unexpected end of file while parsing chunked data") datalen = len(data) response.append(data) self.position += datalen if self.chunk_length == self.position: rfile.readline() if length is not None: length -= datalen if length == 0: break if use_readline and data[-1] == b"\n"[0]: break else: # We're at the beginning of a chunk, so we need to # determine the next size to read self.chunk_length = self.__read_chunk_length(rfile) self.position = 0 if self.chunk_length == 0: # Last chunk. Terminates with a CRLF. rfile.readline() return b''.join(response)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def __new__(cls, classname, bases, classDict): # pylint and pep8 fight over what this should be called (mcs or cls). # pylint gets it right, but we cant scope disable pep8, so we go with # its convention. # pylint: disable=bad-mcs-classmethod-argument timeout = classDict.get('__timeout__', 'NONE') if timeout == 'NONE': timeout = getattr(bases[0], '__timeout__', None) if sysinfo.RUN_LEAKCHECKS and timeout is not None: timeout *= 6 check_totalrefcount = _get_class_attr(classDict, bases, 'check_totalrefcount', True) error_fatal = _get_class_attr(classDict, bases, 'error_fatal', True) uses_handle_error = _get_class_attr(classDict, bases, 'uses_handle_error', True) # Python 3: must copy, we mutate the classDict. Interestingly enough, # it doesn't actually error out, but under 3.6 we wind up wrapping # and re-wrapping the same items over and over and over. for key, value in list(classDict.items()): if key.startswith('test') and callable(value): classDict.pop(key) # XXX: When did we stop doing this? #value = wrap_switch_count_check(value) value = _wrap_timeout(timeout, value) error_fatal = getattr(value, 'error_fatal', error_fatal) if error_fatal: value = errorhandler.wrap_error_fatal(value) if uses_handle_error: value = errorhandler.wrap_restore_handle_error(value) if check_totalrefcount and sysinfo.RUN_LEAKCHECKS: value = leakcheck.wrap_refcount(value) classDict[key] = value return type.__new__(cls, classname, bases, classDict)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
async def login(cls, username: str, password: str) -> t.Optional[int]: """ Make sure the user exists and the password is valid. If so, the ``last_login`` value is updated in the database. :returns: The id of the user if a match is found, otherwise ``None``. """ if len(username) > cls.username.length: logger.warning("Excessively long username provided.") return None if len(password) > cls._max_password_length: logger.warning("Excessively long password provided.") return None response = ( await cls.select(cls._meta.primary_key, cls.password) .where(cls.username == username) .first() .run() ) if not response: # No match found return None stored_password = response["password"] algorithm, iterations_, salt, hashed = cls.split_stored_password( stored_password ) iterations = int(iterations_) if cls.hash_password(password, salt, iterations) == stored_password: # If the password was hashed in an earlier Piccolo version, update # it so it's hashed with the currently recommended number of # iterations: if iterations != cls._pbkdf2_iteration_count: await cls.update_password(username, password) await cls.update({cls.last_login: datetime.datetime.now()}).where( cls.username == username ) return response["id"] else: return None
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 send_mail_async(*args, **kwargs): """ Using celery to send email async You can use it as django send_mail function Example: send_mail_sync.delay(subject, message, from_mail, recipient_list, fail_silently=False, html_message=None) Also, you can ignore the from_mail, unlike django send_mail, from_email is not a required args: Example: send_mail_sync.delay(subject, message, recipient_list, fail_silently=False, html_message=None) """ if len(args) == 3: args = list(args) args[0] = (settings.EMAIL_SUBJECT_PREFIX or '') + args[0] from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER args.insert(2, from_email) args[3] = [mail for mail in args[3] if mail != '[email protected]'] args = tuple(args) try: return send_mail(*args, **kwargs) except Exception as e: logger.error("Sending mail error: {}".format(e))
0
Python
CWE-640
Weak Password Recovery Mechanism for Forgotten Password
The product contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.
https://cwe.mitre.org/data/definitions/640.html
vulnerable
def send_mail_attachment_async(subject, message, recipient_list, attachment_list=None): if attachment_list is None: attachment_list = [] from_email = settings.EMAIL_FROM or settings.EMAIL_HOST_USER subject = (settings.EMAIL_SUBJECT_PREFIX or '') + subject recipient_list = [mail for mail in recipient_list if mail != '[email protected]'] email = EmailMultiAlternatives( subject=subject, body=message, from_email=from_email, to=recipient_list ) for attachment in attachment_list: email.attach_file(attachment) os.remove(attachment) try: return email.send() except Exception as e: logger.error("Sending mail attachment error: {}".format(e))
0
Python
CWE-640
Weak Password Recovery Mechanism for Forgotten Password
The product contains a mechanism for users to recover or change their passwords without knowing the original password, but the mechanism is weak.
https://cwe.mitre.org/data/definitions/640.html
vulnerable
def test_retry_set_remove_headers_on_redirect(self) -> None: retry = Retry(remove_headers_on_redirect=["X-API-Secret"]) assert list(retry.remove_headers_on_redirect) == ["x-api-secret"]
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_retry_default_remove_headers_on_redirect(self) -> None: retry = Retry() assert list(retry.remove_headers_on_redirect) == ["authorization"]
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_redirect_cross_host_set_removed_headers(self) -> None: with PoolManager() as http: r = http.request( "GET", f"{self.base_url}/redirect", fields={"target": f"{self.base_url_alt}/headers"}, headers={"X-API-Secret": "foo", "Authorization": "bar"}, retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), ) assert r.status == 200 data = r.json() assert "X-API-Secret" not in data assert data["Authorization"] == "bar" headers = {"x-api-secret": "foo", "authorization": "bar"} r = http.request( "GET", f"{self.base_url}/redirect", fields={"target": f"{self.base_url_alt}/headers"}, headers=headers, retries=Retry(remove_headers_on_redirect=["X-API-Secret"]), ) assert r.status == 200 data = r.json() assert "x-api-secret" not in data assert "X-API-Secret" not in data assert data["Authorization"] == "bar" # Ensure the header argument itself is not modified in-place. assert headers == {"x-api-secret": "foo", "authorization": "bar"}
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_redirect_cross_host_no_remove_headers(self) -> None: with PoolManager() as http: r = http.request( "GET", f"{self.base_url}/redirect", fields={"target": f"{self.base_url_alt}/headers"}, headers={"Authorization": "foo"}, retries=Retry(remove_headers_on_redirect=[]), ) assert r.status == 200 data = r.json() assert data["Authorization"] == "foo"
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_redirect_cross_host_remove_headers(self) -> None: with PoolManager() as http: r = http.request( "GET", f"{self.base_url}/redirect", fields={"target": f"{self.base_url_alt}/headers"}, headers={"Authorization": "foo"}, ) assert r.status == 200 data = r.json() assert "Authorization" not in data r = http.request( "GET", f"{self.base_url}/redirect", fields={"target": f"{self.base_url_alt}/headers"}, headers={"authorization": "foo"}, ) assert r.status == 200 data = r.json() assert "authorization" not in data assert "Authorization" not in data
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_basic_metric_success(self): self.client.get("/hello/756") expected_duration_attributes = { "http.method": "GET", "http.host": "localhost", "http.scheme": "http", "http.flavor": "1.1", "http.server_name": "localhost", "net.host.port": 80, "http.status_code": 200, } expected_requests_count_attributes = { "http.method": "GET", "http.host": "localhost", "http.scheme": "http", "http.flavor": "1.1", "http.server_name": "localhost", } metrics_list = self.memory_metrics_reader.get_metrics_data() for resource_metric in metrics_list.resource_metrics: for scope_metrics in resource_metric.scope_metrics: for metric in scope_metrics.metrics: for point in list(metric.data.data_points): if isinstance(point, HistogramDataPoint): self.assertDictEqual( expected_duration_attributes, dict(point.attributes), ) self.assertEqual(point.count, 1) elif isinstance(point, NumberDataPoint): self.assertDictEqual( expected_requests_count_attributes, dict(point.attributes), ) self.assertEqual(point.value, 0)
0
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
vulnerable
def get_default_span_name(environ): """ Default span name is the HTTP method and URL path, or just the method. https://github.com/open-telemetry/opentelemetry-specification/pull/3165 https://opentelemetry.io/docs/reference/specification/trace/semantic_conventions/http/#name Args: environ: The WSGI environ object. Returns: The span name. """ method = environ.get("REQUEST_METHOD", "").strip() path = environ.get("PATH_INFO", "").strip() if method and path: return f"{method} {path}" return method
0
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
vulnerable
def collect_request_attributes(environ): """Collects HTTP request attributes from the PEP3333-conforming WSGI environ and returns a dictionary to be used as span creation attributes. """ result = { SpanAttributes.HTTP_METHOD: environ.get("REQUEST_METHOD"), SpanAttributes.HTTP_SERVER_NAME: environ.get("SERVER_NAME"), SpanAttributes.HTTP_SCHEME: environ.get("wsgi.url_scheme"), } host_port = environ.get("SERVER_PORT") if host_port is not None and not host_port == "": result.update({SpanAttributes.NET_HOST_PORT: int(host_port)}) setifnotnone(result, SpanAttributes.HTTP_HOST, environ.get("HTTP_HOST")) target = environ.get("RAW_URI") if target is None: # Note: `"" or None is None` target = environ.get("REQUEST_URI") if target is not None: result[SpanAttributes.HTTP_TARGET] = target else: result[SpanAttributes.HTTP_URL] = remove_url_credentials( wsgiref_util.request_uri(environ) ) remote_addr = environ.get("REMOTE_ADDR") if remote_addr: result[SpanAttributes.NET_PEER_IP] = remote_addr remote_host = environ.get("REMOTE_HOST") if remote_host and remote_host != remote_addr: result[SpanAttributes.NET_PEER_NAME] = remote_host user_agent = environ.get("HTTP_USER_AGENT") if user_agent is not None and len(user_agent) > 0: result[SpanAttributes.HTTP_USER_AGENT] = user_agent setifnotnone( result, SpanAttributes.NET_PEER_PORT, environ.get("REMOTE_PORT") ) flavor = environ.get("SERVER_PROTOCOL", "") if flavor.upper().startswith(_HTTP_VERSION_PREFIX): flavor = flavor[len(_HTTP_VERSION_PREFIX) :] if flavor: result[SpanAttributes.HTTP_FLAVOR] = flavor return result
0
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
vulnerable
def time_dataframe(): try: from pandas._testing import makeTimeDataFrame return makeTimeDataFrame(), None except ImportError: from pandas.util.testing import makeTimeDataFrame return makeTimeDataFrame(), None
0
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
vulnerable
def _clone( self, src: DictionaryObject, pdf_dest: PdfWriterProtocol, force_duplicate: bool, ignore_fields: Optional[Sequence[Union[str, int]]], ) -> None: """ Update the object from src. Args: src: pdf_dest: force_duplicate: ignore_fields: """ self._data = cast("StreamObject", src)._data try: decoded_self = cast("StreamObject", src).decoded_self if decoded_self is None: self.decoded_self = None else: self.decoded_self = cast( "DecodedStreamObject", decoded_self.clone(pdf_dest, force_duplicate, ignore_fields), ) except Exception: pass super()._clone(src, pdf_dest, force_duplicate, ignore_fields)
0
Python
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
def clone( self, pdf_dest: PdfWriterProtocol, force_duplicate: bool = False, ignore_fields: Optional[Sequence[Union[str, int]]] = (), ) -> "DictionaryObject": """Clone object into pdf_dest.""" try: if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore return self except Exception: pass d__ = cast( "DictionaryObject", self._reference_clone(self.__class__(), pdf_dest, force_duplicate), ) if ignore_fields is None: ignore_fields = [] if len(d__.keys()) == 0: d__._clone(self, pdf_dest, force_duplicate, ignore_fields) return d__
0
Python
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
def clone( self, pdf_dest: Any, force_duplicate: bool = False, ignore_fields: Optional[Sequence[Union[str, int]]] = (), ) -> "ContentStream": """ Clone object into pdf_dest. Args: pdf_dest: force_duplicate: ignore_fields: Returns: The cloned ContentStream """ try: if self.indirect_reference.pdf == pdf_dest and not force_duplicate: # type: ignore return self except Exception: pass d__ = cast( "ContentStream", self._reference_clone( self.__class__(None, None), pdf_dest, force_duplicate ), ) if ignore_fields is None: ignore_fields = [] d__._clone(self, pdf_dest, force_duplicate, ignore_fields) return d__
0
Python
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The product contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
def test_slack_webhook(request): """Test webhook.""" try: body = json.loads(request.body) except (TypeError, json.decoder.JSONDecodeError): return JsonResponse({"error": "Cannot parse request body"}, status=400) webhook = body.get("webhook") if not webhook: return JsonResponse({"error": "no webhook URL"}) message = {"text": "_Greetings_ from PostHog!"} try: if is_cloud(): # Protect against SSRF raise_if_user_provided_url_unsafe(webhook) response = requests.post(webhook, verify=False, json=message) if response.ok: return JsonResponse({"success": True}) else: return JsonResponse({"error": response.text}) except: return JsonResponse({"error": "invalid webhook URL"})
0
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
vulnerable
def main() -> None: try: run(sys.argv) except KeyboardInterrupt: pass except (OSError, TypeError, ValueError) as e: print(f"Error: {e}", file=sys.stderr) # noqa: T201 sys.exit(1)
0
Python
CWE-674
Uncontrolled Recursion
The product does not properly control the amount of recursion that takes place, consuming excessive resources, such as allocated memory or the program stack.
https://cwe.mitre.org/data/definitions/674.html
vulnerable
def __init__(self, width): self._width = width pa.PyExtensionType.__init__(self, pa.binary(width))
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def check_export_import_schema(schema_factory): c_schema = ffi.new("struct ArrowSchema*") ptr_schema = int(ffi.cast("uintptr_t", c_schema)) gc.collect() # Make sure no Arrow data dangles in a ref cycle old_allocated = pa.total_allocated_bytes() schema_factory()._export_to_c(ptr_schema) assert pa.total_allocated_bytes() > old_allocated # Delete and recreate C++ object from exported pointer schema_new = pa.Schema._import_from_c(ptr_schema) assert schema_new == schema_factory() assert pa.total_allocated_bytes() == old_allocated del schema_new assert pa.total_allocated_bytes() == old_allocated # Now released with assert_schema_released: pa.Schema._import_from_c(ptr_schema) # Not a struct type pa.int32()._export_to_c(ptr_schema) with pytest.raises(ValueError, match="ArrowSchema describes non-struct type"): pa.Schema._import_from_c(ptr_schema) # Now released with assert_schema_released: pa.Schema._import_from_c(ptr_schema)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_export_import_batch_with_extension(): check_export_import_batch(make_extension_batch)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_export_import_schema_with_extension(): check_export_import_schema(make_extension_schema)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __reduce__(self): return ParamExtType, (self.width,)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __init__(self, width): self._width = width pa.PyExtensionType.__init__(self, pa.binary(width))
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_parquet_extension_with_nested_storage(tmpdir): # Parquet support for extension types with nested storage type import pyarrow.parquet as pq struct_array = pa.StructArray.from_arrays( [pa.array([0, 1], type="int64"), pa.array([4, 5], type="int64")], names=["left", "right"]) list_array = pa.array([[1, 2, 3], [4, 5]], type=pa.list_(pa.int32())) mystruct_array = pa.ExtensionArray.from_storage(MyStructType(), struct_array) mylist_array = pa.ExtensionArray.from_storage( MyListType(list_array.type), list_array) orig_table = pa.table({'structs': mystruct_array, 'lists': mylist_array}) filename = tmpdir / 'nested_extension_storage.parquet' pq.write_table(orig_table, filename) table = pq.read_table(filename) assert table.column('structs').type == mystruct_array.type assert table.column('lists').type == mylist_array.type assert table == orig_table with pytest.raises(pa.ArrowInvalid, match='without all of its fields'): pq.ParquetFile(filename).read(columns=['structs.left'])
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __init__(self): pa.PyExtensionType.__init__(self, pa.int8())
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_parquet_extension_nested_in_extension(tmpdir): # Parquet support for extension<list<extension>> import pyarrow.parquet as pq inner_ext_type = IntegerType() inner_storage = pa.array([4, 5, 6, 7], type=pa.int64()) inner_ext_array = pa.ExtensionArray.from_storage(inner_ext_type, inner_storage) list_array = pa.ListArray.from_arrays([0, 1, None, 3], inner_ext_array) mylist_array = pa.ExtensionArray.from_storage( MyListType(list_array.type), list_array) orig_table = pa.table({'lists': mylist_array}) filename = tmpdir / 'ext_of_list_of_ext.parquet' pq.write_table(orig_table, filename) table = pq.read_table(filename) assert table.column(0).type == mylist_array.type assert table == orig_table
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_uuid_type_pickle(pickle_module): for proto in range(0, pickle_module.HIGHEST_PROTOCOL + 1): ty = UuidType() ser = pickle_module.dumps(ty, protocol=proto) del ty ty = pickle_module.loads(ser) wr = weakref.ref(ty) assert ty.extension_name == "arrow.py_extension_type" del ty assert wr() is None
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_ext_type_basics(): ty = UuidType() assert ty.extension_name == "arrow.py_extension_type"
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_ipc(): batch = example_batch() buf = ipc_write_batch(batch) del batch batch = ipc_read_batch(buf) arr = check_example_batch(batch) assert arr.type == ParamExtType(3)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __init__(self, storage_type, annotation): self.annotation = annotation super().__init__(storage_type)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_parquet_nested_extension(tmpdir): # Parquet support for extension types nested in struct or list import pyarrow.parquet as pq ext_type = IntegerType() storage = pa.array([4, 5, 6, 7], type=pa.int64()) ext_array = pa.ExtensionArray.from_storage(ext_type, storage) # Struct of extensions struct_array = pa.StructArray.from_arrays( [storage, ext_array], names=['ints', 'exts']) orig_table = pa.table({'structs': struct_array}) filename = tmpdir / 'struct_of_ext.parquet' pq.write_table(orig_table, filename) table = pq.read_table(filename) assert table.column(0).type == struct_array.type assert table == orig_table # List of extensions list_array = pa.ListArray.from_arrays([0, 1, None, 3], ext_array) orig_table = pa.table({'lists': list_array}) filename = tmpdir / 'list_of_ext.parquet' pq.write_table(orig_table, filename) table = pq.read_table(filename) assert table.column(0).type == list_array.type assert table == orig_table # Large list of extensions list_array = pa.LargeListArray.from_arrays([0, 1, None, 3], ext_array) orig_table = pa.table({'lists': list_array}) filename = tmpdir / 'list_of_ext.parquet' pq.write_table(orig_table, filename) table = pq.read_table(filename) assert table.column(0).type == list_array.type assert table == orig_table
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_ext_type_str(): ty = IntegerType() expected = "extension<arrow.py_extension_type<IntegerType>>" assert str(ty) == expected assert pa.DataType.__str__(ty) == expected
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_ipc_unknown_type(): batch = example_batch() buf = ipc_write_batch(batch) del batch orig_type = ParamExtType try: # Simulate the original Python type being unavailable. # Deserialization should not fail but return a placeholder type. del globals()['ParamExtType'] batch = ipc_read_batch(buf) arr = check_example_batch(batch) assert isinstance(arr.type, pa.UnknownExtensionType) # Can be serialized again buf2 = ipc_write_batch(batch) del batch, arr batch = ipc_read_batch(buf2) arr = check_example_batch(batch) assert isinstance(arr.type, pa.UnknownExtensionType) finally: globals()['ParamExtType'] = orig_type # Deserialize again with the type restored batch = ipc_read_batch(buf2) arr = check_example_batch(batch) assert arr.type == ParamExtType(3)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def check_example_batch(batch): arr = batch.column(0) assert isinstance(arr, pa.ExtensionArray) assert arr.type.storage_type == pa.binary(3) assert arr.storage.to_pylist() == [b"foo", b"bar"] return arr
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __reduce__(self): return TinyIntType, ()
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __init__(self, storage_type): pa.PyExtensionType.__init__(self, storage_type)
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def test_cast_between_extension_types(): array = pa.array([1, 2, 3], pa.int8()) tiny_int_arr = array.cast(TinyIntType()) assert tiny_int_arr.type == TinyIntType() # Casting between extension types w/ different storage types not okay. msg = ("Casting from 'extension<arrow.py_extension_type<TinyIntType>>' " "to different extension type " "'extension<arrow.py_extension_type<IntegerType>>' not permitted. " "One can first cast to the storage type, " "then to the extension type." ) with pytest.raises(TypeError, match=msg): tiny_int_arr.cast(IntegerType()) tiny_int_arr.cast(pa.int64()).cast(IntegerType()) # Between the same extension types is okay array = pa.array([b'1' * 16, b'2' * 16], pa.binary(16)).cast(UuidType()) out = array.cast(UuidType()) assert out.type == UuidType() # Will still fail casting between extensions who share storage type, # can only cast between exactly the same extension types. with pytest.raises(TypeError, match='Casting from *'): array.cast(UuidType2())
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __init__(self): pa.PyExtensionType.__init__(self, pa.int64())
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def __reduce__(self): return DummyExtensionType, ()
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def check_soa_record(target: str) -> bool: """Checks the presence of a SOA record for the Email Systems Testing.""" result = False try: answers = dns.resolver.query(target, "SOA") result = 0 != len(answers) except Exception: result = False return result
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 full_domain_validator(hostname): """ Fully validates a domain name as compilant with the standard rules: - Composed of series of labels concatenated with dots, as are all domain names. - Each label must be between 1 and 63 characters long. - The entire hostname (including the delimiting dots) has a maximum of 255 characters. - Only characters 'a' through 'z' (in a case-insensitive manner), the digits '0' through '9'. - Labels can't start or end with a hyphen. """ HOSTNAME_LABEL_PATTERN = re.compile(r"(?!-)[A-Z\d-]+(?<!-)$", re.IGNORECASE) if not hostname: return if len(hostname) > 255: raise Exception( "The domain name cannot be composed of more than 255 characters." ) if hostname[-1:] == ".": hostname = hostname[:-1] # strip exactly one dot from the right, if present for label in hostname.split("."): if len(label) > 63: raise Exception( "The label '%(label)s' is too long (maximum is 63 characters)." % {"label": label} ) if not HOSTNAME_LABEL_PATTERN.match(label): raise Exception(f"Unallowed characters in label '{label}'.") return hostname
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 post_process_findings(banner: Optional[Banner], algs: Algorithms) -> List[str]: '''Perform post-processing on scan results before reporting them to the user. Returns a list of algorithms that should not be recommended''' algorithm_recommendation_suppress_list = [] # If the server is OpenSSH, and the diffie-hellman-group-exchange-sha256 key exchange was found with modulus size 2048, add a note regarding the bug that causes the server to support 2048-bit moduli no matter the configuration. if (algs.ssh2kex is not None and 'diffie-hellman-group-exchange-sha256' in algs.ssh2kex.kex_algorithms and 'diffie-hellman-group-exchange-sha256' in algs.ssh2kex.dh_modulus_sizes() and algs.ssh2kex.dh_modulus_sizes()['diffie-hellman-group-exchange-sha256'] == 2048) and (banner is not None and banner.software is not None and banner.software.find('OpenSSH') != -1): # Ensure a list for notes exists. db = SSH2_KexDB.get_db() while len(db['kex']['diffie-hellman-group-exchange-sha256']) < 4: db['kex']['diffie-hellman-group-exchange-sha256'].append([]) db['kex']['diffie-hellman-group-exchange-sha256'][3].append("A bug in OpenSSH causes it to fall back to a 2048-bit modulus regardless of server configuration (https://bugzilla.mindrot.org/show_bug.cgi?id=2793)") # Ensure that this algorithm doesn't appear in the recommendations section since the user cannot control this OpenSSH bug. algorithm_recommendation_suppress_list.append('diffie-hellman-group-exchange-sha256') return algorithm_recommendation_suppress_list
0
Python
CWE-354
Improper Validation of Integrity Check Value
The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
vulnerable
def test_ssh2_server_simple(self, output_spy, virtual_socket): vsocket = virtual_socket w = self.wbuf() w.write_byte(self.protocol.MSG_KEXINIT) w.write(self._kex_payload()) vsocket.rdata.append(b'SSH-2.0-OpenSSH_7.3 ssh-audit-test\r\n') vsocket.rdata.append(self._create_ssh2_packet(w.write_flush())) output_spy.begin() out = self.OutputBuffer() self.audit(out, self._conf()) out.write() lines = output_spy.flush() assert len(lines) == 70
0
Python
CWE-354
Improper Validation of Integrity Check Value
The product does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
vulnerable
def process_file(): content = request.json target_filename = content.get('filename') print(f"Processing {target_filename}") success, reason = process_single(WATCH_DIRECTORY, target_filename) return json.dumps({'filename': target_filename, 'success': success, 'reason': reason})
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 _load_pkcs7_certificates(self, p7) -> typing.List[x509.Certificate]: nid = self._lib.OBJ_obj2nid(p7.type) self.openssl_assert(nid != self._lib.NID_undef) if nid != self._lib.NID_pkcs7_signed: raise UnsupportedAlgorithm( "Only basic signed structures are currently supported. NID" " for this data was {}".format(nid), _Reasons.UNSUPPORTED_SERIALIZATION, ) sk_x509 = p7.d.sign.cert num = self._lib.sk_X509_num(sk_x509) certs = [] for i in range(num): x509 = self._lib.sk_X509_value(sk_x509, i) self.openssl_assert(x509 != self._ffi.NULL) cert = self._ossl2cert(x509) certs.append(cert) return certs
0
Python
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
vulnerable
def handler500(request, template_name="dpaste/500.html"): context = {} context.update(config.extra_template_context) response = render(request, template_name, context, status=500) add_never_cache_headers(response) return response
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def loginForm(request, next=''): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = Login_Form(request.POST) # check whether it's valid: if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) if 'next' in request.POST: return HttpResponseRedirect(request.POST.get('next')) else: return HttpResponseRedirect(reverse('CalendarinhoApp:Dashboard')) else: messages.error(request, "Invalid login details given") form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form}) # if a GET (or any other method) we'll create a blank form else: form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form})
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def loginForm(request, next=''): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = Login_Form(request.POST) # check whether it's valid: if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) next_url = request.POST.get('next', '') if next_url and next_url.startswith('/'): return HttpResponseRedirect(next_url) else: return HttpResponseRedirect(reverse('CalendarinhoApp:Dashboard')) else: messages.error(request, "Invalid login details given") form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form}) # if a GET (or any other method) we'll create a blank form else: form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form})
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def loginForm(request, next=''): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = Login_Form(request.POST) # check whether it's valid: if form.is_valid(): username = request.POST.get('username') password = request.POST.get('password') user = user = authenticate(username=username, password=password) if user and user.is_active: login(request, user) next_url = request.POST.get('next', '') if (next_url and url_has_allowed_host_and_scheme(next_url, settings.ALLOWED_HOSTS)): print("Good People") return HttpResponseRedirect(next_url) else: print("fucking bad shit") return HttpResponseRedirect(reverse('CalendarinhoApp:Dashboard')) else: messages.error(request, "Invalid login details given") form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form}) # if a GET (or any other method) we'll create a blank form else: form = Login_Form() return render(request, 'CalendarinhoApp/login.html', {'form': form})
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def LoadSettingsFile(filename=SETTINGS_FILE): """Loads settings file in yaml format given file name. :param filename: path for settings file. 'settings.yaml' by default. :type filename: str. :raises: SettingsError """ try: with open(filename) as stream: data = load(stream, Loader=Loader) except (YAMLError, OSError) as e: raise SettingsError(e) return data
0
Python
CWE-502
Deserialization of Untrusted Data
The product deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
async def get(self, request: web.Request) -> web.Response: """Return a list of persons if request comes from a local IP.""" try: remote_address = ip_address(request.remote) # type: ignore[arg-type] except ValueError: return self.json_message( message="Invalid remote IP", status_code=HTTPStatus.BAD_REQUEST, message_code="invalid_remote_ip", ) hass: HomeAssistant = request.app["hass"] if is_cloud_connection(hass) or not is_local(remote_address): return self.json_message( message="Not local", status_code=HTTPStatus.BAD_REQUEST, message_code="not_local", ) yaml, storage, _ = hass.data[DOMAIN] persons = [*yaml.async_items(), *storage.async_items()] return self.json( { person[ATTR_USER_ID]: { ATTR_NAME: person[ATTR_NAME], CONF_PICTURE: person.get(CONF_PICTURE), } for person in persons if person.get(ATTR_USER_ID) } )
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
async def _test_fetch_auth_providers_home_assistant( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, ip: str, additional_expected_fn: Callable[[User], dict[str, Any]], ) -> None: """Test fetching auth providers for homeassistant auth provider.""" client = await async_setup_auth( hass, aiohttp_client, [{"type": "homeassistant"}], custom_ip=ip ) provider = hass.auth.auth_providers[0] credentials = await provider.async_get_or_create_credentials({"username": "hello"}) user = await hass.auth.async_get_or_create_user(credentials) expected = { "name": "Home Assistant Local", "type": "homeassistant", "id": None, **additional_expected_fn(user), } resp = await client.get("/auth/providers") assert resp.status == HTTPStatus.OK assert await resp.json() == [expected]
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
async def test_fetch_auth_providers_home_assistant_person_loaded( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, ip: str, is_local: bool, ) -> None: """Test fetching auth providers for homeassistant auth provider, where person integration is loaded.""" domain = "person" config = {domain: {"id": "1234", "name": "test person"}} assert await async_setup_component(hass, domain, config) await _test_fetch_auth_providers_home_assistant( hass, aiohttp_client, ip, lambda user: {"users": {user.id: user.name}} if is_local else {}, )
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable