ByteDance/PatchEval huggingface dataset:
CVE-2022-24825 (Go)

Smokescreen is a simple HTTP proxy that fogs over naughty URLs. The primary use case for Smokescreen is to prevent server-side request forgery (SSRF) attacks in which external attackers leverage the behavior of applications to connect to or scan internal infrastructure. Smokescreen also offers an option to deny access to additional (e.g., external) URLs by way of a deny list. There was an issue in Smokescreen that made it possible to bypass the deny list feature by appending a dot to the end of user-supplied URLs, or by providing input in a different letter case. Recommended to upgrade Smokescreen to version 0.0.3 or later.

Weakness:
CWE-918: name: Server-Side Request Forgery (SSRF)
description: 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.

Repository: https://github.com/stripe/smokescreen

Vulnerable code:
file_path: pkg/smokescreen/acl/v1/acl.go
snippet: func (acl *ACL) ValidateDomains(domains []string) error {
	for _, d := range domains {
		if d == "" {
			return fmt.Errorf("glob cannot be empty")
		}

		if !strings.HasPrefix(d, "*.") && strings.HasPrefix(d, "*") {
			return fmt.Errorf("%v: domain glob must represent a full prefix (sub)domain", d)
		}

		domainToCheck := strings.TrimPrefix(d, "*")
		if strings.Contains(domainToCheck, "*") {
			return fmt.Errorf("%v: domain globs are only supported as prefix", d)
		}
	}
	return nil
}

file_path: pkg/smokescreen/acl/v1/acl.go
snippet: func hostMatchesGlob(host string, domainGlob string) bool {
	if domainGlob != "" && domainGlob[0] == '*' {
		suffix := domainGlob[1:]
		if strings.HasSuffix(host, suffix) {
			return true
		}
	} else if domainGlob == host {
		return true
	}
	return false
}

Fixed code:
file_path: pkg/smokescreen/acl/v1/acl.go
snippet: func (acl *ACL) ValidateDomainGlobs(svc string, globs []string) error {
	for _, glob := range globs {
		if glob == "" {
			return fmt.Errorf("glob cannot be empty")
		}

		if glob == "*" || glob == "*." {
			return fmt.Errorf("%v: %v: domain glob must not match everything", svc, glob)
		}

		if !strings.HasPrefix(glob, "*.") && strings.HasPrefix(glob, "*") {
			return fmt.Errorf("%v: %v: domain glob must represent a full prefix (sub)domain", svc, glob)
		}

		domainToCheck := strings.TrimPrefix(glob, "*")
		if strings.Contains(domainToCheck, "*") {
			return fmt.Errorf("%v: %v: domain globs are only supported as prefix", svc, glob)
		}
	}
	return nil
}

file_path: pkg/smokescreen/acl/v1/acl.go
snippet: func hostMatchesGlob(host string, domainGlob string) bool {
	if host == "" {
		return false
	}

	h := strings.TrimRight(strings.ToLower(host), ".")
	g := strings.TrimRight(strings.ToLower(domainGlob), ".")

	if strings.HasPrefix(g, "*.") {
		suffix := g[1:]
		if strings.HasSuffix(h, suffix) {
			return true
		}
	} else if g == h {
		return true
	}
	return false
}
CVE-2024-10220 (Go)

The kubelet gitRepo volume plugin processes pod-supplied GitRepoVolumeSource fields and invokes the external git binary while preparing the volume. A user who can create a pod with a gitRepo volume can control the repository, revision, and target directory values. If these values are not validated before git is executed, specially crafted option-like arguments or unsafe directory paths can be interpreted by git or can cause clone, checkout, or reset operations to run against paths outside the intended volume directory. This can lead to command execution or filesystem access on the node in the kubelet's execution context. The fix should treat all gitRepo fields as untrusted input, reject values that can be parsed as git options or make the checkout target escape the volume, and ensure any git operations that remain allowed are confined to the intended local volume directory while preserving normal benign gitRepo usage.

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/kubernetes/kubernetes

