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_expect_continue(self): # specifying Connection: close explicitly data = "I have expectations" to_send = tobytes( "GET / HTTP/1.1\n" "Connection: close\n" "Content-Length: %d\n" "Expect: 100-continue\n" "\n" "%s" % (len(data), data) ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line = fp.readline() # continue status line version, status, reason = (x.strip() for x in line.split(None, 2)) self.assertEqual(int(status), 100) self.assertEqual(reason, b"Continue") self.assertEqual(version, b"HTTP/1.1") fp.readline() # blank line line = fp.readline() # next status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) length = int(headers.get("content-length")) or None response_body = fp.read(length) self.assertEqual(int(status), 200) self.assertEqual(length, len(response_body)) self.assertEqual(response_body, tobytes(data))
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 to_yaml(self, data, options=None): """ Given some Python data, produces YAML output. """ options = options or {} if yaml is None: raise ImproperlyConfigured("Usage of the YAML aspects requires yaml.") return yaml.dump(self.to_simple(data, options))
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 testUnravelIndexZeroDim(self): with self.cached_session(): for dtype in [dtypes.int32, dtypes.int64]: with self.assertRaisesRegex(errors.InvalidArgumentError, "dims cannot contain a dim of zero"): indices = constant_op.constant([2, 5, 7], dtype=dtype) dims = constant_op.constant([3, 0], dtype=dtype) self.evaluate(array_ops.unravel_index(indices=indices, dims=dims))
1
Python
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
def _affinity_host(self, context, instance_id): return self.compute_api.get(context, instance_id)['host']
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 dirs_are_valid(self, wrong_dir, tmpdir): """ test if new dir is created and is consistent """ new_im_dir = catalog.intermediate_dir(tmpdir) assert_(not os.path.samefile(new_im_dir, wrong_dir)) new_im_dir2 = catalog.intermediate_dir(tmpdir) assert_(os.path.samefile(new_im_dir, new_im_dir2))
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def test_list_email_content_error(self, task_history_request): """ Test handling of error retrieving email """ invalid_task = FakeContentTask(0, 0, 0, 'test') invalid_task.make_invalid_input() task_history_request.return_value = [invalid_task] url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, {}) self.assertEqual(response.status_code, 200) self.assertTrue(task_history_request.called) returned_email_info = json.loads(response.content)['emails'] self.assertEqual(len(returned_email_info), 1) returned_info = returned_email_info[0] for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']: self.assertEqual(returned_info[info], None)
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def to_xml(self, data, options=None): """ Given some Python data, produces XML output. """ options = options or {} if lxml is None: raise ImproperlyConfigured("Usage of the XML aspects requires lxml.") return tostring(self.to_etree(data, options), xml_declaration=True, encoding='utf-8')
0
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def test_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-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 testSparseDenseInvalidInputs(self): self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(0, shape=[17, 2], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[5], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="Dimensions 17 and 5 are not compatible") self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(0, shape=[17, 4], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[17], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="Dimensions 4 and 2 are not compatible") self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(7, shape=[17, 2], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[17], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="invalid index")
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 MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt)
0
Python
CWE-916
Use of Password Hash With Insufficient Computational Effort
The software generates a hash for a password, but it uses a scheme that does not provide a sufficient level of computational effort that would make password cracking attacks infeasible or expensive.
https://cwe.mitre.org/data/definitions/916.html
vulnerable
def test_request_body_too_large_with_no_cl_http11_connclose(self): body = "a" * self.toobig to_send = "GET / HTTP/1.1\nConnection: close\n\n" to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) # server trusts the content-length header (assumed 0) self.assertline(line, "200", "OK", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def testFeaturesBroadcast(self): np_f = np.array([[1., 2., 3., 4.], [1., 2., 3., 4.]]).astype(np.float32) np_l = np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32) np_loss, np_gradient = self._npXent(labels=np_l, logits=np_f) tf_f = constant_op.constant( np.array([[1., 2., 3., 4.]]).astype(np.float32)) tf_l = constant_op.constant( np.array([[0., 0., 0., 1.], [0., .5, .5, 0.]]).astype(np.float32)) tf_loss, tf_gradient = gen_nn_ops.softmax_cross_entropy_with_logits( tf_f, tf_l) self.assertAllCloseAccordingToType(np_loss, tf_loss) self.assertAllCloseAccordingToType(np_gradient, tf_gradient) tf_f = constant_op.constant(np.array([[1.]]).astype(np.float32)) tf_l = constant_op.constant(np.array([[1.], [1.]]).astype(np.float32)) tf_loss, tf_gradient = gen_nn_ops.softmax_cross_entropy_with_logits( tf_f, tf_l) self.assertAllClose([0, 0], tf_loss) self.assertAllCloseAccordingToType([[0], [0]], tf_gradient)
1
Python
CWE-354
Improper Validation of Integrity Check Value
The software does not validate or incorrectly validates the integrity check values or "checksums" of a message. This may prevent it from detecting if the data has been modified or corrupted in transmission.
https://cwe.mitre.org/data/definitions/354.html
safe
async def actset(self, ctx): """ Configure various settings for the act cog. """
0
Python
CWE-502
Deserialization of Untrusted Data
The application deserializes untrusted data without sufficiently verifying that the resulting data will be valid.
https://cwe.mitre.org/data/definitions/502.html
vulnerable
def classic_parse(self, source): return ast.parse(source)
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_makepasv_issue43285_security_disabled(self): """Test the opt-in to the old vulnerable behavior.""" self.client.trust_server_pasv_ipv4_address = True bad_host, port = self.client.makepasv() self.assertEqual( bad_host, self.server.handler_instance.fake_pasv_server_ip) # Opening and closing a connection keeps the dummy server happy # instead of timing out on accept. socket.create_connection((self.client.sock.getpeername()[0], port), timeout=TIMEOUT).close()
1
Python
NVD-CWE-noinfo
null
null
null
safe
def request(self, method, request_uri, headers, content): """Modify the request headers""" keys = _get_end2end_headers(headers) keylist = "".join(["%s " % k for k in keys]) headers_val = "".join([headers[k] for k in keys]) created = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) cnonce = _cnonce() request_digest = "%s:%s:%s:%s:%s" % ( method, request_uri, cnonce, self.challenge["snonce"], headers_val, ) request_digest = ( hmac.new(self.key, request_digest, self.hashmod).hexdigest().lower() ) headers["authorization"] = ( 'HMACDigest username="%s", realm="%s", snonce="%s",' ' cnonce="%s", uri="%s", created="%s", ' 'response="%s", headers="%s"' ) % ( self.credentials[0], self.challenge["realm"], self.challenge["snonce"], cnonce, request_uri, created, request_digest, keylist, )
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_mapping_file_plain(self): unichrs = lambda s: ''.join(map(chr, map(eval, s.split('+')))) urt_wa = {} with self.open_mapping_file() as f: for line in f: if not line: break data = line.split('#')[0].strip().split() if len(data) != 2: continue csetval = eval(data[0]) if csetval <= 0x7F: csetch = bytes([csetval & 0xff]) elif csetval >= 0x1000000: csetch = bytes([(csetval >> 24), ((csetval >> 16) & 0xff), ((csetval >> 8) & 0xff), (csetval & 0xff)]) elif csetval >= 0x10000: csetch = bytes([(csetval >> 16), ((csetval >> 8) & 0xff), (csetval & 0xff)]) elif csetval >= 0x100: csetch = bytes([(csetval >> 8), (csetval & 0xff)]) else: continue unich = unichrs(data[1]) if ord(unich) == 0xfffd or unich in urt_wa: continue urt_wa[unich] = csetch self._testpoint(csetch, unich)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _build_url(self, path, queries, ignore_prefix): """ Takes a relative path and query parameters, combines them with the base path, and returns the result. Handles utf-8 encoding as necessary. :param path: relative path for this request, relative to self.base_prefix. NOTE: if this parameter starts with a leading '/', this method will strip it and treat it as relative. That is not a standards-compliant way to combine path segments, so be aware. :type path: basestring :param queries: mapping object or a sequence of 2-element tuples, in either case representing key-value pairs to be used as query parameters on the URL. :type queries: mapping object or sequence of 2-element tuples :param ignore_prefix: when building the url, disregard the self.path_prefix :type ignore_prefix: bool :return: path that is a composite of self.path_prefix, path, and queries. May be relative or absolute depending on the nature of self.path_prefix """ # build the request url from the path and queries dict or tuple if not path.startswith(self.path_prefix) and not ignore_prefix: if path.startswith('/'): path = path[1:] path = '/'.join((self.path_prefix, path)) # Check if path is ascii and uses appropriate characters, # else convert to binary or unicode as necessary. try: path = urllib.quote(str(path)) except UnicodeEncodeError: path = urllib.quote(path.encode('utf-8')) except UnicodeDecodeError: path = urllib.quote(path.decode('utf-8')) queries = urllib.urlencode(queries) if queries: path = '?'.join((path, queries)) return path
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 contains(field: Term, value: str) -> Criterion: return field.like(f"%{value}%")
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 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 open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 content = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 content["body"] = ElementTree.tostring(part[0], encoding="UTF-8") elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: _str = ElementTree.tostring(item, encoding="UTF-8") content["header"].append(_str) return content
0
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
vulnerable
def test_jwt_invalid_audience(self, hge_ctx, endpoint): jwt_conf = json.loads(hge_ctx.hge_jwt_conf) if 'audience' not in jwt_conf: pytest.skip('audience not present in conf, skipping testing audience') self.claims['https://hasura.io/jwt/claims'] = mk_claims(hge_ctx.hge_jwt_conf, { 'x-hasura-user-id': '1', 'x-hasura-default-role': 'user', 'x-hasura-allowed-roles': ['user'], }) self.claims['aud'] = 'rubbish_audience' token = jwt.encode(self.claims, hge_ctx.hge_jwt_key, algorithm='RS512').decode('utf-8') self.conf['headers']['Authorization'] = 'Bearer ' + token self.conf['response'] = { 'errors': [{ 'extensions': { 'code': 'invalid-jwt', 'path': '$' }, 'message': 'Could not verify JWT: JWTNotInAudience' }] } self.conf['url'] = endpoint if endpoint == '/v1/graphql': self.conf['status'] = 200 if endpoint == '/v1alpha1/graphql': self.conf['status'] = 400 check_query(hge_ctx, self.conf, add_auth=False)
1
Python
NVD-CWE-noinfo
null
null
null
safe
def test_after_start_response_http11(self): to_send = "GET /after_start_response HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "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"] ) # 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_dir(self, tmpdir): url = QUrl.fromLocalFile(str(tmpdir)) req = QNetworkRequest(url) reply = filescheme.handler(req) # The URL will always use /, even on Windows - so we force this here # too. tmpdir_path = str(tmpdir).replace(os.sep, '/') assert reply.readAll() == filescheme.dirbrowser_html(tmpdir_path)
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 traverse(cls, base, request, path_items): """See ``zope.app.pagetemplate.engine``.""" 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 ITraversable.providedBy(base): base = getattr(base, cls.traverse_method)(name) else: base = traversePathElement(base, name, path_items, request=request) return base
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_symlink_raise(self): """ if existing im dir is a symlink, new one should be created """ if sys.platform != 'win32': tmpdir = tempfile.mkdtemp() try: im_dir = catalog.create_intermediate_dir(tmpdir) root_im_dir = os.path.dirname(im_dir) tempdir = tempfile.mkdtemp(prefix='scipy-test', dir=tmpdir) try: os.rename(root_im_dir, tempdir) except OSError: raise KnownFailureTest("Can't move intermediate dir.") try: os.symlink(tempdir, root_im_dir) except OSError: raise KnownFailureTest( "Can't create symlink to intermediate dir.") else: self.dirs_are_valid(im_dir, tmpdir) finally: remove_tree(tmpdir)
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def 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 testInvalidSparseTensor(self): with test_util.force_cpu(): shape = [2, 2] val = [0] dense = constant_op.constant(np.zeros(shape, dtype=np.int32)) for bad_idx in [ [[-1, 0]], # -1 is invalid. [[1, 3]], # ...so is 3. ]: sparse = sparse_tensor.SparseTensorValue(bad_idx, val, shape) with self.assertRaisesRegex( (ValueError, errors_impl.InvalidArgumentError), "invalid index"): s = sparse_ops.sparse_add(sparse, dense) self.evaluate(s)
1
Python
CWE-476
NULL Pointer Dereference
A NULL pointer dereference occurs when the application dereferences a pointer that it expects to be valid, but is NULL, typically causing a crash or exit.
https://cwe.mitre.org/data/definitions/476.html
safe
def is_internal_attribute(obj, attr): """Test if the attribute given is an internal python attribute. For example this function returns `True` for the `func_code` attribute of python objects. This is useful if the environment method :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden. >>> from jinja2.sandbox import is_internal_attribute >>> is_internal_attribute(str, "mro") True >>> is_internal_attribute(str, "upper") False """ if isinstance(obj, types.FunctionType): if attr in UNSAFE_FUNCTION_ATTRIBUTES: return True elif isinstance(obj, types.MethodType): if attr in UNSAFE_FUNCTION_ATTRIBUTES or \ attr in UNSAFE_METHOD_ATTRIBUTES: return True elif isinstance(obj, type): if attr == 'mro': return True elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)): return True elif isinstance(obj, types.GeneratorType): if attr in UNSAFE_GENERATOR_ATTRIBUTES: return True elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType): if attr in UNSAFE_COROUTINE_ATTRIBUTES: return True elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType): if attri in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES: return True return attr.startswith('__')
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_login_missing_code_post(self): response = self.client.post('/accounts/login/code/') self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].errors, { 'user': ['This field is required.'], 'code': ['This field is required.'], '__all__': ['Unable to log in with provided login code.'] })
1
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
safe
def re_word_boundary(r: str) -> str: """ Adds word boundary characters to the start and end of an expression to require that the match occur as a whole word, but do so respecting the fact that strings starting or ending with non-word characters will change word boundaries. """ # we can't use \b as it chokes on unicode. however \W seems to be okay # as shorthand for [^0-9A-Za-z_]. return r"(^|\W)%s(\W|$)" % (r,)
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 _untarzip_image(path, filename): S3ImageService._test_for_malicious_tarball(path, filename) tar_file = tarfile.open(filename, 'r|gz') tar_file.extractall(path) image_file = tar_file.getnames()[0] tar_file.close() return os.path.join(path, image_file)
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 calc(self, irc, msg, args, text): """<math expression> Returns the value of the evaluated <math expression>. The syntax is Python syntax; the type of arithmetic is floating point. Floating point arithmetic is used in order to prevent a user from being able to crash to the bot with something like '10**10**10**10'. One consequence is that large values such as '10**24' might not be exact. """ try: self.log.info('evaluating %q from %s', text, msg.prefix) x = complex(safe_eval(text, allow_ints=False)) irc.reply(self._complexToString(x)) except OverflowError: maxFloat = math.ldexp(0.9999999999999999, 1024) irc.error(_('The answer exceeded %s or so.') % maxFloat) except InvalidNode as e: irc.error(_('Invalid syntax: %s') % e.args[0]) except NameError as e: irc.error(_('%s is not a defined function.') % e.args[0]) except Exception as e: irc.error(str(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_invalid_identitifer(self): m = ast.Module([ast.Expr(ast.Name(42, ast.Load()))], []) ast.fix_missing_locations(m) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("identifier must be of type str", str(cm.exception))
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
async def on_send_leave_request( self, origin: str, content: JsonDict, room_id: str
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_http11_list(self): body = string.ascii_letters to_send = "GET /list HTTP/1.1\n" "Content-Length: %d\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(headers["content-length"], str(len(body))) self.assertEqual(response_body, tobytes(body)) # remote keeps connection open because it divined the content length # from a length-1 list self.sock.send(to_send) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1")
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 serialize(self, bundle, format='application/json', options={}): """ Given some data and a format, calls the correct method to serialize the data and returns the result. """ desired_format = None for short_format, long_format in self.content_types.items(): if format == long_format: if hasattr(self, "to_%s" % short_format): desired_format = short_format break if desired_format is None: raise UnsupportedFormat("The format indicated '%s' had no available serialization method. Please check your ``formats`` and ``content_types`` on your Serializer." % format) serialized = getattr(self, "to_%s" % desired_format)(bundle, options) return serialized
0
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def get_info_for_package(pkg, channel_id, org_id): log_debug(3, pkg) pkg = map(str, pkg) params = {'name': pkg[0], 'ver': pkg[1], 'rel': pkg[2], 'epoch': pkg[3], 'arch': pkg[4], 'channel_id': channel_id, 'org_id': org_id} # yum repo has epoch="0" not only when epoch is "0" but also if it's NULL if pkg[3] == '0' or pkg[3] == '' or pkg[3]==None: epochStatement = "(epoch is null or epoch = :epoch)" else: epochStatement = "epoch = :epoch" if params['org_id']: orgStatement = "org_id = :org_id" else: orgStatement = "org_id is null" statement = """ select p.path, cp.channel_id, cv.checksum_type, cv.checksum from rhnPackage p join rhnPackageName pn on p.name_id = pn.id join rhnPackageEVR pe on p.evr_id = pe.id join rhnPackageArch pa on p.package_arch_id = pa.id left join rhnChannelPackage cp on p.id = cp.package_id and cp.channel_id = :channel_id join rhnChecksumView cv on p.checksum_id = cv.id where pn.name = :name and pe.version = :ver and pe.release = :rel and %s and pa.label = :arch and %s order by cp.channel_id nulls last """ % (epochStatement, orgStatement) h = rhnSQL.prepare(statement) h.execute(**params) ret = h.fetchone_dict() if not ret: return {'path': None, 'channel_id': None, 'checksum_type': None, 'checksum': None, } return ret
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 __init__(self, method, uri, headers, bodyProducer, persistent=False): """ @param method: The HTTP method for this request, ex: b'GET', b'HEAD', b'POST', etc. @type method: L{bytes} @param uri: The relative URI of the resource to request. For example, C{b'/foo/bar?baz=quux'}. @type uri: L{bytes} @param headers: Headers to be sent to the server. It is important to note that this object does not create any implicit headers. So it is up to the HTTP Client to add required headers such as 'Host'. @type headers: L{twisted.web.http_headers.Headers} @param bodyProducer: L{None} or an L{IBodyProducer} provider which produces the content body to send to the remote HTTP server. @param persistent: Set to C{True} when you use HTTP persistent connection, defaults to C{False}. @type persistent: L{bool} """ self.method = method self.uri = uri self.headers = headers self.bodyProducer = bodyProducer self.persistent = persistent self._parsedURI = None
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 safe_eval(text, allow_ints): node = ast.parse(text, mode='eval') return SafeEvalVisitor(allow_ints).visit(node)
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 feed_read_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, True, True) return render_xml_template('feed.xml', entries=result, 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 stmt(self, stmt, msg=None): mod = ast.Module([stmt], []) self.mod(mod, msg)
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_object(data, position, as_class, tz_aware, uuid_subtype): obj_size = struct.unpack("<i", data[position:position + 4])[0] encoded = data[position + 4:position + obj_size - 1] object = _elements_to_dict(encoded, as_class, tz_aware, uuid_subtype) position += obj_size if "$ref" in object: return (DBRef(object.pop("$ref"), object.pop("$id"), object.pop("$db", None), object), position) return object, position
0
Python
NVD-CWE-Other
Other
NVD is only using a subset of CWE for mapping instead of the entire CWE, and the weakness type is not covered by that subset.
https://nvd.nist.gov/vuln/categories
vulnerable
def testSparseFillEmptyRowsGradNegativeIndexMapValue(self): reverse_index_map = [2, -1] grad_values = [0, 1, 2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, r'Elements in reverse index must be in \[0, 4\)'): self.evaluate( gen_sparse_ops.SparseFillEmptyRowsGrad( reverse_index_map=reverse_index_map, grad_values=grad_values))
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 _dump(self, file=None, format=None): import tempfile if not file: file = tempfile.mktemp() self.load() if not format or format == "PPM": self.im.save_ppm(file) else: file = file + "." + format self.save(file, format) return file
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 _writeHeaders(self, transport, TEorCL): hosts = self.headers.getRawHeaders(b'host', ()) if len(hosts) != 1: raise BadHeaders(u"Exactly one Host header required") # In the future, having the protocol version be a parameter to this # method would probably be good. It would be nice if this method # weren't limited to issuing HTTP/1.1 requests. requestLines = [] requestLines.append( b' '.join( [ _ensureValidMethod(self.method), _ensureValidURI(self.uri), b'HTTP/1.1\r\n', ] ), ) if not self.persistent: requestLines.append(b'Connection: close\r\n') if TEorCL is not None: requestLines.append(TEorCL) for name, values in self.headers.getAllRawHeaders(): requestLines.extend([name + b': ' + v + b'\r\n' for v in values]) requestLines.append(b'\r\n') transport.writeSequence(requestLines)
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 _require_verified_user(self, request): user = request.user if not settings.WAGTAIL_2FA_REQUIRED: # If two factor authentication is disabled in the settings return False if not user.is_authenticated: return False # If the user has no access to the admin anyway then don't require a # verified user here if not ( user.is_staff or user.is_superuser or user.has_perms(["wagtailadmin.access_admin"]) ): return False # Allow the user to a fixed number of paths when not verified user_has_device = django_otp.user_has_device(user, confirmed=True) if request.path in self._get_allowed_paths(user_has_device): return False # For all other cases require that the user is verfied via otp return True
1
Python
NVD-CWE-noinfo
null
null
null
safe
def _consumer(self, auth): auth.process_response() errors = auth.get_errors() if not errors: if auth.is_authenticated: return True else: return False else: current_app.logger.error('Error processing %s' % (', '.join(errors))) return False
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 render_POST(self, request): """ Register with the Identity Server """ send_cors(request) args = get_args(request, ('matrix_server_name', 'access_token')) result = yield self.client.get_json( "matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s" % ( args['matrix_server_name'], urllib.parse.quote(args['access_token']), ), 1024 * 5, ) if 'sub' not in result: raise Exception("Invalid response from homeserver") user_id = result['sub'] tok = yield issueToken(self.sydent, user_id) # XXX: `token` is correct for the spec, but we released with `access_token` # for a substantial amount of time. Serve both to make spec-compliant clients # happy. defer.returnValue({ "access_token": tok, "token": tok, })
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_received_chunked_completed_sets_content_length(self): data = b"""\ GET /foobar HTTP/1.1 Transfer-Encoding: chunked X-Foo: 1 20;\r\n This string has 32 characters\r\n 0\r\n\r\n""" result = self.parser.received(data) self.assertEqual(result, 58) data = data[result:] result = self.parser.received(data) self.assertTrue(self.parser.completed) self.assertTrue(self.parser.error is None) self.assertEqual(self.parser.headers["CONTENT_LENGTH"], "32")
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_can_read_token_from_query_parameters(self): """Tests that Sydent correctly extracts an auth token from query parameters""" self.sydent.run() request, _ = make_request( self.sydent.reactor, "GET", "/_matrix/identity/v2/hash_details?access_token=" + self.test_token ) token = tokenFromRequest(request) self.assertEqual(token, self.test_token)
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 close(self): if self.lock: self.lock.release()
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_parse_header_connection_close(self): data = b"GET /foobar HTTP/1.1\nConnection: close\n\n" self.parser.parse_header(data) self.assertEqual(self.parser.connection_close, 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 __init__(self, env): self._env = env
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_evaluate_dict_key_as_underscore(self): # Traversing to the name `_` will raise a DeprecationWarning # because it will go away in Zope 6. ec = self._makeContext() with warnings.catch_warnings(): warnings.simplefilter('ignore') self.assertEqual(ec.evaluate('d/_'), 'under')
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 edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date
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_type_string(data): """ Translates a Python data type into a string format. """ data_type = type(data) if data_type in (int, long): return 'integer' elif data_type == float: return 'float' elif data_type == bool: return 'boolean' elif data_type in (list, tuple): return 'list' elif data_type == dict: return 'hash' elif data is None: return 'null' elif isinstance(data, basestring): return 'string'
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 testParallelConcatShapeZero(self): if not tf2.enabled(): self.skipTest("only fails in TF2") @def_function.function def f(): y = gen_array_ops.parallel_concat(values=[["tf"]], shape=0) return y with self.assertRaisesRegex(errors.InvalidArgumentError, r"0th dimension of value .* is less than"): f()
1
Python
CWE-369
Divide By Zero
The product divides a value by zero.
https://cwe.mitre.org/data/definitions/369.html
safe
def starts_with(field: Term, value: str) -> Criterion: return field.like(f"{value}%")
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 update(self, **kwargs): consumer_id = load_consumer_id(self.context) if not consumer_id: self.prompt.render_failure_message("This consumer is not registered to the Pulp server.") return delta = dict([(k, v) for k, v in kwargs.items() if v is not None]) if 'note' in delta.keys(): if delta['note']: delta['notes'] = args_to_notes_dict(kwargs['note'], include_none=False) delta.pop('note') # convert display-name to display_name key = 'display-name' if key in delta: v = delta.pop(key) key = key.replace('-', '_') delta[key] = v if kwargs.get(OPTION_EXCHANGE_KEYS.keyword): path = self.context.config['authentication']['rsa_pub'] fp = open(path) try: delta['rsa_pub'] = fp.read() finally: fp.close() try: self.context.server.consumer.update(consumer_id, delta) self.prompt.render_success_message('Consumer [%s] successfully updated' % consumer_id) if not kwargs.get(OPTION_EXCHANGE_KEYS.keyword): return update_server_key(self) except NotFoundException: self.prompt.write('Consumer [%s] does not exist on the server' % consumer_id, tag='not-found')
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 fetch_file(self, in_path, out_path): ''' fetch a file from zone to local ''' vvv("FETCH %s TO %s" % (in_path, out_path), host=self.zone) p = self._buffered_exec_command('dd if=%s bs=%s' % (in_path, BUFSIZE), None) with open(out_path, 'wb+') as out_file: try: for chunk in p.stdout.read(BUFSIZE): out_file.write(chunk) except: traceback.print_exc() raise errors.AnsibleError("failed to transfer file to %s" % out_path) stdout, stderr = p.communicate() if p.returncode != 0: raise errors.AnsibleError("failed to transfer file to %s:\n%s\n%s" % (out_path, stdout, stderr))
1
Python
CWE-59
Improper Link Resolution Before File Access ('Link Following')
The software attempts to access a file based on the filename, but it does not properly prevent that filename from identifying a link or shortcut that resolves to an unintended resource.
https://cwe.mitre.org/data/definitions/59.html
safe
def test_bad_integer(self): # issue13436: Bad error message with invalid numeric values body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=None, col_offset=None)] mod = ast.Module(body, []) with self.assertRaises(ValueError) as cm: compile(mod, 'test', 'exec') self.assertIn("invalid integer value: None", str(cm.exception))
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 receivePing(): vrequest = request.form['id'] db.sentences_victim('report_online', [vrequest]) return json.dumps({'status' : 'OK', 'vId' : vrequest});
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 testPathTraverse(self): # need to perform this test with a "real" folder from OFS.Folder import Folder f = self.folder self.folder = Folder() self.folder.t, self.folder.laf = f.t, f.laf self.folder.laf.write('ok') self.assert_expected(self.folder.t, 'CheckPathTraverse.html')
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 del_project(request, client_id, project): if request.method == 'GET': client = Client.objects.get(id=client_id) try: scrapyd = get_scrapyd(client) result = scrapyd.delete_project(project=project) return JsonResponse(result) except ConnectionError: return JsonResponse({'message': 'Connect Error'})
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 getaddrspec(self): """Parse an RFC 2822 addr-spec.""" aslist = [] self.gotonext() while self.pos < len(self.field): preserve_ws = True if self.field[self.pos] == '.': if aslist and not aslist[-1].strip(): aslist.pop() aslist.append('.') self.pos += 1 preserve_ws = False elif self.field[self.pos] == '"': aslist.append('"%s"' % quote(self.getquote())) elif self.field[self.pos] in self.atomends: if aslist and not aslist[-1].strip(): aslist.pop() break else: aslist.append(self.getatom()) ws = self.gotonext() if preserve_ws and ws: aslist.append(ws) if self.pos >= len(self.field) or self.field[self.pos] != '@': return EMPTYSTRING.join(aslist) aslist.append('@') self.pos += 1 self.gotonext() return EMPTYSTRING.join(aslist) + self.getdomain()
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def install_agent(agent_key): ''' Function downloads Server Density installation agent, and installs sd-agent with agent_key. CLI Example: .. code-block:: bash salt '*' serverdensity_device.install_agent c2bbdd6689ff46282bdaa07555641498 ''' work_dir = '/tmp/' account_url = get_sd_auth('account_url') __salt__['cmd.run']( cmd='curl https://www.serverdensity.com/downloads/agent-install.sh -o install.sh', cwd=work_dir ) __salt__['cmd.run'](cmd='chmod +x install.sh', cwd=work_dir) return __salt__['cmd.run']( cmd='./install.sh -a {account_url} -k {agent_key}'.format( account_url=account_url, agent_key=agent_key), cwd=work_dir )
0
Python
CWE-19
Data Processing Errors
Weaknesses in this category are typically found in functionality that processes data. Data processing is the manipulation of input to retrieve or save information.
https://cwe.mitre.org/data/definitions/19.html
vulnerable
def server_socket_thread(srv): try: while gcounter[0] < request_count: try: client, _ = srv.accept() except ssl.SSLError as e: if e.reason in tls_skip_errors: return raise try: client.settimeout(timeout) fun(client, tick) finally: try: client.shutdown(socket.SHUT_RDWR) except (IOError, socket.error): pass # FIXME: client.close() introduces connection reset by peer # at least in other/connection_close test # should not be a problem since socket would close upon garbage collection if gcounter[0] > request_count: gresult[0] = Exception( "Request count expected={0} actual={1}".format( request_count, gcounter[0] ) ) except Exception as e: # traceback.print_exc caused IOError: concurrent operation on sys.stderr.close() under setup.py test print(traceback.format_exc(), file=sys.stderr) gresult[0] = e
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 reinit(self): """Initialize the random number generator and seed it with entropy from the operating system. """ # Save the pid (helps ensure that Crypto.Random.atfork() gets called) self._pid = os.getpid() # Collect entropy from the operating system and feed it to # FortunaAccumulator self._ec.reinit() # Override FortunaAccumulator's 100ms minimum re-seed interval. This # is necessary to avoid a race condition between this function and # self.read(), which that can otherwise cause forked child processes to # produce identical output. (e.g. CVE-2013-1445) # # Note that if this function can be called frequently by an attacker, # (and if the bits from OSRNG are insufficiently random) it will weaken # Fortuna's ability to resist a state compromise extension attack. self._fa._forget_last_reseed()
1
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
safe
def handleContentChunk(self, data): if self.content.tell() + len(data) > MAX_REQUEST_SIZE: logger.info( "Aborting connection from %s because the request exceeds maximum size", self.client.host) self.transport.abortConnection() return return super().handleContentChunk(data)
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_get_conditions(self, freeze): conditions = ClearableFileInput().get_conditions(None) assert all( condition in conditions for condition in [ {"bucket": "test-bucket"}, {"success_action_status": "201"}, ["starts-with", "$key", "custom/location/tmp"], ["starts-with", "$Content-Type", ""], ] ), conditions
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_login_get(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') response = self.client.get('/accounts/login/code/', { 'code': login_code.code, }) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].cleaned_data['code'], login_code) self.assertTrue(response.wsgi_request.user.is_anonymous) self.assertTrue(LoginCode.objects.filter(pk=login_code.pk).exists())
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 make_homeserver(self, reactor, clock): self.fetches = [] async def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return await make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, federation_http_client=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 render_edit_book(book_id): cc = calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.datatype.notin_(db.cc_exceptions)).all() book = calibre_db.get_filtered_book(book_id, allow_show_archived=True) if not book: flash(_(u"Oops! Selected book title is unavailable. File does not exist or is not accessible"), category="error") return redirect(url_for("web.index")) for lang in book.languages: lang.language_name = isoLanguages.get_language_name(get_locale(), lang.lang_code) book.authors = calibre_db.order_authors([book]) author_names = [] for authr in book.authors: author_names.append(authr.name.replace('|', ',')) # Option for showing convertbook button valid_source_formats=list() allowed_conversion_formats = list() kepub_possible=None if config.config_converterpath: for file in book.data: if file.format.lower() in constants.EXTENSIONS_CONVERT_FROM: valid_source_formats.append(file.format.lower()) if config.config_kepubifypath and 'epub' in [file.format.lower() for file in book.data]: kepub_possible = True if not config.config_converterpath: valid_source_formats.append('epub') # Determine what formats don't already exist if config.config_converterpath: allowed_conversion_formats = constants.EXTENSIONS_CONVERT_TO[:] for file in book.data: if file.format.lower() in allowed_conversion_formats: allowed_conversion_formats.remove(file.format.lower()) if kepub_possible: allowed_conversion_formats.append('kepub') return render_title_template('book_edit.html', book=book, authors=author_names, cc=cc, title=_(u"edit metadata"), page="editbook", conversion_formats=allowed_conversion_formats, config=config, source_formats=valid_source_formats)
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_login_unknown_code(self): response = self.client.post('/accounts/login/code/', { 'code': 'unknown', }) self.assertEqual(response.status_code, 200) self.assertEqual(response.context['form'].errors, { 'code': ['Login code is invalid. It might have expired.'], })
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 env() -> Environment: from openapi_python_client import utils TEMPLATE_FILTERS = {"snakecase": utils.snake_case, "spinalcase": utils.spinal_case} env = Environment(loader=PackageLoader("openapi_python_client"), trim_blocks=True, lstrip_blocks=True) env.filters.update(TEMPLATE_FILTERS) return env
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 _should_decode(typ): # either a basetype which needs to be clamped # or a complex type which contains something that # needs to be clamped. if isinstance(typ, BaseType): return typ.typ not in ("int256", "uint256", "bytes32") if isinstance(typ, (ByteArrayLike, DArrayType)): return True if isinstance(typ, SArrayType): return _should_decode(typ.subtype) if isinstance(typ, TupleLike): return any(_should_decode(t) for t in typ.tuple_members()) raise CompilerPanic(f"_should_decode({typ})") # pragma: notest
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 is_secure(self): return False
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 default_dir_win(tmp_dir=None): """ Create or find default catalog store for Windows systems purpose of 'tmp_dir' is to enable way how to test this function easily """ def create_win_temp_dir(prefix, inner_dir=None, tmp_dir=None): """ create temp dir starting with 'prefix' in 'tmp_dir' or 'tempfile.gettempdir'; if 'inner_dir' is specified, it should be created inside """ tmp_dir_path = find_valid_temp_dir(prefix, tmp_dir) if tmp_dir_path: if inner_dir: tmp_dir_path = os.path.join(tmp_dir_path, inner_dir) if not os.path.isdir(tmp_dir_path): os.mkdir(tmp_dir_path, 0o700) else: tmp_dir_path = create_temp_dir(prefix, inner_dir, tmp_dir) return tmp_dir_path python_name = "python%d%d_compiled" % tuple(sys.version_info[:2]) tmp_dir = tmp_dir or tempfile.gettempdir() temp_dir_name = "%s" % whoami() temp_root_dir = os.path.join(tmp_dir, temp_dir_name) temp_dir_path = os.path.join(temp_root_dir, python_name) _create_dirs(temp_dir_path) if check_dir(temp_dir_path) and check_dir(temp_root_dir): return temp_dir_path else: if check_dir(temp_root_dir): return create_win_temp_dir(python_name, tmp_dir=temp_root_dir) else: return create_win_temp_dir(temp_dir_name, python_name, tmp_dir)
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def test_list_instructor_tasks_problem_student(self, act): """ Test list task history for problem AND student. """ act.return_value = self.tasks url = reverse('list_instructor_tasks', kwargs={'course_id': self.course.id.to_deprecated_string()}) mock_factory = MockCompletionInfo() with patch('instructor.views.instructor_task_helpers.get_task_completion_info') as mock_completion_info: mock_completion_info.side_effect = mock_factory.mock_get_task_completion_info response = self.client.get(url, { 'problem_location_str': self.problem_urlname, 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 200) # check response self.assertTrue(act.called) expected_tasks = [ftask.to_dict() for ftask in self.tasks] actual_tasks = json.loads(response.content)['tasks'] for exp_task, act_task in zip(expected_tasks, actual_tasks): self.assertDictEqual(exp_task, act_task) self.assertEqual(actual_tasks, expected_tasks)
0
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
def get_email_content_response(self, num_emails, task_history_request, with_failures=False): """ Calls the list_email_content endpoint and returns the repsonse """ self.setup_fake_email_info(num_emails, with_failures) task_history_request.return_value = self.tasks.values() url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) with patch('instructor.views.api.CourseEmail.objects.get') as mock_email_info: mock_email_info.side_effect = self.get_matching_mock_email response = self.client.post(url, {}) self.assertEqual(response.status_code, 200) return response
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 process_request(self, req): auth_tok = req.headers.get('X-Auth-Token') user = None tenant = None roles = [] if auth_tok: user, tenant, role = auth_tok.split(':') if tenant.lower() == 'none': tenant = None roles = [role] req.headers['X-User-Id'] = user req.headers['X-Tenant-Id'] = tenant req.headers['X-Roles'] = role req.headers['X-Identity-Status'] = 'Confirmed' kwargs = { 'user': user, 'tenant': tenant, 'roles': roles, 'is_admin': self.is_admin, 'auth_tok': auth_tok, } req.context = context.RequestContext(**kwargs)
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_received_bad_host_header(self): from waitress.utilities import BadRequest data = b"HTTP/1.0 GET /foobar\r\n Host: foo\r\n\r\n" result = self.parser.received(data) self.assertEqual(result, 36) self.assertTrue(self.parser.completed) self.assertEqual(self.parser.error.__class__, BadRequest)
1
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def main(req: func.HttpRequest) -> func.HttpResponse: response = ok( Info( resource_group=get_base_resource_group(), region=get_base_region(), subscription=get_subscription(), versions=versions(), instance_id=get_instance_id(), insights_appid=get_insights_appid(), insights_instrumentation_key=get_insights_instrumentation_key(), ) ) return response
0
Python
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
vulnerable
def render_archived_books(page, sort_param): order = sort_param[0] or [] archived_books = ( ub.session.query(ub.ArchivedBook) .filter(ub.ArchivedBook.user_id == int(current_user.id)) .filter(ub.ArchivedBook.is_archived == True) .all() ) archived_book_ids = [archived_book.book_id for archived_book in archived_books] archived_filter = db.Books.id.in_(archived_book_ids) entries, random, pagination = calibre_db.fill_indexpage_with_archived_books(page, db.Books, 0, archived_filter, order, True, False, 0) name = _(u'Archived Books') + ' (' + str(len(archived_book_ids)) + ')' pagename = "archived" return render_title_template('index.html', random=random, entries=entries, pagination=pagination, title=name, page=pagename, order=sort_param[1])
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 mysql_ends_with(field: Field, value: str) -> Criterion: return functions.Cast(field, SqlTypes.CHAR).like(f"%{value}")
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 test_expect_continue(self): # specifying Connection: close explicitly data = "I have expectations" to_send = tobytes( "GET / HTTP/1.1\r\n" "Connection: close\r\n" "Content-Length: %d\r\n" "Expect: 100-continue\r\n" "\r\n" "%s" % (len(data), data) ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line = fp.readline() # continue status line version, status, reason = (x.strip() for x in line.split(None, 2)) self.assertEqual(int(status), 100) self.assertEqual(reason, b"Continue") self.assertEqual(version, b"HTTP/1.1") fp.readline() # blank line line = fp.readline() # next status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) length = int(headers.get("content-length")) or None response_body = fp.read(length) self.assertEqual(int(status), 200) self.assertEqual(length, len(response_body)) self.assertEqual(response_body, tobytes(data))
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_win_inaccessible_root(self): """ there should be a new root dir created if existing one is not accessible """ tmpdir = tempfile.mkdtemp() try: d_dir = catalog.default_dir_win(tmpdir) root_ddir = os.path.dirname(d_dir) try: os.chmod(root_ddir, stat.S_IREAD | stat.S_IEXEC) except OSError: raise KnownFailureTest("Can't change permissions of root default_dir.") new_ddir = catalog.default_dir_win(tmpdir) assert_(not os.path.samefile(new_ddir, d_dir)) new_ddir2 = catalog.default_dir_win(tmpdir) assert_(os.path.samefile(new_ddir, new_ddir2)) finally: os.chmod(root_ddir, 0o700) remove_tree(tmpdir)
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def test_dmcrypt_with_custom_size(self, conf_ceph_stub): conf_ceph_stub(''' [global] fsid=asdf [osd] osd_dmcrypt_size=8 ''') result = encryption.create_dmcrypt_key() assert len(result) == 172
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_patch_bot_role(self) -> None: self.login("desdemona") email = "[email protected]" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_success(result) user_profile = self.get_bot_user(email) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) # Test for not allowing a non-owner user to make assign a bot an owner role desdemona = self.example_user("desdemona") do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_OWNER) result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization owner") result = self.client_patch(f"/json/bots/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization owner") # Test for not allowing a non-administrator user to assign a bot an administrator role shiva = self.example_user("shiva") self.assertEqual(shiva.role, UserProfile.ROLE_MODERATOR) self.login_user(shiva) do_change_bot_owner(user_profile, shiva, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_ADMINISTRATOR) result = self.client_patch(f"/json/users/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization administrator") result = self.client_patch(f"/json/bots/{user_profile.id}", req) self.assert_json_error(result, "Must be an organization administrator")
1
Python
CWE-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
safe
def object_to_relations(o, e): # process forward and reverse references, so just loop over all the objects of the event if 'Object' in e['Event']: for eo in e['Event']['Object']: if 'ObjectReference' in eo: for ref in eo['ObjectReference']: # we have found original object. Expand to the related object and attributes if eo['uuid'] == o['uuid']: # the reference is an Object if ref.get('Object'): # get the full object in the event, as our objectReference included does not contain everything we need sub_object = get_object_in_event(ref['Object']['uuid'], e) yield object_to_entity(sub_object, link_label=ref['relationship_type']) # the reference is an Attribute if ref.get('Attribute'): ref['Attribute']['event_id'] = ref['event_id'] # LATER remove this ugly workaround - object can't be requested directly from MISP using the uuid, and to find a full object we need the event_id for item in attribute_to_entity(ref['Attribute'], link_label=ref['relationship_type']): yield item # reverse-lookup - this is another objects relating the original object if ref['referenced_uuid'] == o['uuid']: yield object_to_entity(eo, link_label=ref['relationship_type'], link_direction=LinkDirection.OutputToInput)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def test_parse_header_no_cr_in_headerplus(self): data = b"GET /foobar HTTP/8.4" self.parser.parse_header(data) self.assertEqual(self.parser.first_line, data)
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_file(request): path = tempfile.mkdtemp() file_name = os.path.join(path, "%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 emit(self, s, depth, reflow=True): # XXX reflow long lines? if reflow: lines = reflow_lines(s, depth) else: lines = [s] for line in lines: line = (" " * TABSIZE * depth) + line + "\n" self.file.write(line)
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_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, 'security_groups': 10, 'security_group_rules': 20, }} req = fakes.HTTPRequest.blank( '/v2/fake4/os-quota-class-sets/test_class') self.assertRaises(webob.exc.HTTPForbidden, self.controller.update, req, 'test_class', body)
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_parse_header_bad_content_length(self): data = b"GET /foobar HTTP/8.4\r\ncontent-length: abc\r\n" self.parser.parse_header(data) self.assertEqual(self.parser.body_rcv, None)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def list_instructor_tasks(request, course_id): """ List instructor tasks. Takes optional query paremeters. - With no arguments, lists running tasks. - `problem_location_str` lists task history for problem - `problem_location_str` and `unique_student_identifier` lists task history for problem AND student (intersection) """ course_id = SlashSeparatedCourseKey.from_deprecated_string(course_id) problem_location_str = strip_if_string(request.GET.get('problem_location_str', False)) student = request.GET.get('unique_student_identifier', None) if student is not None: student = get_student_from_identifier(student) if student and not problem_location_str: return HttpResponseBadRequest( "unique_student_identifier must accompany problem_location_str" ) if problem_location_str: try: module_state_key = course_id.make_usage_key_from_deprecated_string(problem_location_str) except InvalidKeyError: return HttpResponseBadRequest() if student: # Specifying for a single student's history on this problem tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key, student) else: # Specifying for single problem's history tasks = instructor_task.api.get_instructor_task_history(course_id, module_state_key) else: # If no problem or student, just get currently running tasks tasks = instructor_task.api.get_running_instructor_tasks(course_id) response_payload = { 'tasks': map(extract_task_features, tasks), } return JsonResponse(response_payload)
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 extra_view_dispatch(request, view): """ Dispatch to an Xtheme extra view. :param request: A request. :type request: django.http.HttpRequest :param view: View name. :type view: str :return: A response of some kind. :rtype: django.http.HttpResponse """ theme = getattr(request, "theme", None) or get_current_theme(request.shop) view_func = get_view_by_name(theme, view) if not view_func: msg = "Error! %s/%s: Not found." % (getattr(theme, "identifier", None), view) return HttpResponseNotFound(msg) return view_func(request)
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 is_private_address(url): hostname = urlparse(url).hostname ip_address = socket.gethostbyname(hostname) return ipaddress.ip_address(text_type(ip_address)).is_private
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_serializer(self): exemplar = dict(quota_class_set=dict( id='test_class', metadata_items=10, injected_file_content_bytes=20, volumes=30, gigabytes=40, ram=50, floating_ips=60, instances=70, injected_files=80, security_groups=10, security_group_rules=20, cores=90)) text = self.serializer.serialize(exemplar) print text tree = etree.fromstring(text) self.assertEqual('quota_class_set', tree.tag) self.assertEqual('test_class', tree.get('id')) self.assertEqual(len(exemplar['quota_class_set']) - 1, len(tree)) for child in tree: self.assertTrue(child.tag in exemplar['quota_class_set']) self.assertEqual(int(child.text), exemplar['quota_class_set'][child.tag])
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