ByteDance/PatchEval huggingface dataset:
CVE-2024-5823 (Python)

The application exposes an online update operation in the ChuanhuChatGPT UI that can reach the repository update routine and modify application/configuration files without verifying that the caller is an authenticated administrator. An attacker who can access the Gradio web interface, including a request with no user identity or a non-admin identity, may trigger the update action and cause the updater to overwrite files that affect application behavior. This can lead to unauthorized configuration or code changes and may disrupt normal service operation.

Weakness:
CWE-610: name: Externally Controlled Reference to a Resource in Another Sphere
description: The product uses an externally controlled name or reference that resolves to a resource that is outside of the intended control sphere.

Repository: https://github.com/gaizhenbiao/chuanhuchatgpt

Vulnerable code:
file_path: modules/utils.py
snippet: def update_chuanhu():
    from .repo import background_update

    print("[Updater] Trying to update...")
    update_status = background_update()
    if update_status == "success":
        logging.info("Successfully updated, restart needed")
        status = '<span id="update-status" class="hideK">success</span>'
        return gr.Markdown(value=i18n("\u66f4\u65b0\u6210\u529f\uff0c\u8bf7\u91cd\u542f\u672c\u7a0b\u5e8f") + status)
    else:
        status = '<span id="update-status" class="hideK">failure</span>'
        return gr.Markdown(
            value=i18n(
                "\u66f4\u65b0\u5931\u8d25\uff0c\u8bf7\u5c1d\u8bd5[\u624b\u52a8\u66f4\u65b0](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/\u4f7f\u7528\u6559\u7a0b#\u624b\u52a8\u66f4\u65b0)"
            )
            + status
        )

Fixed code:
file_path: ChuanhuChatbot.py
snippet:         [user_name],

file_path: modules/utils.py
snippet: def update_chuanhu(username):
    if username not in admin_list:
        return gr.Markdown(value=i18n("no_permission_to_update_description"))
    from .repo import background_update

    print("[Updater] Trying to update...")
    update_status = background_update()
    if update_status == "success":
        logging.info("Successfully updated, restart needed")
        status = '<span id="update-status" class="hideK">success</span>'
        return gr.Markdown(value=i18n("\u66f4\u65b0\u6210\u529f\uff0c\u8bf7\u91cd\u542f\u672c\u7a0b\u5e8f") + status)
    else:
        status = '<span id="update-status" class="hideK">failure</span>'
        return gr.Markdown(
            value=i18n(
                "\u66f4\u65b0\u5931\u8d25\uff0c\u8bf7\u5c1d\u8bd5[\u624b\u52a8\u66f4\u65b0](https://github.com/GaiZhenbiao/ChuanhuChatGPT/wiki/\u4f7f\u7528\u6559\u7a0b#\u624b\u52a8\u66f4\u65b0)"
            )
            + status
        )

file_path: modules/utils.py
snippet: from modules.config import retrieve_proxy, hide_history_when_not_logged_in, admin_list
CVE-2022-0691 (JavaScript)

Authorization Bypass Through User-Controlled Key in NPM url-parse prior to 1.5.9.

Weakness:
CWE-862: name: Missing Authorization
description: The product does not perform an authorization check when an actor attempts to access a resource or perform an action.
CWE-639: name: Authorization Bypass Through User-Controlled Key
description: The system's authorization functionality does not prevent one user from gaining access to another user's data or record by modifying the key value identifying the data.

Repository: https://github.com/unshiftio/url-parse

