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

Pomerium is an identity and context-aware access proxy. The Pomerium databroker service is responsible for managing all persistent Pomerium application state. Requests to the databroker service API are authorized by the presence of a JSON Web Token (JWT) signed by a key known by all Pomerium services in the same deployment. However, incomplete validation of this JWT meant that some service account access tokens would incorrectly be treated as valid for the purpose of databroker API authorization. Improper access to the databroker API could allow exfiltration of user info, spoofing of user sessions, or tampering with Pomerium routes, policies, and other settings. A Pomerium deployment is susceptible to this issue if all of the following conditions are met, you have issued a service account access token using Pomerium Zero or Pomerium Enterprise, the access token has an explicit expiration date in the future, and the core Pomerium databroker gRPC API is not otherwise secured by network access controls. This vulnerability is fixed in 0.27.1.

Weakness:
CWE-863: name: Incorrect Authorization
description: The product performs an authorization check when an actor attempts to access a resource or perform an action, but it does not correctly perform the check.

Repository: https://github.com/pomerium/pomerium

Vulnerable code:
file_path: pkg/grpcutil/options.go
snippet: func RequireSignedJWT(ctx context.Context, key []byte) error {
	if len(key) > 0 {
		rawjwt, ok := JWTFromGRPCRequest(ctx)
		if !ok {
			return status.Error(codes.Unauthenticated, "unauthenticated")
		}

		tok, err := jwt.ParseSigned(rawjwt)
		if err != nil {
			return status.Errorf(codes.Unauthenticated, "invalid JWT: %v", err)
		}

		var claims struct {
			Expiry *jwt.NumericDate `json:"exp,omitempty"`
		}
		err = tok.Claims(key, &claims)
		if err != nil {
			return status.Errorf(codes.Unauthenticated, "invalid JWT: %v", err)
		}

		if claims.Expiry == nil || time.Now().After(claims.Expiry.Time()) {
			return status.Errorf(codes.Unauthenticated, "expired JWT: %v", err)
		}
	}
	return nil
}

Fixed code:
file_path: pkg/grpcutil/options.go
snippet: func RequireSignedJWT(ctx context.Context, key []byte) error {
	if len(key) > 0 {
		rawjwt, ok := JWTFromGRPCRequest(ctx)
		if !ok {
			return status.Error(codes.Unauthenticated, "unauthenticated")
		}

		if err := validateJWT(rawjwt, key); err != nil {
			log.Ctx(ctx).Debug().Err(err).Msg("rejected gRPC request due to invalid JWT")
			return status.Error(codes.Unauthenticated, "invalid JWT")
		}
	}
	return nil
}

file_path: pkg/grpcutil/options.go
snippet: func validateJWT(rawjwt string, key []byte) error {
	tok, err := jwt.ParseSigned(rawjwt)
	if err != nil {
		return err
	}

	var claims map[string]*jwt.NumericDate
	err = tok.Claims(key, &claims)
	if err != nil {
		return err
	} else if len(claims) != 1 || claims["exp"] == nil {
		return fmt.Errorf("expected exactly one claim (exp)")
	}

	if t := claims["exp"].Time(); time.Now().After(t) {
		return fmt.Errorf("JWT expired at %s", t.Format(time.DateTime))
	}
	return nil
}
CVE-2024-29041 (JavaScript)