Vulnerable code:
file_path: pkg/volume/git_repo/git_repo.go
snippet: func validateVolume(src *v1.GitRepoVolumeSource) error {
	if err := validateNonFlagArgument(src.Repository, "repository"); err != nil {
		return err
	}
	if err := validateNonFlagArgument(src.Revision, "revision"); err != nil {
		return err
	}
	if err := validateNonFlagArgument(src.Directory, "directory"); err != nil {
		return err
	}
	return nil
}

Fixed code:
file_path: pkg/volume/git_repo/git_repo.go
snippet: func validateVolume(src *v1.GitRepoVolumeSource) error {
	if err := validateNonFlagArgument(src.Repository, "repository"); err != nil {
		return err
	}
	if err := validateNonFlagArgument(src.Revision, "revision"); err != nil {
		return err
	}
	if err := validateNonFlagArgument(src.Directory, "directory"); err != nil {
		return err
	}
	if (src.Revision != "") && (src.Directory != "") {
		cleanedDir := filepath.Clean(src.Directory)
		if strings.Contains(cleanedDir, "/") || (strings.Contains(cleanedDir, "\\")) {
			return fmt.Errorf("%q is not a valid directory, it must not contain a directory separator", src.Directory)
		}
	}
	return nil
}
CVE-2024-45043 (Go)

The OpenTelemetry Collector module AWS firehose receiver is for ingesting AWS Kinesis Data Firehose delivery stream messages and parsing the records received based on the configured record type. `awsfirehosereceiver` allows unauthenticated remote requests, even when configured to require a key. OpenTelemetry Collector can be configured to receive CloudWatch metrics via an AWS Firehose Stream. Firehose sets the header `X-Amz-Firehose-Access-Key` with an arbitrary configured string. The OpenTelemetry Collector awsfirehosereceiver can optionally be configured to require this key on incoming requests. However, when this is configured it **still accepts incoming requests with no key**. Only OpenTelemetry Collector users configured with the “alpha” `awsfirehosereceiver` module are affected. This module was added in version v0.49.0 of the “Contrib” distribution (or may be included in custom builds). There is a risk of unauthorized users writing metrics. Carefully crafted metrics could hide other malicious activity. There is no risk of exfiltrating data. It’s likely these endpoints will be exposed to the public internet, as Firehose does not support private HTTP endpoints. A fix was introduced in PR #34847 and released with v0.108.0. All users are advised to upgrade. There are no known workarounds for this vulnerability.

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/open-telemetry/opentelemetry-collector-contrib

Vulnerable code:
file_path: receiver/awsfirehosereceiver/receiver.go
snippet: func (fmr *firehoseReceiver) validate(r *http.Request) (int, error) {
	if accessKey := r.Header.Get(headerFirehoseAccessKey); accessKey != "" && accessKey != string(fmr.config.AccessKey) {
		return http.StatusUnauthorized, errInvalidAccessKey
	}
	return http.StatusAccepted, nil
}

Fixed code:
file_path: receiver/awsfirehosereceiver/receiver.go
snippet: func (fmr *firehoseReceiver) validate(r *http.Request) (int, error) {
	if string(fmr.config.AccessKey) == "" {
		// No access key is configured - accept all requests.
		return http.StatusAccepted, nil
	}
	if accessKey := r.Header.Get(headerFirehoseAccessKey); accessKey == string(fmr.config.AccessKey) {
		return http.StatusAccepted, nil
	}
	return http.StatusUnauthorized, errInvalidAccessKey
}
CVE-2023-33977 (Python)

Kiwi TCMS has an upload-related cross-site scripting weakness in its attachment handling. Authenticated users who can upload attachments to objects such as test plans or test cases may supply browser-renderable files, especially SVG content, that contain executable JavaScript through constructs such as script elements or event-handler attributes like onload, including case variations. The attachment validation applied by the real configured upload path must reject such active content rather than only detecting a narrow spelling or a single helper-specific pattern. If a malicious attachment is accepted and later served to other users, their browsers may execute attacker-controlled JavaScript in the Kiwi TCMS context. In addition, deployments that serve uploaded files through Nginx or a reverse proxy must continue to deliver effective browser security headers for uploaded content so that proxy/location configuration does not remove protections such as content sniffing prevention, frame restrictions, and Content-Security-Policy.

