ByteDance/PatchEval huggingface dataset:
CVE-2022-0639 (JavaScript)

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

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: function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result =
    protocol +
    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  } else if (url.password) {
    result += ':'+ url.password;
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}

Fixed code:
file_path: index.js
snippet: function toString(stringify) {
  if (!stringify || 'function' !== typeof stringify) stringify = qs.stringify;

  var query
    , url = this
    , protocol = url.protocol;

  if (protocol && protocol.charAt(protocol.length - 1) !== ':') protocol += ':';

  var result =
    protocol +
    ((url.protocol && url.slashes) || isSpecial(url.protocol) ? '//' : '');

  if (url.username) {
    result += url.username;
    if (url.password) result += ':'+ url.password;
    result += '@';
  } else if (url.password) {
    result += ':'+ url.password;
    result += '@';
  } else if (
    url.protocol !== 'file:' &&
    isSpecial(url.protocol) &&
    !url.host &&
    url.pathname !== '/'
  ) {
    //
    // Add back the empty userinfo, otherwise the original invalid URL
    // might be transformed into a valid one with `url.pathname` as host.
    //
    result += '@';
  }

  result += url.host + url.pathname;

  query = 'object' === typeof url.query ? stringify(url.query) : url.query;
  if (query) result += '?' !== query.charAt(0) ? '?'+ query : query;

  if (url.hash) result += url.hash;

  return result;
}
CVE-2021-33420 (JavaScript)

A deserialization issue discovered in inikulin replicator before 1.0.4 allows remote attackers to run arbitrary code via the fromSerializable function in TypedArray object.

Weakness:
CWE-502: name: Deserialization of Untrusted Data
description: The product deserializes untrusted data without sufficiently ensuring that the resulting data will be valid.

Repository: https://github.com/inikulin/replicator

Vulnerable code:
file_path: index.js
snippet: var ARRAY_BUFFER_SUPPORTED = typeof ArrayBuffer === 'function';
var MAP_SUPPORTED          = typeof Map === 'function';
var SET_SUPPORTED          = typeof Set === 'function';

var TYPED_ARRAY_CTORS = [
    'Int8Array',
    'Uint8Array',
    'Uint8ClampedArray',
    'Int16Array',
    'Uint16Array',
    'Int32Array',
    'Uint32Array',
    'Float32Array',
    'Float64Array'
];

file_path: index.js
snippet:         fromSerializable: function (val) {
            return typeof GLOBAL[val.ctorName] === 'function' ? new GLOBAL[val.ctorName](val.arr) : val.arr;
        }

Fixed code:
file_path: index.js
snippet: var TYPED_ARRAY_CTORS = {
    'Int8Array':         Int8Array,
    'Uint8Array':        Uint8Array,
    'Uint8ClampedArray': Uint8ClampedArray,
    'Int16Array':        Int16Array,
    'Uint16Array':       Uint16Array,
    'Int32Array':        Int32Array,
    'Uint32Array':       Uint32Array,
    'Float32Array':      Float32Array,
    'Float64Array':      Float64Array
};

function isFunction (value) {
    return typeof value === 'function';
}

var ARRAY_BUFFER_SUPPORTED = isFunction(ArrayBuffer);
var MAP_SUPPORTED          = isFunction(Map);
var SET_SUPPORTED          = isFunction(Set);

var TYPED_ARRAY_SUPPORTED  = function (typeName) {
    return isFunction(TYPED_ARRAY_CTORS[typeName]); 
};

file_path: index.js
snippet:         fromSerializable: function (val) {
            return TYPED_ARRAY_SUPPORTED(val.ctorName) ? new TYPED_ARRAY_CTORS[val.ctorName](val.arr) : val.arr;
        }
CVE-2024-5138 (Go)

The snapctl component within snapd allows a confined snap to interact with the snapd daemon to take certain privileged actions on behalf of the snap. It was found that snapctl did not properly parse command-line arguments, allowing an unprivileged user to trigger an authorised action on behalf of the snap that would normally require administrator privileges to perform. This could possibly allow an unprivileged user to perform a denial of service or similar.

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/canonical/snapd

