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_credits_one(self, expected_count=1): self.add_change() data = generate_credits( None, timezone.now() - timedelta(days=1), timezone.now() + timedelta(days=1), translation__component=self.component, ) self.assertEqual( data, [{"Czech": [("[email protected]", "Weblate Test", expected_count)]}] )
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 verify_cert_against_key(self, filename, key_filename): """ check that a certificate validates against its private key. """ cert = self.data + filename key = self.data + key_filename cmd = ("openssl x509 -noout -modulus -in %s | openssl md5" % pipes.quote(cert)) cert_md5 = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read() cmd = ("openssl rsa -noout -modulus -in %s | openssl md5" % pipes.quote(key)) key_md5 = Popen(cmd, shell=True, stdout=PIPE, stderr=STDOUT).stdout.read() if cert_md5 == key_md5: return True return False
1
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def execute_cmd(cmd, from_async=False): """execute a request as python module""" for hook in frappe.get_hooks("override_whitelisted_methods", {}).get(cmd, []): # override using the first hook cmd = hook break # via server script if run_server_script_api(cmd): return None try: method = get_attr(cmd) except Exception as e: if frappe.local.conf.developer_mode: raise e else: frappe.respond_as_web_page(title='Invalid Method', html='Method not found', indicator_color='red', http_status_code=404) return if from_async: method = method.queue is_whitelisted(method) is_valid_http_method(method) return frappe.call(method, **frappe.form_dict)
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 from_dict(d: Dict[str, Any]) -> AModel: an_enum_value = AnEnum(d["an_enum_value"]) def _parse_a_camel_date_time(data: Dict[str, Any]) -> Union[datetime, date]: a_camel_date_time: Union[datetime, date] try: a_camel_date_time = datetime.fromisoformat(d["aCamelDateTime"]) return a_camel_date_time except: pass a_camel_date_time = date.fromisoformat(d["aCamelDateTime"]) return a_camel_date_time a_camel_date_time = _parse_a_camel_date_time(d["aCamelDateTime"]) a_date = date.fromisoformat(d["a_date"]) nested_list_of_enums = [] for nested_list_of_enums_item_data in d.get("nested_list_of_enums") or []: nested_list_of_enums_item = [] for nested_list_of_enums_item_item_data in nested_list_of_enums_item_data: nested_list_of_enums_item_item = DifferentEnum(nested_list_of_enums_item_item_data) nested_list_of_enums_item.append(nested_list_of_enums_item_item) nested_list_of_enums.append(nested_list_of_enums_item) some_dict = d.get("some_dict") return AModel( an_enum_value=an_enum_value, a_camel_date_time=a_camel_date_time, a_date=a_date, nested_list_of_enums=nested_list_of_enums, some_dict=some_dict, )
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 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 test_dump(self): node = ast.parse('spam(eggs, "and cheese")') self.assertEqual(ast.dump(node), "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load()), " "args=[Name(id='eggs', ctx=Load()), Constant(value='and cheese')], " "keywords=[]))])" ) self.assertEqual(ast.dump(node, annotate_fields=False), "Module([Expr(Call(Name('spam', Load()), [Name('eggs', Load()), " "Constant('and cheese')], []))])" ) self.assertEqual(ast.dump(node, include_attributes=True), "Module(body=[Expr(value=Call(func=Name(id='spam', ctx=Load(), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=4), " "args=[Name(id='eggs', ctx=Load(), lineno=1, col_offset=5, " "end_lineno=1, end_col_offset=9), Constant(value='and cheese', " "lineno=1, col_offset=11, end_lineno=1, end_col_offset=23)], keywords=[], " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24), " "lineno=1, col_offset=0, end_lineno=1, end_col_offset=24)])" )
0
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
def test_long_body(self): # check server doesnt close connection when body is too short # for cl header to_send = tobytes( "GET /long_body HTTP/1.0\r\n" "Connection: Keep-Alive\r\n" "Content-Length: 0\r\n" "\r\n" ) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) or None response_body = fp.read(content_length) self.assertEqual(int(status), 200) self.assertEqual(content_length, len(response_body)) self.assertEqual(response_body, tobytes("abcdefgh")) # remote does not close connection (keepalive header) self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line = fp.readline() # status line version, status, reason = (x.strip() for x in line.split(None, 2)) headers = parse_headers(fp) content_length = int(headers.get("content-length")) or None response_body = fp.read(content_length) self.assertEqual(int(status), 200)
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_file_position_after_tofile(self): # gh-4118 sizes = [io.DEFAULT_BUFFER_SIZE//8, io.DEFAULT_BUFFER_SIZE, io.DEFAULT_BUFFER_SIZE*8] for size in sizes: err_msg = "%d" % (size,) f = open(self.filename, 'wb') f.seek(size-1) f.write(b'\0') f.seek(10) f.write(b'12') np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10 + 2 + 8, err_msg=err_msg) f = open(self.filename, 'r+b') f.read(2) f.seek(0, 1) # seek between read&write required by ANSI C np.array([0], dtype=np.float64).tofile(f) pos = f.tell() f.close() assert_equal(pos, 10, err_msg=err_msg) os.unlink(self.filename)
0
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
vulnerable
def tearDown(self): LoginCode.objects.all().delete()
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 _is_javascript_scheme(s): if _is_image_dataurl(s): return None return _is_possibly_malicious_scheme(s)
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_parse_header_multiple_content_length(self): from waitress.parser import ParsingError data = b"GET /foobar HTTP/8.4\r\ncontent-length: 10\r\ncontent-length: 20\r\n" try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Content-Length is invalid", e.args[0]) else: # pragma: nocover self.assertTrue(False)
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_after_write_cb(self): to_send = "GET /after_write_cb HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") self.assertEqual(response_body, b"") # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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 testOrdering(self): import six import random with ops.Graph().as_default() as g: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64, name='pi') gi = array_ops.placeholder(dtypes.int64, name='gi') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea([ dtypes.int32, ], shapes=[[]], ordered=True) stage = stager.put(pi, [x], [0]) get = stager.get() size = stager.size() g.finalize() n = 10 with self.session(graph=g) as sess: # Keys n-1..0 keys = list(reversed(six.moves.range(n))) for i in keys: sess.run(stage, feed_dict={pi: i, x: i}) self.assertEqual(sess.run(size), n) # Check that key, values come out in ascending order for i, k in enumerate(reversed(keys)): get_key, values = sess.run(get) self.assertTrue(i == k == get_key == values) self.assertEqual(sess.run(size), 0)
1
Python
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
safe
def _inject_key_into_fs(key, fs, execute=None): """Add the given public ssh key to root's authorized_keys. key is an ssh key string. fs is the path to the base of the filesystem into which to inject the key. """ sshdir = os.path.join(fs, 'root', '.ssh') utils.execute('mkdir', '-p', sshdir, run_as_root=True) utils.execute('chown', 'root', sshdir, run_as_root=True) utils.execute('chmod', '700', sshdir, run_as_root=True) keyfile = os.path.join(sshdir, 'authorized_keys') key_data = [ '\n', '# The following ssh key was injected by Nova', '\n', key.strip(), '\n', ] utils.execute('tee', '-a', keyfile, process_input=''.join(key_data), run_as_root=True)
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 _buffered_exec_command(self, cmd, tmp_path, become_user=None, sudoable=False, executable=None, in_data=None, stdin=subprocess.PIPE): ''' run a command on the zone. This is only needed for implementing put_file() get_file() so that we don't have to read the whole file into memory. compared to exec_command() it looses some niceties like being able to return the process's exit code immediately. ''' 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 happily ignore privilege escalation local_cmd = self._generate_cmd(executable, cmd) vvv("EXEC %s" % (local_cmd), host=self.zone) p = subprocess.Popen(local_cmd, shell=isinstance(local_cmd, basestring), cwd=self.runner.basedir, stdin=stdin, stdout=subprocess.PIPE, stderr=subprocess.PIPE) return p
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_get_header_lines(self): result = self._callFUT(b"slam\nslim") self.assertEqual(result, [b"slam", b"slim"])
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 load_event(self, args, filename, from_misp, stix_version): self.outputname = '{}.json'.format(filename) if len(args) > 0 and args[0]: self.add_original_file(filename, args[0], stix_version) try: event_distribution = args[1] if not isinstance(event_distribution, int): event_distribution = int(event_distribution) if event_distribution.isdigit() else 5 except IndexError: event_distribution = 5 try: attribute_distribution = args[2] if attribute_distribution == 'event': attribute_distribution = event_distribution elif not isinstance(attribute_distribution, int): attribute_distribution = int(attribute_distribution) if attribute_distribution.isdigit() else event_distribution except IndexError: attribute_distribution = event_distribution self.misp_event.distribution = event_distribution self.__attribute_distribution = attribute_distribution self.from_misp = from_misp self.load_mapping()
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_bad_integer(self): # issue13436: Bad error message with invalid numeric values body = [ast.ImportFrom(module='time', names=[ast.alias(name='sleep')], level=None, lineno=None, col_offset=None)] mod = ast.Module(body) with self.assertRaises(ValueError) as cm: compile(mod, 'test', 'exec') self.assertIn("invalid integer value: None", str(cm.exception))
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 do_download_file(book, book_format, client, data, headers): if config.config_use_google_drive: #startTime = time.time() df = gd.getFileFromEbooksFolder(book.path, data.name + "." + book_format) #log.debug('%s', time.time() - startTime) if df: return gd.do_gdrive_download(df, headers) else: abort(404) else: filename = os.path.join(config.config_calibre_dir, book.path) if not os.path.isfile(os.path.join(filename, data.name + "." + book_format)): # ToDo: improve error handling log.error('File not found: %s', os.path.join(filename, data.name + "." + book_format)) if client == "kobo" and book_format == "kepub": headers["Content-Disposition"] = headers["Content-Disposition"].replace(".kepub", ".kepub.epub") response = make_response(send_from_directory(filename, data.name + "." + book_format)) # ToDo Check headers parameter for element in headers: response.headers[element[0]] = element[1] log.info('Downloading file: {}'.format(os.path.join(filename, data.name + "." + book_format))) return response
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_patch_bot_role(self) -> None: self.login("desdemona") email = "[email protected]" user_profile = self.get_bot_user(email) do_change_user_role(user_profile, UserProfile.ROLE_MEMBER, acting_user=user_profile) req = dict(role=UserProfile.ROLE_GUEST) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_success(result) user_profile = self.get_bot_user(email) self.assertEqual(user_profile.role, UserProfile.ROLE_GUEST) # Test for not allowing a non-owner user to make assign a bot an owner role desdemona = self.example_user("desdemona") do_change_user_role(desdemona, UserProfile.ROLE_REALM_ADMINISTRATOR, acting_user=None) req = dict(role=UserProfile.ROLE_REALM_OWNER) result = self.client_patch(f"/json/bots/{self.get_bot_user(email).id}", req) self.assert_json_error(result, "Must be an organization owner")
0
Python
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
vulnerable
def get_by_name(self, name, project): return ( Person.query.filter(Person.name == name) .filter(Project.id == project.id) .one() )
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 test_modify_access_bad_action(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'robot-not-an-action', }) 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 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-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 set_admins(self) -> None: name = self.results["deploy"]["func-name"]["value"] key = self.results["deploy"]["func-key"]["value"] table_service = TableService(account_name=name, account_key=key) if self.admins: update_admins(table_service, self.application_name, self.admins)
0
Python
CWE-285
Improper Authorization
The software does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/285.html
vulnerable
def attemptRequestWithMaliciousMethod(self, method): """ Attempt a request with the provided method. @param method: see L{MethodInjectionTestsMixin} """ agent = client.Agent(self.createReactor()) uri = b"http://twisted.invalid" agent.request(method, uri, client.Headers(), None)
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 testPeek(self): with ops.Graph().as_default() as g: with ops.device('/cpu:0'): x = array_ops.placeholder(dtypes.int32, name='x') pi = array_ops.placeholder(dtypes.int64) gi = array_ops.placeholder(dtypes.int64) p = array_ops.placeholder(dtypes.int32, name='p') with ops.device(test.gpu_device_name()): stager = data_flow_ops.MapStagingArea([ dtypes.int32, ], shapes=[[]]) stage = stager.put(pi, [x], [0]) peek = stager.peek(gi) size = stager.size() g.finalize() n = 10 with self.session(graph=g) as sess: for i in range(n): sess.run(stage, feed_dict={x: i, pi: i}) for i in range(n): self.assertEqual(sess.run(peek, feed_dict={gi: i})[0], i) self.assertEqual(sess.run(size), 10)
1
Python
CWE-843
Access of Resource Using Incompatible Type ('Type Confusion')
The program allocates or initializes a resource such as a pointer, object, or variable using one type, but it later accesses that resource using a type that is incompatible with the original type.
https://cwe.mitre.org/data/definitions/843.html
safe
def home_get_preview(): vId = request.form['vId'] t = (vId,) d = db.sentences_stats('get_preview', t) n = db.sentences_stats('id_networks', t) return json.dumps({'status' : 'OK', 'vId' : vId, 'd' : d, 'n' : n});
1
Python
CWE-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_uses_default(self): account_info = self._make_sqlite_account_info( env={ 'HOME': self.home, 'USERPROFILE': self.home, } ) actual_path = os.path.abspath(account_info.filename) assert os.path.join(self.home, '.b2_account_info') == actual_path
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_reset_student_attempts_all(self, act): """ Test reset all student attempts. """ url = reverse('reset_student_attempts', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'problem_to_reset': self.problem_urlname, 'all_students': True, }) self.assertEqual(response.status_code, 200) self.assertTrue(act.called)
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def test_modify_access_bad_action(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'staff', 'action': 'robot-not-an-action', }) self.assertEqual(response.status_code, 400)
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 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 last_modified(self): modification_time = \ time.gmtime(os.path.getmtime(self._filesystem_path)) return time.strftime("%a, %d %b %Y %H:%M:%S +0000", modification_time)
1
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
safe
def 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-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 test_http11_listlentwo(self): body = string.ascii_letters to_send = "GET /list_lentwo HTTP/1.1\n" "Content-Length: %s\n\n" % len(body) to_send += body to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb") line, headers, response_body = read_http(fp) self.assertline(line, "200", "OK", "HTTP/1.1") expected = b"" for chunk in (body[0], body[1:]): expected += tobytes( "%s\r\n%s\r\n" % (str(hex(len(chunk))[2:].upper()), chunk) ) expected += b"0\r\n\r\n" self.assertEqual(response_body, expected) # connection is always closed at the end of a chunked response self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
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_withstmt(self): tree = self.parse(withstmt) self.assertEqual(tree.body[0].type_comment, "int") tree = self.classic_parse(withstmt) self.assertEqual(tree.body[0].type_comment, None)
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def test_get_students_features_teams(self, has_teams): """ Test that get_students_features includes team info when the course is has teams enabled, and does not when the course does not have teams enabled """ if has_teams: self.course = CourseFactory.create(teams_configuration={ 'max_size': 2, 'topics': [{'topic-id': 'topic', 'name': 'Topic', 'description': 'A Topic'}] }) course_instructor = InstructorFactory(course_key=self.course.id) self.client.login(username=course_instructor.username, password='test') url = reverse('get_students_features', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, {}) res_json = json.loads(response.content) self.assertEqual('team' in res_json['feature_names'], has_teams)
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_modify_access_with_inactive_user(self): self.other_user.is_active = False self.other_user.save() # pylint: disable=no-member url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_user.username, 'rolename': 'beta', 'action': 'allow', }) self.assertEqual(response.status_code, 200) expected = { 'unique_student_identifier': self.other_user.username, 'inactiveUser': 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 _on_ssl_errors(self): self._has_ssl_errors = True
0
Python
CWE-684
Incorrect Provision of Specified Functionality
The code does not function according to its published specifications, potentially leading to incorrect usage.
https://cwe.mitre.org/data/definitions/684.html
vulnerable
def testOutputSizeOutOfBounds(self): with self.assertRaisesRegex(ValueError, "Negative.* dimension size caused by overflow"): with self.session() as sess, self.test_scope(): tf_in = constant_op.constant( -3.5e+35, shape=[10, 19, 22], dtype=dtypes.float32) block_shape = constant_op.constant( 1879048192, shape=[2], dtype=dtypes.int64) paddings = constant_op.constant(0, shape=[2, 2], dtype=dtypes.int32) sess.run(array_ops.space_to_batch_nd(tf_in, block_shape, paddings))
1
Python
CWE-190
Integer Overflow or Wraparound
The software performs a calculation that can produce an integer overflow or wraparound, when the logic assumes that the resulting value will always be larger than the original value. This can introduce other weaknesses when the calculation is used for resource management or execution control.
https://cwe.mitre.org/data/definitions/190.html
safe
def 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())
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 _props_path(self): """Absolute path of the file storing the collection properties.""" return self._filesystem_path + ".props"
1
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
safe
def _inject_net_into_fs(net, fs, execute=None): """Inject /etc/network/interfaces into the filesystem rooted at fs. net is the contents of /etc/network/interfaces. """ netdir = os.path.join(os.path.join(fs, 'etc'), 'network') utils.execute('mkdir', '-p', netdir, run_as_root=True) utils.execute('chown', 'root:root', netdir, run_as_root=True) utils.execute('chmod', 755, netdir, run_as_root=True) netfile = os.path.join(netdir, 'interfaces') utils.execute('tee', netfile, process_input=net, run_as_root=True)
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 expr(self, node, msg=None, *, exc=ValueError): mod = ast.Module([ast.Expr(node)]) self.mod(mod, msg, exc=exc)
0
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
vulnerable
def test_deserializer(self): exemplar = dict(quota_class_set=dict( metadata_items='10', injected_file_content_bytes='20', volumes='30', gigabytes='40', ram='50', floating_ips='60', instances='70', injected_files='80', security_groups='10', security_group_rules='20', cores='90')) intext = ("<?xml version='1.0' encoding='UTF-8'?>\n" '<quota_class_set>' '<metadata_items>10</metadata_items>' '<injected_file_content_bytes>20' '</injected_file_content_bytes>' '<volumes>30</volumes>' '<gigabytes>40</gigabytes>' '<ram>50</ram>' '<floating_ips>60</floating_ips>' '<instances>70</instances>' '<injected_files>80</injected_files>' '<cores>90</cores>' '<security_groups>10</security_groups>' '<security_group_rules>20</security_group_rules>' '</quota_class_set>') result = self.deserializer.deserialize(intext)['body'] self.assertEqual(result, exemplar)
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 sanitized_join(path: str, root: pathlib.Path) -> pathlib.Path: result = (root / path).absolute() if not str(result).startswith(str(root) + "/"): raise ValueError("resulting path is outside root") return result
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_entrance_exam_sttudent_delete_state(self): """ Test delete single student entrance exam state. """ url = reverse('reset_student_attempts_for_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.post(url, { 'unique_student_identifier': self.student.email, 'delete_module': True, }) self.assertEqual(response.status_code, 200) # make sure the module has been deleted changed_modules = StudentModule.objects.filter(module_state_key__in=self.ee_modules) self.assertEqual(changed_modules.count(), 0)
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 check_read_formats(entry): EXTENSIONS_READER = {'TXT', 'PDF', 'EPUB', 'CBZ', 'CBT', 'CBR', 'DJVU'} bookformats = list() if len(entry.data): for ele in iter(entry.data): if ele.format.upper() in EXTENSIONS_READER: bookformats.append(ele.format.lower()) return bookformats
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 nonroot_execute(*cmd_parts, **kwargs): kwargs.pop('run_as_root', None) return real_execute(*cmd_parts, **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 main(): app = create_app() init_errorhandler() app.register_blueprint(web) app.register_blueprint(opds) app.register_blueprint(jinjia) app.register_blueprint(about) app.register_blueprint(shelf) app.register_blueprint(admi) app.register_blueprint(remotelogin) app.register_blueprint(meta) app.register_blueprint(gdrive) app.register_blueprint(editbook) if kobo_available: app.register_blueprint(kobo) app.register_blueprint(kobo_auth) if oauth_available: app.register_blueprint(oauth) success = web_server.start() sys.exit(0 if success else 1)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def remove_cookies(self, names: Iterable[str]): for name in names: if name in self['cookies']: del self['cookies'][name]
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def rpn(self, irc, msg, args): """<rpn math expression> Returns the value of an RPN expression. """ stack = [] for arg in args: try: x = complex(arg) if x == abs(x): x = abs(x) stack.append(x) except ValueError: # Not a float. if arg in SAFE_ENV: f = SAFE_ENV[arg] if callable(f): called = False arguments = [] while not called and stack: arguments.append(stack.pop()) try: stack.append(f(*arguments)) called = True except TypeError: pass if not called: irc.error(_('Not enough arguments for %s') % arg) return else: stack.append(f) elif arg in self._rpnEnv: self._rpnEnv[arg](stack) else: arg2 = stack.pop() arg1 = stack.pop() s = '%s%s%s' % (arg1, arg, arg2) try: stack.append(safe_eval(s, allow_ints=False)) except SyntaxError: irc.error(format(_('%q is not a defined function.'), arg)) return if len(stack) == 1: irc.reply(str(self._complexToString(complex(stack[0])))) else: s = ', '.join(map(self._complexToString, list(map(complex, stack)))) irc.reply(_('Stack: [%s]') % s)
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 adv_search_extension(q, include_extension_inputs, exclude_extension_inputs): for extension in include_extension_inputs: q = q.filter(db.Books.data.any(db.Data.format == extension)) for extension in exclude_extension_inputs: q = q.filter(not_(db.Books.data.any(db.Data.format == extension))) return q
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def test_str(self): code = LoginCode(user=self.user, code='foo', timestamp=datetime(2018, 7, 1)) self.assertEqual(str(code), 'test_user - 2018-07-01 00:00:00')
0
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
vulnerable
def test_enrollment_report_features_csv(self): """ test to generate enrollment report. enroll users, admin staff using registration codes. """ InvoiceTransaction.objects.create( invoice=self.sale_invoice_1, amount=self.sale_invoice_1.total_amount, status='completed', created_by=self.instructor, last_modified_by=self.instructor ) course_registration_code = CourseRegistrationCode.objects.create( code='abcde', course_id=self.course.id.to_deprecated_string(), created_by=self.instructor, invoice=self.sale_invoice_1, invoice_item=self.invoice_item, mode_slug='honor' ) admin_user = AdminFactory() admin_cart = Order.get_cart_for_user(admin_user) PaidCourseRegistration.add_to_order(admin_cart, self.course.id) admin_cart.purchase() # create a new user/student and enroll # in the course using a registration code # and then validates the generated detailed enrollment report test_user = UserFactory() self.register_with_redemption_code(test_user, course_registration_code.code) CourseFinanceAdminRole(self.course.id).add_users(self.instructor) UserProfileFactory.create(user=self.students[0], meta='{"company": "asdasda"}') self.client.login(username=self.instructor.username, password='test') url = reverse('get_enrollment_report', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertIn('The detailed enrollment report is being created.', response.content)
0
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
def test_more_custom_templates(self): """ Test custom templates and metadata Template is relative to collection-specific dir Add custom metadata and test its presence in custom search page """ custom_search = os.path.join(self.root_dir, COLLECTIONS, 'test', 'templates', 'search.html') # add metadata main(['metadata', 'test', '--set', 'some=value']) with open(custom_search, 'w+b') as fh: fh.write(b'overriden search page: ') fh.write(b'{{ metadata | tojson }}\n') # force clear of jinja env cache to reload self.app.rewriterapp.jinja_env.jinja_env.cache = {} resp = self.testapp.get('/test/') resp.charset = 'utf-8' assert resp.status_int == 200 assert resp.content_type == 'text/html' assert 'overriden search page: ' in resp.text print(resp.text) assert '"some":"value"' in resp.text, resp.text
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The software does not neutralize or incorrectly neutralizes user-controllable input before it is placed in output that is used as a web page that is served to other users.
https://cwe.mitre.org/data/definitions/79.html
vulnerable
def test_get_ora2_responses_success(self): url = reverse('export_ora2_data', kwargs={'course_id': unicode(self.course.id)}) with patch('instructor_task.api.submit_export_ora2_data') as mock_submit_ora2_task: mock_submit_ora2_task.return_value = True response = self.client.post(url, {}) success_status = "The ORA data report is being generated." self.assertIn(success_status, response.content)
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def __init__(self, fobj): """ fobj is a file-like object as an icns resource """ # signature : (start, length) self.dct = dct = {} self.fobj = fobj sig, filesize = nextheader(fobj) if sig != b'icns': raise SyntaxError('not an icns file') i = HEADERSIZE while i < filesize: sig, blocksize = nextheader(fobj) if blocksize <= 0: raise SyntaxError('invalid block header') i += HEADERSIZE blocksize -= HEADERSIZE dct[sig] = (i, blocksize) fobj.seek(blocksize, 1) i += blocksize
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 addressResolved(address: IAddress) -> None: addresses.append(address)
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 testSparseDenseInvalidInputs(self): self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(0, shape=[17, 2], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[5], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="Dimensions 17 and 5 are not compatible") self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(0, shape=[17, 4], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[17], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="Dimensions 4 and 2 are not compatible") self._testSparseDenseInvalidInputs( a_indices=constant_op.constant(7, shape=[17, 2], dtype=dtypes.int64), a_values=constant_op.constant(0, shape=[17], dtype=dtypes.float32), a_shape=constant_op.constant([3, 4], dtype=dtypes.int64), b=constant_op.constant(1, shape=[3, 4], dtype=dtypes.float32), expected_error="invalid index")
1
Python
CWE-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 test_list_email_content_error(self, task_history_request): """ Test handling of error retrieving email """ invalid_task = FakeContentTask(0, 0, 0, 'test') invalid_task.make_invalid_input() task_history_request.return_value = [invalid_task] url = reverse('list_email_content', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.get(url, {}) self.assertEqual(response.status_code, 200) self.assertTrue(task_history_request.called) returned_email_info = json.loads(response.content)['emails'] self.assertEqual(len(returned_email_info), 1) returned_info = returned_email_info[0] for info in ['created', 'sent_to', 'email', 'number_sent', 'requester']: self.assertEqual(returned_info[info], None)
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 check_dir(im_dir): """ Check if dir is safe; if it is, return True. These checks make sense only on posix: * directory has correct owner * directory has correct permissions (0700) * directory is not a symlink """ def check_is_dir(): return os.path.isdir(im_dir) def check_permissions(): """ If on posix, permissions should be 0700. """ writable = is_writable(im_dir) if sys.platform != 'win32': try: im_dir_stat = os.stat(im_dir) except OSError: return False writable &= stat.S_IMODE(im_dir_stat.st_mode) == 0o0700 return writable def check_ownership(): """ Intermediate dir owner should be same as owner of process. """ if sys.platform != 'win32': try: im_dir_stat = os.stat(im_dir) except OSError: return False proc_uid = os.getuid() return proc_uid == im_dir_stat.st_uid return True def check_is_symlink(): """ Check if intermediate dir is symlink. """ try: return not os.path.islink(im_dir) except OSError: return False checks = [check_is_dir, check_permissions, check_ownership, check_is_symlink] for check in checks: if not check(): return False return True
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def 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 connectionMade(self): method = getattr(self.factory, 'method', b'GET') self.sendCommand(method, self.factory.path) if self.factory.scheme == b'http' and self.factory.port != 80: host = self.factory.host + b':' + intToBytes(self.factory.port) elif self.factory.scheme == b'https' and self.factory.port != 443: host = self.factory.host + b':' + intToBytes(self.factory.port) else: host = self.factory.host self.sendHeader(b'Host', self.factory.headers.get(b"host", host)) self.sendHeader(b'User-Agent', self.factory.agent) data = getattr(self.factory, 'postdata', None) if data is not None: self.sendHeader(b"Content-Length", intToBytes(len(data))) cookieData = [] for (key, value) in self.factory.headers.items(): if key.lower() not in self._specialHeaders: # we calculated it on our own self.sendHeader(key, value) if key.lower() == b'cookie': cookieData.append(value) for cookie, cookval in self.factory.cookies.items(): cookieData.append(cookie + b'=' + cookval) if cookieData: self.sendHeader(b'Cookie', b'; '.join(cookieData)) self.endHeaders() self.headers = {} if data is not None: self.transport.write(data)
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 __init__( self, reactor: IReactorPluggableNameResolver, ip_whitelist: Optional[IPSet], ip_blacklist: IPSet,
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 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-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 _handle_carbon_sent(self, msg): self.xmpp.event('carbon_sent', msg)
0
Python
CWE-346
Origin Validation Error
The software does not properly verify that the source of data or communication is valid.
https://cwe.mitre.org/data/definitions/346.html
vulnerable
def require_post_params(*args, **kwargs): """ Checks for required parameters or renders a 400 error. (decorator with arguments) `args` is a *list of required POST parameter names. `kwargs` is a **dict of required POST 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.POST.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
1
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
safe
def test_modify_access_bad_role(self): """ Test with an invalid action parameter. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'robot-not-a-roll', 'action': 'revoke', }) 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 __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 test_list_entrance_exam_instructor_with_invalid_exam_key(self): """ Test list task history for entrance exam failure if course has invalid exam. """ url = reverse('list_entrance_exam_instructor_tasks', kwargs={'course_id': unicode(self.course_with_invalid_ee.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, }) self.assertEqual(response.status_code, 400)
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 testInputParserPythonExpression(self): x1 = np.ones([2, 10]) x2 = np.array([[1], [2], [3]]) x3 = np.mgrid[0:5, 0:5] x4 = [[3], [4]] input_expr_str = ('x1=np.ones([2,10]);x2=np.array([[1],[2],[3]]);' 'x3=np.mgrid[0:5,0:5];x4=[[3],[4]]') feed_dict = saved_model_cli.load_inputs_from_input_arg_string( '', input_expr_str, '') self.assertTrue(np.all(feed_dict['x1'] == x1)) self.assertTrue(np.all(feed_dict['x2'] == x2)) self.assertTrue(np.all(feed_dict['x3'] == x3)) self.assertTrue(np.all(feed_dict['x4'] == x4))
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 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
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 create(request, comment_id): comment = get_object_or_404(Comment, pk=comment_id) form = FlagForm( user=request.user, comment=comment, data=post_data(request)) if is_post(request) and form.is_valid(): form.save() return redirect(request.POST.get('next', comment.get_absolute_url())) return render( request=request, template_name='spirit/comment/flag/create.html', context={ 'form': form, 'comment': comment})
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 main(): app = create_app() init_errorhandler() app.register_blueprint(web) app.register_blueprint(opds) app.register_blueprint(jinjia) app.register_blueprint(about) app.register_blueprint(shelf) app.register_blueprint(admi) app.register_blueprint(remotelogin) app.register_blueprint(meta) app.register_blueprint(gdrive) app.register_blueprint(editbook) if kobo_available: app.register_blueprint(kobo) app.register_blueprint(kobo_auth) if oauth_available: app.register_blueprint(oauth) success = web_server.start() sys.exit(0 if success else 1)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def _get_obj_abosolute_path(dataset, rel_path): return os.path.join(DATAROOT, dataset, rel_path)
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
vulnerable
def testInputPreProcessFormats(self): input_str = 'input1=/path/file.txt[ab3];input2=file2' input_expr_str = 'input3=np.zeros([2,2]);input4=[4,5]' input_dict = saved_model_cli.preprocess_inputs_arg_string(input_str) input_expr_dict = saved_model_cli.preprocess_input_exprs_arg_string( input_expr_str) self.assertTrue(input_dict['input1'] == ('/path/file.txt', 'ab3')) self.assertTrue(input_dict['input2'] == ('file2', None)) print(input_expr_dict['input3']) self.assertAllClose(input_expr_dict['input3'], np.zeros([2, 2])) self.assertAllClose(input_expr_dict['input4'], [4, 5]) self.assertTrue(len(input_dict) == 2) self.assertTrue(len(input_expr_dict) == 2)
0
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
vulnerable
def test_recursive_tf_function_with_cond(self): @def_function.function(autograph=False) def recursive_fn(n): return cond_v2.cond_v2(n > 0, recursive_fn(n - 1), 1) with self.assertRaises(RecursionError): recursive_fn(constant_op.constant(5))
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 mysql_insensitive_starts_with(field: Term, value: str) -> Criterion: return Like( functions.Upper(functions.Cast(field, SqlTypes.CHAR)), functions.Upper(StrWrapper(f"{escape_like(value)}%")), escape="", )
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 format_runtime(runtime): retVal = "" if runtime.days: retVal = format_unit(runtime.days, 'duration-day', length="long", locale=get_locale()) + ', ' mins, seconds = divmod(runtime.seconds, 60) hours, minutes = divmod(mins, 60) # ToDo: locale.number_symbols._data['timeSeparator'] -> localize time separator ? if hours: retVal += '{:d}:{:02d}:{:02d}s'.format(hours, minutes, seconds) elif minutes: retVal += '{:2d}:{:02d}s'.format(minutes, seconds) else: retVal += '{:2d}s'.format(seconds) return retVal
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 testSparseFillEmptyRowsGradLargeIndexMapValue(self): reverse_index_map = [2, 10] grad_values = [0, 1, 2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, r'Elements in reverse index must be in \[0, 4\)'): self.evaluate( gen_sparse_ops.SparseFillEmptyRowsGrad( reverse_index_map=reverse_index_map, grad_values=grad_values))
1
Python
CWE-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 is_node(cls, path): filesystem_path = pathutils.path_to_filesystem(path, FOLDER) return os.path.isdir(filesystem_path)
1
Python
CWE-21
DEPRECATED: Pathname Traversal and Equivalence Errors
This category has been deprecated. It was originally used for organizing weaknesses involving file names, which enabled access to files outside of a restricted directory (path traversal) or to perform operations on files that would otherwise be restricted (path equivalence). Consider using either the File Handling Issues category (CWE-1219) or the class Use of Incorrectly-Resolved Name or Reference (CWE-706).
https://cwe.mitre.org/data/definitions/21.html
safe
def get_config(p, section, key, env_var, default, boolean=False, integer=False, floating=False): ''' return a configuration variable with casting ''' value = _get_config(p, section, key, env_var, default) if boolean: return mk_boolean(value) if value and integer: return int(value) if value and floating: return float(value) return value
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 _ensureValidURI(uri): """ A valid URI cannot contain control characters (i.e., characters between 0-32, inclusive and 127) or non-ASCII characters (i.e., characters with values between 128-255, inclusive). @param uri: the URI to check @type uri: L{bytes} @return: the URI if it is valid @rtype: L{bytes} @raise ValueError: if the URI is not valid @see: U{https://tools.ietf.org/html/rfc3986#section-3.3}, U{https://tools.ietf.org/html/rfc3986#appendix-A}, U{https://tools.ietf.org/html/rfc5234#appendix-B.1} """ if _VALID_URI.match(uri): return uri raise ValueError("Invalid URI {!r}".format(uri))
1
Python
CWE-74
Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
The software constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/74.html
safe
def fetch_file(self, in_path, out_path): ''' fetch a file from chroot to local ''' if not in_path.startswith(os.path.sep): in_path = os.path.join(os.path.sep, in_path) normpath = os.path.normpath(in_path) in_path = os.path.join(self.chroot, normpath[1:]) vvv("FETCH %s TO %s" % (in_path, out_path), host=self.chroot) if not os.path.exists(in_path): raise errors.AnsibleFileNotFound("file or module does not exist: %s" % in_path) try: shutil.copyfile(in_path, out_path) except shutil.Error: traceback.print_exc() raise errors.AnsibleError("failed to copy: %s and %s are the same" % (in_path, out_path)) except IOError: traceback.print_exc() raise errors.AnsibleError("failed to transfer file to %s" % 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 test_get_student_progress_url(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].email.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 test_received_preq_not_completed(self): inst, sock, map = self._makeOneWithMap() inst.server = DummyServer() preq = DummyParser() inst.request = preq preq.completed = False preq.empty = True inst.received(b"GET / HTTP/1.1\n\n") self.assertEqual(inst.requests, ()) self.assertEqual(inst.server.tasks, [])
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 request( self, uri, method="GET", body=None, headers=None, redirections=DEFAULT_MAX_REDIRECTS, connection_type=None,
0
Python
CWE-400
Uncontrolled Resource Consumption
The software does not properly control the allocation and maintenance of a limited resource, thereby enabling an actor to influence the amount of resources consumed, eventually leading to the exhaustion of available resources.
https://cwe.mitre.org/data/definitions/400.html
vulnerable
def test_modify_access_revoke_not_allowed(self): """ Test revoking access that a user does not have. """ url = reverse('modify_access', kwargs={'course_id': self.course.id.to_deprecated_string()}) response = self.client.post(url, { 'unique_student_identifier': self.other_staff.email, 'rolename': 'instructor', 'action': 'revoke', }) self.assertEqual(response.status_code, 200)
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(self, stream): '''read vault steam and return python object''' return yaml.safe_load(self.vault.decrypt(stream))
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_parse_header_bad_content_length(self): from waitress.parser import ParsingError data = b"GET /foobar HTTP/8.4\r\ncontent-length: abc\r\n" try: self.parser.parse_header(data) except ParsingError as e: self.assertIn("Content-Length is invalid", e.args[0]) else: # pragma: nocover self.assertTrue(False)
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_rescore_entrance_exam_all_student_and_single(self): """ Test re-scoring with both all students and single student parameters. """ url = reverse('rescore_entrance_exam', kwargs={'course_id': unicode(self.course.id)}) response = self.client.get(url, { 'unique_student_identifier': self.student.email, 'all_students': True, }) self.assertEqual(response.status_code, 400)
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 installNameResolver(self, resolver: IHostnameResolver) -> IHostnameResolver: raise NotImplementedError()
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 __exit__(self, *args, **kw): for k, v in self.old_values.items(): if v is not None: os.environ[k] = v
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 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", req_config, "-days", days, "-key", key, "-text", "-out", req] res = Popen(cmd, shell=True, stdout=PIPE).stdout.read() return req
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_create_rule_quota_limit(self): req = fakes.HTTPRequest.blank('/v2/fake/os-security-group-rules') for num in range(100, 100 + FLAGS.quota_security_group_rules): rule = { 'ip_protocol': 'tcp', 'from_port': num, 'to_port': num, 'parent_group_id': '2', 'group_id': '1' } self.controller.create(req, {'security_group_rule': rule}) rule = { 'ip_protocol': 'tcp', 'from_port': '121', 'to_port': '121', 'parent_group_id': '2', 'group_id': '1' } self.assertRaises(webob.exc.HTTPBadRequest, self.controller.create, req, {'security_group_rule': rule})
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_keepalive_http_11(self): # Handling of Keep-Alive within HTTP 1.1 # All connections are kept alive, unless stated otherwise data = "Default: Keep me alive" s = tobytes( "GET / HTTP/1.1\r\nContent-Length: %d\r\n\r\n%s" % (len(data), data) ) self.connect() self.sock.send(s) response = httplib.HTTPResponse(self.sock) response.begin() self.assertEqual(int(response.status), 200) self.assertTrue(response.getheader("connection") != "close")
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
async def on_GET(self, origin, content, query, room_id): return await self.handler.on_room_state_request( origin, room_id, parse_string_from_args(query, "event_id", None, required=False), )
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 setUp(self): # Create a new sydent self.sydent = make_sydent()
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 make_homeserver(self, reactor, clock): self.fetches = [] async def get_file(destination, path, output_stream, args=None, max_size=None): """ Returns tuple[int,dict,str,int] of file length, response headers, absolute URI, and response code. """ def write_to(r): data, response = r output_stream.write(data) return response d = Deferred() d.addCallback(write_to) self.fetches.append((d, destination, path, args)) return await make_deferred_yieldable(d) client = Mock() client.get_file = get_file self.storage_path = self.mktemp() self.media_store_path = self.mktemp() os.mkdir(self.storage_path) os.mkdir(self.media_store_path) config = self.default_config() config["media_store_path"] = self.media_store_path config["thumbnail_requirements"] = {} config["max_image_pixels"] = 2000000 provider_config = { "module": "synapse.rest.media.v1.storage_provider.FileStorageProviderBackend", "store_local": True, "store_synchronous": False, "store_remote": True, "config": {"directory": self.storage_path}, } config["media_storage_providers"] = [provider_config] hs = self.setup_test_homeserver(config=config, http_client=client) 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 view_configuration(): read_column = calibre_db.session.query(db.Custom_Columns)\ .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all() restrict_columns = calibre_db.session.query(db.Custom_Columns)\ .filter(and_(db.Custom_Columns.datatype == 'text', db.Custom_Columns.mark_for_delete == 0)).all() languages = calibre_db.speaking_language() translations = [LC('en')] + babel.list_translations() return render_title_template("config_view_edit.html", conf=config, readColumns=read_column, restrictColumns=restrict_columns, languages=languages, translations=translations, title=_(u"UI Configuration"), page="uiconfig")
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