Weakness:
CWE-79: name: Improper Neutralization of Input During Web Page Generation ('Cross-site Scripting')
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.

Repository: https://github.com/kiwitcms/Kiwi

Vulnerable code:
file_path: tcms/kiwi_attachments/validators.py
snippet: def deny_uploads_containing_script_tag(uploaded_file):
    for chunk in uploaded_file.chunks(2048):
        if chunk.lower().find(b"<script") > -1:
            raise ValidationError(_("File contains forbidden <script> tag"))


Fixed code:
file_path: tcms/kiwi_attachments/validators.py
snippet: def deny_uploads_containing_script_tag(uploaded_file):
    for chunk in uploaded_file.chunks(2048):
        if chunk.lower().find(b"<script") > -1:
            raise ValidationError(_("File contains forbidden <script> tag"))

        if chunk.lower().find(b"onload=") > -1:
            raise ValidationError(_("File contains forbidden attribute:") + "onload")
CVE-2015-3295 (JavaScript)

markdown-it's Markdown link and image rendering can allow attacker-controlled data: URL destinations to be emitted into generated HTML href or src attributes. A malicious document may supply dangerous data: payloads through any Markdown syntax that defines a link or image destination, including inline destinations and reference-style link or image definitions. These payloads can use HTML, XHTML, SVG, mixed-case schemes, or other active or browser-parseable data: URL variants, causing the rendered HTML to load active content or execute script when displayed or clicked.

Weakness:
CWE-284: name: Improper Access Control
description: The product does not restrict or incorrectly restricts access to a resource from an unauthorized actor.

Repository: https://github.com/markdown-it/markdown-it

Vulnerable code:
file_path: lib/index.js
snippet: var BAD_PROTOCOLS    = [ 'vbscript', 'javascript', 'file' ];

function validateLink(url) {
  // url should be normalized at this point, and existing entities are decoded
  //
  var str = url.trim().toLowerCase();

  if (str.indexOf(':') >= 0 && BAD_PROTOCOLS.indexOf(str.split(':')[0]) >= 0) {
    return false;
  }
  return true;
}

Fixed code:
file_path: lib/index.js
snippet: ////////////////////////////////////////////////////////////////////////////////
//
// This validator does not pretent to functionality of full weight sanitizers.
// It's a tradeoff between default security, simplicity and usability.
// If you need different setup - override validator method as you wish. Or
// replace it with dummy function and use external sanitizer.
//

var BAD_PROTOCOLS      = [ 'vbscript', 'javascript', 'file', 'data' ];
var ALLOWED_DATA_MIMES = [
  'data:image/gif',
  'data:image/png',
  'data:image/jpeg',
  'data:image/webp'
];

function validateLink(url) {
  // url should be normalized at this point, and existing entities are decoded

  var str      = url.trim().toLowerCase(),
      protocol = str.split(':')[0];

  if (str.indexOf(':') >= 0 && BAD_PROTOCOLS.indexOf(protocol) >= 0) {
    if (protocol === 'data' && ALLOWED_DATA_MIMES.indexOf(str.split(';')[0]) >= 0) {
      return true;
    }
    return false;
  }

  return true;
}
CVE-2021-21354 (Python)

Pollbot is open source software which "frees its human masters from the toilsome task of polling for the state of things during the Firefox release process." In Pollbot before version 1.4.4 there is an open redirection vulnerability in the path of "https://pollbot.services.mozilla.com/". An attacker can redirect anyone to malicious sites. To Reproduce type in this URL: "https://pollbot.services.mozilla.com//evil.com/". Affected versions will redirect to that website when you inject a payload like "//evil.com/". This is fixed in version 1.4.4.

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/mozilla/PollBot

Vulnerable code:
file_path: pollbot/middlewares.py
snippet: async def handle_404(request, response):
    if 'json' not in response.headers['Content-Type']:
        if request.path.endswith('/'):
            return web.HTTPFound(request.path.rstrip('/'))
        return web.json_response({
            "status": 404,
            "message": "Page '{}' not found".format(request.path)
        }, status=404)
    return response

