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_basic_functionality(self):
self.create_test_files()
self.attic('init', self.repository_location)
self.attic('create', self.repository_location + '::test', 'input')
self.attic('create', self.repository_location + '::test.2', 'input')
with changedir('output'):
self.attic('extract', self.repository_location + '::test')
self.assert_equal(len(self.attic('list', self.repository_location).splitlines()), 2)
self.assert_equal(len(self.attic('list', self.repository_location + '::test').splitlines()), 11)
self.assert_dirs_equal('input', 'output/input')
info_output = self.attic('info', self.repository_location + '::test')
self.assert_in('Number of files: 4', info_output)
shutil.rmtree(self.cache_path)
info_output2 = self.attic('info', self.repository_location + '::test')
# info_output2 starts with some "initializing cache" text but should
# end the same way as info_output
assert info_output2.endswith(info_output)
| 0 |
Python
|
CWE-264
|
Permissions, Privileges, and Access Controls
|
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
|
https://cwe.mitre.org/data/definitions/264.html
|
vulnerable
|
def _create(self):
url = recurly.base_uri() + self.collection_path
return self.post(url)
| 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 get_misp_connection(config=None, parameters=None):
global misp_connection
if misp_connection:
return misp_connection
if not config:
raise MaltegoException("ERROR: MISP connection not yet established, and config not provided as parameter.")
misp_verify = True
misp_debug = False
misp_url = None
misp_key = None
try:
if is_local_exec_mode():
misp_url = config['MISP_maltego.local.misp_url']
misp_key = config['MISP_maltego.local.misp_key']
if config['MISP_maltego.local.misp_verify'] in ['False', 'false', 0, 'no', 'No']:
misp_verify = False
if config['MISP_maltego.local.misp_debug'] in ['True', 'true', 1, 'yes', 'Yes']:
misp_debug = True
if is_remote_exec_mode():
try:
misp_url = parameters['mispurl'].value
misp_key = parameters['mispkey'].value
except AttributeError:
raise MaltegoException("ERROR: mispurl and mispkey need to be set to something valid")
misp_connection = PyMISP(misp_url, misp_key, misp_verify, 'json', misp_debug, tool='misp_maltego')
except Exception:
if is_local_exec_mode():
raise MaltegoException("ERROR: Cannot connect to MISP server. Please verify your MISP_Maltego.conf settings.")
if is_remote_exec_mode():
raise MaltegoException("ERROR: Cannot connect to MISP server. Please verify your settings (MISP URL and API key), and ensure the MISP server is reachable from the internet.")
return misp_connection
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def _auth_from_challenge(self, host, request_uri, headers, response, content):
"""A generator that creates Authorization objects
that can be applied to requests.
"""
challenges = _parse_www_authenticate(response, "www-authenticate")
for cred in self.credentials.iter(host):
for scheme in AUTH_SCHEME_ORDER:
if scheme in challenges:
yield AUTH_SCHEME_CLASSES[scheme](
cred, host, request_uri, headers, response, content, self
)
| 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_dmcrypt_with_default_size(self, conf_ceph_stub):
conf_ceph_stub('[global]\nfsid=asdf-lkjh')
result = encryption.create_dmcrypt_key()
assert len(result) == 172
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def receivePing():
vrequest = request.form['id']
db.sentences_victim('report_online', [vrequest], 2)
return json.dumps({'status' : 'OK', 'vId' : vrequest});
| 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_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'
| 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_http10_list(self):
body = string.ascii_letters
to_send = (
"GET /list HTTP/1.0\n"
"Connection: Keep-Alive\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.0")
self.assertEqual(headers["content-length"], str(len(body)))
self.assertEqual(headers.get("connection"), "Keep-Alive")
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.0")
| 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_send_empty_body(self):
to_send = "GET / HTTP/1.0\n" "Content-Length: 0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(echo.content_length, "0")
self.assertEqual(echo.body, b"")
| 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
|
async def message(self, ctx, *, message: str):
"""Set the message that is shown at the start of each ticket channel.\n\nUse ``{user.mention}`` to mention the person who created the ticket."""
try:
message.format(user=ctx.author)
await self.config.guild(ctx.guild).message.set(message)
await ctx.send(f"The message has been set to `{message}`.")
except KeyError:
await ctx.send(
"Setting the message failed. Please make sure to only use supported variables in `\{\}`"
)
| 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 test_redundantdef(self):
with self.assertRaisesRegex(SyntaxError, "^Cannot have two type comments on def"):
tree = self.parse(redundantdef)
| 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 _testSparseDenseInvalidInputs(self,
a_indices,
a_values,
a_shape,
b,
expected_error=""):
| 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 __new__(cls, sourceName: str):
"""Dispatches to the right subclass."""
if cls != InputSource:
# Only take control of calls to InputSource(...) itself.
return super().__new__(cls)
if sourceName == "-":
return StdinInputSource(sourceName)
if sourceName.startswith("https:"):
return UrlInputSource(sourceName)
return FileInputSource(sourceName)
| 0 |
Python
|
CWE-78
|
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
|
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
|
https://cwe.mitre.org/data/definitions/78.html
|
vulnerable
|
def test_modify_access_allow(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_user.email,
'rolename': 'staff',
'action': 'allow',
})
self.assertEqual(response.status_code, 200)
| 0 |
Python
|
CWE-352
|
Cross-Site Request Forgery (CSRF)
|
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
|
https://cwe.mitre.org/data/definitions/352.html
|
vulnerable
|
def fetch_file(self, in_path, out_path):
''' fetch a file from jail to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.jail)
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_uses_existing_file_and_ignores_xdg(self):
with WindowsSafeTempDir() as d:
default_db_file_location = os.path.join(self.home, '.b2_account_info')
open(default_db_file_location, 'a').close()
account_info = self._make_sqlite_account_info(
env={
'HOME': self.home,
'USERPROFILE': self.home,
XDG_CONFIG_HOME_ENV_VAR: d,
}
)
actual_path = os.path.abspath(account_info.filename)
assert default_db_file_location == actual_path
assert not os.path.exists(os.path.join(d, 'b2'))
| 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 test_list_entrance_exam_instructor_tasks_all_student(self):
""" Test list task history for entrance exam AND all student. """
url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course.id)})
response = self.client.get(url, {})
self.assertEqual(response.status_code, 200)
# check response
tasks = json.loads(response.content)['tasks']
self.assertEqual(len(tasks), 0)
| 0 |
Python
|
CWE-352
|
Cross-Site Request Forgery (CSRF)
|
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
|
https://cwe.mitre.org/data/definitions/352.html
|
vulnerable
|
def parse_configuration_file(config_path):
"""
Read the config file for an experiment to get ParlAI settings.
:param config_path:
path to config
:return:
parsed configuration dictionary
"""
result = {}
result["configs"] = {}
with open(config_path) as f:
cfg = yaml.load(f.read(), Loader=yaml.FullLoader)
# get world path
result["world_path"] = cfg.get("world_module")
if not result["world_path"]:
raise ValueError("Did not specify world module")
result["overworld"] = cfg.get("overworld")
if not result["overworld"]:
raise ValueError("Did not specify overworld")
result["max_workers"] = cfg.get("max_workers")
if not result["max_workers"]:
raise ValueError("Did not specify max_workers")
result["task_name"] = cfg.get("task_name")
if not result["task_name"]:
raise ValueError("Did not specify task name")
task_world = cfg.get("tasks")
if task_world is None or len(task_world) == 0:
raise ValueError("task not in config file")
# get task file
for task_name, configuration in task_world.items():
if "task_world" not in configuration:
raise ValueError("{} does not specify a task".format(task_name))
result["configs"][task_name] = WorldConfig(
world_name=task_name,
onboarding_name=configuration.get("onboard_world"),
task_name=configuration.get("task_world"),
max_time_in_pool=configuration.get("timeout") or 300,
agents_required=configuration.get("agents_required") or 1,
backup_task=configuration.get("backup_task"),
)
# get world options, additional args
result["world_opt"] = cfg.get("opt", {})
result["additional_args"] = cfg.get("additional_args", {})
return result
| 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 tearDown(self):
if os.path.isfile(self.filename):
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 test_update_api_key(self) -> None:
user = self.example_user("hamlet")
email = user.email
self.login_user(user)
old_api_keys = get_all_api_keys(user)
# Ensure the old API keys are in the authentication cache, so
# that the below logic can test whether we have a cache-flushing bug.
for api_key in old_api_keys:
self.assertEqual(get_user_profile_by_api_key(api_key).email, email)
# First verify this endpoint is not registered in the /json/... path
# to prevent access with only a session.
result = self.client_post("/json/users/me/api_key/regenerate")
self.assertEqual(result.status_code, 404)
# A logged-in session doesn't allow access to an /api/v1/ endpoint
# of course.
result = self.client_post("/api/v1/users/me/api_key/regenerate")
self.assertEqual(result.status_code, 401)
result = self.api_post(user, "/api/v1/users/me/api_key/regenerate")
self.assert_json_success(result)
new_api_key = result.json()["api_key"]
self.assertNotIn(new_api_key, old_api_keys)
user = self.example_user("hamlet")
current_api_keys = get_all_api_keys(user)
self.assertIn(new_api_key, current_api_keys)
for api_key in old_api_keys:
with self.assertRaises(UserProfile.DoesNotExist):
get_user_profile_by_api_key(api_key)
for api_key in current_api_keys:
self.assertEqual(get_user_profile_by_api_key(api_key).email, email)
| 1 |
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
|
safe
|
def parse_soap_enveloped_saml(text, body_class, header_class=None):
"""Parses a SOAP enveloped SAML thing and returns header parts and body
:param text: The SOAP object as XML
:return: header parts and body as saml.samlbase instances
"""
envelope = defusedxml.ElementTree.fromstring(text)
assert envelope.tag == '{%s}Envelope' % NAMESPACE
# print(len(envelope))
body = None
header = {}
for part in envelope:
# print(">",part.tag)
if part.tag == '{%s}Body' % NAMESPACE:
for sub in part:
try:
body = saml2.create_class_from_element_tree(body_class, sub)
except Exception:
raise Exception(
"Wrong body type (%s) in SOAP envelope" % sub.tag)
elif part.tag == '{%s}Header' % NAMESPACE:
if not header_class:
raise Exception("Header where I didn't expect one")
# print("--- HEADER ---")
for sub in part:
# print(">>",sub.tag)
for klass in header_class:
# print("?{%s}%s" % (klass.c_namespace,klass.c_tag))
if sub.tag == "{%s}%s" % (klass.c_namespace, klass.c_tag):
header[sub.tag] = \
saml2.create_class_from_element_tree(klass, sub)
break
return body, header
| 1 |
Python
|
CWE-611
|
Improper Restriction of XML External Entity Reference
|
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
|
https://cwe.mitre.org/data/definitions/611.html
|
safe
|
def test_chunking_request_without_content(self):
header = tobytes("GET / HTTP/1.1\r\nTransfer-Encoding: chunked\r\n\r\n")
self.connect()
self.sock.send(header)
self.sock.send(b"0\r\n\r\n")
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
self.assertEqual(echo.body, b"")
self.assertEqual(echo.content_length, "0")
self.assertFalse("transfer-encoding" in headers)
| 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 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_generator.randrange(0, 256)
| 1 |
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
|
safe
|
def get(self, location, connection=None):
location = location.store_location
if not connection:
connection = self.get_connection(location)
try:
resp_headers, resp_body = connection.get_object(
container=location.container, obj=location.obj,
resp_chunk_size=self.CHUNKSIZE)
except swiftclient.ClientException, e:
if e.http_status == httplib.NOT_FOUND:
uri = location.get_uri()
raise exception.NotFound(_("Swift could not find image at "
"uri %(uri)s") % locals())
else:
raise
class ResponseIndexable(glance.store.Indexable):
def another(self):
try:
return self.wrapped.next()
except StopIteration:
return ''
length = int(resp_headers.get('content-length', 0))
return (ResponseIndexable(resp_body, length), length)
| 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_challenge(self):
rc, root, folder, object = self._makeTree()
response = FauxCookieResponse()
testURL = 'http://test'
request = FauxRequest(RESPONSE=response, URL=testURL,
ACTUAL_URL=testURL)
root.REQUEST = request
helper = self._makeOne().__of__(root)
helper.challenge(request, response)
self.assertEqual(response.status, 302)
self.assertEqual(len(response.headers), 3)
self.assertTrue(response.headers['Location'].endswith(quote(testURL)))
self.assertEqual(response.headers['Cache-Control'], 'no-cache')
self.assertEqual(response.headers['Expires'],
'Sat, 01 Jan 2000 00:00:00 GMT')
| 0 |
Python
|
CWE-601
|
URL Redirection to Untrusted Site ('Open Redirect')
|
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
|
https://cwe.mitre.org/data/definitions/601.html
|
vulnerable
|
def test_large_body(self):
# 1024 characters.
body = "This string has 32 characters.\r\n" * 32
s = tobytes(
"GET / HTTP/1.0\n" "Content-Length: %d\n" "\n" "%s" % (len(body), body)
)
self.connect()
self.sock.send(s)
fp = self.sock.makefile("rb", 0)
line, headers, echo = self._read_echo(fp)
self.assertline(line, "200", "OK", "HTTP/1.0")
self.assertEqual(echo.content_length, "1024")
self.assertEqual(echo.body, tobytes(body))
| 0 |
Python
|
CWE-444
|
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
|
The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination.
|
https://cwe.mitre.org/data/definitions/444.html
|
vulnerable
|
def open_soap_envelope(text):
"""
:param text: SOAP message
:return: dictionary with two keys "body"/"header"
"""
try:
envelope = defusedxml.ElementTree.fromstring(text)
except Exception as exc:
raise XmlParseError("%s" % exc)
assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE
assert len(envelope) >= 1
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
| 1 |
Python
|
CWE-611
|
Improper Restriction of XML External Entity Reference
|
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
|
https://cwe.mitre.org/data/definitions/611.html
|
safe
|
def test_filename(self):
with NamedTemporaryFile() as tmp:
fp = memmap(tmp.name, dtype=self.dtype, mode='w+',
shape=self.shape)
abspath = os.path.abspath(tmp.name)
fp[:] = self.data[:]
self.assertEqual(abspath, fp.filename)
b = fp[:1]
self.assertEqual(abspath, b.filename)
del b
del fp
| 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 render_POST(self, request):
"""
Register with the Identity Server
"""
send_cors(request)
args = get_args(request, ('matrix_server_name', 'access_token'))
hostname = args['matrix_server_name'].lower()
if not is_valid_hostname(hostname):
request.setResponseCode(400)
return {
'errcode': 'M_INVALID_PARAM',
'error': 'matrix_server_name must be a valid hostname'
}
result = yield self.client.get_json(
"matrix://%s/_matrix/federation/v1/openid/userinfo?access_token=%s"
% (
hostname,
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-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 prop_sentences_stats(self, type, vId = None):
return {
'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC",
'all_networks' : "SELECT networks.* FROM networks ORDER BY id",
'get_preview' : ("SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = ?" , vId),
'id_networks' : ("SELECT networks.* FROM networks WHERE id = ?", vId),
'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ",
'get_sessions' : "SELECT COUNT(*) AS Total FROM networks",
'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks",
'get_online' : ("SELECT COUNT(*) AS Total FROM victims WHERE status = ?", vId)
}.get(type, False)
| 1 |
Python
|
CWE-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_methodWithUnprintableASCIIRejected(self):
"""
Issuing a request with a method that contains unprintable
ASCII characters fails with a L{ValueError}.
"""
for c in UNPRINTABLE_ASCII:
method = b"GET%s" % (bytearray([c]),)
with self.assertRaises(ValueError) as cm:
self.attemptRequestWithMaliciousMethod(method)
self.assertRegex(str(cm.exception), "^Invalid method")
| 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 makeTrustRoot(self):
# If this option is specified, use a specific root CA cert. This is useful for testing when it's not
# practical to get the client cert signed by a real root CA but should never be used on a production server.
caCertFilename = self.sydent.cfg.get('http', 'replication.https.cacert')
if len(caCertFilename) > 0:
try:
fp = open(caCertFilename)
caCert = twisted.internet.ssl.Certificate.loadPEM(fp.read())
fp.close()
except Exception:
logger.warn("Failed to open CA cert file %s", caCertFilename)
raise
logger.warn("Using custom CA cert file: %s", caCertFilename)
return twisted.internet._sslverify.OpenSSLCertificateAuthorities([caCert.original])
else:
return twisted.internet.ssl.OpenSSLDefaultPaths()
| 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_sneaky_import_in_style(self):
# Prevent "@@importimport" -> "@import" replacement.
style_codes = [
"@@importimport(extstyle.css)",
"@ @ import import(extstyle.css)",
"@ @ importimport(extstyle.css)",
"@@ import import(extstyle.css)",
"@ @import import(extstyle.css)",
"@@importimport()",
]
for style_code in style_codes:
html = '<style>%s</style>' % style_code
s = lxml.html.fragment_fromstring(html)
cleaned = lxml.html.tostring(clean_html(s))
self.assertEqual(
b'<style>/* deleted */</style>',
cleaned,
"%s -> %s" % (style_code, cleaned))
| 1 |
Python
|
CWE-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 from_xml(self, content):
"""
Given some XML data, returns a Python dictionary of the decoded data.
"""
if lxml is None:
raise ImproperlyConfigured("Usage of the XML aspects requires lxml.")
return self.from_etree(parse_xml(StringIO(content)).getroot())
| 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 json_dumps(value, indent=None):
if isinstance(value, QuerySet):
result = serialize('json', value, indent=indent)
else:
result = json.dumps(value, indent=indent, cls=DjbletsJSONEncoder)
return mark_safe(force_text(result).translate(_safe_js_escapes))
| 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_is_valid_hostname(self):
"""Tests that the is_valid_hostname function accepts only valid
hostnames (or domain names), with optional port number.
"""
self.assertTrue(is_valid_hostname("example.com"))
self.assertTrue(is_valid_hostname("EXAMPLE.COM"))
self.assertTrue(is_valid_hostname("ExAmPlE.CoM"))
self.assertTrue(is_valid_hostname("example.com:4242"))
self.assertTrue(is_valid_hostname("localhost"))
self.assertTrue(is_valid_hostname("localhost:9000"))
self.assertTrue(is_valid_hostname("a.b:1234"))
self.assertFalse(is_valid_hostname("example.com:65536"))
self.assertFalse(is_valid_hostname("example.com:0"))
self.assertFalse(is_valid_hostname("example.com:a"))
self.assertFalse(is_valid_hostname("example.com:04242"))
self.assertFalse(is_valid_hostname("example.com: 4242"))
self.assertFalse(is_valid_hostname("example.com/example.com"))
self.assertFalse(is_valid_hostname("example.com#example.com"))
| 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_basic_two_credentials():
# Test Basic Authentication with multiple sets of credentials
http = httplib2.Http()
password1 = tests.gen_password()
password2 = tests.gen_password()
allowed = [("joe", password1)] # exploit shared mutable list
handler = tests.http_reflect_with_auth(
allow_scheme="basic", allow_credentials=allowed
)
with tests.server_request(handler, request_count=7) as uri:
http.add_credentials("fred", password2)
response, content = http.request(uri, "GET")
assert response.status == 401
http.add_credentials("joe", password1)
response, content = http.request(uri, "GET")
assert response.status == 200
allowed[0] = ("fred", password2)
response, content = http.request(uri, "GET")
assert response.status == 200
| 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_received_multiple_chunks(self):
from waitress.utilities import BadRequest
buf = DummyBuffer()
inst = self._makeOne(buf)
data = (
b"4\r\n"
b"Wiki\r\n"
b"5\r\n"
b"pedia\r\n"
b"E\r\n"
b" in\r\n"
b"\r\n"
b"chunks.\r\n"
b"0\r\n"
b"\r\n"
)
result = inst.received(data)
self.assertEqual(result, len(data))
self.assertEqual(inst.completed, True)
self.assertEqual(b"".join(buf.data), b"Wikipedia in\r\n\r\nchunks.")
self.assertEqual(inst.error, None)
| 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_require_realm_admin(self):
# type: () -> None
"""
The invite_by_admins_only realm setting works properly.
"""
realm = get_realm('zulip')
realm.invite_by_admins_only = True
realm.save()
self.login("hamlet@zulip.com")
email = "alice-test@zulip.com"
email2 = "bob-test@zulip.com"
invitee = "Alice Test <{}>, {}".format(email, email2)
self.assert_json_error(self.invite(invitee, ["Denmark"]),
"Must be a realm administrator")
# Now verify an administrator can do it
self.login("iago@zulip.com")
self.assert_json_success(self.invite(invitee, ["Denmark"]))
self.assertTrue(find_key_by_email(email))
self.assertTrue(find_key_by_email(email2))
self.check_sent_emails([email, email2])
| 1 |
Python
|
CWE-862
|
Missing Authorization
|
The software does not perform an authorization check when an actor attempts to access a resource or perform an action.
|
https://cwe.mitre.org/data/definitions/862.html
|
safe
|
def manipulate(root, strblock):
"""
Maliciously manipulates the structure to create a crafted FIT file
"""
# locate /images/kernel-1 (frankly, it just expects it to be the first one)
kernel_node = root[0][0]
# clone it to save time filling all the properties
fake_kernel = kernel_node.clone()
# rename the node
fake_kernel.name = b'kernel-2'
# get rid of signatures/hashes
fake_kernel.children = []
# NOTE: this simply replaces the first prop... either description or data
# should be good for testing purposes
fake_kernel.props[0].value = b'Super 1337 kernel\x00'
# insert the new kernel node under /images
root[0].children.append(fake_kernel)
# modify the default configuration
root[1].props[0].value = b'conf-2\x00'
# clone the first (only?) configuration
fake_conf = root[1][0].clone()
# rename and change kernel and fdt properties to select the crafted kernel
fake_conf.name = b'conf-2'
fake_conf.props[0].value = b'kernel-2\x00'
fake_conf.props[1].value = b'fdt-1\x00'
# insert the new configuration under /configurations
root[1].children.append(fake_conf)
return root, strblock
| 1 |
Python
|
NVD-CWE-noinfo
| null | null | null |
safe
|
def feed_author(book_id):
off = request.args.get("offset") or 0
entries, __, pagination = calibre_db.fill_indexpage((int(off) / (int(config.config_books_per_page)) + 1), 0,
db.Books,
db.Books.authors.any(db.Authors.id == book_id),
[db.Books.timestamp.desc()])
return render_xml_template('feed.xml', entries=entries, pagination=pagination)
| 0 |
Python
|
CWE-918
|
Server-Side Request Forgery (SSRF)
|
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
|
https://cwe.mitre.org/data/definitions/918.html
|
vulnerable
|
def exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable='/bin/sh', in_data=None):
''' run a command on the chroot '''
if sudoable and self.runner.become and self.runner.become_method not in self.become_methods_supported:
raise errors.AnsibleError("Internal Error: this module does not support running commands via %s" % self.runner.become_method)
if in_data:
raise errors.AnsibleError("Internal Error: this module does not support optimized module pipelining")
# We enter chroot as root so we ignore privlege escalation?
if executable:
local_cmd = [self.chroot_cmd, self.chroot, executable, '-c', cmd]
else:
local_cmd = '%s "%s" %s' % (self.chroot_cmd, self.chroot, cmd)
vvv("EXEC %s" % (local_cmd), host=self.chroot)
p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring),
cwd=self.runner.basedir,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = p.communicate()
return (p.returncode, '', stdout, stderr)
| 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 _create_dirs(self):
if not os.path.exists(self._path):
os.makedirs(self._path)
| 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 pref_set(key, value):
if get_user() is None:
return "Authentication required", 401
get_preferences()[key] = (None if value == 'null' else value)
return Response(json.dumps({'key': key, 'success': ''})), 201
| 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 insensitive_starts_with(field: Term, value: str) -> Criterion:
return Upper(field).like(Upper(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_modify_access_revoke_self(self):
"""
Test that an instructor cannot remove instructor privelages from themself.
"""
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url, {
'unique_student_identifier': self.instructor.email,
'rolename': 'instructor',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
# check response content
expected = {
'unique_student_identifier': self.instructor.username,
'rolename': 'instructor',
'action': 'revoke',
'removingSelfAsInstructor': True,
}
res_json = json.loads(response.content)
self.assertEqual(res_json, expected)
| 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 legacy_raw_flush(writer=None, name=None):
"""Legacy version of flush() that accepts a raw resource tensor for `writer`.
Do not use this function in any new code. Not supported and not part of the
public TF APIs.
Args:
writer: The `tf.summary.SummaryWriter` to flush. If None, the current
default writer will be used instead; if there is no current writer, this
returns `tf.no_op`. For this legacy version only, also accepts a raw
resource tensor pointing to the underlying C++ writer resource.
name: Ignored legacy argument for a name for the operation.
Returns:
The created `tf.Operation`.
"""
if writer is None or isinstance(writer, SummaryWriter):
# Forward to the TF2 implementation of flush() when possible.
return flush(writer, name)
else:
# Legacy fallback in case we were passed a raw resource tensor.
with ops.device("cpu:0"):
return gen_summary_ops.flush_summary_writer(writer, name=name)
| 1 |
Python
|
CWE-475
|
Undefined Behavior for Input to API
|
The behavior of this function is undefined unless its control parameter is set to a specific value.
|
https://cwe.mitre.org/data/definitions/475.html
|
safe
|
def is_leaf(cls, path):
abs_path = os.path.join(FOLDER, path.replace("/", os.sep))
return os.path.isfile(abs_path) and not abs_path.endswith(".props")
| 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 resolutionBegan(resolutionInProgress: IHostResolution) -> None:
recv.resolutionBegan(resolutionInProgress)
| 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 create_network(self, instance_name, instance, network_info):
"""Create the LXD container network on the host
:param instance_name: nova instance name
:param instance: nova instance object
:param network_info: instance network configuration object
:return:network configuration dictionary
"""
LOG.debug('create_network called for instance', instance=instance)
try:
network_devices = {}
if not network_info:
return
for vifaddr in network_info:
cfg = self.vif_driver.get_config(instance, vifaddr)
key = str(cfg['bridge'])
network_devices[key] = \
{'nictype': 'bridged',
'hwaddr': str(cfg['mac_address']),
'parent': key,
'type': 'nic'}
host_device = self.vif_driver.get_vif_devname(vifaddr)
if host_device:
network_devices[key]['host_name'] = host_device
return network_devices
except Exception as ex:
with excutils.save_and_reraise_exception():
LOG.error(
_LE('Fail to configure network for %(instance)s: %(ex)s'),
{'instance': instance_name, 'ex': ex}, instance=instance)
| 1 |
Python
|
NVD-CWE-noinfo
| null | null | null |
safe
|
def delete_service(self, context, service_id):
self.assert_admin(context)
service_ref = self.catalog_api.get_service(context, service_id)
if not service_ref:
raise exception.ServiceNotFound(service_id=service_id)
self.catalog_api.delete_service(context, service_id)
| 1 |
Python
|
CWE-287
|
Improper Authentication
|
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
|
https://cwe.mitre.org/data/definitions/287.html
|
safe
|
def test_security_group_ingress_quota_limit(self):
self.flags(quota_security_group_rules=20)
kwargs = {'project_id': self.context.project_id, 'name': 'test'}
sec_group = db.security_group_create(self.context, kwargs)
authz = self.cloud.authorize_security_group_ingress
for i in range(100, 120):
kwargs = {'to_port': i, 'from_port': i, 'ip_protocol': 'tcp'}
authz(self.context, group_id=sec_group['id'], **kwargs)
kwargs = {'to_port': 121, 'from_port': 121, 'ip_protocol': 'tcp'}
self.assertRaises(exception.EC2APIError, authz, self.context,
group_id=sec_group['id'], **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_valid(self, args):
qutebrowser._validate_untrusted_args(args)
| 1 |
Python
|
CWE-88
|
Improper Neutralization of Argument Delimiters in a Command ('Argument Injection')
|
The software constructs a string for a command to executed by a separate component
in another control sphere, but it does not properly delimit the
intended arguments, options, or switches within that command string.
|
https://cwe.mitre.org/data/definitions/88.html
|
safe
|
def test_modify_access_revoke_with_username(self):
url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.get(url, {
'unique_student_identifier': self.other_staff.username,
'rolename': 'staff',
'action': 'revoke',
})
self.assertEqual(response.status_code, 200)
| 0 |
Python
|
CWE-352
|
Cross-Site Request Forgery (CSRF)
|
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
|
https://cwe.mitre.org/data/definitions/352.html
|
vulnerable
|
def GET(self, path, queries=(), ignore_prefix=False):
return self._request('GET', path, queries, ignore_prefix=ignore_prefix)
| 1 |
Python
|
CWE-295
|
Improper Certificate Validation
|
The software does not validate, or incorrectly validates, a certificate.
|
https://cwe.mitre.org/data/definitions/295.html
|
safe
|
def test_longargs(self):
tree = self.parse(longargs)
for t in tree.body:
# The expected args are encoded in the function name
todo = set(t.name[1:])
self.assertEqual(len(t.args.args),
len(todo) - bool(t.args.vararg) - bool(t.args.kwarg))
self.assertTrue(t.name.startswith('f'), t.name)
for c in t.name[1:]:
todo.remove(c)
if c == 'v':
arg = t.args.vararg
elif c == 'k':
arg = t.args.kwarg
else:
assert 0 <= ord(c) - ord('a') < len(t.args.args)
arg = t.args.args[ord(c) - ord('a')]
self.assertEqual(arg.arg, c) # That's the argument name
self.assertEqual(arg.type_comment, arg.arg.upper())
assert not todo
tree = self.classic_parse(longargs)
for t in tree.body:
for arg in t.args.args + [t.args.vararg, t.args.kwarg]:
if arg is not None:
self.assertIsNone(arg.type_comment, "%s(%s:%r)" %
(t.name, arg.arg, arg.type_comment))
| 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_ipcache_entry(self, client):
"""Build a cache of dns results."""
if client in self.ipcache:
if self.ipcache[client]:
return self.ipcache[client]
else:
raise socket.gaierror
else:
# need to add entry
try:
ipaddr = socket.gethostbyname(client)
self.ipcache[client] = (ipaddr, client)
return (ipaddr, client)
except socket.gaierror:
cmd = "getent hosts %s" % client
ipaddr = Popen(cmd, shell=True, \
stdout=PIPE).stdout.read().strip().split()
if ipaddr:
self.ipcache[client] = (ipaddr, client)
return (ipaddr, client)
self.ipcache[client] = False
self.logger.error("Failed to find IP address for %s" % client)
raise socket.gaierror
| 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_list_course_role_members_noparams(self):
""" Test missing all query parameters. """
url = reverse('list_course_role_members', kwargs={'course_id': self.course.id.to_deprecated_string()})
response = self.client.post(url)
self.assertEqual(response.status_code, 400)
| 1 |
Python
|
CWE-352
|
Cross-Site Request Forgery (CSRF)
|
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
|
https://cwe.mitre.org/data/definitions/352.html
|
safe
|
def _callback() -> None:
has_bad_ip = False
for address in addresses:
# We only expect IPv4 and IPv6 addresses since only A/AAAA lookups
# should go through this path.
if not isinstance(address, (IPv4Address, IPv6Address)):
continue
ip_address = IPAddress(address.host)
if check_against_blacklist(
ip_address, self._ip_whitelist, self._ip_blacklist
):
logger.info(
"Dropped %s from DNS resolution to %s due to blacklist"
% (ip_address, hostname)
)
has_bad_ip = True
# if we have a blacklisted IP, we'd like to raise an error to block the
# request, but all we can really do from here is claim that there were no
# valid results.
if not has_bad_ip:
for address in addresses:
recv.addressResolved(address)
recv.resolutionComplete()
| 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 testSparseCountSparseOutputBadWeightsShape(self):
indices = [[0, 0], [0, 1], [1, 0], [1, 2]]
values = [1, 1, 1, 10]
weights = [1, 2, 4]
dense_shape = [2, 3]
with self.assertRaisesRegex(errors.InvalidArgumentError,
"Weights and values must have the same shape"):
self.evaluate(
gen_count_ops.SparseCountSparseOutput(
indices=indices,
values=values,
dense_shape=dense_shape,
weights=weights,
binary_output=False))
| 1 |
Python
|
CWE-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 _stub_class(self):
def fake_quota_class_get_all_by_name(context, quota_class):
result = dict(class_name=quota_class)
if quota_class == 'test_class':
result.update(
instances=5,
cores=10,
ram=25 * 1024,
volumes=5,
gigabytes=500,
floating_ips=5,
quota_security_groups=10,
quota_security_group_rules=20,
metadata_items=64,
injected_files=2,
injected_file_content_bytes=5 * 1024,
invalid_quota=100,
)
return result
self.stubs.Set(db, 'quota_class_get_all_by_name',
fake_quota_class_get_all_by_name)
| 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 xsrf_token(self):
"""The XSRF-prevention token for the current user/session.
To prevent cross-site request forgery, we set an '_xsrf' cookie
and include the same '_xsrf' value as an argument with all POST
requests. If the two do not match, we reject the form submission
as a potential forgery.
See http://en.wikipedia.org/wiki/Cross-site_request_forgery
"""
if not hasattr(self, "_xsrf_token"):
token = self.get_cookie("_xsrf")
if not token:
token = binascii.b2a_hex(os.urandom(16))
expires_days = 30 if self.current_user else None
self.set_cookie("_xsrf", token, expires_days=expires_days)
self._xsrf_token = token
return self._xsrf_token
| 0 |
Python
|
CWE-203
|
Observable Discrepancy
|
The product behaves differently or sends different responses under different circumstances in a way that is observable to an unauthorized actor, which exposes security-relevant information about the state of the product, such as whether a particular operation was successful or not.
|
https://cwe.mitre.org/data/definitions/203.html
|
vulnerable
|
def visit_Num(self, node):
return self._convert_num(node.n)
| 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 validate(self, data):
user = providers.get_provider('login').login_user(**data, context=self.context)
if user is not None:
data['user'] = user
return data
| 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 prop_sentences_stats(self, type, vId = None):
return {
'get_data' : "SELECT victims.*, geo.*, victims.ip AS ip_local, COUNT(clicks.id) FROM victims INNER JOIN geo ON victims.id = geo.id LEFT JOIN clicks ON clicks.id = victims.id GROUP BY victims.id ORDER BY victims.time DESC",
'all_networks' : "SELECT networks.* FROM networks ORDER BY id",
'get_preview' : "SELECT victims.*, geo.*, victims.ip AS ip_local FROM victims INNER JOIN geo ON victims.id = geo.id WHERE victims.id = '%s'" % (vId),
'id_networks' : "SELECT networks.* FROM networks WHERE id = '%s'" % (vId),
'get_requests' : "SELECT requests.*, geo.ip FROM requests INNER JOIN geo on geo.id = requests.user_id ORDER BY requests.date DESC, requests.id ",
'get_sessions' : "SELECT COUNT(*) AS Total FROM networks",
'get_clicks' : "SELECT COUNT(*) AS Total FROM clicks",
'get_online' : "SELECT COUNT(*) AS Total FROM victims WHERE status = '%s'" % ('online')
}.get(type, False)
| 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 _expand(self, key_material):
output = [b""]
counter = 1
while (self._algorithm.digest_size // 8) * len(output) < self._length:
h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
h.update(output[-1])
h.update(self._info)
h.update(six.int2byte(counter))
output.append(h.finalize())
counter += 1
return b"".join(output)[:self._length]
| 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_bad_host_header(self):
# https://corte.si/posts/code/pathod/pythonservers/index.html
to_send = "GET / HTTP/1.0\n" " Host: 0\n\n"
to_send = tobytes(to_send)
self.connect()
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "400", "Bad Request", "HTTP/1.0")
self.assertEqual(headers.get("server"), "waitress")
self.assertTrue(headers.get("date"))
| 0 |
Python
|
CWE-444
|
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
|
The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination.
|
https://cwe.mitre.org/data/definitions/444.html
|
vulnerable
|
def test_login_get(self):
login_code = LoginCode.objects.create(user=self.user)
response = self.client.get('/accounts/login/code/', {
'user': login_code.user.pk,
'code': login_code.code,
})
self.assertEqual(response.status_code, 200)
self.assertEqual(response.context['form'].cleaned_data['code'], login_code.code)
self.assertTrue(response.wsgi_request.user.is_anonymous)
self.assertTrue(LoginCode.objects.filter(pk=login_code.pk).exists())
| 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 __init__(self):
self.catalog_api = Manager()
self.identity_api = identity.Manager()
self.policy_api = policy.Manager()
self.token_api = token.Manager()
super(ServiceController, self).__init__()
| 1 |
Python
|
CWE-287
|
Improper Authentication
|
When an actor claims to have a given identity, the software does not prove or insufficiently proves that the claim is correct.
|
https://cwe.mitre.org/data/definitions/287.html
|
safe
|
def test_quotas_update_as_user(self):
body = {'quota_set': {'instances': 50, 'cores': 50,
'ram': 51200, 'volumes': 10,
'gigabytes': 1000, 'floating_ips': 10,
'metadata_items': 128, 'injected_files': 5,
'injected_file_content_bytes': 10240,
'security_groups': 10,
'security_group_rules': 20}}
req = fakes.HTTPRequest.blank('/v2/fake4/os-quota-sets/update_me')
self.assertRaises(webob.exc.HTTPForbidden, self.controller.update,
req, 'update_me', 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 _update_load_status(self, ok: bool) -> None:
"""Update the load status after a page finished loading.
Needs to be called by subclasses to trigger a load status update, e.g.
as a response to a loadFinished signal.
"""
if ok:
if self.url().scheme() == 'https':
if self.url().host() in self._insecure_hosts:
self._set_load_status(usertypes.LoadStatus.warn)
else:
self._set_load_status(usertypes.LoadStatus.success_https)
else:
self._set_load_status(usertypes.LoadStatus.success)
elif ok:
self._set_load_status(usertypes.LoadStatus.warn)
else:
self._set_load_status(usertypes.LoadStatus.error)
| 1 |
Python
|
CWE-684
|
Incorrect Provision of Specified Functionality
|
The code does not function according to its published specifications, potentially leading to incorrect usage.
|
https://cwe.mitre.org/data/definitions/684.html
|
safe
|
def test_filelike_longcl_http11(self):
to_send = "GET /filelike_longcl HTTP/1.1\n\n"
to_send = tobytes(to_send)
self.connect()
for t in range(0, 2):
self.sock.send(to_send)
fp = self.sock.makefile("rb", 0)
line, headers, response_body = read_http(fp)
self.assertline(line, "200", "OK", "HTTP/1.1")
cl = int(headers["content-length"])
self.assertEqual(cl, len(response_body))
ct = headers["content-type"]
self.assertEqual(ct, "image/jpeg")
self.assertTrue(b"\377\330\377" in response_body)
| 0 |
Python
|
CWE-444
|
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
|
The product acts as an intermediary HTTP agent
(such as a proxy or firewall) in the data flow between two
entities such as a client and server, but it does not
interpret malformed HTTP requests or responses in ways that
are consistent with how the messages will be processed by
those entities that are at the ultimate destination.
|
https://cwe.mitre.org/data/definitions/444.html
|
vulnerable
|
def test_project_quotas_overrides_noclass(self):
self._stub_class()
self._stub_project(True)
result = quota.get_project_quotas(self.context, 'admin')
self.assertEqual(result, dict(
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,
))
| 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 _join_and_check_path_within_fs(fs, *args):
'''os.path.join() with safety check for injected file paths.
Join the supplied path components and make sure that the
resulting path we are injecting into is within the
mounted guest fs. Trying to be clever and specifying a
path with '..' in it will hit this safeguard.
'''
absolute_path = os.path.realpath(os.path.join(fs, *args))
if not absolute_path.startswith(os.path.realpath(fs) + '/'):
raise exception.Invalid(_('injected file path not valid'))
return absolute_path
| 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 _w(self, content):
self.output.append(format_data(content, format_money_values=True))
| 0 |
Python
|
CWE-1236
|
Improper Neutralization of Formula Elements in a CSV File
|
The software saves user-provided information into a Comma-Separated Value (CSV) file, but it does not neutralize or incorrectly neutralizes special elements that could be interpreted as a command when the file is opened by spreadsheet software.
|
https://cwe.mitre.org/data/definitions/1236.html
|
vulnerable
|
def _make_sqlite_account_info(self, env=None, last_upgrade_to_run=None):
"""
Returns a new SqliteAccountInfo that has just read the data from the file.
:param dict env: Override Environment variables.
"""
# Override HOME to ensure hermetic tests
with mock.patch('os.environ', env or {'HOME': self.home}):
return SqliteAccountInfo(
file_name=self.db_path if not env else None,
last_upgrade_to_run=last_upgrade_to_run,
)
| 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 change_due_date(request, course_id):
"""
Grants a due date extension to a student for a particular unit.
"""
course = get_course_by_id(SlashSeparatedCourseKey.from_deprecated_string(course_id))
student = require_student_from_identifier(request.POST.get('student'))
unit = find_unit(course, request.POST.get('url'))
due_date = parse_datetime(request.POST.get('due_datetime'))
set_due_date_extension(course, unit, student, due_date)
return JsonResponse(_(
'Successfully changed due date for student {0} for {1} '
'to {2}').format(student.profile.name, _display_unit(unit),
due_date.strftime('%Y-%m-%d %H:%M')))
| 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 create(request, topic_id):
topic = get_object_or_404(
Topic.objects.for_access(request.user),
pk=topic_id)
form = NotificationCreationForm(
user=request.user,
topic=topic,
data=request.POST)
if form.is_valid():
form.save()
else:
messages.error(request, utils.render_form_errors(form))
return redirect(request.POST.get('next', topic.get_absolute_url()))
| 0 |
Python
|
CWE-601
|
URL Redirection to Untrusted Site ('Open Redirect')
|
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
|
https://cwe.mitre.org/data/definitions/601.html
|
vulnerable
|
def test_auth_plugin_prompt_password_in_session(self, httpbin):
self.start_session(httpbin)
session_path = self.config_dir / 'test-session.json'
class Plugin(AuthPlugin):
auth_type = 'test-prompted'
def get_auth(self, username=None, password=None):
basic_auth_header = "Basic " + b64encode(self.raw_auth.encode()).strip().decode('latin1')
return basic_auth(basic_auth_header)
plugin_manager.register(Plugin)
with mock.patch(
'httpie.cli.argtypes.AuthCredentials._getpass',
new=lambda self, prompt: 'password'
):
r1 = http(
'--session', str(session_path),
httpbin + '/basic-auth/user/password',
'--auth-type',
Plugin.auth_type,
'--auth', 'user',
)
r2 = http(
'--session', str(session_path),
httpbin + '/basic-auth/user/password',
)
assert HTTP_OK in r1
assert HTTP_OK in r2
# additional test for issue: https://github.com/httpie/httpie/issues/1098
with open(session_path) as session_file:
session_file_lines = ''.join(session_file.readlines())
assert "\"type\": \"test-prompted\"" in session_file_lines
assert "\"raw_auth\": \"user:password\"" in session_file_lines
plugin_manager.unregister(Plugin)
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def test_get_size_from_conf_default(self, conf_ceph_stub):
conf_ceph_stub('''
[global]
fsid=asdf
''')
assert encryption.get_key_size_from_conf() == '512'
| 1 |
Python
|
NVD-CWE-noinfo
| null | null | null |
safe
|
def new_type_to_old_type(typ: new.BasePrimitive) -> old.NodeType:
if isinstance(typ, new.BoolDefinition):
return old.BaseType("bool")
if isinstance(typ, new.AddressDefinition):
return old.BaseType("address")
if isinstance(typ, new.InterfaceDefinition):
return old.InterfaceType(typ._id)
if isinstance(typ, new.BytesMDefinition):
m = typ._length # type: ignore
return old.BaseType(f"bytes{m}")
if isinstance(typ, new.BytesArrayDefinition):
return old.ByteArrayType(typ.length)
if isinstance(typ, new.StringDefinition):
return old.StringType(typ.length)
if isinstance(typ, new.DecimalDefinition):
return old.BaseType("decimal")
if isinstance(typ, new.SignedIntegerAbstractType):
bits = typ._bits # type: ignore
return old.BaseType("int" + str(bits))
if isinstance(typ, new.UnsignedIntegerAbstractType):
bits = typ._bits # type: ignore
return old.BaseType("uint" + str(bits))
if isinstance(typ, new.ArrayDefinition):
return old.SArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.DynamicArrayDefinition):
return old.DArrayType(new_type_to_old_type(typ.value_type), typ.length)
if isinstance(typ, new.TupleDefinition):
return old.TupleType(typ.value_type)
if isinstance(typ, new.StructDefinition):
return old.StructType(
{n: new_type_to_old_type(t) for (n, t) in typ.members.items()}, typ._id
)
raise InvalidType(f"unknown type {typ}")
| 0 |
Python
|
CWE-190
|
Integer Overflow or Wraparound
|
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
|
https://cwe.mitre.org/data/definitions/190.html
|
vulnerable
|
def parse_content_disposition(content_disposition, default_filename):
# type: (str, str) -> str
"""
Parse the "filename" value from a Content-Disposition header, and
return the default filename if the result is empty.
"""
_type, params = cgi.parse_header(content_disposition)
filename = params.get('filename')
if filename:
# We need to sanitize the filename to prevent directory traversal
# in case the filename contains ".." path parts.
filename = sanitize_content_filename(filename)
return filename or default_filename
| 1 |
Python
|
CWE-22
|
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
|
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
|
https://cwe.mitre.org/data/definitions/22.html
|
safe
|
async def on_message(self, message):
if message.author.bot:
return
ctx = await self.bot.get_context(message)
if ctx.prefix is None or not ctx.invoked_with.replace("_", "").isalpha():
return
if ctx.valid and ctx.command.enabled:
try:
if await ctx.command.can_run(ctx):
return
except commands.errors.CheckFailure:
return
ctx.command = self.act
await self.bot.invoke(ctx)
| 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 reset_user_api_key(user_profile: Any) -> None:
old_api_key = user_profile.api_key
user_profile.api_key = generate_api_key()
cache_delete(user_profile_by_api_key_cache_key(old_api_key))
# Like with any API key change, we need to clear any server-side
# state for sending push notifications to mobile app clients that
# could have been registered with the old API key. Fortunately,
# we can just write to the queue processor that handles sending
# those notices to the push notifications bouncer service.
event = {'type': 'clear_push_device_tokens',
'user_profile_id': user_profile.id}
queue_json_publish("deferred_work", event)
| 1 |
Python
|
NVD-CWE-noinfo
| null | null | null |
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,
})
| 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 put_file(self, in_path, out_path):
''' transfer a file from local to zone '''
out_path = self._normalize_path(out_path, self.get_zone_path())
vvv("PUT %s TO %s" % (in_path, out_path), host=self.zone)
self._copy_file(in_path, out_path)
| 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 setup_webdir_if_it_doesnt_exist(ctx):
if is_web_app(ctx):
webdirPath = os.path.join(ctx['BUILD_DIR'], ctx['WEBDIR'])
if not os.path.exists(webdirPath):
fu = FileUtil(FakeBuilder(ctx), move=True)
fu.under('BUILD_DIR')
fu.into('WEBDIR')
fu.where_name_does_not_match(
'^%s/.*$' % os.path.join(ctx['BUILD_DIR'], '.bp'))
fu.where_name_does_not_match(
'^%s/.*$' % os.path.join(ctx['BUILD_DIR'], '.extensions'))
fu.where_name_does_not_match(
'^%s/.*$' % os.path.join(ctx['BUILD_DIR'], '.bp-config'))
fu.where_name_does_not_match(
'^%s$' % os.path.join(ctx['BUILD_DIR'], 'manifest.yml'))
fu.where_name_does_not_match(
'^%s/.*$' % os.path.join(ctx['BUILD_DIR'], ctx['LIBDIR']))
fu.where_name_does_not_match(
'^%s/.*$' % os.path.join(ctx['BUILD_DIR'], '.profile.d'))
fu.where_name_does_not_match(
'^%s$' % os.path.join(ctx['BUILD_DIR'], '.profile'))
fu.done()
| 1 |
Python
|
CWE-254
|
7PK - Security Features
|
Software security is not security software. Here we're concerned with topics like authentication, access control, confidentiality, cryptography, and privilege management.
|
https://cwe.mitre.org/data/definitions/254.html
|
safe
|
def 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 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-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_valid_filename(value, replace_whitespace=True, chars=128):
"""
Returns the given string converted to a string that can be used for a clean
filename. Limits num characters to 128 max.
"""
if value[-1:] == u'.':
value = value[:-1]+u'_'
value = value.replace("/", "_").replace(":", "_").strip('\0')
if use_unidecode:
if config.config_unicode_filename:
value = (unidecode.unidecode(value))
else:
value = value.replace(u'§', u'SS')
value = value.replace(u'ß', u'ss')
value = unicodedata.normalize('NFKD', value)
re_slugify = re.compile(r'[\W\s-]', re.UNICODE)
value = re_slugify.sub('', value)
if replace_whitespace:
# *+:\"/<>? are replaced by _
value = re.sub(r'[*+:\\\"/<>?]+', u'_', value, flags=re.U)
# pipe has to be replaced with comma
value = re.sub(r'[|]+', u',', value, flags=re.U)
value = value[:chars].strip()
if not value:
raise ValueError("Filename cannot be empty")
return value
| 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 runserverobj(method, docs=None, dt=None, dn=None, arg=None, args=None):
frappe.desk.form.run_method.runserverobj(method, docs=docs, dt=dt, dn=dn, arg=arg, args=args)
| 0 |
Python
|
CWE-79
|
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
|
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
|
https://cwe.mitre.org/data/definitions/79.html
|
vulnerable
|
def safe_markup(raw_html: str) -> jinja2.Markup:
"""
Sanitise a raw HTML string to a set of allowed tags and attributes, and linkify any bare URLs.
Args
raw_html: Unsafe HTML.
Returns:
A Markup object ready to safely use in a Jinja template.
"""
return jinja2.Markup(
bleach.linkify(
bleach.clean(
raw_html,
tags=ALLOWED_TAGS,
attributes=ALLOWED_ATTRS,
# bleach master has this, but it isn't released yet
# protocols=ALLOWED_SCHEMES,
strip=True,
)
)
)
| 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
|
async def initialize(self, bot):
# temporary backwards compatibility
key = await self.config.tenorkey()
if not key:
return
await bot.set_shared_api_tokens("tenor", api_key=key)
await self.config.tenorkey.clear()
| 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 _handle_carbon_sent(self, msg):
self.xmpp.event('carbon_sent', msg)
| 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_image(path):
def get_absolute_path(path):
import os
script_dir = os.path.dirname(__file__) # <-- absolute dir the script is in
rel_path = path
abs_file_path = os.path.join(script_dir, rel_path)
return abs_file_path
return send_file(
get_absolute_path(f"./images/{path}"),
mimetype='image/png',
attachment_filename='snapshot.png',
cache_timeout=0
)
| 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_check_password_calls_harden_runtime(self):
hasher = get_hasher('default')
encoded = make_password('letmein')
with mock.patch.object(hasher, 'harden_runtime'), \
mock.patch.object(hasher, 'must_update', return_value=True):
# Correct password supplied, no hardening needed
check_password('letmein', encoded)
self.assertEqual(hasher.harden_runtime.call_count, 0)
# Wrong password supplied, hardening needed
check_password('wrong_password', encoded)
self.assertEqual(hasher.harden_runtime.call_count, 1)
| 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 test_prepare_plugin_docs_command():
rc = DocConfig()
plugin_names = ['copy', 'file']
plugin_type = 'module'
rc.prepare_plugin_docs_command(plugin_names, plugin_type=plugin_type, snippet=True, playbook_dir='/tmp/test')
expected_command = [get_executable_path('ansible-doc'), '-s', '-t', 'module', '--playbook-dir', '/tmp/test', 'copy file']
assert rc.command == expected_command
assert rc.runner_mode == 'subprocess'
assert rc.execution_mode == BaseExecutionMode.ANSIBLE_COMMANDS
| 0 |
Python
|
NVD-CWE-noinfo
| null | null | null |
vulnerable
|
def test_received_headers_finished_expect_continue_false(self):
inst, sock, map = self._makeOneWithMap()
inst.server = DummyServer()
preq = DummyParser()
inst.request = preq
preq.expect_continue = False
preq.headers_finished = True
preq.completed = False
preq.empty = False
preq.retval = 1
inst.received(b"GET / HTTP/1.1\n\n")
self.assertEqual(inst.request, preq)
self.assertEqual(inst.server.tasks, [])
self.assertEqual(inst.outbufs[0].get(100), b"")
| 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 make_homeserver(self, reactor, clock):
self.push_attempts = []
m = Mock()
def post_json_get_json(url, body):
d = Deferred()
self.push_attempts.append((d, url, body))
return make_deferred_yieldable(d)
m.post_json_get_json = post_json_get_json
config = self.default_config()
config["start_pushers"] = True
hs = self.setup_test_homeserver(config=config, proxied_http_client=m)
return hs
| 0 |
Python
|
CWE-601
|
URL Redirection to Untrusted Site ('Open Redirect')
|
A web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a Redirect. This simplifies phishing attacks.
|
https://cwe.mitre.org/data/definitions/601.html
|
vulnerable
|
def test_quotas_defaults(self):
uri = '/v2/fake_tenant/os-quota-sets/fake_tenant/defaults'
req = fakes.HTTPRequest.blank(uri)
res_dict = self.controller.defaults(req, 'fake_tenant')
expected = {'quota_set': {
'id': 'fake_tenant',
'instances': 10,
'cores': 20,
'ram': 51200,
'volumes': 10,
'gigabytes': 1000,
'floating_ips': 10,
'metadata_items': 128,
'injected_files': 5,
'injected_file_content_bytes': 10240}}
self.assertEqual(res_dict, expected)
| 0 |
Python
|
CWE-264
|
Permissions, Privileges, and Access Controls
|
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
|
https://cwe.mitre.org/data/definitions/264.html
|
vulnerable
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.