code
stringlengths
14
2.05k
label
int64
0
1
programming_language
stringclasses
7 values
cwe_id
stringlengths
6
14
cwe_name
stringlengths
5
98
description
stringlengths
36
379
url
stringlengths
36
48
label_name
stringclasses
2 values
async def test_fetch_auth_providers_home_assistant_person_not_loaded( hass: HomeAssistant, aiohttp_client: ClientSessionGenerator, ip: str, ) -> None: """Test fetching auth providers for homeassistant auth provider, where person integration is not loaded.""" await _test_fetch_auth_providers_home_assistant( hass, aiohttp_client, ip, lambda _: {} )
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
async def test_list_persons( hass: HomeAssistant, hass_client_no_auth: ClientSessionGenerator, hass_admin_user: MockUser, ip: str, status_code: HTTPStatus, expected_fn: Callable[[dict[str, Any]], dict[str, Any]], ) -> None: """Test listing persons from a not local ip address.""" user_id = hass_admin_user.id admin = {"id": "1234", "name": "Admin", "user_id": user_id, "picture": "/bla"} config = { DOMAIN: [ admin, {"id": "5678", "name": "Only a person"}, ] } assert await async_setup_component(hass, DOMAIN, config) await async_setup_component(hass, "api", {}) mock_real_ip(hass.http.app)(ip) client = await hass_client_no_auth() resp = await client.get("/api/person/list") assert resp.status == status_code result = await resp.json() assert result == expected_fn(admin)
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def is_in_or_equal(path_1: str | Path, path_2: str | Path): """ True if path_1 is a descendant (i.e. located within) path_2 or if the paths are the same, returns False otherwise. Parameters: path_1: str or Path (should be a file) path_2: str or Path (can be a file or directory) """ path_1, path_2 = abspath(path_1), abspath(path_2) try: if str(path_1.relative_to(path_2)).startswith(".."): # prevent path traversal return False except ValueError: return False return True
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product 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 product 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_complete_admin_task(client, admin_factory, admin_task_factory): admin = admin_factory() client.force_login(admin) task1 = admin_task_factory(assigned_to=admin) task2 = admin_task_factory(assigned_to=admin) url = reverse("admin_tasks:mine") response = client.get(url) assert task1.name in response.content.decode() # Checked button is not visible because tasks are still open assert "btn-success" not in response.content.decode() url = reverse("admin_tasks:detail", args=[task1.id]) response = client.get(url) complete_url = reverse("admin_tasks:completed", args=[task1.id]) assert "Complete" in response.content.decode() assert complete_url in response.content.decode() response = client.get(complete_url, follow=True) task1.refresh_from_db() task2.refresh_from_db() assert "Complete" not in response.content.decode() assert "completed" in response.content.decode() assert "disabled" in response.content.decode() # Cannot add new comment assert "div_id_content" not in response.content.decode() # Complete url is still there to make it open again assert complete_url in response.content.decode() assert task1.completed assert not task2.completed url = reverse("admin_tasks:mine") response = client.get(url) # Check button is now visible assert "btn-success" in response.content.decode()
0
Python
CWE-352
Cross-Site Request Forgery (CSRF)
The web application does not, or can not, sufficiently verify whether a well-formed, valid, consistent request was intentionally provided by the user who submitted the request.
https://cwe.mitre.org/data/definitions/352.html
vulnerable
def get(self, request, *args, **kwargs): task_id = self.kwargs.get("pk", -1) admin_task = get_object_or_404(AdminTask, id=task_id) admin_task.completed = not admin_task.completed admin_task.save() return super().get(request, *args, **kwargs)
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 __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): template = jinja2.Template(value, keep_trailing_newline=True) value = _to_native(template.render(self.__dict__)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def __render_string(self, value): orig = last = value max_recursion = self.__dict__.get('jinja_max_recursion', 5) for _ in range(max_recursion): value = _to_native(self.sandbox.from_string(value).render(self.__dict__, func=lambda:None)) if value == last: return value last = value raise ValueError("too deep jinja re-evaluation on '{}'".format(orig))
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def __init__(self, *args, alias_spec=None, **kwargs): ''' Use the object dict. Optional parameter 'alias_spec' is dictionary of form: {'aliased_to': ['alias_one', 'alias_two', ...], ...} When specified, and one of the aliases is accessed - the 'aliased_to' config option is returned. ''' self.__dict__.update(*args, **kwargs) self.sandbox = sandbox.SandboxedEnvironment(keep_trailing_newline=True) self._aliases = {} if alias_spec: for aliased_to, aliases in alias_spec.items(): for alias in aliases: self._aliases[alias] = aliased_to
0
Python
NVD-CWE-noinfo
null
null
null
vulnerable
def untar_file(tar_path, dst_path): with tarfile.open(tar_path , mode='r') as tfile: tfile.extractall(path=dst_path)
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product 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 product 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
async def prips(ctx, *, argument): Output = subprocess.Popen(f"prips {argument}", stdout=subprocess.PIPE, stderr=subprocess.STDOUT, shell=True) Output = Output.communicate()[0].decode('UTF-8') if len(Output) > 2000: RandomStr = utilities.generate_random_string() with open(f'messages/{RandomStr}' , 'w') as Message: Message.write(Output) Message.close() await ctx.send("Prips Results: ", file=discord.File(f"messages/{RandomStr}")) await ctx.send(f"\n**- {ctx.message.author}**") else: await ctx.send("**Prips Results:**") await ctx.send(f"```{Output}```") await ctx.send(f"\n**- {ctx.message.author}**")
0
Python
CWE-77
Improper Neutralization of Special Elements used in a Command ('Command Injection')
The product constructs all or part of a command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended command when it is sent to a downstream component.
https://cwe.mitre.org/data/definitions/77.html
vulnerable
def element(): element_url = src_url = request.args.get('url') if element_url.startswith('gAAAAA'): try: cipher_suite = Fernet(g.session_key) src_url = cipher_suite.decrypt(element_url.encode()).decode() except (InvalidSignature, InvalidToken) as e: return render_template( 'error.html', error_message=str(e)), 401 src_type = request.args.get('type') try: file_data = g.user_request.send(base_url=src_url).content tmp_mem = io.BytesIO() tmp_mem.write(file_data) tmp_mem.seek(0) return send_file(tmp_mem, mimetype=src_type) except exceptions.RequestException: pass empty_gif = base64.b64decode( 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==') return send_file(io.BytesIO(empty_gif), mimetype='image/gif')
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 element(): element_url = src_url = request.args.get('url') if element_url.startswith('gAAAAA'): try: cipher_suite = Fernet(g.session_key) src_url = cipher_suite.decrypt(element_url.encode()).decode() except (InvalidSignature, InvalidToken) as e: return render_template( 'error.html', error_message=str(e)), 401 src_type = request.args.get('type') try: file_data = g.user_request.send(base_url=src_url).content tmp_mem = io.BytesIO() tmp_mem.write(file_data) tmp_mem.seek(0) return send_file(tmp_mem, mimetype=src_type) except exceptions.RequestException: pass empty_gif = base64.b64decode( 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==') return send_file(io.BytesIO(empty_gif), mimetype='image/gif')
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product 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 product 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 element(): element_url = src_url = request.args.get('url') if element_url.startswith('gAAAAA'): try: cipher_suite = Fernet(g.session_key) src_url = cipher_suite.decrypt(element_url.encode()).decode() except (InvalidSignature, InvalidToken) as e: return render_template( 'error.html', error_message=str(e)), 401 src_type = request.args.get('type') try: file_data = g.user_request.send(base_url=src_url).content tmp_mem = io.BytesIO() tmp_mem.write(file_data) tmp_mem.seek(0) return send_file(tmp_mem, mimetype=src_type) except exceptions.RequestException: pass empty_gif = base64.b64decode( 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==') return send_file(io.BytesIO(empty_gif), mimetype='image/gif')
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 element(): element_url = src_url = request.args.get('url') if element_url.startswith('gAAAAA'): try: cipher_suite = Fernet(g.session_key) src_url = cipher_suite.decrypt(element_url.encode()).decode() except (InvalidSignature, InvalidToken) as e: return render_template( 'error.html', error_message=str(e)), 401 src_type = request.args.get('type') try: file_data = g.user_request.send(base_url=src_url).content tmp_mem = io.BytesIO() tmp_mem.write(file_data) tmp_mem.seek(0) return send_file(tmp_mem, mimetype=src_type) except exceptions.RequestException: pass empty_gif = base64.b64decode( 'R0lGODlhAQABAIAAAP///////yH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==') return send_file(io.BytesIO(empty_gif), mimetype='image/gif')
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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 config(): config_disabled = ( app.config['CONFIG_DISABLE'] or not valid_user_session(session)) if request.method == 'GET': return json.dumps(g.user_config.__dict__) elif request.method == 'PUT' and not config_disabled: if 'name' in request.args: config_pkl = os.path.join( app.config['CONFIG_PATH'], request.args.get('name')) session['config'] = (pickle.load(open(config_pkl, 'rb')) if os.path.exists(config_pkl) else session['config']) return json.dumps(session['config']) else: return json.dumps({}) elif not config_disabled: config_data = request.form.to_dict() if 'url' not in config_data or not config_data['url']: config_data['url'] = g.user_config.url # Save config by name to allow a user to easily load later if 'name' in request.args: pickle.dump( config_data, open(os.path.join( app.config['CONFIG_PATH'], request.args.get('name')), 'wb')) session['config'] = config_data return redirect(config_data['url']) else: return redirect(url_for('.index'), code=403)
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 config(): config_disabled = ( app.config['CONFIG_DISABLE'] or not valid_user_session(session)) if request.method == 'GET': return json.dumps(g.user_config.__dict__) elif request.method == 'PUT' and not config_disabled: if 'name' in request.args: config_pkl = os.path.join( app.config['CONFIG_PATH'], request.args.get('name')) session['config'] = (pickle.load(open(config_pkl, 'rb')) if os.path.exists(config_pkl) else session['config']) return json.dumps(session['config']) else: return json.dumps({}) elif not config_disabled: config_data = request.form.to_dict() if 'url' not in config_data or not config_data['url']: config_data['url'] = g.user_config.url # Save config by name to allow a user to easily load later if 'name' in request.args: pickle.dump( config_data, open(os.path.join( app.config['CONFIG_PATH'], request.args.get('name')), 'wb')) session['config'] = config_data return redirect(config_data['url']) else: return redirect(url_for('.index'), code=403)
0
Python
CWE-22
Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
The product 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 product 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 config(): config_disabled = ( app.config['CONFIG_DISABLE'] or not valid_user_session(session)) if request.method == 'GET': return json.dumps(g.user_config.__dict__) elif request.method == 'PUT' and not config_disabled: if 'name' in request.args: config_pkl = os.path.join( app.config['CONFIG_PATH'], request.args.get('name')) session['config'] = (pickle.load(open(config_pkl, 'rb')) if os.path.exists(config_pkl) else session['config']) return json.dumps(session['config']) else: return json.dumps({}) elif not config_disabled: config_data = request.form.to_dict() if 'url' not in config_data or not config_data['url']: config_data['url'] = g.user_config.url # Save config by name to allow a user to easily load later if 'name' in request.args: pickle.dump( config_data, open(os.path.join( app.config['CONFIG_PATH'], request.args.get('name')), 'wb')) session['config'] = config_data return redirect(config_data['url']) else: return redirect(url_for('.index'), code=403)
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 config(): config_disabled = ( app.config['CONFIG_DISABLE'] or not valid_user_session(session)) if request.method == 'GET': return json.dumps(g.user_config.__dict__) elif request.method == 'PUT' and not config_disabled: if 'name' in request.args: config_pkl = os.path.join( app.config['CONFIG_PATH'], request.args.get('name')) session['config'] = (pickle.load(open(config_pkl, 'rb')) if os.path.exists(config_pkl) else session['config']) return json.dumps(session['config']) else: return json.dumps({}) elif not config_disabled: config_data = request.form.to_dict() if 'url' not in config_data or not config_data['url']: config_data['url'] = g.user_config.url # Save config by name to allow a user to easily load later if 'name' in request.args: pickle.dump( config_data, open(os.path.join( app.config['CONFIG_PATH'], request.args.get('name')), 'wb')) session['config'] = config_data return redirect(config_data['url']) else: return redirect(url_for('.index'), code=403)
0
Python
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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 initialize(self, *args, **kwargs): super().initialize(*args, **kwargs)
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def initialize(self, *args, **kwargs): super().initialize(*args, **kwargs)
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def initialize(self, *args, **kwargs): super().initialize(*args, **kwargs)
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
def normalized_uri(root_dir): """Attempt to make an LSP rootUri from a ContentsManager root_dir Special care must be taken around windows paths: the canonical form of windows drives and UNC paths is lower case """ root_uri = pathlib.Path(root_dir).expanduser().resolve().as_uri() root_uri = re.sub( RE_PATH_ANCHOR, lambda m: "file://{}".format(m.group(1).lower()), root_uri ) return root_uri
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def normalized_uri(root_dir): """Attempt to make an LSP rootUri from a ContentsManager root_dir Special care must be taken around windows paths: the canonical form of windows drives and UNC paths is lower case """ root_uri = pathlib.Path(root_dir).expanduser().resolve().as_uri() root_uri = re.sub( RE_PATH_ANCHOR, lambda m: "file://{}".format(m.group(1).lower()), root_uri ) return root_uri
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def normalized_uri(root_dir): """Attempt to make an LSP rootUri from a ContentsManager root_dir Special care must be taken around windows paths: the canonical form of windows drives and UNC paths is lower case """ root_uri = pathlib.Path(root_dir).expanduser().resolve().as_uri() root_uri = re.sub( RE_PATH_ANCHOR, lambda m: "file://{}".format(m.group(1).lower()), root_uri ) return root_uri
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
def load_jupyter_server_extension(nbapp): """create a LanguageServerManager and add handlers""" nbapp.add_traits(language_server_manager=traitlets.Instance(LanguageServerManager)) manager = nbapp.language_server_manager = LanguageServerManager(parent=nbapp) contents = nbapp.contents_manager page_config = nbapp.web_app.settings.setdefault("page_config_data", {}) root_uri = "" virtual_documents_uri = "" # try to set the rootUri from the contents manager path if hasattr(contents, "root_dir"): root_uri = normalized_uri(contents.root_dir) nbapp.log.debug("[lsp] rootUri will be %s", root_uri) virtual_documents_uri = normalized_uri( Path(contents.root_dir) / manager.virtual_documents_dir ) nbapp.log.debug("[lsp] virtualDocumentsUri will be %s", virtual_documents_uri) else: # pragma: no cover nbapp.log.warn( "[lsp] %s did not appear to have a root_dir, could not set rootUri", contents, ) page_config.update(rootUri=root_uri, virtualDocumentsUri=virtual_documents_uri) add_handlers(nbapp) nbapp.io_loop.call_later(0, initialize, nbapp, virtual_documents_uri)
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def load_jupyter_server_extension(nbapp): """create a LanguageServerManager and add handlers""" nbapp.add_traits(language_server_manager=traitlets.Instance(LanguageServerManager)) manager = nbapp.language_server_manager = LanguageServerManager(parent=nbapp) contents = nbapp.contents_manager page_config = nbapp.web_app.settings.setdefault("page_config_data", {}) root_uri = "" virtual_documents_uri = "" # try to set the rootUri from the contents manager path if hasattr(contents, "root_dir"): root_uri = normalized_uri(contents.root_dir) nbapp.log.debug("[lsp] rootUri will be %s", root_uri) virtual_documents_uri = normalized_uri( Path(contents.root_dir) / manager.virtual_documents_dir ) nbapp.log.debug("[lsp] virtualDocumentsUri will be %s", virtual_documents_uri) else: # pragma: no cover nbapp.log.warn( "[lsp] %s did not appear to have a root_dir, could not set rootUri", contents, ) page_config.update(rootUri=root_uri, virtualDocumentsUri=virtual_documents_uri) add_handlers(nbapp) nbapp.io_loop.call_later(0, initialize, nbapp, virtual_documents_uri)
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def load_jupyter_server_extension(nbapp): """create a LanguageServerManager and add handlers""" nbapp.add_traits(language_server_manager=traitlets.Instance(LanguageServerManager)) manager = nbapp.language_server_manager = LanguageServerManager(parent=nbapp) contents = nbapp.contents_manager page_config = nbapp.web_app.settings.setdefault("page_config_data", {}) root_uri = "" virtual_documents_uri = "" # try to set the rootUri from the contents manager path if hasattr(contents, "root_dir"): root_uri = normalized_uri(contents.root_dir) nbapp.log.debug("[lsp] rootUri will be %s", root_uri) virtual_documents_uri = normalized_uri( Path(contents.root_dir) / manager.virtual_documents_dir ) nbapp.log.debug("[lsp] virtualDocumentsUri will be %s", virtual_documents_uri) else: # pragma: no cover nbapp.log.warn( "[lsp] %s did not appear to have a root_dir, could not set rootUri", contents, ) page_config.update(rootUri=root_uri, virtualDocumentsUri=virtual_documents_uri) add_handlers(nbapp) nbapp.io_loop.call_later(0, initialize, nbapp, virtual_documents_uri)
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
def __init__(self): pass
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def __init__(self): pass
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def __init__(self): pass
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
async def test_io_failure(forbidden_shadow_path, manager, caplog): file_uri = (forbidden_shadow_path / "test.py").as_uri() shadow = setup_shadow_filesystem(forbidden_shadow_path.as_uri()) def send_change(): message = did_open(file_uri, "content") return shadow("client", message, "python-lsp-server", manager) with caplog.at_level(logging.WARNING): assert await send_change() is None assert await send_change() is None # no message should be emitted during the first two attempts assert caplog.text == "" # a wargning should be emitted on third failure with caplog.at_level(logging.WARNING): assert await send_change() is None assert "initialization of shadow filesystem failed three times" in caplog.text assert "PermissionError" in caplog.text caplog.clear() # no message should be emitted in subsequent attempts with caplog.at_level(logging.WARNING): assert await send_change() is None assert caplog.text == ""
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
async def test_io_failure(forbidden_shadow_path, manager, caplog): file_uri = (forbidden_shadow_path / "test.py").as_uri() shadow = setup_shadow_filesystem(forbidden_shadow_path.as_uri()) def send_change(): message = did_open(file_uri, "content") return shadow("client", message, "python-lsp-server", manager) with caplog.at_level(logging.WARNING): assert await send_change() is None assert await send_change() is None # no message should be emitted during the first two attempts assert caplog.text == "" # a wargning should be emitted on third failure with caplog.at_level(logging.WARNING): assert await send_change() is None assert "initialization of shadow filesystem failed three times" in caplog.text assert "PermissionError" in caplog.text caplog.clear() # no message should be emitted in subsequent attempts with caplog.at_level(logging.WARNING): assert await send_change() is None assert caplog.text == ""
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
async def test_io_failure(forbidden_shadow_path, manager, caplog): file_uri = (forbidden_shadow_path / "test.py").as_uri() shadow = setup_shadow_filesystem(forbidden_shadow_path.as_uri()) def send_change(): message = did_open(file_uri, "content") return shadow("client", message, "python-lsp-server", manager) with caplog.at_level(logging.WARNING): assert await send_change() is None assert await send_change() is None # no message should be emitted during the first two attempts assert caplog.text == "" # a wargning should be emitted on third failure with caplog.at_level(logging.WARNING): assert await send_change() is None assert "initialization of shadow filesystem failed three times" in caplog.text assert "PermissionError" in caplog.text caplog.clear() # no message should be emitted in subsequent attempts with caplog.at_level(logging.WARNING): assert await send_change() is None assert caplog.text == ""
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
def change_version(self, new_version: str, dry: bool): changelog = CHANGELOG.read_text(encoding="utf-8") if new_version not in changelog: raise Exception( ( f"{new_version} is absent in CHANGELOG.md file." f" Please update the changelog first." ).format(new_version=new_version) ) for location in self.locations: replace_version( path=location.path, template=location.template, old=self.current_version, new=new_version, dry=dry, )
0
Python
CWE-23
Relative Path Traversal
The product uses external input to construct a pathname that should be within a restricted directory, but it does not properly neutralize sequences such as ".." that can resolve to a location that is outside of that directory.
https://cwe.mitre.org/data/definitions/23.html
vulnerable
def change_version(self, new_version: str, dry: bool): changelog = CHANGELOG.read_text(encoding="utf-8") if new_version not in changelog: raise Exception( ( f"{new_version} is absent in CHANGELOG.md file." f" Please update the changelog first." ).format(new_version=new_version) ) for location in self.locations: replace_version( path=location.path, template=location.template, old=self.current_version, new=new_version, dry=dry, )
0
Python
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
vulnerable
def change_version(self, new_version: str, dry: bool): changelog = CHANGELOG.read_text(encoding="utf-8") if new_version not in changelog: raise Exception( ( f"{new_version} is absent in CHANGELOG.md file." f" Please update the changelog first." ).format(new_version=new_version) ) for location in self.locations: replace_version( path=location.path, template=location.template, old=self.current_version, new=new_version, dry=dry, )
0
Python
CWE-306
Missing Authentication for Critical Function
The product does not perform any authentication for functionality that requires a provable user identity or consumes a significant amount of resources.
https://cwe.mitre.org/data/definitions/306.html
vulnerable
func DefaultGetRequestSkipper(c echo.Context) bool { return c.Request().Method == http.MethodGet }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func DefaultGetRequestSkipper(c echo.Context) bool { return c.Request().Method == http.MethodGet }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func DefaultGetRequestSkipper(c echo.Context) bool { return c.Request().Method == http.MethodGet }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func DefaultGetRequestSkipper(c echo.Context) bool { return c.Request().Method == http.MethodGet }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func TestIsVersionGreaterOrEqualThan(t *testing.T) { tests := []struct { version string target string want bool }{ { version: "0.9.1", target: "0.9.1", want: true, }, { version: "0.10.0", target: "0.9.1", want: true, }, { version: "0.9.0", target: "0.9.1", want: false, }, } for _, test := range tests { result := IsVersionGreaterOrEqualThan(test.version, test.target) if result != test.want { t.Errorf("got result %v, want %v.", result, test.want) } } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func TestIsVersionGreaterOrEqualThan(t *testing.T) { tests := []struct { version string target string want bool }{ { version: "0.9.1", target: "0.9.1", want: true, }, { version: "0.10.0", target: "0.9.1", want: true, }, { version: "0.9.0", target: "0.9.1", want: false, }, } for _, test := range tests { result := IsVersionGreaterOrEqualThan(test.version, test.target) if result != test.want { t.Errorf("got result %v, want %v.", result, test.want) } } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func TestIsVersionGreaterOrEqualThan(t *testing.T) { tests := []struct { version string target string want bool }{ { version: "0.9.1", target: "0.9.1", want: true, }, { version: "0.10.0", target: "0.9.1", want: true, }, { version: "0.9.0", target: "0.9.1", want: false, }, } for _, test := range tests { result := IsVersionGreaterOrEqualThan(test.version, test.target) if result != test.want { t.Errorf("got result %v, want %v.", result, test.want) } } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func TestIsVersionGreaterOrEqualThan(t *testing.T) { tests := []struct { version string target string want bool }{ { version: "0.9.1", target: "0.9.1", want: true, }, { version: "0.10.0", target: "0.9.1", want: true, }, { version: "0.9.0", target: "0.9.1", want: false, }, } for _, test := range tests { result := IsVersionGreaterOrEqualThan(test.version, test.target) if result != test.want { t.Errorf("got result %v, want %v.", result, test.want) } } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func SanitizeContent(content []byte) ([]byte, error) { bodyString := string(content) bm := bluemonday.UGCPolicy() return []byte(bm.Sanitize(bodyString)), nil }
1
Go
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
func GetImage(urlStr string) (*Image, error) { if _, err := url.Parse(urlStr); err != nil { return nil, err } response, err := http.Get(urlStr) if err != nil { return nil, err } defer response.Body.Close() mediatype, err := getMediatype(response) if err != nil { return nil, err } if !strings.HasPrefix(mediatype, "image/") { return nil, errors.New("Wrong image mediatype") } bodyBytes, err := io.ReadAll(response.Body) if err != nil { return nil, err } bodyBytes, err = SanitizeContent(bodyBytes) if err != nil { return nil, err } image := &Image{ Blob: bodyBytes, Mediatype: mediatype, } return image, nil }
1
Go
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
static void cmd_sdbk(Sdb *db, const char *input) { const char *arg = (input[0] == ' ')? input + 1: "*"; char *out = sdb_querys (db, NULL, 0, arg); if (out) { r_cons_println (out); free (out); } else { R_LOG_ERROR ("Usage: ask [query]"); } }
1
Go
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
static void cmd_anal_ucall_ref(RCore *core, ut64 addr) { RAnalFunction *fcn = r_anal_get_function_at (core->anal, addr); if (fcn) { r_cons_printf (" ; %s", fcn->name); } else { r_cons_printf (" ; 0x%" PFMT64x, addr); } }
1
Go
CWE-787
Out-of-bounds Write
The product writes data past the end, or before the beginning, of the intended buffer.
https://cwe.mitre.org/data/definitions/787.html
safe
func (cr *collectionRepo) AddCollection(ctx context.Context, collection *entity.Collection) (err error) { _, err = cr.data.DB.Transaction(func(session *xorm.Session) (result any, err error) { var has bool dbcollection := &entity.Collection{} result = nil has, err = session.Where("user_id = ? and object_id = ?", collection.UserID, collection.ObjectID).Get(dbcollection) if err != nil { return } if has { return } id, err := cr.uniqueIDRepo.GenUniqueIDStr(ctx, collection.TableName()) if err == nil { collection.ID = id _, err = session.Insert(collection) if err != nil { return result, errors.InternalServer(reason.DatabaseError).WithError(err).WithStack() } } return }) return err }
1
Go
CWE-362
Concurrent Execution using Shared Resource with Improper Synchronization ('Race Condition')
The product contains a code sequence that can run concurrently with other code, and the code sequence requires temporary, exclusive access to a shared resource, but a timing window exists in which the shared resource can be modified by another code sequence that is operating concurrently.
https://cwe.mitre.org/data/definitions/362.html
safe
func (uc *UserController) RetrievePassWord(ctx *gin.Context) { req := &schema.UserRetrievePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } captchaPass := uc.actionService.ActionRecordVerifyCaptcha(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP(), req.CaptchaID, req.CaptchaCode) if !captchaPass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "captcha_code", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.CaptchaVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) return } _, _ = uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) _, err := uc.userService.RetrievePassWord(ctx, req) handler.HandleResponse(ctx, err, nil) }
1
Go
CWE-284
Improper Access Control
The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
https://cwe.mitre.org/data/definitions/284.html
safe
func (am *AvatarMiddleware) AvatarThumb() gin.HandlerFunc { return func(ctx *gin.Context) { u := ctx.Request.RequestURI if strings.Contains(u, "/uploads/avatar/") { sizeStr := ctx.Query("s") size := converter.StringToInt(sizeStr) uUrl, err := url.Parse(u) if err != nil { ctx.Next() return } _, urlfileName := filepath.Split(uUrl.Path) uploadPath := am.serviceConfig.UploadPath filePath := fmt.Sprintf("%s/avatar/%s", uploadPath, urlfileName) var avatarfile []byte if size == 0 { avatarfile, err = os.ReadFile(filePath) } else { avatarfile, err = am.uploaderService.AvatarThumbFile(ctx, uploadPath, urlfileName, size) } if err != nil { ctx.Next() return } ext := strings.ToLower(path.Ext(filePath)[1:]) ctx.Header("content-type", fmt.Sprintf("image/%s", ext)) _, err = ctx.Writer.WriteString(string(avatarfile)) if err != nil { log.Error(err) } ctx.Abort() return } else { uUrl, err := url.Parse(u) if err != nil { ctx.Next() return } _, urlfileName := filepath.Split(uUrl.Path) uploadPath := am.serviceConfig.UploadPath filePath := fmt.Sprintf("%s/%s", uploadPath, urlfileName) ext := strings.ToLower(path.Ext(filePath)[1:]) ctx.Header("content-type", fmt.Sprintf("image/%s", ext)) } ctx.Next() } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func Sanitizer(fl validator.FieldLevel) (res bool) { field := fl.Field() switch field.Kind() { case reflect.String: filter := bluemonday.UGCPolicy() field.SetString(filter.Sanitize(field.String())) return true case reflect.Chan, reflect.Map, reflect.Slice, reflect.Array: return field.Len() > 0 case reflect.Ptr, reflect.Interface, reflect.Func: return !field.IsNil() default: return field.IsValid() && field.Interface() != reflect.Zero(field.Type()).Interface() } }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func createDefaultValidator(la i18n.Language) *validator.Validate { validate := validator.New() // _ = validate.RegisterValidation("notblank", validators.NotBlank) _ = validate.RegisterValidation("notblank", NotBlank) _ = validate.RegisterValidation("sanitizer", Sanitizer) validate.RegisterTagNameFunc(func(fld reflect.StructField) (res string) { defer func() { if len(res) > 0 { res = translator.Tr(la, res) } }() if jsonTag := fld.Tag.Get("json"); len(jsonTag) > 0 { if jsonTag == "-" { return "" } return jsonTag } if formTag := fld.Tag.Get("form"); len(formTag) > 0 { return formTag } return fld.Name }) return validate }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (sc *SiteInfoController) UpdateGeneral(ctx *gin.Context) { req := schema.SiteGeneralReq{} if handler.BindAndCheck(ctx, &req) { return } err := sc.siteInfoService.SaveSiteGeneral(ctx, req) handler.HandleResponse(ctx, err, req) }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (req *UpdateInfoRequest) Check() (errFields []*validator.FormErrorField, err error) { if len(req.Username) > 0 { if checker.IsInvalidUsername(req.Username) { errField := &validator.FormErrorField{ ErrorField: "username", ErrorMsg: reason.UsernameInvalid, } errFields = append(errFields, errField) return errFields, errors.BadRequest(reason.UsernameInvalid) } } req.BioHTML = converter.Markdown2BasicHTML(req.Bio) return nil, nil }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func Markdown2BasicHTML(source string) string { content := Markdown2HTML(source) filter := bluemonday.NewPolicy() filter.AllowElements("p", "b", "br") filter.AllowAttrs("src").OnElements("img") filter.AddSpaceWhenStrippingTag(true) content = filter.Sanitize(content) return content }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (us *UserAdminService) UpdateUserPassword(ctx context.Context, req *schema.UpdateUserPasswordReq) (err error) { // Users cannot modify their password if req.UserID == req.LoginUserID { return errors.BadRequest(reason.AdminCannotUpdateTheirPassword) } userInfo, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) if err != nil { return err } if !exist { return errors.BadRequest(reason.UserNotFound) } hashPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { return err } err = us.userRepo.UpdateUserPassword(ctx, userInfo.ID, string(hashPwd)) if err != nil { return err } // logout this user us.authService.RemoveAllUserTokens(ctx, req.UserID) return }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (uc *UserAdminController) UpdateUserStatus(ctx *gin.Context) { req := &schema.UpdateUserStatusReq{} if handler.BindAndCheck(ctx, req) { return } req.LoginUserID = middleware.GetLoginUserIDFromContext(ctx) err := uc.userService.UpdateUserStatus(ctx, req) handler.HandleResponse(ctx, err, nil) }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (us *UserAdminService) UpdateUserStatus(ctx context.Context, req *schema.UpdateUserStatusReq) (err error) { // Admin cannot modify their status if req.UserID == req.LoginUserID { return errors.BadRequest(reason.AdminCannotModifySelfStatus) } userInfo, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) if err != nil { return } if !exist { return errors.BadRequest(reason.UserNotFound) } // if user status is deleted if userInfo.Status == entity.UserStatusDeleted { return nil } if req.IsInactive() { userInfo.MailStatus = entity.EmailStatusToBeVerified } if req.IsDeleted() { userInfo.Status = entity.UserStatusDeleted userInfo.EMail = fmt.Sprintf("%s.%d", userInfo.EMail, time.Now().UnixNano()) } if req.IsSuspended() { userInfo.Status = entity.UserStatusSuspended } if req.IsNormal() { userInfo.Status = entity.UserStatusAvailable userInfo.MailStatus = entity.EmailStatusAvailable } err = us.userRepo.UpdateUserStatus(ctx, userInfo.ID, userInfo.Status, userInfo.MailStatus, userInfo.EMail) if err != nil { return err } // if user reputation is zero means this user is inactive, so try to activate this user. if req.IsNormal() && userInfo.Rank == 0 { return us.userActivity.UserActive(ctx, userInfo.ID) } return nil }
1
Go
NVD-CWE-noinfo
null
null
null
safe
func (uc *UserController) RetrievePassWord(ctx *gin.Context) { req := &schema.UserRetrievePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } captchaPass := uc.actionService.ActionRecordVerifyCaptcha(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP(), req.CaptchaID, req.CaptchaCode) if !captchaPass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "captcha_code", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.CaptchaVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.CaptchaVerificationFailed), errFields) return } _, _ = uc.actionService.ActionRecordAdd(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) err := uc.userService.RetrievePassWord(ctx, req) handler.HandleResponse(ctx, err, nil) }
1
Go
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
safe
func (us *UserService) RetrievePassWord(ctx context.Context, req *schema.UserRetrievePassWordRequest) error { userInfo, has, err := us.userRepo.GetByEmail(ctx, req.Email) if err != nil { return err } if !has { return nil } // send email data := &schema.EmailCodeContent{ Email: req.Email, UserID: userInfo.ID, } code := uuid.NewString() verifyEmailURL := fmt.Sprintf("%s/users/password-reset?code=%s", us.getSiteUrl(ctx), code) title, body, err := us.emailService.PassResetTemplate(ctx, verifyEmailURL) if err != nil { return err } go us.emailService.SendAndSaveCode(ctx, req.Email, title, body, code, data.ToJSONString()) return nil }
1
Go
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
safe
func (cr *captchaRepo) DelCaptcha(ctx context.Context, key string) (err error) { err = cr.data.Cache.Del(ctx, key) if err != nil { log.Debug(err) } return nil }
1
Go
CWE-294
Authentication Bypass by Capture-replay
A capture-replay flaw exists when the design of the product makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).
https://cwe.mitre.org/data/definitions/294.html
safe
func (cr *captchaRepo) DelCaptcha(ctx context.Context, key string) (err error) { err = cr.data.Cache.Del(ctx, key) if err != nil { log.Debug(err) } return nil }
1
Go
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
safe
func (cr *captchaRepo) DelCaptcha(ctx context.Context, key string) (err error) { err = cr.data.Cache.Del(ctx, key) if err != nil { log.Debug(err) } return nil }
1
Go
CWE-307
Improper Restriction of Excessive Authentication Attempts
The product does not implement sufficient measures to prevent multiple failed authentication attempts within a short time frame, making it more susceptible to brute force attacks.
https://cwe.mitre.org/data/definitions/307.html
safe
func (cr *captchaRepo) DelCaptcha(ctx context.Context, key string) (err error) { err = cr.data.Cache.Del(ctx, key) if err != nil { log.Debug(err) } return nil }
1
Go
CWE-263
Password Aging with Long Expiration
The product supports password aging, but the expiration period is too long.
https://cwe.mitre.org/data/definitions/263.html
safe
func (cs *CaptchaService) VerifyCaptcha(ctx context.Context, key, captcha string) (isCorrect bool, err error) { realCaptcha, err := cs.captchaRepo.GetCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha GetCaptcha Error", err.Error()) return false, nil } err = cs.captchaRepo.DelCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha DelCaptcha Error", err.Error()) return false, nil } return strings.TrimSpace(captcha) == realCaptcha, nil }
1
Go
CWE-294
Authentication Bypass by Capture-replay
A capture-replay flaw exists when the design of the product makes it possible for a malicious user to sniff network traffic and bypass authentication by replaying it to the server in question to the same effect as the original message (or with minor changes).
https://cwe.mitre.org/data/definitions/294.html
safe
func (cs *CaptchaService) VerifyCaptcha(ctx context.Context, key, captcha string) (isCorrect bool, err error) { realCaptcha, err := cs.captchaRepo.GetCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha GetCaptcha Error", err.Error()) return false, nil } err = cs.captchaRepo.DelCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha DelCaptcha Error", err.Error()) return false, nil } return strings.TrimSpace(captcha) == realCaptcha, nil }
1
Go
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
safe
func (cs *CaptchaService) VerifyCaptcha(ctx context.Context, key, captcha string) (isCorrect bool, err error) { realCaptcha, err := cs.captchaRepo.GetCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha GetCaptcha Error", err.Error()) return false, nil } err = cs.captchaRepo.DelCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha DelCaptcha Error", err.Error()) return false, nil } return strings.TrimSpace(captcha) == realCaptcha, nil }
1
Go
CWE-307
Improper Restriction of Excessive Authentication Attempts
The product does not implement sufficient measures to prevent multiple failed authentication attempts within a short time frame, making it more susceptible to brute force attacks.
https://cwe.mitre.org/data/definitions/307.html
safe
func (cs *CaptchaService) VerifyCaptcha(ctx context.Context, key, captcha string) (isCorrect bool, err error) { realCaptcha, err := cs.captchaRepo.GetCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha GetCaptcha Error", err.Error()) return false, nil } err = cs.captchaRepo.DelCaptcha(ctx, key) if err != nil { log.Error("VerifyCaptcha DelCaptcha Error", err.Error()) return false, nil } return strings.TrimSpace(captcha) == realCaptcha, nil }
1
Go
CWE-263
Password Aging with Long Expiration
The product supports password aging, but the expiration period is too long.
https://cwe.mitre.org/data/definitions/263.html
safe
func (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.ParsedText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.ParsedText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (tr *GetTagResp) GetExcerpt() { excerpt := strings.TrimSpace(tr.ParsedText) idx := strings.Index(excerpt, "\n") if idx >= 0 { excerpt = excerpt[0:idx] } tr.Excerpt = excerpt }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func (uc *UserController) UserLogout(ctx *gin.Context) { accessToken := middleware.ExtractToken(ctx) if len(accessToken) == 0 { handler.HandleResponse(ctx, nil, nil) return } _ = uc.authService.RemoveUserCacheInfo(ctx, accessToken) _ = uc.authService.RemoveAdminUserCacheInfo(ctx, accessToken) handler.HandleResponse(ctx, nil, nil) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func Markdown2HTML(source string) string { mdConverter := goldmark.New( goldmark.WithExtensions(&DangerousHTMLFilterExtension{}, extension.GFM), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( goldmarkHTML.WithHardWraps(), ), ) var buf bytes.Buffer if err := mdConverter.Convert([]byte(source), &buf); err != nil { log.Error(err) return source } html := buf.String() filter := bluemonday.NewPolicy() html = filter.Sanitize(html) return html }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func Markdown2HTML(source string) string { mdConverter := goldmark.New( goldmark.WithExtensions(&DangerousHTMLFilterExtension{}, extension.GFM), goldmark.WithParserOptions( parser.WithAutoHeadingID(), ), goldmark.WithRendererOptions( goldmarkHTML.WithHardWraps(), ), ) var buf bytes.Buffer if err := mdConverter.Convert([]byte(source), &buf); err != nil { log.Error(err) return source } html := buf.String() filter := bluemonday.NewPolicy() html = filter.Sanitize(html) return html }
1
Go
CWE-79
Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
The product 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
func Dexif(filepath string, destpath string) error { img, err := ioutil.ReadFile(filepath) if err != nil { return err } noExifBytes, err := exifremove.Remove(img) if err != nil { return err } err = os.WriteFile(destpath, noExifBytes, 0644) if err != nil { return err } return nil }
1
Go
CWE-1230
Exposure of Sensitive Information Through Metadata
The product prevents direct access to a resource containing sensitive information, but it does not sufficiently limit access to metadata that is derived from the original, sensitive information.
https://cwe.mitre.org/data/definitions/1230.html
safe
func Dexif(filepath string, destpath string) error { img, err := ioutil.ReadFile(filepath) if err != nil { return err } noExifBytes, err := exifremove.Remove(img) if err != nil { return err } err = os.WriteFile(destpath, noExifBytes, 0644) if err != nil { return err } return nil }
1
Go
CWE-201
Insertion of Sensitive Information Into Sent Data
The code transmits data to another actor, but a portion of the data includes sensitive information that should not be accessible to that actor.
https://cwe.mitre.org/data/definitions/201.html
safe
func (us *UploaderService) uploadFile(ctx *gin.Context, file *multipart.FileHeader, fileSubPath string) ( url string, err error) { siteGeneral, err := us.siteInfoService.GetSiteGeneral(ctx) if err != nil { return "", err } filePath := path.Join(us.serviceConfig.UploadPath, fileSubPath) if err := ctx.SaveUploadedFile(file, filePath); err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } src, err := file.Open() if err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } defer src.Close() Dexif(filePath, filePath) if !checker.IsSupportedImageFile(src, filepath.Ext(fileSubPath)) { return "", errors.BadRequest(reason.UploadFileUnsupportedFileFormat) } url = fmt.Sprintf("%s/uploads/%s", siteGeneral.SiteUrl, fileSubPath) return url, nil }
1
Go
CWE-1230
Exposure of Sensitive Information Through Metadata
The product prevents direct access to a resource containing sensitive information, but it does not sufficiently limit access to metadata that is derived from the original, sensitive information.
https://cwe.mitre.org/data/definitions/1230.html
safe
func (us *UploaderService) uploadFile(ctx *gin.Context, file *multipart.FileHeader, fileSubPath string) ( url string, err error) { siteGeneral, err := us.siteInfoService.GetSiteGeneral(ctx) if err != nil { return "", err } filePath := path.Join(us.serviceConfig.UploadPath, fileSubPath) if err := ctx.SaveUploadedFile(file, filePath); err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } src, err := file.Open() if err != nil { return "", errors.InternalServer(reason.UnknownError).WithError(err).WithStack() } defer src.Close() Dexif(filePath, filePath) if !checker.IsSupportedImageFile(src, filepath.Ext(fileSubPath)) { return "", errors.BadRequest(reason.UploadFileUnsupportedFileFormat) } url = fmt.Sprintf("%s/uploads/%s", siteGeneral.SiteUrl, fileSubPath) return url, nil }
1
Go
CWE-201
Insertion of Sensitive Information Into Sent Data
The code transmits data to another actor, but a portion of the data includes sensitive information that should not be accessible to that actor.
https://cwe.mitre.org/data/definitions/201.html
safe
func updateAcceptAnswerRank(x *xorm.Engine) error { c := &entity.Config{ID: 44, Key: "rank.answer.accept", Value: `-1`} if _, err := x.Update(c, &entity.Config{ID: 44, Key: "rank.answer.accept"}); err != nil { log.Errorf("update %+v config failed: %s", c, err) return fmt.Errorf("update config failed: %w", err) } return nil }
1
Go
CWE-862
Missing Authorization
The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
https://cwe.mitre.org/data/definitions/862.html
safe
func (uc *UserController) UseRePassWord(ctx *gin.Context) { req := &schema.UserRePassWordRequest{} if handler.BindAndCheck(ctx, req) { return } req.Content = uc.emailService.VerifyUrlExpired(ctx, req.Code) if len(req.Content) == 0 { handler.HandleResponse(ctx, errors.Forbidden(reason.EmailVerifyURLExpired), &schema.ForbiddenResp{Type: schema.ForbiddenReasonTypeURLExpired}) return } err := uc.userService.UpdatePasswordWhenForgot(ctx, req) uc.actionService.ActionRecordDel(ctx, schema.ActionRecordTypeFindPass, ctx.ClientIP()) handler.HandleResponse(ctx, err, nil) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (uc *UserController) UserModifyPassWord(ctx *gin.Context) { req := &schema.UserModifyPasswordReq{} if handler.BindAndCheck(ctx, req) { return } req.UserID = middleware.GetLoginUserIDFromContext(ctx) req.AccessToken = middleware.ExtractToken(ctx) oldPassVerification, err := uc.userService.UserModifyPassWordVerification(ctx, req) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !oldPassVerification { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "old_pass", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.OldPasswordVerificationFailed), }) handler.HandleResponse(ctx, errors.BadRequest(reason.OldPasswordVerificationFailed), errFields) return } if req.OldPass == req.Pass { errFields := append([]*validator.FormErrorField{}, &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: translator.Tr(handler.GetLang(ctx), reason.NewPasswordSameAsPreviousSetting), }) handler.HandleResponse(ctx, errors.BadRequest(reason.NewPasswordSameAsPreviousSetting), errFields) return } err = uc.userService.UserModifyPassword(ctx, req) handler.HandleResponse(ctx, err, nil) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (ar *authRepo) RemoveUserTokens(ctx context.Context, userID string, remainToken string) { key := constant.UserTokenMappingCacheKey + userID resp, _ := ar.data.Cache.GetString(ctx, key) mapping := make(map[string]bool, 0) if len(resp) > 0 { _ = json.Unmarshal([]byte(resp), &mapping) log.Debugf("find %d user tokens by user id %s", len(mapping), userID) } for token := range mapping { if token == remainToken { continue } if err := ar.RemoveUserCacheInfo(ctx, token); err != nil { log.Error(err) } else { log.Debugf("del user %s token success") } } if err := ar.RemoveUserStatus(ctx, userID); err != nil { log.Error(err) } if err := ar.data.Cache.Del(ctx, key); err != nil { log.Error(err) } }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (r *GetUserResp) GetFromUserEntity(userInfo *entity.User) { _ = copier.Copy(r, userInfo) r.Avatar = FormatAvatarInfo(userInfo.Avatar, userInfo.EMail) r.CreatedAt = userInfo.CreatedAt.Unix() r.LastLoginDate = userInfo.LastLoginDate.Unix() statusShow, ok := UserStatusShow[userInfo.Status] if ok { r.Status = statusShow } r.HavePassword = len(userInfo.Pass) > 0 }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (u *UserModifyPasswordReq) Check() (errFields []*validator.FormErrorField, err error) { // TODO i18n err = checker.CheckPassword(8, 32, 0, u.Pass) if err != nil { errField := &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), } errFields = append(errFields, errField) return errFields, err } return nil, nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (as *AuthService) RemoveTokensExceptCurrentUser(ctx context.Context, userID string, accessToken string) { as.authRepo.RemoveUserTokens(ctx, userID, accessToken) }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (as *AuthService) RemoveUserAllTokens(ctx context.Context, userID string) { as.authRepo.RemoveUserTokens(ctx, userID, "") }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserAdminService) UpdateUserPassword(ctx context.Context, req *schema.UpdateUserPasswordReq) (err error) { // Users cannot modify their password if req.UserID == req.LoginUserID { return errors.BadRequest(reason.AdminCannotUpdateTheirPassword) } userInfo, exist, err := us.userRepo.GetUserInfo(ctx, req.UserID) if err != nil { return err } if !exist { return errors.BadRequest(reason.UserNotFound) } hashPwd, err := bcrypt.GenerateFromPassword([]byte(req.Password), bcrypt.DefaultCost) if err != nil { return err } err = us.userRepo.UpdateUserPassword(ctx, userInfo.ID, string(hashPwd)) if err != nil { return err } // logout this user us.authService.RemoveUserAllTokens(ctx, req.UserID) return }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserAdminService) UpdateUserRole(ctx context.Context, req *schema.UpdateUserRoleReq) (err error) { // Users cannot modify their roles if req.UserID == req.LoginUserID { return errors.BadRequest(reason.UserCannotUpdateYourRole) } err = us.userRoleRelService.SaveUserRole(ctx, req.UserID, req.RoleID) if err != nil { return err } us.authService.RemoveUserAllTokens(ctx, req.UserID) return }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserService) verifyPassword(ctx context.Context, loginPass, userPass string) bool { if len(loginPass) == 0 && len(userPass) == 0 { return true } err := bcrypt.CompareHashAndPassword([]byte(userPass), []byte(loginPass)) return err == nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserService) UpdatePasswordWhenForgot(ctx context.Context, req *schema.UserRePassWordRequest) (err error) { data := &schema.EmailCodeContent{} err = data.FromJSONString(req.Content) if err != nil { return errors.BadRequest(reason.EmailVerifyURLExpired) } userInfo, exist, err := us.userRepo.GetByEmail(ctx, data.Email) if err != nil { return err } if !exist { return errors.BadRequest(reason.UserNotFound) } enpass, err := us.encryptPassword(ctx, req.Pass) if err != nil { return err } err = us.userRepo.UpdatePass(ctx, userInfo.ID, enpass) if err != nil { return err } // When the user changes the password, all the current user's tokens are invalid. us.authService.RemoveUserAllTokens(ctx, userInfo.ID) return nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserService) UserModifyPassWordVerification(ctx context.Context, req *schema.UserModifyPasswordReq) (bool, error) { userInfo, has, err := us.userRepo.GetByUserID(ctx, req.UserID) if err != nil { return false, err } if !has { return false, errors.BadRequest(reason.UserNotFound) } isPass := us.verifyPassword(ctx, req.OldPass, userInfo.Pass) if !isPass { return false, nil } return true, nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserService) UserModifyPassword(ctx context.Context, req *schema.UserModifyPasswordReq) error { enpass, err := us.encryptPassword(ctx, req.Pass) if err != nil { return err } userInfo, exist, err := us.userRepo.GetByUserID(ctx, req.UserID) if err != nil { return err } if !exist { return errors.BadRequest(reason.UserNotFound) } isPass := us.verifyPassword(ctx, req.OldPass, userInfo.Pass) if !isPass { return errors.BadRequest(reason.OldPasswordVerificationFailed) } err = us.userRepo.UpdatePass(ctx, userInfo.ID, enpass) if err != nil { return err } us.authService.RemoveTokensExceptCurrentUser(ctx, userInfo.ID, req.AccessToken) return nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (us *UserService) GetUserInfoByUserID(ctx context.Context, token, userID string) (resp *schema.GetUserToSetShowResp, err error) { userInfo, exist, err := us.userRepo.GetByUserID(ctx, userID) if err != nil { return nil, err } if !exist { return nil, errors.BadRequest(reason.UserNotFound) } roleID, err := us.userRoleService.GetUserRole(ctx, userInfo.ID) if err != nil { log.Error(err) } resp = &schema.GetUserToSetShowResp{} resp.GetFromUserEntity(userInfo) resp.AccessToken = token resp.RoleID = roleID resp.HavePassword = len(userInfo.Pass) > 0 return resp, nil }
1
Go
CWE-613
Insufficient Session Expiration
According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."
https://cwe.mitre.org/data/definitions/613.html
safe
func (m *MyValidator) Check(value interface{}) (errFields []*FormErrorField, err error) { err = m.Validate.Struct(value) if err != nil { var valErrors validator.ValidationErrors if !errors.As(err, &valErrors) { log.Error(err) return nil, errors.New("validate check exception") } for _, fieldError := range valErrors { errField := &FormErrorField{ ErrorField: fieldError.Field(), ErrorMsg: fieldError.Translate(m.Tran), } // get original tag name from value for set err field key. structNamespace := fieldError.StructNamespace() _, fieldName, found := strings.Cut(structNamespace, ".") if found { originalTag := getObjectTagByFieldName(value, fieldName) if len(originalTag) > 0 { errField.ErrorField = originalTag } } errFields = append(errFields, errField) } if len(errFields) > 0 { errMsg := "" if len(errFields) == 1 { errMsg = errFields[0].ErrorMsg } return errFields, myErrors.BadRequest(reason.RequestFormatError).WithMsg(errMsg) } } if v, ok := value.(Checker); ok { errFields, err = v.Check() if err == nil { return nil, nil } errMsg := "" for _, errField := range errFields { errField.ErrorMsg = translator.Tr(m.Lang, errField.ErrorMsg) errMsg = errField.ErrorMsg } return errFields, myErrors.BadRequest(reason.RequestFormatError).WithMsg(errMsg) } return nil, nil }
1
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
safe
func addLoginLimitations(x *xorm.Engine) error { loginSiteInfo := &entity.SiteInfo{ Type: constant.SiteTypeLogin, } exist, err := x.Get(loginSiteInfo) if err != nil { return fmt.Errorf("get config failed: %w", err) } if exist { content := &schema.SiteLoginReq{} _ = json.Unmarshal([]byte(loginSiteInfo.Content), content) content.AllowEmailRegistrations = true content.AllowEmailDomains = make([]string, 0) data, _ := json.Marshal(content) loginSiteInfo.Content = string(data) _, err = x.ID(loginSiteInfo.ID).Cols("content").Update(loginSiteInfo) if err != nil { return fmt.Errorf("update site info failed: %w", err) } } interfaceSiteInfo := &entity.SiteInfo{ Type: constant.SiteTypeInterface, } exist, err = x.Get(interfaceSiteInfo) if err != nil { return fmt.Errorf("get config failed: %w", err) } siteUsers := &schema.SiteUsersReq{ AllowUpdateDisplayName: true, AllowUpdateUsername: true, AllowUpdateAvatar: true, AllowUpdateBio: true, AllowUpdateWebsite: true, AllowUpdateLocation: true, } if exist { siteUsers.DefaultAvatar = gjson.Get(interfaceSiteInfo.Content, "default_avatar").String() } data, _ := json.Marshal(siteUsers) exist, err = x.Get(&entity.SiteInfo{Type: constant.SiteTypeUsers}) if err != nil { return fmt.Errorf("get config failed: %w", err) } if !exist { usersSiteInfo := &entity.SiteInfo{ Type: constant.SiteTypeUsers, Content: string(data), Status: 1, } _, err = x.InsertOne(usersSiteInfo) if err != nil { return fmt.Errorf("insert site info failed: %w", err) } } return nil }
1
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
safe
func (u *UserRePassWordRequest) Check() (errFields []*validator.FormErrorField, err error) { if err = checker.CheckPassword(u.Pass); err != nil { errFields = append(errFields, &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), }) return errFields, err } return nil, nil }
1
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
safe
func (u *UserModifyPasswordReq) Check() (errFields []*validator.FormErrorField, err error) { if err = checker.CheckPassword(u.Pass); err != nil { errFields = append(errFields, &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), }) return errFields, err } return nil, nil }
1
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
safe
func (u *UserRegisterReq) Check() (errFields []*validator.FormErrorField, err error) { if err = checker.CheckPassword(u.Pass); err != nil { errFields = append(errFields, &validator.FormErrorField{ ErrorField: "pass", ErrorMsg: err.Error(), }) return errFields, err } return nil, nil }
1
Go
CWE-521
Weak Password Requirements
The product does not require that users should have strong passwords, which makes it easier for attackers to compromise user accounts.
https://cwe.mitre.org/data/definitions/521.html
safe
func (vc *VoteController) VoteDown(ctx *gin.Context) { req := &schema.VoteReq{} if handler.BindAndCheck(ctx, req) { return } req.ObjectID = uid.DeShortID(req.ObjectID) req.UserID = middleware.GetLoginUserIDFromContext(ctx) can, needRank, err := vc.rankService.CheckVotePermission(ctx, req.UserID, req.ObjectID, false) if err != nil { handler.HandleResponse(ctx, err, nil) return } if !can { lang := handler.GetLang(ctx) msg := translator.TrWithData(lang, reason.NoEnoughRankToOperate, &schema.PermissionTrTplData{Rank: needRank}) handler.HandleResponse(ctx, errors.Forbidden(reason.NoEnoughRankToOperate).WithMsg(msg), nil) return } resp, err := vc.VoteService.VoteDown(ctx, req) if err != nil { handler.HandleResponse(ctx, err, schema.ErrTypeToast) } else { handler.HandleResponse(ctx, err, resp) } }
1
Go
CWE-366
Race Condition within a Thread
If two threads of execution use a resource simultaneously, there exists the possibility that resources may be used while invalid, in turn making the state of execution undefined.
https://cwe.mitre.org/data/definitions/366.html
safe