Express.js minimalist web framework for node. Versions of Express.js prior to 4.19.0 and all pre-release alpha and beta versions of 5.0 are affected by an open redirect vulnerability using malformed URLs. When a user of Express performs a redirect using a user-provided URL Express performs an encode [using `encodeurl`](https://github.com/pillarjs/encodeurl) on the contents before passing it to the `location` header. This can cause malformed URLs to be evaluated in unexpected ways by common redirect allow list implementations in Express applications, leading to an Open Redirect via bypass of a properly implemented allow list. The main method impacted is `res.location()` but this is also called from within `res.redirect()`. The vulnerability is fixed in 4.19.2 and 5.0.0-beta.3.

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/expressjs/express

Vulnerable code:
file_path: lib/response.js
snippet: res.location = function location(url) {
  var loc = url;

  // "back" is an alias for the referrer
  if (url === 'back') {
    loc = this.req.get('Referrer') || '/';
  }

  // set location

Fixed code:
file_path: lib/response.js
snippet: res.location = function location(url) {
  var loc = url;

  // "back" is an alias for the referrer
  if (url === 'back') {
    loc = this.req.get('Referrer') || '/';
  }

  var lowerLoc = loc.toLowerCase();
  var encodedUrl = encodeUrl(loc);
  if (lowerLoc.indexOf('https://') === 0 || lowerLoc.indexOf('http://') === 0) {
    try {
      var parsedUrl = urlParse(loc);
      var parsedEncodedUrl = urlParse(encodedUrl);
      // Because this can encode the host, check that we did not change the host
      if (parsedUrl.host !== parsedEncodedUrl.host) {
        // If the host changes after encodeUrl, return the original url
        return this.set('Location', loc);
      }
    } catch (e) {
      // If parse fails, return the original url
      return this.set('Location', loc);
    }
  }

  // set location
  return this.set('Location', encodedUrl);
};
CVE-2021-22538 (Go)

A privilege escalation vulnerability impacting the Google Exposure Notification Verification Server (versions prior to 0.23.1), allows an attacker who (1) has UserWrite permissions and (2) is using a carefully crafted request or malicious proxy, to create another user with higher privileges than their own. This occurs due to insufficient checks on the allowed set of permissions. The new user creation event would be captured in the Event Log.

Weakness:
CWE-276: name: Incorrect Default Permissions
description: During installation, installed file permissions are set to allow anyone to modify those files.

Repository: https://github.com/google/exposure-notifications-verification-server

Vulnerable code:
file_path: pkg/rbac/rbac.go
snippet: func CompileAndAuthorize(actorPermission Permission, toUpdate []Permission) (Permission, error) {
	var permission Permission
	for _, update := range toUpdate {
		// Verify that the user making changes has the permissions they are trying
		// to grant. It is not valid for someone to grant permissions larger than
		// they currently have.
		if !Can(actorPermission, update) {
			return 0, fmt.Errorf("actor does not have all scopes which are being granted")
		}
		permission = permission | update
	}

	// Ensure implied permissions. The actor must also have the implied
	// permissions by definition.
	permission = AddImplied(permission)
	return permission, nil
}

Fixed code:
file_path: pkg/rbac/rbac.go
snippet: func CompileAndAuthorize(actorPermission Permission, toUpdate []Permission) (Permission, error) {
	var permission Permission
	for _, update := range toUpdate {
		// Verify the provided permission is a known permission. This prevents a
		// security vulnerability whereby a carefully crafted request is able to
		// provide a value that correctly passes an the bitwise AND check and then
		// modifies the target permission using OR to escalate privilege.
		if _, ok := PermissionMap[update]; !ok {
			if update != LegacyRealmAdmin && update != LegacyRealmUser {
				return 0, fmt.Errorf("provided permission %v is unknown", update)
			}
		}

		// Verify that the user making changes has the permissions they are trying
		// to grant. It is not valid for someone to grant permissions larger than
		// they currently have.
		if !Can(actorPermission, update) {
			return 0, fmt.Errorf("actor does not have all scopes which are being granted")
		}
		permission = permission | update
	}

	// Ensure implied permissions. The actor must also have the implied
	// permissions by definition.
	permission = AddImplied(permission)
	return permission, nil
}
CVE-2017-16025 (JavaScript)

Nes is a websocket extension library for hapi. Hapi is a webserver framework. Versions below and including 6.4.0 have a denial of service vulnerability via an invalid Cookie header. This is only present when websocket authentication is set to `cookie`. Submitting an invalid cookie on the websocket upgrade request will cause the node process to error out.

Weakness:
CWE-287: name: Improper Authentication
description: When an actor claims to have a given identity, the product does not prove or insufficiently proves that the claim is correct.

Repository: https://github.com/hapijs/nes

Vulnerable code:
file_path: lib/socket.js
snippet: internals.Socket.prototype._authenticate = function () {

    const config = this._listener._settings.auth;
    if (!config) {
        return;
    }

    if (config.timeout) {
        this.auth._timeout = setTimeout(() => this.disconnect(), config.timeout);
    }

    const cookies = this._ws.upgradeReq.headers.cookie;
    if (!cookies) {
        return;
    }

    this._listener._connection.states.parse(cookies, (ignoreErr, state, failed) => {

        const auth = state[config.cookie];
        if (auth) {
            this.auth._error = this._setCredentials(auth.credentials, auth.artifacts);
        }
    });
};

Fixed code:
file_path: lib/socket.js
snippet: internals.Socket.prototype._authenticate = function () {

    const config = this._listener._settings.auth;
    if (!config) {
        return;
    }

    if (config.timeout) {
        this.auth._timeout = setTimeout(() => this.disconnect(), config.timeout);
    }

    const cookies = this._ws.upgradeReq.headers.cookie;
    if (!cookies) {
        return;
    }

    this._listener._connection.states.parse(cookies, (err, state, failed) => {

        if (err) {
            this.auth._error = Boom.unauthorized('Invalid nes authentication cookie');
            return;
        }

        const auth = state[config.cookie];
        if (auth) {
            this.auth._error = this._setCredentials(auth.credentials, auth.artifacts);
        }
    });
};


internals.Socket.prototype._setCredentials = function (credentials, artifacts) {

    this.auth.isAuthenticated = true;
    this.auth.credentials = credentials;
    this.auth.artifacts = artifacts;

    return this._listener._sockets.auth(this);
};
CVE-2022-2421 (JavaScript)

Socket.IO parser's binary attachment reconstruction trusts placeholder metadata supplied in encoded packets. When decoding a binary event or acknowledgement, a remote peer can provide a malformed placeholder object with a truthy non-boolean `_placeholder` value or a `num` value that is not a valid attachment index, such as a string naming an inherited Array property or another invalid index. The reconstruction logic may then index the attachment buffer array with attacker-controlled metadata and insert a function object or other non-attachment reference into the decoded packet payload instead of an actual binary attachment. This can expose application code to attacker-controlled unexpected values in event data and cause type confusion or unsafe downstream behavior.

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/socketio/socket.io-parser

Vulnerable code:
file_path: binary.js
snippet: function _reconstructPacket(data, buffers) {
  if (!data) return data;

  if (data && data._placeholder) {
    return buffers[data.num]; // appropriate buffer (should be natural order anyway)
  } else if (isArray(data)) {
    for (var i = 0; i < data.length; i++) {
      data[i] = _reconstructPacket(data[i], buffers);
    }
  } else if (typeof data === 'object') {
    for (var key in data) {
      data[key] = _reconstructPacket(data[key], buffers);
    }
  }

  return data;
}

Fixed code:
file_path: binary.js
snippet: function _reconstructPacket(data, buffers) {
  if (!data) return data;

  if (data && data._placeholder === true) {
    var isIndexValid =
      typeof data.num === "number" &&
      data.num >= 0 &&
      data.num < buffers.length;
    if (isIndexValid) {
      return buffers[data.num]; // appropriate buffer (should be natural order anyway)
    } else {
      throw new Error("illegal attachments");
    }
  } else if (isArray(data)) {
    for (var i = 0; i < data.length; i++) {
      data[i] = _reconstructPacket(data[i], buffers);
    }
  } else if (typeof data === 'object') {
    for (var key in data) {
      data[key] = _reconstructPacket(data[key], buffers);
    }
  }

  return data;
}
CVE-2015-1326 (Python)

python-dbusmock before version 0.15.1 AddTemplate() D-Bus method call or DBusTestCase.spawn_server_template() method could be tricked into executing malicious code if an attacker supplies a .pyc file.

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/martinpitt/python-dbusmock

Vulnerable code:
file_path: dbusmock/mockobject.py
snippet: def load_module(name):
    if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
        sys.path.insert(0, os.path.dirname(os.path.abspath(name)))
        try:
            m = os.path.splitext(os.path.basename(name))[0]
            module = importlib.import_module(m)
        finally:
            sys.path.pop(0)

        return module

Fixed code:
file_path: dbusmock/mockobject.py
snippet: def load_module(name):
    if os.path.exists(name) and os.path.splitext(name)[1] == '.py':
        mod = imp.new_module(os.path.splitext(os.path.basename(name))[0])
        with open(name) as f:
            exec(f.read(), mod.__dict__, mod.__dict__)
        return mod

    return importlib.import_module('dbusmock.templates.' + name)
CVE-2024-22199 (Go)

The Django/Pongo2 template engine adapter for Fiber renders template variables without HTML autoescaping by default. In applications that pass attacker-controlled data into template render bindings, including values reached through nested maps or other template-accessible data structures, malicious HTML or JavaScript markup can be emitted into the response and interpreted by the browser, enabling cross-site scripting. The vulnerable behavior occurs during normal template rendering, including rendering through layouts, whenever user-supplied values are interpolated into HTML output.

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/gofiber/template

Vulnerable code:
file_path: django/django.go
snippet: func (e *Engine) Render(out io.Writer, name string, binding interface{}, layout ...string) error {
	if !e.Loaded || e.ShouldReload {
		if e.ShouldReload {
			e.Loaded = false
		}
		if err := e.Load(); err != nil {
			return err
		}
	}
	tmpl, ok := e.Templates[name]
	if !ok {
		return fmt.Errorf("template %s does not exist", name)
	}

	bind := getPongoBinding(binding)
	parsed, err := tmpl.Execute(bind)
	if err != nil {
		return err
	}
	if len(layout) > 0 && layout[0] != "" {
		if bind == nil {
			bind = make(map[string]interface{}, 1)
		}
		bind[e.LayoutName] = parsed
		lay := e.Templates[layout[0]]
		if lay == nil {
			return fmt.Errorf("LayoutName %s does not exist", layout[0])
		}
		return lay.ExecuteWriter(bind, out)
	}
	if _, err = out.Write([]byte(parsed)); err != nil {
		return err
	}
	return nil
}

Fixed code:
file_path: django/django.go
snippet: func (e *Engine) Render(out io.Writer, name string, binding interface{}, layout ...string) error {
	if !e.Loaded || e.ShouldReload {
		if e.ShouldReload {
			e.Loaded = false
		}
		if err := e.Load(); err != nil {
			return err
		}
	}
	tmpl, ok := e.Templates[name]
	if !ok {
		return fmt.Errorf("template %s does not exist", name)
	}

	bind := getPongoBinding(binding)
	parsed, err := tmpl.Execute(bind)
	if err != nil {
		return err
	}
	if len(layout) > 0 && layout[0] != "" {
		if bind == nil {
			bind = make(map[string]interface{}, 1)
		}

		// Workaround for custom {{embed}} tag
		// Mark the `embed` variable as safe
		// it has already been escaped above
		// e.LayoutName will be 'embed'
		safeEmbed := pongo2.AsSafeValue(parsed)

		// Add the safe value to the binding map
		bind[e.LayoutName] = safeEmbed

		lay := e.Templates[layout[0]]
		if lay == nil {
			return fmt.Errorf("LayoutName %s does not exist", layout[0])
		}
		return lay.ExecuteWriter(bind, out)
	}
	if _, err = out.Write([]byte(parsed)); err != nil {
		return err
	}
	return nil
}
CVE-2023-29159 (Python)

Directory traversal vulnerability in Starlette versions 0.13.5 and later and prior to 0.27.0 allows a remote unauthenticated attacker to view files in a web service which was built using Starlette.

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/encode/starlette

Vulnerable code:
file_path: starlette/staticfiles.py
snippet:     def lookup_path(
        self, path: str
    ) -> typing.Tuple[str, typing.Optional[os.stat_result]]:
        for directory in self.all_directories:
            joined_path = os.path.join(directory, path)
            if self.follow_symlink:
                full_path = os.path.abspath(joined_path)
            else:
                full_path = os.path.realpath(joined_path)
            directory = os.path.realpath(directory)
            if os.path.commonprefix([full_path, directory]) != directory:
                # Don't allow misbehaving clients to break out of the static files
                # directory.
                continue
            try:
                return full_path, os.stat(full_path)
            except (FileNotFoundError, NotADirectoryError):
                continue
        return "", None

Fixed code:
file_path: starlette/staticfiles.py
snippet:     def lookup_path(
        self, path: str
    ) -> typing.Tuple[str, typing.Optional[os.stat_result]]:
        for directory in self.all_directories:
            joined_path = os.path.join(directory, path)
            if self.follow_symlink:
                full_path = os.path.abspath(joined_path)
            else:
                full_path = os.path.realpath(joined_path)
            directory = os.path.realpath(directory)
            if os.path.commonpath([full_path, directory]) != directory:
                # Don't allow misbehaving clients to break out of the static files
                # directory.
                continue
            try:
                return full_path, os.stat(full_path)
            except (FileNotFoundError, NotADirectoryError):
                continue
        return "", None
CVE-2022-23542 (Go)

OpenFGA's authorization check logic can incorrectly authorize access using relationship tuples that remain in storage but are no longer valid under the authorization model selected for the Check request. In particular, when an authorization model is changed or tightened, a tuple that was valid under an older model may violate the current model's type restrictions, yet Check may still treat that stale tuple as evidence of access. An attacker who can rely on previously stored relationship tuples, or trigger checks against objects whose tuples were written under an older model, may be granted permissions that the current model no longer allows.

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

Vulnerable code:
file_path: server/commands/check_utils.go
snippet: func (rc *resolutionContext) readUserTuple(ctx context.Context, backend storage.TupleBackend) (*openfgapb.TupleKey, error) {
	tk, ok := rc.contextualTuples.ReadUserTuple(rc.tk)
	if ok {
		return tk, nil
	}

	tuple, err := backend.ReadUserTuple(ctx, rc.store, rc.tk)
	if err != nil {
		return nil, err
	}
	return tuple.GetKey(), nil
}

Fixed code:
file_path: server/commands/check_utils.go
snippet: func (rc *resolutionContext) readUserTuple(ctx context.Context, backend storage.TupleBackend) (*openfgapb.TupleKey, error) {

	typesys := typesystem.New(rc.model)

	tk, ok := rc.contextualTuples.ReadUserTuple(rc.tk)

	if tk != nil {
		err := validation.ValidateTuple(typesys, tk)
		if err == nil && ok {
			return tk, nil
		}
	}

	tuple, err := backend.ReadUserTuple(ctx, rc.store, rc.tk)
	if err != nil {
		return nil, err
	}

	tk = tuple.GetKey()
	if err := validation.ValidateTuple(typesys, tk); err != nil {
		return nil, nil
	}

	return tk, nil
}