Fixed code:
file_path: pollbot/middlewares.py
snippet: async def handle_404(request, response):
    if 'json' not in response.headers['Content-Type']:
        if request.path.endswith('/'):
            return web.HTTPFound('/' + request.path.strip('/'))
        return web.json_response({
            "status": 404,
            "message": "Page '{}' not found".format(request.path)
        }, status=404)
    return response
CVE-2023-26125 (Go)

Gin's redirect logic for routes that trigger RedirectTrailingSlash uses the client-supplied X-Forwarded-Prefix header when constructing the HTTP redirect Location header. If this header is not strictly validated, an attacker can send a crafted request with a malicious prefix containing URL control syntax such as query or fragment delimiters, schemes, encoded separators, backslashes, or path traversal-like components. Those attacker-controlled values can be reflected into the redirect Location, creating a cache-poisoning input vector and potentially enabling other downstream issues in deployments that rely on forwarded-prefix behavior.

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/t0rchwo0d/gin

Vulnerable code:
file_path: gin.go
snippet: func redirectTrailingSlash(c *Context) {
	req := c.Request
	p := req.URL.Path
	if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
		prefix = url.QueryEscape(prefix)
		prefix = strings.ReplaceAll(prefix, "%2F", "/")

		p = prefix + "/" + req.URL.Path
	}
	req.URL.Path = p + "/"
	if length := len(p); length > 1 && p[length-1] == '/' {
		req.URL.Path = p[:length-1]
	}
	redirectRequest(c)
}

Fixed code:
file_path: gin.go
snippet: var regSafePrefix = regexp.MustCompile("[^a-zA-Z0-9/-]+")
var regRemoveRepeatedChar = regexp.MustCompile("/{2,}")


file_path: gin.go
snippet: func redirectTrailingSlash(c *Context) {
	req := c.Request
	p := req.URL.Path
	if prefix := path.Clean(c.Request.Header.Get("X-Forwarded-Prefix")); prefix != "." {
		prefix = regSafePrefix.ReplaceAllString(prefix, "")
		prefix = regRemoveRepeatedChar.ReplaceAllString(prefix, "/")

		p = prefix + "/" + req.URL.Path
	}
	req.URL.Path = p + "/"
	if length := len(p); length > 1 && p[length-1] == '/' {
		req.URL.Path = p[:length-1]
	}
	redirectRequest(c)
}
CVE-2022-0722 (JavaScript)

Exposure of Sensitive Information to an Unauthorized Actor in GitHub repository ionicabizau/parse-url prior to 7.0.0.

Weakness:
CWE-200: name: Exposure of Sensitive Information to an Unauthorized Actor
description: The product exposes sensitive information to an actor that is not explicitly authorized to have access to that information.

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

Vulnerable code:
file_path: lib/index.js
snippet: function parseUrl(url, normalize = false) {
    if (typeof url !== "string" || !url.trim()) {
        throw new Error("Invalid url.")
    }
    if (normalize) {
        if (typeof normalize !== "object") {
            normalize = {
                stripHash: false
            }
        }
        url = normalizeUrl(url, normalize)
    }
    const parsed = parsePath(url)
    return parsed;
}

Fixed code:
file_path: lib/index.js
snippet: const parseUrl = (url, normalize = false) => {

    // Constants
    const GIT_RE = /((git@|http(s)?:\/\/)([\w\.@]+)(\/|:))(([\~,\w,\-,\_,\/]+)(.git){0,1}((\/){0,1}))/

    if (typeof url !== "string" || !url.trim()) {
        throw new Error("Invalid url.")
    }

    if (normalize) {
        if (typeof normalize !== "object") {
            normalize = {
                stripHash: false
            }
        }
        url = normalizeUrl(url, normalize)
    }

    const parsed = parsePath(url)

    // Potential git-ssh urls
    if (parsed.protocol === "file") {
        const matched  = parsed.href.match(GIT_RE)
        if (matched) {
            parsed.protocols = ["ssh"]
            parsed.protocol = "ssh"
            parsed.resource = matched[4]
            parsed.user = "git"
            parsed.pathname = `/${matched[6]}`
        }
    }

    return parsed;
}
CVE-2022-29822 (JavaScript)

Due to improper parameter filtering in the Feathers js library, which may ultimately lead to SQL injection

