Publicus/cvefixes-security-ir-graphrag huggingface dataset:
CVE-2024-3761: Missing Authorization (CWE-862)
value: In lunary-ai/lunary version 1.2.2, the DELETE endpoint located at `packages/backend/src/api/v1/datasets` is vulnerable to unauthorized dataset deletion due to missing authorization and authentication mechanisms. This vulnerability allows any user, even those without a valid token, to delete a dataset by sending a DELETE request to the endpoint. The issue was fixed in version 1.2.8. The impact of this vulnerability is significant as it permits unauthorized users to delete datasets, potentially leading to data loss or disruption of service.
CWE description: The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
Published: 2024-05-20T09:15Z
Repository: https://github.com/lunary-ai/lunary
Language: TypeScript
Files changed: packages/backend/src/api/v1/datasets/index.ts
Commit date: 2024-04-13 16:27:58 -0300
Commit message: fix: authorization delete dataset (#204)


Diff: diff --git a/packages/backend/src/api/v1/datasets/index.ts b/packages/backend/src/api/v1/datasets/index.ts
index 26c58f7c..c1784088 100644
--- a/packages/backend/src/api/v1/datasets/index.ts
+++ b/packages/backend/src/api/v1/datasets/index.ts
@@ -118,17 +118,22 @@ datasets.patch(
 
     ctx.body = dataset
   },
 )
 
