ByteDance/PatchEval huggingface dataset:
CVE-2024-24579 (Go)

stereoscope is a go library for processing container images and simulating a squash filesystem.  Prior to version 0.0.1, it is possible to craft an OCI tar archive that, when stereoscope attempts to unarchive the contents, will result in writing to paths outside of the unarchive temporary directory. Specifically, use of `github.com/anchore/stereoscope/pkg/file.UntarToDirectory()` function, the  `github.com/anchore/stereoscope/pkg/image/oci.TarballImageProvider` struct, or the higher level `github.com/anchore/stereoscope/pkg/image.Image.Read()` function express this vulnerability. As a workaround, if you are using the OCI archive as input into stereoscope then you can switch to using an OCI layout by unarchiving the tar archive and provide the unarchived directory to stereoscope.

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/anchore/stereoscope

Vulnerable code:
file_path: pkg/file/tarutil.go
snippet: func UntarToDirectory(reader io.Reader, dst string) error {
	visitor := func(entry TarFileEntry) error {
		target := filepath.Join(dst, entry.Header.Name)

		switch entry.Header.Typeflag {
		case tar.TypeDir:
			if _, err := os.Stat(target); err != nil {
				if err := os.MkdirAll(target, 0755); err != nil {
					return err
				}
			}

		case tar.TypeReg:
			f, err := os.OpenFile(target, os.O_CREATE|os.O_RDWR, os.FileMode(entry.Header.Mode))
			if err != nil {
				return err
			}

			// limit the reader on each file read to prevent decompression bomb attacks
			numBytes, err := io.Copy(f, io.LimitReader(entry.Reader, perFileReadLimit))
			if numBytes >= perFileReadLimit || errors.Is(err, io.EOF) {
				return fmt.Errorf("zip read limit hit (potential decompression bomb attack)")
			}
			if err != nil {
				return fmt.Errorf("unable to copy file: %w", err)
			}

			if err = f.Close(); err != nil {
				log.Errorf("failed to close file during untar of path=%q: %w", f.Name(), err)
			}
		}
		return nil
	}

	return IterateTar(reader, visitor)
}

Fixed code:
file_path: pkg/file/tarutil.go
snippet: func UntarToDirectory(reader io.Reader, dst string) error {
	return IterateTar(
		reader,
		tarVisitor{
			fs:          afero.NewOsFs(),
			destination: dst,
		}.visit,
	)
}
CVE-2020-28360 (JavaScript)

The private-ip package exposes an isPrivate(ip) classifier that callers may use to decide whether a server-side request target is unsafe. Its current regular-expression-based checks do not reliably classify IPv4 destinations in private, reserved, or special-use address space, especially when the same destination is supplied through non-canonical decimal IPv4 spellings such as compact inet_aton-style forms or zero-padded decimal components. An attacker who can control an IP address or URL host that is checked with this package can use these reserved or special-use IPv4 destinations to bypass SSRF filtering and cause server-side requests to reach loopback, internal, link-local, shared, documentation, benchmarking, protocol-assignment, broadcast, or otherwise non-public network resources.

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/frenchbread/private-ip

Vulnerable code:
file_path: src/index.js
snippet: export default (ip) => (
  /^(::f{4}:)?10\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
  /^(::f{4}:)?192\.168\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
  /^(::f{4}:)?172\.(1[6-9]|2\d|30|31)\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
  /^(::f{4}:)?127\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
  /^(::f{4}:)?169\.254\.([0-9]{1,3})\.([0-9]{1,3})$/i.test(ip) ||
  /^f[cd][0-9a-f]{2}:/i.test(ip) ||
  /^fe80:/i.test(ip) ||
  /^::1$/.test(ip) ||
  /^::$/.test(ip)
)

Fixed code:
file_path: src/index.js
snippet: var Netmask = require('netmask').Netmask
function netmaskCheck (params) {
  let privateRanges = [
    '0.0.0.0/8',
    '10.0.0.0/8',
    '100.64.0.0/10',
    '127.0.0.0/8',
    '169.254.0.0/16',
    '172.16.0.0/12',
    '192.0.0.0/24',
    '192.0.0.0/29',
    '192.0.0.8/32',
    '192.0.0.9/32',
    '192.0.0.10/32',
    '192.0.0.170/32',
    '192.0.0.171/32',
    '192.0.2.0/24',
    '192.31.196.0/24',
    '192.52.193.0/24',
    '192.88.99.0/24',
    '192.168.0.0/16',
    '192.175.48.0/24',
    '198.18.0.0/15',
    '198.51.100.0/24',
    '203.0.113.0/24',
    '240.0.0.0/4',
    '255.255.255.255/32'
  ].map(b => new Netmask(b))
  for (let r of privateRanges) {
    if (r.contains(params)) return true
  }
  return false
}