Vulnerable code:
file_path: overlord/hookstate/ctlcmd/ctlcmd.go
snippet: func isAllowedToRun(uid uint32, args []string) bool {
	// A command can run if any of the following are true:
	//	* It runs as root
	//	* It's contained in nonRootAllowed
	//	* It's used with the -h or --help flags
	// note: commands still need valid context and snaps can only access own config.
	return uid == 0 ||
		strutil.ListContains(nonRootAllowed, args[0]) ||
		strutil.ListContains(args, "-h") ||
		strutil.ListContains(args, "--help")
}

Fixed code:
file_path: overlord/hookstate/ctlcmd/ctlcmd.go
snippet: func isAllowedToRun(uid uint32, args []string) bool {
	// Root can run all snapctl commands.
	if uid == 0 {
		return true
	}

	for idx, arg := range args {
		// A number of sub-commands are allowed to be executed by non-root users.
		if idx == 0 && strutil.ListContains(nonRootAllowed, arg) {
			return true
		}

		// Invoking help is always allowed.
		if arg == "-h" || arg == "--help" {
			return true
		}

		// Note that we are not interrupting parsing after the first non-option
		// argument (POSIX style), because we want to cater to the use case of
		// the user appending --help or -h at the end of the command and still
		// getting something useful. The only exception is the condition below.

		// The explicit termination argument terminates parsing.
		if arg == "--" {
			break
		}
	}

	return false
}
CVE-2021-36157 (Go)

An issue was discovered in Grafana Cortex through 1.9.0. The header value X-Scope-OrgID is used to construct file paths for rules files, and if crafted to conduct directory traversal such as ae ../../sensitive/path/in/deployment pathname, then Cortex will attempt to parse a rules file at that location and include some of the contents in the error message. (Other Cortex API requests can also be sent a malicious OrgID header, e.g., tricking the ingester into writing metrics to a different location, but the effect is nuisance rather than information disclosure.)

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/cortexproject/cortex

Vulnerable code:
file_path: pkg/tenant/resolver.go
snippet: func (t *SingleResolver) TenantIDs(ctx context.Context) ([]string, error) {
	//lint:ignore faillint wrapper around upstream method
	orgID, err := user.ExtractOrgID(ctx)
	if err != nil {
		return nil, err
	}
	return []string{orgID}, err
}

Fixed code:
file_path: pkg/tenant/resolver.go
snippet: func (t *SingleResolver) TenantIDs(ctx context.Context) ([]string, error) {
	orgID, err := t.TenantID(ctx)
	if err != nil {
		return nil, err
	}
	return []string{orgID}, err
}

file_path: pkg/tenant/resolver.go
snippet: func containsUnsafePathSegments(id string) bool {
	// handle the relative reference to current and parent path.
	if id == "." || id == ".." {
		return true
	}

	return strings.ContainsAny(id, "\\/")
}

var errInvalidTenantID = errors.New("invalid tenant ID")

file_path: pkg/tenant/resolver.go
snippet: func (t *SingleResolver) TenantID(ctx context.Context) (string, error) {
	//lint:ignore faillint wrapper around upstream method
	id, err := user.ExtractOrgID(ctx)
	if err != nil {
		return "", err
	}

	if containsUnsafePathSegments(id) {
		return "", errInvalidTenantID
	}

	return id, nil
}
CVE-2020-28437 (JavaScript)

This affects all versions of package heroku-env. The injection point is located in lib/get.js which is required by index.js.

Weakness:
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.

Repository: https://github.com/brianc/node-heroku-env

Vulnerable code:
file_path: lib/get.js
snippet: module.exports = function(app, cb) {
  exec('heroku config --app ' + app, function(err, stdout) {
    if(err) return cb(err);
    var config = {}
    var lines = stdout.split('\n')
    lines.shift()
    lines.forEach(function(line) {
      if(!line.trim()) return;
      var parts = line.split(': ')
      if(!parts[1]) {
        console.log('could not parse', line)
      } else {
        config[parts[0].trim()] = parts[1].trim()
      }
    })
    cb(null, config)
  })
}

