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_quotas_update_as_admin(self): body = {'quota_set': {'instances': 50, 'cores': 50, 'ram': 51200, 'volumes': 10, 'gigabytes': 1000, 'floating_ips': 10, 'metadata_items': 128, 'injected_files': 5, 'injected_file_content_bytes': 10240}} req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me', use_admin_context=True) res_dict = self.controller.update(req, 'update_me', body) self.assertEqual(res_dict, body)
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_content_length_acceptable(self): self.request.headers['Content-Length'] = MAX_REQUEST_BODY_SIZE self.request.body = "0" * MAX_REQUEST_BODY_SIZE response = self.request.get_response(self.middleware) self.assertEqual(response.status_int, 200)
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 setUp(self): shape = (2, 4, 3) rand = np.random.random self.x = rand(shape) + rand(shape).astype(np.complex)*1j self.x[0,:, 1] = [nan, inf, -inf, nan] self.dtype = self.x.dtype self.filename = tempfile.mktemp()
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 expr(self, node, msg=None, *, exc=ValueError): mod = ast.Module([ast.Expr(node)]) self.mod(mod, msg, exc=exc)
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 load_djpeg(self): # ALTERNATIVE: handle JPEGs via the IJG command line utilities import tempfile, os file = tempfile.mktemp() os.system("djpeg %s >%s" % (self.filename, file)) try: self.im = Image.core.open_ppm(file) finally: try: os.unlink(file) except: pass self.mode = self.im.mode self.size = self.im.size self.tile = []
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 tearDown(self): if os.path.isfile(self.filename): os.unlink(self.filename)
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 async_run(self, args): pid = os.fork() if pid: os.waitpid(pid, 0) else: dpid = os.fork() if not dpid: self.debug_log("Running %s" % " ".join(pipes.quote(a) for a in args)) proc = Popen(args, stdin=PIPE, stdout=PIPE, stderr=PIPE) (out, err) = proc.communicate() rv = proc.wait() if rv != 0: self.logger.error("Trigger: Error running %s (%s): %s" % (args[0], rv, err)) elif err: self.debug_log("Trigger: Error: %s" % err) os._exit(0)
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 test_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_start_response HTTP/1.1\n" "Connection: close\n\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)
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_received_error_from_parser(self): from waitress.utilities import BadRequest data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 garbage """ # header result = self.parser.received(data) # body result = self.parser.received(data[result:]) self.assertEqual(result, 8) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, BadRequest))
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 _checkPolkitPrivilege(self, sender, conn, privilege): # from jockey """ Verify that sender has a given PolicyKit privilege. sender is the sender's (private) D-BUS name, such as ":1:42" (sender_keyword in @dbus.service.methods). conn is the dbus.Connection object (connection_keyword in @dbus.service.methods). privilege is the PolicyKit privilege string. This method returns if the caller is privileged, and otherwise throws a PermissionDeniedByPolicy exception. """ if sender is None and conn is None: # called locally, not through D-BUS return if not self.enforce_polkit: # that happens for testing purposes when running on the session # bus, and it does not make sense to restrict operations here return # query PolicyKit self._initPolkit() try: # we don't need is_challenge return here, since we call with AllowUserInteraction (is_auth, _, details) = self.polkit.CheckAuthorization( ('system-bus-name', {'name': dbus.String(sender, variant_level=1)}), privilege, {'': ''}, dbus.UInt32(1), '', timeout=3000) except dbus.DBusException as e: if e._dbus_error_name == 'org.freedesktop.DBus.Error.ServiceUnknown': # polkitd timed out, connect again self.polkit = None return self._checkPolkitPrivilege(sender, conn, privilege) else: raise if not is_auth: raise PermissionDeniedByPolicy(privilege)
1
Python
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
def auth_type(self): return self.appbuilder.get_app.config["AUTH_TYPE"]
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 test_sanitize_content_filename__platform_dependent( filename, win_expected, non_win_expected
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 check_username(username): username = username.strip() if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar(): log.error(u"This username is already taken") raise Exception (_(u"This username is already taken")) return username
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_render_quoting(self): # WARNING: Don't use assertHTMLEqual in that testcase! # assertHTMLEqual will get rid of some escapes which are tested here! w = widgets.AdminURLFieldWidget() self.assertEqual( w.render('test', 'http://example.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://example.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://example.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( w.render('test', 'http://example-äüö.com/<sometag>some text</sometag>'), '<p class="url">Currently: <a href="http://xn--example--7za4pnc.com/%3Csometag%3Esome%20text%3C/sometag%3E">http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://example-äüö.com/&lt;sometag&gt;some text&lt;/sometag&gt;" /></p>' ) self.assertEqual( w.render('test', 'http://www.example.com/%C3%A4"><script>alert("XSS!")</script>"'), '<p class="url">Currently: <a href="http://www.example.com/%C3%A4%22%3E%3Cscript%3Ealert(%22XSS!%22)%3C/script%3E%22">http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;</a><br />Change: <input class="vURLField" name="test" type="url" value="http://www.example.com/%C3%A4&quot;&gt;&lt;script&gt;alert(&quot;XSS!&quot;)&lt;/script&gt;&quot;" /></p>' )
1
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
def setUp(self): super(TestRequestBodySizeLimiter, self).setUp() @webob.dec.wsgify() def fake_app(req): return webob.Response(req.body) self.middleware = middleware.RequestBodySizeLimiter(fake_app) self.request = webob.Request.blank('/', method='POST')
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 request(self, method, request_uri, headers, content): """Modify the request headers to add the appropriate Authorization header.""" headers["authorization"] = ( "Basic " + base64.b64encode("%s:%s" % self.credentials).strip() )
0
Python
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def test_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\r\nTransfer-Encoding: chunked\r\n\r\n" to_send += control_line + s + "\r\n" # garbage in input to_send += "garbage\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) # receiver caught garbage and turned it into a 400 self.assertline(line, "400", "Bad Request", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"] ) self.assertEqual(headers["content-type"], "text/plain") # 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 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() formatter = logging.Formatter(log_format) handler.setFormatter(formatter) root_logger.addHandler(handler) log_level = os.environ.get("SYDENT_TEST_LOG_LEVEL", "ERROR") root_logger.setLevel(log_level)
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 _ensureSnapshotsFolder(self, subdir=None): """ Ensure that the appropriate snapshot folder exists. """ path = ['snapshots', self._snapshot_id] if subdir is not None: path.extend(subdir.split('/')) current = self._tool for element in path: if element not in current.objectIds(): # No Unicode IDs! current._setObject(str(element), Folder(element)) current = current._getOb(element) return current
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_entrance_exam_delete_state_with_staff(self): """ Test entrance exam delete state failure with staff access. """ self.client.logout() staff_user = StaffFactory(course_key=self.course.id) self.client.login(username=staff_user.username, password='test') url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.post(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 403)
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 render(self, name, value, attrs=None): html = super(AdminURLFieldWidget, self).render(name, value, attrs) if value: value = force_text(self._format_value(value)) final_attrs = {'href': mark_safe(smart_urlquote(value))} html = format_html( '<p class="url">{0} <a {1}>{2}</a><br />{3} {4}</p>', _('Currently:'), flatatt(final_attrs), value, _('Change:'), html ) return html
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_modify_access_allow(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_user.email, 'rolename': 'staff', 'action': 'allow', }) 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 content_security_policy(self): # In case we're serving HTML/SVG, confine any Javascript to a unique # origin so it can't interact with the notebook server. return super(NbconvertFileHandler, self).content_security_policy + \ "; sandbox allow-scripts"
1
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
safe
def test_certificates_features_group_by_mode(self): """ Test for certificate csv features against mode. Certificates should be group by 'mode' in reponse. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1) # retrieve the first certificate from the list, there should be 3 certificates for 'honor' mode. certificate = res_json['certificates'][0] self.assertEqual(certificate.get('total_issued_certificate'), 3) self.assertEqual(certificate.get('mode'), 'honor') self.assertEqual(certificate.get('course_id'), str(self.course.id)) # Now generating downloadable certificates with 'verified' mode for __ in xrange(certificate_count): self.generate_certificate( course_id=self.course.id, mode='verified', status=CertificateStatuses.downloadable ) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) # total certificate count should be 2 for 'verified' mode. self.assertEqual(len(res_json['certificates']), 2) # retrieve the second certificate from the list certificate = res_json['certificates'][1] self.assertEqual(certificate.get('total_issued_certificate'), 3) self.assertEqual(certificate.get('mode'), 'verified')
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 setUp(self): _setup_context() super().setUp()
1
Python
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
def runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None): frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def make_homeserver(self, reactor, clock): presence_handler = Mock() presence_handler.set_state.return_value = defer.succeed(None) hs = self.setup_test_homeserver( "red", federation_http_client=None, federation_client=Mock(), presence_handler=presence_handler, ) return hs
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 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 = defusedxml.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))
1
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
def test_modify_access_allow_with_uname(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_instructor.username, 'rolename': 'staff', 'action': 'allow', }) 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 test_request_body_too_large_with_no_cl_http10(self): body = "a" * self.toobig to_send = "GET / HTTP/1.0\r\n\r\n" to_send += body 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", "HTTP/1.0") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # extra bytes are thrown away (no pipelining), connection 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 exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None): ''' run a command on the chroot ''' p = self._buffered_exec_command(cmd, tmp_path, become_user, sudoable, executable, in_data) stdout, stderr = p.communicate() return (p.returncode, '', 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 vote(request, pk): # TODO: check if user has access to this topic/poll poll = get_object_or_404( CommentPoll.objects.unremoved(), pk=pk ) if not request.user.is_authenticated: return redirect_to_login(next=poll.get_absolute_url()) form = PollVoteManyForm(user=request.user, poll=poll, data=request.POST) if form.is_valid(): CommentPollChoice.decrease_vote_count(poll=poll, voter=request.user) form.save_m2m() CommentPollChoice.increase_vote_count(poll=poll, voter=request.user) return redirect(request.POST.get('next', poll.get_absolute_url())) messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', poll.get_absolute_url()))
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def test_rescore_problem_single(self, act): """ Test rescoring of a single student. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
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 setup_passwordless_with_other_nodes(init_node): """ Setup passwordless with other cluster nodes Should fetch the node list from init node, then swap the key """ # Fetch cluster nodes list cmd = "ssh -o StrictHostKeyChecking=no root@{} crm_node -l".format(init_node) rc, out, err = utils.get_stdout_stderr(cmd) if rc != 0: error("Can't fetch cluster nodes list from {}: {}".format(init_node, err)) cluster_nodes_list = [] for line in out.splitlines(): _, node, stat = line.split() if stat == "member": cluster_nodes_list.append(node) # Filter out init node from cluster_nodes_list cmd = "ssh -o StrictHostKeyChecking=no root@{} hostname".format(init_node) rc, out, err = utils.get_stdout_stderr(cmd) if rc != 0: error("Can't fetch hostname of {}: {}".format(init_node, err)) if out in cluster_nodes_list: cluster_nodes_list.remove(out) # Swap ssh public key between join node and other cluster nodes for node in cluster_nodes_list: swap_public_ssh_key(node)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_stopped_typing(self): self.room_members = [U_APPLE, U_BANANA, U_ONION] # Gut-wrenching from synapse.handlers.typing import RoomMember member = RoomMember(ROOM_ID, U_APPLE.to_string()) self.handler._member_typing_until[member] = 1002000 self.handler._room_typing[ROOM_ID] = {U_APPLE.to_string()} self.assertEquals(self.event_source.get_current_key(), 0) self.get_success( self.handler.stopped_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, ) ) self.on_new_event.assert_has_calls([call("typing_key", 1, rooms=[ROOM_ID])]) put_json = self.hs.get_federation_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": False, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, ) self.assertEquals(self.event_source.get_current_key(), 1) events = self.get_success( self.event_source.get_new_events(room_ids=[ROOM_ID], from_key=0) ) self.assertEquals( events[0], [{"type": "m.typing", "room_id": ROOM_ID, "content": {"user_ids": []}}], )
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_after_start_response_http10(self): to_send = "GET /after_start_response 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, "500", "Internal Server Error", "HTTP/1.0") 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)
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_prepare_plugin_docs_command_with_containerization(tmp_path, runtime, mocker): mocker.patch.dict('os.environ', {'HOME': str(tmp_path)}, clear=True) tmp_path.joinpath('.ssh').mkdir() kwargs = { 'private_data_dir': tmp_path, 'process_isolation': True, 'container_image': 'my_container', 'process_isolation_executable': runtime } rc = DocConfig(**kwargs) rc.ident = 'foo' plugin_names = ['copy', 'file'] plugin_type = 'module' rc.prepare_plugin_docs_command(plugin_names, plugin_type=plugin_type, snippet=True, playbook_dir='/tmp/test') assert rc.runner_mode == 'subprocess' extra_container_args = [] if runtime == 'podman': extra_container_args = ['--quiet'] else: extra_container_args = [f'--user={os.getuid()}'] expected_command_start = [ runtime, 'run', '--rm', '--interactive', '--workdir', '/runner/project', '-v', '{}/.ssh/:/home/runner/.ssh/'.format(rc.private_data_dir), '-v', '{}/.ssh/:/root/.ssh/'.format(rc.private_data_dir), ] if runtime == 'podman': expected_command_start.extend(['--group-add=root', '--ipc=host']) expected_command_start.extend([ '-v', '{}/artifacts/:/runner/artifacts/:Z'.format(rc.private_data_dir), '-v', '{}/:/runner/:Z'.format(rc.private_data_dir), '--env-file', '{}/env.list'.format(rc.artifact_dir), ]) expected_command_start.extend(extra_container_args) expected_command_start.extend([ '--name', 'ansible_runner_foo', 'my_container', 'ansible-doc', '-s', '-t', 'module', '--playbook-dir', '/tmp/test', 'copy ' 'file', ]) assert expected_command_start == rc.command
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def testValuesInVariable(self): indices = constant_op.constant([[1]], dtype=dtypes.int64) values = variables.Variable([1], trainable=False, dtype=dtypes.float32) shape = constant_op.constant([1], dtype=dtypes.int64) sp_input = sparse_tensor.SparseTensor(indices, values, shape) sp_output = sparse_ops.sparse_add(sp_input, sp_input) with test_util.force_cpu(): self.evaluate(variables.global_variables_initializer()) output = self.evaluate(sp_output) self.assertAllEqual(output.values, [2])
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 _sqrt(x): if isinstance(x, complex) or x < 0: return cmath.sqrt(x) else: return math.sqrt(x)
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 helper(self): if not self.cached_helper: cached_helper = self.formstyle(self.table, self.vars, self.errors, self.readonly, self.deletable) if self.csrf: cached_helper.append(INPUT(_type='hidden',_name='_formkey', _value=self.formkey)) for key in self.hidden or {}: cached_helper.append(INPUT(_type='hidden',_name=key, _value=self.hidden[key])) self.cached_helper = cached_helper return cached_helper
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 received(self, data): "See IStreamConsumer" rm = self.remain if rm < 1: self.completed = True # Avoid any chance of spinning return 0 datalen = len(data) if rm <= datalen: self.buf.append(data[:rm]) self.remain = 0 self.completed = True return rm else: self.buf.append(data) self.remain -= datalen return datalen
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 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.GET.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})
0
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False, islist=False): ''' return a configuration variable with casting ''' value = _get_config(p, section, key, env_var, default) if boolean: return mk_boolean(value) if value and integer: return int(value) if value and floating: return float(value) if value and islist: return [x.strip() for x in value.split(',')] return value
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
void AveragePool(const uint8* input_data, const Dims<4>& input_dims, int stride, int pad_width, int pad_height, int filter_width, int filter_height, int32 output_activation_min, int32 output_activation_max, uint8* output_data, const Dims<4>& output_dims) { AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width, pad_height, filter_width, filter_height, output_activation_min, output_activation_max, output_data, output_dims); }
0
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
vulnerable
def save(self): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string = json.dumps( obj=self, indent=4, sort_keys=True, ensure_ascii=True, ) self.path.write_text(json_string + '\n', encoding=UTF8)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _cnonce(): dig = _md5( ( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).encode("utf-8") ).hexdigest() return dig[:16]
0
Python
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def test_s3_malicious_tarballs(self): self.assertRaises(exception.Error, self.image_service._test_for_malicious_tarball, "/unused", os.path.join(os.path.dirname(__file__), 'abs.tar.gz')) self.assertRaises(exception.Error, self.image_service._test_for_malicious_tarball, "/unused", os.path.join(os.path.dirname(__file__), 'rel.tar.gz'))
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 prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ pass
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 create_network(self, instance_name, instance, network_info): """Create the LXD container network on the host :param instance_name: nova instance name :param instance: nova instance object :param network_info: instance network configuration object :return:network configuration dictionary """ LOG.debug('create_network called for instance', instance=instance) try: network_devices = {} if not network_info: return for vifaddr in network_info: cfg = self.vif_driver.get_config(instance, vifaddr) network_devices[str(cfg['bridge'])] = \ {'nictype': 'bridged', 'hwaddr': str(cfg['mac_address']), 'parent': str(cfg['bridge']), 'type': 'nic'} return network_devices except Exception as ex: with excutils.save_and_reraise_exception(): LOG.error( _LE('Fail to configure network for %(instance)s: %(ex)s'), {'instance': instance_name, 'ex': ex}, instance=instance)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def __init__(self, repository, key, manifest, path=None, sync=True): 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): 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() self.sync() self.commit()
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 set_user_password(self, context, user_id, user): user_ref = self.update_user(context, user_id, user) try: for token_id in self.token_api.list_tokens(context, user_id): self.token_api.delete_token(context, token_id) except exception.NotImplemented: # The password has been changed but tokens remain valid for # backends that can't list tokens for users LOG.warning('Password changed for %s, but existing tokens remain ' 'valid' % user_id) return user_ref
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_reset_student_attempts_nonsense(self): """ Test failure with both unique_student_identifier and all_students. """ 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, 'all_students': True, }) self.assertEqual(response.status_code, 400)
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def testSizeAndClear(self): with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.float32, name='x') pi = array_ops.placeholder(dtypes.int64) gi = array_ops.placeholder(dtypes.int64) v = 2. * (array_ops.zeros([128, 128]) + x) with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea( [dtypes.float32, dtypes.float32], shapes=[[], [128, 128]], names=['x', 'v']) stage = stager.put(pi, {'x': x, 'v': v}) size = stager.size() clear = stager.clear() G.finalize() with self.session(graph=G) as sess: sess.run(stage, feed_dict={x: -1, pi: 3}) self.assertEqual(sess.run(size), 1) sess.run(stage, feed_dict={x: -1, pi: 1}) self.assertEqual(sess.run(size), 2) sess.run(clear) self.assertEqual(sess.run(size), 0)
0
Python
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
vulnerable
def sql_insert(self, sentence): self.cursor.execute(sentence) self.conn.commit() return True
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_request_login_code(self): response = self.client.post('/accounts-rest/login/', { 'username': self.user.username, 'next': '/private/', }) self.assertEqual(response.status_code, 200) login_code = LoginCode.objects.filter(user=self.user).first() self.assertIsNotNone(login_code) self.assertEqual(login_code.next, '/private/') self.assertEqual(len(mail.outbox), 1) self.assertIn( 'http://testserver/accounts/login/code/?code={}'.format(login_code.code), mail.outbox[0].body, )
0
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
vulnerable
def test_underscore_traversal(self): t = self.folder.t t.write('<p tal:define="p context/__class__" />') with self.assertRaises(NotFound): t() t.write('<p tal:define="p nocall: random/_itertools/repeat"/>') with self.assertRaises(NotFound): t() t.write('<p tal:content="random/_itertools/repeat/foobar"/>') with self.assertRaises(NotFound): t()
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 the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
def test_started_typing_remote_send(self): self.room_members = [U_APPLE, U_ONION] self.get_success( self.handler.started_typing( target_user=U_APPLE, requester=create_requester(U_APPLE), room_id=ROOM_ID, timeout=20000, ) ) put_json = self.hs.get_http_client().put_json put_json.assert_called_once_with( "farm", path="/_matrix/federation/v1/send/1000000", data=_expect_edu_transaction( "m.typing", content={ "room_id": ROOM_ID, "user_id": U_APPLE.to_string(), "typing": True, }, ), json_data_callback=ANY, long_retries=True, backoff_on_404=True, try_trailing_slash_on_400=True, )
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_valid_restricted_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all(): return False 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 guest_only(view_func): # TODO: test! @wraps(view_func) def wrapper(request, *args, **kwargs): if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) return view_func(request, *args, **kwargs) return wrapper
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 CreateID(self): """Create a packet ID. All RADIUS requests have a ID which is used to identify a request. This is used to detect retries and replay attacks. This function returns a suitable random number that can be used as ID. :return: ID number :rtype: integer """ return random.randrange(0, 256)
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_posix(self): """ test if posix default_dir is writable """ d = catalog.default_dir_posix() assert_(catalog.is_writable(d))
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
async def on_send_join_request( self, origin: str, content: JsonDict
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 HEAD(self, path): return self._request('HEAD', path)
0
Python
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
def testFlushFunction_disallowsInvalidWriterInput(self): with context.eager_mode(): with self.assertRaisesRegex(ValueError, 'Invalid argument to flush'): summary_ops.flush(writer=())
1
Python
CWE-475
Undefined Behavior for Input to API
The behavior of this function is undefined unless its control parameter is set to a specific value.
https://cwe.mitre.org/data/definitions/475.html
safe
def whitelist(allow_guest=False, xss_safe=False, methods=None): """ Decorator for whitelisting a function and making it accessible via HTTP. Standard request will be `/api/method/[path.to.method]` :param allow_guest: Allow non logged-in user to access this method. :param methods: Allowed http method to access the method. Use as: @frappe.whitelist() def myfunc(param1, param2): pass """ if not methods: methods = ['GET', 'POST', 'PUT', 'DELETE'] def innerfn(fn): global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func whitelisted.append(fn) allowed_http_methods_for_whitelisted_func[fn] = methods if allow_guest: guest_methods.append(fn) if xss_safe: xss_safe_methods.append(fn) return fn return innerfn
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 testBoostedTreesSparseAggregateStatsSecurity(self): node_ids = [] gradients = [[1.0]] hessians = [[100.0]] feature_indices = [[0, 0, 0]] feature_values = [0, 0, 0] feature_shape = [0, 0, 0] max_splits = 100 num_buckets = 100 with self.assertRaises((errors.InvalidArgumentError, ValueError)): gen_boosted_trees_ops.boosted_trees_sparse_aggregate_stats( node_ids=node_ids, gradients=gradients, hessians=hessians, feature_indices=feature_indices, feature_values=feature_values, feature_shape=feature_shape, 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 DELETE(self, path, body=None, log_request_body=True): return self._request('DELETE', path, body=body, log_request_body=log_request_body)
0
Python
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
vulnerable
def post(self, request): totp_secret = pyotp.random_base32() request.user.totp_secret = totp_secret request.user.totp_status = TOTPStatus.VERIFYING request.user.save() add_2fa.send(sender=self.__class__, user=request.user) return FormattedResponse({"totp_secret": totp_secret})
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 test_rescore_problem_single_from_uname(self, act): """ Test rescoring of a single student. """ url = reverse('rescore_problem', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'problem_to_reset': self.problem_urlname, 'unique_student_identifier': self.student.username, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
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 recovery_parser(xml): parser = XMLParser(recover=True) return parse(BytesIO(xml), parser)
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 test_bad_request(settings): class BadRequestSpider(ResponseSpider): custom_settings = {'HTTPERROR_ALLOW_ALL': True} def start_requests(self): yield SplashRequest(self.url, endpoint='execute', args={'lua_source': DEFAULT_SCRIPT, 'wait': 'bar'}) class GoodRequestSpider(ResponseSpider): custom_settings = {'HTTPERROR_ALLOW_ALL': True} def start_requests(self): yield SplashRequest(self.url, endpoint='execute', args={'lua_source': DEFAULT_SCRIPT}) items, url, crawler = yield crawl_items(BadRequestSpider, HelloWorld, settings) resp = items[0]['response'] assert resp.status == 400 assert resp.splash_response_status == 400 items, url, crawler = yield crawl_items(GoodRequestSpider, Http400Resource, settings) resp = items[0]['response'] assert resp.status == 400 assert resp.splash_response_status == 200
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 set(self, key, value, serialize=True, timeout=0): """ Set a key/value pair in memcache :param key: key :param value: value :param serialize: if True, value is serialized with JSON before sending to memcache, or with pickle if configured to use pickle instead of JSON (to avoid cache poisoning) :param timeout: ttl in memcache """ key = md5hash(key) if timeout > 0: timeout += time.time() flags = 0 if serialize and self._allow_pickle: value = pickle.dumps(value, PICKLE_PROTOCOL) flags |= PICKLE_FLAG elif serialize: value = json.dumps(value) flags |= JSON_FLAG for (server, fp, sock) in self._get_conns(key): try: sock.sendall('set %s %d %d %s noreply\r\n%s\r\n' % \ (key, flags, timeout, len(value), value)) self._return_conn(server, fp, sock) return except Exception, e: self._exception_occurred(server, e)
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 delete(self, location, connection=None): location = location.store_location if not connection: connection = self.get_connection(location) try: # We request the manifest for the object. If one exists, # that means the object was uploaded in chunks/segments, # and we need to delete all the chunks as well as the # manifest. manifest = None try: headers = connection.head_object( location.container, location.obj) manifest = headers.get('x-object-manifest') except swiftclient.ClientException, e: if e.http_status != httplib.NOT_FOUND: raise if manifest: # Delete all the chunks before the object manifest itself obj_container, obj_prefix = manifest.split('/', 1) segments = connection.get_container( obj_container, prefix=obj_prefix)[1] for segment in segments: # TODO(jaypipes): This would be an easy area to parallelize # since we're simply sending off parallelizable requests # to Swift to delete stuff. It's not like we're going to # be hogging up network or file I/O here... connection.delete_object( obj_container, segment['name']) else: connection.delete_object(location.container, location.obj) except swiftclient.ClientException, e: if e.http_status == httplib.NOT_FOUND: uri = location.get_uri() msg = _("Swift could not find image at URI.") raise exception.NotFound(msg) else: raise
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 _wsse_username_token(cnonce, iso_now, password): return base64.b64encode( _sha(("%s%s%s" % (cnonce, iso_now, password)).encode("utf-8")).digest() ).strip().decode("utf-8")
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 testSparseFillEmptyRowsGrad(self): reverse_index_map = [2, 1] grad_values = [0, 1, 2, 3] d_values, d_default_value = self.evaluate( gen_sparse_ops.SparseFillEmptyRowsGrad( reverse_index_map=reverse_index_map, grad_values=grad_values)) self.assertAllEqual([2, 1], d_values) self.assertEqual(3, d_default_value)
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 uniq(inpt): output = [] inpt = [ " ".join(inp.split()) for inp in inpt] for x in inpt: if x not in output: output.append(x) return output
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_write_cb(self): to_send = "GET /after_write_cb 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", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # 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 generate_ip_set( ip_addresses: Optional[Iterable[str]], extra_addresses: Optional[Iterable[str]] = None, config_path: Optional[Iterable[str]] = None,
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 list_entrance_exam_instructor_tasks(request, course_id): # pylint: disable=invalid-name """ List entrance exam related instructor tasks. Takes either of the following query parameters - unique_student_identifier is an email or username - all_students is a boolean """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) course = get_course_by_id(course_id) student = request.GET.get('unique_student_identifier', None) if student is not None: student = get_student_from_identifier(student) try: entrance_exam_key = course_id.make_usage_key_from_deprecated_string(course.entrance_exam_id) except InvalidKeyError: return HttpResponseBadRequest(_("Course has no valid entrance exam section.")) if student: # Specifying for a single student's entrance exam history tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key, student) else: # Specifying for all student's entrance exam history tasks = instructor_task.api.get_entrance_exam_instructor_task_history(course_id, entrance_exam_key) response_payload = { 'tasks': map(extract_task_features, tasks), } return JsonResponse(response_payload)
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 from_crawler(cls, crawler): splash_base_url = crawler.settings.get('SPLASH_URL', cls.default_splash_url) log_400 = crawler.settings.getbool('SPLASH_LOG_400', True) slot_policy = crawler.settings.get('SPLASH_SLOT_POLICY', cls.default_policy) if slot_policy not in SlotPolicy._known: raise NotConfigured("Incorrect slot policy: %r" % slot_policy) return cls(crawler, splash_base_url, slot_policy, log_400)
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 visit_Name(self, node): id_ = node.id.lower() if id_ in self._env: return self._env[id_] else: raise NameError(node.id)
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 save(self): self['__meta__'] = { 'httpie': __version__ } if self.helpurl: self['__meta__']['help'] = self.helpurl if self.about: self['__meta__']['about'] = self.about self.ensure_directory() json_string = json.dumps( obj=self, indent=4, sort_keys=True, ensure_ascii=True, ) self.path.write_text(json_string + '\n', encoding=UTF8)
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 project_version(request, client_id, project_name): """ get project deploy version :param request: request object :param client_id: client id :param project_name: project name :return: deploy version of project """ if request.method == 'GET': # get client and project model client = Client.objects.get(id=client_id) project = Project.objects.get(name=project_name) scrapyd = get_scrapyd(client) # if deploy info exists in db, return it if Deploy.objects.filter(client=client, project=project): deploy = Deploy.objects.get(client=client, project=project) # if deploy info does not exists in db, create deploy info else: try: versions = scrapyd.list_versions(project_name) except ConnectionError: return JsonResponse({'message': 'Connect Error'}, status=500) if len(versions) > 0: version = versions[-1] deployed_at = timezone.datetime.fromtimestamp(int(version), tz=pytz.timezone(TIME_ZONE)) else: deployed_at = None deploy, result = Deploy.objects.update_or_create(client=client, project=project, deployed_at=deployed_at) # return deploy json info return JsonResponse(model_to_dict(deploy))
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label=label, selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color 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 text(self): components = ( ical.Timezone, ical.Event, ical.Todo, ical.Journal, ical.Card) items = set() try: filenames = os.listdir(self._path) except (OSError, IOError) as e: log.LOGGER.info('Error while reading collection %r: %r' % (self._path, e)) return "" for filename in filenames: path = os.path.join(self._path, filename) try: with filesystem.open(path) as fd: items.update(self._parse(fd.read(), components)) except (OSError, IOError) as e: log.LOGGER.warning('Error while reading item %r: %r' % (path, e)) return ical.serialize( self.tag, self.headers, sorted(items, key=lambda x: x.name))
0
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling 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 replace(self, key, value): self.dict[_hkey(key)] = [value if isinstance(value, unicode) else str(value)]
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 create(request, comment_id): comment = get_object_or_404( Comment.objects.exclude(user=request.user), pk=comment_id) form = LikeForm( user=request.user, comment=comment, data=post_data(request)) if is_post(request) and form.is_valid(): like = form.save() like.comment.increase_likes_count() if is_ajax(request): return json_response({'url_delete': like.get_delete_url()}) return redirect(request.POST.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/create.html', context={ 'form': form, 'comment': comment})
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_wildcard_match(self): pat = glob_to_regex("f?o*baz") self.assertTrue( pat.match("FoobarbaZ"), "* should match string and pattern should be case-insensitive", ) self.assertTrue(pat.match("foobaz"), "* should match 0 characters") self.assertFalse(pat.match("fooxaz"), "the character after * must match") self.assertFalse(pat.match("fobbaz"), "? should not match 0 characters") self.assertFalse(pat.match("fiiobaz"), "? should not match 2 characters")
1
Python
CWE-331
Insufficient Entropy
The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others.
https://cwe.mitre.org/data/definitions/331.html
safe
def intermediate_dir(tmp_dir=None): """ Temporary directory for storing .cpp and .o files during builds. First, try to find the dir and if it exists, verify it is safe. Otherwise, create it. """ im_dir = find_valid_temp_dir(intermediate_dir_prefix(), tmp_dir) py_im_dir = py_intermediate_dir() if im_dir is None: py_im_dir = py_intermediate_dir() im_dir = create_intermediate_dir(tmp_dir) else: im_dir = os.path.join(im_dir, py_im_dir) if not os.path.isdir(im_dir): os.mkdir(im_dir, 0o700) return im_dir
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_modify_access_allow_with_uname(self): url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_instructor.username, 'rolename': 'staff', 'action': 'allow', }) 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 test_notfilelike_http10(self): to_send = "GET /notfilelike 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", "HTTP/1.0") 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) # 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 get_file(recipe): if not recipe.link: recipe.link = Dropbox.get_share_link(recipe) recipe.save() response = requests.get(recipe.link.replace('www.dropbox.', 'dl.dropboxusercontent.')) return io.BytesIO(response.content)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def remove(self, name): filesystem_path = os.path.join(self._filesystem_path, name) if os.path.exists(filesystem_path): os.remove(filesystem_path)
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 __init__(self, hs, tls_client_options_factory): self.hs = hs self.signing_key = hs.signing_key self.server_name = hs.hostname real_reactor = hs.get_reactor() # We need to use a DNS resolver which filters out blacklisted IP # addresses, to prevent DNS rebinding. nameResolver = IPBlacklistingResolver( real_reactor, None, hs.config.federation_ip_range_blacklist ) @implementer(IReactorPluggableNameResolver) class Reactor: def __getattr__(_self, attr): if attr == "nameResolver": return nameResolver else: return getattr(real_reactor, attr) self.reactor = Reactor() user_agent = hs.version_string if hs.config.user_agent_suffix: user_agent = "%s %s" % (user_agent, hs.config.user_agent_suffix) user_agent = user_agent.encode("ascii") self.agent = MatrixFederationAgent( self.reactor, tls_client_options_factory, user_agent ) # Use a BlacklistingAgentWrapper to prevent circumventing the IP # blacklist via IP literals in server names self.agent = BlacklistingAgentWrapper( self.agent, ip_blacklist=hs.config.federation_ip_range_blacklist, ) self.clock = hs.get_clock() self._store = hs.get_datastore() self.version_string_bytes = hs.version_string.encode("ascii") self.default_timeout = 60 def schedule(x): self.reactor.callLater(_EPSILON, x) self._cooperator = Cooperator(scheduler=schedule)
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_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False, config_read_column=False, *join):
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
async def _has_watch_regex_match(self, text: str) -> Tuple[Union[bool, re.Match], Optional[str]]: """ Return True if `text` matches any regex from `word_watchlist` or `token_watchlist` configs. `word_watchlist`'s patterns are placed between word boundaries while `token_watchlist` is matched as-is. Spoilers are expanded, if any, and URLs are ignored. Second return value is a reason written to database about blacklist entry (can be None). """ if SPOILER_RE.search(text): text = self._expand_spoilers(text) text = self.clean_input(text) # Make sure it's not a URL if URL_RE.search(text): return False, None watchlist_patterns = self._get_filterlist_items('filter_token', allowed=False) for pattern in watchlist_patterns: match = re.search(pattern, text, flags=re.IGNORECASE) if match: return match, self._get_filterlist_value('filter_token', pattern, allowed=False)['comment'] return False, None
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 class_instances_from_soap_enveloped_saml_thingies(text, modules): """Parses a SOAP enveloped header and body SAML thing and returns the thing as a dictionary class instance. :param text: The SOAP object as XML :param modules: modules representing xsd schemas :return: The body and headers as class instances """ try: envelope = defusedxml.ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 env = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 env["body"] = instanciate_class(part[0], modules) elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: env["header"].append(instanciate_class(item, modules)) return env
1
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
def screenshotcommentcounts(context, screenshot): """ Returns a JSON array of current comments for a screenshot. Each entry in the array has a dictionary containing the following keys: =========== ================================================== Key Description =========== ================================================== text The text of the comment localdraft True if this is the current user's draft comment x The X location of the comment's region y The Y location of the comment's region w The width of the comment's region h The height of the comment's region =========== ================================================== """ comments = {} user = context.get('user', None) for comment in screenshot.comments.all(): review = get_object_or_none(comment.review) if review and (review.public or review.user == user): position = '%dx%d+%d+%d' % (comment.w, comment.h, \ comment.x, comment.y) comments.setdefault(position, []).append({ 'id': comment.id, 'text': comment.text, 'user': { 'username': review.user.username, 'name': review.user.get_full_name() or review.user.username, }, 'url': comment.get_review_url(), 'localdraft' : review.user == user and \ not review.public, 'x' : comment.x, 'y' : comment.y, 'w' : comment.w, 'h' : comment.h, }) return simplejson.dumps(comments)
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 delete_auth_token(user_id): # Invalidate any prevously generated Kobo Auth token for this user. ub.session.query(ub.RemoteAuthToken).filter(ub.RemoteAuthToken.user_id == user_id)\ .filter(ub.RemoteAuthToken.token_type==1).delete() return ub.session_commit()
0
Python
CWE-284
Improper Access Control
The software does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def get_response(self): token_serializer = self.token_serializer_class( instance=self.token, context=self.get_serializer_context(), ) data = token_serializer.data data['next'] = self.serializer.validated_data['user'].login_code.next return Response(data, status=status.HTTP_200_OK)
1
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
safe