file_path: src/index.js
snippet: export default (ip) => (
  netmaskCheck(ip)
)
CVE-2019-10787 (JavaScript)

im-resize through 2.3.2 allows remote attackers to execute arbitrary commands via the "exec" argument. The cmd argument used within index.js, can be controlled by user without any 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/Turistforeningen/node-im-resize

Vulnerable code:
file_path: index.js
snippet: module.exports = function(image, output, cb) {
  var cmd = module.exports.cmd(image, output);
  exec(cmd, {timeout: 30000}, function(e, stdout, stderr) {
    if (e) { return cb(e); }
    if (stderr) { return cb(new Error(stderr)); }

    return cb(null, output.versions);
  });
};

Fixed code:
file_path: index.js
snippet: module.exports = function(image, output, cb) {
  if(/;|&|`|\$|\(|\)|\|\||\||!|>|<|\?|\${/g.test(JSON.stringify(image))) {
    console.log('Input Validation failed, Suspicious Characters found');
  } else {
  var cmd = module.exports.cmd(image, output);
  exec(cmd, {timeout: 30000}, function(e, stdout, stderr) {
    if (e) { return cb(e); }
    if (stderr) { return cb(new Error(stderr)); }

    return cb(null, output.versions);
  });
}
};
CVE-2022-37109 (JavaScript)

patrickfuller camp up to and including commit bbd53a256ed70e79bd8758080936afbf6d738767 is vulnerable to Incorrect Access Control. Access to the password.txt file is not properly restricted as it is in the root directory served by StaticFileHandler and the Tornado rule to throw a 403 error when password.txt is accessed can be bypassed. Furthermore, it is not necessary to crack the password hash to authenticate with the application because the password hash is also used as the cookie secret, so an attacker can generate his own authentication cookie.

Weakness:
CWE-522: name: Insufficiently Protected Credentials
description: The product transmits or stores authentication credentials, but it uses an insecure method that is susceptible to unauthorized interception and/or retrieval.

Repository: https://github.com/patrickfuller/camp

Vulnerable code:
file_path: server.py
snippet:     def post(self):
        password = self.get_argument("password", "")
        if hashlib.sha512(password).hexdigest() == PASSWORD:
            self.set_secure_cookie(COOKIE_NAME, str(time.time()))
            self.redirect("/")
        else:
            time.sleep(1)
            self.redirect(u"/login?error")

file_path: server.py
snippet: handlers = [(r"/", IndexHandler), (r"/login", LoginHandler),
            (r"/websocket", WebSocket),
            (r"/static/password.txt", ErrorHandler),
            (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': ROOT})]
application = tornado.web.Application(handlers, cookie_secret=PASSWORD)

Fixed code:
file_path: server.py
snippet:     def post(self):
        password = self.get_argument("password", "")
        if hashlib.sha512(password.encode()).hexdigest() == PASSWORD:
            self.set_secure_cookie(COOKIE_NAME, str(time.time()))
            self.redirect("/")
        else:
            time.sleep(1)
            self.redirect(u"/login?error")

file_path: server.py
snippet: handlers = [(r"/", IndexHandler), (r"/login", LoginHandler),
            (r"/websocket", WebSocket),
            (r'/static/(.*)', tornado.web.StaticFileHandler, {'path': os.path.join(ROOT, 'static')})]

secret = base64.b64encode(os.urandom(50)).decode('ascii')
application = tornado.web.Application(handlers, cookie_secret=secret)
CVE-2020-8132 (JavaScript)

Lack of input validation in pdf-image npm package version <= 2.0.0 may allow an attacker to run arbitrary code if PDF file path is constructed based on untrusted user input.

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-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/mooz/node-pdf-image

Vulnerable code:
file_path: index.js
snippet:   constructGetInfoCommand: function () {
    return util.format(
      "pdfinfo \"%s\"",
      this.pdfFilePath
    );
  },

file_path: index.js
snippet:   getInfo: function () {
    var self = this;
    var getInfoCommand = this.constructGetInfoCommand();
    var promise = new Promise(function (resolve, reject) {
      exec(getInfoCommand, function (err, stdout, stderr) {
        if (err) {
          return reject({
            message: "Failed to get PDF'S information",
            error: err,
            stdout: stdout,
            stderr: stderr
          });
        }
        return resolve(self.parseGetInfoCommandOutput(stdout));
      });
    });
    return promise;
  },

Fixed code:
file_path: index.js
snippet:   constructGetInfoCommand: function () {
    return {
      cmd: "pdfinfo",
      args: [this.pdfFilePath]
    };
  },

file_path: index.js
snippet:   getInfo: function () {
    var self = this;
    var getInfoCommand = this.constructGetInfoCommand();
    return new Promise(function (resolve, reject) {
      spawn(getInfoCommand.cmd, getInfoCommand.args, { capture: [ 'stdout', 'stderr' ]})
        .then(function (cmdResult) {
          resolve(self.parseGetInfoCommandOutput(cmdResult.stdout.toString()));
        }).catch(reject);
    });
  },
CVE-2017-1000189 (JavaScript)

nodejs ejs version older than 2.5.5 is vulnerable to a denial-of-service due to weak input validation in the ejs.renderFile()

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/mde/ejs

Vulnerable code:
file_path: lib/ejs.js
snippet: function cpOptsInData(data, opts) {
  _OPTS.forEach(function (p) {
    if (typeof data[p] != 'undefined') {
      // Disallow setting the root opt for includes via a passed data obj
      // Unsanitized, parameterized use of `render` could allow the
      // include directory to be reset, opening up the possibility of
      // remote code execution
      if (p == 'root') {
        return;
      }
      opts[p] = data[p];
    }
  });
}

Fixed code:
file_path: lib/ejs.js
snippet: function cpOptsInData(data, opts) {
  _OPTS.forEach(function (p) {
    if (typeof data[p] != 'undefined') {
      // Disallow passing potentially dangerous opts in the data
      // These opts should not be settable via a `render` call
      if (_OPTS_IN_DATA_BLACKLIST[p]) {
        return;
      }
      opts[p] = data[p];
    }
  });
}

file_path: lib/ejs.js
snippet: var _OPTS_IN_DATA_BLACKLIST = {
      cache: true,
      filename: true,
      root: true,
      localsName: true
    };
CVE-2018-3733 (JavaScript)

crud-file-server node module before 0.9.0 suffers from a Path Traversal vulnerability due to incorrect validation of url, which allows a malicious user to read content of any file with known path.

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/omphalos/crud-file-server

Vulnerable code:
file_path: crud-file-server.js
snippet: var cleanUrl = function(url) { 
	url = decodeURIComponent(url);
	while(url.indexOf('..').length > 0) { url = url.replace('..', ''); }
	return url;
};

Fixed code:
file_path: crud-file-server.js
snippet: var cleanUrl = function(url) { 
	url = decodeURIComponent(url);
	while(url.indexOf('..') >= 0) { url = url.replace('..', ''); }
	return url;
};
CVE-2022-31145 (Go)

FlyteAdmin's external OAuth2/OIDC resource server validation accepts tokens issued by an external identity provider without correctly enforcing the JWT time-validity claims. An authenticated user or token holder can present a previously valid, externally issued Access Token or ID Token whose expiration time has already passed and still be treated as authenticated. This allows access to FlyteAdmin APIs and workflow administration capabilities beyond the token's intended lifetime, weakening session expiration and token revocation assumptions. The fix should ensure that, when FlyteAdmin is configured to trust an external identity provider, externally issued JWTs are accepted only if they are validly signed, intended for an allowed audience, and still valid according to their standard time-based claims, especially `exp`; expired tokens must be rejected and must not produce an authenticated identity, while valid unexpired external tokens should continue to work. Deployments using FlyteAdmin itself as the OAuth2 authorization server are outside the affected scope.

Weakness:
CWE-613: name: Insufficient Session Expiration
description: According to WASC, "Insufficient Session Expiration is when a web site permits an attacker to reuse old session credentials or session IDs for authorization."

Repository: https://github.com/flyteorg/flyteadmin

Vulnerable code:
file_path: auth/authzserver/resource_server.go
snippet: func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {
	raw, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)
	if err != nil {
		return nil, err
	}

	claimsRaw := map[string]interface{}{}
	if err = json.Unmarshal(raw, &claimsRaw); err != nil {
		return nil, fmt.Errorf("failed to unmarshal user info claim into UserInfo type. Error: %w", err)
	}

	return verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), claimsRaw)
}

Fixed code:
file_path: auth/authzserver/resource_server.go
snippet: func (r ResourceServer) ValidateAccessToken(ctx context.Context, expectedAudience, tokenStr string) (interfaces.IdentityContext, error) {
	_, err := r.signatureVerifier.VerifySignature(ctx, tokenStr)
	if err != nil {
		return nil, err
	}

	t, _, err := jwtgo.NewParser().ParseUnverified(tokenStr, jwtgo.MapClaims{})
	if err != nil {
		return nil, fmt.Errorf("failed to parse token: %v", err)
	}

	if err = t.Claims.Valid(); err != nil {
		return nil, fmt.Errorf("failed to validate token: %v", err)
	}

	return verifyClaims(sets.NewString(append(r.allowedAudience, expectedAudience)...), t.Claims.(jwtgo.MapClaims))
}

file_path: auth/authzserver/resource_server.go
snippet: 	jwtgo "github.com/golang-jwt/jwt/v4"
CVE-2020-7674 (JavaScript)

access-policy through 3.1.0 is vulnerable to Arbitrary Code Execution. User input provided to the `template` function is executed by the `eval` function resulting in code execution.

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.

Repository: https://github.com/TupleAustin/access-policy

Vulnerable code:
file_path: lib/encode.js
snippet: function template(literal, data) {
  var tmpl = literal.replace(/(\$\{)/gm, '$1data.');

  return eval('`' + tmpl + '`');
}

Fixed code:
file_path: lib/encode.js
snippet: function template(literal, data) {
  var tmpl = literal.replace(/(\$\{)/gm, '$1data.');
  let blacklist = ['&', ';', '|', '-', '$', '`', '||'];

  if (blacklist.some(v => tmpl.includes(v))) {
    for(var i=0; i<tmpl.length; i++){
      if(blacklist.includes(tmpl[i])){
        tmpl = tmpl.replace(tmpl[i], "");
      }
    }
  } 
  return eval('`' + tmpl + '`');
}

function encodeStatements(statements, data) {
  if (!statements) {
    throw new SyntaxError('Must include statements to encode');
  }

  if (!data) {
    return statements;
  }

  var output = template(JSON.stringify(statements), data);
  output = JSON.parse(output);

  Object.defineProperty(output, 'encoded', {
    __proto__: null,
    value: true
  });

  return output;
}
CVE-2019-15597 (JavaScript)

A code injection exists in node-df v0.1.4 that can allow an attacker to remote code execution by unsanitized input.

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.

Repository: https://github.com/adriano-di-giovanni/node-df

Vulnerable code:
file_path: lib/index.js
snippet:     exec(command, function(err, stdout, stderr) {
        if (err) {
            callback(err)
            return
        }

        if (stderr) {
            callback(new Error(err))
            return
        }

        var entries = parse(stdout, options)

        callback(null, entries)
    })

Fixed code:
file_path: lib/index.js
snippet:     exec(escapeShell(command), function(err, stdout, stderr) {
        if (err) {
            callback(err)
            return
        }

        if (stderr) {
            callback(new Error(err))
            return
        }

        var entries = parse(stdout, options)

        callback(null, entries)
    })
CVE-2025-29778 (Go)

Kyverno is a policy engine designed for cloud native platform engineering teams. Prior to version 1.14.0-alpha.1, Kyverno ignores subjectRegExp and IssuerRegExp while verifying artifact's sign with keyless mode. It allows the attacker to deploy kubernetes resources with the artifacts that were signed by unexpected certificate. Deploying these unauthorized kubernetes resources can lead to full compromise of kubernetes cluster. Version 1.14.0-alpha.1 contains a patch for the issue.

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.

Repository: https://github.com/kyverno/kyverno

Vulnerable code:
file_path: pkg/cosign/cosign.go
snippet: func matchSignatures(signatures []oci.Signature, subject, subjectRegExp, issuer, issuerRegExp string, extensions map[string]string) error {
	if subject == "" && issuer == "" && len(extensions) == 0 {
		return nil
	}

	var errs []error
	for _, sig := range signatures {
		cert, err := sig.Cert()
		if err != nil {
			return fmt.Errorf("failed to read certificate: %w", err)
		}

		if cert == nil {
			return fmt.Errorf("certificate not found")
		}

		if err := matchCertificateData(cert, subject, subjectRegExp, issuer, issuerRegExp, extensions); err != nil {
			errs = append(errs, err)
		} else {
			// only one signature certificate needs to match the required subject, issuer, and extensions
			return nil
		}
	}

	if len(errs) > 0 {
		err := multierr.Combine(errs...)
		return err
	}

	return fmt.Errorf("invalid signature")
}

Fixed code:
file_path: pkg/cosign/cosign.go
snippet: func matchSignatures(signatures []oci.Signature, subject, subjectRegExp, issuer, issuerRegExp string, extensions map[string]string) error {
	if subject == "" && issuer == "" && subjectRegExp == "" && issuerRegExp == "" && len(extensions) == 0 {
		return nil
	}