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 get_search_results(self, term, offset=None, order=None, limit=None, allow_show_archived=False,
config_read_column=False, *join):
| 0 |
Python
|
CWE-918
|
Server-Side Request Forgery (SSRF)
|
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
|
https://cwe.mitre.org/data/definitions/918.html
|
vulnerable
|
def testInputParserBoth(self):
x0 = np.array([[1], [2]])
input_path = os.path.join(test.get_temp_dir(), 'input.npz')
np.savez(input_path, a=x0)
x1 = np.ones([2, 10])
input_str = 'x0=' + input_path + '[a]'
input_expr_str = 'x1=np.ones([2,10])'
feed_dict = saved_model_cli.load_inputs_from_input_arg_string(
input_str, input_expr_str, '')
self.assertTrue(np.all(feed_dict['x0'] == x0))
self.assertTrue(np.all(feed_dict['x1'] == x1))
| 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_credits_view_html(self):
response = self.get_credits("html")
self.assertEqual(response.status_code, 200)
self.assertHTMLEqual(
response.content.decode(),
"<table>\n"
"<tr>\n<th>Czech</th>\n"
'<td><ul><li><a href="mailto:weblate@example.org">'
"Weblate Test</a> (1)</li></ul></td>\n</tr>\n"
"</table>",
)
| 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 Ghostscript(tile, size, fp, scale=1):
"""Render an image using Ghostscript"""
# Unpack decoder tile
decoder, tile, offset, data = tile[0]
length, bbox = data
#Hack to support hi-res rendering
scale = int(scale) or 1
orig_size = size
orig_bbox = bbox
size = (size[0] * scale, size[1] * scale)
bbox = [bbox[0], bbox[1], bbox[2] * scale, bbox[3] * scale]
#print("Ghostscript", scale, size, orig_size, bbox, orig_bbox)
import tempfile, os, subprocess
file = tempfile.mktemp()
# Build ghostscript command
command = ["gs",
"-q", # quite mode
"-g%dx%d" % size, # set output geometry (pixels)
"-r%d" % (72*scale), # set input DPI (dots per inch)
"-dNOPAUSE -dSAFER", # don't pause between pages, safe mode
"-sDEVICE=ppmraw", # ppm driver
"-sOutputFile=%s" % file,# output file
]
if gs_windows_binary is not None:
if gs_windows_binary is False:
raise WindowsError('Unable to locate Ghostscript on paths')
command[0] = gs_windows_binary
# push data through ghostscript
try:
gs = subprocess.Popen(command, stdin=subprocess.PIPE, stdout=subprocess.PIPE)
# adjust for image origin
if bbox[0] != 0 or bbox[1] != 0:
gs.stdin.write(("%d %d translate\n" % (-bbox[0], -bbox[1])).encode('ascii'))
fp.seek(offset)
while length > 0:
s = fp.read(8192)
if not s:
break
length = length - len(s)
gs.stdin.write(s)
gs.stdin.close()
status = gs.wait()
if status:
raise IOError("gs failed (status %d)" % status)
im = Image.core.open_ppm(file)
finally:
try: os.unlink(file)
except: pass
return im
| 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 CreateAuthenticator():
"""Create a packet autenticator. All RADIUS packets contain a sixteen
byte authenticator which is used to authenticate replies from the
RADIUS server and in the password hiding algorithm. This function
returns a suitable random string that can be used as an authenticator.
:return: valid packet authenticator
:rtype: binary string
"""
data = []
for i in range(16):
data.append(random_generator.randrange(0, 256))
if six.PY3:
return bytes(data)
else:
return ''.join(chr(b) for b in data)
| 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 task_remove(request, task_id):
"""
remove task by task_id
:param request:
:return:
"""
if request.method == 'POST':
# delete job from DjangoJob
task = Task.objects.get(id=task_id)
clients = clients_of_task(task)
for client in clients:
job_id = get_job_id(client, task)
DjangoJob.objects.filter(name=job_id).delete()
# delete task
Task.objects.filter(id=task_id).delete()
return JsonResponse({'result': '1'})
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def test_is_valid_matrix_server_name(self):
"""Tests that the is_valid_matrix_server_name function accepts only
valid hostnames (or domain names), with optional port number.
"""
self.assertTrue(is_valid_matrix_server_name("9.9.9.9"))
self.assertTrue(is_valid_matrix_server_name("9.9.9.9:4242"))
self.assertTrue(is_valid_matrix_server_name("[::]"))
self.assertTrue(is_valid_matrix_server_name("[::]:4242"))
self.assertTrue(is_valid_matrix_server_name("[a:b:c::]:4242"))
self.assertTrue(is_valid_matrix_server_name("example.com"))
self.assertTrue(is_valid_matrix_server_name("EXAMPLE.COM"))
self.assertTrue(is_valid_matrix_server_name("ExAmPlE.CoM"))
self.assertTrue(is_valid_matrix_server_name("example.com:4242"))
self.assertTrue(is_valid_matrix_server_name("localhost"))
self.assertTrue(is_valid_matrix_server_name("localhost:9000"))
self.assertTrue(is_valid_matrix_server_name("a.b.c.d:1234"))
self.assertFalse(is_valid_matrix_server_name("[:::]"))
self.assertFalse(is_valid_matrix_server_name("a:b:c::"))
self.assertFalse(is_valid_matrix_server_name("example.com:65536"))
self.assertFalse(is_valid_matrix_server_name("example.com:0"))
self.assertFalse(is_valid_matrix_server_name("example.com:-1"))
self.assertFalse(is_valid_matrix_server_name("example.com:a"))
self.assertFalse(is_valid_matrix_server_name("example.com: "))
self.assertFalse(is_valid_matrix_server_name("example.com:04242"))
self.assertFalse(is_valid_matrix_server_name("example.com: 4242"))
self.assertFalse(is_valid_matrix_server_name("example.com/example.com"))
self.assertFalse(is_valid_matrix_server_name("example.com#example.com"))
| 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 __init__(self, expire_on_commit=True):
""" Initialize a new CalibreDB session
"""
self.session = None
if self._init:
self.initSession(expire_on_commit)
self.instances.add(self)
| 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 sql_one_row(self, sentence, column):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
return self.cursor.fetchone()[column]
| 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 build_request(self, key_filename, req_config, entry):
"""
creates the certificate request
"""
req = tempfile.mkstemp()[1]
days = self.cert_specs[entry.get('name')]['days']
key = self.data + key_filename
cmd = "openssl req -new -config %s -days %s -key %s -text -out %s" % (req_config,
days,
key,
req)
res = Popen(cmd, shell=True, stdout=PIPE).stdout.read()
return req
| 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 testRaggedCountSparseOutputBadSplitsStart(self):
splits = [1, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Splits must start with 0"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False))
| 1 |
Python
|
CWE-119
|
Improper Restriction of Operations within the Bounds of a Memory Buffer
|
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
|
https://cwe.mitre.org/data/definitions/119.html
|
safe
|
def read_config(self, config, **kwargs):
consent_config = config.get("user_consent")
self.terms_template = self.read_template("terms.html")
if consent_config is None:
return
self.user_consent_version = str(consent_config["version"])
self.user_consent_template_dir = self.abspath(consent_config["template_dir"])
if not path.isdir(self.user_consent_template_dir):
raise ConfigError(
"Could not find template directory '%s'"
% (self.user_consent_template_dir,)
)
self.user_consent_server_notice_content = consent_config.get(
"server_notice_content"
)
self.block_events_without_consent_error = consent_config.get(
"block_events_error"
)
self.user_consent_server_notice_to_guests = bool(
consent_config.get("send_server_notice_to_guests", False)
)
self.user_consent_at_registration = bool(
consent_config.get("require_at_registration", False)
)
self.user_consent_policy_name = consent_config.get(
"policy_name", "Privacy Policy"
)
| 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 filter(self, names):
for name in (_hkey(n) for n in names):
if name in self.dict:
del self.dict[name]
| 1 |
Python
|
CWE-93
|
Improper Neutralization of CRLF Sequences ('CRLF Injection')
|
The software uses CRLF (carriage return line feeds) as a special element, e.g. to separate lines or records, but it does not neutralize or incorrectly neutralizes CRLF sequences from inputs.
|
https://cwe.mitre.org/data/definitions/93.html
|
safe
|
def __init__(self, **kwargs):
self.basic_auth = get_anymail_setting('webhook_authorization', default=[],
kwargs=kwargs) # no esp_name -- auth is shared between ESPs
# Allow a single string:
if isinstance(self.basic_auth, six.string_types):
self.basic_auth = [self.basic_auth]
if self.warn_if_no_basic_auth and len(self.basic_auth) < 1:
warnings.warn(
"Your Anymail webhooks are insecure and open to anyone on the web. "
"You should set WEBHOOK_AUTHORIZATION in your ANYMAIL settings. "
"See 'Securing webhooks' in the Anymail docs.",
AnymailInsecureWebhookWarning)
# noinspection PyArgumentList
super(AnymailBasicAuthMixin, self).__init__(**kwargs)
| 0 |
Python
|
CWE-532
|
Insertion of Sensitive Information into Log File
|
Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.
|
https://cwe.mitre.org/data/definitions/532.html
|
vulnerable
|
def substitute_array(self, args):
return [self.substitute(txt) for txt in args]
| 1 |
Python
|
CWE-77
|
Improper Neutralization of Special Elements used in a Command ('Command Injection')
|
The software constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
|
https://cwe.mitre.org/data/definitions/77.html
|
safe
|
def update_headers(self, request_headers: HTTPHeadersDict):
"""
Update the session headers with the request ones while ignoring
certain name prefixes.
"""
headers = self.headers
for name, value in request_headers.copy().items():
if value is None:
continue # Ignore explicitly unset headers
if type(value) is not str:
value = value.decode()
if name.lower() == 'user-agent' and value.startswith('HTTPie/'):
continue
if name.lower() == 'cookie':
for cookie_name, morsel in SimpleCookie(value).items():
self['cookies'][cookie_name] = {'value': morsel.value}
del request_headers[name]
continue
for prefix in SESSION_IGNORED_HEADER_PREFIXES:
if name.lower().startswith(prefix.lower()):
break
else:
headers[name] = value
self['headers'] = dict(headers)
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
async def on_PUT(self, origin, content, query, room_id):
content = await self.handler.on_exchange_third_party_invite_request(content)
return 200, content
| 1 |
Python
|
CWE-400
|
Uncontrolled Resource Consumption
|
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
|
https://cwe.mitre.org/data/definitions/400.html
|
safe
|
def recursive_py_fn(n, x):
if n > 0:
return n * recursive_py_fn(n - 1, x)
return x
| 1 |
Python
|
CWE-667
|
Improper Locking
|
The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.
|
https://cwe.mitre.org/data/definitions/667.html
|
safe
|
def get_file(path):
try:
data_file, metadata = get_info(
path,
pathlib.Path(app.config["DATA_ROOT"])
)
except (OSError, ValueError):
return flask.Response(
"Not Found",
404,
mimetype="text/plain",
)
response = flask.make_response(flask.send_file(
str(data_file),
))
generate_headers(
response.headers,
metadata["headers"],
)
return response
| 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_request_body_too_large_with_wrong_cl_http10(self):
body = "a" * self.toobig
to_send = "GET / HTTP/1.0\n" "Content-Length: 5\n\n"
to_send += body
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb")
# first request succeeds (content-length 5)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
# server trusts the content-length header; no pipelining,
# so request fulfilled, extra bytes are thrown away
# 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 check_unrar(unrarLocation):
if not unrarLocation:
return
if not os.path.exists(unrarLocation):
return _('Unrar binary file not found')
try:
unrarLocation = [unrarLocation]
value = process_wait(unrarLocation, pattern='UNRAR (.*) freeware')
if value:
version = value.group(1)
log.debug("unrar version %s", version)
except (OSError, UnicodeDecodeError) as err:
log.error_or_exception(err)
return _('Error excecuting UnRar')
| 0 |
Python
|
CWE-918
|
Server-Side Request Forgery (SSRF)
|
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
|
https://cwe.mitre.org/data/definitions/918.html
|
vulnerable
|
def test_after_start_response_http11(self):
to_send = "GET /after_start_response HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "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)
| 0 |
Python
|
CWE-444
|
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
|
The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination.
|
https://cwe.mitre.org/data/definitions/444.html
|
vulnerable
|
def test_received_preq_completed_connection_close(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.completed = True
preq.empty = True
preq.connection_close = True
inst.received(b"GET / HTTP/1.1\r\n\r\n" + b"a" * 50000)
self.assertEqual(inst.request, None)
self.assertEqual(inst.server.tasks, [])
| 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_check_safe_path(self):
ret = disk_api._join_and_check_path_within_fs('/foo', 'etc',
'something.conf')
self.assertEquals(ret, '/foo/etc/something.conf')
| 1 |
Python
|
CWE-264
|
Permissions, Privileges, and Access Controls
|
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
|
https://cwe.mitre.org/data/definitions/264.html
|
safe
|
def 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).
Always returns ``False`` on an empty url.
"""
if not url:
return False
netloc = urllib_parse.urlparse(url)[1]
return not netloc or netloc == host
| 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 _check_group_whitelist(self, username, user_id, is_admin, access_token):
http_client = AsyncHTTPClient()
headers = _api_headers(access_token)
if is_admin:
# For admins, /groups returns *all* groups. As a workaround
# we check if we are a member of each group in the whitelist
for group in map(url_escape, self.gitlab_group_whitelist):
url = "%s/groups/%s/members/%d" % (GITLAB_API, group, user_id)
req = HTTPRequest(url, method="GET", headers=headers)
resp = yield http_client.fetch(req, raise_error=False)
if resp.code == 200:
return True # user _is_ in group
else:
# For regular users we get all the groups to which they have access
# and check if any of these are in the whitelisted groups
next_page = url_concat("%s/groups" % GITLAB_API,
dict(all_available=True))
while next_page:
req = HTTPRequest(next_page, method="GET", headers=headers)
resp = yield http_client.fetch(req)
resp_json = json.loads(resp.body.decode('utf8', 'replace'))
next_page = next_page_from_links(resp)
user_groups = set(entry["path"] for entry in resp_json)
# check if any of the organizations seen thus far are in whitelist
if len(self.gitlab_group_whitelist & user_groups) > 0:
return True
return False
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def CreateID(self):
"""Create a packet ID. All RADIUS requests have a ID which is used to
identify a request. This is used to detect retries and replay attacks.
This function returns a suitable random number that can be used as ID.
:return: ID number
:rtype: integer
"""
return random.randrange(0, 256)
| 0 |
Python
|
CWE-330
|
Use of Insufficiently Random Values
|
The software uses insufficiently random numbers or values in a security context that depends on unpredictable numbers.
|
https://cwe.mitre.org/data/definitions/330.html
|
vulnerable
|
def _testErrorWithShapesEager(self, exception_regex, superdiag_shape,
maindiag_shape, subdiag_shape, rhs_shape):
| 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
|
def download_check_files(self, filelist):
# only admins and allowed users may download
if not cherrypy.session['admin']:
uo = self.useroptions.forUser(self.getUserId())
if not uo.getOptionValue('media.may_download'):
return 'not_permitted'
# make sure nobody tries to escape from basedir
for f in filelist:
# don't allow to traverse up in the file system
if '/../' in f or f.startswith('../'):
return 'invalid_file'
# CVE-2015-8309: do not allow absolute file paths
if os.path.isabs(f):
return 'invalid_file'
# make sure all files are smaller than maximum download size
size_limit = cherry.config['media.maximum_download_size']
try:
if self.model.file_size_within_limit(filelist, size_limit):
return 'ok'
else:
return 'too_big'
except OSError as e: # use OSError for python2 compatibility
return str(e)
| 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_request_login_code(self):
response = self.client.post('/accounts-rest/login/', {
'username': self.user.username,
'next': '/private/',
})
self.assertEqual(response.status_code, 200)
login_code = LoginCode.objects.filter(user=self.user).first()
self.assertIsNotNone(login_code)
self.assertEqual(login_code.next, '/private/')
self.assertEqual(len(mail.outbox), 1)
self.assertIn(
'http://testserver/accounts/login/code/?user={}&code={}'.format(
login_code.user.pk,
login_code.code
),
mail.outbox[0].body,
)
| 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 ready(self):
checks.register(check_deprecated_settings)
| 1 |
Python
|
CWE-532
|
Insertion of Sensitive Information into Log File
|
Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.
|
https://cwe.mitre.org/data/definitions/532.html
|
safe
|
def safe_text(raw_text: str) -> jinja2.Markup:
"""
Process text: treat it as HTML but escape any tags (ie. just escape the
HTML) then linkify it.
"""
return jinja2.Markup(
bleach.linkify(bleach.clean(raw_text, tags=[], attributes={}, strip=False))
)
| 0 |
Python
|
CWE-74
|
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
|
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
|
https://cwe.mitre.org/data/definitions/74.html
|
vulnerable
|
def cookies(self) -> RequestsCookieJar:
jar = RequestsCookieJar()
for name, cookie_dict in self['cookies'].items():
jar.set_cookie(create_cookie(
name, cookie_dict.pop('value'), **cookie_dict))
jar.clear_expired_cookies()
return jar
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def start_requests(self):
yield SplashRequest(self.url, endpoint='execute',
args={'lua_source': DEFAULT_SCRIPT})
| 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_list_entrance_exam_instructor_tasks_student(self):
""" Test list task history for entrance exam AND student. """
# create a re-score entrance exam task
url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
# check response
tasks = json.loads(response.content)['tasks']
self.assertEqual(len(tasks), 1)
self.assertEqual(tasks[0]['status'], _('Complete'))
| 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_list_background_email_tasks(self, act):
"""Test list of background email tasks."""
act.return_value = self.tasks
url = reverse('list_background_email_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, {})
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 test_serialization(self):
memcache_client = memcached.MemcacheRing(['1.2.3.4:11211'],
allow_pickle=True)
mock = MockMemcached()
memcache_client._client_cache['1.2.3.4:11211'] = [(mock, mock)] * 2
memcache_client.set('some_key', [1, 2, 3])
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
memcache_client._allow_pickle = False
memcache_client._allow_unpickle = True
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
memcache_client._allow_unpickle = False
self.assertEquals(memcache_client.get('some_key'), None)
memcache_client.set('some_key', [1, 2, 3])
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
memcache_client._allow_unpickle = True
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
memcache_client._allow_pickle = True
self.assertEquals(memcache_client.get('some_key'), [1, 2, 3])
| 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 _redirect_safe(self, url, default=None):
"""Redirect if url is on our PATH
Full-domain redirects are allowed if they pass our CORS origin checks.
Otherwise use default (self.base_url if unspecified).
"""
if default is None:
default = self.base_url
# protect chrome users from mishandling unescaped backslashes.
# \ is not valid in urls, but some browsers treat it as /
# instead of %5C, causing `\\` to behave as `//`
url = url.replace("\\", "%5C")
parsed = urlparse(url)
if parsed.netloc or not (parsed.path + '/').startswith(self.base_url):
# require that next_url be absolute path within our path
allow = False
# OR pass our cross-origin check
if parsed.netloc:
# if full URL, run our cross-origin check:
origin = '%s://%s' % (parsed.scheme, parsed.netloc)
origin = origin.lower()
if self.allow_origin:
allow = self.allow_origin == origin
elif self.allow_origin_pat:
allow = bool(self.allow_origin_pat.match(origin))
if not allow:
# not allowed, use default
self.log.warning("Not allowing login redirect to %r" % url)
url = default
self.redirect(url)
| 1 |
Python
|
CWE-601
|
URL Redirection to Untrusted Site ('Open Redirect')
|
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
|
https://cwe.mitre.org/data/definitions/601.html
|
safe
|
def update_dir_structure_gdrive(book_id, first_author, renamed_author):
book = calibre_db.get_book(book_id)
authordir = book.path.split('/')[0]
titledir = book.path.split('/')[1]
new_authordir = rename_all_authors(first_author, renamed_author, gdrive=True)
new_titledir = get_valid_filename(book.title, chars=96) + u" (" + str(book_id) + u")"
if titledir != new_titledir:
gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), titledir)
if gFile:
gd.moveGdriveFileRemote(gFile, new_titledir)
book.path = book.path.split('/')[0] + u'/' + new_titledir
gd.updateDatabaseOnEdit(gFile['id'], book.path) # only child folder affected
else:
return _(u'File %(file)s not found on Google Drive', file=book.path) # file not found
if authordir != new_authordir and authordir not in renamed_author:
gFile = gd.getFileFromEbooksFolder(os.path.dirname(book.path), new_titledir)
if gFile:
gd.moveGdriveFolderRemote(gFile, new_authordir)
book.path = new_authordir + u'/' + book.path.split('/')[1]
gd.updateDatabaseOnEdit(gFile['id'], book.path)
else:
return _(u'File %(file)s not found on Google Drive', file=authordir) # file not found
# change location in database to new author/title path
book.path = os.path.join(new_authordir, new_titledir).replace('\\', '/')
return rename_files_on_change(first_author, renamed_author, 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 response(self, response, content):
if "authentication-info" not in response:
challenge = _parse_www_authenticate(response, "www-authenticate").get(
"digest", {}
)
if "true" == challenge.get("stale"):
self.challenge["nonce"] = challenge["nonce"]
self.challenge["nc"] = 1
return True
else:
updated_challenge = _parse_www_authenticate(
response, "authentication-info"
).get("digest", {})
if "nextnonce" in updated_challenge:
self.challenge["nonce"] = updated_challenge["nextnonce"]
self.challenge["nc"] = 1
return False
| 0 |
Python
|
CWE-400
|
Uncontrolled Resource Consumption
|
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
|
https://cwe.mitre.org/data/definitions/400.html
|
vulnerable
|
def _path(self):
"""Absolute path of the file at local ``path``."""
return os.path.join(FOLDER, self.path.replace("/", os.sep))
| 0 |
Python
|
CWE-21
|
DEPRECATED: Pathname Traversal and Equivalence Errors
|
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
|
https://cwe.mitre.org/data/definitions/21.html
|
vulnerable
|
def stmt(self, stmt, msg=None):
mod = ast.Module([stmt])
self.mod(mod, msg)
| 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 testPeekBadIndex(self):
stager = data_flow_ops.StagingArea([
dtypes.int32,
], shapes=[[10]])
stager.put([array_ops.zeros([10], dtype=dtypes.int32)])
with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError),
'must be scalar'):
self.evaluate(stager.peek([]))
| 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-327
|
Use of a Broken or Risky Cryptographic Algorithm
|
The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.
|
https://cwe.mitre.org/data/definitions/327.html
|
vulnerable
|
def test_basic_format_all_okay(self):
env = SandboxedEnvironment()
t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')
assert t.render() == 'a42b'
| 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 _expand_user_properties(self, template):
# Make sure username and servername match the restrictions for DNS labels
# Note: '-' is not in safe_chars, as it is being used as escape character
safe_chars = set(string.ascii_lowercase + string.digits)
# Set servername based on whether named-server initialised
if self.name:
# use two -- to ensure no collision possibilities
# are created by an ambiguous boundary between username and
# servername.
# -- cannot occur in a string where - is the escape char.
servername = '--{}'.format(self.name)
safe_servername = '--{}'.format(escapism.escape(self.name, safe=safe_chars, escape_char='-').lower())
else:
servername = ''
safe_servername = ''
legacy_escaped_username = ''.join([s if s in safe_chars else '-' for s in self.user.name.lower()])
safe_username = escapism.escape(self.user.name, safe=safe_chars, escape_char='-').lower()
return template.format(
userid=self.user.id,
username=safe_username,
unescaped_username=self.user.name,
legacy_escape_username=legacy_escaped_username,
servername=safe_servername,
unescaped_servername=servername,
)
| 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 _unpack_returndata(buf, contract_sig, skip_contract_check, context):
return_t = contract_sig.return_type
if return_t is None:
return ["pass"], 0, 0
return_t = calculate_type_for_external_return(return_t)
# if the abi signature has a different type than
# the vyper type, we need to wrap and unwrap the type
# so that the ABI decoding works correctly
should_unwrap_abi_tuple = return_t != contract_sig.return_type
abi_return_t = return_t.abi_type
min_return_size = abi_return_t.min_size()
max_return_size = abi_return_t.size_bound()
assert 0 < min_return_size <= max_return_size
ret_ofst = buf
ret_len = max_return_size
# revert when returndatasize is not in bounds
ret = []
# runtime: min_return_size <= returndatasize
# TODO move the -1 optimization to IR optimizer
if not skip_contract_check:
ret += [["assert", ["gt", "returndatasize", min_return_size - 1]]]
# add as the last IRnode a pointer to the return data structure
# the return type has been wrapped by the calling contract;
# unwrap it so downstream code isn't confused.
# basically this expands to buf+32 if the return type has been wrapped
# in a tuple AND its ABI type is dynamic.
# in most cases, this simply will evaluate to ret.
# in the special case where the return type has been wrapped
# in a tuple AND its ABI type is dynamic, it expands to buf+32.
buf = IRnode(buf, typ=return_t, encoding=_returndata_encoding(contract_sig), location=MEMORY)
if should_unwrap_abi_tuple:
buf = get_element_ptr(buf, 0, array_bounds_check=False)
ret += [buf]
return ret, ret_ofst, ret_len
| 0 |
Python
|
CWE-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 basic_parser(xml):
return parse(BytesIO(xml))
| 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 children(cls, path):
abs_path = os.path.join(FOLDER, path.replace("/", os.sep))
_, directories, files = next(os.walk(abs_path))
for filename in directories + files:
rel_filename = posixpath.join(path, filename)
if cls.is_node(rel_filename) or cls.is_leaf(rel_filename):
yield cls(rel_filename)
| 0 |
Python
|
CWE-21
|
DEPRECATED: Pathname Traversal and Equivalence Errors
|
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
|
https://cwe.mitre.org/data/definitions/21.html
|
vulnerable
|
def test_parse_header_gardenpath(self):
data = b"GET /foobar HTTP/8.4\r\nfoo: bar\r\n"
self.parser.parse_header(data)
self.assertEqual(self.parser.first_line, b"GET /foobar HTTP/8.4")
self.assertEqual(self.parser.headers["FOO"], "bar")
| 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_double_linefeed(self):
self.assertEqual(self._callFUT(b"\n\n"), -1)
| 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 auth_user_registration_role(self):
return self.appbuilder.get_app.config["AUTH_USER_REGISTRATION_ROLE"]
| 0 |
Python
|
CWE-287
|
Improper Authentication
|
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
|
https://cwe.mitre.org/data/definitions/287.html
|
vulnerable
|
def allowed_security_group_rules(context, security_group_id,
requested_rules):
| 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_credits_view_rst(self):
response = self.get_credits("rst")
self.assertEqual(response.status_code, 200)
self.assertEqual(
response.content.decode(),
"""
* Czech
* Weblate <b>Test</b> <weblate@example.org> (1)
""",
)
| 1 |
Python
|
CWE-79
|
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
|
https://cwe.mitre.org/data/definitions/79.html
|
safe
|
def test_list_report_downloads(self):
url = reverse('list_report_downloads', kwargs={'course_id': self.course.id.to_deprecated_string()})
with patch('instructor_task.models.LocalFSReportStore.links_for') as mock_links_for:
mock_links_for.return_value = [
('mock_file_name_1', 'https://1.mock.url'),
('mock_file_name_2', 'https://2.mock.url'),
]
response = self.client.post(url, {})
expected_response = {
"downloads": [
{
"url": "https://1.mock.url",
"link": "<a href=\"https://1.mock.url\">mock_file_name_1</a>",
"name": "mock_file_name_1"
},
{
"url": "https://2.mock.url",
"link": "<a href=\"https://2.mock.url\">mock_file_name_2</a>",
"name": "mock_file_name_2"
}
]
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected_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 testSwitchEagerMode(self):
if not context.executing_eagerly():
return
input_data = [1, 2, 3, 4]
vf, vt = control_flow_ops.switch(input_data, False)
self.assertAllEqual(vf, input_data)
self.assertAllEqual(vt, [])
| 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_parse_soap_enveloped_saml_xxe():
xml = """<?xml version="1.0"?>
<!DOCTYPE lolz [
<!ENTITY lol "lol">
<!ELEMENT lolz (#PCDATA)>
<!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;">
]>
<lolz>&lol1;</lolz>
"""
with raises(EntitiesForbidden):
parse_soap_enveloped_saml(xml, None)
| 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 index():
""" Index handler """
send = prevent_open_redirect(request.vars.send)
if DEMO_MODE:
session.authorized = True
session.last_time = t0
if not send:
send = URL('site')
if session.authorized:
redirect(send)
elif failed_login_count() >= allowed_number_of_attempts:
time.sleep(2 ** allowed_number_of_attempts)
raise HTTP(403)
elif request.vars.password:
if verify_password(request.vars.password[:1024]):
session.authorized = True
login_record(True)
if CHECK_VERSION:
session.check_version = True
else:
session.check_version = False
session.last_time = t0
if isinstance(send, list): # ## why does this happen?
send = str(send[0])
redirect(send)
else:
times_denied = login_record(False)
if times_denied >= allowed_number_of_attempts:
response.flash = \
T('admin disabled because too many invalid login attempts')
elif times_denied == allowed_number_of_attempts - 1:
response.flash = \
T('You have one more login attempt before you are locked out')
else:
response.flash = T('invalid password.')
return dict(send=send)
| 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 make_homeserver(self, reactor, clock):
hs = self.setup_test_homeserver(
"server", federation_http_client=None, federation_sender=Mock()
)
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 test_rescore_entrance_exam_single_student(self, act):
""" Test re-scoring of entrance exam for single student. """
url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {
'unique_student_identifier': self.student.email,
})
self.assertEqual(response.status_code, 200)
self.assertTrue(act.called)
| 0 |
Python
|
CWE-352
|
Cross-Site Request Forgery (CSRF)
|
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
|
https://cwe.mitre.org/data/definitions/352.html
|
vulnerable
|
def require_query_params(*args, **kwargs):
"""
Checks for required paremters or renders a 400 error.
(decorator with arguments)
`args` is a *list of required GET parameter names.
`kwargs` is a **dict of required GET parameter names
to string explanations of the parameter
"""
required_params = []
required_params += [(arg, None) for arg in args]
required_params += [(key, kwargs[key]) for key in kwargs]
# required_params = e.g. [('action', 'enroll or unenroll'), ['emails', None]]
def decorator(func): # pylint: disable=missing-docstring
def wrapped(*args, **kwargs): # pylint: disable=missing-docstring
request = args[0]
error_response_data = {
'error': 'Missing required query parameter(s)',
'parameters': [],
'info': {},
}
for (param, extra) in required_params:
default = object()
if request.GET.get(param, default) == default:
error_response_data['parameters'].append(param)
error_response_data['info'][param] = extra
if len(error_response_data['parameters']) > 0:
return JsonResponse(error_response_data, status=400)
else:
return func(*args, **kwargs)
return wrapped
return decorator
| 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 is_authenticated(self, user, password):
# The content of the file is not cached because reading is generally a
# very cheap operation, and it's useful to get live updates of the
# htpasswd file.
with open(self.filename) as fd:
for line in fd:
line = line.strip()
if line:
login, hash_value = line.split(":")
if login == user and self.verify(hash_value, password):
return True
# Random timer to avoid timing oracles and simple bruteforce attacks
time.sleep(1 + random.random())
return False
| 1 |
Python
|
CWE-362
|
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
|
The program contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
|
https://cwe.mitre.org/data/definitions/362.html
|
safe
|
async def on_PUT(self, origin, content, query, room_id, event_id):
content = await self.handler.on_send_leave_request(origin, content, room_id)
return 200, (200, content)
| 0 |
Python
|
CWE-400
|
Uncontrolled Resource Consumption
|
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
|
https://cwe.mitre.org/data/definitions/400.html
|
vulnerable
|
def _handle_carbon_received(self, msg):
if msg['from'].bare == self.xmpp.boundjid.bare:
self.xmpp.event('carbon_received', msg)
| 1 |
Python
|
CWE-20
|
Improper Input Validation
|
The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly.
|
https://cwe.mitre.org/data/definitions/20.html
|
safe
|
def _default_logfile(exe_name):
'''
Retrieve the logfile name
'''
if salt.utils.is_windows():
logfile_tmp = tempfile.NamedTemporaryFile(dir=os.environ['TMP'],
prefix=exe_name,
suffix='.log',
delete=False)
logfile = logfile_tmp.name
logfile_tmp.close()
else:
logfile = salt.utils.path_join(
'/var/log',
'{0}.log'.format(exe_name)
)
return logfile
| 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 test_credits_view_html(self):
response = self.get_credits("html")
self.assertEqual(response.status_code, 200)
self.assertHTMLEqual(
response.content.decode(),
"<table>\n"
"<tr>\n<th>Czech</th>\n"
'<td><ul><li><a href="mailto:weblate@example.org">'
"Weblate <b>Test</b></a> (1)</li></ul></td>\n</tr>\n"
"</table>",
)
| 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 sentences_stats(self, type, vId = None):
return self.sql_execute(self.prop_sentences_stats(type, vId))
| 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 testRaggedCountSparseOutputEmptySplits(self):
splits = []
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
with self.assertRaisesRegex(
errors.InvalidArgumentError,
"Must provide at least 2 elements for the splits argument"):
self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits,
values=values,
weights=weights,
binary_output=False))
| 1 |
Python
|
CWE-787
|
Out-of-bounds Write
|
The software writes data past the end, or before the beginning, of the intended buffer.
|
https://cwe.mitre.org/data/definitions/787.html
|
safe
|
def _factorial(x):
if x<=10000:
return float(math.factorial(x))
else:
raise Exception('factorial argument too large')
| 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_get_student_progress_url_from_uname(self):
""" Test that progress_url is in the successful response. """
url = reverse('get_student_progress_url', kwargs={'course_id': self.course.id.to_deprecated_string()})
data = {'unique_student_identifier': self.students[0].username.encode("utf-8")}
response = self.client.post(url, data)
self.assertEqual(response.status_code, 200)
res_json = json.loads(response.content)
self.assertIn('progress_url', res_json)
| 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 load_module(name):
if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
sys.path.insert(0, os.path.dirname(os.path.abspath(name)))
try:
m = os.path.splitext(os.path.basename(name))[0]
module = importlib.import_module(m)
finally:
sys.path.pop(0)
return module
return importlib.import_module('dbusmock.templates.' + name)
| 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 assertNeverEmailedWrongUser(self):
self.assertNotIn(self.never_emailed_user.email, [to for email in mail.outbox for to in email.to])
| 1 |
Python
|
CWE-200
|
Exposure of Sensitive Information to an Unauthorized Actor
|
The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.
|
https://cwe.mitre.org/data/definitions/200.html
|
safe
|
def __init__(
self, cache, safe=safename
| 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 check_username(username):
username = username.strip()
if ub.session.query(ub.User).filter(func.lower(ub.User.name) == username.lower()).scalar():
log.error(u"This username is already taken")
raise Exception (_(u"This username is already taken"))
return username
| 0 |
Python
|
CWE-918
|
Server-Side Request Forgery (SSRF)
|
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
|
https://cwe.mitre.org/data/definitions/918.html
|
vulnerable
|
def help_page(page_slug: str) -> str:
"""Fava's included documentation."""
if page_slug not in HELP_PAGES:
abort(404)
html = markdown2.markdown_path(
(resource_path("help") / (page_slug + ".md")),
extras=["fenced-code-blocks", "tables", "header-ids"],
)
return render_template(
"_layout.html",
active_page="help",
page_slug=page_slug,
help_html=render_template_string(
html,
beancount_version=beancount_version,
fava_version=fava_version,
),
HELP_PAGES=HELP_PAGES,
)
| 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 parse_soap_enveloped_saml_thingy(text, expected_tags):
"""Parses a SOAP enveloped SAML thing and returns the thing as
a string.
:param text: The SOAP object as XML string
:param expected_tags: What the tag of the SAML thingy is expected to be.
:return: SAML thingy as a string
"""
envelope = ElementTree.fromstring(text)
# Make sure it's a SOAP message
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
body = None
for part in envelope:
if part.tag == '{%s}Body' % soapenv.NAMESPACE:
assert len(part) == 1
body = part
break
if body is None:
return ""
saml_part = body[0]
if saml_part.tag in expected_tags:
return ElementTree.tostring(saml_part, encoding="UTF-8")
else:
raise WrongMessageType("Was '%s' expected one of %s" % (saml_part.tag,
expected_tags))
| 0 |
Python
|
CWE-611
|
Improper Restriction of XML External Entity Reference
|
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
|
https://cwe.mitre.org/data/definitions/611.html
|
vulnerable
|
def __init__(self, path: Union[str, Path]):
super().__init__(path=Path(path))
self['headers'] = {}
self['cookies'] = {}
self['auth'] = {
'type': None,
'username': None,
'password': None
}
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def dataReceived(self, data: bytes) -> None:
self.stream.write(data)
self.length += len(data)
if self.max_size is not None and self.length >= self.max_size:
self.deferred.errback(
SynapseError(
502,
"Requested file is too large > %r bytes" % (self.max_size,),
Codes.TOO_LARGE,
)
)
self.deferred = defer.Deferred()
self.transport.loseConnection()
| 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 convert_bookformat(book_id):
# check to see if we have form fields to work with - if not send user back
book_format_from = request.form.get('book_format_from', None)
book_format_to = request.form.get('book_format_to', None)
if (book_format_from is None) or (book_format_to is None):
flash(_(u"Source or destination format for conversion missing"), category="error")
return redirect(url_for('editbook.edit_book', book_id=book_id))
log.info('converting: book id: %s from: %s to: %s', book_id, book_format_from, book_format_to)
rtn = helper.convert_book_format(book_id, config.config_calibre_dir, book_format_from.upper(),
book_format_to.upper(), current_user.name)
if rtn is None:
flash(_(u"Book successfully queued for converting to %(book_format)s",
book_format=book_format_to),
category="success")
else:
flash(_(u"There was an error converting this book: %(res)s", res=rtn), category="error")
return redirect(url_for('editbook.edit_book', book_id=book_id))
| 0 |
Python
|
CWE-918
|
Server-Side Request Forgery (SSRF)
|
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
|
https://cwe.mitre.org/data/definitions/918.html
|
vulnerable
|
def read_config(self, config, **kwargs):
consent_config = config.get("user_consent")
self.terms_template = self.read_template("terms.html")
if consent_config is None:
return
self.user_consent_version = str(consent_config["version"])
self.user_consent_template_dir = self.abspath(consent_config["template_dir"])
if not path.isdir(self.user_consent_template_dir):
raise ConfigError(
"Could not find template directory '%s'"
% (self.user_consent_template_dir,)
)
self.user_consent_server_notice_content = consent_config.get(
"server_notice_content"
)
self.block_events_without_consent_error = consent_config.get(
"block_events_error"
)
self.user_consent_server_notice_to_guests = bool(
consent_config.get("send_server_notice_to_guests", False)
)
self.user_consent_at_registration = bool(
consent_config.get("require_at_registration", False)
)
self.user_consent_policy_name = consent_config.get(
"policy_name", "Privacy Policy"
)
| 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 __init__(self, *args, **kwargs):
super(BasketShareForm, self).__init__(*args, **kwargs)
try:
self.fields["image"] = GroupModelMultipleChoiceField(
queryset=kwargs["initial"]["images"],
initial=kwargs["initial"]["selected"],
widget=forms.SelectMultiple(attrs={"size": 10}),
)
except Exception:
self.fields["image"] = GroupModelMultipleChoiceField(
queryset=kwargs["initial"]["images"],
widget=forms.SelectMultiple(attrs={"size": 10}),
)
| 0 |
Python
|
CWE-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 _create_database(self, last_upgrade_to_run):
"""
Make sure that the database is created and sets the file permissions.
This should be done before storing any sensitive data in it.
"""
# Create the tables in the database
conn = self._connect()
try:
with conn:
self._create_tables(conn, last_upgrade_to_run)
finally:
conn.close()
# Set the file permissions
os.chmod(self.filename, stat.S_IRUSR | stat.S_IWUSR)
| 0 |
Python
|
CWE-367
|
Time-of-check Time-of-use (TOCTOU) Race Condition
|
The software checks the state of a resource before using that resource, but the resource's state can change between the check and the use in a way that invalidates the results of the check. This can cause the software to perform invalid actions when the resource is in an unexpected state.
|
https://cwe.mitre.org/data/definitions/367.html
|
vulnerable
|
def sql_insert(self, sentence):
if type(sentence) is str:
self.cursor.execute(sentence)
else:
self.cursor.execute(sentence[0], sentence[1])
self.conn.commit()
return True
| 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_parse_header_11_te_chunked(self):
# NB: test that capitalization of header value is unimportant
data = b"GET /foobar HTTP/1.1\r\ntransfer-encoding: ChUnKed\r\n"
self.parser.parse_header(data)
self.assertEqual(self.parser.body_rcv.__class__.__name__, "ChunkedReceiver")
| 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 _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
if request.path in self._allowed_paths:
return False
# For all other cases require that the user is verfied via otp
return True
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
bool AveragePool(const float* input_data, const Dims<4>& input_dims, int stride,
int pad_width, int pad_height, int filter_width,
int filter_height, float* output_data,
const Dims<4>& output_dims) {
return AveragePool<Ac>(input_data, input_dims, stride, stride, pad_width,
pad_height, filter_width, filter_height, output_data,
output_dims);
}
| 1 |
Python
|
CWE-835
|
Loop with Unreachable Exit Condition ('Infinite Loop')
|
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
|
https://cwe.mitre.org/data/definitions/835.html
|
safe
|
def log_request(handler):
"""log a bit more information about each request than tornado's default
- move static file get success to debug-level (reduces noise)
- get proxied IP instead of proxy IP
- log referer for redirect and failed requests
- log user-agent for failed requests
"""
status = handler.get_status()
request = handler.request
try:
logger = handler.log
except AttributeError:
logger = access_log
if status < 300 or status == 304:
# Successes (or 304 FOUND) are debug-level
log_method = logger.debug
elif status < 400:
log_method = logger.info
elif status < 500:
log_method = logger.warning
else:
log_method = logger.error
request_time = 1000.0 * handler.request.request_time()
ns = dict(
status=status,
method=request.method,
ip=request.remote_ip,
uri=request.uri,
request_time=request_time,
)
msg = "{status} {method} {uri} ({ip}) {request_time:.2f}ms"
if status >= 400:
# log bad referers
ns["referer"] = request.headers.get("Referer", "None")
msg = msg + " referer={referer}"
if status >= 500 and status != 502:
# log all headers if it caused an error
log_method(json.dumps(dict(request.headers), indent=2))
log_method(msg.format(**ns))
prometheus_log_method(handler)
| 0 |
Python
|
CWE-532
|
Insertion of Sensitive Information into Log File
|
Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.
|
https://cwe.mitre.org/data/definitions/532.html
|
vulnerable
|
def fake_quota_get_all_by_project(context, project_id):
result = dict(project_id=project_id)
if override:
result.update(
instances=2,
cores=5,
ram=12 * 1024,
volumes=2,
gigabytes=250,
floating_ips=2,
security_groups=5,
security_group_rules=10,
metadata_items=32,
injected_files=1,
injected_file_content_bytes=2 * 1024,
invalid_quota=50,
)
return result
| 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 text(self):
try:
with open(self._path) as fd:
return fd.read()
except IOError:
return ""
| 0 |
Python
|
CWE-21
|
DEPRECATED: Pathname Traversal and Equivalence Errors
|
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
|
https://cwe.mitre.org/data/definitions/21.html
|
vulnerable
|
def jstree_data(node, selected_node):
result = []
result.append('{')
result.append(format_html('"text": "{}",', node.label))
result.append(
'"state": {{ "opened": true, "selected": {} }},'.format(
'true' if node == selected_node else 'false'
)
)
result.append(
'"data": {{ "href": "{}" }},'.format(node.get_absolute_url())
)
children = node.get_children().order_by('label',)
if children:
result.append('"children" : [')
for child in children:
result.extend(jstree_data(node=child, selected_node=selected_node))
result.append(']')
result.append('},')
return result
| 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 get(self):
if not current_user.is_authenticated:
return "Must be logged in to log out", 200
logout_user()
return "Logged Out", 200
| 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 format_date(self, data):
"""
A hook to control how dates are formatted.
Can be overridden at the ``Serializer`` level (``datetime_formatting``)
or globally (via ``settings.TASTYPIE_DATETIME_FORMATTING``).
Default is ``iso-8601``, which looks like "2010-12-16".
"""
if self.datetime_formatting == 'rfc-2822':
return format_date(data)
return data.isoformat()
| 0 |
Python
|
CWE-20
|
Improper Input Validation
|
The product receives input or data, but it does
not validate or incorrectly validates that the input has the
properties that are required to process the data safely and
correctly.
|
https://cwe.mitre.org/data/definitions/20.html
|
vulnerable
|
def test_fli_overflow(self):
# this should not crash with a malloc error or access violation
im = Image.open(TEST_FILE)
im.load()
| 1 |
Python
|
CWE-119
|
Improper Restriction of Operations within the Bounds of a Memory Buffer
|
The software performs operations on a memory buffer, but it can read from or write to a memory location that is outside of the intended boundary of the buffer.
|
https://cwe.mitre.org/data/definitions/119.html
|
safe
|
def login():
from flask_login import current_user
redirect_url = request.args.get("redirect", request.script_root + url_for("index"))
permissions = sorted(
filter(
lambda x: x is not None and isinstance(x, OctoPrintPermission),
map(
lambda x: getattr(Permissions, x.strip()),
request.args.get("permissions", "").split(","),
),
),
key=lambda x: x.get_name(),
)
if not permissions:
permissions = [Permissions.STATUS, Permissions.SETTINGS_READ]
user_id = request.args.get("user_id", "")
if (not user_id or current_user.get_id() == user_id) and has_permissions(
*permissions
):
return redirect(redirect_url)
render_kwargs = {
"theming": [],
"redirect_url": redirect_url,
"permission_names": map(lambda x: x.get_name(), permissions),
"user_id": user_id,
"logged_in": not current_user.is_anonymous,
}
try:
additional_assets = _add_additional_assets("octoprint.theming.login")
# backwards compatibility to forcelogin & loginui plugins which were replaced by this built-in dialog
additional_assets += _add_additional_assets("octoprint.plugin.forcelogin.theming")
additional_assets += _add_additional_assets("octoprint.plugin.loginui.theming")
render_kwargs.update({"theming": additional_assets})
except Exception:
_logger.exception("Error processing theming CSS, ignoring")
return render_template("login.jinja2", **render_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 __str__(self):
return self.xml().encode('utf8')
| 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_host(self):
"""Returns the HTTP host using the environment or request headers."""
# We try three options, in order of decreasing preference.
if settings.USE_X_FORWARDED_HOST and (
'HTTP_X_FORWARDED_HOST' in self.META):
host = self.META['HTTP_X_FORWARDED_HOST']
elif 'HTTP_HOST' in self.META:
host = self.META['HTTP_HOST']
else:
# Reconstruct the host using the algorithm from PEP 333.
host = self.META['SERVER_NAME']
server_port = str(self.META['SERVER_PORT'])
if server_port != ('443' if self.is_secure() else '80'):
host = '%s:%s' % (host, server_port)
# Disallow potentially poisoned hostnames.
if set(';/?@&=+$,').intersection(host):
raise SuspiciousOperation('Invalid HTTP_HOST header: %s' % host)
return host
| 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_magic_response2():
# check 'body' handling and another 'headers' format
mw = _get_mw()
req = SplashRequest('http://example.com/', magic_response=True,
headers={'foo': 'bar'}, dont_send_headers=True)
req = mw.process_request(req, None)
assert 'headers' not in req.meta['splash']['args']
resp_data = {
'body': base64.b64encode(b"binary data").decode('ascii'),
'headers': {'Content-Type': 'text/plain'},
}
resp = TextResponse("http://mysplash.example.com/execute",
headers={b'Content-Type': b'application/json'},
body=json.dumps(resp_data).encode('utf8'))
resp2 = mw.process_response(req, resp, None)
assert resp2.data == resp_data
assert resp2.body == b'binary data'
assert resp2.headers == {b'Content-Type': [b'text/plain']}
assert resp2.splash_response_headers == {b'Content-Type': [b'application/json']}
assert resp2.status == resp2.splash_response_status == 200
assert resp2.url == "http://example.com/"
| 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 testRaggedCountSparseOutput(self):
splits = [0, 4, 7]
values = [1, 1, 2, 1, 2, 10, 5]
weights = [1, 2, 3, 4, 5, 6, 7]
output_indices, output_values, output_shape = self.evaluate(
gen_count_ops.RaggedCountSparseOutput(
splits=splits, values=values, weights=weights, binary_output=False))
self.assertAllEqual([[0, 1], [0, 2], [1, 2], [1, 5], [1, 10]],
output_indices)
self.assertAllEqual([7, 3, 5, 7, 6], output_values)
self.assertAllEqual([2, 11], output_shape)
| 1 |
Python
|
CWE-787
|
Out-of-bounds Write
|
The software writes data past the end, or before the beginning, of the intended buffer.
|
https://cwe.mitre.org/data/definitions/787.html
|
safe
|
def clean(self):
user_id = self.cleaned_data.get('user', None)
if user_id is None:
raise forms.ValidationError(
self.error_messages['invalid_code'],
code='invalid_code',
)
user = get_user_model().objects.get(pk=user_id)
code = self.cleaned_data['code']
user = authenticate(self.request, **{
get_user_model().USERNAME_FIELD: user.username,
'code': code,
})
if not user:
raise forms.ValidationError(
self.error_messages['invalid_code'],
code='invalid_code',
)
self.cleaned_data['user'] = user
return self.cleaned_data
| 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 test_http11_list(self):
body = string.ascii_letters
to_send = "GET /list HTTP/1.1\r\nContent-Length: %d\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", 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")
| 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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.