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 should_run(self): if self.force: return True if not os.path.exists(self.bower_dir): return True return mtime(self.bower_dir) < mtime(pjoin(repo_root, 'bower.json'))
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 _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 and not self._has_ssl_errors: if sel...
0
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
vulnerable
def home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') ('clean_online') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] rows = db.sentences_stats('get_online') o = rows[0][0] ...
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 download_check_files(self, filelist): # only admins and allowed users may download if not cherrypy.session['admin']: uo = self.useroptions.forUser(self.getUserId()) if not uo.getOptionValue('media.may_download'): return 'not_permitted' # make sure ...
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 getHostByName(self, name, timeout=None): if name not in lookups: return fail(DNSLookupError("OH NO: unknown %s" % (name,))) return succeed(lookups[name])
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_verified_user_has_no_change_user_perm(self, verified_user): """Sanity check.""" assert not verified_user.has_perm("user.change_user")
1
Python
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
safe
def read_http(fp): # pragma: no cover try: response_line = fp.readline() except socket.error as exc: fp.close() # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054): raise ConnectionClo...
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 _get_unauth_response(self, request, reason): """ Get an error response (or raise a Problem) for a given request and reason message. :type request: Request. :param request: HttpRequest :type reason: Reason string. :param reason: str """ if request....
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 _on_ssl_errors(self, error): url = error.url() self._insecure_hosts.add(url.host()) log.webview.debug("Certificate error: {}".format(error)) if error.is_overridable(): error.ignore = shared.ignore_certificate_errors( url, [error], abort_on=[self.abor...
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_rescore_entrance_exam_all_student(self): """ Test rescoring for all students. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'all_students': True, }) self.assertEqual(response.st...
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 test_str(self): code = LoginCode(user=self.user, timestamp=datetime(2018, 7, 1)) self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00')
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 test_counts_view_html(self): response = self.get_counts("html") self.assertEqual(response.status_code, 200) self.assertHTMLEqual( response.content.decode(), """ <table> <tr> <th>Name</th> <th>Email</th> <th>Count total</th> <th>...
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 remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
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 _inject_metadata_into_fs(metadata, fs, execute=None): metadata = dict([(m.key, m.value) for m in metadata]) _inject_file_into_fs(fs, 'meta.js', jsonutils.dumps(metadata))
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 atom_timestamp(self): return (self.timestamp.strftime('%Y-%m-%dT%H:%M:%S+00:00') or '')
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 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.GET.get('student')) unit = find_unit(course, req...
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 generate_config_section(self, config_dir_path, server_name, **kwargs): return """\ ## Federation ## # Restrict federation to the following whitelist of domains. # N.B. we recommend also firewalling your federation listener to limit # inbound federation traffic as early a...
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 __init__(self, loader, shared_loader_obj=None, variables=dict()): self._loader = loader self._filters = None self._tests = None self._available_variables = variables self._cached_result = {} if loader: self...
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 testSparseFillEmptyRowsGradMatrix(self): reverse_index_map = [0, 1] grad_values = [[0, 1], [2, 3]] # Note: Eager mode and graph mode throw different errors here. Graph mode # will fail with a ValueError from the shape checking logic, while Eager # will fail with an InvalidArgumentError from th...
1
Python
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
def make_homeserver(self, reactor, clock): self.http_client = Mock() hs = self.setup_test_homeserver(http_client=self.http_client) return hs
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 _validate_untrusted_args(argv): # NOTE: Do not use f-strings here, as this should run with older Python # versions (so that a proper error can be displayed) try: untrusted_idx = argv.index('--untrusted-args') except ValueError: return rest = argv[untrusted_idx + 1:] if len(r...
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 read_config(self, config, **kwargs): consent_config = config.get("user_consent") self.terms_template = self.read_templates(["terms.html"], autoescape=True)[0] if consent_config is None: return self.user_consent_version = str(consent_config["version"]) self.us...
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 get_key_size_from_conf(): """ Return the osd dmcrypt key size from config file. Default is 512. """ default_key_size = '512' key_size = conf.ceph.get_safe( 'osd', 'osd_dmcrypt_key_size', default='512') if key_size not in ['256', '512']: logger.warning(("I...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_ee_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> <lolz>&lol1;</lolz> """ with raises(EntitiesForbidden): saml2.extension_element_from_string(...
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 respond_error(self, context, exception): context.respond_server_error() stack = traceback.format_exc() return """ <html> <body> <style> body { font-family: sans-serif; color: #888; ...
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 test_change_nonexistent_due_date(self): url = reverse('change_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week3.location.to_deprecated_string(), 'due_date...
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 test_check_safe_path(self): ret = disk_api._join_and_check_path_within_fs('/foo', 'etc', 'something.conf') self.assertEquals(ret, '/foo/etc/something.conf')
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 filter_module(module, safe_names): return dict([ (name, getattr(module, name)) for name in safe_names if hasattr(module, name) ])
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 test_get_students_features_teams(self, has_teams): """ Test that get_students_features includes team info when the course is has teams enabled, and does not when the course does not have teams enabled """ if has_teams: self.course = CourseFactory.create(teams_...
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 test_binding_exception(self, mock_write): """ If there is a problem getting the key, do not attempt to write the file. """ class MockException(Exception): def __str__(self): return "Mock Exception str" mock_cmd = mock.MagicMock() moc...
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 to_html(self, data, options=None): """ Reserved for future usage. The desire is to provide HTML output of a resource, making an API available to a browser. This is on the TODO list but not currently implemented. """ options = options or {} ...
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 set_from_comma_sep_string(rawstr: str) -> Set[str]: if rawstr == '': return set() return {x.strip() for x in rawstr.split(',')}
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 test_get_student_progress_url_noparams(self): """ Test that the endpoint 404's without the required query params. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url) self.assertEqual(response.s...
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 test_multiuse_link_different_realms(self) -> None: """ Verify that an invitation generated for one realm can't be used to join another. """ lear_realm = get_realm("lear") self.realm = lear_realm invite_link = self.generate_multiuse_invite_link(streams=[]) ...
1
Python
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
safe
def put_file(self, in_path, out_path): ''' transfer a file from local to chroot ''' vvv("PUT %s TO %s" % (in_path, out_path), host=self.chroot) try: with open(in_path, 'rb') as in_file: try: p = self._buffered_exec_command('dd of=%s' % out_pa...
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 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 ...
0
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
vulnerable
def check_prereg_key_and_redirect( request: HttpRequest, confirmation_key: str, full_name: Optional[str] = REQ(default=None)
0
Python
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
def aesEncrypt(data, key): cipher = AES.new(key) data = data + (" " * (16 - (len(data) % 16))) return cipher.encrypt(data)
0
Python
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not address...
https://cwe.mitre.org/data/definitions/310.html
vulnerable
def testFlushFunction(self): logdir = self.get_temp_dir() with context.eager_mode(): writer = summary_ops.create_file_writer_v2( logdir, max_queue=999999, flush_millis=999999) with writer.as_default(): get_total = lambda: len(events_from_logdir(logdir)) # Note: First tf.c...
0
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
vulnerable
def get_tests(config={}): tests = [] tests += [RNGForkTest()] if multiprocessing is not None: tests += [RNGMultiprocessingForkTest()] return tests
1
Python
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not address...
https://cwe.mitre.org/data/definitions/310.html
safe
def inspect_format_method(callable): if not has_format: return None if not isinstance(callable, (types.MethodType, types.BuiltinMethodType)) or \ callable.__name__ != 'format': return None obj = callable.__self__ if isinstance(obj, string_types): ...
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def get_mime_for_format(self, format): """ Given a format, attempts to determine the correct MIME type. If not available on the current ``Serializer``, returns ``application/json`` by default. """ try: return self.content_types[format] exc...
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 runTest(self): ## ECB mode mode = self.module.MODE_ECB encryption_cipher = self.module.new(a2b_hex(self.key), mode) ciphertext = encryption_cipher.encrypt(self.plaintext) decryption_cipher = self.module.new(a2b_hex(self.key), mode) decrypted_plaintext = decryptio...
1
Python
CWE-119
Improper Restriction of Operations within the Bounds of a Memory Buffer
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
https://cwe.mitre.org/data/definitions/119.html
safe
def feed_read_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True) return render_xml_template('feed.xml', entries=result, pagination=pagination)
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 remove(self, name): if os.path.exists(os.path.join(self._path, name)): os.remove(os.path.join(self._path, name))
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 test_get_student_progress_url_from_uname(self): """ Test that progress_url is in the successful response. """ url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()}) url += "?unique_student_identifier={}".format( quote(self.stude...
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_index_absolute_path(index): return os.path.join(INDEXDIR, index)
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 testSparseCountSparseOutputBadNumberOfValues(self): indices = [[0, 0], [0, 1], [1, 0]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, "Number of values must match first dimension of indices"): s...
1
Python
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
def parse_server_name(server_name: str) -> Tuple[str, Optional[int]]: """Split a server name into host/port parts. No validation is done on the host part. The port part is validated to be a valid port number. Args: server_name: server name to parse Returns: host/port parts. R...
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 make_homeserver(self, reactor, clock): self.http_client = Mock() return self.setup_test_homeserver(federation_http_client=self.http_client)
1
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
safe
def to_simple(self, data, options): """ For a piece of data, attempts to recognize it and provide a simplified form of something complex. This brings complex Python data structures down to native types of the serialization format(s). """ if isinstance(data, (...
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_get_form(self): response = self.client.get('/contact-us/') # Check response self.assertContains(response, """<label for="id_your_email">Your email</label>""") self.assertTemplateUsed(response, 'tests/form_page.html') self.assertTemplateNotUsed(response, 'tests/form_...
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 f(): return sparse_ops.deserialize_sparse( serialized_sparse=mu_lock, dtype=dtypes.int32)
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 debug_decisions(self, text): """ Classifies candidate periods as sentence breaks, yielding a dict for each that may be used to understand why the decision was made. See format_debug_decision() to help make this output readable. """ for match in self._lang_vars.p...
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 write_data_table(self, report, report_data, has_totals=True): self.data.append([c["title"] for c in report.schema]) for datum in report_data: datum = report.read_datum(datum) self.data.append([format_data(data, format_iso_dates=True) for data in datum]) if has_to...
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 delete(self): shutil.rmtree(self._path) os.remove(self._props_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 get_info_for_package(pkg, channel_id, org_id): log_debug(3, pkg) pkg = map(str, pkg) params = {'name': pkg[0], 'ver': pkg[1], 'rel': pkg[2], 'epoch': pkg[3], 'arch': pkg[4], 'channel_id': channel_id, 'org_id': org_id} ...
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 testPartialIndexInsert(self): with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.float32) f = array_ops.placeholder(dtypes.float32) v = array_ops.placeholder(dtypes.float32) pi = array_ops.placeholder(dtypes.int64) gi =...
0
Python
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
vulnerable
def __init__( self, proxy_type, proxy_host, proxy_port, proxy_rdns=True, proxy_user=None, proxy_pass=None, proxy_headers=None,
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 __init__(self, deferred, max_size): self.stream = BytesIO() self.deferred = deferred self.length = 0 self.max_size = max_size
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_maintain_uuid_token_expiration(self): self.opt_in_group('signing', token_format='UUID') self._maintain_token_expiration()
1
Python
CWE-255
Credentials Management Errors
Weaknesses in this category are related to the management of credentials.
https://cwe.mitre.org/data/definitions/255.html
safe
def test_reset_nonexistent_extension(self): url = reverse('reset_due_date', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'student': self.user1.username, 'url': self.week1.location.to_deprecated_string(), }) sel...
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 load_yaml(yaml_str): """ :param unicode yaml_str: :rtype: dict | list """ return yaml.load(yaml_str)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def bm_to_item(self, bm): return bm.copy()
1
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
safe
def __init__(self, expression, delimiter, **extra): delimiter_expr = Value(str(delimiter)) super().__init__(expression, delimiter_expr, **extra)
1
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
safe
def format_string(self, s, args, kwargs): """If a format call is detected, then this is routed through this method so that our safety sandbox can be used for it. """ if isinstance(s, Markup): formatter = SandboxedEscapeFormatter(self, s.escape) else: f...
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def test_invalid(self, args, message): with pytest.raises(SystemExit, match=re.escape(message)): 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 mysql_insensitive_contains(field: Field, value: str) -> Criterion: return functions.Upper(functions.Cast(field, SqlTypes.CHAR)).like(functions.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_equal_body(self): # check server doesnt close connection when body is equal to # cl header to_send = tobytes( "GET /equal_body HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: 0\n" "\n" ) self.connect() s...
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 testNegativeSeqValuesForGradOp(self): with self.assertRaisesRegex( errors.InvalidArgumentError, r"Row sequence tensor values must not be negative.*"): y = nn_ops.gen_nn_ops.fractional_avg_pool_grad( orig_input_tensor_shape=[2, 2, 2, 2], out_backprop=[[[[1, 2], [3, 4],...
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 format_help_for_context(self, ctx: commands.Context) -> str: #Thanks Sinbad! And Trusty in whose cogs I found this. pre_processed = super().format_help_for_context(ctx) return f"{pre_processed}\n\nVersion: {self.__version__}"
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 handler(request): """Handler for a file:// URL. Args: request: QNetworkRequest to answer to. Return: A QNetworkReply for directories, None for files. """ path = request.url().toLocalFile() try: if os.path.isdir(path): data = dirbrowser_html(path) ...
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 test_login_unknown_code(self): response = self.client.post('/accounts/login/code/', { 'user': 1, 'code': 'unknown', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].errors, { '__all__': ['Unable to log i...
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 get_field(self, field_name, args, kwargs): first, rest = formatter_field_name_split(field_name) obj = self.get_value(first, args, kwargs) for is_attr, i in rest: if is_attr: obj = self._env.getattr(obj, i) else: ...
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def _set_repository_id(self, path, id): config = RawConfigParser() config.read(os.path.join(path, 'config')) config.set('repository', 'id', hexlify(id).decode('ascii')) with open(os.path.join(path, 'config'), 'w') as fd: config.write(fd) return Repository(self.rep...
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 render_search_results(term, offset=None, order=None, limit=None): join = db.books_series_link, db.Books.id == db.books_series_link.c.book, db.Series entries, result_count, pagination = calibre_db.get_search_results(term, offset, ...
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 test_deprecated_setting(self): """The older WEBHOOK_AUTHORIZATION setting is still supported (for now)""" response = self.call_webhook() self.assertEqual(response.status_code, 200)
1
Python
CWE-532
Insertion of Sensitive Information into Log File
Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.
https://cwe.mitre.org/data/definitions/532.html
safe
def test_module(self): body = [ast.Num(42)] x = ast.Module(body) self.assertEqual(x.body, body)
0
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
vulnerable
def setUp(self): self.mock_resource = MockHttpResource(prefix=PATH_PREFIX) self.mock_handler = Mock( spec=[ "get_displayname", "set_displayname", "get_avatar_url", "set_avatar_url", "check_profile_query_allow...
1
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
safe
def edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_c...
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 __getattr__(self, attr: str) -> Any: # Passthrough to the real reactor except for the DNS resolver. if attr == "nameResolver": return self._nameResolver else: return getattr(self._reactor, attr)
1
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
safe
def setUp(self): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = register_query_handler ...
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 _sanitize(value: str) -> str: return re.sub(r"[^\w _-]+", "", value)
0
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
vulnerable
def test_modify_access_noparams(self): """ Test missing all query parameters. """ url = reverse('modify_access', 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 testLegacyQuoteAttribute(c): input_ = [["StartTag", "http://www.w3.org/1999/xhtml", "span", [{"namespace": None, "name": "foo", "value": c}]]] if c == '"': output_ = ["<span foo='%s'>" % c] else: output_ = ['<span foo="%s">' % c] options_ = {"quote_attr_values": "legac...
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_ownership(self): """ test if intermediate dir is owned by correct user """ if sys.platform != 'win32': im_dir = catalog.intermediate_dir() im_dir_stat = os.stat(im_dir) proc_uid = os.getuid() assert_(proc_uid == im_dir_stat.st_uid) ...
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
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-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 testRunCommandInvalidSignature(self, use_tfrt): self.parser = saved_model_cli.create_parser() base_path = test.test_src_dir_path(SAVED_MODEL_PATH) args = self.parser.parse_args([ 'run', '--dir', base_path, '--tag_set', 'serve', '--signature_def', 'INVALID_SIGNATURE', '--input_exprs', '...
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 get_response(self): token_serializer = self.token_serializer_class( instance=self.token, context=self.get_serializer_context(), ) data = token_serializer.data data['next'] = self.serializer.validated_data['code'].next return Response(data, status=s...
0
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
vulnerable
def security_group_count_by_project(context, project_id): authorize_project_context(context, project_id) return model_query(context, models.SecurityGroup, read_deleted="no").\ filter_by(project_id=project_id).\ count()
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 publisher_list(): if current_user.get_view_property('publisher', 'dir') == 'desc': order = db.Publishers.name.desc() order_no = 0 else: order = db.Publishers.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_PUBLISHER): entries = calibre_d...
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 job_log(request, client_id, project_name, spider_name, job_id): """ get log of jog :param request: request object :param client_id: client id :param project_name: project name :param spider_name: spider name :param job_id: job id :return: log of job """ if request.method == '...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_01_checksecure_doublequote(self): """ U01 | quoted text should not be forbidden """ INPUT = 'ls -E "1|2" tmp/test' return self.assertEqual(sec.check_secure(INPUT, self.userconf)[0], 0)
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 quota_set(id): return {'quota_set': {'id': id, 'metadata_items': 128, 'volumes': 10, 'gigabytes': 1000, 'ram': 51200, 'floating_ips': 10, 'instances': 10, 'injected_files': 5, 'cores': 20, 'injected_file_content_bytes': 10240}}
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 find_temp_dir(prefix, tmp_dir=None): """ Find temp dirs in 'tmp_dir' starting with 'prefix'""" matches = [] tmp_dir = tmp_dir or tempfile.gettempdir() for tmp_file in os.listdir(tmp_dir): if tmp_file.startswith(prefix): matches.append(os.path.join(tmp_dir, tmp_file)) return m...
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def test_notfilelike_shortcl_http11(self): to_send = "GET /notfilelike_shortcl 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 = r...
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_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.get(url) self.assertEqual(response.status_code, 400)
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 test_request_body_too_large_with_no_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # server trusts the con...
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 tempdir(change_dir=False): tmpdir = mkdtemp() yield tmpdir shutil.rmtree(tmpdir)
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_can_read_token_from_query_parameters(self): """Tests that Sydent correct extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_to...
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