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_uses_xdg_config_home(self, apiver): with WindowsSafeTempDir() as d: account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, XDG_CONFIG_HOME_ENV_VAR: d, }...
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_token_expiry_maintained(self): foo_client = self.get_client(self.user_foo) orig_token = foo_client.service_catalog.catalog['token'] time.sleep(1.01) reauthenticated_token = foo_client.tokens.authenticate( token=foo_client.auth_token) ...
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 get_student_progress_url(request, course_id): """ Get the progress url of a student. Limited to staff access. Takes query parameter unique_student_identifier and if the student exists returns e.g. { 'progress_url': '/../...' } """ course_id = SlashSeparatedCourseKey.from_dep...
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 _default_logfile(exe_name): ''' Retrieve the logfile name ''' if salt.utils.is_windows(): logfile_tmp = tempfile.NamedTemporaryFile(dir=os.environ['TMP'], prefix=exe_name, suffix='.log', ...
1
Python
CWE-19
Data Processing Errors
Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information.
https://cwe.mitre.org/data/definitions/19.html
safe
def task_status(request, task_id): """ get task status info :param request: request object :param task_id: task id :return: """ if request.method == 'GET': result = [] task = Task.objects.get(id=task_id) clients = clients_of_task(task) for client in clients: ...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def assert_update_forum_role_membership(self, current_user, identifier, rolename, action): """ Test update forum role membership. Get unique_student_identifier, rolename and action and update forum role. """ url = reverse('update_forum_role_membership', kwargs={'course_id': 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 process_command_line(self, argv, verbose=1): usage = "usage: %s start | stop | restart | status | debug " \ "[--pidfile=...] " \ "(run as non-daemon)" % os.path.basename(argv[0]) if len(argv) < 2: print usage raise SystemExit else...
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 subscribe_for_tags(request): """process subscription of users by tags""" #todo - use special separator to split tags tag_names = request.REQUEST.get('tags','').strip().split() pure_tag_names, wildcards = forms.clean_marked_tagnames(tag_names) if request.user.is_authenticated(): if reques...
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(self, key): """ Gets the object specified by key. It will also unpickle the object before returning if it is pickled in memcache. :param key: key :returns: value of the key in memcache """ key = md5hash(key) value = None for (server, ...
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 get_server_key(self): """ Retrieve the server's public key. :return: rsa public key :rtype: str """ return self.server.GET('/pulp/static/rsa_pub.key', ignore_prefix=True)
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 get_vars_next(self): next = current.request.vars._next if isinstance(next, (list, tuple)): next = next[0] if next and self.settings.prevent_open_redirect_attacks: return prevent_open_redirect(next) return next or None
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 attemptRequestWithMaliciousMethod(self, method): """ Attempt a request with the provided method. @param method: see L{MethodInjectionTestsMixin} """ uri = b'http://twisted.invalid' client.getPage(uri, method=method)
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 _cbrt(x): return math.pow(x, 1.0/3)
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_proxied_blacklisted_http_client(self) -> SimpleHttpClient: """ An HTTP client that uses configured HTTP(S) proxies and blacklists IPs based on the IP range blacklist. """ return SimpleHttpClient( self, ip_blacklist=self.config.ip_range_blacklis...
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 harden_runtime(self, password, encoded): """ Bridge the runtime gap between the work factor supplied in `encoded` and the work factor suggested by this hasher. Taking PBKDF2 as an example, if `encoded` contains 20000 iterations and `self.iterations` is 30000, this method...
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 process_statistics(self, metadata, _): args = [metadata.hostname, '-p', metadata.profile, '-g', ':'.join([g for g in metadata.groups])] self.debug_log("running triggers") for notifier in os.listdir(self.data): self.debug_log("running %s" % notifier) ...
1
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
safe
def _get_object_element(dataset, seq_no, rel_path, download_link): """If rel_path and download_link are not None, we are called from scope. Otherwise we are called from ID and need to run SQL query to fetch these attrs.""" if rel_path is None: query = "SELECT rel_path, download_link FROM " + \ ...
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 delete_user_session(user_id, session_key): try: log.info("Deleted session_key : " + session_key) session.query(User_Sessions).filter(User_Sessions.user_id==user_id, User_Sessions.session_key==session_key).delete() session.commit() except (e...
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 testBadInputSizes(self): self._testBadInputSize( tin=math_ops.cast( constant_op.constant(1, shape=[1, 2]), dtype=dtypes.quint8), error_regex="must be rank 4") self._testBadInputSize( tfilter=math_ops.cast( constant_op.constant(1, shape=[1, 2]), dtype=dtypes....
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 makepasv(self): """Internal: Does the PASV or EPSV handshake -> (address, port)""" if self.af == socket.AF_INET: untrusted_host, port = parse227(self.sendcmd('PASV')) if self.trust_server_pasv_ipv4_address: host = untrusted_host else: ...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def delete(self, req, image_id): self._enforce(req, 'delete_image') image = self._get_image(req.context, image_id) if image['protected']: msg = _("Unable to delete as image %(image_id)s is protected" % locals()) raise webob.exc.HTTPForbidden(expla...
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 testRaggedCountSparseOutputBadSplitsEnd(self): splits = [0, 5] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must end with the number of values"): self.evaluate( gen_c...
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 snake_case(value: str) -> str: return stringcase.snakecase(group_title(_sanitize(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 setUp(self): self.mock_federation_resource = MockHttpResource() self.mock_http_client = Mock(spec=[]) self.mock_http_client.put_json = DeferredMockCallable() hs = yield setup_test_homeserver( self.addCleanup, http_client=self.mock_http_client, keyring=Mock(), ...
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 check_is_symlink(): """ Check if intermediate dir is symlink. """ try: return not os.path.islink(im_dir) except OSError: return False
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-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 create_dmcrypt_key(): """ Create the secret dm-crypt key used to decrypt a device. """ # get the customizable dmcrypt key size (in bits) from ceph.conf fallback # to the default of 1024 dmcrypt_key_size = conf.ceph.get_safe( 'osd', 'osd_dmcrypt_key_size', default=1024...
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_get_students_features_cohorted(self, is_cohorted): """ Test that get_students_features includes cohort info when the course is cohorted, and does not when the course is not cohorted. """ url = reverse('get_students_features', kwargs={'course_id': unicode(self.course....
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 move(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) form = CommentMoveForm(topic=topic, data=request.POST) if form.is_valid(): comments = form.save() for comment in comments: comment_posted(comment=comment, mentions=None) topic.decrease_commen...
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 _check_group_whitelist(self, username, user_id, is_admin, access_token): http_client = AsyncHTTPClient() headers = _api_headers(access_token) # Check if we are a member of each group in the whitelist for group in map(url_escape, self.gitlab_group_whitelist): url = "%s...
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_broken_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n" to_send += control_line + s # garbage in input to_send += "GET / HTTP/1.1\nTransfer-...
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_reset_student_attempts_deletall(self): """ Make sure no one can delete all students state on a problem. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.pro...
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 _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require ...
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_create_catalog(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'c') assert_(cat is not None) cat.close() remove_tree(pardir)
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 _parse_cache_control(headers): retval = {} if "cache-control" in headers: parts = headers["cache-control"].split(",") parts_with_args = [ tuple([x.strip().lower() for x in part.split("=", 1)]) for part in parts if -1 != part.find("=") ] par...
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 verify_password(plain_password, user_password): if plain_password == user_password: LOG.debug("password true") return True return False
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 _handle_carbon_received(self, msg): if msg['from'].bare == self.xmpp.boundjid.bare: self.xmpp.event('carbon_received', msg)
1
Python
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
safe
def main(): _validate_untrusted_args(sys.argv) parser = get_argparser() argv = sys.argv[1:] args = parser.parse_args(argv) if args.json_args is not None: args = _unpack_json_args(args) earlyinit.early_init(args) # We do this imports late as earlyinit needs to be run first (because of...
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 prevent_open_redirect(next, host): # Prevent an attacker from adding an arbitrary url after the # _next variable in the request. if next: parts = next.split('/') if ':' not in parts[0] and parts[:2] != ['', '']: return next elif len(par...
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 set_admins(self) -> None: name = self.results["deploy"]["func-name"]["value"] key = self.results["deploy"]["func-key"]["value"] table_service = TableService(account_name=name, account_key=key) if self.admins: update_admins(table_service, self.application_name, self.ad...
0
Python
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
vulnerable
def test_property_from_data_array(self, mocker): name = mocker.MagicMock() required = mocker.MagicMock() data = oai.Schema(type="array", items={"type": "number", "default": "0.0"},) ListProperty = mocker.patch(f"{MODULE_NAME}.ListProperty") FloatProperty = mocker.patch(f"{MOD...
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 from_yaml(self, content): """ Given some YAML data, returns a Python dictionary of the decoded data. """ if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.safe_load(content)
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_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(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
def recursive_fn2(n): if n <= 1: return 2 return recursive_fn1(n - 1)
1
Python
CWE-667
Improper Locking
The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.
https://cwe.mitre.org/data/definitions/667.html
safe
def download_list(): if current_user.get_view_property('download', 'dir') == 'desc': order = ub.User.name.desc() order_no = 0 else: order = ub.User.name.asc() order_no = 1 if current_user.check_visibility(constants.SIDEBAR_DOWNLOAD) and current_user.role_admin(): entr...
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_check_safe_path(self): ret = disk_api._join_and_check_path_within_fs('/foo', 'etc', 'something.conf') self.assertEquals(ret, '/foo/etc/something.conf')
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 _clean_data_struct(orig_data): ''' walk a complex data structure, and use _clean_data() to remove any template tags that may exist ''' if isinstance(orig_data, dict): data = orig_data.copy() for key in data: new_key = _clean_data_struct(key) new_val = _cle...
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 setup_logging(): """Configure the python logging appropriately for the tests. (Logs will end up in _trial_temp.) """ root_logger = logging.getLogger() log_format = ( "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s" " - %(message)s" ) handler = ToTwistedHandler() ...
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 to_plist(self, data, options=None): """ Given some Python data, produces binary plist output. """ options = options or {} if biplist is None: raise ImproperlyConfigured("Usage of the plist aspects requires biplist.") return biplist.wr...
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 _setup_master(self): Router.max_message_size = self.config['max_message_size'] if self.config['profiling']: enable_profiling() self.broker = Broker(activate_compat=False) self.router = Router(self.broker) self.router.debug = self.config.get('debug', False) ...
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 test_nonexistent_catalog_is_none(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'r') remove_tree(pardir) assert_(cat is None)
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_filelike_nocl_http10(self): to_send = "GET /filelike_nocl HTTP/1.0\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", ...
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_request_body_too_large_with_no_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\r\nConnection: close\r\n\r\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", ...
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 _create_dirs(path): """ create provided path, ignore errors """ try: os.makedirs(path, mode=0o700) except OSError: pass
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_reset_entrance_exam_all_student_attempts(self, act): """ Test reset all student attempts for entrance exam. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { ...
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 make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver("server", http_client=None) self.handler = hs.get_device_handler() self.store = hs.get_datastore() 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 count(cls, **kwargs): """Return a count of server side resources given filtering arguments in kwargs. """ url = urljoin(recurly.base_uri(), cls.collection_path) if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.count_for_url(url)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def is_leaf(cls, path): path = os.path.join(filesystem.FOLDER, path.replace("/", os.sep)) return os.path.isdir(path) and os.path.exists(path + ".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 test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200"...
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 __unicode__(self): return self.xml()
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 _get_shared_models(self, args: "DictConfig") -> Dict[str, dict]: with open(args.blueprint.model_opt_path) as f: all_model_opts = yaml.load(f.read()) active_model_opts = { model: opt for model, opt in all_model_opts.items() if self.conversations_nee...
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 test_notfilelike_nocl_http11(self): to_send = "GET /notfilelike_nocl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "...
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_format_quota_set(self): raw_quota_set = { 'instances': 10, 'cores': 20, 'ram': 51200, 'volumes': 10, 'floating_ips': 10, 'metadata_items': 128, 'gigabytes': 1000, 'injected_files': 5, 'inject...
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 table_get_custom_enum(c_id): ret = list() cc = (calibre_db.session.query(db.Custom_Columns) .filter(db.Custom_Columns.id == c_id) .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).one_or_none()) ret.append({'value': "", 'text': ""}) for idx, en in enumerate(cc....
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_get_ora2_responses_already_running(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.side_effect = AlreadyRunningError() r...
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 make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver(http_client=None) self.handler = hs.get_federation_handler() self.store = hs.get_datastore() 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 make_homeserver(self, reactor, clock): self.fetches = [] def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ ...
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 test_build_attr(self): assert set(ClearableFileInput().build_attrs({}).keys()) == { "class", "data-url", "data-fields-x-amz-algorithm", "data-fields-x-amz-date", "data-fields-x-amz-signature", "data-fields-x-amz-credential", ...
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_get_sale_records_features_json(self): """ Test that the response from get_sale_records is in json format. """ for i in range(5): course_registration_code = CourseRegistrationCode( code='sale_invoice{}'.format(i), course_id=self.cou...
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_methodWithCLRFRejected(self): """ Issuing a request with a method that contains a carriage return and line feed fails with a L{ValueError}. """ with self.assertRaises(ValueError) as cm: method = b"GET\r\nX-Injected-Header: value" self.attemptR...
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 read_config(self, config, **kwargs): # FIXME: federation_domain_whitelist needs sytests self.federation_domain_whitelist = None # type: Optional[dict] federation_domain_whitelist = config.get("federation_domain_whitelist", None) if federation_domain_whitelist is not None: ...
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 deserialize(self, content, format='application/json'): """ Given some data and a format, calls the correct method to deserialize the data and returns the result. """ desired_format = None format = format.split(';')[0] for short_format, long_format in sel...
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 escape_text(text: EscapableEntity) -> str: """Escape HTML text We only strip some tags and allow some simple tags such as <h1>, <b> or <i> to be part of the string. This is useful for messages where we want to keep formatting options. (Formerly known as 'permissive_attrencode') 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 testInvalidSparseTensor(self): with test_util.force_cpu(): shape = [2, 2] val = [0] dense = constant_op.constant(np.zeros(shape, dtype=np.int32)) for bad_idx in [ [[-1, 0]], # -1 is invalid. [[1, 3]], # ...so is 3. ]: sparse = sparse_tensor.SparseTe...
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 sentences_stats(self, type, vId = None): return self.sql_execute(self.prop_sentences_stats(type, vId))
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_pathWithCRLFRejected(self): """ Issuing a request with a URI whose path contains a carriage return and line feed fails with a L{ValueError}. """ with self.assertRaises(ValueError) as cm: uri = b"http://twisted.invalid/\r\npath" self.attemptReq...
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 test_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin): session = Session(self.config_dir) session['cookies'] = initial_cookie session.remove_cookies([expired_cookie]) assert expired_cookie not in session.cookies
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 _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, filename) key.get_contents_to_filename(local_filename) return local_filename
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 resolveHostName( self, recv: IResolutionReceiver, hostname: str, portNumber: int = 0
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 logout(request): """ Clears the session and logs the current user out. """ request.user_logout() # FIXME(gabriel): we don't ship a view named splash return shortcuts.redirect('splash')
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
async def handle_404(request, response): if 'json' not in response.headers['Content-Type']: if request.path.endswith('/'): return web.HTTPFound(request.path.rstrip('/')) return web.json_response({ "status": 404, "message": "Page '{}' not found".format(request.path...
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 get_object_src_http(dataset, rel_path): path = _get_obj_abosolute_path(dataset, rel_path) response = send_file(path, cache_timeout=datetime.timedelta( days=365).total_seconds(), add_etags=True, conditiona...
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 __init__(self, directory=None, pattern='__jinja2_%s.cache'): if directory is None: directory = self._get_default_cache_dir() self.directory = directory self.pattern = pattern
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_course_has_entrance_exam_in_student_attempts_reset(self): """ Test course has entrance exam id set while resetting attempts""" url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.post(u...
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 setUp(self): """ Set up global staff role so authorization will not fail. """ super(TestEndpointHttpMethods, self).setUp() global_user = GlobalStaffFactory() self.client.login(username=global_user.username, password='test')
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_received_bad_host_header(self): from waitress.utilities import BadRequest data = b"""\ HTTP/1.0 GET /foobar Host: foo """ result = self.parser.received(data) self.assertEqual(result, 33) self.assertTrue(self.parser.completed) self.assertEqual(self.parser....
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 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 _is_javascript_scheme(s): if _is_image_dataurl(s): return None return _is_possibly_malicious_scheme(s)
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_endpoints_reject_get(self, data): """ Tests that POST endpoints are rejected with 405 when using GET. """ url = reverse(data, kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url) self.assertEqual( response.status_code, 4...
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_roundtrip_file(self): f = open(self.filename, 'wb') self.x.tofile(f) f.close() # NB. doesn't work with flush+seek, due to use of C stdio f = open(self.filename, 'rb') y = np.fromfile(f, dtype=self.dtype) f.close() assert_array_equal(y, self.x....
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 _lookup(self, name, *args, **kwargs): instance = self._lookup_loader.get(name.lower(), loader=self._loader, templar=self) if instance is not None: wantlist = kwargs.pop('wantlist', False) from ansible.utils.listify import listify_lookup_plugin_terms loop_ter...
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_poisoned_http_host_admin_site(self): "Poisoned HTTP_HOST headers can't be used for reset emails on admin views" with self.assertRaises(SuspiciousOperation): self.client.post('/admin_password_reset/', {'email': 'staffmember@example.com'}, HTTP_HOST...
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_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':...
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 getresponse(self): mapper = routes.Mapper() api = context.UnauthenticatedContextMiddleware(rserver.API(mapper)) webob_res = self.req.get_response(api) return utils.FakeHTTPResponse(status=webob_res.status_int, headers=webob_res.headers, ...
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 setUp(self): config = { "general": { "ip.blacklist": "5.0.0.0/8", "ip.whitelist": "5.1.1.1", }, } self.sydent = make_sydent(test_config=config) self.reactor = self.sydent.reactor self.safe_domain, self.safe_ip = b...
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 make_homeserver(self, reactor, clock): config = self.default_config() config["redaction_retention_period"] = "30d" return self.setup_test_homeserver( resource_for_federation=Mock(), http_client=None, config=config )
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 check_ownership(): """ Intermediate dir owner should be same as owner of process. """ if sys.platform != 'win32': try: im_dir_stat = os.stat(im_dir) except OSError: return False proc_uid = os.getuid() return proc_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 load_metadata_preview(request, c_type, c_id, conn=None, share_id=None, **kwargs): """ This is the image 'Preview' tab for the right-hand panel. """ context = {} # the index of a field within a well index = getIntOrDefault(request, "index", 0) manager = BaseContainer(conn, **{str(c_type...
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
async def on_room_state_request( self, origin: str, room_id: str, event_id: str
1
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
safe
def test_use_yaml_safe_load(mock_yaml): """ Ensure we're using yaml.safe_load not yaml.load """ from confire.config import Configuration Configuration.CONF_PATHS = [TESTCONF] Configuration.load() mock_yaml.safe_load.assert_called_once() mock_yaml.load.assert_not_called()
1
Python
NVD-CWE-noinfo
null
null
null
safe