Weakness:
CWE-89: name: Improper Neutralization of Special Elements used in an SQL Command ('SQL Injection')
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.

Repository: https://github.com/feathersjs-ecosystem/feathers-sequelize

Vulnerable code:
file_path: lib/index.js
snippet:   _find (params = {}) {
    const { filters, query: where, paginate } = this.filterQuery(params);
    const order = utils.getOrder(filters.$sort);

    const q = Object.assign({
      where,
      order,
      limit: filters.$limit,
      offset: filters.$skip,
      raw: this.raw,
      distinct: true
    }, params.sequelize);

    if (filters.$select) {
      q.attributes = filters.$select;
    }

    const Model = this.applyScope(params);

    // Until Sequelize fix all the findAndCount issues, a few 'hacks' are needed to get the total count correct

    // Adding an empty include changes the way the count is done
    // See: https://github.com/sequelize/sequelize/blob/7e441a6a5ca44749acd3567b59b1d6ceb06ae64b/lib/model.js#L1780-L1782
    q.include = q.include || [];

    if (paginate && paginate.default) {
      return Model.findAndCountAll(q).then(result => {
        return {
          total: result.count,
          limit: filters.$limit,
          skip: filters.$skip || 0,
          data: result.rows
        };
      }).catch(utils.errorHandler);
    }

    return Model.findAll(q).catch(utils.errorHandler);
  }

Fixed code:
file_path: lib/index.js
snippet:   _find (params = {}) {
    const { filters, query: where, paginate } = this.filterQuery(params);
    const order = utils.getOrder(filters.$sort);

    const q = Object.assign({
      where,
      order,
      limit: filters.$limit,
      offset: filters.$skip,
      raw: this.raw,
      distinct: true
    }, params.sequelize);

    if (filters.$select) {
      q.attributes = filters.$select.map(select => `${select}`);
    }

    const Model = this.applyScope(params);

    // Until Sequelize fix all the findAndCount issues, a few 'hacks' are needed to get the total count correct

    // Adding an empty include changes the way the count is done
    // See: https://github.com/sequelize/sequelize/blob/7e441a6a5ca44749acd3567b59b1d6ceb06ae64b/lib/model.js#L1780-L1782
    q.include = q.include || [];

    if (paginate && paginate.default) {
      return Model.findAndCountAll(q).then(result => {
        return {
          total: result.count,
          limit: filters.$limit,
          skip: filters.$skip || 0,
          data: result.rows
        };
      }).catch(utils.errorHandler);
    }

    return Model.findAll(q).catch(utils.errorHandler);
  }
CVE-2017-1001003 (JavaScript)

math.js before 3.17.0 had an issue where private properties such as a constructor could be replaced by using unicode characters when creating an object.

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/josdejong/mathjs

Vulnerable code:
file_path: lib/expression/node/ObjectNode.js
snippet:   function compileObjectNode(node, defs, args) {
    if (!(node instanceof ObjectNode)) {
      throw new TypeError('No valid ObjectNode')
    }

    var entries = [];
    for (var key in node.properties) {
      if (hasOwnProperty(node.properties, key)) {
        if (!isSafeProperty(node.properties, key)) {
          throw new Error('No access to property "' + key + '"');
        }

        entries.push(stringify(key) + ': ' + compile(node.properties[key], defs, args));
      }
    }
    return '{' + entries.join(', ') + '}';
  }

Fixed code:
file_path: lib/expression/node/ObjectNode.js
snippet:   function compileObjectNode(node, defs, args) {
    if (!(node instanceof ObjectNode)) {
      throw new TypeError('No valid ObjectNode')
    }

    var entries = [];
    for (var key in node.properties) {
      if (hasOwnProperty(node.properties, key)) {
        // we stringify/parse the key here to resolve unicode characters,
        // so you cannot create a key like {"co\\u006Estructor": null} 
        var stringifiedKey = stringify(key)
        var parsedKey = JSON.parse(stringifiedKey)
        if (!isSafeProperty(node.properties, parsedKey)) {
          throw new Error('No access to property "' + parsedKey + '"');
        }

        entries.push(stringifiedKey + ': ' + compile(node.properties[key], defs, args));
      }
    }
    return '{' + entries.join(', ') + '}';
  }