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 testBoostedTreesAggregateStatsSecurity2(self): node_ids = [-10] gradients = [[0.0, 0.0]] hessians = [[100.0]] feature = [[0, 0, 0]] max_splits = 100 num_buckets = 100 with self.assertRaises((errors.InvalidArgumentError, ValueError)): self.evaluate( gen_boosted_trees_ops.boosted_trees_aggregate_stats( node_ids=node_ids, gradients=gradients, hessians=hessians, feature=feature, max_splits=max_splits, num_buckets=num_buckets))
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 _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = _join_and_check_path_within_fs(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join('root', '.ssh', 'authorized_keys') key_data = ''.join([ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ]) _inject_file_into_fs(fs, keyfile, key_data, append=True)
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 the restricted directory.
https://cwe.mitre.org/data/definitions/22.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, decision_text in self._match_potential_end_contexts(text): tokens = self._tokenize_words(decision_text) tokens = list(self._annotate_first_pass(tokens)) while tokens and not tokens[0].tok.endswith(self._lang_vars.sent_end_chars): tokens.pop(0) yield { "period_index": match.end() - 1, "text": decision_text, "type1": tokens[0].type, "type2": tokens[1].type, "type1_in_abbrs": bool(tokens[0].abbr), "type1_is_initial": bool(tokens[0].is_initial), "type2_is_sent_starter": tokens[1].type_no_sentperiod in self._params.sent_starters, "type2_ortho_heuristic": self._ortho_heuristic(tokens[1]), "type2_ortho_contexts": set( self._params._debug_ortho_context(tokens[1].type_no_sentperiod) ), "collocation": ( tokens[0].type_no_sentperiod, tokens[1].type_no_sentperiod, ) in self._params.collocations, "reason": self._second_pass_annotation(tokens[0], tokens[1]) or REASON_DEFAULT_DECISION, "break_decision": tokens[0].sentbreak, }
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_send_push_single_worker(self): """Test that registration works when using a pusher worker. """ http_client_mock = Mock(spec_set=["post_json_get_json"]) http_client_mock.post_json_get_json.side_effect = lambda *_, **__: defer.succeed( {} ) self.make_worker_hs( "synapse.app.pusher", {"start_pushers": True}, proxied_http_client=http_client_mock, ) event_id = self._create_pusher_and_send_msg("user") # Advance time a bit, so the pusher will register something has happened self.pump() http_client_mock.post_json_get_json.assert_called_once() self.assertEqual( http_client_mock.post_json_get_json.call_args[0][0], "https://push.example.com/push", ) self.assertEqual( event_id, http_client_mock.post_json_get_json.call_args[0][1]["notification"][ "event_id" ], )
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def test_keepalive_http11_explicit(self): # Explicitly set keep-alive data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\n" "Connection: keep-alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertTrue(response.getheader("connection") != "close")
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def concat_wrapper(): y = gen_array_ops.concat_v2( values=[[1, 2, 3], [4, 5, 6]], axis=0xb500005b) return y
1
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
safe
def _create_dirs(self): """Create folder storing the collection if absent.""" if not os.path.exists(os.path.dirname(self._path)): os.makedirs(os.path.dirname(self._path))
0
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
vulnerable
def test_get_students_features(self): """ Test that some minimum of information is formatted correctly in the response to get_students_features. """ for student in self.students: student.profile.city = "Mos Eisley {}".format(student.id) student.profile.save() url = reverse('get_students_features', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('students', res_json) for student in self.students: student_json = [ x for x in res_json['students'] if x['username'] == student.username ][0] self.assertEqual(student_json['username'], student.username) self.assertEqual(student_json['email'], student.email) self.assertEqual(student_json['city'], student.profile.city) self.assertEqual(student_json['country'], "")
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 response(self, response, content): if "authentication-info" not in response: challenge = _parse_www_authenticate(response, "www-authenticate").get( "digest", {} ) if "true" == challenge.get("stale"): self.challenge["nonce"] = challenge["nonce"] self.challenge["nc"] = 1 return True else: updated_challenge = _parse_www_authenticate( response, "authentication-info" ).get("digest", {}) if "nextnonce" in updated_challenge: self.challenge["nonce"] = updated_challenge["nextnonce"] self.challenge["nc"] = 1 return False
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 _sqrt(x): if isinstance(x, complex) or x < 0: return cmath.sqrt(x) else: return math.sqrt(x)
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 _read_from_sections(user, collection_url, permission): """Get regex sections.""" filename = os.path.expanduser(config.get("rights", "file")) rights_type = config.get("rights", "type").lower() regex = ConfigParser({"login": user, "path": collection_url}) if rights_type in DEFINED_RIGHTS: log.LOGGER.debug("Rights type '%s'" % rights_type) regex.readfp(StringIO(DEFINED_RIGHTS[rights_type])) elif rights_type == "from_file": log.LOGGER.debug("Reading rights from file %s" % filename) if not regex.read(filename): log.LOGGER.error("File '%s' not found for rights" % filename) return False else: log.LOGGER.error("Unknown rights type '%s'" % rights_type) return False for section in regex.sections(): re_user = regex.get(section, "user") re_collection = regex.get(section, "collection") log.LOGGER.debug( "Test if '%s:%s' matches against '%s:%s' from section '%s'" % ( user, collection_url, re_user, re_collection, section)) user_match = re.match(re_user, user) if user_match: re_collection = re_collection.format(*user_match.groups()) if re.match(re_collection, collection_url): log.LOGGER.debug("Section '%s' matches" % section) if permission in regex.get(section, "permission"): return True else: log.LOGGER.debug("Section '%s' does not match" % section) return False
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 test_register(self) -> None: reset_emails_in_zulip_realm() realm = get_realm("zulip") stream_names = [f"stream_{i}" for i in range(40)] for stream_name in stream_names: stream = self.make_stream(stream_name, realm=realm) DefaultStream.objects.create(stream=stream, realm=realm) # Clear all the caches. flush_per_request_caches() ContentType.objects.clear_cache() with queries_captured() as queries, cache_tries_captured() as cache_tries: self.register(self.nonreg_email("test"), "test") # Ensure the number of queries we make is not O(streams) self.assert_length(queries, 91) # We can probably avoid a couple cache hits here, but there doesn't # seem to be any O(N) behavior. Some of the cache hits are related # to sending messages, such as getting the welcome bot, looking up # the alert words for a realm, etc. self.assert_length(cache_tries, 21) user_profile = self.nonreg_user("test") self.assert_logged_in_user_id(user_profile.id) self.assertFalse(user_profile.enable_stream_desktop_notifications)
1
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
safe
def handler(request, _operation, _current_url): """Handler for a file:// URL. Args: request: QNetworkRequest to answer to. _operation: The HTTP operation being done. _current_url: The page we're on currently. Return: A QNetworkReply for directories, None for files. """ path = request.url().toLocalFile() try: if os.path.isdir(path): data = dirbrowser_html(path) return networkreply.FixedDataNetworkReply( request, data, 'text/html') return None except UnicodeEncodeError: return None
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 do_init(self, args): """Initialize an empty repository""" print('Initializing repository at "%s"' % args.repository.orig) repository = self.open_repository(args.repository, create=True, exclusive=True) key = key_creator(repository, args) manifest = Manifest(key, repository) manifest.key = key manifest.write() repository.commit() Cache(repository, key, manifest, warn_if_unencrypted=False) return self.exit_code
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_notfilelike_shortcl_http11(self): to_send = "GET /notfilelike_shortcl HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, 1) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377" in response_body)
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def sql_one_row(self, sentence, column): self.cursor.execute(sentence) return self.cursor.fetchone()[column]
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 whitelist(f): """Decorator: Whitelist method to be called remotely via REST API.""" f.whitelisted = True return f
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 send_transaction(self, account, to, selector_name, calldata, nonce=None, max_fee=0): return await self.send_transactions(account, [(to, selector_name, calldata)], nonce, max_fee)
0
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
vulnerable
def _ensure_authed(self, ptype, message): """ Checks message type against current auth state. If server mode, and auth has not succeeded, and the message is of a post-auth type (channel open or global request) an appropriate error response Message is crafted and returned to caller for sending. Otherwise (client mode, authed, or pre-auth message) returns None. """ if ( not self.server_mode or ptype <= HIGHEST_USERAUTH_MESSAGE_ID or self.is_authenticated() ): return None # WELP. We must be dealing with someone trying to do non-auth things # without being authed. Tell them off, based on message class. reply = Message() # Global requests have no details, just failure. if ptype == MSG_GLOBAL_REQUEST: reply.add_byte(cMSG_REQUEST_FAILURE) # Channel opens let us reject w/ a specific type + message. elif ptype == MSG_CHANNEL_OPEN: kind = message.get_text() chanid = message.get_int() reply.add_byte(cMSG_CHANNEL_OPEN_FAILURE) reply.add_int(chanid) reply.add_int(OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED) reply.add_string('') reply.add_string('en') # NOTE: Post-open channel messages do not need checking; the above will # reject attemps to open channels, meaning that even if a malicious # user tries to send a MSG_CHANNEL_REQUEST, it will simply fall under # the logic that handles unknown channel IDs (as the channel list will # be empty.) return reply
1
Python
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
def test_specifiying_wagtail_mount_point_does_prepend_allowed_paths_with_wagtail_mount_path(settings): settings.WAGTAIL_MOUNT_PATH = '/wagtail' allowed_paths = VerifyUserMiddleware()._get_allowed_paths(has_device=False) for allowed_path in allowed_paths: assert allowed_path.startswith(settings.WAGTAIL_MOUNT_PATH)
1
Python
NVD-CWE-noinfo
null
null
null
safe
def feed_publisher(book_id): off = request.args.get("offset") or 0 entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0, db.Books, db.Books.publishers.any(db.Publishers.id == book_id), [db.Books.timestamp.desc()]) return render_xml_template('feed.xml', entries=entries, 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 swap_public_ssh_key(remote_node): """ Swap public ssh key between remote_node and local """ # Detect whether need password to login to remote_node if utils.check_ssh_passwd_need(remote_node): # If no passwordless configured, paste /root/.ssh/id_rsa.pub to remote_node's /root/.ssh/authorized_keys status("Configuring SSH passwordless with root@{}".format(remote_node)) # After this, login to remote_node is passwordless append_to_remote_file(RSA_PUBLIC_KEY, remote_node, AUTHORIZED_KEYS_FILE) try: # Fetch public key file from remote_node public_key_file_remote = fetch_public_key_from_remote_node(remote_node) except ValueError as err: warn(err) return # Append public key file from remote_node to local's /root/.ssh/authorized_keys # After this, login from remote_node is passwordless # Should do this step even passwordless is True, to make sure we got two-way passwordless append_unique(public_key_file_remote, AUTHORIZED_KEYS_FILE)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _checknetloc(netloc): if not netloc or netloc.isascii(): return # looking for characters like \u2100 that expand to 'a/c' # IDNA uses NFKC equivalence, so normalize for this check import unicodedata n = netloc.rpartition('@')[2] # ignore anything to the left of '@' n = n.replace(':', '') # ignore characters already included n = n.replace('#', '') # but not the surrounding text n = n.replace('?', '') netloc2 = unicodedata.normalize('NFKC', n) if n == netloc2: return for c in '/?#@:': if c in netloc2: raise ValueError("netloc '" + netloc + "' contains invalid " + "characters under NFKC normalization")
0
Python
CWE-522
Insufficiently Protected Credentials
The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval.
https://cwe.mitre.org/data/definitions/522.html
vulnerable
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.post(url, { 'all_students': True, }) self.assertEqual(response.status_code, 200)
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 get_problem_responses(request, course_id): """ Initiate generation of a CSV file containing all student answers to a given problem. Responds with JSON {"status": "... status message ..."} if initiation is successful (or generation task is already running). Responds with BadRequest if problem location is faulty. """ course_key = CourseKey.from_string(course_id) problem_location = request.POST.get('problem_location', '') try: problem_key = UsageKey.from_string(problem_location) # Are we dealing with an "old-style" problem location? run = problem_key.run if not run: problem_key = course_key.make_usage_key_from_deprecated_string(problem_location) if problem_key.course_key != course_key: raise InvalidKeyError(type(problem_key), problem_key) except InvalidKeyError: return JsonResponseBadRequest(_("Could not find problem with this location.")) try: instructor_task.api.submit_calculate_problem_responses_csv(request, course_key, problem_location) success_status = _( "The problem responses report is being created." " To view the status of the report, see Pending Tasks below." ) return JsonResponse({"status": success_status}) except AlreadyRunningError: already_running_status = _( "A problem responses report generation task is already in progress. " "Check the 'Pending Tasks' table for the status of the task. " "When completed, the report will be available for download in the table below." ) return JsonResponse({"status": already_running_status})
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_post_broken_body(): response = client.post("/items/", data={"name": "Foo", "price": 50.5}) assert response.status_code == 422, response.text assert response.json() == { "detail": [ { "ctx": { "colno": 1, "doc": "name=Foo&price=50.5", "lineno": 1, "msg": "Expecting value", "pos": 0, }, "loc": ["body", 0], "msg": "Expecting value: line 1 column 1 (char 0)", "type": "value_error.jsondecode", } ] } with patch("json.loads", side_effect=Exception): response = client.post("/items/", json={"test": "test2"}) assert response.status_code == 400, response.text assert response.json() == {"detail": "There was an error parsing the body"}
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 last_modified(self): last = max([ os.path.getmtime(os.path.join(self._filesystem_path, filename)) for filename in os.listdir(self._filesystem_path)] or [0]) return time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.gmtime(last))
1
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 Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
safe
def test_received_headers_finished_expect_continue_true_sent_true(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.expect_continue = True preq.headers_finished = True preq.completed = False preq.empty = False inst.sent_continue = True inst.received(b"GET / HTTP/1.1\r\n\r\n") self.assertEqual(inst.request, preq) self.assertEqual(inst.server.tasks, []) self.assertEqual(sock.sent, b"") self.assertEqual(inst.sent_continue, True) self.assertEqual(preq.completed, False)
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def test_filelike_http11(self): to_send = "GET /filelike HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) ct = headers["content-type"] self.assertEqual(ct, "image/jpeg") self.assertTrue(b"\377\330\377" in response_body)
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def request(self, method, uri, headers=None, bodyProducer=None): """ Issue a request to the server indicated by the given C{uri}. An existing connection from the connection pool may be used or a new one may be created. I{HTTP} and I{HTTPS} schemes are supported in C{uri}. @see: L{twisted.web.iweb.IAgent.request} """ uri = _ensureValidURI(uri.strip()) parsedURI = URI.fromBytes(uri) try: endpoint = self._getEndpoint(parsedURI) except SchemeNotSupported: return defer.fail(Failure()) key = (parsedURI.scheme, parsedURI.host, parsedURI.port) return self._requestWithEndpoint(key, endpoint, method, parsedURI, headers, bodyProducer, parsedURI.originForm)
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 setup_db(cls, config_calibre_dir, app_db_path): cls.dispose() if not config_calibre_dir: cls.config.invalidate() return False dbpath = os.path.join(config_calibre_dir, "metadata.db") if not os.path.exists(dbpath): cls.config.invalidate() return False try: cls.engine = create_engine('sqlite://', echo=False, isolation_level="SERIALIZABLE", connect_args={'check_same_thread': False}, poolclass=StaticPool) with cls.engine.begin() as connection: connection.execute(text("attach database '{}' as calibre;".format(dbpath))) connection.execute(text("attach database '{}' as app_settings;".format(app_db_path))) conn = cls.engine.connect() # conn.text_factory = lambda b: b.decode(errors = 'ignore') possible fix for #1302 except Exception as ex: cls.config.invalidate(ex) return False cls.config.db_configured = True if not cc_classes: try: cc = conn.execute(text("SELECT id, datatype FROM custom_columns")) cls.setup_db_cc_classes(cc) except OperationalError as e: log.error_or_exception(e) cls.session_factory = scoped_session(sessionmaker(autocommit=False, autoflush=True, bind=cls.engine)) for inst in cls.instances: inst.initSession() cls._init = True return True
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_after_start_response_http11_close(self): to_send = tobytes( "GET /after_start_response HTTP/1.1\r\nConnection: close\r\n\r\n" ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"], ) self.assertEqual(headers["connection"], "close") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
1
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def google_remote_app(): if "google" not in oauth.remote_apps: oauth.remote_app( "google", base_url="https://www.google.com/accounts/", authorize_url="https://accounts.google.com/o/oauth2/auth?prompt=select_account+consent", request_token_url=None, request_token_params={ "scope": "https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile" }, access_token_url="https://accounts.google.com/o/oauth2/token", access_token_method="POST", consumer_key=settings.GOOGLE_CLIENT_ID, consumer_secret=settings.GOOGLE_CLIENT_SECRET, ) return oauth.google
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 logout(): if current_user is not None and current_user.is_authenticated: ub.delete_user_session(current_user.id, flask_session.get('_id',"")) logout_user() if feature_support['oauth'] and (config.config_login_type == 2 or config.config_login_type == 3): logout_oauth_user() log.debug(u"User logged out") return redirect(url_for('web.login'))
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_reactor(self): """Apply the blacklisting reactor and ensure it properly blocks connections to particular domains and IPs. """ agent = Agent( BlacklistingReactorWrapper( self.reactor, ip_whitelist=self.ip_whitelist, ip_blacklist=self.ip_blacklist, ), ) # The unsafe domains and IPs should be rejected. for domain in (self.unsafe_domain, self.unsafe_ip): self.failureResultOf( agent.request(b"GET", b"http://" + domain), DNSLookupError ) self.reactor.tcpClients = [] # The safe domains IPs should be accepted. for domain in ( self.safe_domain, self.allowed_domain, self.safe_ip, self.allowed_ip, ): agent.request(b"GET", b"http://" + domain) # Grab the latest TCP connection. ( host, port, client_factory, _timeout, _bindAddress, ) = self.reactor.tcpClients.pop()
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_disable_user_invalidates_token(self): from keystoneclient import exceptions as client_exceptions admin_client = self.get_client(admin=True) foo_client = self.get_client(self.user_foo) admin_client.users.update_enabled(user=self.user_foo['id'], enabled=False) self.assertRaises(client_exceptions.Unauthorized, foo_client.tokens.authenticate, token=foo_client.auth_token) self.assertRaises(client_exceptions.Unauthorized, self.get_client, self.user_foo)
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 list_instructor_tasks(request, course_id): """ List instructor tasks. Takes optional query paremeters. - With no arguments, lists running tasks. - `problem_location_str` lists task history for problem - `problem_location_str` and `unique_student_identifier` lists task history for problem AND student (intersection) """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) problem_location_str = strip_if_string(request.POST.get('problem_location_str', False)) student = request.POST.get('unique_student_identifier', None) if student is not None: student = get_student_from_identifier(student) if student and not problem_location_str: return HttpResponseBadRequest( "unique_student_identifier must accompany problem_location_str" ) if problem_location_str: try: module_state_key = course_id.make_usage_key_from_deprecated_string(problem_location_str) except InvalidKeyError: return HttpResponseBadRequest() if student: # Specifying for a single student's history on this problem tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key, student) else: # Specifying for single problem's history tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key) else: # If no problem or student, just get currently running tasks tasks = instructor_task.api.get_running_instructor_tasks(course_id) response_payload = { 'tasks': map(extract_task_features, tasks), } return JsonResponse(response_payload)
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 __init__(self, crawler, splash_base_url, slot_policy, log_400): self.crawler = crawler self.splash_base_url = splash_base_url self.slot_policy = slot_policy self.log_400 = log_400 self.crawler.signals.connect(self.spider_opened, signals.spider_opened)
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 _decompress(compressed_path: Text, target_path: Text) -> None: with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists
0
Python
CWE-23
Relative Path Traversal
The software uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def filter(self, names): for name in [_hkey(n) for n in names]: if name in self.dict: del self.dict[name]
0
Python
CWE-93
Improper Neutralization of CRLF Sequences ('CRLF Injection')
The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.
https://cwe.mitre.org/data/definitions/93.html
vulnerable
def test_get_student_exam_results(self): """ Test whether get_proctored_exam_results returns an appropriate status message when users request a CSV file. """ url = reverse( 'get_proctored_exam_results', kwargs={'course_id': unicode(self.course.id)} ) # Successful case: response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertNotIn('currently being created', res_json['status']) # CSV generation already in progress: with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('currently being created', res_json['status'])
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 feed_booksindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Books.sort, 1, 1)).label('id'))\ .filter(calibre_db.common_filters()).group_by(func.upper(func.substr(db.Books.sort, 1, 1))).all() elements = [] if off == 0: elements.append({'id': "00", 'name':_("All")}) shift = 1 for entry in entries[ off + shift - 1: int(off + int(config.config_books_per_page) - shift)]: elements.append({'id': entry.id, 'name': entry.id}) pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, len(entries) + 1) return render_xml_template('feed.xml', letterelements=elements, folder='opds.feed_letter_books', 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 __getattr__(self, attr: str) -> Any: # Passthrough to the real reactor except for the DNS resolver. return getattr(self._reactor, attr)
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 convert_bookformat(book_id): # check to see if we have form fields to work with - if not send user back book_format_from = request.form.get('book_format_from', None) book_format_to = request.form.get('book_format_to', None) if (book_format_from is None) or (book_format_to is None): flash(_(u"Source or destination format for conversion missing"), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id)) log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to) rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(), book_format_to.upper(), current_user.name) if rtn is None: flash(_(u"Book successfully queued for converting to %(book_format)s", book_format=book_format_to), category="success") else: flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error") return redirect(url_for('editbook.edit_book', book_id=book_id))
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
bool AveragePool(const float* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int kwidth, int kheight, float* output_data, const Dims<4>& output_dims) { float output_activation_min, output_activation_max; GetActivationMinMax(Ac, &output_activation_min, &output_activation_max); return AveragePool(input_data, input_dims, stride_width, stride_height, pad_width, pad_height, kwidth, kheight, output_activation_min, output_activation_max, output_data, output_dims); }
1
Python
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
safe
def extract_messages(obj_list): """ Extract "messages" from a list of exceptions or other objects. For ValidationErrors, `messages` are flattened into the output. For Exceptions, `args[0]` is added into the output. For other objects, `force_text` is called. :param obj_list: List of exceptions etc. :type obj_list: Iterable[object] :rtype: Iterable[str] """ for obj in obj_list: if isinstance(obj, ValidationError): for msg in obj.messages: yield force_text(msg) continue if isinstance(obj, Exception): if len(obj.args): yield force_text(obj.args[0]) continue yield force_text(obj)
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_received_chunk_not_properly_terminated(self): from waitress.utilities import BadRequest buf = DummyBuffer() inst = self._makeOne(buf) data = b"4\r\nWikibadchunk\r\n" result = inst.received(data) self.assertEqual(result, len(data)) self.assertEqual(inst.completed, False) self.assertEqual(buf.data[0], b"Wiki") self.assertEqual(inst.error.__class__, BadRequest)
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def testSpoofedHeadersDropped(self): data = ( b"GET /foobar HTTP/8.4\r\n" b"x-auth_user: bob\r\n" b"content-length: 6\r\n" b"\r\n" b"Hello." ) self.feed(data) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.headers, {"CONTENT_LENGTH": "6",})
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def test_rescore_problem_all(self, act): """ Test rescoring for all students. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
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 generate_subparsers(root, parent_parser, definitions): action_dest = '_'.join(parent_parser.prog.split()[1:] + ['action']) actions = parent_parser.add_subparsers( dest=action_dest ) for command, properties in definitions.items(): is_subparser = isinstance(properties, dict) descr = properties.pop('help', None) if is_subparser else properties.pop(0) command_parser = actions.add_parser(command, description=descr) command_parser.root = root if is_subparser: generate_subparsers(root, command_parser, properties) continue for argument in properties: command_parser.add_argument(**argument)
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 fetch_file(self, in_path, out_path): ''' fetch a file from chroot to local ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot) try: p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None) except OSError: raise errors.AnsibleError("chroot connection requires dd command in the jail") with open(out_path, 'wb+') as out_file: try: for chunk in p.stdout.read(BUFSIZE): out_file.write(chunk) except: traceback.print_exc() raise errors.AnsibleError("failed to transfer file %s to %s" % (in_path, out_path)) stdout, stderr = p.communicate() if p.returncode != 0: raise errors.AnsibleError("failed to transfer file %s to %s:\n%s\n%s" % (in_path, out_path, stdout, stderr))
1
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
safe
def test_level_as_none(self): body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=0, col_offset=0)] mod = ast.Module(body) code = compile(mod, 'test', 'exec') ns = {} exec(code, ns) self.assertIn('sleep', ns)
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 test_filename(self): tmpname = mktemp('', 'mmap') fp = memmap(tmpname, dtype=self.dtype, mode='w+', shape=self.shape) abspath = os.path.abspath(tmpname) fp[:] = self.data[:] self.assertEqual(abspath, fp.filename) b = fp[:1] self.assertEqual(abspath, b.filename) del b del fp os.unlink(tmpname)
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_module(self): body = [ast.Num(42)] x = ast.Module(body, []) self.assertEqual(x.body, body)
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 sync_tree(self): LOGGER.info("sync tree to host") self.transfer_inst.tree.remote(self.tree_, role=consts.HOST, idx=-1) """ federation.remote(obj=self.tree_, name=self.transfer_inst.tree.name, tag=self.transfer_inst.generate_transferid(self.transfer_inst.tree), role=consts.HOST, idx=-1) """
0
Python
CWE-668
Exposure of Resource to Wrong Sphere
The product exposes a resource to the wrong control sphere, providing unintended actors with inappropriate access to the resource.
https://cwe.mitre.org/data/definitions/668.html
vulnerable
def kebab_case(value: str) -> str: return stringcase.spinalcase(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 cookies(self, jar: RequestsCookieJar): # <https://docs.python.org/3/library/cookielib.html#cookie-objects> stored_attrs = ['value', 'path', 'secure', 'expires'] self['cookies'] = {} for cookie in jar: self['cookies'][cookie.name] = { attname: getattr(cookie, attname) for attname in stored_attrs }
0
Python
CWE-200
Exposure of Sensitive Information to an Unauthorized Actor
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
https://cwe.mitre.org/data/definitions/200.html
vulnerable
def test_recursive_tf_function_with_gradients(self): @def_function.function def recursive_fn(n, x): if n > 0: return n * recursive_fn(n - 1, x) else: return x x = variables.Variable(1.0) with backprop.GradientTape() as tape: g = recursive_fn(5, x) dg_dx = tape.gradient(g, x) self.assertEqual(dg_dx.numpy(), 120)
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 last_modified(self): modification_time = time.gmtime(os.path.getmtime(self._path)) return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)
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 Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
vulnerable
def test_02_checksecure_simplequote(self): """ U02 | 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 __init__(self, hs): super().__init__(hs) self.http_client = SimpleHttpClient(hs) # We create a blacklisting instance of SimpleHttpClient for contacting identity # servers specified by clients self.blacklisting_http_client = SimpleHttpClient( hs, ip_blacklist=hs.config.federation_ip_range_blacklist ) self.federation_http_client = hs.get_http_client() self.hs = 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
async def hidden(self, ctx: commands.Context, true_or_false: Optional[bool] = True): """Hide or unhide a voicechannel you own.""" data = await self.config.guild(ctx.guild).pchannels() try: for key in data: if data[key] == ctx.author.voice.channel.id: ov = { ctx.guild.default_role: discord.PermissionOverwrite( view_channel=False, connect=False ), ctx.author: discord.PermissionOverwrite( view_channel=True, connect=True, speak=True, manage_channels=True ), } if self.invoiceConfig: ov[ ctx.guild.get_role( await self.invoiceConfig.channel(ctx.author.voice.channel).role() ) ] = discord.PermissionOverwrite( view_channel=True, connect=True, speak=True ) await ctx.author.voice.channel.edit(overwrites=ov) await ctx.tick() await ctx.send(_("VC has been hidden successfully.")) except AttributeError: return await ctx.send(_("You need to be in a VC to do this."))
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_module_traversal(self): t = self.folder.z # Need to reset to the standard security policy so AccessControl # checks are actually performed. The test setup initializes # a policy that circumvents those checks. SecurityManager.setSecurityPolicy(self.oldPolicy) noSecurityManager() # The getSecurityManager function is explicitly allowed content = ('<p tal:define="a nocall:%s"' ' tal:content="python: a().getUser().getUserName()"/>') t.write(content % 'modules/AccessControl/getSecurityManager') self.assertEqual(t(), '<p>Anonymous User</p>') # Anything else should be unreachable and raise NotFound: # Direct access through AccessControl t.write('<p tal:define="a nocall:modules/AccessControl/users"/>') with self.assertRaises(NotFound): t() # Indirect access through an intermediary variable content = ('<p tal:define="mod nocall:modules/AccessControl;' ' must_fail nocall:mod/users"/>') t.write(content) with self.assertRaises(NotFound): t() # Indirect access through an intermediary variable and a dictionary content = ('<p tal:define="mod nocall:modules/AccessControl;' ' a_dict python: {\'unsafe\': mod};' ' must_fail nocall: a_dict/unsafe/users"/>') t.write(content) with self.assertRaises(NotFound): t()
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 the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
def test_list(self): self.user.session_set.create(session_key='ABC123', ip='127.0.0.1', expire_date=datetime.now() + timedelta(days=1), user_agent='Firefox') response = self.client.get(reverse('user_sessions:session_list')) self.assertContains(response, 'Active Sessions') self.assertContains(response, 'End Session', 3) self.assertContains(response, 'Firefox')
0
Python
CWE-326
Inadequate Encryption Strength
The software stores or transmits sensitive data using an encryption scheme that is theoretically sound, but is not strong enough for the level of protection required.
https://cwe.mitre.org/data/definitions/326.html
vulnerable
def __init__(self, repository, key, manifest, path=None, sync=True, warn_if_unencrypted=True): self.lock = None self.timestamp = None self.txn_active = False self.repository = repository self.key = key self.manifest = manifest self.path = path or os.path.join(get_cache_dir(), hexlify(repository.id).decode('ascii')) if not os.path.exists(self.path): if warn_if_unencrypted and isinstance(key, PlaintextKey): if 'ATTIC_UNKNOWN_UNENCRYPTED_REPO_ACCESS_IS_OK' not in os.environ: print("""Warning: Attempting to access a previously unknown unencrypted repository\n""", file=sys.stderr) answer = input('Do you want to continue? [yN] ') if not (answer and answer in 'Yy'): raise self.CacheInitAbortedError() self.create() self.open() if sync and self.manifest.id != self.manifest_id: # If repository is older than the cache something fishy is going on if self.timestamp and self.timestamp > manifest.timestamp: raise self.RepositoryReplay() # Make sure an encrypted repository has not been swapped for an unencrypted repository if self.key_type is not None and self.key_type != str(key.TYPE): raise self.EncryptionMethodMismatch() self.sync() self.commit()
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 security_group_count_by_project(context, project_id): """Count number of security groups in a project.""" return IMPL.security_group_count_by_project(context, project_id)
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 pref_get(key): if get_user() is None: return "Authentication required", 401 if key in get_preferences(): return Response(json.dumps({'key': key, 'value': get_preferences()[key]})) else: return Response(json.dumps({'key': key, 'error': 'novalue'}))
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_unicorn_render_kwarg(): token = Token( TokenType.TEXT, "unicorn 'tests.templatetags.test_unicorn_render.FakeComponentKwargs' test_kwarg='tested!'", ) unicorn_node = unicorn(None, token) context = {} actual = unicorn_node.render(context) assert "->tested!<-" in actual
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_header_lines(header): """ Splits the header into lines, putting multi-line headers together. """ r = [] lines = header.split(b"\n") for line in lines: if line.startswith((b" ", b"\t")): if not r: # https://corte.si/posts/code/pathod/pythonservers/index.html raise ParsingError('Malformed header line "%s"' % tostr(line)) r[-1] += line else: r.append(line) return 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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def test_request_body_too_large_with_wrong_cl_http11(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\n" "Content-Length: 5\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") # first request succeeds (content-length 5) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # second response is an error response line, headers, response_body = read_http(fp) self.assertline(line, "431", "Request Header Fields Too Large", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def parse_soap_enveloped_saml_thingy(text, expected_tags): """Parses a SOAP enveloped SAML thing and returns the thing as a string. :param text: The SOAP object as XML string :param expected_tags: What the tag of the SAML thingy is expected to be. :return: SAML thingy as a string """ envelope = ElementTree.fromstring(text) # Make sure it's a SOAP message assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 body = None for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 body = part break if body is None: return "" saml_part = body[0] if saml_part.tag in expected_tags: return ElementTree.tostring(saml_part, encoding="UTF-8") else: raise WrongMessageType("Was '%s' expected one of %s" % (saml_part.tag, expected_tags))
0
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
vulnerable
def _decode_xsrf_token(self, cookie): m = _signed_value_version_re.match(utf8(cookie)) if m: version = int(m.group(1)) if version == 2: _, mask, masked_token, timestamp = cookie.split("|") mask = binascii.a2b_hex(utf8(mask)) token = _websocket_mask( mask, binascii.a2b_hex(utf8(masked_token))) timestamp = int(timestamp) return version, token, timestamp else: # Treat unknown versions as not present instead of failing. return None, None, None elif len(cookie) == 32: version = 1 token = binascii.a2b_hex(cookie) # We don't have a usable timestamp in older versions. timestamp = int(time.time()) return (version, token, timestamp) else: return None, None, None
1
Python
CWE-203
Observable Discrepancy
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
https://cwe.mitre.org/data/definitions/203.html
safe
def test_get_problem_responses_already_running(self): """ Test whether get_problem_responses returns an appropriate status message if CSV generation is already in progress. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) with patch('instructor_task.api.submit_calculate_problem_responses_csv') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.post(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('already in progress', res_json['status'])
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_patch_bot_role(self) -> None: self.login("desdemona") email = "[email protected]" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_success(result) user_profile = self.get_bot_user(email) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) # Test for not allowing a non-owner user to make assign a bot an owner role desdemona = self.example_user("desdemona") do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_OWNER) result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization owner") result = self.client_patch(f"/json/bots/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization owner") # Test for not allowing a non-administrator user to assign a bot an administrator role shiva = self.example_user("shiva") self.assertEqual(shiva.role, UserProfile.ROLE_MODERATOR) self.login_user(shiva) do_change_bot_owner(user_profile, shiva, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_ADMINISTRATOR) result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization administrator") result = self.client_patch(f"/json/bots/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization administrator")
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 test_parse_header_bad_content_length(self): data = b"GET /foobar HTTP/8.4\ncontent-length: abc" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv, None)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def 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_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False))
1
Python
CWE-787
Out-of-bounds Write
The software writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
def connectionLost(self, reason = connectionDone) -> None: # If the maximum size was already exceeded, there's nothing to do. if self.deferred.called: return if reason.check(ResponseDone): self.deferred.callback(self.stream.getvalue()) elif reason.check(PotentialDataLoss): # stolen from https://github.com/twisted/treq/pull/49/files # http://twistedmatrix.com/trac/ticket/4840 self.deferred.callback(self.stream.getvalue()) else: self.deferred.errback(reason)
0
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
vulnerable
def __enter__(self): for k, v in self.values.items(): self.old_values[k] = os.environ.get(k) os.environ[k] = v
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 resolveHostName( self, recv: IResolutionReceiver, hostname: str, portNumber: int = 0
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 format_datetime(self, data): """ A hook to control how datetimes are formatted. Can be overridden at the ``Serializer`` level (``datetime_formatting``) or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``). Default is ``iso-8601``, which looks like "2010-12-16T03:02:14". """ if self.datetime_formatting == 'rfc-2822': return format_datetime(data) return data.isoformat()
0
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def get_cc_columns(filter_config_custom_read=False): tmpcc = calibre_db.session.query(db.Custom_Columns)\ .filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() cc = [] r = None if config.config_columns_to_ignore: r = re.compile(config.config_columns_to_ignore) for col in tmpcc: if filter_config_custom_read and config.config_read_column and config.config_read_column == col.id: continue if r and r.match(col.name): continue cc.append(col) return 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 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 modify_identifiers(input_identifiers, db_identifiers, db_session): """Modify Identifiers to match input information. input_identifiers is a list of read-to-persist Identifiers objects. db_identifiers is a list of already persisted list of Identifiers objects.""" changed = False error = False input_dict = dict([(identifier.type.lower(), identifier) for identifier in input_identifiers]) if len(input_identifiers) != len(input_dict): error = True db_dict = dict([(identifier.type.lower(), identifier) for identifier in db_identifiers ]) # delete db identifiers not present in input or modify them with input val for identifier_type, identifier in db_dict.items(): if identifier_type not in input_dict.keys(): db_session.delete(identifier) changed = True else: input_identifier = input_dict[identifier_type] identifier.type = input_identifier.type identifier.val = input_identifier.val # add input identifiers not present in db for identifier_type, identifier in input_dict.items(): if identifier_type not in db_dict.keys(): db_session.add(identifier) changed = True return changed, error
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_posix_dirs_inaccessible(self): """ test if new dir is created if both implicit dirs are not valid""" tmpdir = tempfile.mkdtemp() try: d_dir = catalog.default_dir_posix(tmpdir) try: os.chmod(d_dir, 0o000) except OSError: raise KnownFailureTest("Can't change permissions of default_dir.") d_dir2 = catalog.default_dir_posix(tmpdir) try: os.chmod(d_dir2, 0o000) except OSError: raise KnownFailureTest("Can't change permissions of default_dir.") new_ddir = catalog.default_dir_posix(tmpdir) assert_(not (os.path.samefile(new_ddir, d_dir) or os.path.samefile(new_ddir, d_dir2))) new_ddir2 = catalog.default_dir_posix(tmpdir) assert_(os.path.samefile(new_ddir, new_ddir2)) finally: os.chmod(d_dir, 0o700) os.chmod(d_dir2, 0o700) remove_tree(tmpdir)
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 connect(self, port=None): ''' connect to the chroot; nothing to do here ''' vvv("THIS IS A LOCAL CHROOT DIR", host=self.jail) return self
0
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
vulnerable
def test_modify_access_revoke(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'revoke', }) self.assertEqual(response.status_code, 200)
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) 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 jstree_data(node, selected_node): result = [] result.append('{') result.append('"text": "{}",'.format(node.label)) result.append( '"state": {{ "opened": true, "selected": {} }},'.format( 'true' if node == selected_node else 'false' ) ) result.append( '"data": {{ "href": "{}" }},'.format(node.get_absolute_url()) ) children = node.get_children().order_by('label',) if children: result.append('"children" : [') for child in children: result.extend(jstree_data(node=child, selected_node=selected_node)) result.append(']') result.append('},') return result
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 connectionLost(self, reason = connectionDone) -> None: # If the maximum size was already exceeded, there's nothing to do. if self.deferred.called: return if reason.check(ResponseDone): self.deferred.callback(self.stream.getvalue()) elif reason.check(PotentialDataLoss): # stolen from https://github.com/twisted/treq/pull/49/files # http://twistedmatrix.com/trac/ticket/4840 self.deferred.callback(self.stream.getvalue()) else: self.deferred.errback(reason)
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_asyncdef(self): tree = self.parse(asyncdef) self.assertEqual(tree.body[0].type_comment, "() -> int") self.assertEqual(tree.body[1].type_comment, "() -> int") tree = self.classic_parse(asyncdef) self.assertEqual(tree.body[0].type_comment, None) self.assertEqual(tree.body[1].type_comment, None)
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 send_mail(book_id, book_format, convert, kindle_mail, calibrepath, user_id): """Send email with attachments""" book = calibre_db.get_book(book_id) if convert == 1: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'epub', book_format.lower(), user_id, kindle_mail) if convert == 2: # returns None if success, otherwise errormessage return convert_book_format(book_id, calibrepath, u'azw3', book_format.lower(), user_id, kindle_mail) for entry in iter(book.data): if entry.format.upper() == book_format.upper(): converted_file_name = entry.name + '.' + book_format.lower() link = '<a href="{}">{}</a>'.format(url_for('web.show_book', book_id=book_id), escape(book.title)) EmailText = _(u"%(book)s send to Kindle", book=link) WorkerThread.add(user_id, TaskEmail(_(u"Send to Kindle"), book.path, converted_file_name, config.get_mail_settings(), kindle_mail, EmailText, _(u'This e-mail has been sent via Calibre-Web.'))) return return _(u"The requested file could not be read. Maybe wrong permissions?")
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_content_length_too_large(self): self.request.headers['Content-Length'] = MAX_REQUEST_BODY_SIZE + 1 self.request.body = "0" * (MAX_REQUEST_BODY_SIZE + 1) self.assertRaises(exception.RequestTooLarge, self.request.get_response, self.middleware)
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 test_reactor(self): """Apply the blacklisting reactor and ensure it properly blocks connections to particular domains and IPs. """ agent = Agent( BlacklistingReactorWrapper( self.reactor, ip_whitelist=self.ip_whitelist, ip_blacklist=self.ip_blacklist, ), ) # The unsafe domains and IPs should be rejected. for domain in (self.unsafe_domain, self.unsafe_ip): self.failureResultOf( agent.request(b"GET", b"http://" + domain), DNSLookupError ) self.reactor.tcpClients = [] # The safe domains IPs should be accepted. for domain in ( self.safe_domain, self.allowed_domain, self.safe_ip, self.allowed_ip, ): agent.request(b"GET", b"http://" + domain) # Grab the latest TCP connection. ( host, port, client_factory, _timeout, _bindAddress, ) = self.reactor.tcpClients.pop()
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_reset_student_attempts_single(self): """ Test reset single student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # make sure problem attempts have been reset. changed_module = StudentModule.objects.get(pk=self.module_to_reset.pk) self.assertEqual( json.loads(changed_module.state)['attempts'], 0 )
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_exchange_revoked_invite(self): user_id = self.register_user("kermit", "test") tok = self.login("kermit", "test") room_id = self.helper.create_room_as(room_creator=user_id, tok=tok) # Send a 3PID invite event with an empty body so it's considered as a revoked one. invite_token = "sometoken" self.helper.send_state( room_id=room_id, event_type=EventTypes.ThirdPartyInvite, state_key=invite_token, body={}, tok=tok, ) d = self.handler.on_exchange_third_party_invite_request( room_id=room_id, event_dict={ "type": EventTypes.Member, "room_id": room_id, "sender": user_id, "state_key": "@someone:example.org", "content": { "membership": "invite", "third_party_invite": { "display_name": "alice", "signed": { "mxid": "@alice:localhost", "token": invite_token, "signatures": { "magic.forest": { "ed25519:3": "fQpGIW1Snz+pwLZu6sTy2aHy/DYWWTspTJRPyNp0PKkymfIsNffysMl6ObMMFdIJhk6g6pwlIqZ54rxo8SLmAg" } }, }, }, }, }, ) failure = self.get_failure(d, AuthError).value self.assertEqual(failure.code, 403, failure) self.assertEqual(failure.errcode, Codes.FORBIDDEN, failure) self.assertEqual(failure.msg, "You are not invited to this room.")
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 parse(source, filename='<unknown>', mode='exec', feature_version=LATEST_MINOR_VERSION): """ Parse the source into an AST node including type comments. Similar to compile(source, filename, mode, PyCF_ONLY_AST). Set feature_version to limit the syntax parsed to that minor version of Python 3. For example, feature_version=5 will prevent new syntax features from Python 3.6+ from being used, such as fstrings. Currently only fully supported for Python 3.5+ with partial support for Python 3.4. So, feature_version=3 or less are all equivalent to feature_version=4. When feature_version=4, the parser will forbid the use of the async/await keywords and the '@' operator, but will not forbid the use of PEP 448 additional unpacking generalizations, which were also added in Python 3.5. When feature_version>=7, 'async' and 'await' are always keywords. """ return _ast3._parse(source, filename, mode, feature_version)
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 _test_mapping_file_plain(self): def unichrs(s): return ''.join(chr(int(x, 16)) for x in s.split('+')) urt_wa = {} with self.open_mapping_file() as f: for line in f: if not line: break data = line.split('#')[0].split() if len(data) != 2: continue if data[0][:2] != '0x': self.fail(f"Invalid line: {line!r}") csetch = bytes.fromhex(data[0][2:]) if len(csetch) == 1 and 0x80 <= csetch[0]: continue unich = unichrs(data[1]) if ord(unich) == 0xfffd or unich in urt_wa: continue urt_wa[unich] = csetch self._testpoint(csetch, unich)
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_bad_host_header(self): # https://corte.si/posts/code/pathod/pythonservers/index.html to_send = "GET / HTTP/1.0\r\n Host: 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, "400", "Bad Request", "HTTP/1.0") self.assertEqual(headers.get("server"), "waitress") self.assertTrue(headers.get("date"))
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 those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.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(): entries = ub.session.query(ub.User, func.count(ub.Downloads.book_id).label('count'))\ .join(ub.Downloads).group_by(ub.Downloads.user_id).order_by(order).all() charlist = ub.session.query(func.upper(func.substr(ub.User.name, 1, 1)).label('char')) \ .filter(ub.User.role.op('&')(constants.ROLE_ANONYMOUS) != constants.ROLE_ANONYMOUS) \ .group_by(func.upper(func.substr(ub.User.name, 1, 1))).all() return render_title_template('list.html', entries=entries, folder='web.books_list', charlist=charlist, title=_(u"Downloads"), page="downloadlist", data="download", order=order_no) else: abort(404)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def main(srcfile, dump_module=False): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) auto_gen_msg = common_msg % argv0 mod = asdl.parse(srcfile) if dump_module: print('Parsed Module:') print(mod) if not asdl.check(mod): sys.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) f = open(p, "w") f.write(auto_gen_msg) f.write('#include "asdl.h"\n\n') c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) f.write("PyObject* Ta3AST_mod2obj(mod_ty t);\n") f.write("mod_ty Ta3AST_obj2mod(PyObject* ast, PyArena* arena, int mode);\n") f.write("int Ta3AST_Check(PyObject* obj);\n") f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") f = open(p, "w") f.write(auto_gen_msg) f.write('#include <stddef.h>\n') f.write('\n') f.write('#include "Python.h"\n') f.write('#include "%s-ast.h"\n' % mod.name) f.write('\n') f.write("static PyTypeObject AST_type;\n") v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), Obj2ModPrototypeVisitor(f), FunctionVisitor(f), ObjVisitor(f), Obj2ModVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
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