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 history_data(start_time, offset=None): """Return history data. Arguments: start_time: select history starting from this timestamp. offset: number of items to skip """ # history atimes are stored as ints, ensure start_time is not a float start_time = int(start_time) hist = objreg.get('web-history') if offset is not None: entries = hist.entries_before(start_time, limit=1000, offset=offset) else: # end is 24hrs earlier than start end_time = start_time - 24*60*60 entries = hist.entries_between(end_time, start_time) return [{"url": html.escape(e.url), "title": html.escape(e.title) or html.escape(e.url), "time": e.atime} for e in entries]
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 parse_soap_enveloped_saml(text, body_class, header_class=None): """Parses a SOAP enveloped SAML thing and returns header parts and body :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = defusedxml.ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope)) body = None header = {} for part in envelope: # print(">",part.tag) if part.tag == '{%s}Body' % NAMESPACE: for sub in part: try: body = saml2.create_class_from_element_tree(body_class, sub) except Exception: raise Exception( "Wrong body type (%s) in SOAP envelope" % sub.tag) elif part.tag == '{%s}Header' % NAMESPACE: if not header_class: raise Exception("Header where I didn't expect one") # print("--- HEADER ---") for sub in part: # print(">>",sub.tag) for klass in header_class: # print("?{%s}%s" % (klass.c_namespace,klass.c_tag)) if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag): header[sub.tag] = \ saml2.create_class_from_element_tree(klass, sub) break return body, header
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 setUp(self): # Create a new sydent self.sydent = make_sydent()
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 _register_function_args(context: Context, sig: FunctionSignature) -> List[IRnode]: ret = [] # the type of the calldata base_args_t = TupleType([arg.typ for arg in sig.base_args]) # tuple with the abi_encoded args if sig.is_init_func: base_args_ofst = IRnode(0, location=DATA, typ=base_args_t, encoding=Encoding.ABI) else: base_args_ofst = IRnode(4, location=CALLDATA, typ=base_args_t, encoding=Encoding.ABI) for i, arg in enumerate(sig.base_args): arg_ir = get_element_ptr(base_args_ofst, i) if _should_decode(arg.typ): # allocate a memory slot for it and copy p = context.new_variable(arg.name, arg.typ, is_mutable=False) dst = IRnode(p, typ=arg.typ, location=MEMORY) copy_arg = make_setter(dst, arg_ir) copy_arg.source_pos = getpos(arg.ast_source) ret.append(copy_arg) else: # leave it in place context.vars[arg.name] = VariableRecord( name=arg.name, pos=arg_ir, typ=arg.typ, mutable=False, location=arg_ir.location, encoding=Encoding.ABI, ) return ret
0
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
vulnerable
def parse(self, source): return ast.parse(source, type_comments=True)
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 _is_javascript_scheme(s): is_image_url = False for image_type in _find_image_dataurls(s): is_image_url = True if _is_unsafe_image_type(image_type): return True if is_image_url: return False return bool(_is_possibly_malicious_scheme(s))
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_spawn_netinject_file(self): self.flags(flat_injected=True) db_fakes.stub_out_db_instance_api(self.stubs, injected=True) self._tee_executed = False def _tee_handler(cmd, **kwargs): input = kwargs.get('process_input', None) self.assertNotEqual(input, None) config = [line.strip() for line in input.split("\n")] # Find the start of eth0 configuration and check it index = config.index('auto eth0') self.assertEquals(config[index + 1:index + 8], [ 'iface eth0 inet static', 'address 192.168.1.100', 'netmask 255.255.255.0', 'broadcast 192.168.1.255', 'gateway 192.168.1.1', 'dns-nameservers 192.168.1.3 192.168.1.4', '']) self._tee_executed = True return '', '' def _readlink_handler(cmd_parts, **kwargs): return os.path.realpath(cmd_parts[2]), '' fake_utils.fake_execute_set_repliers([ # Capture the tee .../etc/network/interfaces command (r'tee.*interfaces', _tee_handler), (r'readlink -nm.*', _readlink_handler), ]) self._test_spawn(IMAGE_MACHINE, IMAGE_KERNEL, IMAGE_RAMDISK, check_injection=True) self.assertTrue(self._tee_executed)
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 testSparseCountSparseOutputBadWeightsShape(self): indices = [[0, 0], [0, 1], [1, 0], [1, 2]] values = [1, 1, 1, 10] weights = [1, 2, 4] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Weights and values must have the same shape"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False))
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 generate(bits, randfunc, progress_func=None): """Randomly generate a fresh, new ElGamal key. :Parameters: bits : int Key length, or size (in bits) of the modulus *p*. Recommended value is 2048. randfunc : callable Random number generation function; it should accept a single integer N and return a string of random data N bytes long. progress_func : callable Optional function that will be called with a short string containing the key parameter currently being generated; it's useful for interactive applications where a user is waiting for a key to be generated. :attention: You should always use a cryptographically secure random number generator, such as the one defined in the ``Crypto.Random`` module; **don't** just use the current time and the ``random`` module. :Return: An ElGamal key object (`ElGamalobj`). """ obj=ElGamalobj() # Generate prime p if progress_func: progress_func('p\n') obj.p=bignum(getPrime(bits, randfunc)) # Generate random number g if progress_func: progress_func('g\n') size=bits-1-(ord(randfunc(1)) & 63) # g will be from 1--64 bits smaller than p if size<1: size=bits-1 while (1): obj.g=bignum(getPrime(size, randfunc)) if obj.g < obj.p: break size=(size+1) % bits if size==0: size=4 # Generate random number x if progress_func: progress_func('x\n') while (1): size=bits-1-ord(randfunc(1)) # x will be from 1 to 256 bits smaller than p if size>2: break while (1): obj.x=bignum(getPrime(size, randfunc)) if obj.x < obj.p: break size = (size+1) % bits if size==0: size=4 if progress_func: progress_func('y\n') obj.y = pow(obj.g, obj.x, obj.p) return obj
0
Python
CWE-310
Cryptographic Issues
Weaknesses in this category are related to the design and implementation of data confidentiality and integrity. Frequently these deal with the use of encoding techniques, encryption libraries, and hashing algorithms. The weaknesses in this category could lead to a degradation of the quality data if they are not addressed.
https://cwe.mitre.org/data/definitions/310.html
vulnerable
def _expand(self, key_material): output = [b""] counter = 1 while self._algorithm.digest_size * (len(output) - 1) < self._length: h = hmac.HMAC(key_material, self._algorithm, backend=self._backend) h.update(output[-1]) h.update(self._info) h.update(six.int2byte(counter)) output.append(h.finalize()) counter += 1 return b"".join(output)[:self._length]
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_date_and_server(self): to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, echo = self._read_echo(fp) self.assertline(line, "200", "OK", "HTTP/1.0") self.assertEqual(headers.get("server"), "waitress") self.assertTrue(headers.get("date"))
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_auth_plugin_prompt_password_in_session(self, httpbin): self.start_session(httpbin) session_path = self.config_dir / 'test-session.json' class Plugin(AuthPlugin): auth_type = 'test-prompted' def get_auth(self, username=None, password=None): basic_auth_header = "Basic " + b64encode(self.raw_auth.encode()).strip().decode('latin1') return basic_auth(basic_auth_header) plugin_manager.register(Plugin) with mock.patch( 'httpie.cli.argtypes.AuthCredentials._getpass', new=lambda self, prompt: 'password' ): r1 = http( '--session', str(session_path), httpbin + '/basic-auth/user/password', '--auth-type', Plugin.auth_type, '--auth', 'user', ) r2 = http( '--session', str(session_path), httpbin + '/basic-auth/user/password', ) assert HTTP_OK in r1 assert HTTP_OK in r2 # additional test for issue: https://github.com/httpie/httpie/issues/1098 with open(session_path) as session_file: session_file_lines = ''.join(session_file.readlines()) assert "\"type\": \"test-prompted\"" in session_file_lines assert "\"raw_auth\": \"user:password\"" in session_file_lines plugin_manager.unregister(Plugin)
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_removes_expired_cookies_from_session_obj(self, initial_cookie, expired_cookie, httpbin): session = Session(self.config_dir) session['cookies'] = initial_cookie session.remove_cookies([expired_cookie]) assert expired_cookie not in session.cookies
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\r\nContent-Length: %s\r\n\r\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in (body[0], body[1:]): expected += tobytes( "%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk) ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response 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 feed_seriesindex(): shift = 0 off = int(request.args.get("offset") or 0) entries = calibre_db.session.query(func.upper(func.substr(db.Series.sort, 1, 1)).label('id'))\ .join(db.books_series_link).join(db.Books).filter(calibre_db.common_filters())\ .group_by(func.upper(func.substr(db.Series.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_series', 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 test_get_problem_responses_invalid_location(self): """ Test whether get_problem_responses returns an appropriate status message when users submit an invalid problem location. """ url = reverse( 'get_problem_responses', kwargs={'course_id': unicode(self.course.id)} ) problem_location = '' response = self.client.get(url, {'problem_location': problem_location}) res_json = json.loads(response.content) self.assertEqual(res_json, 'Could not find problem with this location.')
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_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)], " "type_ignores=[])" )
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 get_markdown(text): if not text: return "" pattern = fr'([\[\s\S\]]*?)\(([\s\S]*?):([\[\s\S\]]*?)\)' # Regex check if re.match(pattern, text): # get get value of group regex scheme = re.search(pattern, text, re.IGNORECASE).group(2) # scheme check if scheme in helpdesk_settings.ALLOWED_URL_SCHEMES: replacement = '\\1(\\2:\\3)' else: replacement = '\\1(\\3)' text = re.sub(pattern, replacement, text, flags=re.IGNORECASE) return mark_safe( markdown( text, extensions=[ EscapeHtml(), 'markdown.extensions.nl2br', 'markdown.extensions.fenced_code' ] ) )
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_user_role_list_requires_auth(self): """User role list should 401 without an X-Auth-Token (bug 1006815).""" # values here don't matter because we should 401 before they're checked path = '/v2.0/tenants/%(tenant_id)s/users/%(user_id)s/roles' % { 'tenant_id': uuid.uuid4().hex, 'user_id': uuid.uuid4().hex, } r = self.admin_request(path=path, expected_status=401) self.assertValidErrorResponse(r)
1
Python
CWE-287
Improper Authentication
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
https://cwe.mitre.org/data/definitions/287.html
safe
def create_option(self, name, value, label, selected, index, subindex=None, attrs=None): result = super(TagFormWidget, self).create_option( name=name, value=value, label='{}'.format(conditional_escape(label)), selected=selected, index=index, subindex=subindex, attrs=attrs ) result['attrs']['data-color'] = self.queryset.get(pk=value).color return result
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 flush(writer=None, name=None): """Forces summary writer to send any buffered data to storage. This operation blocks until that finishes. Args: writer: The `tf.summary.SummaryWriter` to flush. If None, the current default writer will be used instead; if there is no current writer, this returns `tf.no_op`. name: Ignored legacy argument for a name for the operation. Returns: The created `tf.Operation`. """ del name # unused if writer is None: writer = _summary_state.writer if writer is None: return control_flow_ops.no_op() if isinstance(writer, SummaryWriter): return writer.flush() raise ValueError("Invalid argument to flush(): %r" % (writer,))
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_all_to_all_split_count_not_equal_to_group_assignment_shape(self): with self.assertRaisesRegex( ValueError, "split_count 1 must equal the size of the second dimension " "of group_assignment 2"): tpu_ops.all_to_all( x=[0.0, 0.1652, 0.6543], group_assignment=[[0, 1], [2, 3]], concat_dimension=0, split_dimension=0, split_count=1)
1
Python
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
def setUp(self): self.mock_federation_resource = MockHttpResource() self.mock_http_client = Mock(spec=[]) self.mock_http_client.put_json = DeferredMockCallable() hs = yield setup_test_homeserver( self.addCleanup, federation_http_client=self.mock_http_client, keyring=Mock(), ) self.filtering = hs.get_filtering() self.datastore = hs.get_datastore()
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 __init__(self, protocol='http', hostname='localhost', port='8080', subsystem=None, accept='application/json', trust_env=None, verify=True, cert_paths=None):
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 visit_Expression(self, node): return self.visit(node.body)
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_multi_wildcard(self): """patterns with multiple wildcards in a row should match""" pat = glob_to_regex("**baz") self.assertTrue(pat.match("agsgsbaz"), "** should match any string") self.assertTrue(pat.match("baz"), "** should match the empty string") self.assertEqual(pat.pattern, r"\A.{0,}baz\Z") pat = glob_to_regex("*?baz") self.assertTrue(pat.match("agsgsbaz"), "*? should match any string") self.assertTrue(pat.match("abaz"), "*? should match a single char") self.assertFalse(pat.match("baz"), "*? should not match the empty string") self.assertEqual(pat.pattern, r"\A.{1,}baz\Z") pat = glob_to_regex("a?*?*?baz") self.assertTrue(pat.match("a g baz"), "?*?*? should match 3 chars") self.assertFalse(pat.match("a..baz"), "?*?*? should not match 2 chars") self.assertTrue(pat.match("a.gg.baz"), "?*?*? should match 4 chars") self.assertEqual(pat.pattern, r"\Aa.{3,}baz\Z")
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 unarchive(byte_array: bytes, directory: Text) -> Text: """Tries to unpack a byte array interpreting it as an archive. Tries to use tar first to unpack, if that fails, zip will be used.""" try: tar = tarfile.open(fileobj=IOReader(byte_array)) tar.extractall(directory) tar.close() return directory except tarfile.TarError: zip_ref = zipfile.ZipFile(IOReader(byte_array)) zip_ref.extractall(directory) zip_ref.close() return directory
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 __post_init__(self) -> None: super().__post_init__() if self.default is not None: self.default = f'"{self.default}"'
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_get_frontend_context_variables_safe(component): # Set component.name to a potential XSS attack component.name = '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>' class Meta: safe = [ "name", ] setattr(component, "Meta", Meta()) frontend_context_variables = component.get_frontend_context_variables() frontend_context_variables_dict = orjson.loads(frontend_context_variables) assert len(frontend_context_variables_dict) == 1 assert ( frontend_context_variables_dict.get("name") == '<a><style>@keyframes x{}</style><a style="animation-name:x" onanimationend="alert(1)"></a>' )
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 __post_init__(self, title: str) -> None: # type: ignore super().__post_init__() reference = Reference.from_ref(title) dedup_counter = 0 while reference.class_name in _existing_enums: existing = _existing_enums[reference.class_name] if self.values == existing.values: break # This is the same Enum, we're good dedup_counter += 1 reference = Reference.from_ref(f"{reference.class_name}{dedup_counter}") self.reference = reference inverse_values = {v: k for k, v in self.values.items()} if self.default is not None: self.default = f"{self.reference.class_name}.{inverse_values[self.default]}" _existing_enums[self.reference.class_name] = self
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 testConcatInvalidAxisInTfFunction(self): @def_function.function def concat_wrapper(): y = gen_array_ops.concat_v2( values=[[1, 2, 3], [4, 5, 6]], axis=0xb500005b) return y with self.assertRaises(ValueError): concat_wrapper()
1
Python
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
safe
def create(request, topic_id): topic = get_object_or_404(Topic, pk=topic_id) form = FavoriteForm(user=request.user, topic=topic, data=request.POST) if form.is_valid(): form.save() else: messages.error(request, utils.render_form_errors(form)) return redirect(request.POST.get('next', 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 _on_load_started(self) -> None: self._progress = 0 self._has_ssl_errors = False self.data.viewing_source = False self._set_load_status(usertypes.LoadStatus.loading) self.load_started.emit()
0
Python
CWE-684
Incorrect Provision of Specified Functionality
The code does not function according to its published specifications, potentially leading to incorrect usage.
https://cwe.mitre.org/data/definitions/684.html
vulnerable
def get(self, arg,word=None): #print "match auto" try: limit = self.get_argument("limit") word = self.get_argument("word") callback = self.get_argument("callback") #jsonp result = rtxcomplete.prefix(word,limit) result = callback+"("+json.dumps(result)+");" #jsonp #result = json.dumps(result) #typeahead self.write(result) except: print(sys.exc_info()[:]) traceback.print_tb(sys.exc_info()[-1]) #print sys.exc_info()[2] self.write("error")
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(request, pk): like = get_object_or_404(CommentLike, pk=pk, user=request.user) if is_post(request): like.delete() like.comment.decrease_likes_count() if is_ajax(request): url = reverse( 'spirit:comment:like:create', kwargs={'comment_id': like.comment.pk}) return json_response({'url_create': url, }) return redirect(request.POST.get('next', like.comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/like/delete.html', context={'like': like})
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 _glob_matches(glob: str, value: str, word_boundary: bool = False) -> bool: """Tests if value matches glob. Args: glob value: String to test against glob. word_boundary: Whether to match against word boundaries or entire string. Defaults to False. """ try: r = regex_cache.get((glob, True, word_boundary), None) if not r: r = _glob_to_re(glob, word_boundary) regex_cache[(glob, True, word_boundary)] = r return bool(r.search(value)) except re.error: logger.warning("Failed to parse glob to regex: %r", glob) return False
0
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
vulnerable
def __init__(self, hs, tls_client_options_factory): self.hs = hs self.signing_key = hs.signing_key self.server_name = hs.hostname # We need to use a DNS resolver which filters out blacklisted IP # addresses, to prevent DNS rebinding. self.reactor = BlacklistingReactorWrapper( hs.get_reactor(), None, hs.config.federation_ip_range_blacklist ) 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, hs.config.federation_ip_range_blacklist, ) # 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)
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 _deny_hook(self, resource=None): app = self.get_app() if current_user.is_authenticated(): status = 403 else: status = 401 #abort(status) if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') if current_user.is_authenticated(): auth_dict = { "authenticated": True, "user": current_user.email, "roles": current_user.role, } else: auth_dict = { "authenticated": False, "user": None, "url": url } return Response(response=json.dumps({"auth": auth_dict}), status=status, mimetype="application/json")
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 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-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def test_create_catalog(self): pardir = self.get_test_dir(erase=1) cat = catalog.get_catalog(pardir,'c') assert_(cat is not None) cat.close() self.remove_dir(pardir)
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 parse_http_message(kind, buf): if buf._end: return None try: start_line = buf.readline() except EOFError: return None msg = kind() msg.raw = start_line if kind is HttpRequest: assert re.match( br".+ HTTP/\d\.\d\r\n$", start_line ), "Start line does not look like HTTP request: " + repr(start_line) msg.method, msg.uri, msg.proto = start_line.rstrip().decode().split(" ", 2) assert msg.proto.startswith("HTTP/"), repr(start_line) elif kind is HttpResponse: assert re.match( br"^HTTP/\d\.\d \d+ .+\r\n$", start_line ), "Start line does not look like HTTP response: " + repr(start_line) msg.proto, msg.status, msg.reason = start_line.rstrip().decode().split(" ", 2) msg.status = int(msg.status) assert msg.proto.startswith("HTTP/"), repr(start_line) else: raise Exception("Use HttpRequest or HttpResponse .from_{bytes,buffered}") msg.version = msg.proto[5:] while True: line = buf.readline() msg.raw += line line = line.rstrip() if not line: break t = line.decode().split(":", 1) msg.headers[t[0].lower()] = t[1].lstrip() content_length_string = msg.headers.get("content-length", "") if content_length_string.isdigit(): content_length = int(content_length_string) msg.body = msg.body_raw = buf.read(content_length) elif msg.headers.get("transfer-encoding") == "chunked": raise NotImplemented elif msg.version == "1.0": msg.body = msg.body_raw = buf.readall() else: msg.body = msg.body_raw = b"" msg.raw += msg.body_raw return msg
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 edit_book_languages(languages, book, upload=False, invalid=None): input_languages = languages.split(',') unknown_languages = [] if not upload: input_l = isoLanguages.get_language_codes(get_locale(), input_languages, unknown_languages) else: input_l = isoLanguages.get_valid_language_codes(get_locale(), input_languages, unknown_languages) for l in unknown_languages: log.error("'%s' is not a valid language", l) if isinstance(invalid, list): invalid.append(l) else: raise ValueError(_(u"'%(langname)s' is not a valid language", langname=l)) # ToDo: Not working correct if upload and len(input_l) == 1: # If the language of the file is excluded from the users view, it's not imported, to allow the user to view # the book it's language is set to the filter language if input_l[0] != current_user.filter_language() and current_user.filter_language() != "all": input_l[0] = calibre_db.session.query(db.Languages). \ filter(db.Languages.lang_code == current_user.filter_language()).first().lang_code # Remove duplicates input_l = helper.uniq(input_l) return modify_database_object(input_l, book.languages, db.Languages, calibre_db.session, 'languages')
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 testInputPreProcessFormats(self): input_str = 'input1=/path/file.txt[ab3];input2=file2' input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]' input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string( input_expr_str) self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(input_dict['input2'] == ('file2', None)) print(input_expr_dict['input3']) self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2])) self.assertAllClose(input_expr_dict['input4'], [4, 5]) self.assertTrue(len(input_dict) == 2) self.assertTrue(len(input_expr_dict) == 2)
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 decompile(self): self.writeln("** Decompiling APK...", clr.OKBLUE) with ZipFile(self.file) as zipped: try: dex = self.tempdir + "/" + self.apk.package + ".dex" with open(dex, "wb") as classes: classes.write(zipped.read("classes.dex")) except Exception as e: sys.exit(self.writeln(str(e), clr.WARNING)) dec = "%s %s -d %s --deobf" % (self.jadx, dex, self.tempdir) os.system(dec) return self.tempdir
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_get_student_exam_results(self): """ Test whether get_proctored_exam_results returns an appropriate status message when users request a CSV file. """ url = reverse( 'get_proctored_exam_results', kwargs={'course_id': unicode(self.course.id)} ) # Successful case: response = self.client.post(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertNotIn('currently being created', res_json['status']) # CSV generation already in progress: with patch('instructor_task.api.submit_proctored_exam_results_report') as submit_task_function: error = AlreadyRunningError() submit_task_function.side_effect = error response = self.client.post(url, {}) res_json = json.loads(response.content) self.assertIn('status', res_json) self.assertIn('currently being created', res_json['status'])
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def test_template_render_with_autoescape(self): """ Test that HTML is correctly escaped in Browsable API views. """ template = Template("{% load rest_framework %}{{ content|urlize_quoted_links }}") rendered = template.render(Context({'content': '<script>alert()</script> http://example.com'})) assert rendered == '&lt;script&gt;alert()&lt;/script&gt;' \ ' <a href="http://example.com" rel="nofollow">http://example.com</a>'
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 func_begin(self, name): ctype = get_c_type(name) self.emit("PyObject*", 0) self.emit("ast2obj_%s(void* _o)" % (name), 0) self.emit("{", 0) self.emit("%s o = (%s)_o;" % (ctype, ctype), 1) self.emit("PyObject *result = NULL, *value = NULL;", 1) self.emit('if (!o) {', 1) self.emit("Py_RETURN_NONE;", 2) self.emit("}", 1) self.emit('', 0)
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def test_received_cl_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = b"""\ GET /foobar HTTP/8.4 Content-Length: 10 """ result = self.parser.received(data) self.assertEqual(result, 41) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))
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 _build_ssl_context( disable_ssl_certificate_validation, ca_certs, cert_file=None, key_file=None, maximum_version=None, minimum_version=None, key_password=None,
0
Python
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and cause an error illegal_chars = '/:#?@' hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars} denorm_chars = [ c for c in map(chr, range(128, sys.maxunicode)) if (hex_chars & set(unicodedata.decomposition(c).split())) and c not in illegal_chars ] # Sanity check that we found at least one such character self.assertIn('\u2100', denorm_chars) self.assertIn('\uFF03', denorm_chars) # bpo-36742: Verify port separators are ignored when they # existed prior to decomposition urllib.parse.urlsplit('http://\u30d5\u309a:80') with self.assertRaises(ValueError): urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380') for scheme in ["http", "https", "ftp"]: for c in denorm_chars: url = "{}://netloc{}false.netloc/path".format(scheme, c) with self.subTest(url=url, char='{:04X}'.format(ord(c))): with self.assertRaises(ValueError): urllib.parse.urlsplit(url)
0
Python
CWE-522
Insufficiently Protected Credentials
The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval.
https://cwe.mitre.org/data/definitions/522.html
vulnerable
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType: if isinstance(typ, new.BoolDefinition): return old.BaseType("bool") if isinstance(typ, new.AddressDefinition): return old.BaseType("address") if isinstance(typ, new.InterfaceDefinition): return old.InterfaceType(typ._id) if isinstance(typ, new.BytesMDefinition): m = typ._length # type: ignore return old.BaseType(f"bytes{m}") if isinstance(typ, new.BytesArrayDefinition): return old.ByteArrayType(typ.length) if isinstance(typ, new.StringDefinition): return old.StringType(typ.length) if isinstance(typ, new.DecimalDefinition): return old.BaseType("decimal") if isinstance(typ, new.SignedIntegerAbstractType): bits = typ._bits # type: ignore return old.BaseType("int" + str(bits)) if isinstance(typ, new.UnsignedIntegerAbstractType): bits = typ._bits # type: ignore return old.BaseType("uint" + str(bits)) if isinstance(typ, new.ArrayDefinition): return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length) if isinstance(typ, new.DynamicArrayDefinition): return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length) if isinstance(typ, new.TupleDefinition): return old.TupleType(typ.value_type) if isinstance(typ, new.StructDefinition): return old.StructType( {n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id ) raise InvalidType(f"unknown type {typ}")
0
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
vulnerable
def initSession(self, expire_on_commit=True): self.session = self.session_factory() self.session.expire_on_commit = expire_on_commit self.update_title_sort(self.config)
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 exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None): ''' run a command on the zone ''' ### TODO: Why all the precautions not to specify /bin/sh? (vs jail.py) if executable == '/bin/sh': executable = None 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 test_credits_view_rst(self): response = self.get_credits("rst") self.assertEqual(response.status_code, 200) self.assertEqual( response.content.decode(), "\n\n* Czech\n\n * Weblate Test <[email protected]> (1)\n\n", )
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 home_get_preview(): vId = request.form['vId'] t = (vId,) d = db.sentences_stats('get_preview', t) n = db.sentences_stats('id_networks', t) return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});
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 test_enrollment_report_features_csv(self): """ test to generate enrollment report. enroll users, admin staff using registration codes. """ InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=self.sale_invoice_1.total_amount, status='completed', created_by=self.instructor, last_modified_by=self.instructor ) course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) admin_user = AdminFactory() admin_cart = Order.get_cart_for_user(admin_user) PaidCourseRegistration.add_to_order(admin_cart, self.course.id) admin_cart.purchase() # create a new user/student and enroll # in the course using a registration code # and then validates the generated detailed enrollment report test_user = UserFactory() self.register_with_redemption_code(test_user, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}') 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 testOutputSizeOutOfBounds(self): tf_in = constant_op.constant( -3.5e+35, shape=[10, 19, 22], dtype=dtypes.float32) block_shape = constant_op.constant( 1879048192, shape=[2], dtype=dtypes.int64) paddings = constant_op.constant(0, shape=[2, 2], dtype=dtypes.int32) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "Negative.* dimension size caused by overflow"): array_ops.space_to_batch_nd(tf_in, block_shape, paddings)
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 login(): form = forms.UserForm() if form.validate_on_submit(): db = get_db() user = db.search( (Query().username == form.username.data) & (Query().type == "user") ) if user and check_password_hash(user[0]["hashed_password"], form.password.data): user = User.from_db(user[0]) login_user(user, remember=True) flash("Login successful!", "success") next_url = request.args.get("next") return redirect(next_url or "/") flash("Invalid credentials", "error") return redirect("/login") return render_template("users/login.html", form=form, title="Login")
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 setUp(self): # Find root page self.root_page = Page.objects.get(id=2) # Add child page child_page = SimplePage( title="Hello world!", slug="hello-world", content="hello", ) self.root_page.add_child(instance=child_page) child_page.save_revision().publish() self.child_page = SimplePage.objects.get(id=child_page.id) # Login self.user = self.login() # Add a couple more users self.subscriber = self.create_user('subscriber') self.non_subscriber = self.create_user('non-subscriber') self.non_subscriber_2 = self.create_user('non-subscriber-2') self.never_emailed_user = self.create_user('never-emailed') PageSubscription.objects.create( page=self.child_page, user=self.user, comment_notifications=True ) PageSubscription.objects.create( page=self.child_page, user=self.subscriber, comment_notifications=True ) # Add comment and reply on a different page for the never_emailed_user # They should never be notified comment_on_other_page = Comment.objects.create( page=self.root_page, user=self.never_emailed_user, text='a comment' ) CommentReply.objects.create( user=self.never_emailed_user, comment=comment_on_other_page, text='a reply' )
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 receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest], 2) return json.dumps({'status' : 'OK', 'vId' : vrequest});
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 test_siblings_cant_talk_master(self): self.router.unidirectional = True test_siblings_cant_talk(self.router)
1
Python
CWE-254
7PK - Security Features
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
https://cwe.mitre.org/data/definitions/254.html
safe
def test_forstmt(self): tree = self.parse(forstmt) self.assertEqual(tree.body[0].type_comment, "int") tree = self.classic_parse(forstmt) self.assertEqual(tree.body[0].type_comment, None)
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def test_underscore_traversal(self): # Prevent traversal to names starting with an underscore (_) ec = self._makeContext() with self.assertRaises(NotFound): ec.evaluate("context/__class__") with self.assertRaises(NotFound): ec.evaluate("nocall: random/_itertools/repeat") with self.assertRaises(NotFound): ec.evaluate("random/_itertools/repeat/foobar")
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 is_safe_url(url, host=None): """ Return ``True`` if the url is a safe redirection (i.e. it doesn't point to a different host and uses a safe scheme). Always returns ``False`` on an empty url. """ if url is not None: url = url.strip() if not url: return False # Chrome treats \ completely as / url = url.replace('\\', '/') # Chrome considers any URL with more than two slashes to be absolute, but # urlparse is not so flexible. Treat any url with three slashes as unsafe. if url.startswith('///'): return False url_info = urlparse(url) # Forbid URLs like http:///example.com - with a scheme, but without a hostname. # In that URL, example.com is not the hostname but, a path component. However, # Chrome will still consider example.com to be the hostname, so we must not # allow this syntax. if not url_info.netloc and url_info.scheme: return False # Forbid URLs that start with control characters. Some browsers (like # Chrome) ignore quite a few control characters at the start of a # URL and might consider the URL as scheme relative. if unicodedata.category(url[0])[0] == 'C': return False return ((not url_info.netloc or url_info.netloc == host) and (not url_info.scheme or url_info.scheme in ['http', 'https']))
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 authenticate(self, request, username=None, code=None, **kwargs): if username is None: username = kwargs.get(get_user_model().USERNAME_FIELD) if not username or not code: return try: user = get_user_model()._default_manager.get_by_natural_key(username) if not self.user_can_authenticate(user): return timeout = getattr(settings, 'NOPASSWORD_LOGIN_CODE_TIMEOUT', 900) timestamp = timezone.now() - timedelta(seconds=timeout) # We don't delete the login code when authenticating, # as that is done during validation of the login form # and validation should not have any side effects. # It is the responsibility of the view/form to delete the token # as soon as the login was successfull. user.login_code = LoginCode.objects.get(user=user, code=code, timestamp__gt=timestamp) return user except (get_user_model().DoesNotExist, LoginCode.DoesNotExist): return
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 add_security_headers(resp): resp.headers['Content-Security-Policy'] = "default-src 'self'" + ''.join([' '+host for host in config.config_trustedhosts.strip().split(',')]) + " 'unsafe-inline' 'unsafe-eval'; font-src 'self' data:; img-src 'self' data:" if request.endpoint == "editbook.edit_book" or config.config_use_google_drive: resp.headers['Content-Security-Policy'] += " *" elif request.endpoint == "web.read_book": resp.headers['Content-Security-Policy'] += " blob:;style-src-elem 'self' blob: 'unsafe-inline';" resp.headers['X-Content-Type-Options'] = 'nosniff' resp.headers['X-Frame-Options'] = 'SAMEORIGIN' resp.headers['X-XSS-Protection'] = '1; mode=block' resp.headers['Strict-Transport-Security'] = 'max-age=31536000;' return resp
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 parse_soap_enveloped_saml(text, body_class, header_class=None): """Parses a SOAP enveloped SAML thing and returns header parts and body :param text: The SOAP object as XML :return: header parts and body as saml.samlbase instances """ envelope = ElementTree.fromstring(text) assert envelope.tag == '{%s}Envelope' % NAMESPACE # print(len(envelope)) body = None header = {} for part in envelope: # print(">",part.tag) if part.tag == '{%s}Body' % NAMESPACE: for sub in part: try: body = saml2.create_class_from_element_tree(body_class, sub) except Exception: raise Exception( "Wrong body type (%s) in SOAP envelope" % sub.tag) elif part.tag == '{%s}Header' % NAMESPACE: if not header_class: raise Exception("Header where I didn't expect one") # print("--- HEADER ---") for sub in part: # print(">>",sub.tag) for klass in header_class: # print("?{%s}%s" % (klass.c_namespace,klass.c_tag)) if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag): header[sub.tag] = \ saml2.create_class_from_element_tree(klass, sub) break return body, header
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 is_leaf(cls, path): filesystem_path = pathutils.path_to_filesystem(path, filesystem.FOLDER) return (os.path.isdir(filesystem_path) and os.path.exists(path + ".props"))
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 fetch(cls) -> "InstanceConfig": entry = cls.get(get_instance_name()) if entry is None: entry = cls() entry.save() return entry
0
Python
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
vulnerable
def make_homeserver(self, reactor, clock): self.http_client = Mock() hs = self.setup_test_homeserver(federation_http_client=self.http_client) 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 get_auth(self, username=None, password=None): basic_auth_header = "Basic " + b64encode(self.raw_auth.encode()).strip().decode('latin1') return basic_auth(basic_auth_header)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def validate_and_sanitize_search_inputs(fn, instance, args, kwargs): kwargs.update(dict(zip(fn.__code__.co_varnames, args))) sanitize_searchfield(kwargs['searchfield']) kwargs['start'] = cint(kwargs['start']) kwargs['page_len'] = cint(kwargs['page_len']) if kwargs['doctype'] and not frappe.db.exists('DocType', kwargs['doctype']): return [] return fn(**kwargs)
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 setUp(self): self.mock_resource = MockHttpResource(prefix=PATH_PREFIX) self.mock_handler = Mock( spec=[ "get_displayname", "set_displayname", "get_avatar_url", "set_avatar_url", "check_profile_query_allowed", ] ) self.mock_handler.get_displayname.return_value = defer.succeed(Mock()) self.mock_handler.set_displayname.return_value = defer.succeed(Mock()) self.mock_handler.get_avatar_url.return_value = defer.succeed(Mock()) self.mock_handler.set_avatar_url.return_value = defer.succeed(Mock()) self.mock_handler.check_profile_query_allowed.return_value = defer.succeed( Mock() ) hs = yield setup_test_homeserver( self.addCleanup, "test", http_client=None, resource_for_client=self.mock_resource, federation=Mock(), federation_client=Mock(), profile_handler=self.mock_handler, ) async def _get_user_by_req(request=None, allow_guest=False): return synapse.types.create_requester(myid) hs.get_auth().get_user_by_req = _get_user_by_req profile.register_servlets(hs, self.mock_resource)
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_write_err(self, *_): """ If there is a problem with the write, the file is still closed. """ class MockException(Exception): pass mock_fp = open.return_value mock_fp.write.side_effect = MockException self.assertRaises(MockException, cli.write_to_location, 'test/loc', 'content') 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 stream_exists_backend(request, user_profile, stream_id, autosubscribe): # type: (HttpRequest, UserProfile, int, bool) -> HttpResponse try: stream = get_and_validate_stream_by_id(stream_id, user_profile.realm) except JsonableError: stream = None result = {"exists": bool(stream)} if stream is not None: recipient = get_recipient(Recipient.STREAM, stream.id) if autosubscribe: bulk_add_subscriptions([stream], [user_profile]) result["subscribed"] = is_active_subscriber( user_profile=user_profile, recipient=recipient) return json_success(result) # results are ignored for HEAD requests return json_response(data=result, status=404)
0
Python
CWE-863
Incorrect Authorization
The software performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check. This allows attackers to bypass intended access restrictions.
https://cwe.mitre.org/data/definitions/863.html
vulnerable
def __getattr__(_self, attr): if attr == "nameResolver": return nameResolver else: return getattr(real_reactor, attr)
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_get_size_from_conf_custom_invalid(self, conf_ceph_stub): conf_ceph_stub(''' [global] fsid=asdf [osd] osd_dmcrypt_key_size=1024 ''') assert encryption.get_key_size_from_conf() == '512'
1
Python
NVD-CWE-noinfo
null
null
null
safe
def __init__(self, sourceName: str): self.sourceName = sourceName self.type = "file" self.content = None
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 _fill(self, target=1, more=None, untilend=False): if more: target = len(self._buf) + more while untilend or (len(self._buf) < target): # crutch to enable HttpRequest.from_bytes if self._sock is None: chunk = b"" else: chunk = self._sock.recv(8 << 10) # print('!!! recv', chunk) if not chunk: self._end = True if untilend: return else: raise EOFError self._buf += chunk
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 project_configure(request, project_name): """ get configuration :param request: request object :param project_name: project name :return: json """ # get configuration if request.method == 'GET': project = Project.objects.get(name=project_name) project = model_to_dict(project) project['configuration'] = json.loads(project['configuration']) if project['configuration'] else None return JsonResponse(project) # update configuration elif request.method == 'POST': project = Project.objects.filter(name=project_name) data = json.loads(request.body) configuration = json.dumps(data.get('configuration'), ensure_ascii=False) project.update(**{'configuration': configuration}) # for safe protection project_name = re.sub('[\!\@\#\$\;\&\*\~\"\'\{\}\]\[\-\+\%\^]+', '', project_name) # execute generate cmd cmd = ' '.join(['gerapy', 'generate', project_name]) p = Popen(cmd, shell=True, stdin=PIPE, stdout=PIPE, stderr=PIPE) stdout, stderr = bytes2str(p.stdout.read()), bytes2str(p.stderr.read()) if not stderr: return JsonResponse({'status': '1'}) else: return JsonResponse({'status': '0', 'message': stderr})
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def prepare(self, reactor, clock, hs): # build a replication server server_factory = ReplicationStreamProtocolFactory(hs) self.streamer = hs.get_replication_streamer() self.server = server_factory.buildProtocol(None) # Make a new HomeServer object for the worker self.reactor.lookups["testserv"] = "1.2.3.4" self.worker_hs = self.setup_test_homeserver( http_client=None, homeserver_to_use=GenericWorkerServer, config=self._get_worker_hs_config(), reactor=self.reactor, ) # Since we use sqlite in memory databases we need to make sure the # databases objects are the same. self.worker_hs.get_datastore().db_pool = hs.get_datastore().db_pool self.test_handler = self._build_replication_data_handler() self.worker_hs._replication_data_handler = self.test_handler repl_handler = ReplicationCommandHandler(self.worker_hs) self.client = ClientReplicationStreamProtocol( self.worker_hs, "client", "test", clock, repl_handler, ) self._client_transport = None self._server_transport = None
0
Python
CWE-601
URL Redirection to Untrusted Site ('Open Redirect')
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
https://cwe.mitre.org/data/definitions/601.html
vulnerable
def valid_id(opts, id_): ''' Returns if the passed id is valid ''' try: if any(x in id_ for x in ('/', '\\', '\0')): return False return bool(clean_path(opts['pki_dir'], id_)) except (AttributeError, KeyError, TypeError): return False
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_received_trailer_startswith_lf(self): buf = DummyBuffer() inst = self._makeOne(buf) inst.all_chunks_received = True result = inst.received(b"\n") self.assertEqual(result, 1) self.assertEqual(inst.completed, True)
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 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-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 get(self, section, option): if section == 'memcache': if option == 'memcache_servers': return '1.2.3.4:5' elif option == 'memcache_serialization_support': return '2' else: raise NoOptionError(option) else: raise NoSectionError(option)
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_invoice_payment_is_still_pending_for_registration_codes(self): """ test generate enrollment report enroll a user in a course using registration code whose invoice has not been paid yet """ course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, 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.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content)
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_27_checksecure_quoted_command(self): """ U27 | quoted command should be parsed """ INPUT = '"bash" && echo 1' return self.assertEqual(sec.check_secure(INPUT, self.userconf)[0], 1)
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 func_begin(self, name): ctype = get_c_type(name) self.emit("PyObject*", 0) self.emit("ast2obj_%s(void* _o)" % (name), 0) self.emit("{", 0) self.emit("%s o = (%s)_o;" % (ctype, ctype), 1) self.emit("PyObject *result = NULL, *value = NULL;", 1) self.emit('if (!o) {', 1) self.emit("Py_INCREF(Py_None);", 2) self.emit('return Py_None;', 2) self.emit("}", 1) self.emit('', 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 test_keepalive_http10_explicit(self): # If header Connection: Keep-Alive is explicitly sent, # we want to keept the connection open, we also need to return # the corresponding header data = "Keep me alive" s = tobytes( "GET / HTTP/1.0\n" "Connection: Keep-Alive\n" "Content-Length: %d\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) connection = response.getheader("Connection", "") self.assertEqual(connection, "Keep-Alive")
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 upload_new_file_gdrive(book_id, first_author, renamed_author, title, title_dir, original_filepath, filename_ext): error = False book = calibre_db.get_book(book_id) file_name = get_valid_filename(title, chars=42) + ' - ' + \ get_valid_filename(first_author, chars=42) + \ filename_ext rename_all_authors(first_author, renamed_author, gdrive=True) gdrive_path = os.path.join(get_valid_filename(first_author, chars=96), title_dir + " (" + str(book_id) + ")") book.path = gdrive_path.replace("\\", "/") gd.uploadFileToEbooksFolder(os.path.join(gdrive_path, file_name).replace("\\", "/"), original_filepath) return rename_files_on_change(first_author, renamed_author, localbook=book, gdrive=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 sentences_stats(self, type, vId = None): return self.sql_execute(self.prop_sentences_stats(type, vId))
0
Python
CWE-89
Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
The software constructs all or part of an SQL command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended SQL command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/89.html
vulnerable
def _ssl_wrap_socket( sock, key_file, cert_file, disable_validation, ca_certs, ssl_version, hostname, key_password
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 prepare_context(self, request, context, *args, **kwargs): """ Hook for adding additional data to the context dict """ pass
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 transact(self, setup): self.dir = 'queries/graphql_query/permissions' with open(self.dir + '/user_select_query_unpublished_articles.yaml') as c: self.conf = yaml.safe_load(c) curr_time = datetime.now() exp_time = curr_time + timedelta(hours=1) self.claims = { 'sub': '1234567890', 'name': 'John Doe', 'iat': math.floor(curr_time.timestamp()), 'exp': math.floor(exp_time.timestamp()) }
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_quotas_update_as_user(self): body = {'quota_class_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-class-sets/test_class') self.assertRaises(webob.exc.HTTPForbidden, self.controller.update, req, 'test_class', 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 call(__self, __context, __obj, *args, **kwargs): """Call an object from sandboxed code.""" fmt = inspect_format_method(__obj) if fmt is not None: return __self.format_string(fmt, args, kwargs) # the double prefixes are to avoid double keyword argument # errors when proxying the call. if not __self.is_safe_callable(__obj): raise SecurityError('%r is not safely callable' % (__obj,)) return __context.call(__obj, *args, **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 sanitize_path(path): """Make absolute (with leading slash) to prevent access to other data. Preserves an potential trailing slash.""" trailing_slash = "/" if path.endswith("/") else "" path = posixpath.normpath(path) new_path = "/" for part in path.split("/"): if not part or part in (".", ".."): continue new_path = posixpath.join(new_path, part) trailing_slash = "" if new_path.endswith("/") else trailing_slash return new_path + trailing_slash
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): self.reqparse = reqparse.RequestParser() super(AuthenticatedService, self).__init__() self.auth_dict = dict() if current_user.is_authenticated(): roles_marshal = [] for role in current_user.roles: roles_marshal.append(marshal(role.__dict__, ROLE_FIELDS)) roles_marshal.append({"name": current_user.role}) for role in RBACRole.roles[current_user.role].get_parents(): roles_marshal.append({"name": role.name}) self.auth_dict = { "authenticated": True, "user": current_user.email, "roles": roles_marshal } else: if app.config.get('FRONTED_BY_NGINX'): url = "https://{}:{}{}".format(app.config.get('FQDN'), app.config.get('NGINX_PORT'), '/login') else: url = "http://{}:{}{}".format(app.config.get('FQDN'), app.config.get('API_PORT'), '/login') self.auth_dict = { "authenticated": False, "user": None, "url": 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_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-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 get_mime_for_format(self, format): """ Given a format, attempts to determine the correct MIME type. If not available on the current ``Serializer``, returns ``application/json`` by default. """ try: return self.content_types[format] except KeyError: return 'application/json'
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