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_received_body_too_large(self): from waitress.utilities import RequestEntityTooLarge self.parser.adj.max_request_body_size = 2 data = ( b"GET /foobar HTTP/1.1\r\n" b"Transfer-Encoding: chunked\r\n" b"X-Foo: 1\r\n" b"\r\n" b"1d;\r\n" b"This string has 29 characters\r\n" b"0\r\n\r\n" ) result = self.parser.received(data) self.assertEqual(result, 62) self.parser.received(data[result:]) self.assertTrue(self.parser.completed) self.assertTrue(isinstance(self.parser.error, RequestEntityTooLarge))
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 testSparseCountSparseOutputBadIndicesShape(self): indices = [[[0], [0]], [[0], [1]], [[1], [0]], [[1], [2]]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex(errors.InvalidArgumentError, "Input indices must be a 2-dimensional tensor"): 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 admin(): version = updater_thread.get_current_version_info() if version is False: commit = _(u'Unknown') else: if 'datetime' in version: commit = version['datetime'] tz = timedelta(seconds=time.timezone if (time.localtime().tm_isdst == 0) else time.altzone) form_date = datetime.strptime(commit[:19], "%Y-%m-%dT%H:%M:%S") if len(commit) > 19: # check if string has timezone if commit[19] == '+': form_date -= timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) elif commit[19] == '-': form_date += timedelta(hours=int(commit[20:22]), minutes=int(commit[23:])) commit = format_datetime(form_date - tz, format='short', locale=get_locale()) else: commit = version['version'] allUser = ub.session.query(ub.User).all() email_settings = config.get_mail_settings() kobo_support = feature_support['kobo'] and config.config_kobo_sync return render_title_template("admin.html", allUser=allUser, email=email_settings, config=config, commit=commit, feature_support=feature_support, kobo_support=kobo_support, title=_(u"Admin page"), page="admin")
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 _decompress(compressed_path: Text, target_path: Text) -> None: with tarfile.open(compressed_path, "r:gz") as tar: tar.extractall(target_path) # target dir will be created if it not exists
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 whitelist(allow_guest=False, xss_safe=False, methods=None): """ Decorator for whitelisting a function and making it accessible via HTTP. Standard request will be `/api/method/[path.to.method]` :param allow_guest: Allow non logged-in user to access this method. :param methods: Allowed http method to access the method. Use as: @frappe.whitelist() def myfunc(param1, param2): pass """ if not methods: methods = ['GET', 'POST', 'PUT', 'DELETE'] def innerfn(fn): global whitelisted, guest_methods, xss_safe_methods, allowed_http_methods_for_whitelisted_func whitelisted.append(fn) allowed_http_methods_for_whitelisted_func[fn] = methods if allow_guest: guest_methods.append(fn) if xss_safe: xss_safe_methods.append(fn) return fn return innerfn
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 make_sydent(test_config={}): """Create a new sydent Args: test_config (dict): any configuration variables for overriding the default sydent config """ # Use an in-memory SQLite database. Note that the database isn't cleaned up between # tests, so by default the same database will be used for each test if changed to be # a file on disk. if 'db' not in test_config: test_config['db'] = {'db.file': ':memory:'} else: test_config['db'].setdefault('db.file', ':memory:') reactor = MemoryReactorClock() return Sydent(reactor=reactor, cfg=parse_config_dict(test_config))
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_check_safe_path(self): ret = disk_api._join_and_check_path_within_fs('/foo', 'etc', 'something.conf') self.assertEquals(ret, '/foo/etc/something.conf')
1
Python
CWE-264
Permissions, Privileges, and Access Controls
Weaknesses in this category are related to the management of permissions, privileges, and other security features that are used to perform access control.
https://cwe.mitre.org/data/definitions/264.html
safe
void AveragePool(const float* input_data, const Dims<4>& input_dims, int stride_width, int stride_height, int pad_width, int pad_height, int kwidth, int kheight, float* output_data, const Dims<4>& output_dims) { float output_activation_min, output_activation_max; GetActivationMinMax(Ac, &output_activation_min, &output_activation_max); AveragePool(input_data, input_dims, stride_width, stride_height, pad_width, pad_height, kwidth, kheight, output_activation_min, output_activation_max, output_data, output_dims); }
0
Python
CWE-835
Loop with Unreachable Exit Condition ('Infinite Loop')
The program contains an iteration or loop with an exit condition that cannot be reached, i.e., an infinite loop.
https://cwe.mitre.org/data/definitions/835.html
vulnerable
def classic_parse(self, source): return ast.parse(source)
1
Python
CWE-125
Out-of-bounds Read
The software reads data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/125.html
safe
def __call__(self, request): file_fields = request.POST.getlist("s3file") for field_name in file_fields: paths = request.POST.getlist(field_name) request.FILES.setlist(field_name, list(self.get_files_from_storage(paths))) if local_dev and request.path == "/__s3_mock__/": return views.S3MockView.as_view()(request) return self.get_response(request)
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 dispatch(self, request, *args, **kwargs): if (int(self.kwargs["user_id"]) == request.user.pk or request.user.has_perm("user.change_user")): if not self.user_allowed(request.user): return self.handle_no_permission(request) return super(OtpRequiredMixin, self).dispatch(request, *args, **kwargs) raise PermissionDenied
1
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
safe
def makepasv(self): if self.af == socket.AF_INET: host, port = parse227(self.sendcmd('PASV')) else: host, port = parse229(self.sendcmd('EPSV'), self.sock.getpeername()) return host, port
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def _inject_admin_password_into_fs(admin_passwd, fs, execute=None): """Set the root password to admin_passwd admin_password is a root password fs is the path to the base of the filesystem into which to inject the key. This method modifies the instance filesystem directly, and does not require a guest agent running in the instance. """ # The approach used here is to copy the password and shadow # files from the instance filesystem to local files, make any # necessary changes, and then copy them back. admin_user = 'root' fd, tmp_passwd = tempfile.mkstemp() os.close(fd) fd, tmp_shadow = tempfile.mkstemp() os.close(fd) passwd_path = _join_and_check_path_within_fs(fs, 'etc', 'passwd') shadow_path = _join_and_check_path_within_fs(fs, 'etc', 'shadow') utils.execute('cp', passwd_path, tmp_passwd, run_as_root=True) utils.execute('cp', shadow_path, tmp_shadow, run_as_root=True) _set_passwd(admin_user, admin_passwd, tmp_passwd, tmp_shadow) utils.execute('cp', tmp_passwd, passwd_path, run_as_root=True) os.unlink(tmp_passwd) utils.execute('cp', tmp_shadow, shadow_path, run_as_root=True) os.unlink(tmp_shadow)
1
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The software uses external input to construct a pathname that is intended to identify a file or directory that is located underneath a restricted parent directory, but the software does not properly neutralize special elements within the pathname that can cause the pathname to resolve to a location that is outside of the restricted directory.
https://cwe.mitre.org/data/definitions/22.html
safe
def test_logout_get(self): login_code = LoginCode.objects.create(user=self.user, code='foobar') self.client.login(username=self.user.username, code=login_code.code) response = self.client.post('/accounts/logout/?next=/accounts/login/') self.assertEqual(response.status_code, 302) self.assertEqual(response['Location'], '/accounts/login/') self.assertTrue(response.wsgi_request.user.is_anonymous)
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_poisoned_http_host(self): "Poisoned HTTP_HOST headers can't be used for reset emails" # This attack is based on the way browsers handle URLs. The colon # should be used to separate the port, but if the URL contains an @, # the colon is interpreted as part of a username for login purposes, # making 'evil.com' the request domain. Since HTTP_HOST is used to # produce a meaningful reset URL, we need to be certain that the # HTTP_HOST header isn't poisoned. This is done as a check when get_host() # is invoked, but we check here as a practical consequence. with self.assertRaises(SuspiciousOperation): self.client.post('/password_reset/', {'email': '[email protected]'}, HTTP_HOST='www.example:[email protected]' ) self.assertEqual(len(mail.outbox), 0)
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 _contains_display_name(self, display_name: str) -> bool: if not display_name: return False body = self._event.content.get("body", None) if not body or not isinstance(body, str): return False # Similar to _glob_matches, but do not treat display_name as a glob. r = regex_cache.get((display_name, False, True), None) if not r: r1 = re.escape(display_name) r1 = _re_word_boundary(r1) r = re.compile(r1, flags=re.IGNORECASE) regex_cache[(display_name, False, True)] = r return bool(r.search(body))
0
Python
CWE-331
Insufficient Entropy
The software uses an algorithm or scheme that produces insufficient entropy, leaving patterns or clusters of values that are more likely to occur than others.
https://cwe.mitre.org/data/definitions/331.html
vulnerable
def __init__(self, env, escape): SandboxedFormatterMixin.__init__(self, env) EscapeFormatter.__init__(self, escape)
1
Python
CWE-134
Use of Externally-Controlled Format String
The software uses a function that accepts a format string as an argument, but the format string originates from an external source.
https://cwe.mitre.org/data/definitions/134.html
safe
def render_prepare_search_form(cc): # prepare data for search-form tags = calibre_db.session.query(db.Tags)\ .join(db.books_tags_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_tags_link.tag'))\ .order_by(db.Tags.name).all() series = calibre_db.session.query(db.Series)\ .join(db.books_series_link)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(text('books_series_link.series'))\ .order_by(db.Series.name)\ .filter(calibre_db.common_filters()).all() shelves = ub.session.query(ub.Shelf)\ .filter(or_(ub.Shelf.is_public == 1, ub.Shelf.user_id == int(current_user.id)))\ .order_by(ub.Shelf.name).all() extensions = calibre_db.session.query(db.Data)\ .join(db.Books)\ .filter(calibre_db.common_filters()) \ .group_by(db.Data.format)\ .order_by(db.Data.format).all() if current_user.filter_language() == u"all": languages = calibre_db.speaking_language() else: languages = None return render_title_template('search_form.html', tags=tags, languages=languages, extensions=extensions, series=series,shelves=shelves, title=_(u"Advanced Search"), cc=cc, page="advsearch")
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 setUp(self): super(TokenExpirationTest, self).setUp() self.identity_api = kvs_identity.Identity() self.load_fixtures(default_fixtures) self.api = service.TokenController()
1
Python
CWE-255
Credentials Management Errors
Weaknesses in this category are related to the management of credentials.
https://cwe.mitre.org/data/definitions/255.html
safe
def recursive_fn(n, x): if n > 0: return n * recursive_fn(n - 1, x) else: return x
1
Python
CWE-667
Improper Locking
The software does not properly acquire or release a lock on a resource, leading to unexpected resource state changes and behaviors.
https://cwe.mitre.org/data/definitions/667.html
safe
def add_original_file(self, filename, original_filename, version): with open(filename, 'rb') as f: sample = base64.b64encode(f.read()).decode('utf-8') original_file = MISPObject('original-imported-file') original_file.add_attribute(**{'type': 'attachment', 'value': original_filename, 'object_relation': 'imported-sample', 'data': sample}) original_file.add_attribute(**{'type': 'text', 'object_relation': 'format', 'value': 'STIX {}'.format(version)}) self.misp_event.add_object(**original_file)
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
async def on_GET(self, origin, content, query, room_id, event_id): return await self.handler.on_event_auth(origin, room_id, event_id)
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 list_zones(self): pipe = subprocess.Popen([self.zoneadm_cmd, 'list', '-ip'], cwd=self.runner.basedir, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE) zones = [] for l in pipe.stdout.readlines(): # 1:work:running:/zones/work:3126dc59-9a07-4829-cde9-a816e4c5040e:native:shared s = l.split(':') if s[1] != 'global': zones.append(s[1]) return zones
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 read_fixed_bytes(self, num_bytes: int) -> bytes: """Reads a fixed number of bytes from the underlying bytestream. Args: num_bytes The number of bytes to read. Returns: The read bytes. Raises: EOFError: Fewer than ``num_bytes`` bytes remained in the underlying bytestream. """ read_bytes = self.read(num_bytes) if len(read_bytes) < num_bytes: raise EOFError(read_bytes) return read_bytes
0
Python
CWE-209
Generation of Error Message Containing Sensitive Information
The software generates an error message that includes sensitive information about its environment, users, or associated data.
https://cwe.mitre.org/data/definitions/209.html
vulnerable
def test_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", 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 _setup_master(self): Router.max_message_size = self.config['max_message_size'] if self.config['profiling']: enable_profiling() self.broker = Broker(activate_compat=False) self.router = Router(self.broker) self.router.debug = self.config.get('debug', False) self.router.undirectional = self.config['unidirectional'] self.router.add_handler( fn=self._on_shutdown_msg, handle=SHUTDOWN, policy=has_parent_authority, ) self.master = Context(self.router, 0, 'master') parent_id = self.config['parent_ids'][0] if parent_id == 0: self.parent = self.master else: self.parent = Context(self.router, parent_id, 'parent') in_fd = self.config.get('in_fd', 100) in_fp = os.fdopen(os.dup(in_fd), 'rb', 0) os.close(in_fd) out_fp = os.fdopen(os.dup(self.config.get('out_fd', 1)), 'wb', 0) self.stream = MitogenProtocol.build_stream(self.router, parent_id) self.stream.accept(in_fp, out_fp) self.stream.name = 'parent' self.stream.receive_side.keep_alive = False listen(self.stream, 'disconnect', self._on_parent_disconnect) listen(self.broker, 'exit', self._on_broker_exit)
0
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
vulnerable
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-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 feed(self, data): parser = self.parser for n in range(100): # make sure we never loop forever consumed = parser.received(data) data = data[consumed:] if parser.completed: return raise ValueError("Looping") # pragma: no cover
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 skip(self, type): if type == TType.BOOL: self.readBool() elif type == TType.BYTE: self.readByte() elif type == TType.I16: self.readI16() elif type == TType.I32: self.readI32() elif type == TType.I64: self.readI64() elif type == TType.DOUBLE: self.readDouble() elif type == TType.FLOAT: self.readFloat() elif type == TType.STRING: self.readString() elif type == TType.STRUCT: name = self.readStructBegin() while True: (name, type, id) = self.readFieldBegin() if type == TType.STOP: break self.skip(type) self.readFieldEnd() self.readStructEnd() elif type == TType.MAP: (ktype, vtype, size) = self.readMapBegin() for _ in range(size): self.skip(ktype) self.skip(vtype) self.readMapEnd() elif type == TType.SET: (etype, size) = self.readSetBegin() for _ in range(size): self.skip(etype) self.readSetEnd() elif type == TType.LIST: (etype, size) = self.readListBegin() for _ in range(size): self.skip(etype) self.readListEnd() else: raise TProtocolException( TProtocolException.INVALID_DATA, "Unexpected type for skipping {}".format(type) )
1
Python
CWE-755
Improper Handling of Exceptional Conditions
The software does not handle or incorrectly handles an exceptional condition.
https://cwe.mitre.org/data/definitions/755.html
safe
def _copy_file(self, in_path, out_path): 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 __setstate__(self, state): """Restore from pickled state.""" self.__dict__ = state self._lock = threading.RLock() self._descriptor_cache = weakref.WeakKeyDictionary() self._key_for_call_stats = self._get_key_for_call_stats()
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 main(req: func.HttpRequest) -> func.HttpResponse: response = ok( Info( resource_group=get_base_resource_group(), region=get_base_region(), subscription=get_subscription(), versions=versions(), instance_id=get_instance_id(), insights_appid=get_insights_appid(), insights_instrumentation_key=get_insights_instrumentation_key(), ) ) return response
0
Python
CWE-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 custom_login(request, **kwargs): # Currently, Django 1.5 login view does not redirect somewhere if the user is logged in if request.user.is_authenticated: return redirect(request.GET.get('next', request.user.st.get_absolute_url())) if request.method == "POST" and request.is_limited(): return redirect(request.get_full_path()) return _login_view(request, authentication_form=LoginForm, **kwargs)
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 check_valid_read_column(column): if column != "0": if not calibre_db.session.query(db.Custom_Columns).filter(db.Custom_Columns.id == column) \ .filter(and_(db.Custom_Columns.datatype == 'bool', db.Custom_Columns.mark_for_delete == 0)).all(): return False return True
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def _create_dirs(self): if not os.path.exists(self._filesystem_path): os.makedirs(self._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 save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1" or ip == "0.0.0.0" or ip == "::": log.error("Localhost was accessed for cover upload") return False, _("You are not allowed to access localhost for cover uploads") img = requests.get(url, timeout=(10, 200), allow_redirects=False) # ToDo: Error Handling img.raise_for_status() return save_cover(img, book_path) except (socket.gaierror, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as ex: log.info(u'Cover Download Error %s', ex) return False, _("Error Downloading Cover") except MissingDelegateError as ex: log.info(u'File Format Error %s', ex) return False, _("Cover Format Error")
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_federation_client_allowed_ip(self, resolver): self.sydent.run() request, channel = make_request( self.sydent.reactor, "POST", "/_matrix/identity/v2/account/register", { "access_token": "foo", "expires_in": 300, "matrix_server_name": "example.com", "token_type": "Bearer", }, ) resolver.return_value = defer.succeed( [ Server( host=self.allowed_domain, port=443, priority=1, weight=1, expires=100, ) ] ) request.render(self.sydent.servlets.registerServlet) transport, protocol = self._get_http_request( self.allowed_ip.decode("ascii"), 443 ) self.assertRegex( transport.value(), b"^GET /_matrix/federation/v1/openid/userinfo" ) self.assertRegex(transport.value(), b"Host: example.com") # Send it the HTTP response res_json = '{ "sub": "@test:example.com" }'.encode("ascii") protocol.dataReceived( b"HTTP/1.1 200 OK\r\n" b"Server: Fake\r\n" b"Content-Type: application/json\r\n" b"Content-Length: %i\r\n" b"\r\n" b"%s" % (len(res_json), res_json) ) self.assertEqual(channel.code, 200)
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_before_start_response_http_11(self): to_send = "GET /before_start_response HTTP/1.1\r\n\r\n" to_send = tobytes(to_send) self.connect() self.sock.send(to_send) fp = self.sock.makefile("rb", 0) line, headers, response_body = read_http(fp) self.assertline(line, "500", "Internal Server Error", "HTTP/1.1") cl = int(headers["content-length"]) self.assertEqual(cl, len(response_body)) self.assertTrue(response_body.startswith(b"Internal Server Error")) self.assertEqual( sorted(headers.keys()), ["connection", "content-length", "content-type", "date", "server"] ) # connection has been closed self.send_check_error(to_send) self.assertRaises(ConnectionClosed, read_http, fp)
1
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def test_qute_settings_persistence(short_tmpdir, request, quteproc_new): """Make sure settings from qute://settings are persistent.""" args = _base_args(request.config) + ['--basedir', str(short_tmpdir)] quteproc_new.start(args) quteproc_new.open_path( 'qute://settings/set?option=search.ignore_case&value=always') assert quteproc_new.get_setting('search.ignore_case') == 'always' quteproc_new.send_cmd(':quit') quteproc_new.wait_for_quit() quteproc_new.start(args) assert quteproc_new.get_setting('search.ignore_case') == 'always'
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 icalc(self, irc, msg, args, text): """<math expression> This is the same as the calc command except that it allows integer math, and can thus cause the bot to suck up CPU. Hence it requires the 'trusted' capability to use. """ try: self.log.info('evaluating %q from %s', text, msg.prefix) x = safe_eval(text, allow_ints=True) irc.reply(str(x)) except OverflowError: maxFloat = math.ldexp(0.9999999999999999, 1024) irc.error(_('The answer exceeded %s or so.') % maxFloat) except InvalidNode as e: irc.error(_('Invalid syntax: %s') % e.args[0]) except NameError as e: irc.error(_('%s is not a defined function.') % str(e).split()[1]) except Exception as e: irc.error(utils.exnToString(e))
1
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
safe
def test_urlsplit_normalization(self): # Certain characters should never occur in the netloc, # including under normalization. # Ensure that ALL of them are detected and cause an error illegal_chars = '/:#?@' hex_chars = {'{:04X}'.format(ord(c)) for c in illegal_chars} denorm_chars = [ c for c in map(chr, range(128, sys.maxunicode)) if (hex_chars & set(unicodedata.decomposition(c).split())) and c not in illegal_chars ] # Sanity check that we found at least one such character self.assertIn('\u2100', denorm_chars) self.assertIn('\uFF03', denorm_chars) # bpo-36742: Verify port separators are ignored when they # existed prior to decomposition urllib.parse.urlsplit('http://\u30d5\u309a:80') with self.assertRaises(ValueError): urllib.parse.urlsplit('http://\u30d5\u309a\ufe1380') for scheme in ["http", "https", "ftp"]: for netloc in ["netloc{}false.netloc", "n{}user@netloc"]: for c in denorm_chars: url = "{}://{}/path".format(scheme, netloc.format(c)) with self.subTest(url=url, char='{:04X}'.format(ord(c))): with self.assertRaises(ValueError): urllib.parse.urlsplit(url)
1
Python
CWE-522
Insufficiently Protected Credentials
The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval.
https://cwe.mitre.org/data/definitions/522.html
safe
def new_user(): content = ub.User() languages = calibre_db.speaking_language() translations = [LC('en')] + babel.list_translations() kobo_support = feature_support['kobo'] and config.config_kobo_sync if request.method == "POST": to_save = request.form.to_dict() _handle_new_user(to_save, content, languages, translations, kobo_support) else: content.role = config.config_default_role content.sidebar_view = config.config_default_show content.locale = config.config_default_locale content.default_language = config.config_default_language return render_title_template("user_edit.html", new_user=1, content=content, config=config, translations=translations, languages=languages, title=_(u"Add new user"), page="newuser", kobo_support=kobo_support, registered_oauth=oauth_check)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def parse(source, filename='<unknown>', mode='exec'): """ Parse the source into an AST node. Equivalent to compile(source, filename, mode, PyCF_ONLY_AST). """ return compile(source, filename, mode, PyCF_ONLY_AST)
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 make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( http_client=None, homeserver_to_use=GenericWorkerServer ) 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_certificates_features_against_status(self): """ Test certificates with status 'downloadable' should be in the response. """ url = reverse('get_issued_certificates', kwargs={'course_id': unicode(self.course.id)}) # firstly generating downloadable certificates with 'honor' mode certificate_count = 3 for __ in xrange(certificate_count): self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.generating) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 0) # Certificates with status 'downloadable' should be in response. self.generate_certificate(course_id=self.course.id, mode='honor', status=CertificateStatuses.downloadable) response = self.client.get(url) res_json = json.loads(response.content) self.assertIn('certificates', res_json) self.assertEqual(len(res_json['certificates']), 1)
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_basic_yaml_security(self): with self.assertRaises(yaml.constructor.ConstructorError): parse_yaml_query('!!python/object/apply:os.system ["echo Hello"]')
1
Python
NVD-CWE-noinfo
null
null
null
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-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 children(cls, path): filesystem_path = pathutils.path_to_filesystem(path, FOLDER) _, directories, files = next(os.walk(filesystem_path)) for filename in directories + files: rel_filename = posixpath.join(path, filename) if cls.is_node(rel_filename) or cls.is_leaf(rel_filename): yield cls(rel_filename)
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 open_soap_envelope(text): """ :param text: SOAP message :return: dictionary with two keys "body"/"header" """ try: envelope = ElementTree.fromstring(text) except Exception as exc: raise XmlParseError("%s" % exc) assert envelope.tag == '{%s}Envelope' % soapenv.NAMESPACE assert len(envelope) >= 1 content = {"header": [], "body": None} for part in envelope: if part.tag == '{%s}Body' % soapenv.NAMESPACE: assert len(part) == 1 content["body"] = ElementTree.tostring(part[0], encoding="UTF-8") elif part.tag == "{%s}Header" % soapenv.NAMESPACE: for item in part: _str = ElementTree.tostring(item, encoding="UTF-8") content["header"].append(_str) return content
0
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
vulnerable
def prepare_key(self, key): key = force_bytes(key) invalid_strings = [ b"-----BEGIN PUBLIC KEY-----", b"-----BEGIN CERTIFICATE-----", b"-----BEGIN RSA PUBLIC KEY-----", b"ssh-rsa", ] if any(string_value in key for string_value in invalid_strings): raise InvalidKeyError( "The specified key is an asymmetric key or x509 certificate and" " should not be used as an HMAC secret." ) return key
0
Python
CWE-327
Use of a Broken or Risky Cryptographic Algorithm
The use of a broken or risky cryptographic algorithm is an unnecessary risk that may result in the exposure of sensitive information.
https://cwe.mitre.org/data/definitions/327.html
vulnerable
def _redirect_request_using_get(self, request, redirect_url): redirected = request.replace(url=redirect_url, method='GET', body='') redirected.headers.pop('Content-Type', None) redirected.headers.pop('Content-Length', None) return redirected
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 testSparseCountSparseOutputBadNumberOfValues(self): indices = [[0, 0], [0, 1], [1, 0]] values = [1, 1, 1, 10] weights = [1, 2, 4, 6] dense_shape = [2, 3] with self.assertRaisesRegex( errors.InvalidArgumentError, "Number of values must match first dimension of indices"): self.evaluate( gen_count_ops.SparseCountSparseOutput( indices=indices, values=values, dense_shape=dense_shape, weights=weights, binary_output=False))
1
Python
CWE-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 all(cls, **kwargs): """Return a `Page` of instances of this `Resource` class from its general collection endpoint. Only `Resource` classes with specified `collection_path` endpoints can be requested with this method. Any provided keyword arguments are passed to the API endpoint as query parameters. """ url = recurly.base_uri() + cls.collection_path if kwargs: url = '%s?%s' % (url, urlencode(kwargs)) return Page.page_for_url(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 load_yamlf(fpath, encoding): """ :param unicode fpath: :param unicode encoding: :rtype: dict | list """ with codecs.open(fpath, encoding=encoding) as f: return yaml.load(f)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def testMustPassTensorArgumentToDLPack(self): with self.assertRaisesRegex( errors.InvalidArgumentError, "The argument to `to_dlpack` must be a TF tensor, not Python object"): dlpack.to_dlpack([1])
1
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def _generate_cmd(self, executable, cmd): if executable: ### TODO: Why was "-c" removed from here? (vs jail.py) local_cmd = [self.zlogin_cmd, self.zone, executable, cmd] else: local_cmd = '%s "%s" %s' % (self.zlogin_cmd, self.zone, cmd) return local_cmd
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 get_pos_tagger(self): from nltk.corpus import brown regexp_tagger = RegexpTagger( [ (r"^-?[0-9]+(\.[0-9]+)?$", "CD"), # cardinal numbers (r"(The|the|A|a|An|an)$", "AT"), # articles (r".*able$", "JJ"), # adjectives (r".*ness$", "NN"), # nouns formed from adjectives (r".*ly$", "RB"), # adverbs (r".*s$", "NNS"), # plural nouns (r".*ing$", "VBG"), # gerunds (r".*ed$", "VBD"), # past tense verbs (r".*", "NN"), # nouns (default) ] ) brown_train = brown.tagged_sents(categories="news") unigram_tagger = UnigramTagger(brown_train, backoff=regexp_tagger) bigram_tagger = BigramTagger(brown_train, backoff=unigram_tagger) trigram_tagger = TrigramTagger(brown_train, backoff=bigram_tagger) # Override particular words main_tagger = RegexpTagger( [(r"(A|a|An|an)$", "ex_quant"), (r"(Every|every|All|all)$", "univ_quant")], backoff=trigram_tagger, ) return main_tagger
1
Python
CWE-1333
Inefficient Regular Expression Complexity
The product uses a regular expression with an inefficient, possibly exponential worst-case computational complexity that consumes excessive CPU cycles.
https://cwe.mitre.org/data/definitions/1333.html
safe
def test_posix_home_inaccessible(self): """ what happens when home catalog dir is innaccessible """ tmpdir = tempfile.mkdtemp() try: d_dir = catalog.default_dir_posix(tmpdir) try: os.chmod(d_dir, 0o000) except OSError: raise KnownFailureTest("Can't change permissions of default_dir.") new_ddir = catalog.default_dir_posix(tmpdir) assert_(not os.path.samefile(new_ddir, d_dir)) new_ddir2 = catalog.default_dir_posix(tmpdir) assert_(os.path.samefile(new_ddir, new_ddir2)) finally: os.chmod(d_dir, 0o700) remove_tree(tmpdir)
1
Python
CWE-269
Improper Privilege Management
The software does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.
https://cwe.mitre.org/data/definitions/269.html
safe
def get_multi(self, keys, server_key): """ Gets multiple values from memcache for the given keys. :param keys: keys for values to be retrieved from memcache :param servery_key: key to use in determining which server in the ring is used :returns: list of values """ server_key = md5hash(server_key) keys = [md5hash(key) for key in keys] for (server, fp, sock) in self._get_conns(server_key): try: sock.sendall('get %s\r\n' % ' '.join(keys)) line = fp.readline().strip().split() responses = {} while line[0].upper() != 'END': if line[0].upper() == 'VALUE': size = int(line[3]) value = fp.read(size) if int(line[2]) & PICKLE_FLAG: if self._allow_unpickle: value = pickle.loads(value) else: value = None elif int(line[2]) & JSON_FLAG: value = json.loads(value) responses[line[1]] = value fp.readline() line = fp.readline().strip().split() values = [] for key in keys: if key in responses: values.append(responses[key]) else: values.append(None) self._return_conn(server, fp, sock) return values except Exception, e: self._exception_occurred(server, e)
1
Python
CWE-94
Improper Control of Generation of Code ('Code Injection')
The software constructs all or part of a code segment using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the syntax or behavior of the intended code segment.
https://cwe.mitre.org/data/definitions/94.html
safe
def save_cover_from_url(url, book_path): try: if not cli.allow_localhost: # 127.0.x.x, localhost, [::1], [::ffff:7f00:1] ip = socket.getaddrinfo(urlparse(url).hostname, 0)[0][4][0] if ip.startswith("127.") or ip.startswith('::ffff:7f') or ip == "::1": log.error("Localhost was accessed for cover upload") return False, _("You are not allowed to access localhost for cover uploads") img = requests.get(url, timeout=(10, 200)) # ToDo: Error Handling img.raise_for_status() return save_cover(img, book_path) except (socket.gaierror, requests.exceptions.HTTPError, requests.exceptions.ConnectionError, requests.exceptions.Timeout) as ex: log.info(u'Cover Download Error %s', ex) return False, _("Error Downloading Cover") except MissingDelegateError as ex: log.info(u'File Format Error %s', ex) return False, _("Cover Format Error")
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
async def on_GET(self, origin, content, query, context, event_id): return await self.handler.on_event_auth(origin, context, event_id)
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_vardecl(self): tree = self.parse(vardecl) self.assertEqual(tree.body[0].type_comment, "int") tree = self.classic_parse(vardecl) 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_permissions(self): """ im dir should have permissions 0700 """ if sys.platform != 'win32': im_dir = catalog.intermediate_dir() im_dir_stat = os.stat(im_dir) assert_(stat.S_IMODE(im_dir_stat.st_mode) == 0o0700) r_im_dir_stat = os.stat(os.path.dirname(im_dir)) assert_(stat.S_IMODE(r_im_dir_stat.st_mode) == 0o0700)
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 is_valid_client_secret(client_secret): """Validate that a given string matches the client_secret regex defined by the spec :param client_secret: The client_secret to validate :type client_secret: str :return: Whether the client_secret is valid :rtype: bool """ return client_secret_regex.match(client_secret) is not None
1
Python
CWE-20
Improper Input Validation
The product receives input or data, but it does not validate or incorrectly validates that the input has the properties that are required to process the data safely and correctly.
https://cwe.mitre.org/data/definitions/20.html
safe
def test_parse_header_11_expect_continue(self): data = b"GET /foobar HTTP/1.1\nexpect: 100-continue" self.parser.parse_header(data) self.assertEqual(self.parser.expect_continue, True)
0
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
vulnerable
def bootstrap_join(context): """ Join cluster process """ global _context _context = context init() _context.init_sbd_manager() _context.validate_option() check_tty() corosync_active = utils.service_is_active("corosync.service") if corosync_active: error("Abort: Cluster is currently active. Run this command on a node joining the cluster.") if not check_prereqs("join"): return cluster_node = _context.cluster_node if _context.stage != "": globals()["join_" + _context.stage](cluster_node) else: if not _context.yes_to_all and cluster_node is None: status("""Join This Node to Cluster: You will be asked for the IP address of an existing node, from which configuration will be copied. If you have not already configured passwordless ssh between nodes, you will be prompted for the root password of the existing node. """) cluster_node = prompt_for_string("IP address or hostname of existing node (e.g.: 192.168.1.1)", ".+") _context.cluster_node = cluster_node utils.ping_node(cluster_node) join_ssh(cluster_node) if not utils.service_is_active("pacemaker.service", cluster_node): error("Cluster is inactive on {}".format(cluster_node)) lock_inst = lock.RemoteLock(cluster_node) try: with lock_inst.lock(): setup_passwordless_with_other_nodes(cluster_node) join_remote_auth(cluster_node) join_csync2(cluster_node) join_ssh_merge(cluster_node) join_cluster(cluster_node) except (lock.SSHError, lock.ClaimLockError) as err: error(err) status("Done (log saved to %s)" % (LOG_FILE))
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def get_cms_details(url): # this function will fetch cms details using cms_detector response = {} cms_detector_command = 'python3 /usr/src/github/CMSeeK/cmseek.py -u {} --random-agent --batch --follow-redirect'.format(url) os.system(cms_detector_command) response['status'] = False response['message'] = 'Could not detect CMS!' parsed_url = urlparse(url) domain_name = parsed_url.hostname port = parsed_url.port find_dir = domain_name if port: find_dir += '_{}'.format(port) print(url) print(find_dir) # subdomain may also have port number, and is stored in dir as _port cms_dir_path = '/usr/src/github/CMSeeK/Result/{}'.format(find_dir) cms_json_path = cms_dir_path + '/cms.json' if os.path.isfile(cms_json_path): cms_file_content = json.loads(open(cms_json_path, 'r').read()) if not cms_file_content.get('cms_id'): return response response = {} response = cms_file_content response['status'] = True # remove cms dir path try: shutil.rmtree(cms_dir_path) except Exception as e: print(e) return response
0
Python
CWE-78
Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
The software constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/78.html
vulnerable
def test_get_header_lines_folded(self): # From RFC2616: # HTTP/1.1 header field values can be folded onto multiple lines if the # continuation line begins with a space or horizontal tab. All linear # white space, including folding, has the same semantics as SP. A # recipient MAY replace any linear white space with a single SP before # interpreting the field value or forwarding the message downstream. # We are just preserving the whitespace that indicates folding. result = self._callFUT(b"slim\r\n slam") self.assertEqual(result, [b"slim slam"])
1
Python
CWE-444
Inconsistent Interpretation of HTTP Requests ('HTTP Request/Response Smuggling')
The product acts as an intermediary HTTP agent (such as a proxy or firewall) in the data flow between two entities such as a client and server, but it does not interpret malformed HTTP requests or responses in ways that are consistent with how the messages will be processed by those entities that are at the ultimate destination.
https://cwe.mitre.org/data/definitions/444.html
safe
def feed_category(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.tags.any(db.Tags.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_invalid_sum(self): pos = dict(lineno=2, col_offset=3) m = ast.Module([ast.Expr(ast.expr(**pos), **pos)]) with self.assertRaises(TypeError) as cm: compile(m, "<test>", "exec") self.assertIn("but got <_ast.expr", 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 testInvalidInstanceKey(self, collective_op, device, communication): dev0 = '/device:%s:0' % device group_size = 2 group_key = 100 instance_key = [100] in_tensor = constant_op.constant([1.]) with self.assertRaises(errors.InvalidArgumentError): with ops.device(dev0): collective_op( in_tensor, group_size, group_key, instance_key, communication_hint=communication)
1
Python
CWE-416
Use After Free
Referencing memory after it has been freed can cause a program to crash, use unexpected values, or execute code.
https://cwe.mitre.org/data/definitions/416.html
safe
def MD5(self,data:str): sha = hashlib.md5(bytes(data.encode())) hash = str(sha.digest()) return self.__Salt(hash,salt=self.salt)
0
Python
CWE-328
Use of Weak Hash
The product uses an algorithm that produces a digest (output value) that does not meet security expectations for a hash function that allows an adversary to reasonably determine the original input (preimage attack), find another input that can produce the same hash (2nd preimage attack), or find multiple inputs that evaluate to the same hash (birthday attack).
https://cwe.mitre.org/data/definitions/328.html
vulnerable
def make_homeserver(self, reactor, clock): hs = self.setup_test_homeserver( "red", http_client=None, federation_client=Mock(), ) self.event_source = hs.get_event_sources().sources["typing"] hs.get_federation_handler = Mock() async def get_user_by_access_token(token=None, allow_guest=False): return { "user": UserID.from_string(self.auth_user_id), "token_id": 1, "is_guest": False, } hs.get_auth().get_user_by_access_token = get_user_by_access_token async def _insert_client_ip(*args, **kwargs): return None hs.get_datastore().insert_client_ip = _insert_client_ip def get_room_members(room_id): if room_id == self.room_id: return defer.succeed([self.user]) else: return defer.succeed([]) @defer.inlineCallbacks def fetch_room_distributions_into( room_id, localusers=None, remotedomains=None, ignore_user=None ): members = yield get_room_members(room_id) for member in members: if ignore_user is not None and member == ignore_user: continue if hs.is_mine(member): if localusers is not None: localusers.add(member) else: if remotedomains is not None: remotedomains.add(member.domain) hs.get_room_member_handler().fetch_room_distributions_into = ( fetch_room_distributions_into ) 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 remove_logical_volumes(*paths): """Remove one or more logical volume.""" for path in paths: clear_logical_volume(path) if paths: lvremove = ('lvremove', '-f') + paths execute(*lvremove, attempts=3, run_as_root=True)
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 recursive_fn(n): return cond_v2.cond_v2(n > 0, recursive_fn(n - 1), 1)
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 test_login_unknown_code(self): response = self.client.post('/accounts-rest/login/code/', { 'code': 'unknown', }) self.assertEqual(response.status_code, 400) self.assertEqual(response.json(), { 'code': ['Login code is invalid. It might have expired.'], })
0
Python
CWE-312
Cleartext Storage of Sensitive Information
The application stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
https://cwe.mitre.org/data/definitions/312.html
vulnerable
def allow_all(tag: str, name: str, value: str) -> bool: return True
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 _cnonce(): dig = _md5( "%s:%s" % (time.ctime(), ["0123456789"[random.randrange(0, 9)] for i in range(20)]) ).hexdigest() return dig[:16]
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 auth_username_ci(self): return self.appbuilder.get_app.config.get("AUTH_USERNAME_CI", True)
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 test_refresh_token(self): token = self.xsrf_token # A user's token is stable over time. Refreshing the page in one tab # might update the cookie while an older tab still has the old cookie # in its DOM. Simulate this scenario by passing a constant token # in the body and re-querying for the token. for i in range(5): token = self.get_token(token) # Implementation detail: the same token is returned each time self.assertEqual(token, self.xsrf_token) response = self.fetch( "/", method="POST", body=urllib_parse.urlencode(dict(_xsrf=self.xsrf_token)), headers=self.cookie_headers(token)) self.assertEqual(response.code, 200)
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 test_open_soap_envelope_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> <lolz>&lol1;</lolz> """ with raises(soap.XmlParseError): soap.open_soap_envelope(xml)
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 testBadFilterShape(self): strides = [1, 1, 1, 1, 1] padding = "VALID" tin = constant_op.constant( .5053710941, shape=[2, 2, 2, 2, 1], dtype=dtypes.float32) filter_sizes = constant_op.constant(0, shape=[], dtype=dtypes.int32) out_backprop = constant_op.constant( .5053710941, shape=[2, 2, 2, 2, 1], dtype=dtypes.float32) with self.assertRaisesRegex((ValueError, errors.InvalidArgumentError), "must be rank 1"): nn_ops.conv3d_backprop_filter_v2( input=tin, filter_sizes=filter_sizes, out_backprop=out_backprop, strides=strides, padding=padding)
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 run_tests(self): # pytest may be not installed yet import pytest args = ['--forked', '--fulltrace', '--no-cov', 'tests/'] if self.test_suite: args += ['-k', self.test_suite] sys.stderr.write('setup.py:test run pytest {}\n'.format(' '.join(args))) errno = pytest.main(args) sys.exit(errno)
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 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-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
def test_captcha_validate_value(self): captcha = FlaskSessionCaptcha(self.app) _default_routes(captcha, self.app) with self.app.test_request_context('/'): captcha.generate() answer = captcha.get_answer() assert not captcha.validate(value="wrong") captcha.generate() answer = captcha.get_answer() assert captcha.validate(value=answer)
0
Python
CWE-754
Improper Check for Unusual or Exceptional Conditions
The software does not check or incorrectly checks for unusual or exceptional conditions that are not expected to occur frequently during day to day operation of the software.
https://cwe.mitre.org/data/definitions/754.html
vulnerable
def test_format_arbitrary_settings(self): self.assertEqual(get_format('DEBUG'), 'DEBUG')
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 testRaggedCountSparseOutputBadSplitsEnd(self): splits = [0, 5] values = [1, 1, 2, 1, 2, 10, 5] weights = [1, 2, 3, 4, 5, 6, 7] with self.assertRaisesRegex(errors.InvalidArgumentError, "Splits must end with the number of values"): self.evaluate( gen_count_ops.RaggedCountSparseOutput( splits=splits, values=values, weights=weights, binary_output=False))
1
Python
CWE-617
Reachable Assertion
The product contains an assert() or similar statement that can be triggered by an attacker, which leads to an application exit or other behavior that is more severe than necessary.
https://cwe.mitre.org/data/definitions/617.html
safe
def feed_unread_books(): off = request.args.get("offset") or 0 result, pagination = render_read_books(int(off) / (int(config.config_books_per_page)) + 1, False, True) return render_xml_template('feed.xml', entries=result, pagination=pagination)
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def accounts_home_from_multiuse_invite(request: HttpRequest, confirmation_key: str) -> HttpResponse: multiuse_object = None try: multiuse_object = get_object_from_key(confirmation_key, [Confirmation.MULTIUSE_INVITE]) # Required for OAuth 2 except ConfirmationKeyException as exception: realm = get_realm_from_request(request) if realm is None or realm.invite_required: return render_confirmation_key_error(request, exception) return accounts_home( request, multiuse_object_key=confirmation_key, multiuse_object=multiuse_object )
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_open_with_filename(self): with NamedTemporaryFile() as tmp: fp = memmap(tmp.name, dtype=self.dtype, mode='w+', shape=self.shape) fp[:] = self.data[:] 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 home_get_dat(): d = db.sentences_stats('get_data') n = db.sentences_stats('all_networks') rows = db.sentences_stats('get_clicks') c = rows[0][0] rows = db.sentences_stats('get_sessions') s = rows[0][0] vId = ('online', ) rows = db.sentences_stats('get_online', vId) o = rows[0][0] return json.dumps({'status' : 'OK', 'd' : d, 'n' : n, 'c' : c, 's' : s, 'o' : o});
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 __init__(self, sourceName: str): self.sourceName = sourceName self.type = "file" self.content = None
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 generate_ip_set( ip_addresses: Optional[Iterable[str]], extra_addresses: Optional[Iterable[str]] = None, config_path: Optional[Iterable[str]] = None,
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 testSwitchEagerMode(self): if not context.executing_eagerly(): return input_data = [1, 2, 3, 4] vf, vt = control_flow_ops.switch(input_data, False) self.assertAllEqual(vf, input_data) self.assertAllEqual(vt, [])
1
Python
CWE-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_with_admins(self) -> None: no_admins = InstanceConfig(admins=None) with_admins = InstanceConfig(admins=[UUID(int=0)]) with_admins_2 = InstanceConfig(admins=[UUID(int=1)]) no_admins.update(with_admins) self.assertEqual(no_admins.admins, None) with_admins.update(with_admins_2) self.assertEqual(with_admins.admins, with_admins_2.admins)
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 test_device_list_view_for_own_user_returns_200(self, verified_user, rf): with override_settings(WAGTAIL_2FA_REQUIRED=True): request = rf.get('foo') request.user = verified_user response = DeviceListView.as_view()(request, user_id=verified_user.id) assert response.status_code == 200
1
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
safe
def test_parse_soap_enveloped_saml_thingy_xxe(): xml = """<?xml version="1.0"?> <!DOCTYPE lolz [ <!ENTITY lol "lol"> <!ELEMENT lolz (#PCDATA)> <!ENTITY lol1 "&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;&lol;"> ]> <lolz>&lol1;</lolz> """ with raises(EntitiesForbidden): soap.parse_soap_enveloped_saml_thingy(xml, None)
1
Python
CWE-611
Improper Restriction of XML External Entity Reference
The software processes an XML document that can contain XML entities with URIs that resolve to documents outside of the intended sphere of control, causing the product to embed incorrect documents into its output.
https://cwe.mitre.org/data/definitions/611.html
safe
def get_proxied_http_client(self) -> SimpleHttpClient: """ An HTTP client that uses configured HTTP(S) proxies. """ return SimpleHttpClient( self, http_proxy=os.getenvb(b"http_proxy"), https_proxy=os.getenvb(b"HTTPS_PROXY"), )
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 edit_book_comments(comments, book): modif_date = False if comments: comments = clean_html(comments) if len(book.comments): if book.comments[0].text != comments: book.comments[0].text = comments modif_date = True else: if comments: book.comments.append(db.Comments(text=comments, book=book.id)) modif_date = True return modif_date
0
Python
CWE-918
Server-Side Request Forgery (SSRF)
The web server receives a URL or similar request from an upstream component and retrieves the contents of this URL, but it does not sufficiently ensure that the request is being sent to the expected destination.
https://cwe.mitre.org/data/definitions/918.html
vulnerable
def __init__(self, pool_connections=DEFAULT_POOLSIZE, pool_maxsize=DEFAULT_POOLSIZE, max_retries=DEFAULT_RETRIES, pool_block=DEFAULT_POOLBLOCK, verify=True, cert_paths=None):
1
Python
CWE-295
Improper Certificate Validation
The software does not validate, or incorrectly validates, a certificate.
https://cwe.mitre.org/data/definitions/295.html
safe