-datasets.delete("/:id", async (ctx: Context) => {
-  const { id } = ctx.params
+datasets.delete(
+  "/:id",
+  checkAccess("datasets", "delete"),
+  async (ctx: Context) => {
+    const { id } = ctx.params
+    const { projectId } = ctx.state
 
-  await sql`delete from dataset where id = ${id}`
+    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
 
-  ctx.status = 200
-})
+    ctx.status = 200
+  },
+)
 
 // Create prompt
 datasets.post(
   "/prompts",
   checkAccess("datasets", "update"),

Vulnerable code: datasets.delete("/:id", async (ctx: Context) => {
  const { id } = ctx.params
  await sql`delete from dataset where id = ${id}`
  ctx.status = 200
})
Fixed code: datasets.delete(
  "/:id",
  checkAccess("datasets", "delete"),
  async (ctx: Context) => {
    const { id } = ctx.params
    const { projectId } = ctx.state
    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
    ctx.status = 200
  },
)
CVE-2024-4146: Incorrect Authorization (CWE-863)
value: In lunary-ai/lunary version v1.2.13, an improper authorization vulnerability exists that allows unauthorized users to access and manipulate projects within an organization they should not have access to. Specifically, the vulnerability is located in the `checkProjectAccess` method within the authorization middleware, which fails to adequately verify if a user has the correct permissions to access a specific project. Instead, it only checks if the user is part of the organization owning the project, overlooking the necessary check against the `account_project` table for explicit project access rights. This flaw enables attackers to gain complete control over all resources within a project, including the ability to create, update, read, and delete any resource, compromising the privacy and security of sensitive information.
CWE description: The product 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.
CVSS v3 base score: 9.8
Published: 2024-06-08T20:15Z
Repository: https://github.com/lunary-ai/lunary
Language: TypeScript
Files changed: packages/backend/src/utils/authorization.ts
Commit date: 2024-05-25 16:44:59 -0300
Commit message: fix: project accesss (#343)


Diff: diff --git a/packages/backend/src/utils/authorization.ts b/packages/backend/src/utils/authorization.ts
index 43de2465..8974cc80 100644
--- a/packages/backend/src/utils/authorization.ts
+++ b/packages/backend/src/utils/authorization.ts
@@ -1,20 +1,18 @@
 import { Next } from "koa"
 import sql from "./db"
 import Context from "./koa"
 import { Action, ResourceName, hasAccess } from "shared"
 
-// TODO: Needs to use account_project instead
 export async function checkProjectAccess(projectId: string, userId: string) {
   const [{ exists: hasAccess }] = await sql`
       select exists (
         select 1 
-        from project 
-        where org_id = (select org_id from account where id = ${userId}) 
-          and id = ${projectId}
+        from account_project ap
+        where ap.project_id = ${projectId} and ap.account_id = ${userId}
       )
-    `
+  `
   return hasAccess
 }
 
 export function checkAccess(resourceName: ResourceName, action: Action) {
   return async (ctx: Context, next: Next) => {

Vulnerable code: // TODO: Needs to use account_project instead
        from project 
        where org_id = (select org_id from account where id = ${userId}) 
          and id = ${projectId}
    `
Fixed code:         from account_project ap
        where ap.project_id = ${projectId} and ap.account_id = ${userId}
  `
CVE-2024-5129: Insufficient Information (NVD-CWE-noinfo)
value: A Privilege Escalation Vulnerability exists in lunary-ai/lunary version 1.2.2, where any user can delete any datasets due to missing authorization checks. The vulnerability is present in the dataset deletion functionality, where the application fails to verify if the user requesting the deletion has the appropriate permissions. This allows unauthorized users to send a DELETE request to the server and delete any dataset by specifying its ID. The issue is located in the datasets.delete function within the datasets index file.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-06-06T19:16Z
Repository: https://github.com/lunary-ai/lunary
Language: TypeScript
Files changed: packages/backend/src/api/v1/datasets/index.ts
Commit date: 2024-04-13 16:27:58 -0300
Commit message: fix: authorization delete dataset (#204)


Diff: diff --git a/packages/backend/src/api/v1/datasets/index.ts b/packages/backend/src/api/v1/datasets/index.ts
index 26c58f7c..c1784088 100644
--- a/packages/backend/src/api/v1/datasets/index.ts
+++ b/packages/backend/src/api/v1/datasets/index.ts
@@ -118,17 +118,22 @@ datasets.patch(
 
     ctx.body = dataset
   },
 )
 
-datasets.delete("/:id", async (ctx: Context) => {
-  const { id } = ctx.params
+datasets.delete(
+  "/:id",
+  checkAccess("datasets", "delete"),
+  async (ctx: Context) => {
+    const { id } = ctx.params
+    const { projectId } = ctx.state
 
-  await sql`delete from dataset where id = ${id}`
+    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
 
-  ctx.status = 200
-})
+    ctx.status = 200
+  },
+)
 
 // Create prompt
 datasets.post(
   "/prompts",
   checkAccess("datasets", "update"),

Vulnerable code: datasets.delete("/:id", async (ctx: Context) => {
  const { id } = ctx.params
  await sql`delete from dataset where id = ${id}`
  ctx.status = 200
})
Fixed code: datasets.delete(
  "/:id",
  checkAccess("datasets", "delete"),
  async (ctx: Context) => {
    const { id } = ctx.params
    const { projectId } = ctx.state
    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
    ctx.status = 200
  },
)
CVE-2024-5130: Incorrect Authorization (CWE-863)
value: An Incorrect Authorization vulnerability exists in lunary-ai/lunary versions up to and including 1.2.2, which allows unauthenticated users to delete any dataset. The vulnerability is due to the lack of proper authorization checks in the dataset deletion endpoint. Specifically, the endpoint does not verify if the provided project ID belongs to the current user, thereby allowing any dataset to be deleted without proper authentication. This issue was fixed in version 1.2.8.
CWE description: The product 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.
Published: 2024-06-06T19:16Z
Repository: https://github.com/lunary-ai/lunary
Language: TypeScript
Files changed: packages/backend/src/api/v1/datasets/index.ts
Commit date: 2024-04-13 16:27:58 -0300
Commit message: fix: authorization delete dataset (#204)


Diff: diff --git a/packages/backend/src/api/v1/datasets/index.ts b/packages/backend/src/api/v1/datasets/index.ts
index 26c58f7c..c1784088 100644
--- a/packages/backend/src/api/v1/datasets/index.ts
+++ b/packages/backend/src/api/v1/datasets/index.ts
@@ -118,17 +118,22 @@ datasets.patch(
 
     ctx.body = dataset
   },
 )
 
-datasets.delete("/:id", async (ctx: Context) => {
-  const { id } = ctx.params
+datasets.delete(
+  "/:id",
+  checkAccess("datasets", "delete"),
+  async (ctx: Context) => {
+    const { id } = ctx.params
+    const { projectId } = ctx.state
 
-  await sql`delete from dataset where id = ${id}`
+    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
 
-  ctx.status = 200
-})
+    ctx.status = 200
+  },
+)
 
 // Create prompt
 datasets.post(
   "/prompts",
   checkAccess("datasets", "update"),

Vulnerable code: datasets.delete("/:id", async (ctx: Context) => {
  const { id } = ctx.params
  await sql`delete from dataset where id = ${id}`
  ctx.status = 200
})
Fixed code: datasets.delete(
  "/:id",
  checkAccess("datasets", "delete"),
  async (ctx: Context) => {
    const { id } = ctx.params
    const { projectId } = ctx.state
    await sql`delete from dataset where id = ${id} and projectId = ${projectId}`
    ctx.status = 200
  },
)
CVE-2024-5131: Improper Access Control (CWE-284)
value: An Improper Access Control vulnerability exists in the lunary-ai/lunary repository, affecting versions up to and including 1.2.2. The vulnerability allows unauthorized users to view any prompts in any projects by supplying a specific prompt ID to an endpoint that does not adequately verify the ownership of the prompt ID. This issue was fixed in version 1.2.25.
CWE description: The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.
Published: 2024-06-06T19:16Z
Repository: https://github.com/lunary-ai/lunary
Language: TypeScript
Files changed: packages/backend/src/api/v1/template-versions.ts
Commit date: 2024-05-19 15:47:48 -0300
Commit message: fix: api security (#331)


Diff: diff --git a/packages/backend/src/api/v1/template-versions.ts b/packages/backend/src/api/v1/template-versions.ts
index 8a940fb4..77cf4221 100644
--- a/packages/backend/src/api/v1/template-versions.ts
+++ b/packages/backend/src/api/v1/template-versions.ts
@@ -50,18 +50,31 @@ versions.get("/latest", async (ctx: Context) => {
 
   ctx.body = latestVersion
 })
 
 versions.get("/:id", async (ctx: Context) => {
+  const { id: versionId } = ctx.params
+  const { projectId } = ctx.state
+
   const [version] = await sql`
-    select * from template_version where id = ${ctx.params.id}
+    select
+      tv.*
+    from
+      template_version tv
+      left join template t on tv.template_id = t.id
+      left join project p on t.project_id = p.id and p.id = ${projectId}
+    where
+      tv.id = ${versionId}
   `
+  if (!version) {
+    ctx.throw(401, "You do not have access to this ressource.")
+  }
 
   version.extra = unCamelObject(version.extra)
 
   const [template] = await sql`
-    select * from template where project_id = ${ctx.state.projectId} and id = ${version.templateId}
+    select * from template where project_id = ${projectId} and id = ${version.templateId}
   `
 
   ctx.body = { ...version, template }
 })
 

Vulnerable code:     select * from template_version where id = ${ctx.params.id}
    select * from template where project_id = ${ctx.state.projectId} and id = ${version.templateId}
Fixed code:   const { id: versionId } = ctx.params
  const { projectId } = ctx.state

    select
      tv.*
    from
      template_version tv
      left join template t on tv.template_id = t.id
      left join project p on t.project_id = p.id and p.id = ${projectId}
    where
      tv.id = ${versionId}
  if (!version) {
    ctx.throw(401, "You do not have access to this ressource.")
  }
    select * from template where project_id = ${projectId} and id = ${version.templateId}
CVE-2023-25807: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: DataEase is an open source data visualization and analysis tool. When saving a dashboard on the DataEase platform saved data can be modified and store malicious code. This vulnerability can lead to the execution of malicious code stored by the attacker on the server side when the user accesses the dashboard. The vulnerability has been fixed in version 1.18.3.

CWE description: 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.
CVSS v3 base score: 5.4
Published: 2023-02-28T16:15Z
Repository: https://github.com/dataease/dataease
Language: Unknown
Commit date: 2023-02-21 14:00:47 +0800
Commit message: Merge pull request #4596 from dataease/pr@dev@refactor_xss-attack

refactor: 仪表板防范XSS攻击 #4585
CVE-2024-23328: Insufficient Information (NVD-CWE-noinfo)
value: Dataease is an open source data visualization analysis tool. A deserialization vulnerability exists in the DataEase datasource, which can be exploited to execute arbitrary code. The location of the vulnerability code is `core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java.` The blacklist of mysql jdbc attacks can be bypassed and attackers can further exploit it for deserialized execution or reading arbitrary files. This vulnerability is patched in 1.18.15 and 2.3.0.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-02-29T01:44Z
Repository: https://github.com/dataease/dataease
Language: Java
Files changed: core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java
Commit date: 2024-01-18 17:53:34 +0800
Commit message: fix: 限制 mysql 非法参数

Diff: diff --git a/core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java b/core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java
index fad120d167..b6e0e8e6e4 100644
--- a/core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java
+++ b/core/core-backend/src/main/java/io/dataease/datasource/type/Mysql.java
@@ -4,10 +4,11 @@ import io.dataease.api.ds.vo.DatasourceConfiguration;
 import io.dataease.exception.DEException;
 import lombok.Data;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.stereotype.Component;
 
+import java.net.URLDecoder;
 import java.util.Arrays;
 import java.util.List;
 
 @Data
 @Component("mysql")
@@ -23,11 +24,11 @@ public class Mysql extends DatasourceConfiguration {
                     .replace("HOSTNAME", getHost().trim())
                     .replace("PORT", getPort().toString().trim())
                     .replace("DATABASE", getDataBase().trim());
         } else {
             for (String illegalParameter : illegalParameters) {
-                if (getExtraParams().toLowerCase().contains(illegalParameter.toLowerCase())) {
+                if (getExtraParams().toLowerCase().contains(illegalParameter.toLowerCase()) || URLDecoder.decode(getExtraParams()).contains(illegalParameter.toLowerCase())) {
                     DEException.throwException("Illegal parameter: " + illegalParameter);
                 }
             }
 
             return "jdbc:mysql://HOSTNAME:PORT/DATABASE?EXTRA_PARAMS"

Vulnerable code:                 if (getExtraParams().toLowerCase().contains(illegalParameter.toLowerCase())) {
Fixed code: import java.net.URLDecoder;
                if (getExtraParams().toLowerCase().contains(illegalParameter.toLowerCase()) || URLDecoder.decode(getExtraParams()).contains(illegalParameter.toLowerCase())) {
CVE-2024-37304: Insufficient Information (NVD-CWE-noinfo)
value: NuGet Gallery is a package repository that powers nuget.org. The NuGetGallery has a security vulnerability related to its handling of autolinks in Markdown content. While the platform properly filters out JavaScript from standard links, it does not adequately sanitize autolinks. This oversight allows attackers to exploit autolinks as a vector for Cross-Site Scripting (XSS) attacks. When a user inputs a Markdown autolink such as `<javascript:alert(1)>`, the link is rendered without proper sanitization. This means that the JavaScript code within the autolink can be executed by the browser, leading to an XSS attack. Version 2024.05.28 contains a patch for this issue.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-06-12T15:15Z
Repository: https://github.com/NuGet/NuGetGallery
Language: C#
Files changed: src/NuGetGallery/Services/MarkdownService.cs
Commit date: 2024-02-28 13:03:25 -0800
Commit message: don't support javascript (#9836)


Diff: diff --git a/src/NuGetGallery/Services/MarkdownService.cs b/src/NuGetGallery/Services/MarkdownService.cs
index 5adeaee2c..1483e1406 100644
--- a/src/NuGetGallery/Services/MarkdownService.cs
+++ b/src/NuGetGallery/Services/MarkdownService.cs
@@ -18,10 +18,11 @@ namespace NuGetGallery
     public class MarkdownService : IMarkdownService
     {
         private static readonly TimeSpan RegexTimeout = TimeSpan.FromMinutes(1);
         private static readonly Regex EncodedBlockQuotePattern = new Regex("^ {0,3}&gt;", RegexOptions.Multiline, RegexTimeout);
         private static readonly Regex LinkPattern = new Regex("<a href=([\"\']).*?\\1", RegexOptions.None, RegexTimeout);
+        private static readonly Regex JavaScriptPattern = new Regex("<a href=([\"\'])javascript:.*?\\1 rel=([\"'])noopener noreferrer nofollow\\1>", RegexOptions.None, RegexTimeout);
         private static readonly Regex HtmlCommentPattern = new Regex("<!--.*?-->", RegexOptions.Singleline, RegexTimeout);
         private static readonly Regex ImageTextPattern = new Regex("!\\[\\]\\(", RegexOptions.Singleline, RegexTimeout);
         private static readonly string altTextForImage = "alternate text is missing from this package README image";
 
         private readonly IFeatureFlagService _features;
@@ -283,10 +284,11 @@ private RenderedMarkdownResult GetHtmlFromMarkdownMarkdig(string markdownString,
                 }
 
                 renderer.Render(document);
                 output.Content = htmlWriter.ToString().Trim();
                 output.IsMarkdigMdSyntaxHighlightEnabled = _features.IsMarkdigMdSyntaxHighlightEnabled();
+                output.Content = JavaScriptPattern.Replace(htmlWriter.ToString(), "").Trim();
 
                 return output;
             }
         }
     }

Fixed code:         private static readonly Regex JavaScriptPattern = new Regex("<a href=([\"\'])javascript:.*?\\1 rel=([\"'])noopener noreferrer nofollow\\1>", RegexOptions.None, RegexTimeout);
                output.Content = JavaScriptPattern.Replace(htmlWriter.ToString(), "").Trim();
CVE-2022-48468: Integer Overflow or Wraparound (CWE-190)
value: protobuf-c before 1.4.1 has an unsigned integer overflow in parse_required_member.
CWE description: The product performs a calculation that can
         produce an integer overflow or wraparound when the logic
         assumes that the resulting value will always be larger than
         the original value. This occurs when an integer value is
         incremented to a value that is too large to store in the
         associated representation. When this occurs, the value may
         become a very small or negative number.
CVSS v3 base score: 5.5
Published: 2023-04-13T21:15Z
Repository: https://github.com/protobuf-c/protobuf-c
Language: Unknown
Commit date: 2022-07-10 20:37:15 -0400
Commit message: Merge pull request #513 from protobuf-c/edmonds/issue499

Fix issue #499: unsigned integer overflow
CVE-2014-125088: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: A vulnerability was found in qt-users-jp silk 0.0.1. It has been declared as problematic. This vulnerability affects unknown code of the file contents/root/examples/header.qml. The manipulation of the argument model.key/model.value leads to cross site scripting. The attack can be initiated remotely. The name of the patch is bbc5d6eeea800025ef29edda3fd3c57836239eae. It is recommended to apply a patch to fix this issue. The identifier of this vulnerability is VDB-221488.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2023-02-20T08:15Z
Repository: https://github.com/qt-users-jp/silk
Language: Other
Files changed: contents/root/examples/header.qml
Commit date: 2014-10-23 16:44:09 +0900
Commit message: fix XSS vector in document body issue in header.qml

Change-Id: Icb0981b2aed71f4b7e7d189eea27d5a69ef228e4
Reviewed-on: http://cr.qtquick.me/874
Tested-by: http://ci.qtquick.me/
Tested-by: R Kake <helicalgear@gmail.com>
Reviewed-by: R Kake <helicalgear@gmail.com>
Tested-by: Tasuku Suzuki <stasuku@gmail.com>
Reviewed-by: Tasuku Suzuki <stasuku@gmail.com>

Diff: diff --git a/contents/root/examples/header.qml b/contents/root/examples/header.qml
index 4cd3592..e9355b3 100755
--- a/contents/root/examples/header.qml
+++ b/contents/root/examples/header.qml
@@ -37,14 +37,14 @@ Html {
         H1 { text: title.text }
         Dl {
             Repeater {
                 model: http.requestHeader
                 Component {
-                    Dt { text: model.key }
+                    Dt { text: Silk.escapeHTML(model.key) }
                 }
                 Component {
-                    Dd { text: model.value }
+                    Dd { text: Silk.escapeHTML(model.value) }
                 }
             }
         }
     }
 }

Vulnerable code:                     Dt { text: model.key }
                    Dd { text: model.value }
Fixed code:                     Dt { text: Silk.escapeHTML(model.key) }
                    Dd { text: Silk.escapeHTML(model.value) }
CVE-2021-3866: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: Cross-site Scripting (XSS) - Stored in GitHub repository zulip/zulip more than and including 44f935695d452cc3fb16845a0c6af710438b153d and prior to 3eb2791c3e9695f7d37ffe84e0c2184fae665cb6.
CWE description: 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.
CVSS v3 base score: 5.4
Published: 2022-01-20T11:15Z
Repository: https://github.com/zulip/zulip
Language: Other
Files changed: static/templates/recipient_row.hbs
Commit date: 2022-01-18 21:28:21 -0800
Commit message: CVE-2021-3853: Fix HTML escaping in recipient_row.

Commit 44f935695d452cc3fb16845a0c6af710438b153d (#20462) incorrectly
added these extra braces while intending to add whitespace control.
This triple-brace syntax was asking Handlebars to skip escaping the
string.

Signed-off-by: Anders Kaseorg <anders@zulip.com>

Diff: diff --git a/static/templates/recipient_row.hbs b/static/templates/recipient_row.hbs
index faf923f239..9cfc1df973 100644
--- a/static/templates/recipient_row.hbs
+++ b/static/templates/recipient_row.hbs
@@ -15,11 +15,11 @@
                 {{~#if is_web_public ~}}
                     <i class="fa fa-globe recipient-row-stream-icon" title="{{t 'This is a web public stream' }}" aria-label="{{t 'This is a web public stream' }}"></i>
                 {{/if}}
 
                 {{~! Recipient (e.g. stream/topic or topic) ~}}
-                {{~{display_recipient}~}}
+                {{~display_recipient~}}
             </a>
 
             {{! hidden narrow icon for copy-pasting }}
             <span class="copy-paste-text">&gt;</span>
 

Vulnerable code:                 {{~{display_recipient}~}}
Fixed code:                 {{~display_recipient~}}
CVE-2013-10010: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting') (CWE-79)
value: A vulnerability classified as problematic has been found in zerochplus. This affects the function PrintResList of the file test/mordor/thread.res.pl. The manipulation leads to cross site scripting. It is possible to initiate the attack remotely. The patch is named 9ddf9ecca8565341d8d26a3b2f64540bde4fa273. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-218007.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2023-01-11T16:15Z
Repository: https://github.com/zerochplus/zerochplus
Language: Perl
Files changed: test/mordor/thread.res.pl
Commit date: 2013-04-30 09:08:43 +0000
Commit message: パスワード抜きのXSS脆弱性対策

git-svn-id: http://svn.sourceforge.jp/svnroot/zerochplus/zerochplus/trunk@435 567da1b6-7cfc-4bc0-8471-d03287871468

Diff: diff --git a/test/mordor/thread.res.pl b/test/mordor/thread.res.pl
index b7e83e4..aca4f32 100644
--- a/test/mordor/thread.res.pl
+++ b/test/mordor/thread.res.pl
@@ -255,10 +255,19 @@ sub PrintResList
 		$pRes	= $Dat->Get($i);
 		@elem	= split(/<>/, $$pRes);
 		$log = $Logger->Get($logsize - 1 + $i - $lastnum);
 		@logs	= split(/<>/,$log,-1) if (defined $log);
 		
+		foreach (0 .. $#logs) {
+			$logs[$_] =~ s/[\x0d\x0a\0]//g;
+			$logs[$_] =~ s/&/&amp;/g;
+			$logs[$_] =~ s/"/&quot;/g;
+			$logs[$_] =~ s/'/&#39;/g;
+			$logs[$_] =~ s/</&lt;/g;
+			$logs[$_] =~ s/>/&gt;/g;
+		}
+		
 		$Page->Print("<tr><td class=\"Response\" valign=top>");
 		
 		# Xí Éæé\¦}§
 		if ($isAbone) {
 			$Page->Print("<input type=checkbox name=RESS value=$i></td>");

Fixed code: 		foreach (0 .. $#logs) {
			$logs[$_] =~ s/[\x0d\x0a\0]//g;
			$logs[$_] =~ s/&/&amp;/g;
			$logs[$_] =~ s/"/&quot;/g;
			$logs[$_] =~ s/'/&#39;/g;
			$logs[$_] =~ s/</&lt;/g;
			$logs[$_] =~ s/>/&gt;/g;
		}
CVE-2021-29455: Improper Verification of Cryptographic Signature (CWE-347)
value: Grassroot Platform is an application to make it faster, cheaper and easier to persistently organize and mobilize people in low-income communities. Grassroot Platform before master deployment as of 2021-04-16 did not properly verify the signature of JSON Web Tokens when refreshing an existing JWT. This allows to forge a valid JWT. The problem has been patched in version 1.3.1 by deprecating the JWT refresh function, which was an overdue deprecation regardless (the "refresh" flow is no longer used).
CWE description: The product does not verify, or incorrectly verifies, the cryptographic signature for data.
CVSS v3 base score: 5.3
Published: 2021-04-19T19:15Z
Repository: https://github.com/grassrootza/grassroot-platform
Language: Unknown
Commit date: 2021-04-16 16:45:39 +0200
Commit message: Merge pull request #412 from grassrootza/fix/refresh

Removing deprecated refresh function
CVE-2023-41047: Improper Neutralization of Special Elements Used in a Template Engine (CWE-1336)
value: OctoPrint is a web interface for 3D printers. OctoPrint versions up until and including 1.9.2 contain a vulnerability that allows malicious admins to configure a specially crafted GCODE script that will allow code execution during rendering of that script. An attacker might use this to extract data managed by OctoPrint, or manipulate data managed by OctoPrint, as well as execute arbitrary commands with the rights of the OctoPrint process on the server system. OctoPrint versions from 1.9.3 onward have been patched. Administrators of OctoPrint instances are advised to make sure they can trust all other administrators on their instance and to also not blindly configure arbitrary GCODE scripts found online or provided to them by third parties.
CWE description: The product uses a template engine to insert or process externally-influenced input, but it does not neutralize or incorrectly neutralizes special elements or syntax that can be interpreted as template expressions or other code directives when processed by the engine.
CVSS v3 base score: 6.5
Published: 2023-10-09T16:15Z
Repository: https://github.com/OctoPrint/OctoPrint
Language: Unknown
Commit date: 2023-10-09 14:31:21 +0200
Commit message: Merge branch 'bug/gcode_script_vuln' into staging/bugfix
CVE-2024-23637: Improper Authentication (CWE-287)
value: OctoPrint is a web interface for 3D printer.s OctoPrint versions up until and including 1.9.3 contain a vulnerability that allows malicious admins to change the password of other admin accounts, including their own, without having to repeat their password. An attacker who managed to hijack an admin account might use this to lock out actual admins from their OctoPrint instance. The vulnerability will be patched in version 1.10.0.
CWE description: When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.
CVSS v3 base score: 4.9
Published: 2024-01-31T18:15Z
Repository: https://github.com/OctoPrint/OctoPrint
Language: Unknown
Commit date: 2024-01-31 13:10:40 +0100
Commit message: Merge branch 'fix/reauthenticate' into maintenance
CVE-2014-7192: Improper Control of Generation of Code ('Code Injection') (CWE-94)
value: Eval injection vulnerability in index.js in the syntax-error package before 1.1.1 for Node.js 0.10.x, as used in IBM Rational Application Developer and other products, allows remote attackers to execute arbitrary code via a crafted file.
CWE description: The product 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.
Published: 2014-12-11T11:59Z
Repository: https://github.com/substack/node-syntax-error
Language: JavaScript
Files changed: index.js, test/sources/run2.js
Commit date: 2014-07-14 19:52:00 -0700
Commit message: use eval() with early throw instead of Function() to prevent script injection

Diff: diff --git a/index.js b/index.js
index 43dbdf4..9acae6b 100644
--- a/index.js
+++ b/index.js
@@ -2,14 +2,15 @@ var esprima = require('esprima-fb');
 
 module.exports = function (src, file) {
     if (typeof src !== 'string') src = String(src);
     
     try {
-        Function(src);
+        eval('throw "STOP"; (function () { ' + src + '})()');
         return;
     }
     catch (err) {
+        if (err === 'STOP') return undefined;
         if (err.constructor.name !== 'SyntaxError') throw err;
         return errorInfo(src, file);
     }
 };
 
diff --git a/test/sources/run2.js b/test/sources/run2.js
index f301d32..88c7b94 100644
--- a/test/sources/run2.js
+++ b/test/sources/run2.js
@@ -1 +1,3 @@
-}); process.exit(1); (function () {
+})();
+process.exit(1);
+(function () {

Vulnerable code:         Function(src);
}); process.exit(1); (function () {
Fixed code:         eval('throw "STOP"; (function () { ' + src + '})()');
        if (err === 'STOP') return undefined;
})();
process.exit(1);
(function () {
CVE-2016-15030: URL Redirection to Untrusted Site ('Open Redirect') (CWE-601)
value: A vulnerability classified as problematic has been found in Arno0x TwoFactorAuth. This affects an unknown part of the file login/login.php. The manipulation of the argument from leads to open redirect. It is possible to initiate the attack remotely. This product does not use versioning. This is why information about affected and unaffected releases are unavailable. The patch is named 8549ad3cf197095f783643e41333586d6a4d0e54. It is recommended to apply a patch to fix this issue. The associated identifier of this vulnerability is VDB-223803.
CWE description: 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.
CVSS v3 base score: 6.1
Published: 2023-03-25T18:15Z
Repository: https://github.com/Arno0x/TwoFactorAuth
Language: PHP
Files changed: login/login.php
Commit date: 2016-01-27 17:15:48 -0500
Commit message: cross-site ?from can be used for phishing

Using cross-site ?from, the user can be presented with a fake "auth failed" page, which will trick them into logging in again. Since they are now on a different site, the site can capture their user, password, and current token in order to steal their access to the real site.
Diff: diff --git a/login/login.php b/login/login.php
index 7cde8dd..5c0b439 100644
--- a/login/login.php
+++ b/login/login.php
@@ -82,12 +82,16 @@ else {
 	        $_SESSION["username"] = $username;
 	        $_SESSION["isAdmin"] = ($isAdmin === 1)? true: false;
 	        
 	        //--------------------------------------------------
 	        // Checking which URL we should redirect the user to
-	        if (isset($_POST["from"])) {
-	        	$from = urldecode($_POST["from"]);
+	        if (isset($_GET['from'])) {
+	        	$from = $_GET['from'];
+			if (preg_match('#^(?:https?:)?//#', $_GET['from'], $m)) {
+				$url = parse_url($_GET['from']);
+				$from = $url['path'] . (!empty($url['query']) ? '?' . $url['query'] : '') . (!empty($url['fragment']) ? '#' . $url['fragment'] : '');
+			}
 	            $redirectTo = ((isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] === "on")? "https://" : "http://").$_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$from;
 	        }
 	        else {
 	            $redirectTo = AUTH_SUCCEED_REDIRECT_URL;
 	        }

Vulnerable code: 	        if (isset($_POST["from"])) {
	        	$from = urldecode($_POST["from"]);
Fixed code: 	        if (isset($_GET['from'])) {
	        	$from = $_GET['from'];
			if (preg_match('#^(?:https?:)?//#', $_GET['from'], $m)) {
				$url = parse_url($_GET['from']);
				$from = $url['path'] . (!empty($url['query']) ? '?' . $url['query'] : '') . (!empty($url['fragment']) ? '#' . $url['fragment'] : '');
			}
CVE-2015-20108: Improper Neutralization of Special Elements used in a Command ('Command Injection') (CWE-77)
value: xml_security.rb in the ruby-saml gem before 1.0.0 for Ruby allows XPath injection and code execution because prepared statements are not used.
CWE description: 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.
CVSS v3 base score: 9.8
Published: 2023-05-27T19:15Z
Repository: https://github.com/SAML-Toolkits/ruby-saml
Language: Ruby
Files changed: lib/xml_security.rb
Commit date: 2015-04-29 17:25:00 +0200
Commit message: Fix possible xpath injection

Diff: diff --git a/lib/xml_security.rb b/lib/xml_security.rb
index 6de836a..b1867ba 100644
--- a/lib/xml_security.rb
+++ b/lib/xml_security.rb
@@ -254,11 +254,11 @@ module XMLSecurity
 
       # check digests
       REXML::XPath.each(@sig_element, "//ds:Reference", {"ds"=>DSIG}) do |ref|
         uri = ref.attributes.get_attribute("URI").value
 
-        hashed_element = document.at_xpath("//*[@ID='#{uri[1..-1]}']")
+        hashed_element = document.at_xpath("//*[@ID=$uri]", nil, { 'uri' => uri[1..-1] })
         canon_algorithm = canon_algorithm REXML::XPath.first(
           ref,
           '//ds:CanonicalizationMethod',
           { "ds" => DSIG }
         )

Vulnerable code:         hashed_element = document.at_xpath("//*[@ID='#{uri[1..-1]}']")
Fixed code:         hashed_element = document.at_xpath("//*[@ID=$uri]", nil, { 'uri' => uri[1..-1] })
CVE-2013-3081: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection') (CWE-89)
value: SQL injection vulnerability in the checkEmailFormat function in plugins/jojo_core/classes/Jojo.php in Jojo before 1.2.2 allows remote attackers to execute arbitrary SQL commands via the X-Forwarded-For HTTP header to /articles/test/.
CWE description: The product 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. Without sufficient removal or quoting of SQL syntax in user-controllable inputs, the generated SQL query can cause those inputs to be interpreted as SQL instead of ordinary user data.
Published: 2014-06-09T19:55Z
Repository: https://github.com/JojoCMS/Jojo-CMS
Language: PHP
Files changed: plugins/jojo_core/classes/Jojo.php
Commit date: 2013-05-07 11:09:47 +1200
Commit message: Fix SQL injection issue CVE-2013-3081

Diff: diff --git a/plugins/jojo_core/classes/Jojo.php b/plugins/jojo_core/classes/Jojo.php
index c61e1af..c47c5db 100755
--- a/plugins/jojo_core/classes/Jojo.php
+++ b/plugins/jojo_core/classes/Jojo.php
@@ -2459,18 +2459,22 @@ class Jojo {
     }
 
     /* Gets the IP address of the visitor, bypassing proxies */
     static function getIp()
     {
+        $ip = false;
         if ( (getenv('HTTP_X_FORWARDED_FOR') != '') && (strtolower(getenv('HTTP_X_FORWARDED_FOR')) != 'unknown')) {
             $iparray = explode(',', getenv('HTTP_X_FORWARDED_FOR'));
-            return $iparray[0];
+            $ip = $iparray[0];
         } elseif (getenv('REMOTE_ADDR') != '') {
-            return getenv('REMOTE_ADDR');
-        } else {
-            return false;
+            $ip = getenv('REMOTE_ADDR');
         }
+        /* check IP is valid format */
+        if (preg_match('/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/', $ip)) {
+        	return $ip;
+        }
+        return false;
     }
 
     /* reads the user agent string and gives the browser type - quick and simple detection */
     static function getBrowser()
     {

Vulnerable code:             return $iparray[0];
            return getenv('REMOTE_ADDR');
        } else {
            return false;
Fixed code:         $ip = false;
            $ip = $iparray[0];
            $ip = getenv('REMOTE_ADDR');
        /* check IP is valid format */
        if (preg_match('/\\b(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\b/', $ip)) {
        	return $ip;
        }
        return false;
CVE-2024-32035: Insufficient Information (NVD-CWE-noinfo)
value: ImageSharp is a 2D graphics API. A vulnerability discovered in the ImageSharp library, where the processing of specially crafted files can lead to excessive memory usage in image decoders. The vulnerability is triggered when ImageSharp attempts to process image files that are designed to exploit this flaw.  This flaw can be exploited to cause a denial of service (DoS) by depleting process memory, thereby affecting applications and services that rely on ImageSharp for image processing tasks. Users and administrators are advised to update to the latest version of ImageSharp that addresses this vulnerability to mitigate the risk of exploitation. The problem has been patched in v3.1.4 and v2.1.8.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-04-15T20:15Z
Repository: https://github.com/SixLabors/ImageSharp
Language: Unknown
Commit date: 2024-04-11 00:16:16 +0200
Commit message: Merge pull request #2706 from SixLabors/af/memlimit-01

Limit all memory allocations in the MemoryAllocator layer
CVE-2024-32036: Insufficient Information (NVD-CWE-noinfo)
value: ImageSharp is a 2D graphics API. A data leakage flaw was found in ImageSharp's JPEG and TGA decoders. This vulnerability is triggered when an attacker passes a specially crafted JPEG or TGA image file to a software using ImageSharp, potentially disclosing sensitive information from other parts of the software in the resulting image buffer. The problem has been patched in v3.1.4 and v2.1.8.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-04-15T20:15Z
Repository: https://github.com/SixLabors/ImageSharp
Language: Unknown
Commit date: 2024-04-11 00:21:58 +0200
Commit message: Merge pull request #2716 from SixLabors/js/clear-buffers

Clear Pixel Buffers on Decode.
CVE-2024-41131: Insufficient Information (NVD-CWE-noinfo)
value: ImageSharp is a 2D graphics API. An Out-of-bounds Write vulnerability has been found in the ImageSharp gif decoder, allowing attackers to cause a crash using a specially crafted gif. This can potentially lead to denial of service. All users are advised to upgrade to v3.1.5 or v2.1.9.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-07-22T15:15Z
Repository: https://github.com/SixLabors/ImageSharp
Language: Unknown
Commit date: 2024-06-21 08:53:24 +1000
Commit message: Merge pull request #2754 from SixLabors/backport-v3/gif-lzw

v3 - Backport. Handle out of bounds Gif LZW max code
CVE-2024-41132: Insufficient Information (NVD-CWE-noinfo)
value: ImageSharp is a 2D graphics API. A vulnerability discovered in the ImageSharp library, where the processing of specially crafted files can lead to excessive memory usage in the Gif decoder. The vulnerability is triggered when ImageSharp attempts to process image files that are designed to exploit this flaw. All users are advised to upgrade to v3.1.5 or v2.1.9.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-07-22T15:15Z
Repository: https://github.com/SixLabors/ImageSharp
Language: Unknown
Commit date: 2024-07-07 16:40:08 +1000
Commit message: Merge pull request #2764 from SixLabors/js/v4-merge-2758-fix

v4 Fix 2758
CVE-2024-41132: Insufficient Information (NVD-CWE-noinfo)
value: ImageSharp is a 2D graphics API. A vulnerability discovered in the ImageSharp library, where the processing of specially crafted files can lead to excessive memory usage in the Gif decoder. The vulnerability is triggered when ImageSharp attempts to process image files that are designed to exploit this flaw. All users are advised to upgrade to v3.1.5 or v2.1.9.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
Published: 2024-07-22T15:15Z
Repository: https://github.com/SixLabors/ImageSharp
Language: Unknown
Commit date: 2024-07-07 16:09:22 +1000
Commit message: Merge pull request #2759 from SixLabors/js/fix-2758

v3.1.x Fix 2758
CVE-2023-48707: Cleartext Storage of Sensitive Information (CWE-312)
value: CodeIgniter Shield is an authentication and authorization provider for CodeIgniter 4. The `secretKey` value is an important key for HMAC SHA256 authentication and in affected versions was stored in the database in cleartext form. If a malicious person somehow had access to the data in the database, they could use the key and secretKey for HMAC SHA256 authentication to send requests impersonating that corresponding user. This issue has been addressed in version 1.0.0-beta.8. Users are advised to upgrade. There are no known workarounds for this vulnerability.
CWE description: The product stores sensitive information in cleartext within a resource that might be accessible to another control sphere.
CVSS v3 base score: 6.5
Published: 2023-11-24T18:15Z
Repository: https://github.com/codeigniter4/shield
Language: Unknown
Commit date: 2023-11-23 08:22:00 +0900
Commit message: Merge pull request from GHSA-v427-c49j-8w6x

fix: Cleartext Storage of Sensitive Information in HMAC SHA256 Authentication
CVE-2023-48708: Insertion of Sensitive Information into Log File (CWE-532)
value: CodeIgniter Shield is an authentication and authorization provider for CodeIgniter 4. In affected versions successful login attempts are recorded with the raw tokens stored in the log table. If a malicious person somehow views the data in the log table they can obtain a raw token which can then be used to send a request with that user's authority. This issue has been addressed in version 1.0.0-beta.8. Users are advised to upgrade. Users unable to upgrade should disable logging for successful login attempts by the configuration files.
CWE description: Information written to log files can be of a sensitive nature and give valuable guidance to an attacker or expose sensitive user information.
CVSS v3 base score: 6.5
Published: 2023-11-24T18:15Z
Repository: https://github.com/codeigniter4/shield
Language: Unknown
Commit date: 2023-11-23 08:32:26 +0900
Commit message: Merge pull request from GHSA-j72f-h752-mx4w

fix: raw token logging
CVE-2020-19491: Out-of-bounds Write (CWE-787)
value: There is an invalid memory access bug in cgif.c that leads to a Segmentation fault in sam2p 0.49.4. A crafted input will lead to a denial of service or possibly unspecified other impact.
CWE description: The product writes data past the end, or before the beginning, of the intended buffer.
CVSS v3 base score: 7.8
Published: 2021-07-21T18:15Z
Repository: https://github.com/pts/sam2p
Language: C
Files changed: cgif.c
Commit date: 2019-07-18 16:56:16 +0200
Commit message: fixed segfault in GIF reading; this fixes https://github.com/pts/sam2p/issues/67

Diff: diff --git a/cgif.c b/cgif.c
index 96f3ea1..7c2cb7c 100644
--- a/cgif.c
+++ b/cgif.c
@@ -1549,11 +1549,12 @@ int CGIFFF DGifSlurp(CGIFFF GifFileType *GifFile)
   			  ep->ByteCount = ExtData[0];
 			  ep->Bytes = (GifByteType *)xmalloc(ep->ByteCount * sizeof(GifByteType));
   			  memcpy(ep->Bytes,ExtData,ep->ByteCount * sizeof(char));
   			#else
   			  if (ExtData==NULL) break;
-  			  AddExtensionBlock(sp, ExtData[0], ExtData+1);
+                          AddExtensionBlock(&ext, ExtData[0], ExtData+1);
+                          ext.ExtensionBlocks[ext.ExtensionBlockCount-1].code=ext_code;
   			#endif
 		    }
 		}
 		break;
 

Vulnerable code:   			  AddExtensionBlock(sp, ExtData[0], ExtData+1);
Fixed code:                           AddExtensionBlock(&ext, ExtData[0], ExtData+1);
                          ext.ExtensionBlocks[ext.ExtensionBlockCount-1].code=ext_code;
CVE-2020-19492: Insufficient Information (NVD-CWE-noinfo)
value: There is a floating point exception in ReadImage that leads to a Segmentation fault in sam2p 0.49.4. A crafted input will lead to a denial of service or possibly unspecified other impact.
CWE description: There is insufficient information about the issue to classify it; details are unkown or unspecified.
CVSS v3 base score: 7.8
Published: 2021-07-21T18:15Z
Repository: https://github.com/pts/sam2p
Language: Other
Files changed: input-tga.ci
Commit date: 2019-07-18 17:09:40 +0200
Commit message: improved error reporting for 0-width in TGA loading; this fixes https://github.com/pts/sam2p/issues/66

Diff: diff --git a/input-tga.ci b/input-tga.ci
index 6185527..be6515d 100644
--- a/input-tga.ci
+++ b/input-tga.ci
@@ -450,11 +450,11 @@ ReadImage (FILE              *fp,
     }
   else
 	  pelbytes = 3;
 
   wh = (unsigned)width * height;
-  if (wh / width != height) {
+  if (width != 0 && wh / width != height) {
    idl_error:
     FATALP("TGA: image dimensions too large");
   }
   wh3 = 3U * wh;
   if (wh3 / 3 != wh) goto idl_error;

Vulnerable code:   if (wh / width != height) {
Fixed code:   if (width != 0 && wh / width != height) {