Fixed code:
file_path: lib/get.js
snippet: var execFile = require('child_process').execFile;
module.exports = function(app, cb) {
  execFile(`heroku`, ["config", "--app", app] , function(err, stdout) {
    if(err) return cb(err);
    var config = {}
    var lines = stdout.split('
')
CVE-2021-23363 (JavaScript)

This affects the package kill-by-port before 0.0.2. If (attacker-controlled) user input is given to the killByPort function, it is possible for an attacker to execute arbitrary commands. This is due to use of the child_process exec function without input sanitization.

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/GuyMograbi/kill-by-port

Vulnerable code:
file_path: index.js
snippet: exports.killByPort = function (port) {
  var processId = null
  try {
    processId = exec(`lsof -t -i:${port}`)
  } catch (e) {

  }

  if (processId !== null) { // if exists kill
    exec(`kill ${processId}`)
  }
}

Fixed code:
file_path: index.js
snippet: exports.killByPort = function (port) {
  var processId = null
  try {
    processId = exec(`lsof -t -i:${parseInt(port, 10)}`)
  } catch (e) {

  }

  if (processId !== null) { // if exists kill
    exec(`kill ${processId}`)
  }
}
CVE-2019-10792 (JavaScript)

bodymen before 1.1.1 is vulnerable to Prototype Pollution. The handler function could be tricked into adding or modifying properties of Object.prototype using a __proto__ payload.

Weakness:
CWE-74: name: Improper Neutralization of Special Elements in Output Used by a Downstream Component ('Injection')
description: The product constructs all or part of a command, data structure, or record using externally-influenced input from an upstream component, but it does not neutralize or incorrectly neutralizes special elements that could modify how it is parsed or interpreted when it is sent to a downstream component.

Repository: https://github.com/diegohaz/bodymen

Vulnerable code:
file_path: src/index.js
snippet: export function handler (type, name, fn) {
  if (arguments.length > 2) {
    handlers[type][name] = fn
  }

  return handlers[type][name]
}

Fixed code:
file_path: src/index.js
snippet: export function handler (type, name, fn) {
  if (
    type === 'constructor' ||
    type === '__proto__' ||
    name === 'constructor' ||
    name === '__proto__'
  ) {
    return
  }
  if (arguments.length > 2) {
    handlers[type][name] = fn
  }

  return handlers[type][name]
}
CVE-2019-10788 (JavaScript)

im-metadata through 3.0.1 allows remote attackers to execute arbitrary commands via the "exec" argument. It is possible to inject arbitrary commands as part of the metadata options which is given to the "exec" function.

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/Turistforeningen/node-im-metadata

Vulnerable code:
file_path: index.js
snippet: module.exports = function(path, opts, cb) {
  if (!cb) {
    cb = opts;
    opts = {};
  }

  var cmd = module.exports.cmd(path, opts);
  opts.timeout = opts.timeout || 5000;

  exec(cmd, opts, function(e, stdout, stderr) {
    if (e) { return cb(e); }
    if (stderr) { return cb(new Error(stderr)); }

    return cb(null, module.exports.parse(path, stdout, opts));
  });
};

Fixed code:
file_path: index.js
snippet: module.exports = function(path, opts, cb) {
  if (!cb) {
    cb = opts;
    opts = {};
  }

  if(/;|&|`|\$|\(|\)|\|\||\||!|>|<|\?|\${/g.test(JSON.stringify(path))) {
    console.log('Input Validation failed, Suspicious Characters found');
  } else {
    var cmd = module.exports.cmd(path, opts);
    opts.timeout = opts.timeout || 5000;
    exec(cmd, opts, function(e, stdout, stderr) {
      if (e) { return cb(e); }
    if (stderr) { return cb(new Error(stderr)); }

      return cb(null, module.exports.parse(path, stdout, opts));
  });
}
};
CVE-2023-32303 (Python)

Planet is software that provides satellite data. The secret file stores the user's Planet API authentication information. It should only be accessible by the user, but before version 2.0.1, its permissions allowed the user's group and non-group to read the file as well. This issue was patched in version 2.0.1. As a workaround, set the secret file permissions to only user read/write by hand.

Weakness:
CWE-732: name: Incorrect Permission Assignment for Critical Resource
description: The product specifies permissions for a security-critical resource in a way that allows that resource to be read or modified by unintended actors.

Repository: https://github.com/planetlabs/planet-client-python

Vulnerable code:
file_path: planet/auth.py
snippet:     def __init__(self, path):
        self.path = path

file_path: planet/auth.py
snippet:     def _write(self, contents: dict):
        LOGGER.debug(f'Writing to {self.path}')
        with open(self.path, 'w') as fp:
            fp.write(json.dumps(contents))

Fixed code:
file_path: planet/auth.py
snippet:     def __init__(self, path: typing.Union[str, pathlib.Path]):
        self.path = pathlib.Path(path)

        self.permissions = stat.S_IRUSR | stat.S_IWUSR  # user rw

        # in sdk versions <=2.0.0, secret file was created with the wrong
        # permissions, fix this automatically as well as catching the unlikely
        # cases where the permissions get changed externally
        self._enforce_permissions()

file_path: planet/auth.py
snippet:     def _write(self, contents: dict):
        LOGGER.debug(f'Writing to {self.path}')

        def opener(path, flags):
            return os.open(path, flags, self.permissions)

        with open(self.path, 'w', opener=opener) as fp:
            fp.write(json.dumps(contents))

file_path: planet/auth.py
snippet:     def _enforce_permissions(self):
        '''if the file's permissions are not what they should be, fix them'''
        try:
            # in octal, permissions is the last three bits of the mode
            file_permissions = self.path.stat().st_mode & 0o777
            if file_permissions != self.permissions:
                LOGGER.debug(
                    f'{self.path} permissions are {oct(file_permissions)}, '
                    f'should be {oct(self.permissions)}. Fixing.')
                self.path.chmod(self.permissions)
        except FileNotFoundError:
            # just skip it if the secret file doesn't exist
            pass
CVE-2023-24623 (Go)

Paranoidhttp before 0.3.0 allows SSRF because [::] is equivalent to the 127.0.0.1 address, but does not match the filter for private addresses.

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/hakobe/paranoidhttp

Vulnerable code:
file_path: client.go
snippet: func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {
	c := basicConfig()
	for _, opt := range opts {
		opt(c)
	}
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return "", err
	}

	ip := net.ParseIP(host)
	if ip != nil {
		if ip.To4() != nil && c.isIPForbidden(ip) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
		return net.JoinHostPort(ip.String(), port), nil
	}

	if c.isHostForbidden(host) {
		return "", fmt.Errorf("bad host is detected: %v", host)
	}

	r := resolver
	if r == nil {
		r = net.DefaultResolver
	}
	addrs, err := r.LookupIPAddr(ctx, host)
	if err != nil || len(addrs) <= 0 {
		return "", err
	}
	safeAddrs := make([]net.IPAddr, 0, len(addrs))
	for _, addr := range addrs {
		// only support IPv4 address
		if addr.IP.To4() == nil {
			continue
		}
		if c.isIPForbidden(addr.IP) {
			return "", fmt.Errorf("bad ip is detected: %v", addr.IP)
		}
		safeAddrs = append(safeAddrs, addr)
	}
	if len(safeAddrs) == 0 {
		return "", fmt.Errorf("fail to lookup ip addr: %v", host)
	}
	return net.JoinHostPort(safeAddrs[0].IP.String(), port), nil
}

Fixed code:
file_path: client.go
snippet: func safeAddr(ctx context.Context, resolver *net.Resolver, hostport string, opts ...Option) (string, error) {
	c := basicConfig()
	for _, opt := range opts {
		opt(c)
	}
	host, port, err := net.SplitHostPort(hostport)
	if err != nil {
		return "", err
	}

	ip := net.ParseIP(host)
	if ip != nil {
		if ip.IsUnspecified() || (ip.To4() != nil && c.isIPForbidden(ip)) {
			return "", fmt.Errorf("bad ip is detected: %v", ip)
		}
		return net.JoinHostPort(ip.String(), port), nil
	}

	if c.isHostForbidden(host) {
		return "", fmt.Errorf("bad host is detected: %v", host)
	}

	r := resolver
	if r == nil {
		r = net.DefaultResolver
	}
	addrs, err := r.LookupIPAddr(ctx, host)
	if err != nil || len(addrs) <= 0 {
		return "", err
	}
	safeAddrs := make([]net.IPAddr, 0, len(addrs))
	for _, addr := range addrs {
		// only support IPv4 address
		if addr.IP.To4() == nil {
			continue
		}
		if c.isIPForbidden(addr.IP) {
			return "", fmt.Errorf("bad ip is detected: %v", addr.IP)
		}
		safeAddrs = append(safeAddrs, addr)
	}
	if len(safeAddrs) == 0 {
		return "", fmt.Errorf("fail to lookup ip addr: %v", host)
	}
	return net.JoinHostPort(safeAddrs[0].IP.String(), port), nil
}