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_confirmation_obj_not_exist_error(self) -> None: """Since the key is a param input by the user to the registration endpoint, if it inserts an invalid value, the confirmation object won't be found. This tests if, in that scenario, we handle the exception by redirecting the user to the confirmation_link_expired_error page. """ email = self.nonreg_email("alice") password = "password" realm = get_realm("zulip") inviter = self.example_user("iago") prereg_user = PreregistrationUser.objects.create( email=email, referred_by=inviter, realm=realm ) confirmation_link = create_confirmation_link(prereg_user, Confirmation.USER_REGISTRATION) registration_key = "invalid_confirmation_key" url = "/accounts/register/" response = self.client_post( url, {"key": registration_key, "from_confirmation": 1, "full_nme": "alice"} ) self.assertEqual(response.status_code, 404) self.assert_in_response("The registration link has expired or is not valid.", response) registration_key = confirmation_link.split("/")[-1] response = self.client_post( url, {"key": registration_key, "from_confirmation": 1, "full_nme": "alice"} ) self.assert_in_success_response(["We just need you to do one last thing."], response) response = self.submit_reg_form_for_user(email, password, key=registration_key) self.assertEqual(response.status_code, 302)
0
Python
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
vulnerable
def _get_index_absolute_path(index): return os.path.join(INDEXDIR, index)
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
def test_session_with_cookie_followed_by_another_header(self, httpbin): """ Make sure headers don’t get mutated — <https://github.com/httpie/httpie/issues/1126> """ self.start_session(httpbin) session_data = { "headers": { "cookie": "...", "zzz": "..." } } session_path = self.config_dir / 'session-data.json' session_path.write_text(json.dumps(session_data)) r = http('--session', str(session_path), 'GET', httpbin.url + '/get', env=self.env()) assert HTTP_OK in r assert 'Zzz' in r
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_basic_format_safety(self): env = SandboxedEnvironment() t = env.from_string('{{ "a{0.__class__}b".format(42) }}') assert t.render() == 'ab'
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def _unpack_returndata(buf, contract_sig, skip_contract_check, context): return_t = contract_sig.return_type if return_t is None: return ["pass"], 0, 0 return_t = calculate_type_for_external_return(return_t) # if the abi signature has a different type than # the vyper type, we need to wrap and unwrap the type # so that the ABI decoding works correctly should_unwrap_abi_tuple = return_t != contract_sig.return_type abi_return_t = return_t.abi_type min_return_size = abi_return_t.min_size() max_return_size = abi_return_t.size_bound() assert 0 < min_return_size <= max_return_size ret_ofst = buf ret_len = max_return_size # revert when returndatasize is not in bounds ret = [] # runtime: min_return_size <= returndatasize # TODO move the -1 optimization to IR optimizer if not skip_contract_check: ret += [["assert", ["gt", "returndatasize", min_return_size - 1]]] # add as the last IRnode a pointer to the return data structure # the return type has been wrapped by the calling contract; # unwrap it so downstream code isn't confused. # basically this expands to buf+32 if the return type has been wrapped # in a tuple AND its ABI type is dynamic. # in most cases, this simply will evaluate to ret. # in the special case where the return type has been wrapped # in a tuple AND its ABI type is dynamic, it expands to buf+32. buf = IRnode(buf, typ=return_t, encoding=_returndata_encoding(contract_sig), location=MEMORY) if should_unwrap_abi_tuple: buf = get_element_ptr(buf, 0, array_bounds_check=False) ret += [buf] return ret, ret_ofst, ret_len
0
Python
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
vulnerable
def 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 H_FILE: with open(H_FILE, "w") as f: 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") if C_FILE: with open(C_FILE, "w") as f: 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)
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 prevent_open_redirect(url): # Prevent an attacker from adding an arbitrary url after the # _next variable in the request. host = current.request.env.http_host print(host) if not url: return None if REGEX_OPEN_REDIRECT.match(url): parts = url.split('/') if len(parts) > 2 and parts[2] == host: return url return None return url
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 setURL(self, url): _ensureValidURI(url.strip()) self.url = url uri = URI.fromBytes(url) if uri.scheme and uri.host: self.scheme = uri.scheme self.host = uri.host self.port = uri.port self.path = uri.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 test_sneaky_import_in_style(self): # Prevent "@@importimport" -> "@import" replacement. style_codes = [ "@@importimport(extstyle.css)", "@ @ import import(extstyle.css)", "@ @ importimport(extstyle.css)", "@@ import import(extstyle.css)", "@ @import import(extstyle.css)", "@@importimport()", ] for style_code in style_codes: html = '<style>%s</style>' % style_code s = lxml.html.fragment_fromstring(html) cleaned = lxml.html.tostring(clean_html(s)) self.assertEqual( b'<style>/* deleted */</style>', cleaned, "%s -> %s" % (style_code, cleaned))
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 final_work(self): # this must come before archive creation to ensure that log # files are closed and cleaned up at exit. self._finish_logging() # package up the results for the support organization if not self.opts.build: old_umask = os.umask(0o077) if not self.opts.quiet: print(_("Creating compressed archive...")) # compression could fail for a number of reasons try: final_filename = self.archive.finalize( self.opts.compression_type) except (OSError, IOError) as e: if e.errno in fatal_fs_errors: self.ui_log.error("") self.ui_log.error(" %s while finalizing archive" % e.strerror) self.ui_log.error("") self._exit(1) except: if self.opts.debug: raise else: return False finally: os.umask(old_umask) else: final_filename = self.archive.get_archive_path() self.policy.display_results(final_filename, build=self.opts.build) self.tempfile_util.clean() return True
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 __init__(self, deferred): self.deferred = deferred
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_siblings_cant_talk(self): self.router.unidirectional = True l1 = self.router.local() l2 = self.router.local() logs = testlib.LogCapturer() logs.start() e = self.assertRaises(mitogen.core.CallError, lambda: l2.call(ping_context, l1)) msg = self.router.unidirectional_msg % ( l2.context_id, l1.context_id, ) self.assertTrue(msg in str(e)) self.assertTrue('routing mode prevents forward of ' in logs.stop())
0
Python
CWE-254
7PK - Security Features
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
https://cwe.mitre.org/data/definitions/254.html
vulnerable
def prop_sentences_stats(self, type, vId = None): return { 'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC", 'all_networks' : "SELECT networks.* FROM networks ORDER BY id", 'get_preview' : ("SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = ?" , vId), 'id_networks' : ("SELECT networks.* FROM networks WHERE id = ?", vId), 'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ", 'get_sessions' : "SELECT COUNT(*) AS Total FROM networks", 'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks", 'get_online' : ("SELECT COUNT(*) AS Total FROM victims WHERE status = ?", vId) }.get(type, False)
1
Python
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
safe
def job_log(request, client_id, project_name, spider_name, job_id): """ get log of jog :param request: request object :param client_id: client id :param project_name: project name :param spider_name: spider name :param job_id: job id :return: log of job """ if request.method == 'GET': client = Client.objects.get(id=client_id) # get log url url = log_url(client.ip, client.port, project_name, spider_name, job_id) try: # get last 1000 bytes of log response = requests.get(url, timeout=5, headers={ 'Range': 'bytes=-1000' }, auth=(client.username, client.password) if client.auth else None) # Get encoding encoding = response.apparent_encoding # log not found if response.status_code == 404: return JsonResponse({'message': 'Log Not Found'}, status=404) # bytes to string text = response.content.decode(encoding, errors='replace') return HttpResponse(text) except requests.ConnectionError: return JsonResponse({'message': 'Load Log Error'}, status=500)
0
Python
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
def test_certificates_features_against_status(self): """ Test certificates with status 'downloadable' should be in the response. """ 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.generating) response = self.client.post(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 0) # Certificates with status 'downloadable' should be in response. self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.post(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1)
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_tofile_sep(self): x = np.array([1.51, 2, 3.51, 4], dtype=float) f = open(self.filename, 'w') x.tofile(f, sep=',') f.close() f = open(self.filename, 'r') s = f.read() f.close() assert_equal(s, '1.51,2.0,3.51,4.0') 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 _create(self): url = urljoin(recurly.base_uri(), self.collection_path) return self.post(url)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def _handle_carbon_sent(self, msg): if msg['from'].bare == self.xmpp.boundjid.bare: self.xmpp.event('carbon_sent', msg)
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_pathWithWithUnprintableASCIIRejected(self): """ Issuing a request with a URI whose path contains unprintable ASCII characters fails with a L{ValueError}. """ for c in UNPRINTABLE_ASCII: uri = b"http://twisted.invalid/OK%s" % (bytearray([c]),) with self.assertRaises(ValueError) as cm: self.attemptRequestWithMaliciousURI(uri) self.assertRegex(str(cm.exception), "^Invalid URI")
1
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
def test_digest_object_stale(): credentials = ("joe", "password") host = None request_uri = "/digest/stale/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="bd669f", ' 'algorithm=MD5, qop="auth", stale=true' ) response.status = 401 content = b"" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, response, content, None ) # Returns true to force a retry assert d.response(response, content)
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_in_generator(self): to_send = "GET /in_generator 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 adv_search_serie(q, include_series_inputs, exclude_series_inputs): for serie in include_series_inputs: q = q.filter(db.Books.series.any(db.Series.id == serie)) for serie in exclude_series_inputs: q = q.filter(not_(db.Books.series.any(db.Series.id == serie))) return q
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 testOutOfBoundAxis(self): input_tensor = constant_op.constant([1., 1.]) input_min = [0] input_max = [1] q_input, _, _ = array_ops.quantize(input_tensor, 0, 1, dtypes.qint32) error = (errors.InvalidArgumentError, ValueError) with self.assertRaisesRegex(error, r".*Axis must be less than input dimension.*"): self.evaluate( gen_array_ops.dequantize( input=q_input, min_range=input_min, max_range=input_max, axis=2**31 - 1))
1
Python
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def _get_obj_absolute_path(obj_path): return os.path.join(DATAROOT, obj_path)
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_reset_student_attempts_delete(self): """ Test delete single student state. """ url = reverse('reset_student_attempts', 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, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted self.assertEqual( StudentModule.objects.filter( student=self.module_to_reset.student, course_id=self.module_to_reset.course_id, # module_id=self.module_to_reset.module_id, ).count(), 0 )
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 another_upload_file(request): path = tempfile.mkdtemp() file_name = os.path.join(path, "another_%s.txt" % request.node.name) with open(file_name, "w") as f: f.write(request.node.name) return file_name
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 _allowed_paths(self): """Return the paths the user may visit when not verified via otp This result cannot be cached since we want to be compatible with the django-hosts package. Django-hosts alters the urlconf based on the hostname in the request, so the urls might exist for admin.<domain> but not for www.<domain>. """ results = [] for route_name in self._allowed_url_names: try: results.append(settings.WAGTAIL_MOUNT_PATH + reverse(route_name)) except NoReverseMatch: pass return results
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def accounts_home_from_multiuse_invite(request: HttpRequest, confirmation_key: str) -> HttpResponse: realm = get_realm_from_request(request) multiuse_object = None try: multiuse_object = get_object_from_key(confirmation_key, [Confirmation.MULTIUSE_INVITE]) if realm != multiuse_object.realm: return render(request, "confirmation/link_does_not_exist.html", status=404) # Required for OAuth 2 except ConfirmationKeyException as exception: if realm is None or realm.invite_required: return render_confirmation_key_error(request, exception) return accounts_home( request, multiuse_object_key=confirmation_key, multiuse_object=multiuse_object )
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 set_multi(self, mapping, server_key, serialize=True, timeout=0): """ Sets multiple key/value pairs in memcache. :param mapping: dictonary of keys and values to be set in memcache :param servery_key: key to use in determining which server in the ring is used :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 for memcache """ server_key = md5hash(server_key) if timeout > 0: timeout += time.time() msg = '' for key, value in mapping.iteritems(): key = md5hash(key) 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 msg += ('set %s %d %d %s noreply\r\n%s\r\n' % (key, flags, timeout, len(value), value)) for (server, fp, sock) in self._get_conns(server_key): try: sock.sendall(msg) 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 test_digest_object_auth_info(): credentials = ("joe", "password") host = None request_uri = "/digest/nextnonce/" headers = {} response = httplib2.Response({}) response["www-authenticate"] = ( 'Digest realm="myrealm", nonce="barney", ' 'algorithm=MD5, qop="auth", stale=true' ) response["authentication-info"] = 'nextnonce="fred"' content = b"" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, response, content, None ) # Returns true to force a retry assert not d.response(response, content) assert d.challenge["nonce"] == "fred" assert d.challenge["nc"] == 1
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 _get_default_cache_dir(self): tmpdir = tempfile.gettempdir() # On windows the temporary directory is used specific unless # explicitly forced otherwise. We can just use that. if os.name == 'n': return tmpdir if not hasattr(os, 'getuid'): raise RuntimeError('Cannot determine safe temp directory. You ' 'need to explicitly provide one.') dirname = '_jinja2-cache-%d' % os.getuid() actual_dir = os.path.join(tmpdir, dirname) try: os.mkdir(actual_dir, 0700) except OSError as e: if e.errno != errno.EEXIST: raise return actual_dir
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_check_unsafe_path(self): self.assertRaises(exception.Invalid, disk_api._join_and_check_path_within_fs, '/foo', 'etc/../../../something.conf')
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_specifiying_wagtail_mount_point_does_prepend_allowed_paths_with_wagtail_mount_path(settings): settings.WAGTAIL_MOUNT_PATH = '/wagtail' allowed_paths = VerifyUserMiddleware()._allowed_paths for allowed_path in allowed_paths: assert allowed_path.startswith(settings.WAGTAIL_MOUNT_PATH)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def fn(x): return ragged_array_ops.cross(x)
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 _filesystem_path(self): """Absolute path of the file at local ``path``.""" return pathutils.path_to_filesystem(self.path, FOLDER)
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_parse_www_authenticate_malformed(): # TODO: test (and fix) header value 'barbqwnbm-bb...:asd' leads to dead loop with tests.assert_raises(httplib2.MalformedHeader): httplib2._parse_www_authenticate( { "www-authenticate": 'OAuth "Facebook Platform" "invalid_token" "Invalid OAuth access token."' } )
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_invalid(self, args, message): with pytest.raises(SystemExit, match=re.escape(message)): qutebrowser._validate_untrusted_args(args)
1
Python
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
safe
def download(url, location): """ Download files to the specified location. :param url: The file URL. :type url: str :param location: The absolute path to where the downloaded file is to be stored. :type location: str """ request = urllib2.urlopen(url) try: content = request.read() fp = open(location, 'w+') try: fp.write(content) finally: fp.close() finally: request.close()
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 async_run(prog, args): pid = os.fork() if pid: os.waitpid(pid, 0) else: dpid = os.fork() if not dpid: os.system(" ".join([prog] + args)) os._exit(0)
0
Python
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
def test_as_expected(self, mopen, mock_os): """ When everything works as expected, ensure that the file is closed. """ mock_fp = open.return_value cli.write_to_location('test/loc', 'content') mock_os.path.dirname.assert_called_once_with('test/loc') mock_os.makedirs.assert_called_once_with(mock_os.path.dirname.return_value) open.assert_called_once_with('test/loc', 'w+') mock_fp.write.assert_called_once_with('content') mock_fp.close.assert_called_once_with()
1
Python
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
safe
def test_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 testImageCropAndResizeWithInvalidInput(self): with self.session(): with self.assertRaises((errors.InternalError, ValueError)): op = image_ops_impl.crop_and_resize_v2( image=np.ones((1, 1, 1, 1)), boxes=np.ones((11, 4)), box_indices=np.ones((11)), crop_size=[2065374891, 1145309325]) self.evaluate(op)
1
Python
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def _download_file(bucket, filename, local_dir): key = bucket.get_key(filename) local_filename = os.path.join(local_dir, os.path.basename(filename)) key.get_contents_to_filename(local_filename) return local_filename
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 create_dmcrypt_key(): """ Create the secret dm-crypt key (KEK) used to encrypt/decrypt the Volume Key. """ random_string = os.urandom(128) key = base64.b64encode(random_string).decode('utf-8') return key
1
Python
NVD-CWE-noinfo
null
null
null
safe
def _normalize_path(self, path, prefix): if not path.startswith(os.path.sep): path = os.path.join(os.path.sep, path) normpath = os.path.normpath(path) return os.path.join(prefix, normpath[1:])
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_received_control_line_finished_all_chunks_not_received(self): buf = DummyBuffer() inst = self._makeOne(buf) result = inst.received(b"a;discard\n") self.assertEqual(inst.control_line, b"") self.assertEqual(inst.chunk_remainder, 10) self.assertEqual(inst.all_chunks_received, False) self.assertEqual(result, 10) self.assertEqual(inst.completed, False)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def test_request_body_too_large_chunked_encoding(self): control_line = "20;\r\n" # 20 hex = 32 dec s = "This string has 32 characters.\r\n" to_send = "GET / HTTP/1.1\nTransfer-Encoding: chunked\n\n" repeat = control_line + s to_send += repeat * ((self.toobig // len(repeat)) + 1) 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) # body bytes counter caught a max_request_body_size overrun self.assertline(line, "413", "Request Entity Too Large", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertEqual(headers["content-type"], "text/plain") # 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_create_registration_code_without_invoice_and_order(self): """ test generate detailed enrollment report, used a registration codes which has been created via invoice or bulk purchase scenario. """ course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, mode_slug='honor' ) test_user1 = UserFactory() self.register_with_redemption_code(test_user1, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content)
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_before_start_response_http_11_close(self): to_send = tobytes( "GET /before_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 test_get_delete_dataobj_not_found(test_app, client: FlaskClient): response = client.get("/dataobj/delete/1") assert response.status_code == 302
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 create_class_from_xml_string(target_class, xml_string): """Creates an instance of the target class from a string. :param target_class: The class which will be instantiated and populated with the contents of the XML. This class must have a c_tag and a c_namespace class variable. :param xml_string: A string which contains valid XML. The root element of the XML string should match the tag and namespace of the desired class. :return: An instance of the target class with members assigned according to the contents of the XML - or None if the root XML tag and namespace did not match those of the target class. """ if not isinstance(xml_string, six.binary_type): xml_string = xml_string.encode('utf-8') tree = defusedxml.ElementTree.fromstring(xml_string) return create_class_from_element_tree(target_class, tree)
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_digest_object(): credentials = ("joe", "password") host = None request_uri = "/test/digest/" headers = {} response = { "www-authenticate": 'Digest realm="myrealm", nonce="KBAA=35", algorithm=MD5, qop="auth"' } content = b"" d = httplib2.DigestAuthentication( credentials, host, request_uri, headers, response, content, None ) d.request("GET", request_uri, headers, content, cnonce="33033375ec278a46") our_request = "authorization: " + headers["authorization"] working_request = ( 'authorization: Digest username="joe", realm="myrealm", ' 'nonce="KBAA=35", uri="/test/digest/"' + ', algorithm=MD5, response="de6d4a123b80801d0e94550411b6283f", ' 'qop=auth, nc=00000001, cnonce="33033375ec278a46"' ) assert our_request == working_request
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 append(self, key, value): self.dict.setdefault(_hkey(key), []).append(_hval(value))
1
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
safe
def test_nonexistent_catalog_is_none(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'r') self.remove_dir(pardir) assert_(cat is None)
0
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
vulnerable
def test_received_chunk_is_properly_terminated(self): buf = DummyBuffer() inst = self._makeOne(buf) data = b"4\r\nWiki\r\n" result = inst.received(data) self.assertEqual(result, len(data)) self.assertEqual(inst.completed, False) self.assertEqual(buf.data[0], b"Wiki")
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 delete(request, pk): favorite = get_object_or_404(TopicFavorite, pk=pk, user=request.user) favorite.delete() return redirect(request.POST.get('next', favorite.topic.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 preprocess_input_exprs_arg_string(input_exprs_str, safe=True): """Parses input arg into dictionary that maps input key to python expression. Parses input string in the format of 'input_key=<python expression>' into a dictionary that maps each input_key to its python expression. Args: input_exprs_str: A string that specifies python expression for input keys. Each input is separated by semicolon. For each input key: 'input_key=<python expression>' safe: Whether to evaluate the python expression as literals or allow arbitrary calls (e.g. numpy usage). Returns: A dictionary that maps input keys to their values. Raises: RuntimeError: An error when the given input string is in a bad format. """ input_dict = {} for input_raw in filter(bool, input_exprs_str.split(';')): if '=' not in input_exprs_str: raise RuntimeError('--input_exprs "%s" format is incorrect. Please follow' '"<input_key>=<python expression>"' % input_exprs_str) input_key, expr = input_raw.split('=', 1) if safe: try: input_dict[input_key] = ast.literal_eval(expr) except: raise RuntimeError( f'Expression "{expr}" is not a valid python literal.') else: # ast.literal_eval does not work with numpy expressions input_dict[input_key] = eval(expr) # pylint: disable=eval-used return input_dict
1
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
safe
def test_digest_next_nonce_nc(): # Test that if the server sets nextnonce that we reset # the nonce count back to 1 http = httplib2.Http() password = tests.gen_password() grenew_nonce = [None] handler = tests.http_reflect_with_auth( allow_scheme="digest", allow_credentials=(("joe", password),), out_renew_nonce=grenew_nonce, ) with tests.server_request(handler, request_count=5) as uri: http.add_credentials("joe", password) response1, _ = http.request(uri, "GET") info = httplib2._parse_www_authenticate(response1, "authentication-info") assert response1.status == 200 assert info.get("digest", {}).get("nc") == "00000001", info assert not info.get("digest", {}).get("nextnonce"), info response2, _ = http.request(uri, "GET") info2 = httplib2._parse_www_authenticate(response2, "authentication-info") assert info2.get("digest", {}).get("nc") == "00000002", info2 grenew_nonce[0]() response3, content = http.request(uri, "GET") info3 = httplib2._parse_www_authenticate(response3, "authentication-info") assert response3.status == 200 assert info3.get("digest", {}).get("nc") == "00000001", info3
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_show_unit_extensions(self): self.test_change_due_date() url = reverse('show_unit_extensions', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {'url': self.week1.location.to_deprecated_string()}) self.assertEqual(response.status_code, 200, response.content) self.assertEqual(json.loads(response.content), { u'data': [{u'Extended Due Date': u'2013-12-30 00:00', u'Full Name': self.user1.profile.name, u'Username': self.user1.username}], u'header': [u'Username', u'Full Name', u'Extended Due Date'], u'title': u'Users with due date extensions for %s' % self.week1.display_name})
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 _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.replace('@', '') # ignore characters already included n = n.replace(':', '') # but not the surrounding text n = n.replace('#', '') 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")
1
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
safe
def make_homeserver(self, reactor, clock): self.mock_federation = Mock() self.mock_registry = Mock() self.query_handlers = {} def register_query_handler(query_type, handler): self.query_handlers[query_type] = handler self.mock_registry.register_query_handler = register_query_handler hs = self.setup_test_homeserver( http_client=None, resource_for_federation=Mock(), federation_client=self.mock_federation, federation_registry=self.mock_registry, ) self.handler = hs.get_directory_handler() self.store = hs.get_datastore() self.my_room = RoomAlias.from_string("#my-room:test") self.your_room = RoomAlias.from_string("#your-room:test") self.remote_room = RoomAlias.from_string("#another:remote") 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 load_yaml(yaml_str): """ :param unicode yaml_str: :rtype: dict | list """ return yaml.safe_load(yaml_str)
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_change_password_invalidates_token(self): from keystoneclient import exceptions as client_exceptions client = self.get_client(admin=True) username = uuid.uuid4().hex passwd = uuid.uuid4().hex user = client.users.create(name=username, password=passwd, email=uuid.uuid4().hex) token_id = client.tokens.authenticate(username=username, password=passwd).id # authenticate with a token should work before a password change client.tokens.authenticate(token=token_id) client.users.update_password(user=user.id, password=uuid.uuid4().hex) # authenticate with a token should not work after a password change self.assertRaises(client_exceptions.Unauthorized, client.tokens.authenticate, token=token_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 test_send_event_single_sender(self): """Test that using a single federation sender worker correctly sends a new event. """ mock_client = Mock(spec=["put_json"]) mock_client.put_json.return_value = make_awaitable({}) self.make_worker_hs( "synapse.app.federation_sender", {"send_federation": True}, http_client=mock_client, ) user = self.register_user("user", "pass") token = self.login("user", "pass") room = self.create_room_with_remote_server(user, token) mock_client.put_json.reset_mock() self.create_and_send_event(room, UserID.from_string(user)) self.replicate() # Assert that the event was sent out over federation. mock_client.put_json.assert_called() self.assertEqual(mock_client.put_json.call_args[0][0], "other_server") self.assertTrue(mock_client.put_json.call_args[1]["data"].get("pdus"))
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 render_hot_books(page, order): if current_user.check_visibility(constants.SIDEBAR_HOT): if order[1] not in ['hotasc', 'hotdesc']: # Unary expression comparsion only working (for this expression) in sqlalchemy 1.4+ #if not (order[0][0].compare(func.count(ub.Downloads.book_id).desc()) or # order[0][0].compare(func.count(ub.Downloads.book_id).asc())): order = [func.count(ub.Downloads.book_id).desc()], 'hotdesc' if current_user.show_detail_random(): random = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()) \ .order_by(func.random()).limit(config.config_random_books) else: random = false() off = int(int(config.config_books_per_page) * (page - 1)) all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id))\ .order_by(*order[0]).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.session.query(db.Books).filter(calibre_db.common_filters()).filter( db.Books.id == book.Downloads.book_id).first() if downloadBook: entries.append(downloadBook) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination(page, config.config_books_per_page, numBooks) return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=_(u"Hot Books (Most Downloaded)"), page="hot", order=order[1]) 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 is_whitelisted(method): # check if whitelisted if frappe.session['user'] == 'Guest': if (method not in frappe.guest_methods): frappe.throw(_("Not permitted"), frappe.PermissionError) if method not in frappe.xss_safe_methods: # strictly sanitize form_dict # escapes html characters like <> except for predefined tags like a, b, ul etc. for key, value in frappe.form_dict.items(): if isinstance(value, string_types): frappe.form_dict[key] = frappe.utils.sanitize_html(value) else: if not method in frappe.whitelisted: frappe.throw(_("Not permitted"), frappe.PermissionError)
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 fake_security_group_rule_count_by_group(context, sec_group_id): return 0
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 pascal_case(value: str) -> str: return stringcase.pascalcase(_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 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-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
async def start_verification(self, client_id, username): async with self.lock: await self.db.execute('SELECT code FROM scratchverifier_usage WHERE \ client_id=? AND username=?', (client_id, username)) row = await self.db.fetchone() if row is not None: await self.db.execute('UPDATE scratchverifier_usage SET expiry=? \ WHERE client_id=? AND username=? AND code=?', (int(time.time()) + VERIFY_EXPIRY, client_id, username, row[0])) return row[0] code = sha256( str(client_id).encode() + str(time.time()).encode() + username.encode() + token_bytes() # 0->A, 1->B, etc, to avoid Scratch's phone number censor ).hexdigest().translate({ord('0') + i: ord('A') + i for i in range(10)}) await self.db.execute('INSERT INTO scratchverifier_usage (client_id, \ code, username, expiry) VALUES (?, ?, ?, ?)', (client_id, code, username, int(time.time() + VERIFY_EXPIRY))) await self.db.execute('INSERT INTO scratchverifier_logs (client_id, \ username, log_time, log_type) VALUES (?, ?, ?, ?)', (client_id, username, int(time.time()), 1)) await self.db.execute('DELETE FROM scratchverifier_usage WHERE \ expiry<=?', (int(time.time()),)) return code
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 testSparseCountSparseOutputBadNumberOfValues(self): indices = [[0, 0], [0, 1], [1, 0]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, "Number of values must match first dimension of indices"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False))
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 __init__(self, sydent): self.sydent = sydent # The default endpoint factory in Twisted 14.0.0 (which we require) uses the # BrowserLikePolicyForHTTPS context factory which will do regular cert validation # 'like a browser' self.agent = Agent( BlacklistingReactorWrapper( reactor=self.sydent.reactor, ip_whitelist=sydent.ip_whitelist, ip_blacklist=sydent.ip_blacklist, ), connectTimeout=15, )
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 __iter__(self): return iter(self._kwargs)
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def test_big_arrays(self): L = (1 << 31) + 100000 tmp = mktemp(suffix='.npz') a = np.empty(L, dtype=np.uint8) np.savez(tmp, a=a) del a npfile = np.load(tmp) a = npfile['a'] npfile.close() os.remove(tmp)
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 __init__(self, *args, **kwargs): super(BasketShareForm, self).__init__(*args, **kwargs) try: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], initial=kwargs["initial"]["selected"], widget=forms.SelectMultiple(attrs={"size": 10}), ) except Exception: self.fields["image"] = GroupModelMultipleChoiceField( queryset=kwargs["initial"]["images"], widget=forms.SelectMultiple(attrs={"size": 10}), )
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 boboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) validate = getSecurityManager().validate path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else: found = traversePathElement(object, name, path_items, request=request) # Special backwards compatibility exception for the name ``_``, # which was often used for translation message factories. # Allow and continue traversal. if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) object = found continue # All other names starting with ``_`` are disallowed. # This emulates what restrictedTraverse does. if name.startswith('_'): raise NotFound(name) # traversePathElement doesn't apply any Zope security policy, # so we validate access explicitly here. try: validate(object, object, name, found) object = found except Unauthorized: # Convert Unauthorized to prevent information disclosures raise NotFound(name) return object
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_get_response_requests_exception(self, mock_get): mock_response = mock.Mock() mock_response.status_code = 500 mock_response.text = "Server Error" exception_message = "Some requests exception" requests_exception = requests.RequestException(exception_message) mock_response.raise_for_status.side_effect = requests_exception mock_get.return_value = mock_response url = "https://example.com/" query_runner = BaseHTTPQueryRunner({}) response, error = query_runner.get_response(url) mock_get.assert_called_once_with("get", url, auth=None) self.assertIsNotNone(error) self.assertEqual(exception_message, 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 run_custom_method(doctype, name, custom_method): """cmd=run_custom_method&doctype={doctype}&name={name}&custom_method={custom_method}""" doc = frappe.get_doc(doctype, name) if getattr(doc, custom_method, frappe._dict()).is_whitelisted: frappe.call(getattr(doc, custom_method), **frappe.local.form_dict) else: frappe.throw(_("Not permitted"), frappe.PermissionError)
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 intermediate_dir(): """ Location in temp dir for storing .cpp and .o files during builds. """ python_name = "python%d%d_intermediate" % tuple(sys.version_info[:2]) path = os.path.join(tempfile.gettempdir(),"%s"%whoami(),python_name) if not os.path.exists(path): os.makedirs(path, mode=0o700) return path
0
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
vulnerable
def _normalize_headers(headers): return dict( [ ( _convert_byte_str(key).lower(), NORMALIZE_SPACE.sub(_convert_byte_str(value), " ").strip(), ) for (key, value) in headers.items() ] )
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 feed_authorindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Authors.sort, 1, 1)).label('id'))\ .join(db.books_authors_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Authors.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_author', 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 check_is_dir(): return os.path.isdir(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 is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: str :return: Whether the client_secret is valid :rtype: bool """ return ( 0 < len(client_secret) <= 255 and CLIENT_SECRET_REGEX.match(client_secret) is not None )
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 _rpsl_db_query_to_graphql_out(query: RPSLDatabaseQuery, info: GraphQLResolveInfo): """ Given an RPSL database query, execute it and clean up the output to be suitable to return to GraphQL. Main changes are: - Enum handling - Adding the asn and prefix fields if applicable - Ensuring the right fields are returned as a list of strings or a string """ database_handler = info.context['request'].app.state.database_handler if info.context.get('sql_trace'): if 'sql_queries' not in info.context: info.context['sql_queries'] = [repr(query)] else: info.context['sql_queries'].append(repr(query)) for row in database_handler.execute_query(query, refresh_on_error=True): graphql_result = {snake_to_camel_case(k): v for k, v in row.items() if k != 'parsed_data'} if 'object_text' in row: graphql_result['objectText'] = remove_auth_hashes(row['object_text']) if 'rpki_status' in row: graphql_result['rpkiStatus'] = row['rpki_status'] if row.get('ip_first') is not None and row.get('prefix_length'): graphql_result['prefix'] = row['ip_first'] + '/' + str(row['prefix_length']) if row.get('asn_first') is not None and row.get('asn_first') == row.get('asn_last'): graphql_result['asn'] = row['asn_first'] object_type = resolve_rpsl_object_type(row) for key, value in row.get('parsed_data', dict()).items(): if key == 'auth': value = remove_auth_hashes(value) graphql_type = schema.graphql_types[object_type][key] if graphql_type == 'String' and isinstance(value, list): value = '\n'.join(value) graphql_result[snake_to_camel_case(key)] = value yield graphql_result
0
Python
CWE-212
Improper Removal of Sensitive Information Before Storage or Transfer
The product stores, transfers, or shares a resource that contains sensitive information, but it does not properly remove that information before the product makes the resource available to unauthorized actors.
https://cwe.mitre.org/data/definitions/212.html
vulnerable
def test_fix_missing_locations(self): src = ast.parse('write("spam")') src.body.append(ast.Expr(ast.Call(ast.Name('spam', ast.Load()), [ast.Str('eggs')], []))) self.assertEqual(src, ast.fix_missing_locations(src)) self.maxDiff = None self.assertEqual(ast.dump(src, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='write', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=5), " "args=[Constant(value='spam', lineno=1, col_offset=6, end_lineno=1, " "end_col_offset=12)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=13), Expr(value=Call(func=Name(id='spam', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=0), " "args=[Constant(value='eggs', lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0)], keywords=[], lineno=1, col_offset=0, end_lineno=1, " "end_col_offset=0), lineno=1, col_offset=0, end_lineno=1, end_col_offset=0)])" )
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 read_http(fp): # pragma: no cover try: response_line = fp.readline() except socket.error as exc: fp.close() # errno 104 is ENOTRECOVERABLE, In WinSock 10054 is ECONNRESET if get_errno(exc) in (errno.ECONNABORTED, errno.ECONNRESET, 104, 10054): raise ConnectionClosed raise if not response_line: raise ConnectionClosed header_lines = [] while True: line = fp.readline() if line in (b"\r\n", b"\r\n", b""): break else: header_lines.append(line) headers = dict() for x in header_lines: x = x.strip() if not x: continue key, value = x.split(b": ", 1) key = key.decode("iso-8859-1").lower() value = value.decode("iso-8859-1") assert key not in headers, "%s header duplicated" % key headers[key] = value if "content-length" in headers: num = int(headers["content-length"]) body = b"" left = num while left > 0: data = fp.read(left) if not data: break body += data left -= len(data) else: # read until EOF body = fp.read() return response_line, headers, 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 rename_all_authors(first_author, renamed_author, calibre_path="", localbook=None, gdrive=False): # Create new_author_dir from parameter or from database # Create new title_dir from database and add id if first_author: new_authordir = get_valid_filename(first_author, chars=96) for r in renamed_author: new_author = calibre_db.session.query(db.Authors).filter(db.Authors.name == r).first() old_author_dir = get_valid_filename(r, chars=96) new_author_rename_dir = get_valid_filename(new_author.name, chars=96) if gdrive: gFile = gd.getFileFromEbooksFolder(None, old_author_dir) if gFile: gd.moveGdriveFolderRemote(gFile, new_author_rename_dir) else: if os.path.isdir(os.path.join(calibre_path, old_author_dir)): try: old_author_path = os.path.join(calibre_path, old_author_dir) new_author_path = os.path.join(calibre_path, new_author_rename_dir) shutil.move(os.path.normcase(old_author_path), os.path.normcase(new_author_path)) except (OSError) as ex: log.error("Rename author from: %s to %s: %s", old_author_path, new_author_path, ex) log.debug(ex, exc_info=True) return _("Rename author from: '%(src)s' to '%(dest)s' failed with error: %(error)s", src=old_author_path, dest=new_author_path, error=str(ex)) else: new_authordir = get_valid_filename(localbook.authors[0].name, chars=96) return new_authordir
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 load(self): config_type = type(self).__name__.lower() try: with self.path.open(encoding=UTF8) as f: try: data = json.load(f) except ValueError as e: raise ConfigFileError( f'invalid {config_type} file: {e} [{self.path}]' ) self.update(data) except FileNotFoundError: pass except OSError as e: raise ConfigFileError(f'cannot read {config_type} file: {e}')
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def set_session_tracks(display_obj): """Save igv tracks as a session object. This way it's easy to verify that a user is requesting one of these files from remote_static view endpoint Args: display_obj(dict): A display object containing case name, list of genes, lucus and tracks """ session_tracks = list(display_obj.get("reference_track", {}).values()) for key, track_items in display_obj.items(): if key not in ["tracks", "custom_tracks", "sample_tracks"]: continue for track_item in track_items: session_tracks += list(track_item.values()) session["igv_tracks"] = session_tracks
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_notfilelike_iobase_http11(self): to_send = "GET /notfilelike_iobase HTTP/1.1\n\n" to_send = tobytes(to_send) self.connect() for t in range(0, 2): self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(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)
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 is_whitelisted(method): # check if whitelisted if frappe.session['user'] == 'Guest': if (method not in frappe.guest_methods): frappe.throw(_("Not permitted"), frappe.PermissionError) if method not in frappe.xss_safe_methods: # strictly sanitize form_dict # escapes html characters like <> except for predefined tags like a, b, ul etc. for key, value in frappe.form_dict.items(): if isinstance(value, string_types): frappe.form_dict[key] = frappe.utils.sanitize_html(value) else: if not method in frappe.whitelisted: frappe.throw(_("Not permitted"), frappe.PermissionError)
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 testOrdering(self): import six import random with ops.Graph().as_default() as G: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64, name='pi') gi = array_ops.placeholder(dtypes.int64, name='gi') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea( [ dtypes.int32, ], shapes=[[]], ordered=True) stage = stager.put(pi, [x], [0]) get = stager.get() size = stager.size() G.finalize() n = 10 with self.session(graph=G) as sess: # Keys n-1..0 keys = list(reversed(six.moves.range(n))) for i in keys: sess.run(stage, feed_dict={pi: i, x: i}) self.assertTrue(sess.run(size) == n) # Check that key, values come out in ascending order for i, k in enumerate(reversed(keys)): get_key, values = sess.run(get) self.assertTrue(i == k == get_key == values) self.assertTrue(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 __setitem__(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 feed_hot(): off = request.args.get("offset") or 0 all_books = ub.session.query(ub.Downloads, func.count(ub.Downloads.book_id)).order_by( func.count(ub.Downloads.book_id).desc()).group_by(ub.Downloads.book_id) hot_books = all_books.offset(off).limit(config.config_books_per_page) entries = list() for book in hot_books: downloadBook = calibre_db.get_book(book.Downloads.book_id) if downloadBook: entries.append( calibre_db.get_filtered_book(book.Downloads.book_id) ) else: ub.delete_download(book.Downloads.book_id) numBooks = entries.__len__() pagination = Pagination((int(off) / (int(config.config_books_per_page)) + 1), config.config_books_per_page, numBooks) 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 boboAwareZopeTraverse(object, path_items, econtext): """Traverses a sequence of names, first trying attributes then items. This uses zope.traversing path traversal where possible and interacts correctly with objects providing OFS.interface.ITraversable when necessary (bobo-awareness). """ request = getattr(econtext, 'request', None) path_items = list(path_items) path_items.reverse() while path_items: name = path_items.pop() if name == '_': warnings.warn('Traversing to the name `_` is deprecated ' 'and will be removed in Zope 6.', DeprecationWarning) elif name.startswith('_'): raise NotFound(name) if OFS.interfaces.ITraversable.providedBy(object): object = object.restrictedTraverse(name) else: object = traversePathElement(object, name, path_items, request=request) return object
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 scriptPath(*pathSegs): startPath = os.path.dirname(os.path.dirname(os.path.realpath(__file__))) return os.path.join(startPath, *pathSegs)
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 read_templates( self, filenames: List[str], custom_template_directory: Optional[str] = None, autoescape: bool = False,
0
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
vulnerable
def tempdir(change_dir=False): tmpdir = mkdtemp() yield tmpdir shutil.rmtree(tmpdir)
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 file(path): path = secure_filename(path) if app.interface.encrypt and isinstance(app.interface.examples, str) and path.startswith(app.interface.examples): with open(os.path.join(app.cwd, path), "rb") as encrypted_file: encrypted_data = encrypted_file.read() file_data = encryptor.decrypt( app.interface.encryption_key, encrypted_data) return send_file(io.BytesIO(file_data), attachment_filename=os.path.basename(path)) else: return send_file(os.path.join(app.cwd, path))
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 __init__(self, conn=None, host=None, result=None, comm_ok=True, diff=dict()): # which host is this ReturnData about? if conn is not None: self.host = conn.host delegate = getattr(conn, 'delegate', None) if delegate is not None: self.host = delegate else: self.host = host self.result = result self.comm_ok = comm_ok # if these values are set and used with --diff we can show # changes made to particular files self.diff = diff if type(self.result) in [ str, unicode ]: self.result = utils.parse_json(self.result) if self.host is None: raise Exception("host not set") if type(self.result) != dict: raise Exception("dictionary result expected")
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