Vulnerable code:
file_path: index.js
snippet: var required = require('requires-port')
  , qs = require('querystringify')
  , CRHTLF = /[\n\r\t]/g
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
  , windowsDriveLetter = /^[a-zA-Z]:/
  , whitespace = /^[ \f\n\r\t\v\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;

Fixed code:
file_path: index.js
snippet: var required = require('requires-port')
  , qs = require('querystringify')
  , CRHTLF = /[\n\r\t]/g
  , slashes = /^[A-Za-z][A-Za-z0-9+-.]*:\/\//
  , protocolre = /^([a-z][a-z0-9.+-]*:)?(\/\/)?([\\/]+)?([\S\s]*)/i
  , windowsDriveLetter = /^[a-zA-Z]:/
  , whitespace = /^[\x00-\x20\u00a0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000\ufeff]+/;
CVE-2020-26226 (JavaScript)

In the npm package semantic-release before version 17.2.3, secrets that would normally be masked by `semantic-release` can be accidentally disclosed if they contain characters that become encoded when included in a URL. Secrets that do not contain characters that become encoded when included in a URL are already masked properly. The issue is fixed in version 17.2.3.

Weakness:
CWE-116: name: Improper Encoding or Escaping of Output
description: The product prepares a structured message for communication with another component, but encoding or escaping of the data is either missing or done incorrectly. As a result, the intended structure of the message is not preserved.

Repository: https://github.com/semantic-release/semantic-release

Vulnerable code:
file_path: lib/hide-sensitive.js
snippet: module.exports = (env) => {
  const toReplace = Object.keys(env).filter((envVar) => {
    // https://github.com/semantic-release/semantic-release/issues/1558
    if (envVar === 'GOPRIVATE') {
      return false;
    }

    return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;
  });

  const regexp = new RegExp(toReplace.map((envVar) => escapeRegExp(env[envVar])).join('|'), 'g');
  return (output) =>
    output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
};

Fixed code:
file_path: lib/hide-sensitive.js
snippet: module.exports = (env) => {
  const toReplace = Object.keys(env).filter((envVar) => {
    // https://github.com/semantic-release/semantic-release/issues/1558
    if (envVar === 'GOPRIVATE') {
      return false;
    }

    return /token|password|credential|secret|private/i.test(envVar) && size(env[envVar].trim()) >= SECRET_MIN_SIZE;
  });

  const regexp = new RegExp(
    toReplace
      .map((envVar) => `${escapeRegExp(env[envVar])}|${encodeURI(escapeRegExp(env[envVar]))}`)
      .join('|'),
    'g'
  );
  return (output) =>
    output && isString(output) && toReplace.length > 0 ? output.toString().replace(regexp, SECRET_REPLACEMENT) : output;
};
CVE-2024-39877 (Python)

Apache Airflow's DAG documentation handling treats the DAG author-controlled `doc_md` value as template input and can render it with unsafe Jinja behavior during DAG parsing or scheduler-side processing. An authenticated DAG author can supply malicious documentation content, whether as inline markdown or documentation loaded from a markdown file, that abuses template evaluation to reach Python objects and execute arbitrary code or system commands in the scheduler context. This violates Airflow's security model by allowing DAG authors to escape the intended DAG author privilege boundary and affect scheduler-side files, secrets, credentials, or host state.

Weakness:
CWE-94: name: Improper Control of Generation of Code ('Code Injection')
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.
CWE-77: name: Improper Neutralization of Special Elements used in a Command ('Command Injection')
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.
CWE-78: name: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

Repository: https://github.com/apache/airflow

Vulnerable code:
file_path: airflow/models/dag.py
snippet:     def get_doc_md(self, doc_md: str | None) -> str | None:
        if doc_md is None:
            return doc_md

        env = self.get_template_env(force_sandboxed=True)

        if not doc_md.endswith(".md"):
            template = jinja2.Template(doc_md)
        else:
            try:
                template = env.get_template(doc_md)
            except jinja2.exceptions.TemplateNotFound:
                return f"""
                # Templating Error!
                Not able to find the template file: `{doc_md}`.
                """

        return template.render()

Fixed code:
file_path: airflow/models/dag.py
snippet:     def get_doc_md(self, doc_md: str | None) -> str | None:
        if doc_md is None:
            return doc_md

        if doc_md.endswith(".md"):
            try:
                return open(doc_md).read()
            except FileNotFoundError:
                return doc_md

        return doc_md
CVE-2022-3298 (Python)

Allocation of Resources Without Limits or Throttling in GitHub repository ikus060/rdiffweb prior to 2.4.8.

Weakness:
CWE-770: name: Allocation of Resources Without Limits or Throttling
description: The product allocates a reusable resource or group of resources on behalf of an actor without imposing any restrictions on the size or number of resources that can be allocated, in violation of the intended security policy for that actor.

Repository: https://github.com/ikus060/rdiffweb

Vulnerable code:
file_path: rdiffweb/controller/pref_sshkeys.py
snippet: class SshForm(CherryForm):
    title = StringField(
        _('Title'),
        description=_('The title is an optional description to identify the key. e.g.: bob@thinkpad-t530'),
        validators=[validators.data_required()],
    )
    key = StringField(
        _('Key'),
        widget=TextArea(),
        description=_(
            "Enter a SSH public key. It should start with 'ssh-dss', 'ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384' or 'ecdsa-sha2-nistp521'."
        ),
        validators=[validators.data_required(), validate_key],
    )
    fingerprint = StringField('Fingerprint')

Fixed code:
file_path: rdiffweb/controller/pref_sshkeys.py
snippet: class SshForm(CherryForm):
    title = StringField(
        _('Title'),
        description=_('The title is an optional description to identify the key. e.g.: bob@thinkpad-t530'),
        validators=[
            validators.data_required(),
            validators.length(
                max=256,
                message=_('Title too long.'),
            ),
        ],
    )
    key = StringField(
        _('Key'),
        widget=TextArea(),
        description=_(
            "Enter a SSH public key. It should start with 'ssh-dss', 'ssh-ed25519', 'ssh-rsa', 'ecdsa-sha2-nistp256', 'ecdsa-sha2-nistp384' or 'ecdsa-sha2-nistp521'."
        ),
        validators=[validators.data_required(), validate_key],
    )
    fingerprint = StringField('Fingerprint')
CVE-2021-21321 (JavaScript)

fastify-reply-from is an npm package which is a fastify plugin to forward the current http request to another server. In fastify-reply-from before version 4.0.2, by crafting a specific URL, it is possible to escape the prefix of the proxied backend service. If the base url of the proxied server is "/pub/", a user expect that accessing "/priv" on the target service would not be possible. In affected versions, it is possible. This is fixed in version 4.0.2.

Weakness:
CWE-20: name: Improper Input Validation
description: The product receives input or data, but it does
        not validate or incorrectly validates that the input has the
        properties that are required to process the data safely and
        correctly.

Repository: https://github.com/fastify/fastify-reply-from

Vulnerable code:
file_path: lib/utils.js
snippet: function buildURL (source, reqBase) {
  const dest = new URL(source, reqBase)

  // if base is specified, source url should not override it
  if (reqBase && !reqBase.startsWith(dest.origin)) {
    throw new Error('source must be a relative path string')
  }

  return dest
}

Fixed code:
file_path: lib/utils.js
snippet: function buildURL (source, reqBase) {
  const dest = new URL(source, reqBase)

  // if base is specified, source url should not override it
  if (reqBase) {
    if (!reqBase.endsWith('/') && dest.href.length > reqBase.length) {
      reqBase = reqBase + '/'
    }

    if (!dest.href.startsWith(reqBase)) {
      throw new Error('source must be a relative path string')
    }
  }

  return dest
}
CVE-2020-15233 (Go)

ORY Fosite OAuth2 redirect URI validation permits overly broad matching for native-app loopback redirects. A requested loopback redirect URI can be accepted even when it changes security-relevant parts of a registered redirect URI, including host or address-family, path case, or query parameters. An attacker with access to the loopback interface can use a crafted authorization request to override the registered redirect target or attach attacker-controlled query parameters during an OAuth flow.

Weakness:
CWE-601: name: URL Redirection to Untrusted Site ('Open Redirect')
description: The web application accepts a user-controlled input that specifies a link to an external site, and uses that link in a redirect.

Repository: https://github.com/ory/fosite

Vulnerable code:
file_path: authorize_helper.go
snippet: func isMatchingRedirectURI(uri string, haystack []string) bool {
	requested, err := url.Parse(uri)
	if err != nil {
		return false
	}

	for _, b := range haystack {
		if strings.ToLower(b) == strings.ToLower(uri) || isLoopbackURI(requested, b) {
			return true
		}
	}
	return false
}

file_path: authorize_helper.go
snippet: func isLoopbackURI(requested *url.URL, registeredURI string) bool {
	registered, err := url.Parse(registeredURI)
	if err != nil {
		return false
	}

	if registered.Scheme != "http" || !isLoopbackAddress(registered.Host) {
		return false
	}

	if requested.Scheme == "http" && isLoopbackAddress(requested.Host) && registered.Path == requested.Path {
		return true
	}

	return false
}

Fixed code:
file_path: authorize_helper.go
snippet: func isMatchingRedirectURI(uri string, haystack []string) bool {
	requested, err := url.Parse(uri)
	if err != nil {
		return false
	}

	for _, b := range haystack {
		if b == uri || isMatchingAsLoopback(requested, b) {
			return true
		}
	}
	return false
}

file_path: authorize_helper.go
snippet: func isMatchingAsLoopback(requested *url.URL, registeredURI string) bool {
	registered, err := url.Parse(registeredURI)
	if err != nil {
		return false
	}

	// Native apps that are able to open a port on the loopback network
	// interface without needing special permissions (typically, those on
	// desktop operating systems) can use the loopback interface to receive
	// the OAuth redirect.
	//
	// Loopback redirect URIs use the "http" scheme and are constructed with
	// the loopback IP literal and whatever port the client is listening on.
	//
	// Source: https://tools.ietf.org/html/rfc8252#section-7.3
	if requested.Scheme == "http" &&
		isLoopbackAddress(requested.Host) &&
		registered.Hostname() == requested.Hostname() &&
		// The port is skipped here - see codedoc above!
		registered.Path == requested.Path &&
		registered.RawQuery == requested.RawQuery {
		return true
	}

	return false
}
CVE-2020-7795 (JavaScript)

The package get-npm-package-version before 1.0.7 are vulnerable to Command Injection via main function in index.js.

Weakness:
CWE-94: name: Improper Control of Generation of Code ('Code Injection')
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.
CWE-77: name: Improper Neutralization of Special Elements used in a Command ('Command Injection')
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.
CWE-78: name: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

Repository: https://github.com/hoperyy/get-npm-package-version

Vulnerable code:
file_path: index.js
snippet: module.exports = function (packageName, { registry = '', timeout = null } = {}) {
    try {
        let version;

        const config = {
            stdio: ['pipe', 'pipe', 'ignore']
        };

        if (timeout) {
            config.timeout = timeout;
        }

        if (registry) {
            version = require('child_process').execSync(`npm view ${packageName} version --registry ${registry}`, config);
        } else {
            version = require('child_process').execSync(`npm view ${packageName} version`, config);
        }

        if (version) {
            return version.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
        } else {
            return null;
        }

    } catch(err) {
        return null;
    }
}

Fixed code:
file_path: index.js
snippet: module.exports = function (packageName, { registry = '', timeout = null } = {}) {
    try {
        if (/[`$&{}[;|]/g.test(packageName) || /[`$&{}[;|]/g.test(registry)) {
            return null
        }
        let version;

        const config = {
            stdio: ['pipe', 'pipe', 'ignore']
        };

        if (timeout) {
            config.timeout = timeout;
        }

        if (registry) {
            version = require('child_process').execSync(`npm view ${packageName} version --registry ${registry}`, config);
        } else {
            version = require('child_process').execSync(`npm view ${packageName} version`, config);
        }

        if (version) {
            return version.toString().trim().replace(/^\n*/, '').replace(/\n*$/, '');
        } else {
            return null;
        }

    } catch(err) {
        return null;
    }
}
CVE-2022-39286 (Python)

Jupyter Core is a package for the core common functionality of Jupyter projects. Jupyter Core prior to version 4.11.2 contains an arbitrary code execution vulnerability in `jupyter_core` that stems from `jupyter_core` executing untrusted files in CWD. This vulnerability allows one user to run code as another. Version 4.11.2 contains a patch for this issue. There are no known workarounds.

Weakness:
CWE-285: name: Improper Authorization
description: The product does not perform or incorrectly performs an authorization check when an actor attempts to access a resource or perform an action.
CWE-250: name: Execution with Unnecessary Privileges
description: The product performs an operation at a privilege level that is higher than the minimum level required, which creates new weaknesses or amplifies the consequences of other weaknesses.
CWE-269: name: Improper Privilege Management
description: The product does not properly assign, modify, track, or check privileges for an actor, creating an unintended sphere of control for that actor.

Repository: https://github.com/jupyter/jupyter_core

Vulnerable code:
file_path: jupyter_core/application.py
snippet:     def config_file_paths(self):
        path = jupyter_config_path()
        if self.config_dir not in path:
            path.insert(0, self.config_dir)
        path.insert(0, os.getcwd())
        return path

Fixed code:
file_path: jupyter_core/application.py
snippet:     def config_file_paths(self):
        path = jupyter_config_path()
        if self.config_dir not in path:
            # Insert config dir as first item.
            path.insert(0, self.config_dir)
        return path
CVE-2020-7631 (JavaScript)

diskusage-ng through 0.2.4 is vulnerable to Command Injection.It allows execution of arbitrary commands via the path argument.

Weakness:
CWE-78: name: Improper Neutralization of Special Elements used in an OS Command ('OS Command Injection')
description: The product constructs all or part of an OS command using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify the intended OS command when it is sent to a downstream component.

Repository: https://github.com/iximiuz/node-diskusage-ng

Vulnerable code:
file_path: lib/posix.js
snippet: function diskusage(path, cb) {
    if (path.indexOf('"') !== -1) {
        return cb(new Error('Paths with double quotes are not supported yet'));
    }

    exec('df -k "' + path + '"', function(err, stdout) {
        if (err) {
            return cb(err);
        }

        try {
            cb(null, parse(stdout));
        } catch (e) {
            cb(e);
        }
    });
}

Fixed code:
file_path: lib/posix.js
snippet: function diskusage(path, cb) {
    execFile('df', ['-k', path], function(err, stdout) {
        if (err) {
            return cb(err);
        }

        try {
            cb(null, parse(stdout));
        } catch (e) {
            cb(e);
        }
    });
}

file_path: lib/posix.js
snippet: var execFile = require('child_process').execFile;
CVE-2022-1992 (Go)

Path Traversal in GitHub repository gogs/gogs prior to 0.12.9.

Weakness:
CWE-73: name: External Control of File Name or Path
description: The product allows user input to control or influence paths or file names that are used in filesystem operations.
CWE-22: name: Improper Limitation of a Pathname to a Restricted Directory ('Path Traversal')
description: 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.

Repository: https://github.com/gogs/gogs

Vulnerable code:
file_path: internal/pathutil/pathutil.go
snippet: func Clean(p string) string {
	return strings.Trim(path.Clean("/"+p), "/")
}

Fixed code:
file_path: internal/pathutil/pathutil.go
snippet: func Clean(p string) string {
	p = strings.ReplaceAll(p, `\`, "/")
	return strings.Trim(path.Clean("/"+p), "/")
}
CVE-2023-45809 (Python)

Wagtail's admin user-account bulk action views can disclose information about selected user accounts to authenticated admin users who have access to the Wagtail admin but do not have permission to add, change, or delete users. A low-privileged editor can directly request user bulk-action URLs and supply arbitrary user IDs in the query parameters. This issue is not limited to deleting users; any user-account bulk action that renders a confirmation, error, no-access, or other response for selected users can become an information-disclosure path, including actions such as deletion, changing active status, or assigning roles. Even when the requested action is not performed, the response may reveal readable account identifiers such as display names, usernames, email addresses, or full names, allowing unauthorized enumeration or discovery of user identities.

Weakness:
CWE-532: name: Insertion of Sensitive Information into Log File
description: The product writes sensitive information to a log file.

Repository: https://github.com/wagtail/wagtail

Vulnerable code:
file_path: wagtail/users/views/bulk_actions/user_bulk_action.py
snippet: 
class UserBulkAction(BulkAction):
    models = [get_user_model()]

Fixed code:
file_path: wagtail/users/views/bulk_actions/user_bulk_action.py
snippet: User = get_user_model()


class UserBulkAction(PermissionCheckedMixin, BulkAction):
    models = [User]
    permission_policy = ModelPermissionPolicy(User)
    any_permission_required = ["add", "change", "delete"]