code
stringlengths
12
2.05k
label
int64
0
1
programming_language
stringclasses
9 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
103
description
stringlengths
36
1.23k
url
stringlengths
36
48
label_name
stringclasses
2 values
def test_basic_functionality(self): self.create_test_files() self.attic('init', self.repository_location) self.attic('create', self.repository_location + '::test', 'input') self.attic('create', self.repository_location + '::test.2', 'input') with changedir('output'): ...
0
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
vulnerable
def _create(self): url = recurly.base_uri() + self.collection_path return self.post(url)
1
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
safe
def get_misp_connection(config=None, parameters=None): global misp_connection if misp_connection: return misp_connection if not config: raise MaltegoException("ERROR: MISP connection not yet established, and config not provided as parameter.") misp_verify = True misp_debug = False ...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _auth_from_challenge(self, host, request_uri, headers, response, content): """A generator that creates Authorization objects that can be applied to requests. """ challenges = _parse_www_authenticate(response, "www-authenticate") for cred in self.credentials.iter(host):...
0
Python
CWE-400
Uncontrolled Resource Consumption
The software 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 test_dmcrypt_with_default_size(self, conf_ceph_stub): conf_ceph_stub('[global]\nfsid=asdf-lkjh') result = encryption.create_dmcrypt_key() assert len(result) == 172
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest], 2) return json.dumps({'status' : 'OK', 'vId' : vrequest});
1
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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
safe
def get_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (list, t...
1
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
safe
def test_http10_list(self): body = string.ascii_letters to_send = ( "GET /list HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n\n" % len(body) ) to_send += body to_send = tobytes(to_send) self.connect() self.sock...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def test_send_empty_body(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK",...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
async def message(self, ctx, *, message: str): """Set the message that is shown at the start of each ticket channel.\n\nUse ``{user.mention}`` to mention the person who created the ticket.""" try: message.format(user=ctx.author) await self.config.guild(ctx.guild).message.set(...
0
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software 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_redundantdef(self): with self.assertRaisesRegex(SyntaxError, "^Cannot have two type comments on def"): tree = self.parse(redundantdef)
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def _testSparseDenseInvalidInputs(self, a_indices, a_values, a_shape, b, expected_error=""):
1
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
safe
def __new__(cls, sourceName: str): """Dispatches to the right subclass.""" if cls != InputSource: # Only take control of calls to InputSource(...) itself. return super().__new__(cls) if sourceName == "-": return StdinInputSource(sourceName) if sou...
0
Python
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
def test_modify_access_allow(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_user.email, 'rolename': 'staff', 'action': 'allow', })...
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 fetch_file(self, in_path, out_path): ''' fetch a file from jail to local ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail) p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None) with open(out_path, 'wb+') as out_file: try: ...
1
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
safe
def test_uses_existing_file_and_ignores_xdg(self): with WindowsSafeTempDir() as d: default_db_file_location = os.path.join(self.home, '.b2_account_info') open(default_db_file_location, 'a').close() account_info = self._make_sqlite_account_info( env={ ...
0
Python
CWE-367
Time-of-check Time-of-use (TOCTOU) Race Condition
The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.
https://cwe.mitre.org/data/definitions/367.html
vulnerable
def test_list_entrance_exam_instructor_tasks_all_student(self): """ Test list task history for entrance exam AND all student. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) self.assertEqual(r...
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 parse_configuration_file(config_path): """ Read the config file for an experiment to get ParlAI settings. :param config_path: path to config :return: parsed configuration dictionary """ result = {} result["configs"] = {} with open(config_path) as f: cfg = ya...
0
Python
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename)
0
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
def test_update_api_key(self) -> None: user = self.example_user("hamlet") email = user.email self.login_user(user) old_api_keys = get_all_api_keys(user) # Ensure the old API keys are in the authentication cache, so # that the below logic can test whether we have a ca...
1
Python
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
safe
def parse_soap_enveloped_saml(text, body_class, header_class=None): """Parses a SOAP enveloped SAML thing and returns header parts and body :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = defusedxml.ElementTree.fromstring(text) assert...
1
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
def test_chunking_request_without_content(self): header = tobytes("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n") self.connect() self.sock.send(header) self.sock.send(b"0\r\n\r\n") fp = self.sock.makefile("rb", 0) line, headers, echo = self._read_echo(fp) ...
1
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 ...
https://cwe.mitre.org/data/definitions/444.html
safe
def CreateID(self): """Create a packet ID. All RADIUS requests have a ID which is used to identify a request. This is used to detect retries and replay attacks. This function returns a suitable random number that can be used as ID. :return: ID number :rtype: integer ...
1
Python
CWE-330
Use of Insufficiently Random Values
The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.
https://cwe.mitre.org/data/definitions/330.html
safe
def get(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: resp_headers, resp_body = connection.get_object( container=location.container, obj=location.obj, ...
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_challenge(self): rc, root, folder, object = self._makeTree() response = FauxCookieResponse() testURL = 'http://test' request = FauxRequest(RESPONSE=response, URL=testURL, ACTUAL_URL=testURL) root.REQUEST = request helper = self....
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 test_large_body(self): # 1024 characters. body = "This string has 32 characters.\r\n" * 32 s = tobytes( "GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body) ) self.connect() self.sock.send(s) fp = self.sock.makefile("rb", 0) ...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv...
1
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
def test_filename(self): with NamedTemporaryFile() as tmp: fp = memmap(tmp.name, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmp.name) fp[:] = self.data[:] self.assertEqual(abspath, fp.filename) ...
1
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
safe
def render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) hostname = args['matrix_server_name'].lower() if not is_valid_hostname(hostname): reque...
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 prop_sentences_stats(self, type, vId = None): return { 'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC", 'all_net...
1
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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
safe
def test_methodWithUnprintableASCIIRejected(self): """ Issuing a request with a method that contains unprintable ASCII characters fails with a L{ValueError}. """ for c in UNPRINTABLE_ASCII: method = b"GET%s" % (bytearray([c]),) with self.assertRaises(V...
1
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software 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
safe
def makeTrustRoot(self): # If this option is specified, use a specific root CA cert. This is useful for testing when it's not # practical to get the client cert signed by a real root CA but should never be used on a production server. caCertFilename = self.sydent.cfg.get('http', 'replication...
1
Python
CWE-770
Allocation of Resources Without Limits or Throttling
The software 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_sneaky_import_in_style(self): # Prevent "@@importimport" -> "@import" replacement. style_codes = [ "@@importimport(extstyle.css)", "@ @ import import(extstyle.css)", "@ @ importimport(extstyle.css)", "@@ import import(extstyle.css)", ...
1
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software 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
safe
def from_xml(self, content): """ Given some XML data, returns a Python dictionary of the decoded data. """ if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return self.from_etree(parse_xml(StringIO(content)).getroot())
1
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
safe
def json_dumps(value, indent=None): if isinstance(value, QuerySet): result = serialize('json', value, indent=indent) else: result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder) return mark_safe(force_text(result).translate(_safe_js_escapes))
1
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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
safe
def test_is_valid_hostname(self): """Tests that the is_valid_hostname function accepts only valid hostnames (or domain names), with optional port number. """ self.assertTrue(is_valid_hostname("example.com")) self.assertTrue(is_valid_hostname("EXAMPLE.COM")) self.asse...
1
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
safe
def test_basic_two_credentials(): # Test Basic Authentication with multiple sets of credentials http = httplib2.Http() password1 = tests.gen_password() password2 = tests.gen_password() allowed = [("joe", password1)] # exploit shared mutable list handler = tests.http_reflect_with_auth( a...
0
Python
CWE-400
Uncontrolled Resource Consumption
The software 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 test_received_multiple_chunks(self): from waitress.utilities import BadRequest buf = DummyBuffer() inst = self._makeOne(buf) data = ( b"4\r\n" b"Wiki\r\n" b"5\r\n" b"pedia\r\n" b"E\r\n" b" in\r\n" ...
1
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 ...
https://cwe.mitre.org/data/definitions/444.html
safe
def test_require_realm_admin(self): # type: () -> None """ The invite_by_admins_only realm setting works properly. """ realm = get_realm('zulip') realm.invite_by_admins_only = True realm.save() self.login("hamlet@zulip.com") email = "alice-tes...
1
Python
CWE-862
Missing Authorization
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
def manipulate(root, strblock): """ Maliciously manipulates the structure to create a crafted FIT file """ # locate /images/kernel-1 (frankly, it just expects it to be the first one) kernel_node = root[0][0] # clone it to save time filling all the properties fake_kernel = kernel_node.clone()...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def feed_author(book_id): off = request.args.get("offset") or 0 entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0, db.Books, db.Books.authors....
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 exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None): ''' run a command on the chroot ''' if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported: raise errors.AnsibleError("Internal Err...
0
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
def _create_dirs(self): if not os.path.exists(self._path): os.makedirs(self._path)
0
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issu...
https://cwe.mitre.org/data/definitions/21.html
vulnerable
def pref_set(key, value): if get_user() is None: return "Authentication required", 401 get_preferences()[key] = (None if value == 'null' else value) return Response(json.dumps({'key': key, 'success': ''})), 201
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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 insensitive_starts_with(field: Term, value: str) -> Criterion: return Upper(field).like(Upper(f"{value}%"))
0
Python
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software 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 test_modify_access_revoke_self(self): """ Test that an instructor cannot remove instructor privelages from themself. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_stud...
1
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
safe
def legacy_raw_flush(writer=None, name=None): """Legacy version of flush() that accepts a raw resource tensor for `writer`. Do not use this function in any new code. Not supported and not part of the public TF APIs. Args: writer: The `tf.summary.SummaryWriter` to flush. If None, the current default ...
1
Python
CWE-475
Undefined Behavior for Input to API
The behavior of this function is undefined unless its control parameter is set to a specific value.
https://cwe.mitre.org/data/definitions/475.html
safe
def is_leaf(cls, path): abs_path = os.path.join(FOLDER, path.replace("/", os.sep)) return os.path.isfile(abs_path) and not abs_path.endswith(".props")
0
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issu...
https://cwe.mitre.org/data/definitions/21.html
vulnerable
def resolutionBegan(resolutionInProgress: IHostResolution) -> None: recv.resolutionBegan(resolutionInProgress)
1
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
safe
def create_network(self, instance_name, instance, network_info): """Create the LXD container network on the host :param instance_name: nova instance name :param instance: nova instance object :param network_info: instance network configuration object :return:network configur...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def delete_service(self, context, service_id): self.assert_admin(context) service_ref = self.catalog_api.get_service(context, service_id) if not service_ref: raise exception.ServiceNotFound(service_id=service_id) self.catalog_api.delete_service(context, service_id)
1
Python
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
def test_security_group_ingress_quota_limit(self): self.flags(quota_security_group_rules=20) kwargs = {'project_id': self.context.project_id, 'name': 'test'} sec_group = db.security_group_create(self.context, kwargs) authz = self.cloud.authorize_security_group_ingress for i i...
1
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
def test_valid(self, args): qutebrowser._validate_untrusted_args(args)
1
Python
CWE-88
Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
The software constructs a string for a command to executed by a separate component in another control sphere, but it does not properly delimit the intended arguments, options, or switches within that command string.
https://cwe.mitre.org/data/definitions/88.html
safe
def test_modify_access_revoke_with_username(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.username, 'rolename': 'staff', 'action': ...
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(self, path, queries=(), ignore_prefix=False): return self._request('GET', path, queries, ignore_prefix=ignore_prefix)
1
Python
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
safe
def test_longargs(self): tree = self.parse(longargs) for t in tree.body: # The expected args are encoded in the function name todo = set(t.name[1:]) self.assertEqual(len(t.args.args), len(todo) - bool(t.args.vararg) - bool(t.args.kwarg...
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def get_ipcache_entry(self, client): """Build a cache of dns results.""" if client in self.ipcache: if self.ipcache[client]: return self.ipcache[client] else: raise socket.gaierror else: # need to add entry try: ...
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 test_list_course_role_members_noparams(self): """ Test missing all query parameters. """ url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url) self.assertEqual(response.status_code, 400)
1
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
safe
def _callback() -> None: has_bad_ip = False for address in addresses: # We only expect IPv4 and IPv6 addresses since only A/AAAA lookups # should go through this path. if not isinstance(address, (IPv4Address, IPv6Address)): ...
1
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
safe
def testSparseCountSparseOutputBadWeightsShape(self): indices = [[0, 0], [0, 1], [1, 0], [1, 2]] values = [1, 1, 1, 10] weights = [1, 2, 4] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): ...
1
Python
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def _stub_class(self): def fake_quota_class_get_all_by_name(context, quota_class): result = dict(class_name=quota_class) if quota_class == 'test_class': result.update( instances=5, cores=10, ram=25 * 1024, ...
1
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
def xsrf_token(self): """The XSRF-prevention token for the current user/session. To prevent cross-site request forgery, we set an '_xsrf' cookie and include the same '_xsrf' value as an argument with all POST requests. If the two do not match, we reject the form submission a...
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 visit_Num(self, node): return self._convert_num(node.n)
1
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software 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
safe
def validate(self, data): user = providers.get_provider('login').login_user(**data, context=self.context) if user is not None: data['user'] = user return data
0
Python
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
vulnerable
def prop_sentences_stats(self, type, vId = None): return { 'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC", 'a...
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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 _expand(self, key_material): output = [b""] counter = 1 while (self._algorithm.digest_size // 8) * len(output) < self._length: h = hmac.HMAC(key_material, self._algorithm, backend=self._backend) h.update(output[-1]) h.update(self._info) h....
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 test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\n" " Host: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def test_login_get(self): login_code = LoginCode.objects.create(user=self.user) response = self.client.get('/accounts/login/code/', { 'user': login_code.user.pk, 'code': login_code.code, }) self.assertEqual(response.status_code, 200) self.assertEqual...
1
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
safe
def __init__(self): self.catalog_api = Manager() self.identity_api = identity.Manager() self.policy_api = policy.Manager() self.token_api = token.Manager() super(ServiceController, self).__init__()
1
Python
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
def test_quotas_update_as_user(self): body = {'quota_set': {'instances': 50, 'cores': 50, 'ram': 51200, 'volumes': 10, 'gigabytes': 1000, 'floating_ips': 10, 'metadata_items': 128, 'injected_files': 5, ...
1
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
def _update_load_status(self, ok: bool) -> None: """Update the load status after a page finished loading. Needs to be called by subclasses to trigger a load status update, e.g. as a response to a loadFinished signal. """ if ok: if self.url().scheme() == 'https': ...
1
Python
CWE-684
Incorrect Provision of Specified Functionality
The code does not function according to its published specifications, potentially leading to incorrect usage.
https://cwe.mitre.org/data/definitions/684.html
safe
def test_filelike_longcl_http11(self): to_send = "GET /filelike_longcl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def test_project_quotas_overrides_noclass(self): self._stub_class() self._stub_project(True) result = quota.get_project_quotas(self.context, 'admin') self.assertEqual(result, dict( instances=2, cores=5, ram=12 * 1024, vo...
1
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
def _join_and_check_path_within_fs(fs, *args): '''os.path.join() with safety check for injected file paths. Join the supplied path components and make sure that the resulting path we are injecting into is within the mounted guest fs. Trying to be clever and specifying a path with '..' in it will h...
1
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software 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 software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of t...
https://cwe.mitre.org/data/definitions/22.html
safe
def _w(self, content): self.output.append(format_data(content, format_money_values=True))
0
Python
CWE-1236
Improper Neutralization of Formula Elements in a CSV File
The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.
https://cwe.mitre.org/data/definitions/1236.html
vulnerable
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None): """ Returns a new SqliteAccountInfo that has just read the data from the file. :param dict env: Override Environment variables. """ # Override HOME to ensure hermetic tests with mock.patch('os.e...
0
Python
CWE-367
Time-of-check Time-of-use (TOCTOU) Race Condition
The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.
https://cwe.mitre.org/data/definitions/367.html
vulnerable
def change_due_date(request, course_id): """ Grants a due date extension to a student for a particular unit. """ course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id)) student = require_student_from_identifier(request.POST.get('student')) unit = find_unit(course, re...
1
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
safe
def create(request, topic_id): topic = get_object_or_404( Topic.objects.for_access(request.user), pk=topic_id) form = NotificationCreationForm( user=request.user, topic=topic, data=request.POST) if form.is_valid(): form.save() else: messages.error...
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 test_auth_plugin_prompt_password_in_session(self, httpbin): self.start_session(httpbin) session_path = self.config_dir / 'test-session.json' class Plugin(AuthPlugin): auth_type = 'test-prompted' def get_auth(self, username=None, password=None): b...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_get_size_from_conf_default(self, conf_ceph_stub): conf_ceph_stub(''' [global] fsid=asdf ''') assert encryption.get_key_size_from_conf() == '512'
1
Python
NVD-CWE-noinfo
null
null
null
safe
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType: if isinstance(typ, new.BoolDefinition): return old.BaseType("bool") if isinstance(typ, new.AddressDefinition): return old.BaseType("address") if isinstance(typ, new.InterfaceDefinition): return old.InterfaceType(typ._i...
0
Python
CWE-190
Integer Overflow or Wraparound
The software 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
vulnerable
def parse_content_disposition(content_disposition, default_filename): # type: (str, str) -> str """ Parse the "filename" value from a Content-Disposition header, and return the default filename if the result is empty. """ _type, params = cgi.parse_header(content_disposition) filename = param...
1
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software 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 software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of t...
https://cwe.mitre.org/data/definitions/22.html
safe
async def on_message(self, message): if message.author.bot: return ctx = await self.bot.get_context(message) if ctx.prefix is None or not ctx.invoked_with.replace("_", "").isalpha(): return if ctx.valid and ctx.command.enabled: try: ...
0
Python
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def reset_user_api_key(user_profile: Any) -> None: old_api_key = user_profile.api_key user_profile.api_key = generate_api_key() cache_delete(user_profile_by_api_key_cache_key(old_api_key)) # Like with any API key change, we need to clear any server-side # state for sending push notifications to mob...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) result = yield self.client.get_json( "matrix://%s/_matrix/federation/v1/openid/userinfo?access_t...
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 put_file(self, in_path, out_path): ''' transfer a file from local to zone ''' out_path = self._normalize_path(out_path, self.get_zone_path()) vvv("PUT %s TO %s" % (in_path, out_path), host=self.zone) self._copy_file(in_path, out_path)
0
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
def setup_webdir_if_it_doesnt_exist(ctx): if is_web_app(ctx): webdirPath = os.path.join(ctx['BUILD_DIR'], ctx['WEBDIR']) if not os.path.exists(webdirPath): fu = FileUtil(FakeBuilder(ctx), move=True) fu.under('BUILD_DIR') fu.into('WEBDIR') fu.where_name...
1
Python
CWE-254
7PK - Security Features
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
https://cwe.mitre.org/data/definitions/254.html
safe
def render_edit_book(book_id): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exis...
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 testRaggedCountSparseOutput(self): splits = [0, 4, 7] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] output_indices, output_values, output_shape = self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output...
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def get_valid_filename(value, replace_whitespace=True, chars=128): """ Returns the given string converted to a string that can be used for a clean filename. Limits num characters to 128 max. """ if value[-1:] == u'.': value = value[:-1]+u'_' value = value.replace("/", "_").replace(":", "...
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 runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None): frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software 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 safe_markup(raw_html: str) -> jinja2.Markup: """ Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs. Args raw_html: Unsafe HTML. Returns: A Markup object ready to safely use in a Jinja template. """ return jinja2.Markup( bl...
1
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software 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
safe
async def initialize(self, bot): # temporary backwards compatibility key = await self.config.tenorkey() if not key: return await bot.set_shared_api_tokens("tenor", api_key=key) await self.config.tenorkey.clear()
0
Python
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
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 get_image(path): def get_absolute_path(path): import os script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in rel_path = path abs_file_path = os.path.join(script_dir, rel_path) return abs_file_path return send_file( get_absolute_path(f"....
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software 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 software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of t...
https://cwe.mitre.org/data/definitions/22.html
vulnerable
def test_check_password_calls_harden_runtime(self): hasher = get_hasher('default') encoded = make_password('letmein') with mock.patch.object(hasher, 'harden_runtime'), \ mock.patch.object(hasher, 'must_update', return_value=True): # Correct password supplied, no ...
1
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
safe
def test_prepare_plugin_docs_command(): rc = DocConfig() plugin_names = ['copy', 'file'] plugin_type = 'module' rc.prepare_plugin_docs_command(plugin_names, plugin_type=plugin_type, snippet=True, playbook_dir='/tmp/test') expected_command = [get_executable_path('ansible-doc'), '-s', '-t', 'module', ...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_received_headers_finished_expect_continue_false(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = False preq.headers_finished = True preq.completed = False ...
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 ...
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def make_homeserver(self, reactor, clock): self.push_attempts = [] m = Mock() def post_json_get_json(url, body): d = Deferred() self.push_attempts.append((d, url, body)) return make_deferred_yieldable(d) m.post_json_get_json = post_json_get_json...
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 test_quotas_defaults(self): uri = '/v2/fake_tenant/os-quota-sets/fake_tenant/defaults' req = fakes.HTTPRequest.blank(uri) res_dict = self.controller.defaults(req, 'fake_tenant') expected = {'quota_set': { 'id': 'fake_tenant', 'instances':...
0
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
vulnerable